运行直接从Shell python使用uwsgidecorators的uWSGI应用

时间:2018-12-03 07:32:04

标签: flask uwsgi pythoninterpreter

您可能知道,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导入似乎真的很糟糕。

1 个答案:

答案 0 :(得分:0)

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

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():
  ...