IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]python flask SQLAlchemy 的用法

    csharp25发表于 2017-05-26 11:50:07
    love 0
    为了方便,可选择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


沪ICP备19023445号-2号
友情链接