【发布时间】:2020-05-13 11:38:13
【问题描述】:
我有几个从 CLI 使用的 Python 脚本。现在有人问我是否可以提供一个 Web API 来执行一些通常从 CLI 完成的工作。我想回复 JSON 格式的数据。我对 JSON 或 API 知之甚少。
如何从 http 请求中检索查询数据?
如何为我的脚本的响应创建 HTTP 标头?
给定以下 URL,我如何回复名为“Steve”的 JSON 回复?
http://myserver.com/api.py?query=who
我已经有一个运行正常的 Apache Web 服务器,可以提供 HTML 和 CGI 脚本。它只是对我需要一些帮助的 Python 脚本进行编码。我宁愿不使用像 Flask 这样的框架。
一个简单的代码示例将不胜感激。
以下是我想出的 Python 代码,但我知道这不是正确的做法,而且它不使用 JSON:
#!/usr/local/bin/python3.7
import cgi # CGI module
# Set page headers and start page
print("Content-type: text/plain")
print("X-Content-Type-Options: nosniff\x0d\x0a\x0d\x0a")
# Form defaults
query_arg = None
# Get form values, if any
form = cgi.FieldStorage()
# Get the rest of the values if the form was submitted
if "query" in form.keys():
query_arg = form["query"].value
if query_arg == "who":
print("Steve", end="", flush=True)
【问题讨论】:
-
不要重新发明*。有多个框架:django rest framework、flask、aiohttp、fastAPI、...