简体   繁体   中英

How do I force Flask/SQLAlchemy to create a table?

I'm using Flask with flask.ext.sqlalchemy for the first time. I'm getting an error telling me a table doesn't exist, but I thought the object relational setup would take care of that. Guess not. What am I missing in the following code?

from flask import Flask, request, url_for
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = 'This is really unique and secret'

db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] ='mysql://golfape:mypass@mysql.server/golfape$swarm'


class Suggestion(db.Model):
    __tablename__ = 'suggestions'
    id   = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(100))

    def __init__( self, name ):
        self.name = name

@app.route('/')
def get_suggestion():
    return """
        <p>What do you think swarm prediction could be applied to?</p>
        <form method = "POST" action="%s">
             <input name="name" />
             <input type="submit" value="Go!" />
         </form>
         """ % (url_for('append_suggestion'),)


@app.route('/suggestions', methods=['POST'] )
def append_suggestion():
    name = request.form["name"]
    newSuggestion = Suggestion( name = name )
    db.session.add( newSuggestion )
    db.session.commit()
    return """
        <p>Thanks for suggesting %s</p>
        <p><a href="%s">Back</a></p>
        """ % (name, url_for('get_suggestion'))

Here is the error:

File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue ProgrammingError: (ProgrammingError) (1146, "Table 'golfape$swarm.suggestions' doesn't exist") 'INSERT INTO suggestions (name) VALUES (%s)' ('fishing',)

You have to call db.create_all() once to have sqlalchemy create the schema:

from my_app import Suggestion, db
db.create_all()

Moreover you have to move the database config URL line before initializing db:

app.config['SQLALCHEMY_DATABASE_URI'] ='mysql://golfape:mypass@mysql.server/golfape$swarm'
db = SQLAlchemy(app)

UPDATE The above mentioned problem is about connecting to mysql db and finding proper connector for it. install the following module:

pip install pymysql

and change your connection string like this:

db = SQLAlchemy('mysql+pymysql://user:password@mysql.server/database_name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM