全栈工程师开发手册 (作者:栾鹏)
架构系列文章
aiohttp是python中基于asyncio技术实现的。asyncio可参考https://luanpeng.blog.csdn.net/article/details/81461277
注意: python的异步返回有时是通过异常expection向上冒泡的, 在异步函数中使用try catch有时无法捕获某些异常的, 异常会作为返回结果直接返回给上一层
aiohttp服务器
下面是aiohttp作为服务器端的一个简单的demo。
#!/usr/bin/env python3
import argparse
from aiohttp import web
import asyncio
import base64
import logging
import uvloop
import time,datetime
import json
import requests
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
routes = web.RouteTableDef()
@routes.get('/')
async def hello(request):
return web.Response(text="Hello, world")
# 定义一个路由映射,接收网址参数,post方式
@routes.post('/demo1/{name}')
async def demo1(request): # 异步监听,只要一有握手就开始触发,此时网址参数中的name就已经知道了,但是前端可能还没有完全post完数据。
name = request.match_in