当前位置:   article > 正文

Flask一:安装初始,return方式,Request,Jinja2,session

Flask一:安装初始,return方式,Request,Jinja2,session

一:安装和初始

  1. 1.Flask 安装 + 启动
  2. from flask import Flask
  3. app = Flask(__name__) # 实例化flask对象 # __name__ 多app应用,分区实例在哪个文件中
  4. app.run()
  5. 高级启动:
  6. from flask import Flask
  7. app = Flask(__name__)
  8. @app.route("/") # app中的rotue装饰器
  9. def home(): # 视图函数
  10. return "Hello World!"
  11. app.run()



二: Render, Redirect HttpResponse

  1. 2.Flask Response
  2. 1.HttpResponse("HelloWorld") "HelloWorld" 返回字符串
  3. from flask import render_template 默认存放路径 templates
  4. 2.render("模板路径") render_template 返回模板
  5. from flask import redirect 重定向
  6. 3.redirect("/")
  7. Flask 中的返回特殊封装 2
  8. 1.jsonify 转换标准JSON格式
  9. 响应头中加入 Content-type:application/json
  10. 在Flask 1.1.1 版本中 加入了 直接返回字典 可以不再使用jsonify了
  11. 2.send_file 发送文件
  12. 打开并返回文件内容,
  13. 自动识别文件类型,
  14. 响应头中加入Content-type:文件类型 # Content-Type: audio/mpeg
  15. ps:当浏览器无法识别Content-type时,会下载文件
  16. # 大的视频文件是 分段式请求
  17. # 打开并返回文件内容,自动识别文件类型,content-type:文件类型
  18. # Ps:
  19. # 浏览器无法识别content-type时,都以下载返回。 识别的话,直接打开
  1. from flask import Flask, render_template, redirect, jsonify, send_file
  2. # Alt + 回车 快速的导入模块
  3. app = Flask(__name__) # 实例化flask对象 # __name__ 多app应用,分区实例在哪个文件中
  4. app.config["DEBUG"] = True # 能够随时更改自动重启,不加的话每次更改代码需要手动重启
  5. @app.route("/") # app中的rotue装饰器
  6. def home(): # 视图函数
  7. # return 1
  8. # TypeError: The view function did not return a valid response.
  9. # The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a int.
  10. return "home"
  11. @app.route("/index")
  12. def index():
  13. return render_template("index.html")
  14. @app.route("/reback")
  15. def reback():
  16. return redirect('/index')
  17. @app.route("/json")
  18. def my_jsonify():
  19. # return jsonify({"a":1})
  20. return {"k": "v"}
  21. @app.route("/myfile")
  22. def my_file():
  23. # return send_file('1chushi.py')
  24. # return send_file('1.jpg')
  25. return send_file('ss.mp3')
  26. # 传文件
  27. # 不管video还是audio都是显示 Audio
  28. app.run()



三:Request

  1. 3.Flask Request
  2. 假登录
  3. 405 请求方式不被允许 - GET请求可以 POST请求 405 Method Not Allowed
  4. Form表单 - FormData
  5. f orm - 表单
  6. from flask import request 公共对象
  7. 1.request.form 获取FormData中的数据 - Form表单
  8. 2.request.args # 获取URL中的参数
  9. 3.request.files # 获取FormData中的文件数据
  10. print(request.url) # 获取访问路径
  11. print(request.method) # 获取请求方式
  12. print(request.path) # 路由地址 /login
  13. print(request.values) # Form 和 Args 中的数据
  14. # 综合获取 X
  15. print(request.args.get("id")) # 获取URL中的参数
  16. print(request.args["id"]) # 获取URL中的参数
  17. print(request.args.to_dict()) # 获取URL中的参数 转换成 字典
  18. print(request.environ) # 获取请求原始信息
  19. print(request.base_url) # 获取URL头,不包含参数
  20. print(request.json) # 毁三观 1 请求头中 Content-type:application/json 数据序列化 request.json
  21. print(request.data) # 毁三观 2 请求头中 Content-type 不包含 Form or data
  22. print(request.headers) # 请求头中的数据

3.1:request.py

  1. from flask import Flask, render_template, request
  2. import os
  3. app = Flask(__name__)
  4. app.config["DEBUG"] = True # 能够随时更改自动重启,不加的话每次更改代码需要手动重启
  5. @app.route("/login", methods=["POST", "GET"])
  6. def login():
  7. if request.method == "GET":
  8. print(request.url) # 获取访问路径
  9. # request.url: http://127.0.0.1:5000/login
  10. # request.url: http://127.0.0.1:5000/login?id=1
  11. print(request.method) # 获取请求方式
  12. # GET
  13. # GET
  14. print(request.path) # 路由地址 /login
  15. # /login
  16. # /login
  17. print(request.values) # 可以获取URL中的参数 也可以获取 FormData中的数据
  18. # 综合获取 ,可以获取url 和 formdata的数据
  19. # CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([])])
  20. # CombinedMultiDict([ImmutableMultiDict([('id', '1')]), ImmutableMultiDict([])])
  21. print(request.args)
  22. # ImmutableMultiDict([('id', '1')])
  23. print(request.args.to_dict()) # 获取URL中的参数 转换成 字典
  24. # {}
  25. # {'id': '1'}
  26. print(request.args.get("id")) # 获取URL中的参数
  27. # None 没有参数的时候就是None
  28. # 1
  29. # print(request.args["id"]) # 获取URL中的参数
  30. # 1
  31. # 字典索引取不到值的时候 ,会出现keyerror
  32. print(request.environ) # 获取请求原始信息
  33. # {'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': <_io.BufferedReader name=1140>, 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'werkzeug.server.shutdown': <function WSGIRequestHandler.make_environ.<locals>.shutdown_server at 0x000001F2C1CD8378>, 'SERVER_SOFTWARE': 'Werkzeug/0.15.4', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'PATH_INFO': '/login', 'QUERY_STRING': '', 'REQUEST_URI': '/login', 'RAW_URI': '/login', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': 14611, 'SERVER_NAME': '127.0.0.1', 'SERVER_PORT': '5000', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTP_HOST': '127.0.0.1:5000', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9,en;q=0.8', 'HTTP_COOKIE': 'sessionid=wnuu61vo39ha2rnhjly8tturem306js3; csrftoken=dBlvd2yERl2dy9Oe7JoPLWer7aaOf35nx83lvoruaY0NOkl3T747KlIo5YwZ7026', 'werkzeug.request': <Request 'http://127.0.0.1:5000/login' [GET]>}
  34. print(request.base_url) # 获取URL头,不包含参数
  35. # http://127.0.0.1:5000/login
  36. print(request.json) # 毁三观 1 请求头中 Content-type:application/json 数据序列化 request.json
  37. # None
  38. print(request.data) # 毁三观 2 请求头中 Content-type 不包含 Form or data
  39. # b''
  40. print(request.headers) # 请求头中的数据
  41. # Host: 127.0.0.1:5000
  42. # Connection: keep-alive
  43. # Cache-Control: max-age=0
  44. # Upgrade-Insecure-Requests: 1
  45. # User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
  46. # Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
  47. # Accept-Encoding: gzip, deflate, br
  48. # Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
  49. # Cookie: sessionid=wnuu61vo39ha2rnhjly8tturem306js3; csrftoken=dBlvd2yERl2dy9Oe7JoPLWer7aaOf35nx83lvoruaY0NOkl3T747KlIo5YwZ7026
  50. return render_template("login.html")
  51. if request.method == "POST":
  52. print(request.method)
  53. # POST
  54. print(request.form)
  55. # Multidict 多重字典,得到字典套列表套元组的类型
  56. # ImmutableMultiDict([('username', '123'), ('pwd', '456')])
  57. print(request.form.to_dict())
  58. # {'username': '123', 'pwd': '456'}
  59. print(request.values) # 可以获取URL中的参数 也可以获取 FormData中的数据
  60. # CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('username', '123'), ('pwd', '456')])])
  61. print(request.values.to_dict())
  62. # {'username': '123', 'pwd': '456'}
  63. print(request.json) # 毁三观 1 请求头中 Content-type:application/json 数据序列化 request.json
  64. # None
  65. print(request.data) # 毁三观 2 请求头中 Content-type 不包含 Form or data 原始请求体数据
  66. # b''
  67. print(request.headers)
  68. # Host: 127.0.0.1:5000
  69. # Connection: keep-alive
  70. # Content-Length: 235
  71. # Cache-Control: max-age=0
  72. # Origin: http://127.0.0.1:5000
  73. # Upgrade-Insecure-Requests: 1
  74. # Content-Type: multipart/form-data; boundary=----WebKitFormBoundary1BWoxZMCbTbU3Koy
  75. # User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
  76. # Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
  77. # Referer: http://127.0.0.1:5000/login
  78. # Accept-Encoding: gzip, deflate, br
  79. # Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
  80. # Cookie: sessionid=wnuu61vo39ha2rnhjly8tturem306js3; csrftoken=dBlvd2yERl2dy9Oe7JoPLWer7aaOf35nx83lvoruaY0NOkl3T747KlIo5YwZ7026
  81. # print(request.files.get("my_file"))
  82. #
  83. # my_file = request.files.get("my_file")
  84. # # fp = os.path.join("templates",my_file.filename)
  85. # my_file.save(my_file.filename)
  86. # 获取文件的数据
  87. print(request.files)
  88. # ImmutableMultiDict([('my_file', <FileStorage: '1.jpg' ('image/jpeg')>)])
  89. # 文件只在File 里显示
  90. # Form中不包含
  91. print(request.files.get("my_file"))
  92. # <FileStorage: '1.jpg' ('image/jpeg')>
  93. my_file = request.files.get("my_file")
  94. # my_file.save(my_file.filename)
  95. # 保存到本地的
  96. # 可以指定路径 用os模块
  97. fq = os.path.join("templates", my_file.filename)
  98. my_file.save(fq)
  99. username = request.form.get("username")
  100. password = request.form["pwd"]
  101. # Get 和索引都能拿到值
  102. if username == "123" and password == "456":
  103. return "登录成功"
  104. else:
  105. return "登录失败"
  106. # 如果包导入的话,if __name__下面不会执行
  107. if __name__ == '__main__':
  108. app.run()

3.2:login.html

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>Title</title>
  8. <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
  9. </head>
  10. <body>
  11. <form action="/login" method="post" enctype="multipart/form-data">
  12. 用户名: <input type="text " name="username">
  13. 密码: <input type="password" name="pwd">
  14. <input type="file" name="my_file">
  15. <input type="submit">
  16. </form>
  17. <script src="jquery-3.4.1.js"></script>
  18. <script>
  19. </script>
  20. </body>
  21. </html>



四:Jinja2和高级用法

  1. 4.Jinja2
  2. {{}} 引用 or 执行
  3. {%%} 逻辑语法 if else for

4.1:jinja2.py

  1. from flask import Flask, render_template,request,redirect,Markup
  2. STUDENT = {'name': 'Ivan', 'age': 38, 'gender': '中'}
  3. STUDENT_LIST = [
  4. {'name': 'Sail', 'age': 38, 'gender': '中'},
  5. {'name': 'Ivan', 'age': 73, 'gender': '男'},
  6. {'name': 'VS', 'age': 84, 'gender': '女'}
  7. ]
  8. STUDENT_DICT = {
  9. 1: {'name': 'Sail', 'age': 38, 'gender': '中'},
  10. 2: {'name': 'Ivan', 'age': 73, 'gender': '男'},
  11. 3: {'name': 'VS', 'age': 84, 'gender': '女'},
  12. }
  13. app = Flask(__name__)
  14. app.config["DEBUG"] = True
  15. @app.template_global()
  16. # 把ab函数传到前端了
  17. def ab(a,b):
  18. return a+b
  19. @app.route("/jija")
  20. def jija():
  21. my_in = Markup("<input type='text' name='uname'>")
  22. return render_template("jija.html",
  23. stu_info=STUDENT,
  24. stu_list=STUDENT_LIST,
  25. stu_dict=STUDENT_DICT,
  26. m=my_in
  27. )
  28. if __name__ == '__main__':
  29. app.run("127.0.0.1", 9999)

4.2:jinja2.html

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. {{ stu_info }}
  9. <table border="1px">
  10. <tr>
  11. <td>name</td>
  12. <td>age</td>
  13. <td>gender</td>
  14. </tr>
  15. <tr>
  16. <td>{{ stu_info.name }}</td>
  17. <td>{{ stu_info.get("age") }}</td>
  18. <td>{{ stu_info["gender"] }}</td>
  19. </tr>
  20. </table>
  21. <br/>
  22. {{ stu_list }}
  23. <table border="1px">
  24. <tr>
  25. <td>name</td>
  26. <td>age</td>
  27. <td>gender</td>
  28. </tr>
  29. ```
  30. {% for foo in stu_list %}
  31. <tr>
  32. <td>{{ foo.name }}</td>
  33. <td>{{ foo.get("age") }}</td>
  34. <td>{% if foo["gender"] !="男" and foo["gender"] !="女" %}
  35. {{ foo["gender"] }}
  36. {% endif %}
  37. </td>
  38. </tr>
  39. {% endfor %}
  40. ```
  41. </table>
  42. <br/>
  43. {{ stu_dict }}
  44. <table border="1px">
  45. <tr>
  46. <td>id</td>
  47. <td>name</td>
  48. <td>age</td>
  49. <td>gender</td>
  50. </tr>
  51. <tr>
  52. {% for id,s in stu_dict.items() %}
  53. <td>{{ id }}</td>
  54. <td>{{ s.name }}</td>
  55. <td>{{ s.get("age") }}</td>
  56. <td>{{ s["gender"] }}</td>
  57. </tr>
  58. {% endfor %}
  59. </table>
  60. <br/>
  61. {{ m }}
  62. <br/>
  63. {% macro my_input(na,ty) %}
  64. <input type="{{ ty }}" name="{{ na }}">
  65. {% endmacro %}
  66. {{ my_input("uname","text") }} # macro 需要启动才生产输入框
  67. <br/>
  68. {#{{ ab(1,2) }}#}
  69. </body>
  70. </html>

1538399-20190710210057826-1114950191.png



五:session

  1. 5.Flask中的Session 不是三方组件 //Flask-Session
  2. from flask import session
  3. session 交由客户端保管机制
  4. # eyJ1c2VybmFtZSI6IjEyMyJ9.XSVpHA.W0NfiCmW-lsTV0mvQI7mx2mf1Wo
  5. # .eJyrViotTi3KS8xNVbJSMjQyVtKBCxhiiBhhiBhjiJhgiJhiiJhBRWoBMFYkPg.XSVsaA.9merwNdTg3ZkZrdTumYRG7x8x7Y
  6. # .eJyrViotTi3KS8xNVbJSMjQyVtKBCxhiiBhhiBhjiJhgiJhiiJhBRWoBMFYkPg.XSVsvg.6OqcN7CR6nrT2BtE-w1kBAr3xPo
  7. # .eJxNzL0OgCAMBOB36exAoRTjs7jwUzcdNEzGdxckMV1u-e7uhnrJecRdYIG1eqS5pWCB6RccZDGtlQSjIvsRBxtbwZEmN8gZ21czK6JBiamtQhZF_qPAuR-WookH-dQO_WYiPC-8zDp8.XSVtLw.7I-z1bsqiWFln3cipbrVOpEE33g
  8. 反序列化机制 -
  9. 当客户端发起请求 - request 带上 Cookie - Cookie中有session的加密字符串 - Flask 收到Session加密字符串 - 通过secret_key解密session的加密字符串 - 获得 {username:123}
  10. 序列化机制 - 开启session - session["username"] = uname
  11. 先创建一个字典 {username:123} 接下来 通过secret_key + 时间戳 + 签名 加密 形成
  12. # eyJ1c2VybmFtZSI6IjEyMyJ9.XSVpHA.W0NfiCmW-lsTV0mvQI7mx2mf1Wo session的加密字符串

5.1:session.py

  1. from flask import Flask, session, request, render_template, redirect
  2. app = Flask(__name__)
  3. app.debug = True
  4. app.secret_key = "adfnaskjfnakjs"
  5. STUDENT = {'name': 'Old', 'age': 38, 'gender': '中'}
  6. STUDENT_LIST = [
  7. {'name': 'Old', 'age': 38, 'gender': '中'},
  8. {'name': 'Boy', 'age': 73, 'gender': '男'},
  9. {'name': 'EDU', 'age': 84, 'gender': '女'}
  10. ]
  11. STUDENT_DICT = {
  12. 1: {'name': 'Old', 'age': 38, 'gender': '中'},
  13. 2: {'name': 'Boy', 'age': 73, 'gender': '男'},
  14. 3: {'name': 'EDU', 'age': 84, 'gender': '女'},
  15. }
  16. @app.route("/login", methods=["POST", "GET"])
  17. def login():
  18. if request.method == "GET":
  19. return render_template("login.html")
  20. uname = request.form.get("username")
  21. pwd = request.form.get("pwd")
  22. if uname == '123' and pwd == '123':
  23. session['username'] = uname
  24. return "登陆成功"
  25. else:
  26. return "登录失败"
  27. @app.route("/detail")
  28. def detail():
  29. if session.get("username"):
  30. return render_template("jija.html",
  31. stu_info=STUDENT,
  32. stu_list=STUDENT_LIST,
  33. stu_dict=STUDENT_DICT, )
  34. else:
  35. return redirect("/login")
  36. if __name__ == '__main__':
  37. app.run("127.0.0.1", 9999)

5.2:login.html

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>Title</title>
  8. <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
  9. </head>
  10. <body>
  11. <form action="/login" method="post" enctype="multipart/form-data">
  12. 用户名: <input type="text " name="username">
  13. 密码: <input type="password" name="pwd">
  14. <input type="file" name="my_file">
  15. <input type="submit">
  16. </form>
  17. <script src="jquery-3.4.1.js"></script>
  18. <script>
  19. </script>
  20. </body>
  21. </html>





转载于:https://www.cnblogs.com/Quantum-World/p/11166227.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/191347
推荐阅读
相关标签
  

闽ICP备14008679号