博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第一个Flask程序
阅读量:1973 次
发布时间:2019-04-27

本文共 5204 字,大约阅读时间需要 17 分钟。

本文将简要的介绍Flask的各部分作用,并编写并运行第一个最简单的Flask程序。

1. 初始化

所有Flask程序都必须创建一个程序实例。Web服务器使用一种名为Web服务器网关接口(Web Server Gateway Interface,WSGI)的协议,把接收自客户端的所有请求都转交给这个对象处理。程序实例是Flask类的对象,经常使用如下代码创建:

from flask import Flaskapp = Flask(__name__)
当然在使用Flask之前要安装flask

>yum -y install python-pip

>pip install flask

Flask类的构造函数只有一个必须指定的参数,即程序主模块或包的名字。在大多数程序中,Python的__name__变量就是所需要的值,这个变量决定程序的根目录,以便稍后能够找到相对于程序根目录的资源文件位置。

2.路由和视图函数

客户端(例如Web浏览器)把请求发送给Web服务器,Web服务器再把请求发送给Flask程序实例。程序实例需要知道对每个URL请求运行哪些代码,所以保存了一个URL到Python函数的映射关系。处理URL和函数之间关系的程序称之为路由(router)

在Flask程序中定义路由的最简便方式,是使用程序实例提供的app.route修饰器,把修饰的函数注册为路由。下面的例子说明了如何使用这个修饰器声明路由:

@app.route('/')def index():    return '

Hello World!

'
index()函数注册为程序根地址的处理程序。如果部署程序的服务器域名为www.example.com,在浏览器中访问http://www.example.com/后,会触发服务器执行index()函数。这个函数的返回值称为响应,在客户端接收到的内容。如果客户端是Web浏览器,响应就是显示给用户查看的文档。

视图函数:像index()这样的函数称为视图函数。视图函数返回的响应可以是包含HTML的简单字符串,也可以是复杂的表单。

对于http://www.example.com/{username}这样的URL,只需要在route修饰器中使用特殊的句法即可,例如:

@app.route('/
')def usr(username): return '

Hello,%s!

' % username
尖括号中的内容就是动态部分,任何能匹配静态部分的URL都会映射到这个路由上。调用视图函数时,Flask会将冬天部分作为参数传入函数。

路由中的动态部分默认使用字符串,不过也可使用类型定义。例如,路由/user/<int:id>只会匹配动态片段id为整数的URL。Flask支持在路由中使用int,float和path类型。path类型也是字符串,但不把斜线视作分隔符,而将其作为冬天片段的一部分。

3.启动服务器

程序实例用run方法启动Flask集成的开发Web服务器:

Hello.py:

#!/usr/bin/pythonimport osimport sysimport logging.configimport flaskimport socketfrom flask import Flask,jsonifyfrom flask import requestfrom flask import abortfrom flask import make_responseapp = Flask(__name__)@app.route('/')def index():    return '

Hello World!

'@app.route('/
')def usr(username): return '

Hello,%s!

' % username if __name__ == "__main__": hostname = socket.gethostname() ip = socket.gethostbyname( hostname ) app.run( host=ip,port=5000,debug=False )
在这里只要直接执行程序就会启动Web服务器。服务器启动后,会进入轮询,等待并处理请求。轮询会一直运行,直到程序停止,比如按Ctril-C键。

有一些选项参数可被app.run()函数接受用于设置Web服务器的操作模式。在开发过程中启用调试模式会带来一些便利,比如说激活调试器和重载程序。要想采用调试模式,可以把app.run的debug参数设置为True。

启动服务器:

在浏览器中输入:http://10.15.230.29:5000 或者命令行输入:curl -X GET http://10.15.230.29:5000

在浏览器中输入:http://10.15.230.29:5000/wahaha 命令行输入:curl -X GET http://10.15.230.29:5000/wahaha

在浏览器中输入:http://10.15.230.29:5000/name/age

当输入了以上地址,程序不知道如何吹了,因此会向浏览器返回错误代码404(Not Found)。

4.响应

make_response:Flask视图函数还可以返回Response对象。make_response()函数可接收1个,2个,3个参数(和视图函数的返回值一样),并返回一个Response对象。

abort:用于返回错误,参数是状态码。

jsonify:按照json的方式返回值。

下面再看一下一段示例代码:

#!/usr/bin/pythonimport socket import osimport sys from flask import Flask,jsonifyfrom flask import requestfrom flask import abortfrom flask import make_response                                                                                                                                                              app = Flask(__name__)tasks = [     {           'id':1,        'title':u'Buy groceries',        'description':u'Milk,Cheese, Pizza,Fuilt , Tylenol',        'done':False    },      {           'id':2,        'title':u'Learn Python',        'description':u'Need to find a good Python tutorial on the web',        'done':False    }   ]@app.route('/')def get():    return 'hello world\n'@app.route('/todo/api/v1/tasks',methods=['GET'])def get_tasks():    return jsonify({'tasks':tasks})@app.route('/todo/api/v1/tasks/haha',methods=['GET','POST'])def get_task_by_id():    return make_response(jsonify({'tasks':tasks[int(request.json.get('id',""))-1]}),200)if __name__ == '__main__':    hostname = socket.gethostname()    ip = socket.gethostbyname( hostname )    app.run(debug=False,host=ip,port=5000)
首先调用第一个API:'/todo/api/v1/tasks'来获取所有task:

>curl -X GET http://localhost:5000/todo/api/v1/tasks

再调用第二个API:'/todo/api/v1/tasks/haha',获取id=2的信息,有三种请求方式:

>curl -X GET -H "Content-Type: application/json"   -d '{"id":"2"}'

注:return make_response(jsonify({'tasks':tasks[int(request.json.get('id',""))-1]}),200)

>curl -X GET  -d "id=2"    

>curl -X GET  

注:return make_response(jsonify({'tasks':tasks[int(request.args['id']-1]}),200)

或者return make_response(jsonify({'tasks':tasks[int(request.values['id']-1]}),200)

request.data:contains the incoming request data as string in case it came with a minetype Flask does not handle
request.args:if you want the parameters in the URL
request.form:if you want the information in the body(as sent by a html POST form)
request.values:if you want both

app.run的参数为:

host:server host

port:server port

use_debugger:flag whether to default to using the Werkzeug debugger. This can be overriden in the command line by passing the -d or -D flag.Default to False,for security.

use_reloader:flag whether to use the auto-reloader.Default to True when debugging. This can be overriden in the command line by passing the -r/-R flag.

threaded:should the process handle each request in a seperate thread?

processes:number of processes to spawn

passthrough_errors:disable the error catching.This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc)

ssl_crt : path to ssl certificate file

ssl_key : path to ssl key file

Author:忆之独秀

Email:leaguenew@qq.com

注明出处:

你可能感兴趣的文章
Python手动读取CIFAR-10数据集
查看>>
Pytorch(十一) —— 分布式(多GPU)训练
查看>>
Deeplab v3
查看>>
Pytorch之经典神经网络语义分割(3.2) —— ASPP 空洞空间金字塔池化(atrous spatial pyramid pooling )
查看>>
NLP 之 Perplexity困惑度
查看>>
tensor/矩阵/图片等更换通道,调整size
查看>>
本地和colab 中 改变tensorflow的版本
查看>>
Camera-ready ddl
查看>>
CUB-200鸟类数据集
查看>>
Python反射机制
查看>>
YAPF —— Python代码格式化工具
查看>>
UGC 用户产生内容
查看>>
ranger
查看>>
slurm
查看>>
xfce4
查看>>
xrdp
查看>>
Raft算法
查看>>
Python计算文本BLEU分数
查看>>
swap内存(linux)
查看>>
torch.distributed 分布式
查看>>