您的位置:首页 > 编程语言 > Python开发

python flask SQLAlchemy 的用法

2017-05-26 11:50 363 查看
为了方便,可选择python云平台测试,本例(十分推荐)使用的是pythonanywhere.

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: