我写的demo程序
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager,Shell
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1/hello'
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir,'data.sqlite')
manager = Manager(app)
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
def __repr__(self):
return '' % self.username
def make_shell_context():
return dict(app=app,db=db,User=User)
manager.add_command('shell',Shell(make_context=make_shell_context))
if __name__ == '__main__':
manager.run()
可以再mysql插入数据,插入之前:
mysql> select * from users;
+------+-------------+---------+
| id | username | role_id |
+------+-------------+---------+
| NULL | yzxu | NULL |
| NULL | dayiguizhen | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | test | NULL |
+------+-------------+---------+
13 rows in set (0.00 sec)
yzxu@ubuntu:~/py/github$ python sql.py shell
>>> user = User(username='after')
>>> db.session.add(user)
>>> db.session.commit()
插入成功:
mysql> select * from users;
+------+-------------+---------+
| id | username | role_id |
+------+-------------+---------+
| NULL | yzxu | NULL |
| NULL | dayiguizhen | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | yzxu | NULL |
| NULL | test | NULL |
| NULL | after | NULL |
+------+-------------+---------+
14 rows in set (0.00 sec)
但是查询不到东西
>>> User.query.filter_by(username='after').all()
[None]
但是把URI换成SQLite的就可以查询到
>>> db.create_all()
>>> u = User(username='yzxu')
>>> db.session.add(u)
>>> db.session.commit()
>>> User.query.all()
[]
>>> quit()
是不是把URI换成mysql还有进行一些其他的操作?