I introduced the program on the WEB server side at the in-house study session for beginners (3rd time), so I wrote it here as well.
Environment: windows10, python3.7
Python provides a simple web server library. You can start the WEB server with just a command.
This time, we will implement it using CGI, which is easy to develop. CGI is a mechanism that processes requests from the browser.
Since the following path where the command is issued will be published, at the place you want to publish Execute the following command.
>python -m http.server 8888 --cgi
For example
d:\work\py_test
When executed in the above path
Put html in d: \ work \ py_test
Place the python file to be called in d: \ work \ py_test \ cgi-bin .
In the case of a business system, a database (hereinafter referred to as DB) is used to store data on the server side. This time, it takes time to prepare the DB, so I implemented it by storing the data in a file.
In Python, both file operations and DB operations can be easily implemented. The operation is similar Open → use → close It is a procedure of.
Create the following source file.
↓ Place in d: \ work \ py_test \
file_tesl.html
<html>
<head><meta http-equiv="content-type" charset="utf-8"></head>
<body>
File operation test
<br>
<form action="http://localhost:8888/cgi-bin/cgi_file_test.py" method="get">
<div>Enter name<input name="name" id="name" value=""></div>
<button>Run</button>
</form>
</body>
</html>
↓ Place in d: \ work \ py_test \ cgi-bin \
cgi_file_test.py
import cgi
import os
#Receiving parameters
form = cgi.FieldStorage()
str_name = form["name"].value
#Export to file (addition mode)
f = open('./data/test.txt','a')
f.write(str_name + "\n")
f.close()
#Read from file
read_str = ""
with open('./data/test.txt','r') as f:
for row in f:
read_str = read_str +"<br>"+ row.strip()
#Output in html
print ("Content-Type: text/html")
print ()
print ("<html><body>")
print ("The names you have entered so far are",read_str,"<br>")
print ("<a href=\"../file_test.html\">Return</a>")
print ("</body></html>")
Enter the following URL in your web browser and display it to check the operation.
http://locahost:8888/file_tesl.html
After displaying it on your web browser, enter your name and press "Run". After the screen transition, press "Back" and Let's enter the name.
You can see that it will be added.
In this way, Python not only makes cgi easy, but also makes file operations super easy.
Since the framework is used in the actual business WEB system, it is not hobo to write such a cgi, but since you can easily realize the WEB system, why not try various things?
Recommended Posts