Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect If Flask App Is Running Locally

Tags:

python

flask

I would like certain parts of my code to not run while it is being run locally.

This is because, I am having trouble installing certain dependencies locally, for the code to run.

Specifically, memcache doesn't work for me locally.

@app.route('/some_url_route/')
@cache.cached(timeout=2000) #ignore this locally
def show_a_page():

How would the app somehow ignore the cache section of the code above, when running locally?

like image 300
GangstaGraham Avatar asked Oct 03 '22 18:10

GangstaGraham


2 Answers

In my code I follow a Django-esq model and have a main settings.py file I keep all my settings in.

In that file putting DEBUG = True for your local environment (and False for production) I then use:

 from settings import DEBUG

 if DEBUG:
     # Do this as it's development
 else:
     # Do this as it's production

So in your cache decorator include a similar line that only checks memcached if DEBUG=False

You can then load all these settings into your Flask setup as detailed in the configuration documentation.

like image 154
Ewan Avatar answered Oct 20 '22 14:10

Ewan


If you're using Flask-Cache, then just edit the settings:

if app.debug:
    app.settings.CACHE_TYPE = 'null'  # the cache that doesn't cache

cache = Cache(app)
...

A better approach would be to have separate settings for production and development. I use a class-based approach:

class BaseSettings(object):
    ...

class DevelopmentSettings(BaseSettings):
    DEBUG = True
    CACHE_TYPE = 'null'
    ...

class ProductionSettings(BaseSettings):
    CACHE_TYPE = 'memcached'
    ...

And then import the appropriate object when you setup your app (config.py is the name of the file which contains the settings):

app.config.from_object('config.DevelopmentConfig')
like image 35
Blender Avatar answered Oct 20 '22 14:10

Blender