简体   繁体   中英

Detect If Flask App Is Running Locally

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM