import json from typing import Set import peewee as pw from playhouse import shortcuts db = pw.SqliteDatabase(":memory:") class BaseModel(pw.Model): __attr_protected__ = set() __attr_accessible__ = set() class Meta: database = db @classmethod def _filter_attrs(cls, attrs, use_whitelist=True): if use_whitelist: whitelist = cls.__attr_accessible__ - cls.__attr_protected__ return {k: v for k, v in attrs.items() if k in whitelist} else: blacklist = cls.__attr_protected__ - cls.__attr_accessible__ return {k: v for k, v in attrs.items() if k not in blacklist} @classmethod def get_or_create(cls, **kw): if "defaults" in kw: kw["defaults"] = cls._filter_attrs(kw.pop("defaults")) return super().get_or_create(**kw)
import peewee import sys import datetime database = peewee.SqliteDatabase("db.sqlite") class BaseModel(peewee.Model): class Meta: database = database class User(BaseModel): displayname = peewee.CharField() email = peewee.CharField(unique=True) password = peewee.CharField() created = peewee.DateTimeField(default=datetime.datetime.utcnow()) class Poll(BaseModel): name = peewee.CharField() description = peewee.CharField(default="") number = peewee.CharField(unique=True) owner = peewee.ForeignKeyField(User, backref="polls") created = peewee.DateTimeField(default=datetime.datetime.utcnow()) public = peewee.BooleanField(default=True) published = peewee.DateTimeField(default=datetime.datetime.utcnow()) allow_multiple_choices = peewee.BooleanField(default=True) allow_duplicate_answers = peewee.BooleanField(default=False) answer_response = peewee.CharField(default="Thank you for your vote")
class Meta: database = orm.SqliteDatabase('executive.db')
import os.path import peewee as pw db = pw.SqliteDatabase( os.path.join(os.path.dirname(__file__), 'Vortune-data.db')) class Vortune(pw.Model): qqid = pw.IntegerField(default=0, primary_key=True) last_time = pw.TextField() vortune_filepath = pw.TextField() class Meta: database = db def init(): if not os.path.exists(os.path.join(os.path.dirname(__file__), 'qa.db')): db.connect() db.create_tables([Vortune]) db.close() init()
''' This module contains the customer model''' import peewee as p DB = p.SqliteDatabase('customers.db') class BaseModel(p.Model): ''' This class sets up the base model ''' class Meta: #pylint: disable=too-few-public-methods ''' This class is meta of the basemodel ''' database = DB class Customer(BaseModel): ''' This class sets up the customer model ''' customer_id = p.IntegerField(primary_key=True) name = p.CharField(max_length=20) lastname = p.CharField(max_length=20) home_address = p.CharField(max_length=100) phone_number = p.CharField(max_length=10) email_address = p.CharField(max_length=50) status = p.CharField(max_length=8) credit_limit = p.IntegerField() #instantiates customer database DB.create_tables([Customer])
class DBTestCase(unittest.TestCase): TEST_DB = peewee.SqliteDatabase(':memory:') def run(self, result=None): with test_database(self.TEST_DB, (models.User, models.Follower)): super().run(result)
import peewee import os db = peewee.SqliteDatabase(os.getenv("DB_FILE"), threadlocals=True) class Whitelist(peewee.Model): nick = peewee.CharField(unique=True) class Meta: database = db
def __call__(self): return peewee.SqliteDatabase(self.path)
import uuid import peewee from flask import Flask import flask_admin as admin from flask_admin.contrib.peewee import ModelView app = Flask(__name__) app.config['SECRET_KEY'] = '123456790' db = peewee.SqliteDatabase('test.sqlite', check_same_thread=False) class BaseModel(peewee.Model): class Meta: database = db class User(BaseModel): username = peewee.CharField(max_length=80) email = peewee.CharField(max_length=120) def __unicode__(self): return self.username class UserInfo(BaseModel): key = peewee.CharField(max_length=64) value = peewee.CharField(max_length=64)
import peewee from model import Users db = peewee.SqliteDatabase("user_data.db") if __name__ == "__main__": try: db.connect(reuse_if_open=True) models = [Users] db.create_tables(models) db.close() except peewee.OperationalError as error: print(error)
# coding: utf-8 # In[17]: # 连接数据库 import peewee db = peewee.SqliteDatabase('hupu.db') db.connect() # In[18]: # 定义并创建模型 class Post(peewee.Model): class Meta: database = db pid = peewee.IntegerField() title = peewee.CharField() count_reply = peewee.IntegerField() count_view = peewee.IntegerField() status = peewee.IntegerField(default=0) class Reply(peewee.Model): class Meta: database = db post = peewee.ForeignKeyField(Post, backref='replies') uid = peewee.IntegerField() create_time = peewee.DateTimeField()
import peewee as pw db = pw.SqliteDatabase('test.db') class Test(pw.Model): pid = pw.IntegerField(primary_key=True) content = pw.TextField() vcontent = pw.IntegerField(default=1) class Meta: database = db if __name__ == '__main__': db.connect() db.create_tables([Test]) db.close()
def __init__(self, database_name): self.database_name = peewee.SqliteDatabase(database_name)
import peewee db = peewee.SqliteDatabase("events.db") class EventsList(peewee.Model): event_name = peewee.TextField() class Meta: #to specify the database to which the tables belong database = db class ParticipantList(peewee.Model): participant_name = peewee.TextField() event_name = peewee.ForeignKeyField(EventsList) class Meta: database = db db.connect() db.create_tables([EventsList, ParticipantList])
import peewee import sqlite3 file = 'countries.db' db = peewee.SqliteDatabase(file) class Pais(peewee.Model): nombre = peewee.TextField() lenguajes = peewee.TextField() continente = peewee.TextField() capital = peewee.TextField() zona = peewee.TextField() class Meta: database = db db_table = 'Country' def count_paises(): db.connect() total = Pais.select().count() db.close() return total def data_countries(pais='Mexico'): conexion = sqlite3.connect(file) cursor = conexion.cursor() datos = cursor.execute(
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import peewee root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) db_path = os.path.join(root_path, "data/desktop/desktop2014.db") #desktop_db = peewee.SqliteDatabase(db_path) desktop_db = peewee.SqliteDatabase(db_path, autocommit=False) class Package(peewee.Model): pkg_name = peewee.CharField() display_flag = peewee.BooleanField() first_category_name = peewee.CharField() second_category_name = peewee.CharField() start_pkg_names = peewee.CharField() class Meta: database = desktop_db class Desktop(peewee.Model): desktop_path = peewee.CharField()
import peewee import datetime from mailchimp3 import MailChimp db = peewee.SqliteDatabase('db_otaku.db') # usamos orm peewee class Animes(peewee.Model): # animes title = peewee.TextField() episodes = peewee.IntegerField() duration = peewee.TextField() rating = peewee.TextField() synopsis = peewee.TextField() image_url = peewee.TextField() status = peewee.TextField() class Meta: database = db db_table = 'ANIME' class Mangas(peewee.Model): # mangas title = peewee.TextField() status = peewee.TextField() image_url = peewee.TextField() synopsis = peewee.TextField() chapters = peewee.IntegerField() class Meta:
import peewee as pw db = pw.SqliteDatabase('database.db') def initialize(): Author.create_table(fail_silently=True) Book.create_table(fail_silently=True) class BaseModel(pw.Model): class Meta: database = db class Author(BaseModel): name = pw.CharField(max_length=100) birth_day = pw.DateField() country = pw.CharField(max_length=100) class Book(BaseModel): title = pw.CharField(max_length=100) year = pw.IntegerField() author = pw.ForeignKeyField(Author)
+------------------------------------------------------------------------------------------------------------------------------------+ | | | Module Name : Models | | Module Purpose : Mysql Database Design , and model relationship , for database functioning | | Inputs : ORM class | | Outputs : Create code , database Object | | Author : Borbolla Automation Inc | | Email : [email protected] | | webpage : www.borbolla-automation.com | +------------------------------------------------------------------------------------------------------------------------------------+ """ import peewee import datetime database = peewee.SqliteDatabase("QR_code.db") #database = peewee.MySQLDatabase(host = "0.tcp.ngrok.io" , port = 17199 , user = "******" , password = "******" , database = "converter_hsg") class BaseModel(peewee.Model): class Meta: database = database class CastingCode(BaseModel): #str_code = peewee.CharField(max_length = 20 , primary_key = True ,null = False , unique = True) casting_code = peewee.CharField(max_length=26, null=False, unique=True) #code_from_probe = peewee.CharField(max_length = 20 ,null = True) code_engraved = peewee.BooleanField(index=True, null=True, default=0,
from datetime import datetime from decimal import Decimal __author__ = 'kenneth' import peewee db = peewee.SqliteDatabase('bet.sqlite3', threadlocals=True) class ModelStuff(peewee.Model): class Meta: database = db class User(ModelStuff): iid = peewee.IntegerField() username = peewee.CharField() password = peewee.CharField() email = peewee.CharField() role = peewee.CharField() joined_on = peewee.DateTimeField() def __unicode__(self): return self.username class Match(ModelStuff): iid = peewee.IntegerField(unique=True) homeTeam = peewee.CharField(max_length=10) awayTeam = peewee.CharField(max_length=10) startTime = peewee.DateTimeField()
def draw_mustache(image, x, y, w, h): mw = w * 2 // 5 mh = h // 10 mx = x + w // 2 - mw // 2 my = y + h * 2 // 3 # cv2.rectangle(image, (mx, my), (mx+mw, my+mh), (255, 255, 0), 10) hair_w = max(mw // 20, 1) for dx in range(mw // hair_w): cv2.line(image, (mx + hair_w * dx, my), (mx + hair_w * (dx + 1), my + mh), (0, 0, 0), 1) cv2.line(image, (mx + hair_w * dx, my + mh), (mx + hair_w * (dx + 1), my), (0, 0, 0), 1) database = peewee.SqliteDatabase("external_data/Mustached.db") class Mustached(peewee.Model): name = peewee.CharField() class Meta: database = database Mustached.create_table() # Шаг 2 - распознаем лица for image_path in downloaded_files: face_cascade = cv2.CascadeClassifier(
from dtalk.utils.threads import threaded from dtalk.utils import six from dtalk.models import signals from dtalk.models.db import Model from sleekxmpp.jid import JID from dtalk.dispatch import receiver import dtalk.xmpp.signals as xmpp_signals USER_DB_VERSION = "0.1" COMMON_DB_VERSION = "0.1" logger = logging.getLogger('models.Model') DEFAULT_GROUP = '我的好友' user_db = pw.SqliteDatabase(None, check_same_thread=False, threadlocals=True) common_db = pw.SqliteDatabase(None, check_same_thread=False, threadlocals=True) user_db_init_finished = False common_db_init_finished = False def check_user_db_inited(): return user_db_init_finished def check_common_db_inited(): return common_db_init_finished @contextmanager
import peewee from swagger_server.__main__ import db_conn db = peewee.SqliteDatabase(db_conn) class BaseModel(peewee.Model): """Classe model base""" class Meta: # Indica em qual banco de dados a tabela # 'author' sera criada (obrigatorio). Neste caso, # utilizamos o banco 'codigo_avulso.db' criado anteriormente database = db
import peewee db = peewee.SqliteDatabase('database.db') class Value(peewee.Model): id = peewee.AutoField() name = peewee.CharField(verbose_name='Название') value = peewee.FloatField(verbose_name='Значение') date = peewee.DateField(verbose_name='Дата') class Meta: database = db if __name__ == '__main__': Value.create_table()
from managers import hardwareevents, cloudevents class deviceManager(BaseManager): pass # Read the Config File c = ConfigHelper( 'C:\\shunya\\IOT.Device.SmartTrack\\CONFIG_FILES\\Demo_Route_drop_10_tst.INI' ) log = LoggingHelper(ConfigHelper.logconfig.disabled, ConfigHelper.logconfig.logtoconsole) # Initialize the Database Specified as per the config file localdb = pw.SqliteDatabase(ConfigHelper.dbfile) log.info("setiing up Database file ") md.proxy.initialize(localdb) log.info("Database initialize") md.devicedata.create_table(True) log.info("Creating table") cm = cloudmanager(log) log.info("cloud manager class object created") hardmamanger = hardwaremanager(log) log.info("hardware manager class object created") #self.events=hardwareevents()
from datetime import timedelta from functools import wraps import falcon from falcon_oauth.provider.oauth2 import OAuthProvider from falcon_oauth.utils import utcnow import peewee from dateutil import parser db = peewee.SqliteDatabase(':memory:') class DateTimeField(peewee.DateTimeField): # Sqlite does not parse offset in datetime def python_value(self, value): if value: return parser.parse(value) return value class BaseModel(peewee.Model): class Meta: database = db class User(BaseModel): username = peewee.CharField(max_length=100) def check_password(self, password): return password != 'wrong'
import peewee as orm db = orm.SqliteDatabase('executive.db') class BaseModel(orm.Model): class Meta: database = orm.SqliteDatabase('executive.db') class Project(BaseModel): name = orm.CharField() parent = orm.ForeignKeyField('self', null=True, backref='children') class Action(BaseModel): name = orm.CharField() deadline = orm.DateTimeField() project = orm.ForeignKeyField(Project, null=True) completed = orm.BooleanField(default=False) context = orm.CharField(null=True) class ScheduledAction(BaseModel): """Scheduled action have a period within which they are active.""" name = orm.CharField() cron = orm.CharField() lastcompleted = orm.DateTimeField(null=True) db.connect()
import peewee from datetime import datetime from bakthat.conf import config, load_config, DATABASE import hashlib import json import sqlite3 import os database = peewee.SqliteDatabase(DATABASE) class JsonField(peewee.CharField): """Custom JSON field.""" def db_value(self, value): return json.dumps(value) def python_value(self, value): try: return json.loads(value) except: return value class BaseModel(peewee.Model): class Meta: database = database @classmethod def create(cls, **attributes): print "create" return super(BaseModel, cls).create(**attributes)
import peewee as pw db = pw.SqliteDatabase('pycamp_projects.db') class Pycampista(pw.Model): username = pw.CharField(unique=True) chat_id = pw.CharField(unique=True) arrive = pw.DateTimeField(null=True) leave = pw.DateTimeField(null=True) class Meta: database = db class Slot(pw.Model): code = pw.CharField() # For example A1 for first slot first day start = pw.DateTimeField() class Meta: database = db class Project(pw.Model): name = pw.CharField() difficult_level = pw.IntegerField(default=1) # From 1 to 3 topic = pw.CharField(null=True) slot = pw.ForeignKeyField(Slot, null=True) class Meta: database = db
Logging 模块基本 设置 ''' logger = logging.getLogger('MagazineDownload') formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s') file_handler = logging.FileHandler('magazinelogger.log') file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.setLevel(logging.INFO) ''' DataBase 设置 ''' db = peewee.SqliteDatabase('magazine.db') class NewsModel(peewee.Model): category = peewee.CharField() date = peewee.DateField() section = peewee.IntegerField() title = peewee.CharField() author = peewee.CharField() class Meta: database = db class Magazine(): """ 作为杂志爬虫基类 """