学习廖雪峰老师python教程中aiohttp遇到的问题:
报被弃用Warning:
C:Usersdellpy3venvasyncio_test.py:47: DeprecationWarning: loop argument is deprecated
app = web.Application(loop=loop)
解决: 删除app = web.Application(loop=loop)中loop=loop参数
C:Usersdellpy3venvasyncio_test.py:50: DeprecationWarning: Application.make_handler(…) is deprecated, use AppRunner API instead
srv = await loop.create_server(app.make_handler(),‘127.0.0.1’,8000)
解决:见下
浏览器访问时不显示body而是自动下载
解决:web.Response中加入content_type=‘text/html’
import logging; logging.basicConfig(level=logging.INFO)
import asyncio
from aiohttp import web
#旧的
# async def index(request):
# await asyncio.sleep(0.5)
# return web.Response(body=b'Index')
# async def hello(request):
# await asyncio.sleep(0.5)
# text = 'hello, %s!' % request.match_info['name']
# return web.Response(body=text.encode('utf-8'))
# async def init(loop):
# app = web.Application(loop=loop)
# app.router.add_route('GET', '/', index)
# app.router.add_route('GET', '/hello/{name}', hello)
# srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
# print('Server started at http://127.0.0.1:8000...')
# return srv
# loop = asyncio.get_event_loop()
# loop.run_until_complete(init(loop))
# loop.run_forever()
async def index(request):
await asyncio.sleep(0.5)
return web.Response(body=b'Index',content_type='text/html')
async def hello(request):
await asyncio.sleep(0.5)
text = 'hello, %s!' % request.match_info['name']
return web.Response(body=text.encode('utf-8'),content_type='text/html')
async def init():
app = web.Application()
app.router.add_route('GET', '/', index)
app.router.add_route('GET', '/hello/{name}', hello)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, '127.0.0.1', 8000)
await site.start()
logging.info('server started at http://127.0.0.1:8000...')
loop = asyncio.get_event_loop()
loop.run_until_complete(init())
loop.run_forever()



