在Python的Flask框架下使用sqlalchemy库的简单教程


Posted in Python onApril 09, 2015

flask中的sqlalchemy 相比于sqlalchemy封装的更加彻底一些 , 在一些方法上更简单

首先import类库:

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">from flask import Flask 
  from flask.ext.sqlalchemy import SQLAlchemy</span>

 

然后,需要加载 数据库路径

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">mysqlname='<span style="color: rgb(230, 219, 116); font-family: 'Source Code Pro'; font-size: 13pt; background-color: rgb(39, 40, 34);">mysql://user:passwd@127.0.0.1/student?charset=utf8</span>'</span>

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">app = Flask(__name__) 
  app.config['SQLALCHEMY_DATABASE_URI'] = mysqlname 
  db = SQLAlchemy(app)</span>

通过前面两步 ,我们已经让flask和数据库联系到了一起

下面我们要把 flask和具体的表联系在一起、

这样建立一个model模型

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">class User(db.Model): 
   
    """存储 每种报警类型的数量 , 以 分钟 为单位进行统计 
    :param source: string ,报警来源 
    :param network_logic_area: string ,该报警所属的逻辑网络区域 
    :param start_time: datetime , 报警发生时间 
    """ 
   
    __tablename__ = 'hello' 
    id = db.Column(db.Integer , primary_key = True) 
    source = db.Column(db.String(255) ) 
    network_logic_area = db.Column(db.String(255) ) 
    start_time = db.Column(db.DateTime) 
    count = db.Column(db.Integer) 
   
    def __init__(self , source , network_logic_area , start_time , count): 
      self.source = source 
      self.network_logic_area = network_logic_area 
      self.start_time = start_time 
      self.count = count 
   
    def alter(self): 
      self.count += 1;</span>

上面这个代码,就让falsk和具体的表hello联系在了一起

在这个类中 ,我们首先要指定表,然后把这个表中的列都列出来,最后定义一个 初始化函数 , 让后面插入数据使用

现在开始具体的数据库操作:

1、insert

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">    p = User(........) 
      db.session.add(p) 
      db.session.commit()</span>

通过 类User构造了一条数据

2、find

用主键获取数据:
Code example:

User.query.get(1)

<User
 u'admin'>

通过一个精确参数进行反查:
Code example:

peter
=

User.query.filter_by(username='peter').first() 
#注意:精确查询函数query.filter_by(),是通过传递参数进行查询;其他增强型查询函数是query.filter(),通过传递表达式进行查询。

print(peter.id) 
#如果数据不存在则返回None

模糊查询:
Code example:
 

User.query.filter(User.email.endswith('@example.com')).all()

[<User
 u'admin'>,
 <User u'guest'>]

逻辑非1:
Code example:
 

peter
=

User.query.filter(User.username
 !=

'peter').first()

print(peter.id)

逻辑非2:
Code example:
 

from

sqlalchemy import

not_

peter
=

User.query.filter(not_(User.username=='peter')).first()

print(peter.id)

逻辑与:
Code example:

from

sqlalchemy import

and_

peter
=

User.query.filter(and_(User.username=='peter',
 User.email.endswith('@example.com'))).first()

print(peter.id)

逻辑或:
Code example:

from

sqlalchemy import

or_

peter
=

User.query.filter(or_(User.username
 !=

'peter',
 User.email.endswith('@example.com'))).first()

print(peter.id)

filter_by:这个里面只能放具体放入条件,不能放一个复杂的计算 ,

filter: 这个里面可以放一些复杂的计算

.first:取第一条数据

.all:取出所有数据

还有一个其他的方法,可以进行排序、计数之类的操作

3、使用sql语句

可以通过 前面构造的 db 直接使用sql的原生语句

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">insert_table.db.engine.execute(' ..... ')</span>

4、delete

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">me = User(........)</span>

在CODE上查看代码片派生到我的代码片

<span style="font-size:18px;">db.session.delete(me) 
  db.session.commit()</span>

5、更新数据

Code example:
 
u
=

User.query.first()

u.username
=

'guest' 
#更新数据和变量赋值那么简单,但必须是通过查询返回的对象。

db.session.commit()
Python 相关文章推荐
Python提示[Errno 32]Broken pipe导致线程crash错误解决方法
Nov 19 Python
Python Requests安装与简单运用
Apr 07 Python
Python 获取当前所在目录的方法详解
Aug 02 Python
Python二叉树的定义及常用遍历算法分析
Nov 24 Python
用Django实现一个可运行的区块链应用
Mar 08 Python
解决Django的request.POST获取不到内容的问题
May 28 Python
python模块之subprocess模块级方法的使用
Mar 26 Python
python词云库wordCloud使用方法详解(解决中文乱码)
Feb 17 Python
Python argparse模块使用方法解析
Feb 20 Python
Python模块/包/库安装的六种方法及区别
Feb 24 Python
pytorch加载语音类自定义数据集的方法教程
Nov 10 Python
Python time库的时间时钟处理
May 02 Python
详解Python中的正则表达式的用法
Apr 09 #Python
Python中几种操作字符串的方法的介绍
Apr 09 #Python
详解Python中的__new__()方法的使用
Apr 09 #Python
Python中动态获取对象的属性和方法的教程
Apr 09 #Python
详解Python中的循环语句的用法
Apr 09 #Python
python3简单实现微信爬虫
Apr 09 #Python
初步理解Python进程的信号通讯
Apr 09 #Python
You might like
40个迹象表明你还是PHP菜鸟
2008/09/29 PHP
php计算多维数组中所有值总和的方法
2015/06/24 PHP
PHP的几个常用加密函数
2016/02/03 PHP
Symfony2学习笔记之插件格式分析
2016/03/17 PHP
PHP中__autoload和Smarty冲突的简单解决方法
2016/04/08 PHP
PHP实现倒计时功能
2020/11/16 PHP
一份老外写的XMLHttpRequest代码多浏览器支持兼容性
2007/01/11 Javascript
jquery 选择器部分整理
2009/10/28 Javascript
jQuery拖动元素并对元素进行重新排序
2015/12/30 Javascript
jQuery获取checkbox选中的值
2016/01/28 Javascript
浅谈JQuery+ajax+jsonp 跨域访问
2016/06/25 Javascript
jQuery实现文字自动横移
2017/01/08 Javascript
js Canvas绘制圆形时钟效果
2017/02/17 Javascript
JS实现仿饿了么在浏览器标签页失去焦点时网页Title改变
2017/06/01 Javascript
新手如何快速理解js异步编程
2019/06/24 Javascript
node.js中npm包管理工具用法分析
2020/02/14 Javascript
JS前端模块化原理与实现方法详解
2020/03/17 Javascript
python服务器端收发请求的实现代码
2014/09/29 Python
Python获取DLL和EXE文件版本号的方法
2015/03/10 Python
在Python的Django框架中用流响应生成CSV文件的教程
2015/05/02 Python
python通过函数属性实现全局变量的方法
2015/05/16 Python
Python+MongoDB自增键值的简单实现
2016/11/04 Python
python如何代码集体右移
2020/07/20 Python
python删除文件、清空目录的实现方法
2020/09/23 Python
python集合的新增元素方法整理
2020/12/07 Python
英国女士家居服网站:hush
2017/08/09 全球购物
美国女孩洋娃娃店:American Girl
2017/10/24 全球购物
九年级数学教学反思
2014/02/02 职场文书
企业内控岗位的职责
2014/02/07 职场文书
《中国梦我的梦》中学生演讲稿
2014/08/20 职场文书
钱学森观后感
2015/06/04 职场文书
子女赡养老人协议书
2016/03/23 职场文书
2019新员工心得体会
2019/06/25 职场文书
php 文件上传至OSS及删除远程阿里云OSS文件
2021/07/04 PHP
pandas数值排序的实现实例
2021/07/25 Python
mongodb的安装和开机自启动详细讲解
2021/08/02 MongoDB