[Mac] I want to make a simple HTTP server that runs CGI with Python

things to do

Build a simple local HTTP server with CGI in Python.

I tried to write a CGI script in Python instead of Perl if it was simple.

environment

What is CGI

  • CGI is an abbreviation for Common Gateway Interface, which is a function to display the result of processing programmatically on a Web server. *

(Quoted from What is CGI)

In short, I think that it is a function that can create a dynamic web page, fetch a value from a browser, process it on the server side, and return it again.

Preparing a local HTTP server

First of all, you have to set up a server, so set up an HTTP server locally and display a web page.

Write Index.html in the directory you want to work with to create the page you want to display. This time, the data to be sent will be food and season.

index.html


<html>
    <head>
        <title>Server test</title>
        <meta http-equiv="content-type" charset="utf-8">
    </head>
    <body>
    <form action="/cgi-bin/cgi_test.py" method="POST">
        <div>
            <label for="name">Favorite food</label>
            <input type="text" name="food" value="Apple">
            <label for="season">Favorite season</label>
            <input type="text" name="season" value="winter">
            <button>Send</button>
        </div>
    </form>
    </body>
</html>

What you have to pay attention to here is the path of the action

"/cgi-bin/CGI script file name"

Is to be. This is the relative path to the CGI script file, which will be used later to create the script file using the script file name specified here.

Server startup test

Try starting the server once. Start it in the terminal.

$ python3 -m http.server 8080

When executed, it will look like the one below. I used 8080 for the time being, but any other number is fine as long as it can be used.

Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

Now, check if it works. http://localhost:8080/ If all goes well, it will look like this: By the way, even if you press the submit button, you should still get an error. server_test.png

Writing a CGI script

Now, let's write the CGI script in Python. Create a directory named cgi-bin in the working directory (the directory where index.html is located), and write the CGI script in it. The file structure looks like this.

.
├── cgi-bin
│   └── cgi_test.py
└── index.html

Also, for the file name here, use the name specified earlier in index.html.

cgi_test.py


#!/usr/bin/env python

import cgi
import cgitb
cgitb.enable()

print("Content-Type: text/html; charset=utf-8\n\n")

print("<html><body>")
form = cgi.FieldStorage()

for key in form:
    value = form[key].value
    print('<p>%s: %s</p>' % (key, value))

print("</body></html>")

Be sure to write #! / Usr / bin / env python on the first line here. If you do not write this, you will get the error `ʻOS Error: [Errno 8] Exec format error: ``. This specifies an interpreter, but please refer to the following articles for details. #! / Bin / sh is not just a comment! Shebang! (Qiita)

Let's run a CGI script

Let's do it. Start the server in the terminal as before. Now add the --cgi option to run CGI.

python3 -m http.server 8080 --cgi

After confirming the startup at http: // localhost: 8080 /, press Send this time to confirm. cgi_test.png If it can be displayed, it is successful.

If you get an error

If you do not see it when you press the submit button, first check the terminal to see what kind of error you are getting.

· Permission is not 755 (not allowed)

code 403, message CGI script is not executable

→ Enter chmod 755 CGI script name.py in the terminal on the cgi-bin directory.

-Character code is not set

SyntaxError: Non-ASCII character '\xe5'

→ Add # coding: utf-8 to the top of the file.

reference

Build a comfortable web server with python and test CGI. (Qiita)

Recommended Posts

[Mac] I want to make a simple HTTP server that runs CGI with Python
I want to make a game with Python
I want to use a wildcard that I want to shell with Python remove
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to write to a file with Python
A simple Python HTTP server that supports Range Requests
I want to work with a robot in python.
[Python] I want to make a nested list a tuple
I want to AWS Lambda with Python on Mac!
I want to run a quantum computer with Python
I tried to make a simple mail sending application with tkinter of Python
I want to make a blog editor with django admin
How to specify a public directory Python simple HTTP server
I want to make a click macro with pyautogui (desire)
I want to make a click macro with pyautogui (outlook)
I want to debug with Python
I want to make input () a nice complement in python
How to start a simple WEB server that can execute cgi of php and python
[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
I want to set up a GUI development environment with Python or Golang on Mac
I tried to make a generator that generates a C # container class from CSV with Python
I want to make a voice changer using Python and SPTK with reference to a famous site
[5th] I tried to make a certain authenticator-like tool with python
I tried to create a server environment that runs on Windows 10
Rubyist tried to make a simple API with Python + bottle + MySQL
[2nd] I tried to make a certain authenticator-like tool with python
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I want to do a full text search with elasticsearch + python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I want to build a Python environment
I want to analyze logs with Python
I want to play with aws with python
I made a simple blackjack with Python
[Python] I tried to make a simple program that works on the command line using argparse.
I tried to communicate with a remote server by Socket communication with Python.
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to build a Mac Python development environment with pythonz + direnv
I want to make a web application using React and Python flask
I want to make matplotlib a dark theme
I want to use MATLAB feval with python
I want to create a window in Python
Start a simple Python web server with Docker
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
I want to use Temporary Directory with Python2
#Unresolved I want to compile gobject-introspection with Python3
I want to solve APG4b with Python (Chapter 2)
Try to make a dihedral group with Python
I want to make C ++ code from Python code!
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I want to create a nice Python development environment for my new Mac
I want to create a priority queue that can be updated in Python (2.7)
[Patent analysis] I tried to make a patent map with Python without spending money
I want to exe and distribute a program that resizes images Python3 + pyinstaller
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
If you want to make a discord bot with python, let's use a framework