Python3+Flask安装使用教程

一、环境配置

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

pip install Flask

二、第一个应用程序

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

# 导入Flask类
from flask import Flask
# 实例化,可视为固定格式
app = Flask(__name__)

# route()方法用于设定路由;类似spring路由配置
@app.route(‘/‘)
def hello_world():
    return ‘Hello, World!‘

if __name__ == ‘__main__‘:
    # app.run(host, port, debug, options)
    # 默认值:host=127.0.0.1, port=5000, debug=false
    app.run()

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

三、get和post实现

3.1 创建用到的模板文件

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

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get请求示例</title>
</head>
<body>
    <form action="/deal_request" method="get">
        <input type="text" name="q" />
        <input type="submit" value="搜索" />
    </form>
</body>
</html>

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>post请求示例</title>
</head>
<body>
    <form action="/deal_request" method="post">
        <input type="text" name="q" />
        <input type="submit" value="搜索" />
    </form>
</body>
</html>

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

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

3.2 编写相关的处理方法

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

# 导入Flask类
from flask import Flask
from flask import render_template
from flask import request
# 实例化,可视为固定格式
app = Flask(__name__)

# route()方法用于设定路由;类似spring路由配置
#等价于在方法后写:app.add_url_rule(‘/‘, ‘helloworld‘, hello_world)
@app.route(‘/helloworld‘)
def hello_world():
    return ‘Hello, World!‘

# 配置路由,当请求get.html时交由get_html()处理
@app.route(‘/get.html‘)
def get_html():
    # 使用render_template()方法重定向到templates文件夹下查找get.html文件
    return render_template(‘get.html‘)

# 配置路由,当请求post.html时交由post_html()处理
@app.route(‘/post.html‘)
def post_html():
    # 使用render_template()方法重定向到templates文件夹下查找post.html文件
    return render_template(‘post.html‘)

# 配置路由,当请求deal_request时交由deal_request()处理
# 默认处理get请求,我们通过methods参数指明也处理post请求
# 当然还可以直接指定methods = [‘POST‘]只处理post请求, 这样下面就不需要if了
@app.route(‘/deal_request‘, methods = [‘GET‘, ‘POST‘])
def deal_request():
    if request.method == "GET":
        # get通过request.args.get("param_name","")形式获取参数值
        get_q = request.args.get("q","")
        return render_template("result.html", result=get_q)
    elif request.method == "POST":
        # post通过request.form["param_name"]形式获取参数值
        post_q = request.form["q"]
        return render_template("result.html", result=post_q)

if __name__ == ‘__main__‘:
    # app.run(host, port, debug, options)
    # 默认值:host=127.0.0.1, port=5000, debug=false
    app.run()

3.3 查看运行效果

重新运行helloworld.py。

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

get.html如下:

get查询结果如下:

post.html如下:

post查询结果如下:

四、restful

4.1 安装flask-restful

restful我这里通过Flask-RESTful实现。

pip install flask-restful

4.2 实现rest代码

修改helloworld.py,添加三处,具体见注释

# 导入Flask类
from flask import Flask
from flask import render_template
from flask import request
# 添加位置一。从Flask-RESTful中导入以下三项
from flask_restful import Api
from flask_restful import Resource
from flask_restful import reqparse

# 实例化,可视为固定格式
app = Flask(__name__)
# 添加位置二。
# 实例化一个api用于配置rest路由
# 实例化一个参数解析类,用于rest获取get和post提交的参数
api = Api(app)
parser = reqparse.RequestParser()
# 注册q参数parser才能解析get和post中的q参数。这种注册才能解析的要求是否有点孤儿
parser.add_argument(‘q‘, type=str, help=‘Rate to charge for this resource‘)

# route()方法用于设定路由;类似spring路由配置
#等价于在方法后写:app.add_url_rule(‘/‘, ‘helloworld‘, hello_world)
@app.route(‘/helloworld‘)
def hello_world():
    return ‘Hello, World!‘

# 配置路由,当请求get.html时交由get_html()处理
@app.route(‘/get.html‘)
def get_html():
    # 使用render_template()方法重定向到templates文件夹下查找get.html文件
    return render_template(‘get.html‘)

# 配置路由,当请求post.html时交由post_html()处理
@app.route(‘/post.html‘)
def post_html():
    # 使用render_template()方法重定向到templates文件夹下查找post.html文件
    return render_template(‘post.html‘)

# 配置路由,当请求deal_request时交由deal_request()处理
# 默认处理get请求,我们通过methods参数指明也处理post请求
# 当然还可以直接指定methods = [‘POST‘]只处理post请求, 这样下面就不需要if了
@app.route(‘/deal_request‘, methods = [‘GET‘, ‘POST‘])
def deal_request():
    if request.method == "GET":
        # get通过request.args.get("param_name","")形式获取参数值
        get_q = request.args.get("q","")
        return render_template("result.html", result=get_q)
    elif request.method == "POST":
        # post通过request.form["param_name"]形式获取参数值
        post_q = request.form["q"]
        return render_template("result.html", result=post_q)

# 添加位置三。
# 添加rest类(是类而不是和Flask一样直接是方法)
class Rest(Resource):
    # get提交时的处理方法
    def get(self):
        result = {}
        args = parser.parse_args()
        result["method"] = "get"
        result["q"] = args["q"]
        return result
    # post提交时的处理方法
    def post(self):
        result = {}
        args = parser.parse_args()
        result["method"] = "post"
        result["q"] = args["q"]
        return result
# 配置路由
api.add_resource(Rest, ‘/rest‘)

if __name__ == ‘__main__‘:
    # app.run(host, port, debug, options)
    # 默认值:host=127.0.0.1, port=5000, debug=false
    app.run()

4.3 查看运行结果

即然是restful我们也就不写html了,直接用curl模拟提交。重新运行helloworld.py,请求如下图(之前非rest的get和post当然也还能正常访问):

五、Flask与Django比较

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

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框架 使用flask-restful框架 差不多 Flask使用方法flask-rest使用类格式不统一;flask-restful需要注册参数有点孤儿
数据库操作 django集成了对数据库的操作 Flask没集成对数据库的操作要另行直连或使用sqlalchemy 差不多 django复杂很大程度来源于对数据库的集成。

5.2 Flask适合使用场景

Django复杂来源于其“可能用到的功能都先集成”,Flask的轻量来源其“暂时不用的功能都先不做处理”。随着项目规模的扩大最终Django有的东西Flask也都需要有,而且由于没做统一规划Flask将处于劣势位置。

个人认为Flask适用以下两个场景:

一是开发者没有Spring等企业级框架开发经验,不然Django很多项为什么要配置为什么这样配置不那样配置比较难理解。

二是项目大概是十来个页面、就只有两三张数据表甚至不用数据库的规模,在这种程度下减少的配置工作还算能抵得过增加的开发工作量。

如果之前用过Spring之类的框架写过代码的话个人还是推荐不管项目大小都直接用Django,主要是Flask不统一的格式让人很难受。

参考:

https://www.yiibai.com/flask

http://flask.pocoo.org/docs/1.0/quickstart/#

https://flask-restful.readthedocs.io/en/latest/

原文地址:https://www.cnblogs.com/lsdb/p/10488448.html

时间: 2024-08-04 08:52:49

Python3+Flask安装使用教程的相关文章

最新python3.6安装beatifulsoup教程

今天刚开始尝试了flask和django,我决定还是学习信息搜集 以下是我的beautifulsoup安装过程

Python3+mitmproxy安装使用教程(Windows)

一.安装 1.1 安装mitmproxy 直接使用pip安装即可 pip install mitmproxy pip本质上会一是安装mitmproxy库的相关代码,二是安装mitmproxy.exe/mitmdump.exe/mitmdump.exe三个可执行程序. 可执行程序被安装在$PYTHON_HOME/Scripts文件夹下,如果是conda版本的python那可以用以下命令来查看当前使用的是哪个环境. conda env list 1.2 安装证书 和burpsuite类似mitmpr

今天带来Pycharm安装详细教程

Python环境搭建-安利Python小白的Python和Pycharm安装详细教程 人生苦短,我用Python.众所周知,Python目前越来越火,学习Python的小伙伴也越来越多.最近看到群里的小伙伴经常碰到不会安装Python或者不知道去哪下载Python安装包等系列问题,为了方便大家学习Python,小编整理了一套Python和Pycharm安装详细教程,只要大家按照这个步骤来,就可以轻松的搞定Python和Pycharm的安装了. Python具有跨平台性,它几乎可以在任何平台下运行

Python、 Pycharm、Django安装详细教程(图文)

这篇文章主要介绍了Python. Pycharm.Django安装详细教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 最近做项目要用到python,那么不用说就得先配置好python环境 以及选择好python工具.接下来分享自己的安装过程. (一).Python的安装 1.先进入官网下载python版本,https://www.python.org/downloads/ 2.下载完成后双击.exe文件进行安装,可以自定

MapGIS6.7安装图文教程(完美破解)

mapgis安装比较简单,主要注意在安装的时候,先打开软件狗,然后再进行软件安装,一般就不会照成其他安装失败的现象,有时候安装之前没有打开软件狗也安装成功了,也有这情况,不过软件使用也需要软件狗的支持!MapGIS6.7安装图文教程(完美破解)工具/原料 MapGIS6.7安装包和软件狗 电脑(现在的电脑配置都可以安装) 方法/步骤 1 打开软件狗,注意防火墙,可能会阻止打开 MapGIS6.7安装图文教程(完美破解) 2 点击SETUP67.EXE,如图,进行mapgis安装 MapGIS6.

[分享]Ubuntu12.04安装基础教程(图文)

原文地址: http://teliute.org/linux/Ubsetup/lesson21/lesson21.html 1.进入 live cd 桌面 1)设置好启动后,断开网络,然后重新启动动计算机,能够用硬盘启动,也能够刻成光盘启动,镜像的下载地址: 进入后找蓝色链接点击下载,如 ubuntu-12.04-desktop-i386.iso,64位CPU能够下载amd64的版本号:http://mirrors.sohu.com/ubuntu-releases/12.04/ WinXP硬盘安

安卓模拟器BlueStacks 安装使用教程(图解)

系统要求 操作系统 Win XP SP3/Vista/Win 7/Win 8/Win 8.1 所需的运行环境 Win XP用户请先升级到SP3 并安装Windows Installer 4.5 Win XP用户需先安装.NET Framework 2.0 SP2或.NET Framework 4.0 硬件要求 最低配置:2GB内存,支持OpenGL 2.0以上的显卡,分辨率大于1024X768 安装教程 下载安卓模拟器并解压,得到模拟器安装包并开始安装. BlueStacks不能设置安装路径,但

Windows7 Python-3.6 安装PyCrypto(pycrypto 2.6.1)出现错误以及解决方法

今天准备在Windows系统上基于python3.6安装一个pycrypto 2.6.1模块,很不幸的报了一堆错误,如下所示: running install running build running build_py running build_ext warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. building 'Crypto.Random.OSRNG.winrandom'

在 Windows 上安装 Hadoop 教程(转)

在 Windows 上安装 Hadoop 教程 一见 2010.1.6 www.hadoopor.com/[email protected] 1. 安装 JDK 不建议只安装 JRE,而是建议直接安装 JDK,因为安装 JDK 时,可以同时安装 JRE. MapReduce 程序的编写和 Hadoop 的编译都依赖于 JDK,光 JRE 是不够的. JRE 下载地址:http://www.java.com/zh_CN/download/manual.jsp JDK 下载地址:http://jav