python flask SQLAlchemy 的用法
2017-05-26 11:50
363 查看
为了方便,可选择python云平台测试,本例(十分推荐)使用的是pythonanywhere.
1. 初始化
2. model
3. 创建mysql数据库
4. 打开console执行:
注意,如果使用的是python2.7,可能会遇到错误 'module mysql not found.'
解决方案:
1. 运行
搜索出可用的mysql connector包
2. 安装
1. 初始化
db = SQLAlchemy() SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format( username="username", password="password", hostname="hostURL", databasename="db_name", ) app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
2. model
from app import db, login_manager class Employee(UserMixin, db.Model): """ Create an Employee table """ # Ensures table will be named in plural and not in singular # as is the name of the model __tablename__ = 'employees' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(60), index=True, unique=True) username = db.Column(db.String(60), index=True, unique=True) first_name = db.Column(db.String(60), index=True) last_name = db.Column(db.String(60), index=True) password_hash = db.Column(db.String(128)) department_id = db.Column(db.Integer, db.ForeignKey('departments.id')) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) is_admin = db.Column(db.Boolean, default=False) @property def password(self): """ Prevent pasword from being accessed """ raise AttributeError('password is not a readable attribute.') @password.setter def password(self, password): """ Set password to a hashed password """ self.password_hash = generate_password_hash(password) def verify_password(self, password): """ Check if hashed password matches actual password """ return check_password_hash(self.password_hash, password) def __repr__(self): return '<Employee: {}>'.format(self.username)
3. 创建mysql数据库
4. 打开console执行:
flask db migrate flask db upgrade
注意,如果使用的是python2.7,可能会遇到错误 'module mysql not found.'
解决方案:
1. 运行
pip search mysql-connector | grep --color mysql-connector-python
搜索出可用的mysql connector包
2. 安装
pip install mysql-connector-python-rf
相关文章推荐
- python sqlalchemy更简单的用法
- Python的Flask框架中SQLAlchemy使用时的乱码问题解决
- 从源码解析Python的Flask框架中request对象的用法
- MySQL-python中间件的安装及Flask_SQLAlchemy的学习
- python Flask-SQLAlchemy 连接数据库
- python sqlalchemy的简单用法
- flask-sqlalchemy 用法总结
- python Flask-SQLAlchemy操作数据库
- Python程序和Flask框架中使用SQLAlchemy的教程
- python---pymsql+flask_sqlalchemy连接数据库
- Python的Flask框架中SQLAlchemy使用时的乱码问题解决
- 在Python程序和Flask框架中使用SQLAlchemy的教程
- 从源码解析Python的Flask框架中request对象的用法
- 从源码解析Python的Flask框架中request对象的用法
- Python――flask-sqlalchemy 自动生成符合Sqlachemy的Model:sqlautocode/sqlacodegen使用方式
- Python的Flask框架中@app.route的用法教程
- 从源码解析Python的Flask框架中request对象的用法
- Python的Flask框架中使用Flask-SQLAlchemy管理数据库的教程
- Python学习之Flask-SQLAlchemy乱码异常
- Python-Flask:利用flask_sqlalchemy实现分页效果