Reputation: 1383
I'm building a basic Flask Application with an an AngularJS front end and I am currently at the point where I need to make a connection to a MySQL database I have hosted with Godaddy phpmyadmin.
This is part of my __init__.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
# Create instnace called app
app = Flask(__name__)
app.config['SQLAlchemy_DATABASE_URI'] = 'mysql://username:password#@xxxxxx.hostedresource.com/dbname'
# Create SQLAlchemy object
db = SQLAlchemy(app)
# ...
This is my models.py
from app import app, db
class UsersPy(db.Model):
__tablename__ = "userspy"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
def __init__(self, username, password):
self.username = username
self.password = password
def __repr__(self):
return '<title {}'.format(self.username)
This is a snippet from my views.py:
from app import app, db
from app.models import UsersPy
from flask import render_template, request, redirect, url_for, jsonify, session, flash
@app.route('/testdb/')
def testdb():
admin = UsersPy('user1', 'password1')
guest = UsersPy('user2', 'password2')
db.session.add(admin)
db.session.add(guest)
#db.session.merge(admin)
#db.session.merge(guest)
db.session.commit()
results = UsersPy.query.all()
json_results = []
for result in results:
d = {'username': result.username,
'password': result.password}
json_results.append(d)
return jsonify(items=json_results)
All of this works well, the users are 'created' and displayed back in JSON format when you visit the /testdb/ location, however the actual database hosted with Godaddy is not being updated so the real connection must not be being made or it is failing for some reason. I have the userspy database table already created but add() and commit() functions are not actually adding users to the database. I can't figure out how to solidify the connection between SQLAlchemy and the MySQL Database. Any help is appreciated, thanks.
Upvotes: 2
Views: 14527
Reputation: 31
A good first step in debugging this would be to set SQLALCHEMY_ECHO
to True
in your app configuration. This will cause the actual MySQL database statements that SQLAlchemy is executing to be printed out.
Also, it's worth noting that SQLAlchemy_DATABASE_URI
is different from SQLALCHEMY_DATABASE_URI
, which is what the Flask-SQLAlchemy documentation states the config key should be.
Upvotes: 3