Please help in solving this problem.
I have a project in Flask with a structure:
project
- main.py
- app
-- __init__.py
-- main
--- __init__.py
--- routes.py
-- auth
--- __init__.py
--- routes.py
--- forms.py
-- templates
--- index.html
app/main/routes.py
from flask import render_template
from app.main import bp
#bp.route('/')
def index():
return render_template('index.html')
app/main/init.py
from flask import Blueprint
bp = Blueprint('main', __name__)
from app.main import routes
app/init.py
from flask import Flask
from config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
from app.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
main.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
I get an error when I start the application:
Could not build url for endpoint 'index'. Did you mean 'main.index' instead?
Tried to insert main.index. instead of index.html in combination with template_folder='../templates'. But then it doesn't find the template.
Related
I just want to use flask to build a simple web, i tried with the code below:
__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] ='thangvc91'
return app
main.py
from web.template import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
it always said the error:
"from web.template import create_app
ModuleNotFoundError: No module named 'web'
[Done] exited with code=1 in 0.122 seconds"
can you assist on this ?
folder structures like below:
web - static
- template - __init__.py
- views.py
- models.py
- auth.py
-main.py
My code structure. I tried but kept getting error cannot import name 'caching'. I guess my method isn't correct as caching will not have app initiation when I import caching in external file.
xyz
-app.py
-run.py
-urls
-v2.py
-resource
-views.py
-external.py
run.py
from app import create_app
if __name__ == "__main__":
career_app = create_app()
career_app.run(host=HOST,
port=PORT,
debug=True)
app.py
from flask import Flask
from flask_caching import Cache
caching = Cache(config={'CACHE_TYPE': 'simple'})
def create_app():
"""Create web app."""
app = Flask(__name__)
configure_app(app)
caching.init_app(app)
setup_blueprints(app)
return app
external.py
from app import caching
v1.py
v2_api.add_resource(UserConfigView, '/user/config',
endpoint='user_config_view')
It is a simple factory app setup
ext.py
from flask_caching import Cache
cache = Cache()
app.py
def create_app():
app = Flask(__name__)
register_extensions(app)
...
def register_extensions(app):
cache.init_app(app, config=settings.params.CACHE_CONFIG)
I'm trying to clean up my flask app and I decided to use a boilerplate structure. I have the auth_bp blueprint, it's defined in auth.py , I have the following folder structure;
-app_root
-application
-__init__.py
- auth.py
- other files like template and static
- config.py (for configuration)
- server.py (to run the app through flask_script )
In __init__.py I have two classes: app and mail and I need to use them in my auth.py file.
But when I write :
from application import app, mail
I get an ImportError: cannot import name app
Here's the code in __init__.py:
from flask import Flask
from flask_mail import Mail
import config
from auth import auth_bp
app = Flask(__name__)
app.config.from_object("config.Config")
mail = Mail(app)
app.register_blueprint(auth_bp)
#app.route("/")
def home():
return "homepage"
Edit : Solved: I had to import auth after creating the app and mail object.
I'm trying to write tests for a simple Flask application. Structure of the project is following:
app/
static/
templates/
forms.py
models.py
views.py
migrations/
config.py
manage.py
tests.py
tests.py
import unittest
from app import create_app, db
from flask import current_app
from flask.ext.testing import TestCase
class AppTestCase(TestCase):
def create_app(self):
return create_app('test_config')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_hello(self):
response = self.client.get('/')
self.assert_200(response)
app/init.py
# app/__init__.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
return app
app = create_app('default')
from . import views
When I launch the tests, test_hello fails because response.status_code is 404. Tell me, please, how can I fix it? It seems, that app instance doesn't know anything about view functions in the views.py. If it needs the whole code, it can be found here
Your views.py file mount the routes in the app created in your __init__.py file.
You must bind these routes to your created app in create_app test method.
I suggest you to invert the dependency. Instead the views.py import your code, you can make a init_app to be imported and called from your __init__.py or from the test file.
# views.py
def init_app(app):
app.add_url_rule('/', 'index', index)
# repeat to each route
You can do better than that, using a Blueprint.
def init_app(app):
app.register_blueprint(blueprint)
This way, your test file can just import this init_app and bind the blueprint to the test app object.
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
Applitation Factories
Application with Blueprints
Application Dispatching
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
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!"