我试图在蓝图中使用flask_sqlalchemy而不编写任何模型。我不确定是否支持此功能,但是我的目标是替换我用sqlalchemy编写的现有数据库驱动程序。 这就是我的应用现在的结构
my db.py file
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
my main.py file
from .db import db
if os.getenv('FLASK_ENV') != 'production':
load_dotenv(verbose=True)
app = Flask(__name__)
database_uri = 'postgresql+psycopg2://{user}:{password}@{host}/{database}??sslmode={sslmode}'.format(
user=os.getenv('PGUSER'),
password=os.getenv("PGPASSWORD"),
host=os.getenv("PGHOST"),
port=os.getenv("PGPORT"),
database=os.getenv("PGDATABASE"),
sslmode=os.getenv("PG_SSL")
)
app.config.update(
SQLALCHEMY_DATABASE_URI=database_uri,
SQLALCHEMY_TRACK_MODIFICATIONS=False,
)
db.init_app(app)
app.register_blueprint(api, urlprefix="/")
cors = CORS(app, supports_credentials=True)
app.secret_key = '079bc80c-cbd6-4fc5-b1aa-8fe01fde50dc'
然后我尝试通过以下方式在模块内部使用
from flask import current_app as app
rows = db.engine.execute("select users.username, users.id, string_agg(coalesce(keys.service, ''), ',') from users left join keys on keys.user_id = users.id where users.username = '" + username + "' and users.password='" + password + "'" + "group by (users.username,users.id)")
但是在执行代码时我的代码中出现以下错误
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().
我还尝试将main.py代码更改为以下内容
app = Flask(__name__)
database_uri = 'postgresql+psycopg2://{user}:{password}@{host}/{database}??sslmode={sslmode}'.format(
user=os.getenv('PGUSER'),
password=os.getenv("PGPASSWORD"),
host=os.getenv("PGHOST"),
port=os.getenv("PGPORT"),
database=os.getenv("PGDATABASE"),
sslmode=os.getenv("PG_SSL")
)
app.config.update(
SQLALCHEMY_DATABASE_URI=database_uri,
SQLALCHEMY_TRACK_MODIFICATIONS=False,
)
with app.app_context():
db.init_app(app)
from flask.blueprints import Blueprint
from app.api.routes import api
# from werkzeug.middleware.profiler import ProfilerMiddleware
# app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[5], profile_dir='./profile')
app.register_blueprint(api, urlprefix="/")
cors = CORS(app, supports_credentials=True)
app.secret_key = '079bc80c-cbd6-4fc5-b1aa-8fe01fde50dc'
但是我在执行此操作时收到以下错误
AttributeError: 'Flask' object has no attribute 'db'
以我想要的方式执行代码的正确方法是什么?
答案 0 :(得分:-1)
我只是使用您的代码并对其进行了一些修改以在此处创建有效的解决方案:https://github.com/amucunguzi/SO-raw-sql-flask-sqlalchemy。
当您尝试执行需要RuntimeError: Working outside of application context
但没有“当前(HTTP)请求”的操作时,即通常不是从{{1}开始执行整个程序,则此flask.current_app
很典型}函数(https://flask.palletsprojects.com/en/1.1.x/api/#flask.current_app)。
话虽如此,请确保正确导入模块(请参见view
文件)。另外,最好将views.py
作为构造函数依赖项传递给模块/服务。