5

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)

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.