Python CGI
Revision as of 06:42, 17 April 2018 by Michael Murtaugh (talk | contribs) (→Unicode issue with Apache)
Sample code
Hello World
#!/usr/bin/python
print ("Content-type: text/html;charset=utf-8\n")
print ("Hello world!")
Dump the env!
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import cgi
cgi.print_environ()
Receive some text from a form
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import cgitb; cgitb.enable()
import cgi
q = cgi.FieldStorage()
text = q.getvalue("text", "")
print ("Content-type: text/html;charset=utf-8\n")
# Print any received text in a purple box
print ("""<h1>Hello</h1>""")
if text:
print ("""<div style="border: 5px solid purple">""")
print text
print ("""</div>""")
# Print the form
print ("""<form method="get" action="">
<textarea name="text"></textarea>
<input type="submit" />
</form>""")
RTFM
Python has a CGI module that takes care of many things like working with values posted form a form or handling an uploaded file.
http://docs.python.org/2/library/cgi.html#module-cgi
Python CGI Checklist
Python 3
Mini server
python -m http.server --cgi 8000
Unicode issue with Apache
- Add PassEnv LANG line to the end of your /etc/apache2/apache2.conf or .htaccess.
- Uncomment . /etc/default/locale line in /etc/apache2/envvars.
- Make sure line similar to LANG="en_US.UTF-8" is present in /etc/default/locale.
https://stackoverflow.com/questions/9322410/set-encoding-in-python-3-cgi-scripts#19574801
A simple test CGI...
#!/usr/bin/env python3
import sys
import cgitb; cgitb.enable()
print('Content-Type: text/html; charset=utf-8')
print()
print('<html><body><pre>' + sys.stdout.encoding + '</pre>h€lló wörld<body></html>')