There is a file forms.py, it creates a list of tuples that contain the id and the name of the country (this is necessary to create a form with a choice countries in the select tag). The problem is that the country data is stored in a database that I access through flask_sqlalchemy. Which in turn requires app context. I'm using an app factory and I don't understand how I can get the app context. Maybe the problem is in the architecture of the project?
forms.py
def country_choices():
with current_app._get.app_context():
country_choices = [ (c.id, c.country_name) for c in\
Countries.query.with_entities(Countries.id, Countries.country_name) ]
return country_choices
class UserForm(FlaskForm):
username = StringField('username', validators=[DataRequired(message=blank_field_error), Length(min=4, max=20, message=username_lenght_error), username__is_unique, NoneOf(list(username_bad_symbols), message=username_bad_symbols_error)])
email = EmailField('email', validators=[DataRequired(message=blank_field_error), Email(message=email_error), email__is_unique])
password = PasswordField('password', validators=[DataRequired(), Length(min=8, max=255, message=password_lenght_error)])
confirm_password = PasswordField('confirm_password', validators [DataRequired(message=blank_field_error), EqualTo('password', message=password_equal_error)])
country = SelectField('country', validators=[DataRequired()], choices=country_choices() )
submit = SubmitField('submit')
init.py
from flask_uploads import configure_uploads
from flask import Flask
from .extensions import mail, db, manager, a_lot_photos
# Импорт Blueprint'ов
from app.users import users
from app.help import help
from app.views import main
def create_app():
app = Flask(__name__)
app.config.from_object('config.Config')
# Инициализация расширений
db.init_app(app)
mail.init_app(app)
manager.init_app(app)
configure_uploads(app, a_lot_photos)
from .jinja_filters import time_ago_format, time_to_end_format, format_price
app.jinja_env.filters['time_ago_format'] = time_ago_format
app.jinja_env.filters['time_to_end_format'] = time_to_end_format
app.jinja_env.filters['format_price'] = format_price
with app.app_context():
# Подключение blueprint'ов
app.register_blueprint(main, url_prefix='')
app.register_blueprint(users, url_prefix='/users')
app.register_blueprint(help, url_prefix='/help')
return app
app.py
from app import create_app
app = create_app()
app.app_context().push()
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
I tried to use current_app, but useless.
with current_app._get_current_object.app_context():
too.