flask连接并创建数据库代码实现
时间:2021-07-01 10:21:17
帮助过:40人阅读
from flask_sqlalchemy import SQLAlchemyimport pymysql#pymysql视为mysqlDBpymysql.install_as_MySQLdb()app = Flask(__name__)#链接mysql数据库app.config[‘SQLALCHEMY_DATABASE_URI‘]=‘mysql://root:a123456@49.235.91.84:3306/flask‘#追踪程序修改,占用内存空间,app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘]=True#创建sqlalchemy 的实例,app为谁服务fdb = SQLAlchemy(app)#创建模型类 models# 创建一个users类,映射到表l#创建字段,设置主键,自增,#创建字段 username 长度为80的字符串,不允许为空,唯一#创建字段:age 整数,允许为空#创建字段,email 长度为120的字符串,必须唯一class Users(db.Model): __tablename__ = ‘users‘ #表名 id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(80),nullable=Flask,unique=True) age = db.Column(db.Integer) email = db.Column(db.String(120),unique=True) def __init__(self,username,age,email): self.username = username self.age = age self.email = email def __repr__(self): return ‘<Users:%r>‘% self.usernameclass Student(db.Model): __tablename__ = ‘student‘ # 表名 id = db.Column(db.Integer,primary_key=True) sanme = db.Column(db.String(30),nullable=False) sage = db.Column(db.Integer) def __init__(self,sname,sage): self.sname = sname self.sage = sage def __repr__(self): return ‘<Student:%r>‘ % self.snameclass Teacher(db.Model): __tablename__ = ‘teacher‘ # 表名 id = db.Column(db.Integer,primary_key=True) tanme = db.Column(db.String(30),nullable=False) tage = db.Column(db.Integer) def __init__(self,tname,tage): self.tname = tname self.tage = tage def __repr__(self): return ‘<Teacher:%r>‘ % self.tnameclass Course(db.Model): __tablename__ = ‘course‘ # 表名 id = db.Column(db.Integer,primary_key=True) canme = db.Column(db.String(30),nullable=False) def __init__(self,cname): self.cname = cname def __repr__(self): return ‘<Course:%r>‘ % self.cname#将创建好的实体类映射回数据库db.create_all()@app.route(‘/‘)def index1(): return render_template(‘index.html‘)if __name__ == ‘__main__‘: app.run(debug=True )flask连接并创建数据库代码实现
标签:name user 好的 html mod redirect 主键 建模 request