标签:
感谢,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 Flask from flask_sqlalchemy import SQLAlchemy from flask import Response from flask import json, jsonify app = Flask(__name__) app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql+pymysql://root:123456@localhost/TestBlog‘ app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = True db = 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 = User(‘admin‘,‘password‘,‘admin@admin.com‘) db.session.add(udata) db.session.commit() return jsonify(data) if __name__ == ‘__main__‘: app.run()
标签:
原文地址:http://www.cnblogs.com/ylzx/p/5861068.html