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

flask_sqlalchemy基本设置

时间:2018-09-29 00:08:36      阅读:255      评论:0      收藏:0      [点我收藏+]

标签: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()

技术分享图片

 

flask_sqlalchemy基本设置

标签:dia   orm   分享图片   http   author   base   create   desc   format   

原文地址:https://www.cnblogs.com/wuheng-123/p/9721488.html

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