温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Flask框架中使用路由和视图

发布时间:2021-05-12 17:13:38 来源:亿速云 阅读:174 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关如何在Flask框架中使用路由和视图,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

创建一个简单flask框架程序

#1.导入Flask类
from flask import Flask
#2.创建Flask对象接收一个参数__name__,它会指向程序所在的包
app = Flask(__name__)
#3.装饰器的作用是将路由映射到视图函数index
@app.route('/')
def index():
  return 'Hello World'
#4.Flask应用程序实例的run方法,启动WEB服务器
if __name__ == '__main__':
  app.run()

1.Flask对象参数:

参数描述
name(必写)代表程序主函数__main__
static_folder静态资源文件夹(默认static)
static_url_path静态资源路径(默认/static)
template_folder模板文件夹(默认templates)

2.run方法参数:

参数描述
ipIP地址
port端口
debug默认为False,更改为True可以不重启服务器进行服务器修改(ctrl+s保存即可), 并且报错后会有相应提示

debug 默认为False,更改为True可以不重启服务器进行服务器修改(ctrl+s保存即可), 并且报错后会有相应提示

路由视图函数

@app.route("/路径"):路由装饰器,可以通过路径执行被装饰的函数
app.url_map:可查看当前路由函数和路径

1.动态参数:@app.route("/路径/<类型:变量>")

常用类型

类型描述
int整型
float浮点型
path字符串型

自定义类型:

(1)编写⾃定义转换器类,继承BaseConverter
(2)编写init⽅法
(3)初始化⽗类,⼦类变量
(4)将⾃定义转换器添加到默认转换器列表中

例:

from flask import Flask
from werkzeug.routing import BaseConverter
#1.自定义类,继承自BaseConverter
class MyRegexConverter(BaseConverter):
  # 2.编写方法, init
  def __init__(self,map,regex):
    # 3.初始化, 父类, 子类变量
    super(MyRegexConverter, self).__init__(map)
    self.regex = regex
app = Flask(__name__)
# 4.将自定义转换器添加到,系统默认的转换列表中
app.url_map.converters["re"] = MyRegexConverter
print(app.url_map.converters)
# 接收三位整数
# 通过re调用的init方法, 参数1[默认]: app.url_map, 参数2: 自己定义的规则
@app.route('/<re("\d{3}"):number>')
def hello_world(number):
  return "the re number is %s"%number
# 接收四位整数
@app.route('/<re("\d{4}"):number>')
def get_four_number(number):
  return "the four number is %s"%number
# 接收手机号
@app.route('/<re("1[3456789]\d{9}"):mobile>')
def get_mobile_number(mobile):
  return "the mobile number is %s"%mobile
if __name__ == '__main__':
  app.run()

2.指定请求方式:

@app.route("/路径",methods=["⽅式1","方式2"])

方式:GET(默认),POST,PUT,DELETE

3.视图函数返回内容:

(1)直接返回响应体对象:

返回响应体、状态码、响应头

return "hello","666",{"name":"zhangsan"}

(2)手动创建响应体对象:

response = make_response("响应体")
response.status = "状态码 状态码描述"
response.headers = {响应头键值对}
(response.headers["Content-Type"] = "application/json")
return response

(3)返回json:

jsonify(dict)
jsonify(key=value,key2=value2)

(4)重定向:

重定向:redirect("路径")
反解析:url_for("函数",key=value)
二者配合使⽤可以传递参数

例:

"""
url_for, 反解析,根据视图函数名称找到,视图函数的路径地址,可以携带参数
格式: url_for('函数名',key=value), 返回的是一个地址(字符串)
"""""
from flask import Flask,url_for,redirect
app = Flask(__name__)
# 京东, 代号111
@app.route('/jingdong')
def jingdong():
  #print(url_for("taobao")) #/taobao
  # print(url_for("taobao",token=111)) #/taobao/111
  response = redirect(url_for("taobao",token=111))
  return response
#易迅, 代号222
@app.route('/yixun')
def yixun():
  response = redirect(url_for("taobao",token=222))
  return response
@app.route('/other')
def other():
  response = redirect(url_for("taobao",token=888))
  return response
# 淘宝
@app.route('/taobao/<int:token>')
def taobao(token):
  #判断哪个平台过来的用户
  if(token == 111):
    return "欢迎京东用户,光临淘宝,给你打9折"
  elif(token == 222):
    return "欢迎易迅用户,光临淘宝,给你打5折"
  else:
    return "其他用户"
if __name__ == '__main__':
  app.run()

4.异常处理:

(1)抛出异常(abort):

abort(code)

code为HTTP错误状态码

(2)异常捕获(errorhandler):

code为HTTP错误状态码
@app.errorhandler(code)
def fun():
…

参数加载方式

1.从类中加载:app.config.from_object()

例:

class Config(object):
  #调试模式
  DEBUG=True
app.config.from_object(Config)

2.从配置⽂件中加载:app.config.from_pyfile()

例:

app.config.from_pyfile("config.ini")

3.从环境变量加载(了解):

app.config.from_envvar()

上述就是小编为大家分享的如何在Flask框架中使用路由和视图了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI