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中如何使用分步式进程计算详解

python中如何使用分步式进程计算详解

前言 在python中使用多进程和多线程都能达到同时运行多个任务,和多进程和多线程的选择上,应该优先选择多进程的方式,因为多进程更加稳定,且对于进程的操作管理也更加方便,但有一点是多进程...

Python2.x利用commands模块执行Linux shell命令

用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands...

Form表单及django的form表单的补充

Form表单及django的form表单的补充

form 表单中的button按钮 <button>提交</button> :放在form表单中,会有一个提交事件,会提交form数据, <input ty...

python调用shell的方法

1.1  os.system(command)在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system(...

python 创建一个保留重复值的列表的补码

给定列表a = [1,2,2,3],其子列表b = [1,2]以这样一种排序(a)==排序(b补码)的方式找到一个补全b的列表.在上面的例子中,补码将是[2,3]的列表. 使用列表解析是...