脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python3+Flask安装使用教程详解

Python3+Flask安装使用教程详解

2021-09-05 00:07诸子流 Python

这篇文章主要介绍了Python3+Flask安装使用教程详解,需要的朋友可以参考下

 一、Flask安装环境配置

当前我的开发环境是Miniconda3+PyCharm。开发环境其实无所谓,自己使用Python3+Nodepad都可以。安装Flask库:

pip install Flask

二、第一个Flask应用程序

将以下内容保存为helloworld.py:

  1. # 导入Flask类
  2. from flask import Flask
  3. # 实例化,可视为固定格式
  4. app = Flask(__name__)
  5.  
  6. # route()方法用于设定路由;类似spring路由配置
  7. @app.route('/helloworld')
  8. def hello_world():
  9. return 'Hello, World!'
  10.  
  11. if __name__ == '__main__':
  12. # app.run(host, port, debug, options)
  13. # 默认值:host="127.0.0.1", port=5000, debug=False
  14. app.run(host="0.0.0.0", port=5000)

直接运行该文件,然后访问:http://127.0.0.1:5000/helloworld。结果如下图:

Python3+Flask安装使用教程详解

三、get和post实现

3.1 创建用到的模板文件

Flask默认到templates目录下查找模板文件,在上边helloworld.py同级目录下创建templates文件夹。

在templates文件夹下创建get.html,写入以下内容:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>get请求示例</title>
  6. </head>
  7. <body>
  8. <form action="/deal_request" method="get">
  9. <input type="text" name="q" />
  10. <input type="submit" value="搜索" />
  11. </form>
  12. </body>
  13. </html>

再在templates文件夹下创建post.html,写入以下内容:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>post请求示例</title>
  6. </head>
  7. <body>
  8. <form action="/deal_request" method="post">
  9. <input type="text" name="q" />
  10. <input type="submit" value="搜索" />
  11. </form>
  12. </body>
  13. </html>

最后在templates文件夹下创建result.html,写入以下内容:

  1. <!-- Flask 使用Jinja2模板引擎,Jinja2模板引擎源于Django板模所以很多语法和Django是类似的 -->
  2. <h1>{{ result }}</h1>

3.2 编写相关的处理方法

在helloworld.py中添加get_html()、post_html()和deal_request()三个方法,更多说明见注释。当前helloworld.py内容如下:

  1. # 导入Flask类
  2. from flask import Flask
  3. from flask import render_template
  4. from flask import request
  5. # 实例化,可视为固定格式
  6. app = Flask(__name__)
  7.  
  8. # route()方法用于设定路由;类似spring路由配置
  9. #等价于在方法后写:app.add_url_rule('/', 'helloworld', hello_world)
  10. @app.route('/helloworld')
  11. def hello_world():
  12. return 'Hello, World!'
  13.  
  14. # 配置路由,当请求get.html时交由get_html()处理
  15. @app.route('/get.html')
  16. def get_html():
  17. # 使用render_template()方法重定向到templates文件夹下查找get.html文件
  18. return render_template('get.html')
  19.  
  20. # 配置路由,当请求post.html时交由post_html()处理
  21. @app.route('/post.html')
  22. def post_html():
  23. # 使用render_template()方法重定向到templates文件夹下查找post.html文件
  24. return render_template('post.html')
  25.  
  26. # 配置路由,当请求deal_request时交由deal_request()处理
  27. # 默认处理get请求,我们通过methods参数指明也处理post请求
  28. # 当然还可以直接指定methods = ['POST']只处理post请求, 这样下面就不需要if了
  29. @app.route('/deal_request', methods = ['GET', 'POST'])
  30. def deal_request():
  31. if request.method == "GET":
  32. # get通过request.args.get("param_name","")形式获取参数值
  33. get_q = request.args.get("q","")
  34. return render_template("result.html", result=get_q)
  35. elif request.method == "POST":
  36. # post通过request.form["param_name"]形式获取参数值
  37. post_q = request.form["q"]
  38. return render_template("result.html", result=post_q)
  39.  
  40. if __name__ == '__main__':
  41. # app.run(host, port, debug, options)
  42. # 默认值:host=127.0.0.1, port=5000, debug=false
  43. app.run()

3.3 查看运行效果

重新运行helloworld.py。

当前目录结构如下(.idea目录不用管):

Python3+Flask安装使用教程详解

get.html如下:

Python3+Flask安装使用教程详解

get查询结果如下:

Python3+Flask安装使用教程详解

post.html如下:

Python3+Flask安装使用教程详解

post查询结果如下:

Python3+Flask安装使用教程详解

四、restful

所谓restful简单理解就是以json等格式(而非以前的表单格式)发起请求,及以json等格式(而非以前的html)进行响应。

等下我们通过curl模拟rest请求,然后使用jsonify实现rest响应。

4.1 服务端实现代码

  1. # 导入Flask类
  2. from flask import Flask, jsonify
  3. from flask import render_template
  4. from flask import request
  5.  
  6. # 实例化,可视为固定格式
  7. app = Flask(__name__)
  8.  
  9. # route()方法用于设定路由;类似spring路由配置
  10. #等价于在方法后写:app.add_url_rule('/', 'helloworld', hello_world)
  11. @app.route('/helloworld')
  12. def hello_world():
  13. return 'Hello, World!'
  14.  
  15. # 配置路由,当请求get.html时交由get_html()处理
  16. @app.route('/get.html')
  17. def get_html():
  18. # 使用render_template()方法重定向到templates文件夹下查找get.html文件
  19. return render_template('get.html')
  20.  
  21. # 配置路由,当请求post.html时交由post_html()处理
  22. @app.route('/post.html')
  23. def post_html():
  24. # 使用render_template()方法重定向到templates文件夹下查找post.html文件
  25. return render_template('post.html')
  26.  
  27. # 配置路由,当请求deal_request时交由deal_request()处理
  28. # 默认处理get请求,我们通过methods参数指明也处理post请求
  29. # 当然还可以直接指定methods = ['POST']只处理post请求, 这样下面就不需要if了
  30. @app.route('/deal_request', methods=['GET', 'POST'])
  31. def deal_request():
  32. if request.method == "GET":
  33. # get通过request.args.get("param_name","")形式获取参数值
  34. get_q = request.args.get("q","")
  35. return render_template("result.html", result=get_q)
  36. elif request.method == "POST":
  37. # post通过request.form["param_name"]形式获取参数值
  38. post_q = request.form["q"]
  39. return render_template("result.html", result=post_q)
  40.  
  41. @app.route('/rest_test',methods=['POST'])
  42. def hello_world1():
  43. """
  44. 通过request.json以字典格式获取post的内容
  45. 通过jsonify实现返回json格式
  46. """
  47. post_param = request.json
  48. result_dict = {
  49. "result_code": 2000,
  50. "post_param": post_param
  51. }
  52. return jsonify(result_dict)
  53.  
  54. if __name__ == '__main__':
  55. # app.run(host, port, debug, options)
  56. # 默认值:host=127.0.0.1, port=5000, debug=false
  57. app.run()

4.2 请求模拟

  1. curl -H "Content-Type:application/json" -X POST --data '{"username": "ls","password":"toor"}' http://127.0.0.1:5000/rest_test

4.3 效果截图

Python3+Flask安装使用教程详解

五、Flask与Django比较

5.1 Django配置复杂

如果对Django不是很了解,可以参看

Python3+PyCharm+Django+Django REST framework开发教程详解

Python3+Django get/post请求实现教程详解

仅从文章长度看就比这篇长很多,所以Django比Flask复杂(得多)是肯定的。更具体比较如下:

比较项 Django Flask 复杂度比较 说明
项目创建 Django需要用命令创建项目 Flask直接编写文件就可运行 Django复杂 Django需要用命令创建项目是因为要创建出整个项目框架
路由 Django使用专门的urls.py文件 Flask直接使用@app.route() Django笨重 Django类似Strut2的配置Flask类似Spring的配置,Flask感觉更好
get和post request.GET['name']和request.POST["name"] request.args.get("name","")和request.form["q"] 差不多 Flask格式上不统一
restful 使用django-resful框架 使用jsonify 差不多 Flask不需要单建一个app,更直观一些
数据库操作 django集成了对数据库的操作 Flask没集成对数据库的操作要另行直连或使用sqlalchemy 差不多 django复杂很大程度来源于对数据库的集成。

5.2 Flask和Django各自适合使用场景

我们经常会听说这样的一个近乎共识的观点:Django是Python最流行的Web框架但配置比较复杂,Flask是一个轻量级的框架配置比较简单如果项目比较小推荐使用Flask。

进一步来说,Flask的轻量来源其“暂时不用的功能都先不做处理”,Django复杂来源于其“可能用到的功能都先集成”;随着项目规模的扩大最终Django有的东西Flask也都需要有。

所以,如果平时你用python是东用一个库西用一个库,东写一个场景西写一个场景,而不是专门开发web,那么你适合使用Flask,因为这样你的学习成本低及以前的知识都能用上去。

本文主要讲解了Python3+Flask安装使用教程如果想查看更多关于Python3+Flask的知识文章请点击下面相关文章

原文链接:https://www.cnblogs.com/lsdb/p/10488448.html

延伸 · 阅读

精彩推荐