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中使用HTMLParser解析HTML的教程

如果我们要编写一个搜索引擎,第一步是用爬虫把目标网站的页面抓下来,第二步就是解析该HTML页面,看看里面的内容到底是新闻、图片还是视频。 假设第一步已经完成了,第二步应该如何解析HTML...

Python 实现大整数乘法算法的示例代码

我们平时接触的长乘法,按位相乘,是一种时间复杂度为 O(n ^ 2) 的算法。今天,我们来介绍一种时间复杂度为 O (n ^ log 3) 的大整数乘法(log 表示以 2 为底的对数)...

对python使用telnet实现弱密码登录的方法详解

系统环境: 64位win7企业版 python2.7.10 2016.08.16修改内容: 1)read_until()函数是可以设置timeout的,之前不能获取到password之后...

Python中map,reduce,filter和sorted函数的使用方法

map map(funcname, list) python的map 函数使得函数能直接以list的每个元素作为参数传递到funcname中, 并返回响应的新的list 如下:...

解决谷歌搜索技术文章时打不开网页问题的python脚本

注意:Win7或者WIn8用户要用管理员权限执行。 项目地址:http://code.google.com/p/my-hosts-file/downloads复制代码 代码如下:impo...