初始化和設置數(shù)據(jù)庫配置信息
1睛低、使用flask_sqlalchemy中SQLAlchemy進行初始化
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
2谎痢、配置數(shù)據(jù)庫config
DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSWORD = 'mysql'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask_sql'
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
創(chuàng)建數(shù)據(jù)庫 注:數(shù)據(jù)庫可以提前創(chuàng)建好
create database flask_demo charset utf8;
3磕昼、在主app文件中添加配置
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
4、測試數(shù)據(jù)庫是否連接成功 注:運行程序沒有報錯表示連接成功
db.create_all()
- 5节猿、使用Flask-SQLAlchemy 創(chuàng)建模型與表的映射
class Articles(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# nullable=False 不能為空
title = db.Column(db.String(32),nullable=False)
content = db.Column(db.Text,nullable=False)
db.drop_all()
- 創(chuàng)建數(shù)據(jù)庫表完整代碼
from flask import Flask
import config
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# nullable=False 不能為空
title = db.Column(db.String(32),nullable=False)
content = db.Column(db.Text,nullable=False)
class Articles(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# nullable=False 不能為空
title = db.Column(db.String(32),nullable=False)
content = db.Column(db.Text,nullable=False)
db.drop_all()
db.create_all()
@app.route('/')
def index():
return 'Hello World'
if __name__ == '__main__':
app.run(debug=True)