uvicornとFastAPIによるサーバー構築 その2

server.py

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel


app = FastAPI()


class Request(BaseModel):
message: str


@app.post("/hoge_post")
async def hoge_func(req: Request):
print(req.message)
return {'output': req.message}


def start():
config = uvicorn.Config("server:app", host="127.0.0.1", port=8000, log_level="info")
server = uvicorn.Server(config=config)
server.run()


if __name__ == '__main__':
start()


client.py

import json
import urllib.request


def make_data():
data = {
'message': 'hello'
}
return data


def client():
req = urllib.request.Request(
'http://127.0.0.1:8000/hoge_post',
headers={'Content-Type': 'application/json'},
data=json.dumps(make_data()).encode('utf-8')
)
with urllib.request.urlopen(req) as res:
print(json.load(res))


if __name__ == '__main__':
client()