Python CGI: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "== CGI Module == 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/lib...")
 
No edit summary
Line 1: Line 1:
== Example ==
<source lang="python">
#!/usr/bin/python
print ("Content-type: text/html;charset=utf-8\n")
print ("Hello world!")
</source>
=== Receive some text from a form ===
<source lang="python">
#!/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>""")
</source>
=== Dump the env! ===
<source lang="python">
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import cgi
cgi.print_environ()
</source>
== CGI Module ==
== CGI Module ==
Python has a CGI module that takes care of many things like working with values posted form a form or handling an uploaded file.
Python has a CGI module that takes care of many things like working with values posted form a form or handling an uploaded file.

Revision as of 11:40, 12 February 2014

Example

#!/usr/bin/python
print ("Content-type: text/html;charset=utf-8\n")
print ("Hello world!")

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>""")

Dump the env!

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import cgi
cgi.print_environ()

CGI Module

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