新聞中心
創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!
成都創(chuàng)新互聯(lián)公司堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站建設(shè)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的阜平網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!這篇文章主要介紹了Flask框架連接數(shù)據(jù)庫的方法,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
Flask不能直接連接數(shù)據(jù)庫,需要借助于ORM(Object Relational Mapper)。在這一部分,我們將借助于SQLAlchemy使用Postgres數(shù)據(jù)庫。
安裝Flask-SQLAlchemy和Postgres
首先安裝flask-sqlalchemy:
$ pip install flask-sqlalchemy
然后從官方下載并安裝postgres:https://postgresapp.com/
創(chuàng)建數(shù)據(jù)庫
在終端中使用下面的命令創(chuàng)建一個appdb數(shù)據(jù)庫:
$ createdb appdb
更新應(yīng)用配置
修改app.config,添加數(shù)據(jù)庫相關(guān)的配置信息:
app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI']='postgresql://localhost/appdb' SQLALCHEMY_TRACK_MODIFICATIONS = True db = SQLAlchemy(app)
然后在代碼中就可以使用這些配置數(shù)據(jù)了:
from flask import Flask, request, render_template from flask_sqlalchemy import SQLAlchemy # Settingsapp = Flask(__name__) app.config['DEBUG'] = Trueapp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/appdb' db = SQLAlchemy(app)@app.route('/')def hello_world(): return 'Hello, World!'if __name__ == '__main__': app.run()
現(xiàn)在,讓我們創(chuàng)建第一個模型(Model)。所有模型的基類是db.Model,使用Column來定義數(shù)據(jù)列:
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
在代碼中使用模型:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/testdb' db = SQLAlchemy(app) 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" app = Flask(__name__) if __name__ == "__main__": app.run()
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享Flask框架連接數(shù)據(jù)庫的方法內(nèi)容對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道,遇到問題就找創(chuàng)新互聯(lián),詳細(xì)的解決方法等著你來學(xué)習(xí)!
標(biāo)題名稱:Flask框架連接數(shù)據(jù)庫的方法-創(chuàng)新互聯(lián)
文章來源:http://fisionsoft.com.cn/article/cshscj.html