Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if a Flask app is being run on localhost?

I want my Flask app to have different behaviors when it is being run on localhost and when it is being hosted online. How can I detect from a flask app when it is on localhost and when it is deployed?

like image 373
Jason Brooks Avatar asked Dec 09 '25 23:12

Jason Brooks


1 Answers

You'll want to look at the configuration handling section of the docs, most specifically, the part on dev / production. To summarize here, what you want to do is:

  • Load a base configuration which you keep in source control with sensible defaults for things which need to have some value. Anything which needs a value should have the value set to what makes sense for production not for development.
  • Load an additional configuration from a path discovered via an environment variable that provides environment-specific settings (e. g. the database URL).

An example in code:

from __future__ import absolute_imports
from flask import Flask
import .config  # This is our default configuration

app = Flask(__name__)

# First, set the default configuration
app.config.from_object(config)

# Then, load the environment-specific information
app.config.from_envvar("MYAPP_CONFIG_PATH")

# Setup routes and then ...

if __name__ == "__main__":
    app.run()

See also: The docs for Flask.config

like image 142
Sean Vieira Avatar answered Dec 12 '25 11:12

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!