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

yipeiwu_com7年前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中Iterator迭代器的使用杂谈

迭代器是一种支持next()操作的对象。它包含一组元素,当执行next()操作时,返回其中一个元素;当所有元素都被返回后,生成一个StopIteration异常。 >>&...

python中set常用操作汇总

sets 支持 x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, sli...

python模拟enum枚举类型的方法小结

本文实例总结了python模拟enum枚举类型的方法。分享给大家供大家参考。具体分析如下: python中没有enum枚举类型,可能python认为这玩意压根就没用,下面列举了三种方法模...

使用python遍历指定城市的一周气温

处于兴趣,写了一个遍历指定城市五天内的天气预报,并转为华氏度显示。 把城市名字写到一个列表里这样可以方便的添加城市。并附有详细注释 import requests import js...

Python3实现腾讯云OCR识别

Python3实现腾讯云OCR识别

废话不多说,在网上找了下腾讯云OCR识别的,示例不多,用Python的还是Python2.7,花了点时间改成Python3的。 先上图,腾讯自己的示例图: 下面是代码: imp...