user729076
user729076

Reputation: 261

uwsgi two MySql errors after some time from starting application

I'm using uwsgi for my python application. I am new to uwsgi. When I want to run uwsgi in the background I do this:

uwsgi --http 127.0.0.1:1088 --wsgi-file app.py --callable app --master --processes 1 --workers 1 --threads 1 --daemonize=logs.txt

then after some time e.g. 10 minutes when I try to login to my test account on my live website I always get 500 internal error. In logs.txt file I found this exception:

OperationalError("(_mysql_exceptions.OperationalError) (2006, 'MySQL server has gone away')")

or sometimes this one

StatementError("(sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back",)

What I did:

below is my code. How can I solve my problem ? Thanks

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://brrr:brrr@localhost/grrr'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
app.config['SQLALCHEMY_POOL_RECYCLE'] = 285

db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
from models import *
app.secret_key = 'super secret key'

login_manager = LoginManager()
login_manager.init_app(app)

from models import *
login_manager.login_view = "login"

@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == int(user_id)).first()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/success')
def success():
    return render_template('success.html')

@app.route('/login', methods=['GET','POST'])
def login():
    error = None
    if request.method == 'POST':
        user = ser.query.filter_by(username=request.form['username']).first()
    if user is not None:
        user_pass = request.form['password']
        if bcrypt.check_password_hash(user.password, user_pass):
            login_user(user)
            return redirect(url_for('success'))
        else:
            error = 'error'
    else:
        error = 'error'
    return render_template('login.html', error=error)

@app.route('/signup', methods=['GET','POST'])
def signup():
    user_name_error = None
    email_error = None
    if request.method == 'POST':
        user = User(
        username=request.form['username'],
        password=request.form['password']
        )
        db.session.add(user)
        db.session.commit()
        login_user(user)
        return redirect(url_for('success'))
    return render_template('signup.html')

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

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

Upvotes: 1

Views: 457

Answers (1)

user729076
user729076

Reputation: 261

I did the same thing like PizzaPleb did here link so I re-init my db like this

db.init_app(app)

I pasted it here

...
from models import *
login_manager.login_view = "login"
**db.init_app(app)**
...

and I got rid off that exception.

Upvotes: 1

Related Questions