文章目录
显示
数据库的ORM
当我们学完ORM之后,就可以利用前面所学的知识搭建框架结构,
Flask-SQLAlchemy
pip install flask_sqlalchemy
pip install mysqlclient
http://flask-sqlalchemy.pocoo.org/2.3
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
Windows下Flask同數據庫打交道
1. 以管理员身份运行Pycharm
2.安装库
pip install flask_sqlalchemy
pip install mysqlclient
https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
输入代码测试:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1/mysql'
db = SQLAlchemy(app)
@app.route('/api')
def index():
from sqlalchemy import text
sql = text("SELECT * FROM 'user'")
result = db.engine.execute(sql)
for row in result:
app.logger.info(row)
return 'Index Page'