首页 > 代码库 > 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/TestBlog‘app.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错误
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。