4

I've got a small flask server which uses click to define a few commands run via cron. My server connects to Rabbitmq via asyncio & asynqp:

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

When I run a click command, it loads the flask app (which I want as it includes my DB models) but also starts another connection to rabbitmq. I'd like to be able to check in the above init_app function if I'm running in the context of a click command or just as a flask server.

Here is an example of a click command definition:

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

def init_app(app):
    app.cli.add_command(my_function)
caffeinated.tech
  • 6,428
  • 1
  • 21
  • 40

1 Answers1

3

This is a bit of a hack but it worked for me:

# 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. 

See: How do I access command line arguments?

forestj
  • 983
  • 6
  • 15
  • Thank you for the answer. I should have updated my question with my interim solution of adding environment variables to my cron commands. Using arguments & environment variables seems to be plenty reliable and easy to understand. – caffeinated.tech Jul 09 '21 at 21:14