[Python] How to use workers with hypercorn serve?

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I want to start my FastAPI app using hypercorn from main.py.

    I used this command to start the server manually:

    hypercorn --access-logformat "%(R)s %(s)s %(st)s %(D)s %({Header}o)s" --access-logfile - -b 0.0.0.0:8000 -w 9 app:app

    Now I need to do the same thing from my code. First attempt was:

    from hypercorn.config import Config
    from hypercorn.asyncio import serve

    from api.app import app # app = FastAPI()

    config = Config()
    config.bind = ['0.0.0.0:8000']
    config.access_log_format = '%(R)s %(s)s %(st)s %(D)s %({Header}o)s'
    config.accesslog = mainLog # mainLog = logging.getLogger('main')
    config.loglevel = 'INFO'

    asyncio.run(serve(app, config))


    I've tried to set config.workers = 9 , but in response I've got:

    Warning: The config `workers` has no affect when using serve
    warnings.warn("The config `workers` has no affect when using serve", Warning)


    Then I rewrite my code to this:

    import logging
    import asyncio

    from hypercorn.config import Config
    from hypercorn.asyncio import serve

    from api.app import app


    mainLog = logging.getLogger('main')
    ...

    async def main(app, config):
    await serve(app, config)

    if __name__ == "__main__":
    config = Config()
    config.bind = ['0.0.0.0:8000']
    config.access_log_format = "%(R)s %(s)s %(st)s %(D)s %({Header}o)s"
    config.accesslog = mainLog
    config.loglevel = 'INFO'
    config.worker_class = 'asyncio'
    config.workers = 9
    try:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(app, config))

    except:
    mainLog.exception('Fail to start server')


    But I still got the same warning. Documentation says:


    ... it is possible to use Hypercorn programmatically via the serve function available for either the asyncio or trio Workers (note the asyncio serve can be used with uvloop).
    ​

    Am I misunderstand the docs? I have lack of knowledge in this area, so please help me.

    Continue reading...

Compartilhe esta Página