Forums

POST data, client browser info, etc?

Apache provides POST data, as well as client browser info, to a CGI processor, such a Python script, in environment variables. My script fails to find these in os.environ, as can be seen by entering text into the text field in http://voland0.pythonanywhere.com/ , and submitting.

Here is the application wrapper:

def application(environ, start_response): if environ.get('PATH_INFO') == '/': import HTML content = HTML.startHTML('Test') + HTML.para('This is a test.') + HTML.para(HTML.getEnv()) + HTML.form() + HTML.closeHTML() status = '200 OK' else: status = '404 NOT FOUND' content = 'Page not found.' response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(content)))] start_response(status, response_headers) yield content.encode('utf8')

Here is the HTML.py file: def startHTML(title): HTMLstart = '<!DOCTYPE html>\n<html lang="en">\n' HTMLstart += ' <head>\n <meta charset="utf8">\n' HTMLstart += ' <title>\n' + title + '\n </title>\n' HTMLstart += ' </head>\n' HTMLstart += ' <body>\n' return HTMLstart

def para(paraContent): paraIngred = ' <p>\n' paraIngred += paraContent + '\n' paraIngred += ' </p>\n' return paraIngred

def form(): formOut = ' <form method="POST" action="http://voland0.pythonanywhere.com/">\n' formOut += ' <table>\n <tr>\n <td>\n' formOut += ' <input type="text" name="textual">\n </td>\n' formOut += ' <td>\n <input type="submit">\n </td>' formOut += ' </td>\n </tr>\n </table>\n </form>\n' return formOut def closeHTML(): closeUp = ' </body>\n </html>\n' return closeUp

def getEnv(): from os import environ result = '' for k in sorted(list(environ.keys())): result += k + ' ' + environ[k] + '<br>\n' return result

Please, advise.

Hi there,

The simplest thing to do is to pick one of the Python WSGI frameworks like Django or Flask, they give you a nice API for dealing with requests, responses, and POST parameters.

If you really want to hand-roll an app that implements the low-level WSGI protocol, that's a bit over my head so I can't give any advice really, but a bit of googling suggests that

environ['wsgi.input']

might be the thing to look at? https://www.python.org/dev/peps/pep-0333/

It might seem more simple to work through Django, Flask, etc., but that should present a different learning curve, wouldn't it?

But, your second suggestion lead me pay more attention to the call to application(), that the environment is passed to it, and that I was misguiding myself trying to get it from os.environ . I had to, then, pass environ to the proc that formats it in a table, and I also had to convert the bytes in the keyed data to string.

Thank you for the slap with the cluestick!