Forums

Connecting MySQL and python project problems

I'm trying to connect my python project and MySQL following the flask guide. I get this error:

(mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on '<4ndy456.mysql.pythonanywhere-services.com>:3306' (-2 Name or service  not known)

When I run db.create_all() that comes up.

My python code:

from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["DEBUG"] = True

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="4ndy456",
    password="<actualpassword>",
    hostname="4ndy456.mysql.pythonanywhere-services.com",
    databasename="4ndy456$comments",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

class Comment(db.Model):

    __tablename__ = "comments"

    id = db.Column(db.Integer, primary_key=True)
    content = db.column(db.String(4096))

comments = []

@app.route('/', methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("main_page.html", comments=comments)
    comments.append(request.form["contents"])
    return redirect(url_for('index'))

[edited by admin for formatting]

That looks like the correct hostname for your database, so I would expect that to work. Were you running db.create_all() on PythonAnywhere.

yup, on the mysql console on python anywhere but the error still comes up

In that error message it looks like there are some superfluous <angle brackets>?

Can't connect to MySQL server on '<4ndy456.mysql.pythonanywhere-services.com>:3306'