主要内容:
1.flask 第一个小程序
2.response三剑客:
response,render_template,redirect
3.request
4.Jinja2
5.session
一.flask 第一个小程序
1)安装flask pip3 install flask
2)导入flask
from flask import Flask
from flask import Flask app = Flask(__name__) app.run() ###右键运行就可以了
在上面的基础上设置路由
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "这是首页" app.run() ###@app.route("/home",methods=["GET","POST"]) ###上面是路由设置
二.response三剑客以及相关子设置.
关于模板的设置,默认是需要是需要在项目下建立一个文件夹,文件夹必须为templates,在pycharm中如果设置自动提醒的话,需要右键点击templates选择mark directory as --------templates floder.
关于三剑客的设置参考如下:
from flask import Flask,render_template,redirect,send_file,jsonify,request app = Flask(__name__) @app.route("/index") def index(): return "这是首页" ###相当于HttpResponse @app.route("/login") def login(): return render_template("login.html") ##需要导入render_template,然后在templates里面写入html文件 @app.route("/home",methods=["GET","POST"]) def home(): username = request.form.get("name") pwd = request.form.get("password") if username == "leon" and pwd == "leon": return redirect("/index") #导入redirect 后,做个跳转 return "错误哦" app.run()
关于send_file和jsonify
return send_file("2.mp3") # 打开文件并返回客户端
return jsonify({"name":"yinwangba"}) # 返回标准的json格式字符串 content-type: application/json
示例如下:
from flask import Flask,render_template,redirect,send_file,jsonify,request app = Flask(__name__) @app.route("/index") def index(): return "这是首页" ###相当于HttpResponse @app.route("/login") def login(): return render_template("login.html") ##需要导入render_template,然后在templates里面写入html文件 @app.route("/home",methods=["GET","POST"]) def home(): username = request.form.get("name") pwd = request.form.get("password") if username == "leon" and pwd == "leon": return redirect("/index") #导入redirect 后,做个跳转 return "错误哦" @app.route("/getfile") def getfile(): return send_file("day115.txt") @app.route("/getjson") def getjson(): a = {"k":"v"} return jsonify(a) app.run()
三.request
这里需要注意的是request并不是作为参数传入的,而是request作为池子调用的,需要的时候去到池子里面去取的
# print(request.form) # form 存放form表单中的序列化数据 # print(request.args) # args 存放URL中的序列化数据 # print(request.values) # values 存放URL和form表单中的序列化数据 # print(request.method) # method 存放请求方式 # print(request.path) # path 路由地址 # print(request.url) # url 请求全部地址 http://127.0.0.1:5000/home?id=jwb&username=ywb # print(request.host) # host 主机位 127.0.0.1:5000 # print(request.host_url) # host_url 将主机位转成url http://127.0.0.1:5000/ # print(request.data) # data 当请求头content-type无法被识别时 # print(request.json) # json 当请求头content-type:application/json # print(request.headers) # headers 查看请求头 # print(request.files.get("file")) # files 获取文件对象 # file = request.files.get("file") # file.save(file.filename) #存储文件
测试示例如下:
from flask import Flask,render_template,redirect,send_file,jsonify,request app = Flask(__name__) @app.route("/index") def index(): return "这是首页" ###相当于HttpResponse @app.route("/login") def login(): return render_template("login.html") ##需要导入render_template,然后在templates里面写入html文件 @app.route("/home",methods=["GET","POST"]) def home(): username = request.form.get("name") pwd = request.form.get("password") print("**********************************") print("request form",request.form) print("request args",request.args) print("request values",request.values) print("request method ",request.method) print("request path",request.path) print("request url",request.url) print("request host_url",request.host_url) print("request.data",request.data) print("request headers",request.headers) print("***********************************") if username == "leon" and pwd == "leon": return redirect("/index") #导入redirect 后,做个跳转 return "错误哦" @app.route("/getfile") def getfile(): return send_file("day115.txt") @app.route("/getjson") def getjson(): a = {"k":"v"} return jsonify(a) app.run() """ 运行结果如下: ********************************** 127.0.0.1 - - [20/Nov/2018 15:57:33] "GET /index HTTP/1.1" 200 - request form ImmutableMultiDict([('name', 'leon'), ('password', 'leon'), ('file', '')]) request args ImmutableMultiDict([('v1', '1'), ('token', 'hehe')]) request values CombinedMultiDict([ImmutableMultiDict([('v1', '1'), ('token', 'hehe')]), ImmutableMultiDict([('name', 'leon'), ('password', 'leon'), ('file', '')])]) request method POST request path /home request url http://127.0.0.1:5000/home?v1=1&token=hehe request host_url http://127.0.0.1:5000/ request.data b'' request headers Host: 127.0.0.1:5000 Connection: keep-alive Content-Length: 382 Cache-Control: max-age=0 Origin: http://127.0.0.1:5000 Upgrade-Insecure-Requests: 1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryivB199QYMwLFX1yt User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Referer: http://127.0.0.1:5000/login Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 Cookie: csrftoken=7PvuH3f1qTGBzyaSlBSnfgoRaCP5TkN6f0LT9WsG7Rwl1imm7e6H2O2WrgtzMYa8 *********************************** """
测试file的示例如下:
if username == "leon" and pwd == "leon": file = request.files.get("file")#这里是获取文件对象 file.save(file.filename)#这里是存储 return redirect("/index") #导入redirect 后,做个跳转
四.Jinja2 的使用
jinja2和django 的templates很像.
这里大概介绍一下语法如下:
{{}} 引用变量 非逻辑代码时使用
{%%} 逻辑代码使用
| safe
Markup : from flask import Markup 后台返回安全标签字符串
{% block jj2 %}
{% include "login.html" %}
{% macro func(name,type_name) %}
<input type="{{ type_name }}" name="{{ name }}">
<input type="submit" value="提交文件">
{% endmacro %}
{{ func("file","file") }}
下面举例如下:
""" 参考数据如下: STUDENT = {'name': 'leon', 'age': 18, 'gender': 'man'} STUDENT_LIST = [ {'name': 'ben', 'age': 18, 'gender': "mid"}, {'name': 'roy', 'age': 23, 'gender': 'female'}, {'name': 'leon', 'age': 34, 'gender': '女'} ] STUDENT_DICT = { 1: {'name': 'tim', 'age': 18, 'gender': 'mid'}, 2: {'name': 'leon', 'age': 23, 'gender': 'man'}, 3: {'name': 'roy', 'age': 34, 'gender': 'female'}, } """" ###index里面的代码如下 {{ stu }} 获取字典的三种方法 <br> 1 {{ stu.name }} <br> 2 {{ stu.get("age") }} <br> 3 {{ stu["gender"] }}
下面是表格显示列表和字典的数据.这里需要注意的是,如果在循环中引用的话,不能使用.name的方式的.
示例如下
<table border="1px"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> </thead> <tbody> {% for stu_li in stu_list %} <tr> <td>{{ stu_li.name}}</td> <td>{{ stu_li.get("age") }}</td> <td>{{ stu_li["gender"] }}</td> </tr> {% endfor %} </tbody> </table> <table border="1px"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> </thead> <tbody> {% for stu_d in stu_dic %} <tr> <td>{{ stu_d }}</td> <td>{{ stu_dic.get(stu_d).name}}</td> <td>{{ stu_dic[stu_d].age }}</td> {# <td>{{ stu_dic.get(stu_d).gender }}</td>#} <td>{% if stu_dic.get(stu_d).gender != "中" %} {{stu_dic.get(stu_d).gender}} {% else %} 不存在 {% endif %}</td> </tr> {% endfor %} </tbody> </table>
关于jinja2中如果引入标签,
如果在前端的话,示例如下:
""" html前端代码如下 """ {{ a|safe }} flask后端代码如下: @app.route("/jinja",methods=["GET","POST"]) def jinja(): a = "<a href='http://www.baidu.com'>123</a>" a = Markup(a) return render_template("jinja.html",stu=STUDENT,stu_list = STUDENT_LIST,stu_dic = STUDENT_DICT,a=a )
如果在后端的话实现的话是通过导入Markup来实现的.
from flask import Flask,render_template,redirect,request,send_file,jsonify,Markup,session
@app.route("/jinja",methods=["GET","POST"]) def jinja(): a = "<a href='http://www.baidu.com'>123</a>" a = Markup(a) return render_template("jinja.html",stu=STUDENT,stu_list = STUDENT_LIST,stu_dic = STUDENT_DICT,a=a )
还有一个概念宏定义:
示例代码如下:
{% macro func(name,type_name) %} <input type="{{ type_name }}" name="{{ name }}"> <input type="submit" value="提交文件"> {% endmacro %} <form action="post"> {{ func("file","file") }} </form>
五.session组件.
session组件需要注意两件事情,
1是session组件需要设置app.secret_key
2是session被序列化后存放在 浏览器的cookie中的.
示例如下:
from flask import Flask,render_template,redirect,request,send_file,jsonify,Markup,session app.secret_key = "leon" ####seesion写入 @app.route("/home",methods=["GET","POST"]) def home(): name = request.form.get("name") pwd = request.form.get("password") if name == "leon" and pwd == "leon": # file = request.files.get("file") session["user"] = name # file.save("123.txt") return redirect("/index") return "登录失败的!" ####session验证如下: if session.get("user"): return ""ok""
六.特殊装饰器
特殊装饰器:
@app.template_global()
def a_and_b(a,b):
return a+b
@app.template_filter()
def abc(a,b,c):
return a+b+c
示例::
#在flask后端Py文件里写如下代码: @app.template_global() def a_b(a,b): return a+b #在前端index页面写如下引用 {{ a_b(1,2) }} 第二个 #在flask后端Py文件里写如下代码: @app.template_filter() def abc(a,b,c): return a+b+c #在前端index页面写如下引用 {{ a_b(1,2 )| abc(1,1) }}