任务已被销毁,但在尝试 运行 使用 HTTPS 的 aiohttp 服务器时处于挂起状态

Task was destroyed but it is pending when trying to run a aiohttp server using HTTPS

试图弄清楚如何使 HTTPS 与 aiohttp 服务器一起工作,但是当我尝试在使用 ssl_context.[=18= 时尝试向路由发出请求时,我不断收到以下错误]

Task was destroyed but it is pending!

如果我从 web.run_app 中删除 ssl_context,服务器工作正常,但我无法通过 HTTPS 访问服务器。不确定我是否没有以正确的方式使用 ssl_context?任何见解将不胜感激。我的服务器示例如下:

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')

您需要创建 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 导航到您的页面现在应该可以工作了,但是,当然您需要在浏览器中确认证书是正确的。