aiohttp AppRunner的用法

參考廖雪峯的aiohttp教程,會出現兩個DeprecationWarning,

  • loop argument is deprecated
  • Application.make_handler(...) is deprecated, use AppRunner API instead

解決方案

  • loop 參數直接不用就是
  • 參見aiohttp官網,AppRunner的用法:
    The simple startup code for serving HTTP site on 'localhost', port 8080 looks like:
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 8080)
await site.start()
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.INFO)
import os,json,time,asyncio
from datetime import datetime
from aiohttp import web

# def index(request): # 原始簡單的url處理函數
#     return web.Response(body=b'<h1>Awesome</h1>',content_type='text/html')

def init_jinja2(app, **kw): #初始化 jinja2的 env
   pass

async def logger_factory(app, handler):
    async def logger(request):
        logging.info('Request: %s %s' % (request.method, request.path))
        return (await handler(request))
    return logger

#  生產  post 提交的數據
async def data_factory(app, handler):
   pass

#將url處理函數的返回值 轉換成 response 對象
async def response_factory(app, handler):
    pass
    return response

#  將blog  評論的發佈時間 轉換成 多少時間之前
def datetime_filter(t):
    delta = int(time.time() - t)
    if delta < 60:
        return u'1分鐘前'
    if delta < 3600:
        return u'%s分鐘前' % (delta // 60)
    if delta < 86400:
        return u'%s小時前' % (delta // 3600)
    if delta < 604800:
        return u'%s天前' % (delta // 86400)
    dt = datetime.fromtimestamp(t)
    return u'%s年%s月%s日' % (dt.year, dt.month, dt.day)

async def init(loop):
    db = configs.configs.db
    await orm.create_pool(loop=loop, **db)
    #DeprecationWarning: loop argument is deprecated
    app = web.Application(loop = loop,middlewares=[ #攔截器 一個URL在被某個函數處理前,能夠通過一系列的middleware的處理。
        logger_factory, response_factory #工廠模式
    ])
    init_jinja2(app, filters=dict(datetime=datetime_filter))
    add_routes(app, 'handlers')
    add_static(app)

    # DeprecationWarning: Application.make_handler(...) is deprecated, use AppRunner API instead
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '192.168.2.101', 9000)
    logging.info('server started at http://192.168.2.101:9000...')
    await site.start()
     
    #之前的寫法
    # srv = await loop.create_server(app.make_handler(), '192.168.2.101', 9000)
    # logging.info('server started at http://192.168.2.101:9000...')
    # return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
相關文章
相關標籤/搜索