创建一个纯python API(没有任何框架),邮递员客户端可以成功发布json请求 [英] Creating a pure python API (without any framework) where postman client can successfully post json requests

查看:14
本文介绍了创建一个纯python API(没有任何框架),邮递员客户端可以成功发布json请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我尝试过的.

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()

上面的代码出现以下错误.

Getting below error with above code.

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

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

邮递员应该能够发送具有 json 正文的 post 请求.

Postman should be able to send post request having json body.

推荐答案

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

You didn't show full error message and I don't use Windows to test it but SimpleHTTPRequestHandler doesn't have function do_POST to receive POST request and this can make problem.

您必须使用 SimpleHTTPRequestHandler 来创建自己的带有 do_POST 的类.

You will have to use SimpleHTTPRequestHandler to create own class with do_POST.

而且这个函数需要

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

所以它需要大量的工作.

so it will need a lot of work.

最小工作服务器

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` 

和测试代码

import requests

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

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

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

This example doesn't check if you run /api or /api/function or /api/function/arguments because it would need much more code.

所以没有框架的纯 python API 可能需要大量工作,而且可能会浪费时间.

So pure python API without framework can need a lot of work and it can be waste of time.

Flask 相同的代码.它更短,它已经检查您是否发送到 /api.

The same code with Flask. It is much shorter and it already checks if you send to /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)


顺便说一句:

如果您想测试帖子数据,则可以使用门户 http://httpbin.org 并发送 POST 请求 http://httpbin.org/post 它将发回所有数据和标题.

If you want to test post data then you can use portal http://httpbin.org and send POST request to http://httpbin.org/post and it will send back all data and headers.

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

It can be used also for other requests and data.

这个门户是用 Flask 创建的,甚至还有源代码的链接,所以你可以在自己的电脑上安装它.

This portal was created with Flask and there is even link to source code so you can install it on own computer.

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

It seems httpbin is part of Postman repo on GitHub.

这篇关于创建一个纯python API(没有任何框架),邮递员客户端可以成功发布json请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆