Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用JSON响应http请求_Python_Json_Api_Http - Fatal编程技术网

在Python中使用JSON响应http请求

在Python中使用JSON响应http请求,python,json,api,http,Python,Json,Api,Http,我有几个从CLI使用的Python脚本。现在有人问我是否可以提供一个web API来执行通常从CLI完成的一些工作。我想用JSON格式的数据来回应。我对JSON或API知之甚少 如何从http请求中检索查询数据 如何从我的脚本中为响应创建HTTP头 给定以下URL,我如何使用名为“Steve”的JSON回复进行响应 我已经有一个运行正常的ApacheWeb服务器,可以提供HTML和CGI脚本。这只是编写Python脚本,我需要一些帮助。我不希望使用像Flask这样的框架 一个简单的代码示例将不胜

我有几个从CLI使用的Python脚本。现在有人问我是否可以提供一个web API来执行通常从CLI完成的一些工作。我想用JSON格式的数据来回应。我对JSON或API知之甚少

如何从http请求中检索查询数据

如何从我的脚本中为响应创建HTTP头

给定以下URL,我如何使用名为“Steve”的JSON回复进行响应

我已经有一个运行正常的ApacheWeb服务器,可以提供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)

您正在尝试使用核心python代码构建请求处理程序。它能够处理http请求,在我看来这不是个好主意,因为它附带了多个安全场景,而且在跨服务器请求中,处理所有请求和请求场景有点困难。我建议使用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

不要重新发明轮子。为此有多种框架:django rest框架、flask、aiohttp、fastAPI等等。。。
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