Python Flask SQLAlchemy蓝图中的应用程序工厂初始化问题

时间:2018-10-03 07:10:57

标签: python flask flask-sqlalchemy flask-wtforms blueprint

我在使用Application Factory进行初始化时遇到问题。我正在使用Blueprint和SQLAlchemy。 这是我的程序结构。

App_v1
 app.py
 config.py
 App_Py
       main
           __init__.py
           forms.py
           views.py
       static
       templates
       __init__.py
      app_v1.db
      models.py

app.py

from App_Py import create_app
app=create_app()

if __name__=='__main__':
app.run(debug=True,port=4044)

config.py

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
SECRET_KEY = ‘wdsfqsqdsqsdfqsqsdsq’
SQLALCHEMY_DATABASE_URI = 'sqlite:///'+os.path.join(basedir,'app_v1.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

App_Py 初始化 .py

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config

db = SQLAlchemy()
migrate=Migrate()
login_manager = LoginManager()
login_manager.login_view = 'users.login'

def create_app(config_class=Config):
  app = Flask(__name__)
  app.config.from_object(config_class)

  db.init_app(app)
  migrate.init_app(app, db)
  login_manager.init_app(app)

  from App_Py.main.views import main
  app.register_blueprint(main)
  return app

models.py

from App_Py import db,login_manager
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin

类User(db.Model,UserMixin):

__tablename__ = 'users'

id = db.Column(db.Integer,primary_key=True)
email = db.Column(db.String(64),unique=True,index=True)
username = db.Column(db.String(64),unique=True,index=True)
password_hash = db.Column(db.String(128))

def __init__(self, email, username, password):
    self.email = email
    self.username = username
    self.password_hash = generate_password_hash(password)

def __repr__(self):
    return f"Username {self.username}"

class Task_Add(db.Model):

  id = db.Column(db.Integer,primary_key=True)
  task_add = db.Column(db.String(64))
  def __init__(self,task_add):
    self.task_add = task_add

  def __repr__(self):
    return f"{self.task_add}"

内部主文件夹 views.py

from flask import render_template,url_for,flash,redirect,request,Blueprint
from flask_login import current_user,login_required
from App_Py import db
from App_Py.main.forms import TaskForm
from App_Py.models import User,Task_Add

main = Blueprint('main',__name__)  

@main.route('/view_task’)
def view_task():

运行程序时,在命令提示符下单击Python时,我无法承诺创建用户数据库:

from App_Py import db
from App_Py.models import User

u= User(username=‘dqfq’,email=‘one@one.com’,password=‘test’)
db.session.add(u)
db.session.commit()

提交时出现错误,提示无法提交。如何在Flask中启动Application Factory。我使用应用程序工厂的原因是我将为以后的目的使用弹性搜索。 谢谢您的建议。

错误:

(venv) iMac:App_Py_v1 symtech$ python
Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from App_Py import db
>>> from App_Py.models import User
>>> u=User(username='David',email='david@gmail.com',password='test')
>>> db.session.add(u)
Traceback (most recent call last):
File "/Users/symtech/Desktop/App_Py/App_Py_v1/venv/lib/python3.6/site-     packages/sqlalchemy/util/_collections.py", line 999, in __call__
return self.registry[key]
KeyError: 4320752448

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/symtech/Desktop/App_Py/App_Py_v1/venv/lib/python3.6/site-   packages/sqlalchemy/orm/scoping.py", line 153, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/symtech/Desktop/App_Py/App_Py_v1/venv/lib/python3.6/site-   packages/sqlalchemy/util/_collections.py", line 1001, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/Users/symtech/Desktop/App_Py/App_Py_v1/venv/lib/python3.6/site- packages/sqlalchemy/orm/session.py", line 2950, in __call__
return self.class_(**local_kw)
File "/Users/symtech/Desktop/App_Py/App_Py_v1/venv/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 141, in __init__
self.app = app = db.get_app()
File "/Users/symtech/Desktop/App_Py/App_Py_v1/venv/lib/python3.6/site- packages/flask_sqlalchemy/__init__.py", line 912, in get_app
'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or    push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
>>> >>>

更改后出现相同的问题和错误:

def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)

with app.app_context():
  db.init_app(app)
  migrate.init_app(app, db)
  ...........

  from APP_Py.users.views import users
  app.register_blueprint(users)
  ......

  return app

1 个答案:

答案 0 :(得分:0)

我注意到(刚才)您正在尝试从命令行提交用户。您可能缺少用于提交数据库的任何应用程序上下文。有关从命令行添加用户的解决方案,请参见以下URL:http://flask-sqlalchemy.pocoo.org/2.3/contexts/

我正在使用的应用程序中当前正在使用的另一种解决方案是在您的main.py中添加以下内容,甚至在create_app函数中也可以使用。

    from App_Py import db
    from App_Py.models import User

    @app.before_first_request
    def load_user():
        u=User(username='David',email='david@gmail.com',password='test')
        db.session.add(u)
        db.session.commit()