标签:dia orm 分享图片 http author base create desc format
from flask import Flask from flask_sqlalchemy import SQLAlchemy #区别 sqlalchemy这是第三方模块不属于flask app = Flask(__name__) HOSTNAME = ‘127.0.0.1‘ PORT = 3306 DATABASE = ‘first_sqlalchemy_demo‘ USERNAME = ‘root‘ PASSWORD = ‘123456‘ #dialect+driver://username:password@host:port/database DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) #SQLALCHEMY_DATABASE_URI是定死的,只能这么写 app.config[‘SQLALCHEMY_DATABASE_URI‘] = DB_URI app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = False db = SQLAlchemy(app) # app.debug = True#这里注意,这样开启debug,数据映射到数据库两次 class User(db.Model): __tablename__ = ‘user‘ id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(50),nullable=False) class Article(db.Model): __tablename__ = ‘article‘ id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(50),nullable=False) uid = db.Column(db.Integer,db.ForeignKey(‘user.id‘),nullable=False) author = db.relationship(‘User‘,backref=‘articles‘) # db.drop_all() # db.create_all() #增加数据 def create_data_mysql(): user = User(username=‘zhiliaoxuetang‘) article = Article(title=‘python flask‘) article.author = user #映射到数据库中 db.session.add(article) db.session.commit() #查询 #User.query 相当于db.session.query(User),如果要做复杂的查询还是要用db.session.query(User) # user_all_desc = User.query.order_by(User.id.desc()).all() # print(user_all_desc) #修改数据 # user_update = User.query.filter(User.id==1).first() # user_update.username = ‘old boy‘ # db.session.commit() #删除数据 user_delete = User.query.filter(User.id==2).first() db.session.delete(user_delete) db.session.commit() @app.route(‘/‘) def hello_world(): return ‘hello world!‘ if __name__ == ‘__main__‘: # create_data_mysql() app.run()
标签:dia orm 分享图片 http author base create desc format
原文地址:https://www.cnblogs.com/wuheng-123/p/9721488.html