码迷,mamicode.com
首页 > 数据库 > 详细

Flask -SQLAlchemy 数据库一对一

时间:2020-02-08 11:44:56      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:type   com   comm   print   root   datetime   user   tab   key   

from  flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import config
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(50),nullable=False)
password = db.Column(db.String(50),nullable=False)
phone = db.Column(db.String(11),nullable=False)
email = db.Column(db.String(30),nullable=False)
reg_time = db.Column(db.DateTime,default = datetime.now)
class Lib_card(db.Model):
__tablename__ =‘lib_card‘
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
card_id = db.Column(db.Integer,nullable=False)
papers_type = db.Column(db.String(50),nullable=False)
borrow_reg_time = db.Column(db.DateTime,default=datetime.now)
user_id = db.Column(db.Integer,db.ForeignKey(‘user.id‘))
users = db.relationship(‘User‘,backref=db.backref(‘cards‘),uselist=False)
db.create_all()
@app.route(‘/add‘)
def add():
user1 = User(username=‘张三‘,password=‘1111111‘,phone=‘138888888‘,email=‘10086@qq.com‘)
user2 = User(username=‘李氏‘,password=‘2222222‘,phone=‘137777777‘,email=‘10000@qq.com‘)
db.session.add(user1)
db.session.add(user2)

card1 = Lib_card(card_id=‘18001‘,user_id=‘1‘,papers_type=‘身份证‘)
card2= Lib_card(card_id=‘18002‘,user_id=‘2‘,papers_type=‘身份证‘)
db.session.add(card1)
db.session.add(card2)
db.session.commit()
return ‘添加数据成功‘
@app.route(‘/select‘)
def select():
user = User.query.filter(User.username==‘张三‘).first()
art = user.cards
for k in art:
print(k)
print(k.card_id)
card = Lib_card.query.filter(Lib_card.card_id==‘18001‘).first()
user = card.users
print(user.username)
return ‘查询数据成功‘


@app.route(‘/‘)
def index():
return ‘index‘
if __name__ == ‘__main__‘:
app.run(debug=True)

config 为数据库链接配置
USERNAME = ‘root‘
PASSWD=‘1234qwer¥%&‘
HOST=‘127.0.0.1‘
PORT=‘3306‘
DATABASE=‘db_demo1‘
DB_URI="mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(USERNAME,PASSWD,HOST,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI=DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS=False
SQLALCHEMY_ECHO = True

Flask -SQLAlchemy 数据库一对一

标签:type   com   comm   print   root   datetime   user   tab   key   

原文地址:https://www.cnblogs.com/hnsya/p/12275798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!