flask连接并创建数据库代码实现

JessePinkmen 2019-12-10


from flask import Flask,request,render_template,make_response,redirect
from flask_sqlalchemy import SQLAlchemy
import pymysql
#pymysql视为mysqlDB
pymysql.install_as_MySQLdb()

app = Flask(__name__)
#链接mysql数据库
app.config[‘SQLALCHEMY_DATABASE_URI‘]=‘mysql://root::3306/flask‘

#追踪程序修改,占用内存空间,
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘]=True

#创建sqlalchemy 的实例,app为谁服务f
db = 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.username


class 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.sname


class 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.tname

class 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 )

相关推荐

yyyxxxs / 0评论 2020-05-10