当前位置: 首页 > news >正文

python flask SQLAlchemy 的用法

为了方便,可选择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

相关文章:

  • Blog须知
  • Azure VM Scalable Sets -- 适用IAAS架构
  • 数据库设计技巧14则
  • 一张图说明HTTPS 握手过程
  • linux-2.6.26内核中ARM中断实现详解(1)
  • 创建Azure scheduler完成日常任务
  • (TipsTricks)用客户端模板精简JavaScript代码
  • eclipse 生成发布的apk (signed zipalign过程)
  • 使用黄金分割比值计算斐波那契数列
  • 遭遇飞信“中奖” 之 图文全攻略
  • Swift 3 实现拍照功能
  • 我们欠了地球什么?
  • Iphone 消息通知(APNS)的3种方式 -- C# 和 nodejs
  • 创建Azure Function
  • 金旭亮博客之“桌面应用程序开发技术”资源主页
  • Google 是如何开发 Web 框架的
  • 10个最佳ES6特性 ES7与ES8的特性
  • 3.7、@ResponseBody 和 @RestController
  • JDK 6和JDK 7中的substring()方法
  • jQuery(一)
  • JS字符串转数字方法总结
  • Linux CTF 逆向入门
  • Nodejs和JavaWeb协助开发
  • PHP 使用 Swoole - TaskWorker 实现异步操作 Mysql
  • Travix是如何部署应用程序到Kubernetes上的
  • Vue2.x学习三:事件处理生命周期钩子
  • 从零开始学习部署
  • 浏览器缓存机制分析
  • 译米田引理
  • 优秀架构师必须掌握的架构思维
  • # Maven错误Error executing Maven
  • (70min)字节暑假实习二面(已挂)
  • (zhuan) 一些RL的文献(及笔记)
  • (八)c52学习之旅-中断实验
  • (备忘)Java Map 遍历
  • (分布式缓存)Redis分片集群
  • (附源码)计算机毕业设计ssm基于B_S的汽车售后服务管理系统
  • (离散数学)逻辑连接词
  • (算法)N皇后问题
  • (转)微软牛津计划介绍——屌爆了的自然数据处理解决方案(人脸/语音识别,计算机视觉与语言理解)...
  • (转)真正的中国天气api接口xml,json(求加精) ...
  • .NET “底层”异步编程模式——异步编程模型(Asynchronous Programming Model,APM)...
  • .NET Core使用NPOI导出复杂,美观的Excel详解
  • .NET学习教程二——.net基础定义+VS常用设置
  • /bin/bash^M: bad interpreter: No such file or directory
  • :O)修改linux硬件时间
  • @cacheable 是否缓存成功_Spring Cache缓存注解
  • [CF703D]Mishka and Interesting sum/[BZOJ5476]位运算
  • [ChromeApp]指南!让你的谷歌浏览器好用十倍!
  • [Godot] 3D拾取
  • [HUBUCTF 2022 新生赛]
  • [iOS]随机生成UUID通用唯一识别码
  • [Java][Android][Process] ProcessBuilder与Runtime差别
  • [mysql]游标和触发器
  • [NOIP2011DAY1P1]铺地毯