創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比方正網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式方正網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋方正地區(qū)。費(fèi)用合理售后完善,十多年實體公司更值得信賴。Flask框架使模型和數(shù)據(jù)同步的方法?這個問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
使用ORM時,需要執(zhí)行遷移操作以便在模型和持久化數(shù)據(jù)之間保持同步。我們使用Flask-Migrate這個擴(kuò)展來完成該任務(wù)。
首先安裝:
$ pip install flask-migrate $ pip install flask_script
然后在代碼中引入:
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand
進(jìn)行必要的配置:
migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand)
運(yùn)行管理器:
if __name__ == '__main__': manager.run()
完整的代碼如下:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/appdb'db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand)class Post(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(80), unique=True) post_text = db.Column(db.String(255)) def __init__(self, title, post_text): self.title = title self.post_text = post_text@app.route('/')def index(): return "Hello World"if __name__ == "__main__": manager.run()
使用如下的命令初始化Alembic:
$ python app.py db init Creating directory /Users/Vihar/Desktop/flask-databases/migrations ... done ... ... ... Generating /Users/Vihar/Desktop/flask-databases/migrations/alembic.ini ... done
執(zhí)行第一個遷移任務(wù):
$ python app.py db migrate INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.autogenerate.compare] Detected added table 'post'Generating /Users/Vihar/Desktop/flask-databases/migrations/versions/ed3b3a028447_.py ... done
一旦上述命令執(zhí)行完畢,我們的數(shù)據(jù)表就會創(chuàng)建成功?,F(xiàn)在更新數(shù)據(jù)庫:
$ python app.py db upgrade
感謝各位的閱讀!看完上述內(nèi)容,你們對Flask框架使模型和數(shù)據(jù)同步的方法大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道。
名稱欄目:Flask框架使模型和數(shù)據(jù)同步的方法-創(chuàng)新互聯(lián)
分享網(wǎng)址:http://aaarwkj.com/article34/coespe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、動態(tài)網(wǎng)站、網(wǎng)站維護(hù)、做網(wǎng)站、營銷型網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)