#-*- coding: utf-8 -*-
#!/usr/bin/env python3
import logging; logging.basicConfig(level=logging.INFO)
import asyncio, os, json, time
from datetime import datetime
from aiohttp import web
def index(request):
#网页显示 Awesome
return web.Response(body=b'<h1>Awesome</h1>', headers={'content-type': 'text/html'})
#request为aiohttp.web.request实例,包含http请求的信息,一般不用自己构造。
#web.Response构造并返回一个response实例,Response类声明class aiohttp.web.Response(*,
#status=200, headers=None, content_type=None, body=None, text=None)
#asyncio.coroutine将generator标记为coroutine类型,
#coroutine内部可以用yield from调用另一个coroutine
@asyncio.coroutine
def init(loop):
#创建一个web服务器实例,loop:event loop used for processing HTTP requests
app = web.Application(loop=loop)
#通过router的指定的方法可以把请求的链接和对应的处理函数关联在一起
app.router.add_route('GET', '/', index)
#运行web服务器,服务器启动后,有用户在浏览器访问,就可以做出对应的响应
#127.0.0.1本机地址,9000为端口
#loop.create_server创建一个TCP server
#app.make_handler() Creates HTTP protocol factory for handling requests
#yield from返回一个创建好的,绑定IP和端口以及http协议簇的监听服务的协程
srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 9000)
logging.info('server started at http://127.0.0.1:9000...')
return srv
#固定写法
loop = asyncio.get_event_loop() #生成一个事件循环实例
loop.run_until_complete(init(loop)) #运行init(loop),run_until_complete: if the argument
# is a coroutine object,it is wrapped by ensure_future().对Loop进行了初始化,创建了tcp server
loop.run_forever() #一直运行
python web - 编写web 骨架 解析
最新推荐文章于 2024-06-04 09:56:50 发布