创建一个纯Python API(没有任何框架),邮递员客户端可以成功发布json请求

Far*_*han 0 python api http python-requests

以下是我尝试过的。

import http.server
import socketserver
import requests

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

def api(data):
    r = requests.post('http://localhost:8000/api', json=data)
    return r.json()
Run Code Online (Sandbox Code Playgroud)

使用上面的代码出现以下错误。

ConnectionRefusedError: [WinError 10061] 由于目标计算机主动拒绝而无法建立连接

Postman 应该能够发送具有 json 正文的 post 请求。

fur*_*ras 6

您没有显示完整的错误消息,我没有使用 Windows 来测试它,但SimpleHTTPRequestHandler没有do_POST接收POST请求的功能,这可能会产生问题。

您将不得不使用SimpleHTTPRequestHandler来创建自己的类do_POST

这个功能需要

  • 获取标头信息
  • 读取 JSON 字符串
  • 将请求数据从 JSON 字符串转换为字典
  • 将响应数据从字典转换为 JSON 字符串
  • 发送标头
  • 发送 JSON 字符串

所以这需要做很多工作。

最小工作服务器

import http.server
import socketserver
import json

PORT = 8000

class MyHandler(http.server.SimpleHTTPRequestHandler):
    
    def do_POST(self):
        # - request -
        
        content_length = int(self.headers['Content-Length'])
        #print('content_length:', content_length)
        
        if content_length:
            input_json = self.rfile.read(content_length)
            input_data = json.loads(input_json)
        else:
            input_data = None
            
        print(input_data)
        
        # - response -
        
        self.send_response(200)
        self.send_header('Content-type', 'text/json')
        self.end_headers()
        
        output_data = {'status': 'OK', 'result': 'HELLO WORLD!'}
        output_json = json.dumps(output_data)
        
        self.wfile.write(output_json.encode('utf-8'))


Handler = MyHandler

try:
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"Starting http://0.0.0.0:{PORT}")
        httpd.serve_forever()
except KeyboardInterrupt:
    print("Stopping by Ctrl+C")
    httpd.server_close()  # to resolve problem `OSError: [Errno 98] Address already in use` 
Run Code Online (Sandbox Code Playgroud)

以及测试代码

import requests

data = {'search': 'hello world?'}

r = requests.post('http://localhost:8000/api', json=data)
print('status:', r.status_code)
print('json:', r.json())
Run Code Online (Sandbox Code Playgroud)

此示例不会检查您是否运行/apior/api/function或 ,/api/function/arguments因为它需要更多代码。

因此,没有框架的纯Python API可能需要大量工作,而且可能会浪费时间。


与 相同的代码Flask。它要短得多,并且它已经检查您是否发送到/api.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api', methods=["GET", "POST"])
def api():
    input_data = request.json
    print(input_data)
    output_data = {'status': 'OK', 'result': 'HELLO WORLD!'}
    return jsonify(output_data)

if __name__ == '__main__':
    #app.debug = True
    app.run(host='0.0.0.0', port=8000)
Run Code Online (Sandbox Code Playgroud)

顺便提一句:

如果您想测试发布数据,那么您可以使用门户http://httpbin.org并向http://httpbin.org/post发送POST请求,它将发回所有数据和标头。

它也可用于其他请求和数据。

该门户是用 Flask 创建的,甚至还有源代码链接,因此您可以将其安装在自己的计算机上。


它似乎httpbin是 GitHub 上存储库的一部分Postman