简体   繁体   English

将参数传递给python decorator

[英]passing parameters to python decorator

I am using uwsgi decorators(specifically the cron decorator) to do things at specific times. 我正在使用uwsgi装饰器(特别是cron装饰器)在特定时间做事情。 I have the following code: 我有以下代码:

import cherrypy
import uwsgidecorators

class TestObject(object):
    @cherrypy.expose
    def index(self):
        launchapp = self.launchapp(-1,-1,-1,-1,-1,"foobar")
        return "This is a test"

    @uwsgidecorators.cron(minute,hour,day,month,dayweek)
    def launchapp(self,target):
        print "the target is %s" %target
        return

However I get the error: 但是我得到错误:

    @uwsgidecorators.cron(minute,hour,day,month,dayweek)
NameError: name 'minute' is not defined

I am basically trying to specify the timing parameters for the cron decorator in the index function. 我基本上试图在索引函数中指定cron修饰符的时序参数。 Anyone know what I am doing wrong? 谁知道我做错了什么?

Why your code fails 你的代码失败的原因

The error has nothing to do with the fact that you're passing parameters, it's just that the minute variable is undefined. 该错误与您传递参数的事实无关,它只是未定义的minute变量。

You would get the exact same error doing: 你会得到完全相同的错误:

>>> a = 'a'
>>> print b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> 

What you probably want to do is: 你可能想做的是:

@uwsgidecorators.cron(minute = 5,hour = 2, # and so on.

Please have a look at the uwsgi documentation for a more comprehensive example. 有关更全面的示例,请查看uwsgi文档


-- EDIT below. - 编辑下面。

How you could fix it 你怎么解决它

It seems that you're trying to add a task to your crontab after index is hit. 看起来你试图在命中索引后向你的crontab添加一个任务。

That's not the use case for the decorator, the decorator is only meant to say that a function should run on a cron at function definition . 这不是装饰器的用例,装饰器只是说函数应该在函数定义的cron 上运行 Basically, when the decorator is executed (and the function defined , not called ), it gets added to the crontab. 基本上,当执行装饰器(并且定义了函数,未调用 )时,它会被添加到crontab中。

In your case, you want to add a function to the crontab; 在您的情况下,您想要向crontab添加一个函数; so you should use something like uwsgi.add_cron . 所以你应该使用像uwsgi.add_cron这样的东西。 You can have a look at the decorator code to see how you could use it. 您可以查看装饰器代码以了解如何使用它。

You shouldn't be using a method but a function, though. 但是,您不应该使用方法而是使用函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM