简体   繁体   English

在 Python 中使用 JSON 响应 http 请求

[英]Responding to an http request with JSON in Python

I have several Python scripts that are used from the CLI.我有几个从 CLI 使用的 Python 脚本。 Now I have been asked if I could provide a web API to perform some of the work normally done from the CLI.现在有人问我是否可以提供一个 Web API 来执行一些通常从 CLI 完成的工作。 I would like to respond with JSON formatted data.我想用 JSON 格式的数据进行响应。 I know little about JSON or API's.我对 JSON 或 API 知之甚少。

How do I retrieve the query data from the http request?如何从 http 请求中检索查询数据?

How to a create the HTTP headers for the response from my script?如何为来自我的脚本的响应创建 HTTP 标头?

Given the following URL, how can I respond with a JSON reply of the name "Steve"?给定以下 URL,我如何使用名称为“Steve”的 JSON 回复进行响应?

http://myserver.com/api.py?query=who

I already have a functioning Apache web server running, and can serve up HTML and CGI scripts.我已经有一个运行正常的 Apache Web 服务器,并且可以提供 HTML 和 CGI​​ 脚本。 It's simply coding the Python script that I need some help with.它只是编写我需要一些帮助的 Python 脚本。 I would prefer not to use a framework, like Flask.我不想使用框架,比如 Flask。

A simple code example would be appreciated.一个简单的代码示例将不胜感激。

The following is the Python code that I've come up with, but I know it's not the correct way to do this, and it doesn't use JSON:以下是我想出的 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)

You are trying to build a request handler with core python code.您正在尝试使用核心 Python 代码构建请求处理程序。 which is able to handle http request, In my opinion its not good idea as there are multiple securty scenarios attached with it, also in cross server request its bit difficult to handle all request and request scenarios .它能够处理 http 请求,在我看来这不是一个好主意,因为它附带了多个安全场景,而且在跨服务器请求中它有点难以处理所有请求和请求场景。 I will suggest to use Flask which is very lightweight and this will give an pre-setup of routing mechanism to handle all kind of request in very less code below is the snippet to generate http json response hope it helps我会建议使用非常轻量级的 Flask,这将预先设置路由机制来处理所有类型的请求,下面是生成 http json 响应的代码片段,希望对您有所帮助

import sys
import flask
import random, string
from flask import  jsonify

class Utils:
    def make_response(self):
        response = jsonify({
           'message': 'success',
        })
        response.status_code = 200
        return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM