首页 > 代码库 > Flask-SQLAlchemy错误

Flask-SQLAlchemy错误

 

感谢,http://www.zhihu.com/question/29719547

  根据《Flask web开发...》这本书上操作连接数据一直有问题 ”No module named ‘MySQLdb‘“

  首先需要安装pip install PyMySQL

  然后mysql://root:123456@localhost/TestBlog 改为mysql+pymysql://root:123456@localhost/TestBlog

  下面是我测试通过的代码

from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyfrom flask import Responsefrom flask import json, jsonifyapp = Flask(__name__)app.config[SQLALCHEMY_DATABASE_URI] = mysql+pymysql://root:123456@localhost/TestBlogapp.config[SQLALCHEMY_TRACK_MODIFICATIONS] = Truedb = SQLAlchemy(app)class User(db.Model):    __tablename__ = t_users    id = db.Column(db.Integer, primary_key=True)    username = db.Column(db.String(80), unique=True)    password = db.Column(db.String(100))    email = db.Column(db.String(120), unique=True)    def __init__(self, username, password, email):        self.username = username        self.password = password        self.email = email    def __repr__(self):        return <User %r> % self.username@app.route(/)def hello_world():    # me = User(‘zxj‘)    # db.session.add(me)    return {"name":"zxj"}@app.route(/register, methods = [POST])def register():    data = {        username: 张先生,        userID: 1    }    # js = json.dumps(data)    # resp = Response(js, status=200, mimetype=‘application/json‘)    udata = http://www.mamicode.com/User(admin,password,admin@admin.com)    db.session.add(udata)    db.session.commit()    return jsonify(data)if __name__ == __main__:    app.run()

 

Flask-SQLAlchemy错误