另外⼀个框架,叫做 Flask-SQLAlchemyFlask-SQLAlchemy 是对SQLAlchemy进行了⼀个简单的封装,使得我们在 flask 中使用sqlalchemy 更加的简单。
    可以通过pip install flask-sqlalchemy

    1. from flask import Flask
    2. from flask_sqlalchemy import SQLAlchemy
    3. # localhost
    4. HOSTNAME = '127.0.0.1'
    5. DATABASE = 'demo'
    6. PORT = 3306
    7. USERNAME = 'root'
    8. PASSWORD = 'root'
    9. DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
    10. app = Flask(__name__)
    11. # engine = create_engine(DB_URL)
    12. app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
    13. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    14. db = SQLAlchemy(app)
    15. class User(db.Model):
    16. # 如果不写__tablename__ 会以模型名字的小写来定义表名
    17. __tablename__ = 'users'
    18. id = db.Column(db.Integer, primary_key=True)
    19. name = db.Column(db.String(50))
    20. article = db.relationship('Artcile', backref='user')
    21. def __repr__(self):
    22. return "User(name:%s)" % self.name
    23. class Artcile(db.Model):
    24. __tablename__ = 'article'
    25. id = db.Column(db.Integer, primary_key=True)
    26. title = db.Column(db.String(50))
    27. uid = db.Column(db.Integer, db.ForeignKey('users.id'))
    28. # user = db.relationship('User', backref='article')
    29. db.drop_all()
    30. db.create_all()
    31. # 添加数据
    32. # user = User(name='ecithy')
    33. # article = Artcile(title='python')
    34. # article.user = user
    35. # db.session.add(article)
    36. # db.session.commit()
    37. # 查询数据
    38. # session.query()
    39. # user = User.query.all()
    40. # print(user)
    41. # users = User.query.order_by(User.id.desc()).all()
    42. # print(users)
    43. # users = db.session.query(User).all()
    44. # print(users)
    45. # user = User.query.filter(User.name == 'ecithy').first()
    46. # db.session.delete(user)
    47. # db.session.commit()
    48. @app.route("/")
    49. def index():
    50. return "首页"
    51. if __name__ == '__main__':
    52. app.run(debug=True)