I am trying to connect my FLASK app with MySQL on localhost(127.0.0.1:5000) but getting below error.
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'waiting for initial communication packet', system error: 60")
I am using "flask_mysqldb" library. When i tried to fill form and hit submit. it tries to connect to db but never got success and returns error.
Please check out my code and help.
from flask import Flask, render_template, flash, redirect, url_for, request, session, logging
from data import Articles
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt
app = Flask("__name__")
# config MySQL
app.config["MYSQL_HOST"] = "127.0.0.1"
app.config["MYSQL_PORT"] = 5000
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_DB"] = "myflaskapp"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
# init MySQL
mysql = MySQL(app)
Articles = Articles()
@app.route("/")
def index():
return render_template("index.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/articles")
def articles():
return render_template("articles.html", articles = Articles)
@app.route("/article/<string:id>/")
def article(id):
return render_template("article.html", id=id)
# collect and validate user data
class RegisterForm(Form):
name = StringField('Name', [validators.Length(min=1, max=50)])
username = StringField('Username', [validators.Length(min=4, max=25)])
email = StringField('Email', [validators.Length(min=6, max=50)])
password = PasswordField('Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Password do not match')
])
confirm = PasswordField('Confirm Password')
# insert user data to DB
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
name = form.name.data
email = form.email.data
username = form.username.data
password = sha256_crypt.encrypt(str(form.password.data))
# create cursor(handler) to connect DB
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users(name, email, username, password) VALUES (%s, %s, %s, %s)", (name, email, username, password))
# commit to db
mysql.connection.commit()
# close the connection
cur.close()
flash('You are now Registered', 'success')
return redirect(url_for('index'))
return render_template('register.html', form=form)
if __name__ == "__main__":
app.run(debug=True)
Below are the versions i am using.
- Python: 3.6
- MySQL: 5.7.21
Q: Is "flask_mysqldb" support python 3.6 or not?
Q: What is the good alternative, if required?
- PyMySQL
- mysqlclient
- SQLalchemy
And yes, mysqlclient is also installed already.