目录结构
需安装库:
pip3 install flask-sqlalchemy==2.2
pip3 install FLASK
第一步:配置数据库相关信息
settings.py
DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = 'whr123456'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'whr_blog'
SQLALCHEMY_DATABASE_URI = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format(
DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE
)
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
第二步:建立数据库model
models.py
from blog import db
import datetime
class ArticleInfo(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer,primary_key=True)
author = db.Column(db.String(20),unique=True)
category = db.Column(db.ForeignKey('category.name'),comment='类别')
desc = db.Column(db.String(100))
content = db.Column(db.Text,comment='文章内容')
valid = db.Column(db.BOOLEAN,comment='是否删除')
click_num = db.Column(db.Integer,default=0,comment='点击量')
love_num = db.Column(db.Integer,default=0,comment='点赞')
image = db.Column(db.LargeBinary,comment='图片')
create_time = db.Column(db.DateTime,default=datetime.datetime.now())
update_time = db.Column(db.DateTime,default=None)
class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(20),unique=True)
create_time = db.Column(db.DateTime,default=datetime.datetime.now())
db.create_all()
第三步:blog目录下__init__.py文件,注意:app = Flask(name) 在所有的文件中只能出现一次
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
app.config.from_object('settings')
db = SQLAlchemy(app)
views.py
from flask import Flask,render_template,request
from blog import db,app
from blog.models import ArticleInfo,Category
@app.route("/")
def index():
return render_template('index.html')
@app.route("/addCat")
def addCat():
return render_template("addCategory.html")
@app.route("/addCategory" ,methods=['GET','POST'])
def addCategory():
if request.method == 'POST':
cat = Category()
cat.name = request.form['nm']
print(cat.name)
db.session.add(cat)
db.session.commit()
msg = "add category successful"
return render_template('result.html',msg=msg)
@app.route("/listCategory")
def listCategory():
cats = Category.query.all()
return render_template('categoryList.html',cats = cats)
@app.route("/deleteCat/<id>")
def deleteCat(id):
cat = Category.query.filter_by(id=id).first()
db.session.delete(cat)
db.session.commit()
msg = "delete category successful"
return render_template('result.html',msg=msg)
@app.route("/updateCat/<id>",methods=['GET','POST'])
def updateCat(id):
cat = Category.query.filter_by(id=id).first()
print(cat)
if request.method == 'POST':
cat = Category.query.filter_by(id=id).first()
cat.name = request.form['nm']
db.session.commit()
msg = "update category successful"
return render_template('result.html',msg=msg)
elif request.method == 'GET':
return render_template('updateCategory.html',cat=cat)
else:
msg = "fail"
return render_template('result.html',msg=msg)
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=5000)
index.html
<body>
<h2>
<a href="/addCat">新增分类</a><br>
<a href="/listCategory">查看分类</a>
</h2>
</body>
addCategory.html
<body>
<form action = "{{ url_for('addCategory') }}" method = "POST">
<h3>addCategory</h3>
Name<br>
<input type = "text" name = "nm" /></br>
<input type = "submit" value = "submit" /><br>
</form>
</body>
result.html
<body>
<h2>
result of addition : {{ msg }} <br>
<a href = "\">go back to home page</a>
</h2>
</body>
categoryList.html
<body>
<h2>category</h2>
<h5>
{% for cat in cats %}
<td>{{ cat.id }}</td>
<td>{{ cat['name'] }}</td>
<td><a href="/deleteCat/{{ cat.id }}">delete</a></td>
<td><a href="/updateCat/{{ cat.id }}">edit</a></td>
<br>
{% endfor %}
</h5>
</body>
updateCategory.html
<body>
<form action = "/updateCat/{{ cat.id }}" method = "POST">
<h3>updateCategory</h3>
Name<br>
<input type = "text" name = "nm" value="{{ cat.name }}"/></br>
<input type = "submit" value = "submit" /><br>
</form>
</body>
在用pycharm在views文件中直接运行就可以了~
建议:在练习的时候可以按照 :增-查-删-修改 的顺序来对应相应的方法
希望帮到大家~ 喜欢的点赞哦~❤️❤️❤️❤️❤️❤️❤️❤️❤️