tips:不涉及session,是纯简单数据共享
实现步骤:
第一步:搭建框架
首先flask比较灵活建议先搭架子
蓝图存放具体后端功能实现,你可以认为是flask的孩子
可以把相关的功能模块规整为同一个主题
⚠️新建的时候不是文件夹!!是python package,名自定义,为了明白是蓝图命名为blueprint
static存放css、js、img等文件
templates存放自己的html文件
app.py相当于汇总,做基础绑定
config放的是配置信息,比如数据库
exts放的是扩展的插件,比如SQLAlchemy,同时这个文件的意义就在于可以解决解决循环引用的问题
models放的是数据库这一个表的具体模型,比如你的用户表
第二步:创建数据库
官方下载链接https://dev.mysql.com/downloads/mysql/
一定要注意下载和自己mac版相一致的
然后用Navicat进行管理
然后填完信息点一下Test Connection测试一下
这个密码是你当时安装输过的,如果没改过就是root
忘了也没有关系可以重置密码的
新建好就不用手动创建表啦
使用Flask数据库迁移三部曲
使用前要牢记在app那边进行好绑定
打开pycharm的终端
依次输入三条命令:
flask db init
flask db migrate
flask db upgrade
然后刷新你的数据库
user表是主要的,另外那个表是迁移带的,告知的是版本号
第三步:设计前端网页
框架用的Bootstrap的组件这边我直接贴代码:
index.html:
网页访问地址:http://127.0.0.1:5000/auth/login
密码是加密了,不是直接明文存放在数据库中的
![请添加图片描述](https://img-blog.csdnimg.cn/7ab90ab4ad2342d39e740a51ba2586f6.png
<!DOCTYPEhtml><htmllang="en"><head><metacharset="utf-8"/><metaname="viewport"width="device-width,"initial-scale="1.0,"maximum-scale="1.0,"user-scalable="0"/><title>表单</title><linkrel="stylesheet"href="{{ url_for('static',filename = 'css/circle.css') }}"><linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"crossorigin="anonymous"></head><body><formmethod="POST"><divclass="form-group"><labelfor="exampleInputEmail1">User name </label><inputtype="text"placeholder="请输入长度为5的用户名"name="username"class="form-control"id="exampleInputEmail1"aria-describedby="emailHelp"></div><divclass="form-group"><labelfor="exampleInputPassword1">Password</label><inputtype="password"name="password"class="form-control"id="exampleInputPassword1"><smallid="emailHelp"class="form-text text-muted">We'll never share your password with anyone else.</small></div><divclass="form-group"><labelfor="exampleInputPassword1">Age</label><inputtype="text"name="age"class="form-control"id="exampleInputPassword1"></div><buttontype="submit"class="btn btn-primary btn-block">Submit</button></form></body></html>
result.html:
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"crossorigin="anonymous"><title>结果</title><scriptsrc="{{ url_for('static',filename = 'js/p5.js') }}"></script><scriptsrc="{{ url_for('static',filename = 'js/circle.js') }}"></script><linkrel="stylesheet"href="{{ url_for('static',filename = 'css/circle.css') }}"></head><body><tableclass="table"><theadclass="thead-light"><tr><thscope="col">Id</th><thscope="col">Name</th><thscope="col">Age</th></tr></thead><tbody>
{% for student in people %}
<tr><td>{{ student.id }}</td><td>{{ student.username }}</td><td>{{ student.age }}</td></tr>
{% endfor %}
</tbody></table></body></html>
第四步:后端实现存储数据库
auth.py:
from flask import Blueprint, render_template, request, redirect, url_for
from werkzeug.security import generate_password_hash
from wtforms import form
from exts import db
from models import User
from.froms import loginForm
bp = Blueprint("auth", __name__, url_prefix="/auth")@bp.route('/login', methods=['GET','POST'])deflogin():if request.method =='GET':return render_template('index.html')else:
username = request.form.get('username')
password = request.form.get('password')
age = request.form.get('age')print("username", username)
user = User(username=username, password=generate_password_hash(password), age=age)
db.session.add(user)
db.session.commit()return redirect(url_for("auth.result"))@bp.route('/result', methods=['GET','POST'])defresult():# put application's code here
people = User.query.all()print(people)return render_template('result.html', people=people)
其中最关键的是:
user = User(username=username, password=generate_password_hash(password), age=age)
db.session.add(user)
db.session.commit()
实现了数据的存储到数据库
然后查询数据库的所有内容转发到新的页面
people = User.query.all()print(people)return render_template('result.html', people=people)
数据库的存放情况:
整体实现需要的代码文件:
github: https://github.com/jinyuyuu/p5js_flask.git
注意 git文件没有额外的migrations,你需要用三件套迁移一下数据库
1、auth.py(上面有)
2、circle.css:
html, body {
margin: 20px;
padding: 4px;}
canvas {
display: block;
margin: auto;
width: 40%;
/*border: 3px solid #73AD21;*/}
3、circle.js:
let angles =[30, 10, 45, 35, 60, 38, 75, 67];functionsetup(){
createCanvas(720, 400);
noStroke();
noLoop(); // 执行一次之后停止
}functiondraw(){
background(100);
pieChart(300, angles);}function pieChart(diameter, data){let lastAngle =0;for(let i =0; i < data.length; i++){let gray = map(i, 0, data.length, 0, 255);
fill(gray);
arc(
width / 2,
height / 2,
diameter,
diameter,
lastAngle,
lastAngle + radians(angles[i]));
lastAngle += radians(angles[i]);}}
4、p5.js下载地址:下载程序库里面有
5、index.html(上面有)
6、result.html(上面有)
7、config.py
HOSTNAME ='127.0.0.1'
PORT ='3306'
DATABASE ='student'
USERNAME ='root'
PASSWORD ='root'
DB_URI ='mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
8、models.py
from exts import db
classUser(db.Model):
__tablename__ ="user"id= db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(100))
password = db.Column(db.String(400))
age = db.Column(db.Integer())def__repr__(self):returnf'<User {self.id}>'
9、exts.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
版权归原作者 YUISOK 所有, 如有侵权,请联系我们删除。