1

如您所知,uwsgidecorators仅当您的应用程序在 的上下文中运行时才有效uwsgi,这在文档中并不完全清楚:https ://uwsgi-docs.readthedocs.io/en/latest/PythonDecorators.html

我的代码正在使用这些装饰器,例如用于锁定:

@uwsgidecorators.lock
def critical_func():
  ...

当我使用 uwsgi 部署我的应用程序时,这工作得很好,但是,当直接从 Python shell 启动它时,我得到了一个预期的错误:

File ".../venv/lib/python3.6/site-packages/uwsgidecorators.py", line 10, in <module>
  import uwsgi
ModuleNotFoundError: No module named 'uwsgi'

是否有任何已知的解决方案可以在两种模式下运行我的应用程序?显然,当使用简单的解释器时,我不需要同步和其他功能来工作,但是做一些 try-except 导入似乎真的很糟糕的编码。

4

1 回答 1

1

与此同时,我做了以下实现,很高兴知道有一些更简单的东西:

class _dummy_lock():
    """Implement the uwsgi lock decorator without actually doing any locking"""
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)


class uwsgi_lock():
    """
    This is a lock decorator that wraps the uwsgi decorator to allow it to work outside of a uwsgi environment as well.
    ONLY STATIC METHODS can be locked using this functionality
    """
    def __init__(self, f):
        try:
            import uwsgidecorators
            self.lock = uwsgidecorators.lock(f)  # the real uwsgi lock class
        except ModuleNotFoundError:
            self.lock = _dummy_lock(f)

    def __call__(self, *args, **kwargs):
        return self.lock(*args, **kwargs)

@staticmethod
@uwsgi_lock
def critical_func():
  ...
于 2018-12-03T07:49:46.843 回答