zappa / Zappa

Serverless Python
https://zappa.ws/zappa
MIT License
3.25k stars 363 forks source link

[Migrated] async with flask create_app pattern? #803

Closed jneves closed 5 months ago

jneves commented 3 years ago

Originally from: https://github.com/Miserlou/Zappa/issues/1958 by joshpurvis

Context

When using a create_app() pattern with flask, zappa.async.task decorated functions aren't able to access the app context. I sort of understand why they can't access current_app, as that's just a proxy, but can't figure out how to workaround it.

Expected Behavior

Expect to be able to access current_app.config items

Actual Behavior

[1573401852781] ENTERING TASK
[1573401852783] Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.: RuntimeError
Traceback (most recent call last):
  File "/var/task/handler.py", line 602, in lambda_handler
  return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 248, in lambda_handler
  return handler.handler(event, context)
  File "/var/task/handler.py", line 382, in handler
  result = self.run_function(app_function, event, context)
  File "/var/task/handler.py", line 287, in run_function
  result = app_function(event, context)
  File "/var/task/zappa/asynchronous.py", line 272, in route_lambda_task
  return run_message(message)
  File "/var/task/zappa/asynchronous.py", line 308, in run_message
  **message['kwargs']
  File "/var/task/myapp.py", line 8, in background_task
  key = current_app.config['SOME_KEY']
  File "/var/task/werkzeug/local.py", line 348, in __getattr__
  return getattr(self._get_current_object(), name)
  File "/var/task/werkzeug/local.py", line 307, in _get_current_object
  return self.__local()
  File "/var/task/flask/globals.py", line 52, in _find_app
  raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

Possible Fix

Steps to Reproduce

myapp.py

from flask import Flask, current_app
from zappa.async import task

@task
def background_task():
    print("ENTERING TASK")
    key = current_app.config['SOME_KEY']
    print(key)
    print("EXITING TASK")

def create_app(name=__name__, config=None):
    """ Create app using factory pattern

    :param name:
    :param config:
    :return: Flask app
    """
    app = Flask(name)

    app.config['SOME_KEY'] = 'SOME_SECRET'

    @app.route('/')
    def index():
        return "Hello World"

    @app.route('/trigger')
    def trigger():
        background_task()
        return "Launched background task!"

    return app

run.py

from myapp import create_app

app = create_app()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

Your Environment

Zappa: 0.48.2 Python: 3.6.9 (via virtualenv)

{
    "test": {
        "app_function": "run.app",
        "aws_region": "us-east-2",
        "timeout_seconds": 30,
        "cors": true,
        "profile_name": "default",
        "project_name": "PROJECT NAME",
        "runtime": "python3.6",
        "s3_bucket": "myapp-zappa",
        "vpc_config": {
            "SubnetIds": ["PRIVATE SUBNET ID", "PUBLIC SUBNET ID"],
            "SecurityGroupIds": ["SECURITY GROUP ID"]
        }
    }
}
phil-airship commented 1 year ago

Did you ever find a workaround to this? I'm struggling on my end, and using with current_app.app_context() does not allow it

github-actions[bot] commented 5 months ago

Hi there! Unfortunately, this Issue has not seen any activity for at least 90 days. If the Issue is still relevant to the latest version of Zappa, please comment within the next 10 days if you wish to keep it open. Otherwise, it will be automatically closed.

github-actions[bot] commented 5 months ago

Hi there! Unfortunately, this Issue was automatically closed as it had not seen any activity in at least 100 days. If the Issue is still relevant to the latest version of Zappa, please open a new Issue.