Discuss / Python / 课程中的例程运行会出错,应该是版本的问题。

课程中的例程运行会出错,应该是版本的问题。

Topic source

我的机器上安装了python 3.7。结合同学的回复,测试了一下程序有效:

import asyncio   

from aiohttp import web

async def index(request):

    await asyncio.sleep(0.5)

    return web.Response(body=b'<h1>Index</h1>', content_type='text/html', charset='utf-8')

    #return web.Response(body=b'<h1>Index</h1>') #这样返回,只能出现“下载”文件;

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', charset='utf-8') 

    #return web.Response(body=text.encode('utf-8')) #这样运行http://127.0.0.1:8002/hello/name,则返回一个name下载文件。    

async def init():

    app = web.Application()

    app.router.add_get('/', index)

    app.router.add_get('/hello/{name}', hello)

    runner = web.AppRunner(app)

    # app.make_handler()这个方法用不了,改用APPrunner,虽然我没看懂,但是官方替换是这样得

    await runner.setup()

    site = web.TCPSite(runner, '127.0.0.1', 8002)  #当用8000接口,显示错误:OSError: [Errno 10048] error while attempting to bind on address ('127.0.0.1', 8000): 通常每个套接字地址(协议/网络地址/ 端口)只允许使用一次。那么换成8001或8002,这样一般就可以了

    await site.start()

    print('Server started at http://127.0.0.1:8002...')

    return site

loop = asyncio.get_event_loop()

loop.run_until_complete(init())

loop.run_forever()

将上述例程保存为aiohttp3.py,(之所以起个名字后面带个数字,是为了与电脑内可能带的aiohttp.py文件加以区分)

在命令行下运行python aiohttp3.py,就会启动服务器。显示:Server started at http://127.0.0.1:8002...

在浏览器地址栏中输入:http://127.0.0.1:8002,会显示index;

在浏览器地址栏中输入:http://127.0.0.1:8002/hello/shanon,会显示

hello, shanon!


  • 1

Reply