flask_sqlalchemy基本设置
Posted python成长中
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask_sqlalchemy基本设置相关的知识,希望对你有一定的参考价值。
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()
以上是关于flask_sqlalchemy基本设置的主要内容,如果未能解决你的问题,请参考以下文章
from flask_sqlalchemy import SQLAlchemy 无法创建数据库表,代码无报错,代码如下,python版本是3.5
使用flask_sqlalchemy“ImportError:无法导入名称”