全棧工程師開發手冊 (作者:欒鵬)
架構系列文章
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