Domanda

Sto cercando di catturare i dati POST da un semplice modulo.

Questa è la prima volta che sto giocando intorno con WSGIREF e io non riesco a trovare il modo corretto per farlo.

This is the form:
<form action="test" method="POST">
<input type="text" name="name">
<input type="submit"></form>

E la funzione che è, ovviamente, mancano le giuste informazioni per prendere posto:

def app(environ, start_response):
    """starts the response for the webserver"""
    path = environ[ 'PATH_INFO']
    method = environ['REQUEST_METHOD']
    if method == 'POST':
        if path.startswith('/test'):
            start_response('200 OK',[('Content-type', 'text/html')])
            return "POST info would go here %s" % post_info
    else:
        start_response('200 OK', [('Content-type', 'text/html')])
        return form()
È stato utile?

Soluzione

Si dovrebbe essere la lettura delle risposte dal server.

di nosklo risposta per un problema simile: " PEP 333 dice è necessario leggere environ [ 'wsgi.input'] ".

Il codice testato (adattato da questa risposta ):
Caveat: Questo codice è solo a scopo dimostrativo.
Attenzione: Cercate di evitare percorsi o nomi di file hard-codifica

.
def app(environ, start_response):
    path    = environ['PATH_INFO']
    method  = environ['REQUEST_METHOD']
    if method == 'POST':
        if path.startswith('/test'):
            try:
                request_body_size = int(environ['CONTENT_LENGTH'])
                request_body = environ['wsgi.input'].read(request_body_size)
            except (TypeError, ValueError):
                request_body = "0"
            try:
                response_body = str(request_body)
            except:
                response_body = "error"
            status = '200 OK'
            headers = [('Content-type', 'text/plain')]
            start_response(status, headers)
            return [response_body]
    else:
        response_body = open('test.html').read()
        status = '200 OK'
        headers = [('Content-type', 'text/html'),
                    ('Content-Length', str(len(response_body)))]
        start_response(status, headers)
        return [response_body]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top