服务端

# -*-codeing=utf-8-*-

import json
from wsgiref.simple_server import make_server
import os
import torch

# 定义函数,参数是函数的两个参数,都是python本身定义的,默认就行了。
def application(environ, start_response):
    # 定义文件请求的类型和当前请求成功的code
    start_response('200 OK', [('Content-Type', 'application/json')])

    # environ是当前请求的所有数据,包括Header和URL,body
    request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
    request_body = json.loads(request_body)

    username = request_body["username"]
    print('server...', username)
    # 逻辑处理 ......
    result = 'world'
    return [result.encode('utf-8')]


if __name__ == "__main__":
    port = 6088
    httpd = make_server("0.0.0.0", port, application)
    print("serving http on port {0}...".format(str(port)))
    httpd.serve_forever()

客户端

import json

import requests

url = "http://127.0.0.1:6088/"
headers = {
    "content-type": "application/json"
}
data = {
    "username": "hello"
}
response = requests.post(url, headers=headers, json=data)
print("client...", response.text)

运行结果

先运行服务端代码:

python接口服务 python 服务接口_python


然后运行客户端代码:

python接口服务 python 服务接口_接口_02


python接口服务 python 服务接口_服务端_03