背景
当你想搭建一套服务实现某个demo或者是小型服务,最快的方式就是使用fastapi+aiohttp+uvicorn。
案例
1、服务端接口
# -*- encoding: utf-8 -*-
import aiohttp
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/api")
async def api():
async with aiohttp.ClientSession() as session:
async with session.post("http://jsonplaceholder.typicode.com/posts") as response:
return await response.json()
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8080)
请求的地址:
curl http://localhost:8080/api
返回结果:
INFO: 127.0.0.1:58407 - "GET /api HTTP/1.1" 200 OK
INFO: 127.0.0.1:58407 - "GET /api HTTP/1.1" 200 OK
INFO: 127.0.0.1:58407 - "GET /api HTTP/1.1" 200 OK
INFO: 127.0.0.1:58407 - "GET /api HTTP/1.1" 200 OK
2、请求端接口
# -*- encoding: utf-8 -*-
import aiohttp
from fastapi import FastAPI
import asyncio
async def req():
async with aiohttp.ClientSession() as session:
async with session.get("http://localhost:8080/api") as response:
return await response.json()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
result = loop.run_until_complete(req())
print(result)