use HTTPS in flask asyncio running

1.1k views Asked by At

I use flask in windows 10. I want to use HTTPS for the protocol. However, I use flask+asyncio so could not use "ssl=..." method. How could I achieve HTTPS in my case?

    import hypercorn.asyncio
from app import app, client, telegram_handler
# must import telegram_handler script here to separate bot session and client from celery


async def main():
    # for event in telegram_handler.bot.list_event_handlers():
    #     print(event)
    # await telegram_handler.bot.catch_up()   # doesn't work due to telethon lib issue.
    await hypercorn.asyncio.serve(app, hypercorn.Config())  # this throw Exception when press Ctrl-C


# By default, `Quart.run` uses `asyncio.run()`, which creates a new asyncio
# event loop. If we create the `TelegramClient` before, `telethon` will
# use `asyncio.get_event_loop()`, which is the implicit loop in the main
# thread. These two loops are different, and it won't work.
#
# So, we have to manually pass the same `loop` to both applications to
# make 100% sure it works and to avoid headaches.
#
# To run Quart inside `async def`, we must use `hypercorn.asyncio.serve()`
# directly.
#
# This example creates a global client outside of Quart handlers.
# If you create the client inside the handlers (common case), you
# won't have to worry about any of this, but it's still good to be
# explicit about the event loop.
if __name__ == '__main__':
    # client.add_event_handler(handler)
    # must start so that it can add event handler
    # print("Start client...")
    # must connect before it can start, so on initial run this will hang because cannot get OTP
    # client.start()
    # print("Client started!")
    client.loop.run_until_complete(main())

Thia is my hypercorn config class:

    class Config:
        _bind = ["127.0.0.1:8000"]
        _insecure_bind: List[str] = []
        _quic_bind: List[str] = []
        _quic_addresses: List[Tuple] = []
        _log: Optional[Logger] = None
    
        access_log_format = '%(h)s %(l)s %(l)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
        accesslog: Union[logging.Logger, str, None] = None
        alpn_protocols = ["h2", "http/1.1"]
        alt_svc_headers: List[str] = []
        application_path: str
        backlog = 100
        ca_certs: Optional[str] = None
        certfile: Optional[str] = None
        ciphers: str = "ECDHE+AESGCM"
        debug = False
        dogstatsd_tags = ""
        errorlog: Union[logging.Logger, str, None] = "-"
        graceful_timeout: float = 3 * SECONDS
        group: Optional[int] = None
        h11_max_incomplete_size = 16 * 1024 * BYTES
        h2_max_concurrent_streams = 100
        h2_max_header_list_size = 2 ** 16
        h2_max_inbound_frame_size = 2 ** 14 * OCTETS
        include_server_header = True
        keep_alive_timeout = 5 * SECONDS
        keyfile: Optional[str] = None
        logconfig:

 Optional[str] = None
    logconfig_dict: Optional[dict] = None
    logger_class = Logger
    loglevel: str = "INFO"
    max_app_queue_size: int = 10
    pid_path: Optional[str] = None
    root_path = ""
    server_names: List[str] = []
    shutdown_timeout = 60 * SECONDS
    ssl_handshake_timeout = 60 * SECONDS
    startup_timeout = 60 * SECONDS
    statsd_host: Optional[str] = None
    statsd_prefix = ""
    umask: Optional[int] = None
    use_reloader = False
    user: Optional[int] = None
    verify_flags: Optional[VerifyFlags] = None
    verify_mode: Optional[VerifyMode] = None
    websocket_max_message_size = 16 * 1024 * 1024 * BYTES
    websocket_ping_interval: Optional[int] = None
    worker_class = "asyncio"
    workers = 1

How could I get the certificate files for HTTPS?

Where could I generate these kind of certificate files for HTTPS?

1

There are 1 answers

2
pgjones On

The Hypercorn Config object has certfile and keyfile attributes that when set to paths that point to the relevant certificate files will be used to serve HTTPS.