廖雪峰python实战项目_Day1

#! app.py

import logging;logging.basicConfig(level=logging.INFO)

import asyncio, os, json, time
from datetime import datetime

from aiohttp import web

def index(request):                                         #视图函数
    return web.Response(body=b'<h1>Awesome</h1>')

@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)                        #1 1 创建app实例
    app.router.add_route('GET','/',index)                   #2 把URL和index函数注册到app.router
    srv = yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)        #3 用aiohttp.RequestHandlerFactory 作为协议簇创建套接字,可以用 make_handle() 创建。
    logging.info('server start at http://127.0.0.1:9000...')
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

这是基于asyncio和aiohttp搭建的Web骨架。

首先,获取协程 、运行协程

loop = asyncio.get_event_loop()                    #获取最小协程单元 
loop.run_until_complete(init(loop))                #放入任务(Task)init(loop)
loop.run_forever()                                  #一直运行

然后,看异步协程任务

@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)                        #1 1 Application,构造函数 def __init__(self, *, logger=web_logger, loop=None,router=None, handler_factory=RequestHandlerFactory,middlewares=(), debug=False):
    app.router.add_route('GET','/',index)                   #2 把URL和index函数注册到app.router
    srv = yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)        #3 用aiohttp.RequestHandlerFactory 作为协议簇创建套接字,可以用 make_handle() 创建。
    logging.info('server start at http://127.0.0.1:9000...')
    return srv
我把init(loop)函数称为 异步协程任务,异步指这个函数是异步IO操作,协程任务指这个函数返回值用途是放置于协程中执行的。
app = web.Application(loop=loop)     接受一个消息循环作为参数,返回一个app实例

app.router.add_route('GET','/',index)   添加route到router,请求方式是GET,URL是'/',则交给视图函数index处理。
 srv = yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)    loop.create_server()创建一个异步协程任务:创建一个绑定127.0.0.1和9000端口的TCP服务。A coroutine which creates a TCP server bound to host and port.The return value is a Server object which can be used to stopthe service.

使用了@asyncio.coroutine和yield from的组合,表示这个函数是一个coroutine(异步协程任务),可以放到loop中执行的。

最后,看视图函数(index)

所谓视图函数,就是处理URL的函数。从URL到视图函数,称之为路由。

def index(request):                                         #视图函数
    return web.Response(body=b'<h1>Awesome</h1>')
index函数接受一个request,返回web.Response对象。看一些Response对象的构造函数:
def __init__(self, *, body=None, status=200,reason=None, text=None, headers=None, content_type=None,charset=None)
*标示了之后的是可变参量。body:HTML中的body部分;status:状态码,200标示正常;headers:HTML的头部。

body=b'<h1>Awesome</h1>'  b''标示了body接受的是bytes变量


猜你喜欢

转载自blog.csdn.net/bird333/article/details/80721528
今日推荐