想要用flask_sqlalchemy結(jié)合Blueprint分模塊寫(xiě)一下SQL的增刪改查接口,結(jié)果發(fā)現(xiàn)有循環(huán)引入問(wèn)題。
一開(kāi)始,我在app.py中使用db = SQLAlchemy(app)創(chuàng)建數(shù)據(jù)庫(kù)對(duì)象;并且使用app.register_blueprint(db_bp, url_prefix='/db')注冊(cè)藍(lán)圖。
這使得我的依賴關(guān)系是這樣的。db.py → app,py 中的db對(duì)象;app.py → db,py 用于注冊(cè)藍(lán)圖,產(chǎn)生了循環(huán)引用。
接著我學(xué)著使用一個(gè)model.py來(lái)存放db變量,但是使用錯(cuò)誤,下面是錯(cuò)誤的示例。
我在model.py使用db = SQLAlchemy()創(chuàng)建了未注冊(cè)的db對(duì)象
在app.py中使用db.init_app(app)來(lái)連接數(shù)據(jù)庫(kù),注冊(cè)db對(duì)象
但在db.py中錯(cuò)誤引用了app.py中的db對(duì)象,再次產(chǎn)生了循環(huán)引用
解決方法,在db.py中引入model.py中的db對(duì)象即可。
此時(shí)的依賴關(guān)系如下,db.py和app.py → model.py 用于獲取db對(duì)象;app.py → db.py 用于注冊(cè)藍(lán)圖。
?
看到一些比較麻煩的解決方案,1. 把db變量變成一個(gè)web接口,用請(qǐng)求的方式獲取。
2. 把a(bǔ)pp注冊(cè)db和blueprint的操作都放入main函數(shù)中?;蛘撸确庋b到def create_app()函數(shù)中,然后在main函數(shù)中調(diào)用。
參考?使用Flask-SQLAlchemy和Blueprints循環(huán)導(dǎo)入db引用 | 那些遇到過(guò)的問(wèn)題
?
dao.py
from flask import Blueprint, request, jsonify
from models import db
from models import KnowledgeEntity
from sqlalchemy.exc import SQLAlchemyError
# 創(chuàng)建視圖函數(shù)藍(lán)圖
app = Blueprint('KnowledgeDAO', __name__)
'''
word = db.Column(db.String(255), primary_key=True)
content = db.Column(db.Text, unique=True, nullable=False)
priority = db.Column(db.String(255), unique=True, nullable=False)
association = db.Column(db.JSON, unique=True, nullable=False)
'''
# 創(chuàng)建用戶
@app.route('/add', methods=['POST'])
def create_user():
data = request.get_json()
word = data.get('word')
content = data.get('content')
priority = data.get('priority')
association = data.get('association')
if not word or not priority:
return jsonify({'message': 'Both word and priority are required'}), 400
entity = KnowledgeEntity(word=word, content=content, priority=priority, association=association)
try:
db.session.add(entity)
db.session.commit()
return jsonify(1), 201
except SQLAlchemyError as e:
db.session.rollback() # 回滾事務(wù)以撤銷之前的操作
error_message = str(e)
return f'Error: {error_message}', 500
# 查詢所有用戶
@app.route('/selectAll', methods=['POST'])
def get_users():
users = KnowledgeEntity.query.all()
print('users',users)
# user_list = [{'id': user.id, 'username': user.username, 'email': user.email} for user in users]
return jsonify(1)
?model.py文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-729289.html
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class KnowledgeEntity(db.Model):
__tablename__ = 'knowledge'
word = db.Column(db.String(255), primary_key=True)
content = db.Column(db.Text, unique=True, nullable=False)
priority = db.Column(db.String(255), unique=True, nullable=False)
association = db.Column(db.JSON, unique=True, nullable=False)
def __init__(self, word, content=None, priority=None, association=None):
self.word = word
self.content = content
self.priority = priority
self.association = association
?app.py(改進(jìn)后的)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-729289.html
from flask import Flask, request, jsonify,g
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from models import db
# 導(dǎo)入視圖函數(shù)
from DAO import KnowledgeDAO
app = Flask(__name__)
# 配置選項(xiàng),用于控制 Flask 在將 Python 字典轉(zhuǎn)換為 JSON 數(shù)據(jù)時(shí)是否按照鍵的字母順序?qū)︽I進(jìn)行排序,默認(rèn)情況下,它的值為 True,表示會(huì)對(duì)鍵進(jìn)行排序。
app.config['JSON_SORT_KEYS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/ennote'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 注冊(cè)跨域
CORS(app, resources=r'/*') # 注冊(cè)CORS, "/*" 允許訪問(wèn)所有api
# 連接數(shù)據(jù)庫(kù)
db.init_app(app)
# 注冊(cè)藍(lán)圖
app.register_blueprint(KnowledgeDAO.app, url_prefix='/knowledge')
if __name__ == '__main__':
# 創(chuàng)建應(yīng)用上下文
with app.app_context():
# 在這里執(zhí)行需要應(yīng)用上下文的操作
# 例如,訪問(wèn)數(shù)據(jù)庫(kù)或使用Flask的全局變量
db.create_all()
app.run(host='127.0.0.1', port=5000, debug=True)
到了這里,關(guān)于flask-sqlalchemy結(jié)合Blueprint遇到循環(huán)引入問(wèn)題的解決方案的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!