Flask-SQLAlchemy
Flask-SQLAlchemy
安装 pip install Flask-SQLAlchemy
创建一个Flask项目
manager
from app01 import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
app01/__init__
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from app01.views import users
def create_app():
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:root@127.0.0.1:3306/sqlalchemy666?charset=utf8"
app.config["SQLALCHEMY_POOL_SIZE"] = 10
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
app.register_blueprint(users.users)
return app
app01/view/user
from flask import Blueprint, request, render_template, redirect
from app01.models import User
from app01 import db
users = Blueprint("user", __name__)
@users.route("/add_user", methods=["POST", "GET"])
def add_user():
if request.method == "GET":
return render_template("add_user.html")
else:
username = request.form.get("username")
db.session.add(User(name=username))
db.session.commit()
return redirect("/user_list")
@users.route("/user_list", methods=["POST", "GET"])
def user_list():
res = User.query.all()
print(res)
return render_template("user_list.html", user_list=res)
@users.route("/del/<uid>", methods=["POST", "GET"])
def delete_user(uid):
res = User.query.filter(User.id == int(uid)).delete()
db.session.commit()
print(res)
return redirect("/user_list")
app01/models
from app01 import db
class User(db.Model):
__tablename__ = "users_flask"
__table_args__ = {"useexisting": True}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), nullable=False)
if __name__ == '__main__':
from app01 import create_app
app = create_app()
db.create_all(app=app)
# db.drop_all(app=app)
app01/templates/add_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
添加用户: <input type="text" name="username" >
<input type="submit" value="添加">
</form>
</body>
</html>
app01/templates/user_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1px">
<tr>
<td>id</td>
<td>name</td>
<td>option</td>
</tr>
{% for user in user_list %}
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><a href="/del/{{user.id}}">删除</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>