Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Python: Simple HTTP Server With CGI Scripts Enabled

DZone's Guide to

Python: Simple HTTP Server With CGI Scripts Enabled

This article takes us through how to get Python code running as a CGI script on a web server. Check it out!

· Web Dev Zone
Free Resource

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

If you want to experiment some python code as CGI script to serve by a HTTP server, you can get started by these steps:

  1. Create a cgi-bin directory.
  2. Ready!

No, really, it's that simple! Try these CGI scripts out.

Example 1: cgi-bin/hello.py

#!/usr/bin/env python3

localvars_table = '<table>'
for x in dir():
  localvars_table += '<tr><td>%s</td></tr>' % x
localvars_table += '</table>'

print("Content-type: text/html")
print("")
print("""<html><body>
<p>Hello World! Your custom CGI script is working. Here are your current Python local variables.</p>
%s
<p>NOTE: If you want to write useful CGI script, try the Python 'cgi' module. See cgitest.py script.</p>
</body></html>""" % (localvars_table))

To test and run this, you simply invoke these couple commands:

bash> chmod a+x cgi-bin/hello.py
bash> python3 -m http.server --cgi

You may now test it on your browser with http://localhost:8000/cgi-bin/hello.py. Hit CTRL+C to stop the server.

If you want to do more with fancy CGI scripts, try the Python's cgi module. Here is another example.

Example 2: cgi-bin/cgitest.py

#!/usr/bin/env python3

import cgi
cgi.test()

Again chmod your cgitest.py script and visit http://localhost:8000/cgi-bin/cgitest.py. You will see all the HTTP related data as expected when working with a CGI script. See https://docs.python.org/3/library/cgi.html for more details.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
server ,python ,code ,cgi ,http ,scripts ,http server ,script

Published at DZone with permission of Zemian Deng, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}