Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 331 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
NameError: name 'app' is not defined with Flask

#1
I have the following *structure* in my project

\ myapp
\ app
__init__.py
views.py
run.py

And the following code:

**run.py**

from app import create_app

if __name__ == '__main__':
app = create_app()
app.run(debug=True, host='0.0.0.0', port=5001)

**views.py**

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

**__init__.py**

from flask import Flask


def create_app():
app = Flask(__name__)
from app import views
return app

I'm trying to use the `factory design pattern` to create my `app` objects with different `config` files each time, and with a subdomain dispatcher be able to create and route different objects depending on the `subdomain` on the user request.

I'm following the Flask documentation where they talk about, all of this:

- [Application Context](

[To see links please register here]

)
- [Applitation Factories](

[To see links please register here]

)
- [Application with Blueprints](

[To see links please register here]

)
- [Application Dispatching](

[To see links please register here]

)

But I couldn't make it work, it seems that with my actual project `structure` there are no way to pass throw the `app` object to my `views.py` and it throw and `NameError`

> NameError: name 'app' is not defined
Reply

#2
After do what Miguel suggest (use the `Blueprint`) everything works, that's the final code, working:

**__init.py__**

...

def create_app(cfg=None):
app = Flask(__name__)
from api.views import api
app.register_blueprint(api)
return app

**views.py**

from flask import current_app, Blueprint, jsonify
api = Blueprint('api', __name__)

@api.route("/")
def index():
# We can use "current_app" to have access to our "app" object
return "Hello World!"
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through