get/post与测试

get请求,蓝图文件:

  1. from flask import Blueprint,request
  2. index_page = Blueprint("index_page",__name__)
  3. @index_page.route('/')
  4. def index():
  5. return "index page"
  6. @index_page.route('/me')
  7. def hello():
  8. return "hello, this is me"
  9. @index_page.route('/get')
  10. def get():
  11. var_a = request.args.get('a','Welcom')
  12. return 'request:%sparams:%s,var_a:%s'%(request.method,request.args,var_a)

访问127.0.0.1/learning/get?a=Tom时 ,浏览器的显示:
请求测试 - 图1

post请求:

from flask import Blueprint,request


index_page = Blueprint("index_page",__name__)

@index_page.route('/')
def index():
    return "index page"


@index_page.route('/me')
def hello():
    return "hello, this is me"

@index_page.route('/get')
def get():
    var_a = request.args.get('a','Welcom')
    return 'request:%sparams:%s,var_a:%s'%(request.method,request.args,var_a)


@index_page.route('/post',methods=['POST'])
def post():
    var_b = request.values['b'] if 'b' in request.values else 'welcome'
    return 'request: %s; params: %s; var_b: %s;%s'%(request.method,request.args,var_b,request.values)

如何既取到post的form的值,又能取到get的args的值:request.values【源码中values封装了两个变量的值,类型是CombinedMultiDict】不过不知道是不是升级了,我这里看的时候,from已经是空的了,从request.args中也能取到post的值。

返回结果:
请求测试 - 图2

使用post方法获取文件上传:
enctype = “multiport/form-data”

from flask import Blueprint,request


index_page = Blueprint("index_page",__name__)

@index_page.route('/')
def index():
    return "index page"


@index_page.route('/me')
def hello():
    return "hello, this is me"

@index_page.route('/get')
def get():
    var_a = request.args.get('a','Welcom')
    return 'request:%sparams:%s,var_a:%s'%(request.method,request.args,var_a)


@index_page.route('/post',methods=['POST'])
def post():
    var_b = request.values['b'] if 'b' in request.values else 'welcome'
    return 'request: %s; params: %s; var_b: %s;%s'%(request.method,request.args,var_b,request.values)



@index_page.route('/upload',methods=['POST'])
def upload():
    var_c = request.files['file'] if 'file' in request.files else None
    return 'request: %s; params: %s; var_c: %s; values:%s'%(request.method,request.files,var_c,request.values)

请求测试 - 图3

请求测试 - 图4

测试

post工具:curl,postman

curl

get:
curl "http://127.0.0.1:5000/learning/get?a=Tom"

post:
curl "http://127.0.0.1:5000/learning/post" -X POST -d "b=Jerry"
-X表示方法,-d表示参数

postman

也可以通过postman的功能展示curl的写法:
请求测试 - 图5

请求测试 - 图6