使Flask的url支持正则表达式以及一个api小demo


from flask import Flask
from flask import jsonify
from flask import request
from werkzeug.routing import BaseConverter
app = Flask(__name__)


#重新定义url匹配规则
class RegexConverter(BaseConverter): def __init__(self, url, *args): self.url = url self.regex = args[0] app.url_map.converters['regex'] = RegexConverter #请求地址映射 @app.route('/index',methods=['POST']) def test_post(): #定义响应结果集 resultMap = {} #获取post请求参数 a = request.json['a'] b = request.json['b'] #如果参数必填就要加上 if a and b: if a == b: resultMap['ret_code'] = 200 resultMap['ret_info'] = '成功' #返回json格式的 return jsonify(resultMap) else: resultMap['ret_code'] = 500 resultMap['ret_info'] = '失败' return jsonify(resultMap) else: resultMap['ret_code'] = 500 resultMap['ret_info'] = '缺少请求参数' return jsonify(resultMap)

#万能url可以接收所有进入这个服务的请求 @app.route(
'/<regex(r"[\w\W]*"):url>',methods=['GET']) def test_get(url): resultMap = {} c = request.args.get('c') d = request.args.get('d') if c and d: if c != d: resultMap['ret_code'] = 200 resultMap['ret_info'] = 'c和d不相等哟' return jsonify(resultMap) else: resultMap['ret_code'] = 500 resultMap['ret_info'] = 'c和d相等啦啦啦啦啦' return jsonify(resultMap) else: resultMap['ret_code'] = 500 resultMap['ret_info'] = '缺少请求参数' return jsonify(resultMap) if __name__ == '__main__': app.run(debug=True,port=505)

 

 

 

  

posted @ 2017-12-19 14:47  luckylemon  阅读(2065)  评论(1编辑  收藏  举报