【问题标题】:python: decorator with variable function namepython:具有可变函数名称的装饰器
【发布时间】:2020-01-22 19:20:17
【问题描述】:

我想动态选择装饰器下面的函数名称(在运行时):

@app.server.route('/downloadable/<path:path>')
def the_name_which_I_actually_would_like_to_set_dynamically(path):
    pass

更新:

这是一个更具体的代码示例。第一次调用create_endpoint 工作正常,但是第二次调用create_endpoint 时出错

import dash
from flask import Flask

server = Flask(__name__)
app = dash.Dash(server=server)
app.config['suppress_callback_exceptions']=True

def create_endpoint(function_name = "test_function_name"):
    @app.server.route('/downloadable/<path:path>')
    def test_function_name(path):
        pass

create_endpoint()
create_endpoint()

-->

AssertionError: View function mapping is overwriting an existing endpoint function: test_function_name

【问题讨论】:

  • 你能分享更多关于你如何使用它的细节吗?您是要更改函数对象的属性以进行检查,还是真的要分配一个不同的名称?如果您不知道这些函数的名称,您打算如何编写使用这些函数的代码?
  • 基于How do I create a variable number of variables?,您可能会发现将函数作为值放入字典并更改其键更容易。但这取决于您实际要完成的工作;这似乎是一个XY-problem
  • @PatrickHaugh:我添加了一个代码示例以使其更清晰
  • @wjandrea:抱歉,我不明白这如何帮助我解决问题
  • @PatrickHaugh:这个例子够清楚了吗?还是需要更多详细信息?

标签: python flask plotly-dash


【解决方案1】:

您可以直接使用add_url_rule。规则本身(url 模式)需要明确,以便服务器知道使用什么函数。

def test_function():
    pass

app.server.add_url_rule("/alpha", "alpha", test_function)
app.server.add_url_rule("/bravo", "bravo", test_function)

【讨论】:

  • 很好,谢谢。我想这是解决我的具体问题的最好方法。 +1
猜你喜欢
  • 1970-01-01
  • 2018-10-25
  • 2021-12-16
  • 2020-12-18
  • 2018-08-16
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
相关资源
最近更新 更多