I have a flask app launched. however,the repeat function to update databse was not triggered. How can I let that function keep running backend and updating database? This is my code below.
My design was that I have a function to keep updating database , then webpage in flask app can show records in database. I am using APschedule to call function - “DataBaseUpdate”. However, it doesn’t run.
Someone told me create another non-web worker service in App platform. My questions are #1. update database, the worker service should connect internet, is non-web service will work? #2. Is the code base for this service independent than the flask-app? If so, can I use one dockerfile to deploy both this service and flask-app in future for convenience?
if __name__ == "__main__":
with app.app_context():
db.create_all() # <--- create db object.
start = datetime.date.today()+ datetime.timedelta(days=1) #set start and end time
end= start + datetime.timedelta(days=10)
scheduler = BackgroundScheduler()
scheduler.add_job(DataBaseUpdate, 'interval', seconds=30)
scheduler.start()
port = int(os.environ.get('PORT', 5000))
app.run(debug=True, host='0.0.0.0', port=port)
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Hi there,
In the context of the DigitalOcean App Platform, setting up a background task to regularly update the database in a Flask application requires a slightly different approach. Let’s address your concerns and outline the steps for implementing a reliable solution:
Independent Worker Service:
Shared Codebase Considerations:
app.py
for Flask app andworker.py
for the background tasks).Worker Service Configuration:
worker.py
, configure APScheduler or any other background task manager to run the database update tasks.Regarding your Dockerfile setup:
Dockerfile:
DigitalOcean App Platform Setup:
Example Dockerfile:
SERVICE_TYPE
to decide whether to start the web service (app.py
with Gunicorn) or the worker service (worker.py
).Environment Variables:
SERVICE_TYPE
toworker
for the worker service and leave it asweb
(or set it explicitly) for the web service in the DigitalOcean App Platform configuration.After deployment, thoroughly test both the web and worker services to ensure they are functioning as expected. The worker service should run the database update tasks at the specified intervals, and the web service should remain responsive to user requests.
Let me know how it goes!
Best,
Bobby