I had a huge working flask application running in an ec2 server with AWS RDS. I am using Apache with mod-wsgi. Suddenly all the URIs which make queries return errors.
I cannot spot why I started getting an "OperationalError: no such table: users u'SELECT users....'
The table is shown in the MySQL show tables. Further if I log into the server, acvitavate the virtualenv, and from the python console run:
from flask.ext.script import Manager
from myapp import create_app
from myapp.extensions import db
app=create_app()
manager=Manager(app)
ctx = app.app_context()
ctx.push()
I can access the user table and others. So what is going on here?
I am using two different configurations (development/production). This is done through the use of an environment variable. If I ran the code above in the production server, then I get the production configuration. How can I start to debug the problematic connection?
The app.wsgi file reads like this
import sys
sys.path.insert(0,"/var/www/myapp")
from myapp import create_app
application = create_app()
and then create_app is called, and apparently it reads the correct configuration. In particular, it will import and run
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
and then configure it
db.init_app(app)
The apache2 error log reads like this:
mod_authz_core.c(802): [client XXX.XX.XX.XX:29629] AH01626: authorization result of Require all granted: granted
mod_authz_core.c(802): [client XXX.XX.XX.XX:29629] AH01626: authorization result of <RequireAny>: granted
mod_authz_core.c(802): [client XXX.XX.XX.XX:29629] AH01626: authorization result of Require all granted: granted
mod_authz_core.c(802): [client XXX.XX.XX.XX:29629] AH01626: authorization result of <RequireAny>: granted
mod_wsgi (pid=6780, process='', application='ec2-XXX.XX.XX.XX.compute-1.amazonaws.com|'): Reloading WSGI script '/var/www/wsgi-scripts/app.wsgi'.
mod_wsgi (pid=6780): Exception occurred processing WSGI script '/var/www/wsgi-scripts/app.wsgi'.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1-py2.7.egg/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/Flask-0.10.1- py2.7.egg/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/myapp/myapp/frontend/views.py", line 71, in index
#current_app.logger.debug('debug')
File "/usr/local/lib/python2.7/dist-packages/Flask_SQLAlchemy-2.0- py2.7.egg/flask_sqlalchemy/__init__.py", line 431, in paginate
items = self.limit(per_page).offset((page - 1) * per_page).all()
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7- linux-x86_64.egg/sqlalchemy/orm/query.py", line 2320, in all
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7- linux-x86_64.egg/sqlalchemy/orm/query.py", line 2438, in __iter__
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/orm/query.py", line 2453, in _execute_and_instances
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 729, in execute
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 826, in _execute_clauseelement
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 958, in _execute_context
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 1159, in _handle_dbapi_exception
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/util/compat.py", line 199, in raise_from_cause
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/engine/base.py", line 951, in _execute_context
File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.8-py2.7-linux-x86_64.egg/sqlalchemy/engine/default.py", line 436, in do_execute
OperationalError: (OperationalError) no such table: users u'SELECT users.password AS users_password, users.id AS users_id, users.name AS users_name, users.email AS users_email, users.openid AS users_openid, users.activation_key AS users_activation_key, users.created_time AS users_created_time, users.avatar AS users_avatar, users.role_code AS users_role_code, users.status_code AS users_status_code, users.user_detail_id AS users_user_detail_id, users.followers AS users_followers, users.following AS users_following \\nFROM users\\n LIMIT ? OFFSET ?' (10, 0)
There was a sequence of details that led to the problem. By design, the default configuration is loaded first and then it is overwritten with the line
app.config.from_envvar("PRODUCTION_CFG",silent=True)
The problem was that the environment variable was set in the session in which I was using the bash, but not in the session were the server was running. I fixed it by using app.config.from_pyfile instead.
Related
For educational purposes, we're building a very simple Flask app. While it runs smoothly locally, it no longer does when I copy the code to my virtual private server.
The route is defined as follows:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def sign_up():
...
This is the function that uses autocomplete:
with connection.cursor() as cursor:
sql = f"SELECT * FROM movies WHERE title"
query = cursor.execute(sql)
data = cursor.fetchall()
# from flask import jsonify
results = [data[i]['title'] for i in range(len(data))]
return render_template("autocomplete.html", results=results)
autocomplete.html is located in the templates folder, which sits next to the Python program file.
And the web service is started like this:
if __name__ == '__main__':
app.run(host='0.0.0.0')
I can start the web service successfully, but when I connect using the URL, it returns a 500 error, and the server console shows:
[2020-05-28 16:19:47,099] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "app.py", line 94, in sign_up
return render_template("autocomplete.html", results=results)
File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template
ctx.app,
File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 120, in _render
rv = template.render(context)
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
self.environment.handle_exception()
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "/root/miniconda3/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "/root/recommender/app-flask/templates/autocomplete.html", line 10, in top-level template code
$.getJSON("{{url_for('autocomplete')}}",{
File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 370, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2216, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 358, in url_for
endpoint, values, method=method, force_external=external
File "/root/miniconda3/lib/python3.7/site-packages/werkzeug/routing.py", line 2179, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'autocomplete'. Did you mean 'static' instead?
I assume this is because of a change in the URL, but I don't know how to solve this.
Can anyone help?
$.getJSON("{{url_for('autocomplete')}}",{
=> your code wrong at this line, read more about url_for in flask.
It's need to render route like: <blueprint_name>.<function_name> If use app as route use can skip blueprint_name => Ex: .sign_up
sample
I am trying to use mysql to run a python-flask web application. I am connecting to the database in the main application file however, everytime I try to enter data into the database (i.e. register a customer) I keep getting the error:
Traceback (most recent call last):
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/home/<username>/.local/lib/python2.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/mnt/c/Users/<username>/Documents/<web application>/app.py", line 156, in register
cur = mysql.connection.cursor()
File "/home/<username>/.local/lib/python2.7/site-packages/flask_mysqldb/__init__.py", line 94, in connection
ctx.mysql_db = self.connect
File "/home/<username>/.local/lib/python2.7/site-packages/flask_mysqldb/__init__.py", line 81, in connect
return MySQLdb.connect(**kwargs)
File "/home/<username>/.local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
return Connection(*args, **kwargs)
File "/home/<username>/.local/lib/python2.7/site-packages/MySQLdb/connections.py", line 179, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (1045, "Access denied for user 'root'#'localhost' (using password: YES)")
I have looked at similar articles with the main suggestion being:
(in sql)
USE mysql;
UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE User='root';
flush privileges;
exit;
(in terminal): sudo service mysql restart
How I config the database:
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '<root password>'
app.config['MYSQL_DB'] = '<db name>'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
#init MYSQL
mysql= MySQL(app)
However, the error still persists after trying this. I am unsure how to continue so any help would be appreciated.
If you are able to make the queries when logged into MySQL normally, there should be no reason to not be able to do them in the application (with the same user/pass).
I would recommend checking if your password has any characters that could parse incorrectly, eg ' \ .
If you don't see any issues with the password, you can try to just connect to MySQL from the application before doing any queries and see if the connection is successful.
I'm trying to run https://github.com/swifthorseman/flask-peewee-heroku-setup locally on win 10, using python 3.6. I'm not sure if this project is designed to be run locally, maybe its only designed for heroku.
I have run the file teletubbies.py locally which created the db and table as you can see in the screenshot. To run it locally (or try to) I added the lines:
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
and I'm running it using
python server.py
The entire server.py file as I have it:
from flask import Flask, render_template, g
from tellytubbies import retrieve_all, db_proxy
app = Flask(__name__)
#app.before_request
def before_request():
g.db = db_proxy
g.db.connect()
#app.after_request
def after_request(response):
g.db.close()
return response
#app.route('/')
def index():
tellytubbies = retrieve_all()
return render_template("index.html", tellytubbies=tellytubbies)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
By stepping through the code I don't see an error until the line:
tellytubbies = retrieve_all()
Which then crashes giving the following Traceback:
Traceback (most recent call last):
File "....myfile\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "....myfile\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "....myfile\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "....myfile\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "....myfile\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "....myfile\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "....myfile\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "....myfile\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "....myfile\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "....myfile\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "...\server.py", line 18, in index
tellytubbies = retrieve_all()
File "...\tellytubbies.py", line 32, in retrieve_all
for tellytubby in TellyTubby.select().order_by(TellyTubby.name):
File "....myfile\lib\site-packages\peewee.py", line 3281, in __iter__
return iter(self.execute())
File "....myfile\lib\site-packages\peewee.py", line 3274, in execute
self._qr = ResultWrapper(model_class, self._execute(), query_meta)
File "....myfile\lib\site-packages\peewee.py", line 2939, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "....myfile\lib\site-packages\peewee.py", line 3837, in execute_sql
self.commit()
File "....myfile\lib\site-packages\peewee.py", line 3656, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "....myfile\lib\site-packages\peewee.py", line 135, in reraise
raise value.with_traceback(tb)
File "....myfile\lib\site-packages\peewee.py", line 3830, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: no such table: tellytubby
The retrieve_all() function comes from the teletubbies.py file:
def retrieve_all():
results = []
for tellytubby in TellyTubby.select().order_by(TellyTubby.name):
results.append(tellytubby)
return results
the teletubbies.py does work when I run it as
python teletubbies.py
How can I get this working?
Your flask server works fine for me, after I run python teletubbies.py to initialize the sqlite database. However, if I remove the tellytubbies.db file that was created by running the script directly, the flask server fails with the same exception you quote.
Something to consider here is that when you run tellytubbies.py, the database file tellytubbies.db will be created in whatever directory you run it from. If you then run server.py from a different directory - for instance, if your IDE is running it - it won't find the other tellytubbies.db, so a new one will be created; but becase the tables were only created in your __main__ section in tellytubbies.py, the tables won't be created.
So your flask server needs to do some of the initialization that teletubbies.py is doing. I replaced the if __name__ == '__main__': section of your server.py with the following and it it works. It will work whether you keep the same database file or remove it between runs to start from scratch. I've added a check to make sure the same rows don't get inserted repeatedly.
if __name__ == '__main__':
from teletubbies import add_tellytubbies, TellyTubby
db_proxy.connect()
db_proxy.create_tables([TellyTubby], safe=True)
if TellyTubby.select().count() == 0:
add_tellytubbies()
app.run(debug=True, use_reloader=True)
I'm hosting a website/app using Flask/SQLAlchemy on Google's App Engine, part of which entails communicating with a PostgreSQL server and querying it to populate the website. The SQL server is hosted on Google's Compute Engine as a VM instance per these instructions, but with the server open to all connections.
When I send a GET request to the website/app when it is hosted on localhost, I get the data I expect. However, when I launch the app and attempt to send the same request to the new URL, I get an HTTP 500 error. In GCP's logging section, I see the request and a stack trace containing the following:
(/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:279)
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/main.py", line 108, in get_book1
for item in models.Book.query.all():
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask_sqlalchemy/__init__.py", line 498, in __get__
return type.query_class(mapper, session=self.sa.session())
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/sqlalchemy/orm/scoping.py", line 78, in __call__
return self.registry()
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/sqlalchemy/util/_collections.py", line 990, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/sqlalchemy/orm/session.py", line 2829, in __call__
return self.class_(**local_kw)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask_sqlalchemy/__init__.py", line 145, in __init__
bind = options.pop('bind', None) or db.engine
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask_sqlalchemy/__init__.py", line 922, in engine
return self.get_engine()
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask_sqlalchemy/__init__.py", line 941, in get_engine
return connector.get_engine()
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/flask_sqlalchemy/__init__.py", line 543, in get_engine
self._engine = rv = sqlalchemy.create_engine(info, **options)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/sqlalchemy/engine/__init__.py", line 387, in create_engine
return strategy.create(*args, **kwargs)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/sqlalchemy/engine/strategies.py", line 80, in create
dbapi = dialect_cls.dbapi(**dbapi_args)
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/sqlalchemy/dialects/postgresql/psycopg2.py", line 554, in dbapi
import psycopg2
File "/base/data/home/apps/s~cs373-idb/20170411t063743.400476890985925133/lib/psycopg2/__init__.py", line 50, in <module>
from psycopg2._psycopg import ( # noqa
ImportError: dynamic module does not define init function (init_psycopg)
Given dummy data (i.e., having the app return some set data as opposed to querying the database,) the GET requests work fine, and TravisCI has no problem running tests which also involve querying the database using the same source, so I'm confident that the problem is with the database and its interaction with GAE.
I've read seemingly conflicting articles on Google's own website on whether or not PostgreSQL is supported by the App Engine. Is there a way to solve this?
If it helps, this is the lib folder that I've set for the app:
aniso8601 flask itsdangerous.py MarkupSafe-1.0.dist-info requests-2.13.0.dist-info SQLAlchemy-1.1.9.dist-info
aniso8601-1.2.0.dist-info Flask-0.12.1.dist-info itsdangerous.pyc psycopg2 requests_toolbelt werkzeug
click flask_restful jinja2 psycopg2-2.7.1.dist-info requests_toolbelt-0.7.1.dist-info Werkzeug-0.12.1.dist-info
click-6.7.dist-info Flask_RESTful-0.3.5.dist-info Jinja2-2.9.6.dist-info python_dateutil-2.6.0.dist-info six-1.10.0.dist-info
coverage flask_sqlalchemy markup pytz six.py
coverage-4.3.4.dist-info Flask_SQLAlchemy-2.2.dist-info markup-0.2.dist-info pytz-2017.2.dist-info six.pyc
dateutil itsdangerous-0.24.dist-info markupsafe requests sqlalchemy
These libraries were added from GCP's console with the command:
pip install -r requirements.txt -t lib
where requirements.txt contains this list:
Flask
Flask-SQLAlchemy
psycopg2
Markup
requests
flask_restful
requests-toolbelt
coverage
Finally, my python version is 2.7.9 and pip 9.0.1
Thank you in advance for taking the time to read this. Any advice would be immensely appreciated.
I am trying to get my Google App Engine app to work with Flask-SQLAlchemy. I am getting the error:
AttributeError: 'module' object has no attribute 'paramstyle'
I have followed the instructions in this answer (Local MySQLdb connection fails with AttributeError for paramstyle when running GAE development server) and so I no longer get the error in the interactive console (when I make an app context).
However, the error still appears when I run the app in my local GAE. Why is this still happening? I am running OSX Mavericks. The full trace:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 266, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/conor/Documents/Projj/lib/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/conor/Documents/Projj/financey.py", line 117, in login_view
userObj = get_user(username)
File "/Users/conor/Documents/Projj/financey.py", line 88, in get_user
return db.session.query(User).filter_by(username=username).first()
File "/Users/conor/Documents/Projj/lib/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/Users/conor/Documents/Projj/lib/sqlalchemy/util/_collections.py", line 864, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/Users/conor/Documents/Projj/lib/flask_sqlalchemy/__init__.py", line 139, in __init__
bind=db.engine,
File "/Users/conor/Documents/Projj/lib/flask_sqlalchemy/__init__.py", line 780, in engine
return self.get_engine(self.get_app())
File "/Users/conor/Documents/Projj/lib/flask_sqlalchemy/__init__.py", line 797, in get_engine
return connector.get_engine()
File "/Users/conor/Documents/Projj/lib/flask_sqlalchemy/__init__.py", line 473, in get_engine
self._engine = rv = sqlalchemy.create_engine(info, **options)
File "/Users/conor/Documents/Projj/lib/sqlalchemy/engine/__init__.py", line 332, in create_engine
return strategy.create(*args, **kwargs)
File "/Users/conor/Documents/Projj/lib/sqlalchemy/engine/strategies.py", line 69, in create
dialect = dialect_cls(**dialect_args)
File "/Users/conor/Documents/Projj/lib/sqlalchemy/dialects/mysql/base.py", line 1985, in __init__
default.DefaultDialect.__init__(self, **kwargs)
File "/Users/conor/Documents/Projj/lib/sqlalchemy/engine/default.py", line 124, in __init__
self.paramstyle = self.dbapi.paramstyle
AttributeError: 'module' object has no attribute 'paramstyle'
EDIT: In attempting to further diagnose the issue, when I import MySQLdb in the GAE Interactive Console (in the browser) I get the error ImportError: No module named _mysql
After looking around and debugging for far too long, I finally discovered the issue. When you run the GAE development server, the dev_appserver must be told exactly which MySQL instance you want to connect to. The connection string you use (e.g. in Python) doesn't matter. The connection string only determines database name and instance. However, SQLAlchemy can figure it out fine if you run form an ipython console. This may be due to a different driver being used under the hood.
Hopefully this saves someone else a lot of hair-pulling. Run your dev_appserver.py like so:
dev_appserver.py --mysql_host=<Cloud SQL IP> --mysql_user=root --mysql_password=<Cloud SQL root password> <application directory>