Flask是一个用Python编写的Web应用程序框架,Flask基于Werkzeug WSGI工具包和Jinja2模板引擎
一个最简单的 Flask 应用
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run(host='172.18.109.240')
Flask类的route()函数是一个装饰器,它告诉应用程序哪个URL应该调用相关的函数
app.route(rule, options)
rule 参数表示与该函数的URL绑定。
options 是要转发给基础Rule对象的参数列表
在上面的示例中,'/ ' URL与hello_world()函数绑定。因此,当在浏览器中打开web服务器的主页时,将呈现该函数的输出
app.run(host, port, debug, options) :Flask类的run()方法在本地开发服务器上运行应用程序
host要监听的主机名。 默认为127.0.0.1(localhost)。设置为“0.0.0.0”以使服务器在外部可用
port默认值为5000
debug 默认为false。 如果设置为true,则提供调试信息
options 要转发到底层的Werkzeug服务器。
Flask 路由:将从客户端发送过来的请求发到指定函数上
@app.route(‘/hhh’)
def hello_world():
return ‘hello world’
在这里,URL ‘/ hhh’ 规则绑定到hello_world()函数。 因此,如果用户访问http:// localhost:5000/hhh 的URL时,hello_world()函数的输出将在浏览器中呈现。
Flask HTTP方法
协议中定义了从指定URL检索数据的不同方法
GET以未加密的形式将数据发送到服务器。最常见的方法。
HEAD 和GET方法相同,但没有响应体。
POST 用于将HTML表单数据发送到服务器。POST方法接收的数据不由服务器缓存
PUT 用上传的内容替换目标资源的所有当前表示
DELETE 删除由URL给出的目标资源的所有当前表示
默认情况下,Flask路由响应GET请求。但是,可以通过为route()装饰器传递 methods 参数来更改此首选项
@app.route('/hhh',methods=['GET','PSOT'])
Flask Request对象
服务器在接受到客户端的请求后,会自动创建Request对象,有Flask框架创建,Request对象不可修改,对于 web 应用来说对客户端向服务器发送的数据作出响应很重要。在 Flask 中由全局 对象 request 来提供请求信息
导入模块request
from flask import request
Request对象的重要属性如下所列:
GET
from flask import request
app = Flask(__name__)
@app.route('/hhh',methods=['GET'])
def hello_world():
print(request.args)
return 'Hello World'
if __name__ == '__main__':
app.run(host='172.18.109.240')
运行python文件返回
ImmutableMultiDict([('username', "'bhs'")])
120.244.154.84 - - [12/Jun/2020 15:16:21] "GET /hhh?username=%27bhs%27 HTTP/1.1" 200 -
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/hhh',methods=['GET'])
def hello_world():
print(request.args['username'])
return 'Hello World'
if __name__ == '__main__':
app.run(host='172.18.109.240')
返回结果
'bhs'
120.244.154.84 - - [12/Jun/2020 15:19:03] "GET /hhh?username=%27bhs%27 HTTP/1.1" 200 -
POST
客户端
[root@bhs ~]# more bhs.py
#encoding=utf-8
import requests
url = "http://127.0.0.1:5000/hhh"
data = {"text1":"hello", "text2": "world"}
res = requests.post(url, data=data)
print(res.text)
运行结果
[root@bhs ~]# python bhs.py
返回给访问客户端数据
服务端
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/hhh',methods=['POST'])
def hello_world():
ttt1=request.form["text1"]
print("文本数据1",ttt1)
ttt2=request.form["text2"]
print("文本数据2",ttt2)
return "返回给访问客户端数据"
if __name__ == '__main__':
app.run()
返回:
文本数据1 hello
文本数据2 world
127.0.0.1 - - [12/Jun/2020 15:50:58] "POST /hhh HTTP/1.1" 200 -
GET 和 POST 的区别
GET请求 的参数会设置在 URL的查询字符串部分。
POST请求 的参数 会设置在 请求的请求体中。
GET比POST更不安全,因为参数直接暴露在URL上,所以不能用来传递敏感信息。