On local machine, using a local MySQL database everything goes fine. Here is my app __init__.py
file:
#rootfolder/__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:
from dotenv import load_dotenv
load_dotenv()
DB_URL = os.getenv('MYSQL_URL')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
from projectname.Controller.root import root
from projectname.Controller.user_controller import user_routes # This imports Model too
app.register_blueprint(root)
app.register_blueprint(user_routes)
db.create_all()
The user_routes
Blueprint imports the Model classes as well. I see the created tables in my local database, so the logic seems fine.
Printed out 'HELLO'
and the DB_URL
inside the if ON_HEROKU:
condition to check the url in the cloud:
if ON_HEROKU:
DB_URL = os.environ.get('CLEARDB_DATABASE_URL')
print('HELLO')
print(DB_URL)
I can see them looking at heroku logs:
.
.
app[web.1]: HELLO
app[web.1]: mysql://*********:*******@us-cdbr-iron-east-05.cleardb.net/heroku_c52490fb3111cda?reconnect=true
.
.
Indeed, I have the installed ClearDB on heroku with that url as a config var:
I've also managed to connect to this heroku db using HeidiSQL and the url heroku created me. So everything must be at place.
Commenting out the db.create_all()
function the deployed heroku app throws no error and I see the base json message following my root route. However, adding db.create_all()
back I get the following log error:
app[web.1]: db.create_all()
app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 1033, in create_all
.
.
.
app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 118, in dbapi
app[web.1]: return __import__("MySQLdb")
app[web.1]: ModuleNotFoundError: No module named 'MySQLdb'
I had similar errors locally so I've tried to modify the URL heroku gave me with the mysql+pymysql://
drivername and adding PyMySQL==0.9.3
to my requirements.txt
(I'm not sure if heroku checks that).
It was not enough the error is now:
app[web.1]: db.create_all()
app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 1033, in create_all
.
.
.
app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect
app[web.1]: return Connection(*args, **kwargs)
app[web.1]: TypeError: __init__() got an unexpected keyword argument 'reconnect'
My Procfile
looks like this: web gunicorn run:app
, as a run.py
starts the whole application.
What am I missing here?