惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
SegmentFault 最新的问题
Y
Y Combinator Blog
Recorded Future
Recorded Future
博客园 - Franky
I
InfoQ
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
Cyberwarzone
Cyberwarzone
The Register - Security
The Register - Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Cloudbric
Cloudbric
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Check Point Blog
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
U
Unit 42
N
Netflix TechBlog - Medium
The Cloudflare Blog
Spread Privacy
Spread Privacy
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队
T
Troy Hunt's Blog
Engineering at Meta
Engineering at Meta
H
Heimdal Security Blog
TaoSecurity Blog
TaoSecurity Blog
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
B
Blog
S
Securelist
H
Hacker News: Front Page
Google Online Security Blog
Google Online Security Blog
G
Google Developers Blog

Sam's lab

python 100 lines of code, bulk config of network devices (II) - Sam's lab python 100 lines of code, bulk config of network devices (II) - Sam's lab Homelab | files sharing apps — Send&Pingvin Share - Sam's lab Homelab | files sharing apps — Send&Pingvin Share - Sam's lab Homelab | Low-level design—Proxmox - Sam's lab Homelab | Low-level design—Proxmox - Sam's lab Homelab | Low-level design –Nginx Reverse Proxy - Sam's lab Homelab | Low-level design –Nginx Reverse Proxy - Sam's lab Homelab | Architecture Design and Implementation – High-level design - Sam's lab Homelab | Architecture Design and Implementation – High-level design - Sam's lab Typecho | Migrated - Sam's lab Typecho | Migrated - Sam's lab Let’s Encrypt | Wildcard Certificates - Sam's lab Let’s Encrypt | Wildcard Certificates - Sam's lab Python | Monitoring, Alarms - Sam's lab Python | Monitoring, Alarms - Sam's lab PVE | Managing Virtual Machines via rest api - Sam's lab PVE | Managing Virtual Machines via rest api - Sam's lab Python ORM | peewee - Sam's lab
Python ORM | peewee - Sam's lab
sam · 2022-08-06 · via Sam's lab

python使用过程中,难免要用到一些关系型数据库,例如sqlite, mysql, postgresql,而增删查改过程中,字符串的拼接着实让人头大

如果你有用过Django web后端框架,自带的ORM组件简化了数据库的操作,在常规数据库的操作方式上,又抽象了一层,把一个个的数据库文件,一张张的表,抽象为一个个的对象,一个个的 python类;增删查改等等操作,抽象为一个个的函数和属性,以面向对象编程的思路和方式来操作数据库。

这里推荐一个独立的Python ORM库—-peewee,不需要Django环境。

github项目地址:

https://github.com/coleifer/peewee

文档地址:

http://docs.peewee-orm.com/en/latest/peewee/quickstart.html

如果你有使用Django ORM的经验,peewee非常容易理解和上手

创建数据库文件和表:

from peewee import *
import datetime


db = SqliteDatabase('ip_monitor_db.db')

class ip_monitor_db(Model):
    manage_ip = CharField(unique=True)
    online_or_not = BooleanField(default=True)
    monitor_or_not = BooleanField(default=True)
    sent_or_not = BooleanField(default=False)
    last_sent_time = DateTimeField(default=datetime.datetime.now)
    

    class Meta:
        database = db # if there are many databases ,This model uses the "testing.db" database.

class Person(Model):
    name = CharField()
    birthday = DateField()

    class Meta:
        database = db # This model uses the "ip_monitor_db.db" database.

if __name__ == '__main__':
    ############################# create DB and Tables
    db.connect()
    db.create_tables([ip_monitor_db,Person])

插入

     ############################### insert items (2 ways)
     ip1 = ip_monitor_db(manage_ip = 'baidu.com')
     ip1.save()
     ip2 = ip_monitor_db(manage_ip = '114.114.114.114', monitor_or_not = False)
     ip2.save()
     ip3 = ip_monitor_db.create(manage_ip = '100.64.0.1')

查询

    ############################# query items
    # 查询所有
     all = ip_monitor_db.select()
     print(all)
    # 条件查询(2 ways)
     all1 = ip_monitor_db.get(ip_monitor_db.manage_ip == 'baidu.com')
     print(all1)
     all2 = ip_monitor_db.select().where(ip_monitor_db.online_or_not == True)
     all2 = ip_monitor_db.select().where(ip_monitor_db.online_or_not == True).get() # only get the first one element when there are many targets
   # 如果有多条查询结果,可以迭代该结果
    for ip in ip_monitor_db.select():
        print(ip.manage_ip)

    #
    query = ip_monitor_db.select().where(ip_monitor_db.online_or_not == True)
    for element in query:
        print(element.manage_ip, element.last_sent_time)

更新

    ####################################update items
     all4 = ip_monitor_db.get(ip_monitor_db.manage_ip == 'baidu.com')
     all4.manage_ip = '114.114.114.114'
     all4.monitor_or_not = False
     all4.save()
     print(all4.manage_ip)
     print(all4.monitor_or_not)

删除

     ###########################delete items
     all3 = ip_monitor_db.delete().where(ip_monitor_db.monitor_or_not == False).execute()
     print(all3)

其他还有更多,联合查找,排序,外键等等参考官方文档

附上 常规的字符串拼接操作数据库方式,sqlite3为例

from asyncio.windows_events import NULL
import sqlite3
from datetime import datetime, timedelta


def create_tab():
    conn = sqlite3.connect('ip_monitor_db.sqlite3')
    c = conn.cursor()
    #  创建表
    sql = '''
        CREATE TABLE ip_monitor_db(
        ID INTEGER PRIMARY KEY  AUTOINCREMENT,
		manage_ip text NOT NULL UNIQUE,
        online_or_not bool NOT NULL,
		monitor_or_not bool NOT NULL,
        sent_or_not bool NOT NULL,
        last_sent_time datetime NOT NULL)
        '''
    c.execute(sql)
    conn.commit()
    c.close()
    conn.close()


def insert_tab(manage_ip, online_or_not = True, monitor_or_not= True, last_sent_time = datetime.now(), sent_or_not = False):
    conn = sqlite3.connect('ip_monitor_db.sqlite3')
    c = conn.cursor()
    #  插入表
    sql = '''INSERT INTO ip_monitor_db(manage_ip, online_or_not, monitor_or_not, last_sent_time, sent_or_not) VALUES (?,?,?,?,?)'''
    c.execute(sql, (manage_ip, online_or_not, monitor_or_not, last_sent_time, sent_or_not))
    conn.commit()
    c.close()
    conn.close()

def update_tab(manage_ip, online_or_not=NULL, last_sent_time = NULL, sent_or_not = NULL):
    conn = sqlite3.connect('ip_monitor_db.sqlite3')
    c = conn.cursor()
    #  更新表
    sql = '''UPDATE ip_monitor_db SET online_or_not = ?, last_sent_time = ?, sent_or_not = ? WHERE manage_ip = ?'''
    c.execute(sql, (online_or_not, last_sent_time, sent_or_not, manage_ip))
    conn.commit()
    c.close()
    conn.close()

def select_tab(column='*'):
    conn = sqlite3.connect('ip_monitor_db.sqlite3')
    c = conn.cursor()
    #  查询表
    sql = f'''SELECT {column} FROM ip_monitor_db'''
    results = c.execute(sql)
    results_all = results.fetchall()
    return results_all
    conn.commit()
    c.close()
    conn.close()



if __name__ == '__main__':
    #create_tab()
    #insert_tab(manage_ip='baidu.com')
    #insert_tab(manage_ip='114.114.114.114')
    #insert_tab(manage_ip='100.64.0.1')
    print(select_tab('manage_ip'))
    print(select_tab('manage_ip'))

以上

Post Views: 2,846