aiohttp官方教程翻译(4)—— 服务器端编程之快速开始

Web Server Quickstart


1、Run a Simple Web Server(启动一个简单的Web服务器)

为了使一个web服务器生效,首先创建一个请求处理器

一个请求处理器必须是一个接受Request实例作为他唯一参数并且返回一个Response实例的协程:

from aiohttp import web

async def hello(request):
    return web.Response(text="Hello, world")

之后,创建一个Application实例并在特定的HTTP方法和路径上注册请求处理器:

app = web.Application()
app.add_routes([web.get('/', hello)])

然后,通过 run_app() 运行(最好指定下端口,不然可能会有进程已经占用默认端口):

web.run_app(app,host='127.0.0.1', port=9000)

又或者你更愿意使用route装饰器创建一个route table 并注册一个web处理器:

routes = web.RouteTableDef()

@routes.get('/')
async def hello(request):
    return web.Response(text="Hello, world")

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

两种方法本质上无区别,关键在于你喜欢上面的那种Django风格,还是下面的Flask风格

结果可以看到在127.0.0.1:9000上返回的hello world文本


2、Command Line Interface (CLI)(命令行界面)

aiohttp.web能够生效一个CLI给基于TCP/IP的程序快速提供给服务

$ python -m aiohttp.web -H localhost -P 8080 package.module:init_func
def init_func(argv):
    app = web.Application()
    app.router.add_get("/", index_handler)
    return app

3、Handler(处理器)(ps:和第一节东西差不多)

一个处理器必须是一个接受Request实例作为他唯一参数并且返回一个 StreamResponse实例的协程:

async def handler(request):
    return web.Response()

使用Application.add_routes()进行绑定:

app.add_routes([web.get('/', handler),
                web.post('/post', post_handler),
                web.put('/put', put_handler)])

或者使用route装饰器:

routes = web.RouteTableDef()

@routes.get('/')
async def get_handler(request):
    ...

@routes.post('/post')
async def post_handler(request):
    ...

@routes.put('/put')
async def put_handler(request):
    ...

app.add_routes(routes)

未知HTTP方法也是被 route() 或 RouteTableDef.route()支持的,允许一个Handler处理任何HTTP方法:

app.add_routes([web.route('*', '/path', all_handler)])

默认情况下,使用GET方法添加的端点将接受HEAD请求并返回与GET请求相同的响应头。你还可以拒绝路由上的HEAD请求:

web.get('/', handler, allow_head=False)

4、Resources and Routes

to be modified

你可能感兴趣的:(aiohttp,python)