代码之家  ›  专栏  ›  技术社区  ›  antfuentes87

任务已被破坏,但在尝试使用https运行aiohttp服务器时它处于挂起状态

  •  0
  • antfuentes87  · 技术社区  · 8 年前

    尝试找出如何使https与 aiohttp 服务器,但是当我尝试在使用时向路由发出请求时,我会一直收到下面的错误 ssl_context .

    任务已被破坏,但仍处于挂起状态!

    如果我移除 ssl_上下文 从 web.run_app 服务器工作正常,但我无法通过HTTPS访问服务器。不确定我是否不使用 ssl_上下文 正确的方法?任何见解都会受到极大的赞赏。我的服务器示例如下:

    import json
    import asyncio
    
    from aiohttp import web
    from aiomysql import create_pool
    from aiomysql import DictCursor
    
    host = 'localhost'
    user = 'user'
    password = 'password'
    db = 'db'
    
    routes = web.RouteTableDef()
    headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    }
    async def fetch_data(table):
        async with create_pool(host=host,port=3306,user=user,password=password,db=db) as pool:
            async with pool.get() as conn:
                async with conn.cursor(DictCursor) as cur:
                    sql = "SELECT id FROM `{}`"
                    sql = sql.format(table)
                    await cur.execute(sql)
                    dataset = await cur.fetchall()
                    return dataset
    
    @routes.get('/hello')
    async def hello(request):
        dataset = await fetch_data('my_table')
        return web.json_response(dataset, headers=headers)
    
    app = web.Application()
    app.add_routes(routes)
    web.run_app(app, port=9090, ssl_context='https')
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Andrej Kesely    8 年前

    您需要创建SSL上下文(例如,使用方法 ssl.create_default_context() )然后向其提供证书(可自签名)。

    要创建自签名证书,请使用此命令(只需将所有问题保留为默认值):

    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt
    

    然后,在脚本中使用此证书创建SSL上下文:

    import ssl
    
    sc = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    sc.load_cert_chain('selfsigned.crt', 'selfsigned.key')
    

    …然后提供给您 web.run_app() :

    web.run_app(app, port=9090, ssl_context=sc)
    

    现在应该可以运行服务器并通过HTTPS导航到您的页面,但是,当然您需要在浏览器中确认证书是正确的。