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使用xlrd模块读写Excel文件的方法

本文实例讲述了python使用xlrd模块读写Excel文件的方法。分享给大家供大家参考。具体如下: 一、安装xlrd模块 到python官网下载http://pypi.python....

python实现AES加密与解密

AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windo...

python变量的存储原理详解

python变量的存储原理详解

变量的存储 在高级语言中,变量是对内存及其地址的抽象。 对于python而言,python的一切变量都是对象,变量的存储,采用了引用语义的方式,存储的只是一个变量的值所在的内存地址,而...

pycharm 使用心得(三)Hello world!

pycharm 使用心得(三)Hello world!

1,新建一个项目 File --> New Project... 2,新建一个文件右键单击刚建好的helloWord项目,选择New --> Python File 3,...

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

一、现象 最近在数据库中删除了一张表,重新执行python manage.py migrate时出错,提示不存在这张表。通过查找相关的资料,最后找到了相关的解决方法,下面话不多说了,来一...