如何检查 python 是否是 运行 作为 click cli 命令而不是 flask 服务器?

How to check if python is running as a click cli command instead of the flask server?

我有一个小型 flask 服务器,它使用 click 通过 cron 定义一些命令 运行。 我的服务器通过 asyncio 和 asynqp 连接到 Rabbitmq:

class RabbitMQConnection():
    def __init__(self):
        self.connection = None
        self.channel = None
        self.exchange = None

    @asyncio.coroutine
    def connect(self): 
        self.connection = yield from asynqp.connect(
            'rabbitmq-host',
            5672,
            username=RABBITMQ_USERNAME,
            password=RABBITMQ_PASSWORD)

class MessageProcessor(Thread):
    def run(self):
        loop = asyncio.new_event_loop()
        loop.create_task(self._run())
        loop.run_forever()

    @asyncio.coroutine
    def _run(self):
        rabbit = RabbitMQConnection()
        yield from rabbit.connect()


def init_app(app):
    thread = MessageProcessor()
    thread.daemon = True
    thread.start()

当我 运行 单击命令时,它会加载 flask 应用程序(我想要它,因为它包含我的数据库模型),但也会启动与 rabbitmq 的另一个连接。 如果我 运行 在单击命令的上下文中或仅作为烧瓶服务器,我希望能够检查上面的 init_app 函数。

这里是一个点击命令定义的例子:

@click.command('my-function')
@with_appcontext
def my_function():
    click.echo('this was fun')

def init_app(app):
    app.cli.add_command(my_function)

这有点难,但对我有用:

# detect if we are running the app.
# otherwise we are running a custom flask command.
command_line = ' '.join(sys.argv)
is_running_server = ('flask run' in command_line) or ('gunicorn' in command_line)

if is_running_server:
  # do stuff that should only happen when running the server. 

参见:How do I access command line arguments?