Flask学习笔记
1.环境
conda reate -n flask python
conda activate flask
pip install flask -i http://pypi.douban.com/simple/--trusted-host pypi.douban.com
2.知识点
2.1.第一个flask项目
首先项目的结构
static(文件夹,放css,js,图片文件等)
templates(文件夹,放html文件)
1.第一个flask项目.py
from flask import Flask#flask包中导入Flask类
app=Flask(__name__)#使用Flask类创建一个对象#创建路由和试图函数的映射@app.route("/")defhello():return"hello world"if __name__=="__main__":
app.run()
2.2.修改Debug,host,port配置
app.run(debug=True,host="0.0.0.0",port="5001")
2.3.url与视图函数
有参路由,路由传参
查询字符串的方式传参:http://172.20.10.5:5000/book/list?page=9,默认page=1
from flask import Flask,request
app=Flask(__name__)#1.url:http[80]/https[443]://www.域名.com:port/[email protected]("/")defhello():return"hello world"@app.route("/profile")defprofile():return"个人中心"#2.有参路由,路由传参@app.route("/blog/<int:blog_id>")defblog_detail(blog_id):return"您访问的博客是:%d"%blog_id
#3.查询字符串的方式传参:http://172.20.10.5:5000/book/list?page=9,默认[email protected]("/book/list")defbook_list():
page=request.args.get(key="page",default=1,type=int)returnf"这是第{page}页"if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.4.模板渲染
1.templates/blog.html
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><titel>博客</titel></head><body><h1>博客id是:{{blog_id}}</h1><p>博客名是:{{user_name}}</p><!--1.取变量值*/--><div>{{user.username}}/{{user.email}}</div><!--2.取对象属性*/--><div>{{person.u}}/{{person["e"]}}</div><!--1.字典的取值有两种方式*/--></body></html>
2.模板渲染.py
from flask import Flask,render_template
app=Flask(__name__)@app.route("/")defhello():return render_template("index.html")#1.自动去templates目录下面找index.html文件,并渲染@app.route("/blog/<blog_id>")defblog_detail(blog_id):return render_template("blog.html",blog_id=blog_id,user_name="zoe")#2.传参数给html去渲染,html:{{var_name}}classUser:def__init__(self,username,email):
self.username=username
self.email=email
@app.route("/information")definformation():
user=User(username="张三",email="111@zs")
person={"u":"李四","e":"222@ls"}return render_template("blog.html",user=user,person=person)#3.传的参数是对象,字典。if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.5.过滤器
传到html的变量处理再渲染,这时用管道操作符(|),连接自带的过滤器或者自定义的过滤器.
1.filter.html
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><titel></titel></head><body><div>{{user.username}}长度是:{{user.username|length}}</div><!--1.管道操作符后连接length自带的过滤器--><div>{{mytime|dformat}}</div><!--2.管道操作符后连接的是自定义的过滤器--></body></html>
2.过滤器.py
from flask import Flask,render_template
from datetime import datetime
app=Flask(__name__)classUser:def__init__(self,username,email):
self.username=username
self.email=email
#2.自定义过滤器defdatetime_format(value,format="%Y年%m月%d日 %H:%M"):return value.strftime(format)
app.add_template_filter(datetime_format,"dformat")#将自定义的datetime_format,以dformat为名添加到app的过滤器中@app.route("/filter")deffilter():
user=User(username="张三",email="111@zs")
mytime=datetime.now()return render_template("filter.html",user=user,mytime=mytime)#1.user这里在html中会用到自带的过滤器,给出变量的lengthif __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.6.控制语句for与if
1.control.html
<!DOCTYPEhtml><htmllang="en"><head><metachatset="UTF-8"><title>控制语句if与for</title></head><body>
{% if age>18 %}
<div>你已成年</div>
{% elif age==18 %}
<div>你今年成年</div>
{% else %}
<div>你未成年啊</div>
{% endif %}
{% for book in books %}
<div>书名:{{book.name}},作者:{{book.author}}</div>
{% endfor %}
</body></html>
2.控制语句.py
from flask import Flask,render_template
app=Flask("__name__")@app.route("/control")defcontrol():
age=8
books=[{"name":"三国演义","author":"罗贯中"},{"name":"水浒传","author":"施耐庵"}]return render_template("control.html",age=age,books=books)if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.7.模板继承
1.base.html
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>{% block title %}{% endblock %}</title></head><body>
这是base文字
{% block body %}{% endblock %}
</body></html>
2.child1.html
{% extends "base.html"%}
{% block title %}
child1的title
{% endblock %}
{% block body %}
child1的body
{% endblock %}
3.模板继承.py
from flask import Flask,render_template
app=Flask("__name__")@app.route("/child1")defchild1():return render_template("child1.html")if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.8.加载静态文件
在html文件里加载static里面的css,js,picture等文件。
1.alert.js
alert("js执行的弹窗");
2.style.css
body{background-color:pink;}
3.static.html
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>静态文件加载</title><linkrel="stylesheet"href="{{url_for('static',filename='css/style.css')}}"><!--加载css样式文件--><scriptsrc="{{url_for('static',filename='js/alert.js')}}"></script><!--加载js文件--></head><body><imgsrc="{{url_for('static',filename='img/1.jpg')}}"alt=""><!--加载img文件--></body></html>
4.加载静态文件.py
from flask import Flask,render_template
app=Flask("__name__")@app.route("/my_static")defmy_static():return render_template("static.html")if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.9.mysql操作
2.9.1.安装mysql
这里可以参考博文。
然后在flask环境中
pip install pymysql
pip install flask-sqlalchemy
创建一个名为database_learn的数据库
2.9.2.在python中连接数据库并测试是否连接成功
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="xxxx"
DATABASE="database_learn"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)#1.sqlalchemy读取app的config,然后自动连接,#2.测试sql是否连接成功,输出(1,),表示连接成功with app.app_context():with db.engine.connect()as conn:
rs=conn.execute(text("select 1"))print(rs.fetchone())@app.route("/")defhello():return"hello"if __name__=="__main__":
app.run()
2.9.3.创建表并增删改查
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="xxxx"
DATABASE="database_learn"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)#1.ORM对象关系映射,一个ORM模型与数据库中的一个表对应:创建一个类就是创建了一张表,实例化一个对象就是插入了一条数据classUser(db.Model):
__tablename__="user"#表名id=db.Column(db.Integer,primary_key=True,autoincrement=True)#设为主键,自动增长
username=db.Column(db.String(100),nullable=False)#不可置空
password=db.Column(db.String(100),nullable=False)with app.app_context():
db.create_all()#开始创建表#1.增:@app.route("/user/add")defadd_user():
user=User(username="张三",password="123")#1.创建ORM对象
db.session.add(user)#2.将ORM对象添加到db.session
db.session.commit()#3.将db.session中的改变同步到数据库中return"用户创建成功"#2.查询:get查找(根据主键查找);filter_by查找@app.route("/query")defquery():#1.get查找# user=User.query.get(1)# print(f"{user.id}:{user.username}--{user.password}")#2.filter_by查找
users=User.query.filter_by(username="张三")#是一个Query类数组for user in users:print(user.username)return"查找成功"#3.改:@app.route("/user/update")defupdate_user():
user=User.query.filter_by(username="张三").first()
user.password="gai"
db.session.commit()return"数据修改成功"#4.删:@app.route("/user/delete")defdelete_user():
user=User.query.get(1)
db.session.delete(user)
db.session.commit()return"删除成功"@app.route("/")defhello():return"hello"if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.9.4.外键与表关系
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="190023"
DATABASE="database_learn"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)classUser(db.Model):
__tablename__="user"#表名id=db.Column(db.Integer,primary_key=True,autoincrement=True)#设为主键,自动增长
username=db.Column(db.String(100),nullable=False)#不可置空
password=db.Column(db.String(100),nullable=False)classArticle(db.Model):
__tablename__="article"id=db.Column(db.Integer,primary_key=True,autoincrement=True)
title=db.Column(db.String(200),nullable=False)
content=db.Column(db.Text,nullable=False)#添加两表之间的外键
author_id=db.Column(db.Integer,db.ForeignKey("user.id"))#添加两表之间的对象关系
author=db.relationship("User",backref="articles")#article.author返回User的对象,user.articles返回Article的对象with app.app_context():
db.create_all()#增@app.route("/article/add")defar_ad():
article1=Article(title="西游记",content="xxxxxxxxxxxxxxxx")
article1.author=User.query.get(2)
article2=Article(title="红楼梦",content="yyyyyyyyyyyyyyyy")
article2.author=User.query.get(2)#添加到session中
db.session.add_all([article1,article2])#session中的数据同步到数据库中
db.session.commit()return"文章添加成功"#查@app.route("/article/query")defar_qu():
user=User.query.get(2)for article in user.articles:print(article.title)return"文章查找成功"if __name__=="__main__":
app.run(debug=True,host="0.0.0.0",port="5000")
2.9.5.flask-migrate迁移ORM模型
set flask环境
pip install flask-migrate
pip install flask-migrate --upgrade
pip install flask-sqlalchemy --upgrade
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
HOSTNAME="127.0.0.1"
PORT=3306
USERNAME="root"
PASSWORD="190023"
DATABASE="database_flask"
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
db=SQLAlchemy(app)
migrate=Migrate(app,db)#ORM模型映射的三步#1.flask db init:秩序执行一次,相当于仓库初始化#2.flask db migrate:识别ORM模型的改变,生成迁移脚本#3.flask db upgrade:
版权归原作者 我是小z呀 所有, 如有侵权,请联系我们删除。