【Flask笔记】
命令行启动flask应用
Linux:
(假设hello.py是服务器脚本)
$ export FLASK_APP=hello.py
$ flask run --host=0.0.0.0
Windows cmd:
set FLASK_APP=server.py
flask run --host=0.0.0.0
hello world
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<h1>哈哈</h1>"
# 括号中的参数使得同一网络下的所有设备都可以访问该服务器(不过我试了下似乎没有效果)
app.run(host="0.0.0.0")
实现传参(两种方式):
- 使用转换器
# 参数默认为string类型
@app.route("/<name>")
def hello_world(name):
return f"<h1>你好{name}</h1> "
# 转换器可以实现int类型传参(在尖括号中标记)
@app.route("/<int:name>")
def hello_world(name):
return f"<h1>你好{name}</h1> "
转换器类型:
类型 | 描述 |
---|---|
string | (省缺)接收任何不包含斜杠的文本 |
int | 接受正整数 |
float | 接受浮点数 |
path | 类似string ,但可以包含斜杠 |
uuid | 接受UUID字符串 |
- (不知道叫啥方式)
# 这里的request是flask的,不是urllib库的
from urllib import request
@app.route("/", methods=["POST"])
def hello_world():
# 若用户的POST请求没有携带数据,则默认name为“哈哈”
name = request.args.get("name", default="哈哈", type=str)
return f"名字是: {name}"
重定向
@app.route("/bilibili")
def bilibili():
return redirect("https://www.bilibili.com/")
接受POST请求
@app.route("/test", methods=["POST"])
def first_post():
my_json = request.get_json() # 浏览器请求携带的json数据
print(my_json)
return "good" # 给浏览器返回的响应
检测POST请求参数是否正确
@app.route("/test", methods=["POST"])
def first_post():
try
my_json = request.get_json() # 浏览器请求携带的json数据
print(my_json)
get_name = my_json.get("name")
get_age = my_json.get("age")
if not all([get_name, get_age]):
return jsonify(msg="缺少参数")
return "good" # 给浏览器返回的响应
except Exception as e:
print(e)
return jsonify(msg="出错了,请查看是否正确访问")
jinja2
模板渲染
在项目文件夹下新建templates文件夹(名字一定要打对)
在文件夹中新建一个index.html
现在项目的结构为
- demo01
- templates
- index.html
- hello.py
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo01</title>
</head>
<body>
<!-- 这个位置的双花括号可以填一个形参,此形参的值将由后端传递过来 -->
<h1>{{username}}</h1>
</body>
</html>
hello.py
from flask import render_template
@app.route("/demo01/<username>")
def template_demo01(username):
# 传递html文件的同时,将username这个用户输入传递到html中
return render_template("index.html", username=username)
同样也可以渲染类对象
<!-- tamplates/index.html -->
<h1>hello {{student.sname}}, your sid is {{student.sid}}</h1>
# hello.py
class Student:
def __init__(self, sid, sname):
self.sid = sid
self.sname = sname
@app.route("/", methods=["GET"])
def hello_student():
s1 = Student("001", "牛马")
return render_template("demo01.html", student=s1)
也可以渲染字典
<!-- tamplates/index.html -->
<!-- 使用中括号或者点都可以访问到属性 -->
<h1>hello {{student.sname}}, your sid is {{student["sname"]}}</h1>
# hello.py
@app.route("/", methods=["GET"])
def hello_student():
s1 = {
"sname": "牛哥",
"sid": "001"
}
return render_template("demo01.html", student=s1)
过滤器的使用
<!-- tamplates/index.html -->
<!-- | length 可以得到student.sname的长度 -->
<h1>你的名字长度是 {{student.sname | length}}}}</h1>
过滤器名称 | 作用 |
---|---|
safe | 解析字符串中的html标签 |
striptags | 去除字符串中的html标签 |
更多内置过滤器参考官方文档
还可以自定义过滤器
from datetime import datetime
# 1. 定义你想实现的函数功能
def datetime_format(value, format="%Y年%m月%d日 %H:%M"):
return value.strftime(format)
# 2. 把它假入到app的过滤器中,并起个名字
app.add_template_filter(datetime_format, "dformat")
@app.route("/", methods=["GET"])
def hello_student():
s1 = {
"sname": "牛哥",
"sid": "001"
}
now = datetime.now()
return render_template("demo01.html", student=s1, now=now)
<!-- 在html中用刚刚起的名字来调用过滤器 -->
<h1>hello {{student.sname | length}}, now is {{now | dformat}}</h1>
流程控制
{% if age > 18 %}
<div>您已满18岁,可以观看</div>
{% elif age==18 %}
<div>您刚满18岁,需要在父母陪同下观看</div>
{% else %}
<div>您未满18岁,不可以观看</div>
{% endif %}
{% for book in books %}
<!-- 在jinja2中不存在break -->
<div>图书名称:{{ book.name }},图书作者:{{ book.author}} </div>
{% endfor %}}
模板继承
<!-- 用extends关键字进行继承 -->
{% extends "parent.html" %}
父模板中可以留白,让子类自己去实现
<!-- parent.html -->
<title>{% block title %}{% end block %}</title>
<!-- child.html -->
{% extends "parent.html" %}
{% block title %}
我是子类标题
{% end block %}
加载静态文件
项目结构
- demo01
- static
- css
- index.css
- js
- index.js
- img
- pandaman.png
- templates
- index.html
- hello.py
在index.html
中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- 用url_for()函数加载静态资源,只要是静态资源,第一个参数就永远是'static',第二个参数填static文件夹下的文件路径 -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}">
<script src="{{ url_for('static', filename='js/index.js') }}"></script>
<title>demo01</title>
</head>
<body>
<h1>hello {{student.sname | length}}, now is {{now | fuck}}</h1>
<img src="{{ url_for('static', filename='img/熊猫人.png') }}">
</body>
</html>