我第一次使用Flask和flask.ext.sqlalchemy。我收到一个错误,告诉我一个表不存在,但我认为对象关系设置会处理这个问题。可能不会。我在以下代码中遗漏了什么?
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'))
这是错误:
文件“/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py”,第36行,在defaulterrorhandler中 提出错误类,错误值 ProgrammingError :( ProgrammingError)(1146,“表'golfape $ swarm.suggestions'不存在”)'INSERT INTO建议(名称)VALUES(%s)'('钓鱼',)
答案 0 :(得分:1)
您必须调用 db.create_all()一次才能让sqlalchemy创建架构:
from my_app import Suggestion, db
db.create_all()
此外,您必须在初始化db:
之前移动数据库配置URL行app.config['SQLALCHEMY_DATABASE_URI'] ='mysql://golfape:mypass@mysql.server/golfape$swarm'
db = SQLAlchemy(app)
<强> 更新 强> 上面提到的问题是关于连接到mysql db并找到适当的连接器。安装以下模块:
pip install pymysql
并更改您的连接字符串:
db = SQLAlchemy('mysql+pymysql://user:password@mysql.server/database_name')