问题
I'm deploying a ML model for the first time. I'm using flask-restful to create a rest api and gunicorn as stand-alone WSGI.my project directory has only 2 files , ML_model.py and rApi.py. i installed gunicorn and ran the server using gunicorn -w 4 -b 127.0.0.1:5000 rApi:app
and i'm able to use the restAPi. I see many things like .env , .config and wsgi.py files mentioned in tutorials available online.
what am I missing. why do i need all those files if i can use the API already?
回答1:
I see many things like .env , .config and wsgi.py files mentioned
Most likely these things are just different ways of loading configurations into the app.
For example with a .env
file, you could declare some varaible in the form:
#.env
MODEL_FILE=some/path/to/a.h5
Then load this in with something like python-dotenv, utimately allowing you to do the following in your app:
model_to_use = os.getenv('MODEL_FILE', 'default.h5')
then_do_someting_with(model_to_use)
This keeps hard coded (possibly secret variables) out of your code, avoiding commiting them to source control. So when you deploy the app to another server or system, you can create a new .env
file which instead contains:
MODEL_FILE=some/production_ready/file.h5
Now the same copy of the code can be deployed with different functionality.
A dedicated config.py
may be used if you want to keep all of the above configuration loading together, then in your app.py
just do something like:
from config import MODEL_FILE
# ...
do_something_with(MODEL_FILE)
Dedicated wsgi.py
files are sometimes seen so that a WSGI server can load the module wsgi:app
. This file may contain configuration that is specific to WSGI deployment (Such as applying ProxyFix middleware to the app).
Of course this is just one method of applying that configuration to the application. You could also pass a PROXYFIX_ON
env var in, then do some logic in the code to enable the actual functionality based on the presence of this.
The latter means that functionality is disabled or enabled by changing that env var. The former means that functionality is disabled or enabled based on the module used to run the server.
It's really up to you how you design this part of the app. Loading config from environment variables is pretty common though. It's certainly a good idea to have an idea of how your chosen deployment method deals with this also. For example:
- Heroku: Configuration and Config Vars
- Pythonanywhere: How to set environment variables for your web apps
- Docker: Environment variables in Compose
来源:https://stackoverflow.com/questions/61676668/deploying-ml-models-with-flask-and-gunicorn