pythonchalice

How to generate an executable from an AWS-chalice application?


I have an AWS-chalice project and I want to generate an executable form this project.

So instead of running chalice local to start a local server, I just call the executable file.


Solution

  • I came up with this solution, based on Pyinstaller:

    1. Manually inject environment variables
    2. Manually start local server
    3. Manually intercept and handle special events (like SQS, Cron, ...)
    4. Compile the code with Pyinstaller

    call this code from at the end of app.py:

    import os
    from chalice.cli import CLIFactory
    from chalice.local import LocalDevServer
    def start_standalone(app):
        stage = os.environ.get("stage", "dev")
        print(f"initializing standalone server: {stage}")
        factory = CLIFactory(project_dir=os.getcwd(), debug=True, environ=os.environ, profile="dev")
        config = factory.create_config_obj(
            chalice_stage_name=stage
        )
        os.environ = {**os.environ, **config.environment_variables}
    
        host = os.environ.get("host", '127.0.0.1')
        port = os.environ.get("port", 8000)
        s = LocalDevServer(app, config=config, host=host, port=port)
        s.serve_forever()
        #handle_special_events(app) # to handle SQS and Cron; didn't include the code as it is not the main goal of this question
    

    At this stage, you can run python app.py to make sure that your changes are valid.

    Then using Pyinstaller run pyinstaller -F --add-data="./.chalice/config.json:.chalice" app.py

    PS: you might want to move the part about environment variables to the beginning of app.py so it can be used in your initialization.