peewee
import threading from datetime import datetime from peewee import Model, PostgresqlDatabase, AutoField, DateTimeField from playhouse.shortcuts import ReconnectMixin from contextlib import contextmanager from config.env_config import POSTGRES_HOST, POSTGRES_PORT, POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB class ReconnectAsyncPooledPostgresDatabase(ReconnectMixin, PostgresqlDatabase): _instance_lock = threading.Lock() _instance = None db_config = { "host": POSTGRES_HOST, "port": POSTGRES_PORT, "user": POSTGRES_USER, "password": POSTGRES_PASSWORD, "database": POSTGRES_DB, } @classmethod def get_db_instance(cls): with cls._instance_lock: if not cls._instance: cls._instance = cls(**cls.db_config) return cls._instance db = ReconnectAsyncPooledPostgresDatabase.get_db_instance() @contextmanager def get_db(): try: db.connect() yield db finally: if not db.is_closed(): db.close() class BaseModel(Model): id = AutoField(primary_key=True, verbose_name="ID") create_at = DateTimeField(null=False, default=datetime.utcnow, verbose_name="创建时间") # update_at = DateTimeField(null=False, default=datetime.utcnow, verbose_name="更新时间") def save(self, *args, **kwargs): # self.update_at = datetime.utcnow() return super().save(*args, **kwargs) class Meta: database = db
from enum import Enum from peewee import CharField, ForeignKeyField, BigIntegerField, FixedCharField from playhouse.postgres_ext import JSONField from p_database import BaseModel, db class DeviceInfo(BaseModel): device_sn = CharField(max_length=64, verbose_name="设备名称") class Meta: table_name = "e_device_info" class DeviceWarning(BaseModel): time_stamp = BigIntegerField(index=True, verbose_name="报警时间戳") device = ForeignKeyField(DeviceInfo, verbose_name="设备信息") class Meta: table_name = "e_device_warning" if __name__ == '__main__': # db.create_tables([DeviceInfo, DeviceWarning]) device_list = DeviceInfo.select() print(device_list) print(list(device_list)) print(DeviceWarning.select().where(DeviceWarning.device.in_(device_list)).count()) # device_info = DeviceInfo.select().where( # (DeviceInfo.device_sn == "webPc6ZURC") | (DeviceInfo.id == 3) # ).first() # print(device_info) # print(DeviceWarning.select().where((DeviceWarning.device == device_info) & (DeviceWarning.id == 1002)).count()) # DeviceWarning.update(image_path="...").where((DeviceWarning.device == device_info) & (DeviceWarning.id == 1002)).execute() # DeviceWarning.create( # time_stamp=19283343, # device=device_info, # )
一些详细的操作:https://www.cnblogs.com/yxi-liu/p/peewee.html
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/17951745