[英]How to pass HTML form input to Python script?
我有这样的表单标签
<form name="input_form" action="/test.py" method="get">
Set Frequency: <input type="number" name="set_freq" id="set_freq"> <br>
<input type="submit" value="Submit" />
<input id="reset" type="reset" value="Reset" /><br>
</form>
我需要把它放在哪里,用户输入 1500 或任何值,然后一旦点击提交,该数字就会传递给 python 程序 test.py 。
有不止一种方法可以做到这一点,您可以使用 CGI(调用 python 脚本并提供输出的网络服务器)或 WSGI 框架,如 Django 或 Flask,或其他。 当然,这些也需要从“典型”网络服务器(如 apache 或 Nginx 或 Gunicorn 等)提供服务。
我的建议是使用像 Flask 这样的框架来完成这项任务。
通过运行安装它,最好是在虚拟环境中:
pip install flask
那么你可以写一些简单的东西
from flask import Flask, request, render_template
# Flask constructor
app = Flask(__name__)
# A decorator used to tell the application
# which URL is associated function
@app.route('/test.py', methods =["GET", "POST"])
def get_freq():
if request.method == "POST":
# getting input with freq = set_freq in HTML form
freq = request.form.get("set_freq") # <--- do whatever you want with that value
return "Your freq value is " + freq
return render_template("form.html")
if __name__=='__main__':
app.run()
那么您需要提供要提供的form.html
模板,并将其放在./templates
文件夹中。
<form action="{{ url_for("get_freq") }}" method="post"> <label for="set_freq">Set Frequency:</label> <input type="number" id="set_freq" name="set_freq" > <button type="submit">submit</button>
现在运行脚本并打开http://127.0.0.1:5000/test.py您将收到表单,通过提交它,您会将频率值直接发送到您可以解释它的后端。
学习目的:
出于学习目的,您可以在不使用框架的情况下使用 python 标准库中的 HTTP 服务器。 这不是用于生产的,甚至可能比使用 web 框架需要更多的努力(这是使用此类框架的重点)。
#!/usr/bin/env python3
"""
Usage::
./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
from urllib.parse import urlparse, parse_qs
class S(BaseHTTPRequestHandler):
def _set_response(self, code):
self.send_response(code)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
query_components = parse_qs(urlparse(self.path).query)
if query_components.get('set_freq'):
freq = query_components.get('set_freq') # <--- do whatever you want with that value
print(freq)
self._set_response(200)
self.wfile.write("Python HTTP server received your GET request".encode("utf-8"))
def run(server_class=HTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info('Starting httpd...\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
运行 web 服务器,当它开始监听传入请求时,您现在可以打开表单页面并提交数据。 您需要编辑表单发送数据的路径,这是最后的代码段。
<:DOCTYPE html> <html> <body> <h2>HTML Forms</h2> <form name="input_form" action="http://localhost:8080"> Set Frequency, <input type="number" name="set_freq" id="set_freq"> <br> <input type="submit" value="Submit" /> <input id="reset" type="reset" value="Reset" /><br> </form> <p>If you click the "Submit" button. the form data will be sent to your local Python 3 HTTP server.</p> </body> </html>
同样,这也不是完整的或优化的或生产代码。 使用它以防万一您想启动并运行一些东西来玩和学习。
代码说明:
BaseHTTPRequestHandler
class 用于处理到达服务器的 HTTP 请求。 它本身无法响应任何实际的 HTTP 请求; 它必须被子类化以处理每个请求方法(例如 GET 或 POST)。 所以我们通过添加将在 GET 请求上调用的do_GET
方法在S
class 中扩展它。
来自 Python 官方文档:
处理程序将解析请求和标头,然后调用特定于请求类型的方法。 方法名称是根据请求构造的。 例如,对于请求方法 SPAM,do_SPAM() 方法将在没有 arguments 的情况下被调用。 所有相关信息都存储在处理程序的实例变量中。 子类不需要重写或扩展init () 方法。
从这里阅读更多信息: https://docs.python.org/3/library/http.server.html#http.server.HTTPServer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.