0
votes

I'm trying to connect my flask application to my local MySQL database for testing. I've made a flask object and a class to represent an example table to be created after a successful connection.

These are my local env vars for my project:

#.env
LOCAL_MYSQL_URL = mysql://Username:[email protected]:3306/database_name

This is my project_name __init__ file:

#__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

ON_HEROKU = 'ON_HEROKU' in os.environ

if ON_HEROKU:
    DB_URL = os.environ.get('CLEARDB_DATABASE_URL')
else:
    DB_URL = os.environ.get('LOCAL_MYSQL_URL')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')

db = SQLAlchemy(app)  
db.create_all()
db.session.commit()

However I get the following error after running the app:

  if sa_url.drivername.startswith('mysql'):
AttributeError: 'NoneType' object has no attribute 'drivername'

I am trying to make this work following tutorials and answers contributed here on stackoverlow to similar questions, but none of them helped me out so far.

What am I missing here? What's wrong with my mysql driver name?

2
Does it raise a KeyError if you change this line: DB_URL = os.environ.get('LOCAL_MYSQL_URL') to os.environ['LOCAL_MYSQL_URL']?SuperShoot
@SuperShoot Yes. I've tried it out your way, and I get : raise KeyError(key) from None KeyError: 'MYSQL_URL'MattSom
"What's wrong with my mysql driver name?": 'NoneType' object has no attribute 'drivername' means that sa_url is None, there's nothing wrong with the driver name, just that the url you are passing to flask-sqlalchemy is None and None.drivername doesn't exist.SuperShoot
I have had to use pymysql to get this working. pip install pymysqlcinch
@MattSom that is in direct conflict with your comment where you said that you get the key error accessing the env var without .get(). I'm not sure where to go from here.SuperShoot

2 Answers

2
votes

Make sure the SQLAlchemy URI resembles this format after pip install pymysql

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{DB_USERNAME}:{DB_PASSWORD}@localhost:3306/{DB_NAME}'
0
votes

if you ever use "db.Model.metadata.reflect(db.engine)" in your models.py you will still get the same error message. So change the drivername mysqldb to pymysql as suggest by @MattSom and comment or delete this instruction "db.Model.metadata.reflect(db.engine)"