I received the HTML form data in Python and tried to display it.
First, write the code to submit the form in HTML.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form method="POST" action="cgi-bin/index.py">
<label>text:</label>
<textarea name="text"></textarea>
<button type="submit">Send</button>
</form>
</body>
</html>
--About method
The method
has a GET
method to get the data and a POST
method to send the data.
This time, we will send the data, so we will use the POST
method.
--About ʻaction`
You can specify the URL to send the data with ʻaction. This time, send it to
cgi-bin / index.py` that will appear later.
For more information on submitting form data, see the following articles. https://developer.mozilla.org/ja/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
Next, write a CGI (Gateway Interface Standard) script that receives and displays data in Python. A CGI script is a script that is started by an HTTP server and processes data entered by the user in HTML or the like. For details, refer to the following article. https://docs.python.org/ja/3/library/cgi.html#module-cgi
cgi-bin/index.py
#!usr/bin/python
# -*- coding: utf-8 -*-
import cgi #Import CGI module
import cgitb
import sys
cgitb.enable() #Since it is used for debugging, it is not described in the production environment.
form = cgi.FieldStorage() #Get form data
print("Content-Type: text/html; charset=UTF-8") #Header for writing HTML
print("")
#If no form data has been entered
if "text" not in form:
print("<h1>Error!</h1>")
print("<br>")
print("Enter the text!")
print("<a href='/'><button type='submit'>Return</button></a>")
sys.exit()
text = form.getvalue("text") #Get the value of the data
print(text)
Change the execution authority with the following command for later execution.
Command
$ chmod 755 cgi-bin/index.py
(I referred to the following article. https://qiita.com/shuichi0712/items/5ddc5b4e30c2373b17fb )
Next, run the CGI server.
Write the script for that in cgiserver.py
.
cgiserver.py
import http.server
http.server.test(HandlerClass=http.server.CGIHTTPRequestHandler)
After that, execute the following command to run the CGI server.
Command
$ python -m http.server --cgi
After that, if you search for http://0.0.0.0:8000 in the browser, the form will be displayed, and if you fill out and submit the form, the input contents will be displayed.
Recommended Posts