Search code examples
pythonwebwebservercgi

Running a simple cgi webserver with python, but nothing shown on browser


I was trying to run a cgi webserver using the following python script (hello.py):

print ('Content-Type: text/html')
print
print ('<html>')
print ('<head><title>Hello from Python</title></head>')
print ('<body>')
print ('<h2>Hello from Python</h2>')
print ('</body></html>')

I put hello.py in the cgi-bin folder of the dir where I am running python. On the command window, I started the web server using:

python -m http.server --bind localhost --cgi 8000

Than I opened a browser with: http://localhost:8000/cgi-bin/hello.py

The browser is opened, but it's blank, nothing is displayed, while it is supposed to display "Hello from python" according to the script. These are the message displayed on the backend, there seemed to be no error.

C:\python_dir>python -m http.server --bind localhost --cgi 8000
Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...
127.0.0.1 - - [17/Feb/2018 15:14:41] "GET /cgi-bin/hello.py HTTP/1.1" 200 -
127.0.0.1 - - [17/Feb/2018 15:14:41] command: C:\python_dir\python.exe -u 
C:\Users\user\cgi-bin\hello.py ""
127.0.0.1 - - [17/Feb/2018 15:14:41] CGI script exited OK

This is my first time with starting webserver, I cannot figure out what is wrong.


Solution

  • Your script returns everything as header content, not as body as you had expected, as shown by a quick curl call:

    curl --verbose localhost:8000/cgi-bin/hello.py

    * HTTP 1.0, assume close after body
    < HTTP/1.0 200 Script output follows
    < Server: SimpleHTTP/0.6 Python/3.6.4
    < Date: Sat, 17 Feb 2018 20:41:26 GMT
    < Content-Type: text/html
    < <html>
    < <head><title>Hello from Python</title></head>
    < <body>
    < <h2>Hello from Python</h2>
    < </body></html>
    * Closing connection 0
    

    By separating headers and content, the server is able to differentiate headers from body:

    print ('Content-Type: text/html')
    print ('\n')
    print
    ...
    

    Gives:

    * HTTP 1.0, assume close after body
    < HTTP/1.0 200 Script output follows
    < Server: SimpleHTTP/0.6 Python/3.6.4
    < Date: Sat, 17 Feb 2018 20:45:35 GMT
    < Content-Type: text/html
    <
    
    <html>
    <head><title>Hello from Python</title></head>
    <body>
    <h2>Hello from Python</h2>
    </body></html>
    * Closing connection 0