Issue
I have a small Flask application. I add an extra security layer which is log in. I based my refactoring on the DO article.
In a nutshell,
__init__.py
:
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
from sqlalchemy import create_engine
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'e56432f4402c9a0c166fe6c6a0a2fbbd'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
db.init_app(app)
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
from .models import User
@login_manager.user_loader
def load_user(user_id):
# since the user_id is just the primary key of our user table, use it in the query for the user
return User.query.get(int(user_id))
return app
In order to create DB, I need to run in REPL:
from project import db, create_app
db.create_all(app=create_app())
This is both inconvenient and makes Docker image creation harder. I run an application as flask run
. I saw similar issues but don't understand how to apply to my scenario.
How can I overcome this complication?
UPDATE 1:
My project structure is the following:
project/
project/
__init__.py
auth.py
main.py
models.py
static/
templates/
Dockerfile
requirements.txt
Solution
I found a more elegant solution
Instead of return app
make the following block, so an application will be created in the runtime if and only if the context was initialized and database created.
with app.app_context():
db.create_all()
return app
Surprisingly the Flask-SqlAlchemy
is pointing out to REPL db creation as a first solution, not the one above.
UPDATE:
Here is an example of my Dockerfile:
FROM python:3.7-slim
ENV FLASK_APP=.
WORKDIR /app
COPY requirements.txt /app/requirements.txt
COPY . /app
RUN pip install -r requirements.txt
CMD flask run -h 0.0.0.0 -p 5000
The catch is that you have to change how you run flask
, not via python
command.
Answered By - Dmytro Chasovskyi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.