如何从Flask中的另一个蓝图调用方法? [英] How to call a method from a different blueprint in Flask?

查看:314
本文介绍了如何从Flask中的另一个蓝图调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想调用一个通常会返回一个视图或者呈现一个模板的方法(一个路由),从在一个不同的蓝图的路线。



这怎么能正确地做?



谢谢。

解决方案

视图只是函数;导入该函数并直接调用它,传递它可能已经定义的任何路由参数。

蓝图的作用是使注册一组路由更容易在一个通用的前缀下,将他们的模板和静态资源进行分组,并为那个组处理与请求相关的事件(请求开始,请求完成等)。但是,如何调用视图不会改变。例如,如果在 foo 中有路由,蓝图,在 foo.py 模块中:

  @ foo.route ('/ bar /< id>)
def bar(id):
return something_done_with_id(id)

您可以导入该函数并在别处使用它:

  import foo 

@ baz.route('/ spam / ham / eggs'):
def baz():
return foo.bar(42)

这里 bar 从URL中取一个参数,名为 id ,所以当调用视图函数时,我们需要传入一个参数的值。

请注意任何蓝图 before_request after_request context_processor 函数不会执行(发生在路由时)是特定于Blueprint的错误处理程序。


I have an application with multiple blueprinted modules.

I would like to call a method (a route) that would normally return a view or render a template, from within a different blueprint's route.

How can this be done correctly?

Thank you.

解决方案

Views are just functions; import the function and call it directly, passing in any route parameters that it may have defined.

The role of the Blueprint is to make it easier to register a group of routes under a common prefix, group their templates and static resources, and handle request-related events for just that group (request started, request completed, etc.). But how you call a view doesn't change.

For example, if you have a route in the foo blueprint, in the foo.py module:

@foo.route('/bar/<id>')
def bar(id):
    return something_done_with_id(id)

you can import that function and use it elsewhere:

import foo

@baz.route('/spam/ham/eggs'):
def baz():
    return foo.bar(42)

Here bar takes a parameter from the URL, named id, so when calling the view function we do need to pass in a value for that parameter.

Do note that any blueprint before_request, after_request and context_processor functions are not executed (that happens at routing time), nor are Blueprint-specific error handlers in effect.

这篇关于如何从Flask中的另一个蓝图调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆