I am using nginx and gunicorn to serve flask app. Everything is working good the ony issue is, I need to restart gunicorn after couple of hours either I haven't update any code to the server. Here are steps which I have followed.
Step-1 wsgi.py file in project's root directory.
from myproject import app
if __name__ == "__main__":
app.run()
Step-2 Verified with server with following command which is working
- python app.py
- gunicorn --bind 0.0.0.0:5000 wsgi:app
Step-3 Setup gunicorn service: /etc/systemd/system/gunicorn.service
[Unit]
Description=Gunicorn API
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/var/www/api-setup
Environment="PATH=/var/www/api-setup/venv/bin"
ExecStart=/var/www/api-setup/venv/bin/gunicorn --workers 1 --bind unix:app.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target
Step-4: nginx conf file: /etc/nginx/site-available/my-nginx-conf
server {
listen 80;
client_max_body_size 1008M;
server_name Some.IP.Address;
root /var/www/api-setup/;
location / {
proxy_pass http://unix:/var/www/api-setup/app.sock;
}
}
After couple of hours, when I request to server, it showing error
sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back [SQL: 'SELECT tbls.id AS.....]
and after running
sudo systemctl1 restart gunicorn
everything works good. Any thoughts would be appriciated.
Sample Code
# Save Process
@api.route('/save')
class SaveData(Resource):
@classmethod
@jwt_required
def post(self):
try:
# Get request payload
data = request.json
instance = Model.find_by_id(id)
instance.name = 'Updated Name'
db.session.add(instance)
db.session.commit()
return BaseController.send_response(response, 200)
except Exception as e:
db.session.rollback()
api.abort(e.status_code, e.message)
Thanks!