Discuss / Python / 上面那个格式乱了,重新发一遍

上面那个格式乱了,重新发一遍

Topic source

经测试,要设置 content_typehtml 才能正常显示,不然就会变成下载一个文件。

import asyncio
from aiohttp import web

async def index(request):
    await asyncio.sleep(0.5)
    return web.Response(body='<h1>Index</h1>'.encode(), content_type='text/html')

async def hello(request):
    await asyncio.sleep(0.5)
    text = '<h1>hello, %s!</h1>' % request.match_info['name']
    return web.Response(body=text.encode('utf-8'), content_type='text/html')

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()

然后根据 Web Server Quickstart 进行了一些修改,看起来更简洁易懂:

from aiohttp import web
import asyncio

routes = web.RouteTableDef()

@routes.get('/')
async def index(request):
    await asyncio.sleep(2)
    return web.Response(body='<h1>Index</h1>'.encode(), content_type='text/html')

@routes.get('/hello/{name}')
async def hello(request):
    await asyncio.sleep(0.5)
    text = '<h1>hello, %s!</h1>' % request.match_info['name']
    return web.Response(body=text.encode('utf-8'), content_type='text/html')

app = web.Application()
app.add_routes(routes)
web.run_app(app)

在浏览器输入 localhost:8080/hello/zj 即可看到粗体的 hello, zj!


  • 1

Reply