测开之路三十一:Flask基础之请求与相应

from flask import request
request.path
request.method
request.form
request.args
request.values

一般用form获取post的参数,用args获取get的参数,如果不想区分get和post,则用value获取

创建路由

访问

控制台

flask路由默认只支持get请求,而浏览器默认发的是get请求,所以没问题,在没有声明请求方法的情况下,当发post请求时,就会报405 

 

在路由里面声明post请求,再访问

再看控制台

这个时候再用get请求,又报错

在路由里面把get也加上再访问

返回json字符串,如,把请求参数转json再返回

第一种方式,用python自带的json库

get

post

第二种方式,用flask里面的jsonify

 

get

post

使用get方法实现计算器,例如请求为http://localhost:8888/calculator?method=add&a=3&b=5则返回3+5=8,计算器支持四则运算:add\sub\mul\div

 

@app.route('/calculator')
def calculator():
data = request.values.to_dict()
mothod = data.get('method', 'add')
try:
a = float(data.get('a', 0))
b = float(data.get('b', 0))
if mothod == 'add':
return f'{a}+{b}={a+b}'
elif mothod == 'sub':
return f'{a}-{b}={a-b}'
elif mothod == 'mul':
return f'{a}*{b}={a*b}'
elif mothod == 'div':
return f'{a}/{b}={a/b}'
else:
return '不支持的运算'
except Exception as erro:
return str(erro)

 

猜你喜欢

转载自www.cnblogs.com/zhongyehai/p/10828854.html