aiohttp + motor搭建异步服务器
aiohttp
- 网络访问是一个IO操作
- aiohttp就是把asyncio用在服务器端
- aiohttp则是基于asyncio实现的HTTP框架
motor
- 对pymongo进行封装来实现异步操作mongo的 Python第三方库
- 安装命令pip install motor
- 官方文档
下面搭建的一个简单的异步服务器
import asyncio
import motor.motor_asyncio
from aiohttp import web
client = motor.motor_asyncio.AsyncIOMotorClient("*********", 27017)
db = client["findjob"]
class Index(web.View):
async def get(self):
res = await db.chinahr.find_one()
print(res)
res.pop("_id")
return web.Response(body=bytes(html,encoding='utf-8'), content_type='text/html', charset="utf-8")
loop = asyncio.get_event_loop()
app = web.Application(loop=loop)
app.add_routes([web.get("/", Index)])
if __name__ == '__main__':
web.run_app(app, port=20008, host="127.0.0.1")