paskvilwiki

up: programming

Flask and Flask-RestPlus

last updated 2019-09

structuring the project

handling requests

file upload

@ns.route('/')
class Handle(Resource):
    @ns.param('data', description='We will just return this.', _in='formData', type='string', required=True)
    @ns.param('file', description='We will save this as /tmp/test.jpg.', _in='formData', type='file', required=True)
    def post(self):
        with open('/tmp/test.jpg', 'wb') as f:
            f.write(request.files['file'].read())
        return {'data': request.form['data']}

"MySQL server has gone away" with (Flask-)SQLAlchemy

this hits infrequently used connections - most cloud hosts kill unused DB connections after some time

it's a problem if your SQLAlchemy connection pool is not recycled often enough

you can just lower the recycle time to solve this. it's also good to increase the pool size to handle the case where your load increases (at times):

app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'pool_size': 100,
    'pool_recycle': 240,
    'pool_pre_ping': True,  # test each connection before use, reconnect if it's dead
}

SQLAlchemy's default pool is 5 connections, and Flask-SQLAlchemy recycles MySQL connections after 7200 s, but many cloud providers kill inactive connections after about 5 min, thus the 4 min period above

update 2026 - this used to be SQLALCHEMY_POOL_SIZE and SQLALCHEMY_POOL_RECYCLE, both gone in Flask-SQLAlchemy 3