flask框架路由常用定义方式总结

yipeiwu_com6年前Python基础

本文实例讲述了flask框架路由常用定义方式。分享给大家供大家参考,具体如下:

路由的各种定义方式

请求方式限定

使用 methods 参数指定可接受的请求方式,可以是多种

@app.route('/',methods=['GET'])
def hello():
  return '<h1>hello world</h1>'

路由查找方式

同一路由指向两个不同的函数,在匹配过程中,至上而下依次匹配

@app.route('/')
def hello():
  return '<h1>hello world</h1>'
@app.route('/')
def hello_2017():
  return '<h1>hello 2017</h1>'

所以上面路由 / 输出的结果为 hello 函数的结果

给路由传参示例

有时我们需要将同一类URL映射到同一个视图函数处理,比如:使用同一个视图函数 来显示不同用户的个人信息。

路由传递的参数默认当做string处理,这里指定int,尖括号中的内容是动态的,也可不指定类型

@app.route('/user/<int:id>')
def hello_itheima(id):
  return 'hello itcast %d' %id

重定向redirect示例

from flask import redirect
@app.route('/')
def hello_itheima():
  return redirect('http://www.itcast.cn')

返回JSON

from flask import Flask,json
@app.route('/json')
def do_json():
  hello = {"name":"stranger", "say":"hello"}
  return json.dumps(hello)

返回状态码示例

在 Python 中返回状态码有两种方式实现:

- 直接return 
    - 可以自定义返回状态码,可以实现不符合http协议的状态码,例如:error=666,errmsg='查询数据库异常',其作用是为了实现前后端数据交互的方便
- abort方法
    - 只会抛出符合http协议的异常状态码,用于手动抛出异常

@app.route('/')
def hello_itheima():
  return 'hello itcast',666

正则路由示例

在web开发中,可能会出现限制用户访问规则的场景,那么这个时候就需要用到正则匹配,限制访问,优化访问

导入转换器包

from werkzeug.routing import BaseConverter

自定义转换器并实现

# 自定义转换器
class Regex_url(BaseConverter):
  def __init__(self,url_map,*args):
    super(Regex_url,self).__init__(url_map)
    self.regex = args[0]
app = Flask(__name__)
# 将自定义转换器类添加到转换器字典中
app.url_map.converters['re'] = Regex_url
@app.route('/user/<re("[a-z]{3}"):id>')
def hello_itheima(id):
  return 'hello %s' %id

自带几种转换器

DEFAULT_CONVERTERS = {
  'default':     UnicodeConverter,
  'string':      UnicodeConverter,
  'any':       AnyConverter,
  'path':       PathConverter,
  'int':       IntegerConverter,
  'float':      FloatConverter,
  'uuid':       UUIDConverter,
}

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

相关文章

详解python:time模块用法

详解python:time模块用法

time模块下有两种时间表示方法: 第1种是:时间戳的方式。是基于1970年1月1日0时0分0秒的偏移。浮点数。 第2种是:struct_time()类型的表示方法。gmtime()和l...

python json.loads兼容单引号数据的方法

Python的json模块解析单引号数据会报错,示例如下 >>> import json >>> data = "{'field1': 0, 'f...

Python制作Windows系统服务

最近有个Python程序需要安装并作为Windows系统服务来运行,过程中碰到一些坑,整理了一下。 Python服务类 首先Python程序需要调用一些Windows系统API才能作为系...

基于OpenCV python3实现证件照换背景的方法

基于OpenCV python3实现证件照换背景的方法

简述 生活中经常要用到各种要求的证件照电子版,红底,蓝底,白底等,大部分情况我们只有其中一种,所以通过技术手段进行合成,用ps处理证件照,由于技术不到位,有瑕疵,所以想用python&o...

numpy:找到指定元素的索引示例

目的:在numpy数组中知道指定元素的索引 函数: np.argwhere >>>x >>>array([[0, 1, 2], [3, 4,...