Exemple #1
0
import peewee
from playhouse.postgres_ext import PostgresqlExtDatabase

psql_db = PostgresqlExtDatabase('simple_plotdata', user='******', password='******')


class Family(peewee.Model):
    """
    ORM model of the Family table
    """
    name = peewee.CharField()

    class Meta:
        database = psql_db


if __name__ == '__main__':
    for art in Family.select():
        print(art.name)
Exemple #2
0
from typing import Dict, Iterable

import peewee
from playhouse.postgres_ext import BinaryJSONField, PostgresqlExtDatabase
from playhouse.shortcuts import model_to_dict

from robotoff import settings
from robotoff.utils.types import JSONType

db = PostgresqlExtDatabase(
    settings.DB_NAME,
    user=settings.DB_USER,
    password=settings.DB_PASSWORD,
    host=settings.DB_HOST,
    port=5432,
)


def batch_insert(model_cls, data: Iterable[Dict], batch_size=100) -> int:
    rows = 0
    inserts = []

    for item in data:
        inserts.append(item)
        rows += 1

        if rows % batch_size == 0:
            model_cls.insert_many(inserts).execute()
            inserts = []

    if inserts:
Exemple #3
0
# lignes = fichier.readlines()
# liste = []

# for ligne in lignes:
#     if ligne != '\\\n':
#         lignepropre = ligne.replace("\\", "")
#         lignepropre = lignepropre.replace("\n", "")
#         lignepropre = lignepropre.replace("}", "")
#         liste += [lignepropre]

#aprés lecture de ce fichier une connexion est initialisé

db = PostgresqlExtDatabase(host='localhost',
                           database='immo',
                           user='******',
                           password='******',
                           port=5432)


class BaseModel(Model):
    class Meta:
        database = db


class Logement(BaseModel):

    id_logement = AutoField()
    id_type = IntegerField()
    surface = IntegerField()
    nb_chambre = IntegerField()
"""
Postgresql settings for peewee mappings.
"""
from playhouse.postgres_ext import PostgresqlExtDatabase

from common.config import Config

CFG = Config()

DB = PostgresqlExtDatabase(
    CFG.db_name,
    user=CFG.db_user,
    password=CFG.db_pass,
    host=CFG.db_host,
    port=CFG.db_port,
    sslmode=CFG.db_ssl_mode,
    sslrootcert=CFG.db_ssl_root_cert_path,
)
Exemple #5
0
import os
import uuid
import datetime
from peewee import *
from playhouse.postgres_ext import PostgresqlExtDatabase, JSONField
import config

dir_path = os.path.dirname(os.path.realpath(__file__))

DATABASE = SqliteDatabase('{}{}people.db'.format(dir_path, os.path.sep))

psql_db = PostgresqlExtDatabase('my_database',
                                user=config.PGU,
                                password=config.PGP,
                                register_hstore=False,
                                host=config.HOST,
                                port=config.PORT)


class BasePost(Model):
    class Meta:
        database = psql_db


class Charge(BasePost):
    info = JSONField()


class BaseModel(Model):
    class Meta:
        database = psql_db
Exemple #6
0
import json

from peewee import *
from config import *
from playhouse.postgres_ext import PostgresqlExtDatabase, JSONField, ArrayField

db = PostgresqlExtDatabase(bdname,
                           user=bduser,
                           password=bdpassword,
                           host=bdhost,
                           port=bdport,
                           autoconnect=True,
                           autorollback=True)

from models.Films import Films
from models.Users import Users
from models.Dataset import Dataset

# Films.create_table()
# Users.create_table()
# Dataset.create_table()
Exemple #7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setup import *
#DBs
DATADIR = /XXXXXX'

from playhouse.postgres_ext import PostgresqlExtDatabase, BinaryJSONField
db = PostgresqlExtDatabase(database='LiveAI', user='******')
def uuid_generater():
    random.seed()
    return uuid.uuid4()
#     return base64.b64encode('/'.join([datetime.now(JST).strftime('%Y%m%d%H%M%S'), str(os.getpid())]).encode('utf-8'))
###################################################
#
# >>>>>>>>WEBDATA_SQL>>>>>>>>>>>>>>>>>>>>>>>>>>>
#
####################################################
class SQLModel(Model):
    class Meta:
        database = db

class SS(SQLModel):
    url = TextField(null = True)
    text = TextField(null = True)
    time = DateTimeField(null=True, default = datetime.now())
    class Meta:
        db_table = 'ss'
class SSdialog(SQLModel):
    url = TextField(null = True)
    person = TextField(null = True)
    text = TextField(null = True)
Exemple #8
0
redis_kw = 'lsadfkj'

smtp_cfg = {
    'host': "smtp.ym.163.com",
    'user': "******",
    'pass': "******",
    'postfix': 'yunsuan.org',
}

# Used in HTML render files.
cfg = {
    'app_url_name': 'map',
    'DEBUG': True,
    'PORT': '8088',
    'site_type': 2,
}


dbconnect = PostgresqlExtDatabase(
    'maplet',
    user='******',
    password='******',
    host='127.0.0.1',
    autocommit=True,
    autorollback=True
)

router_post = {'1': 'post',
               '2': 'map',
               }
Exemple #9
0
    from playhouse.postgres_ext import PostgresqlExtDatabase
    from peewee import SQL
    from playhouse.postgres_ext import BinaryJSONField, JSONField
    from peewee import TextField, IntegerField, DateTimeField, BooleanField
except ImportError:
    print 'you need install peewee, please run:'
    print 'sudo pip install peewee'
    exit(1)

from db_bz import getDBConf

conf = getDBConf()

psql_db = PostgresqlExtDatabase(conf.db_name,
                                user=conf.user,
                                password=conf.password,
                                host=conf.host,
                                register_hstore=False)

import model_bz


class BaseModel(model_bz.base):
    '''
    >>> BaseModel.drop_table(True)
    '''
    class Meta:
        database = psql_db


class test(BaseModel):
Exemple #10
0
from peewee import Model, CharField, DateTimeField, ForeignKeyField, AutoField, IntegerField, FloatField, BooleanField
from playhouse.postgres_ext import PostgresqlExtDatabase, ArrayField, BlobField

from utils import log

pg_db = PostgresqlExtDatabase('postgres', user='******', password='******',
                              host='tcc_timescaledb', port=5432)


class BaseModel(Model):
    """A base model that will use our Postgresql database"""

    class Meta:
        database = pg_db


class Station(BaseModel):
    name = CharField(primary_key=True, unique=True)
    description = CharField()
    is_training = BooleanField()
    trained_model = BlobField(null=True)  # Trained model for aggregate data


class Observation(BaseModel):
    id_ = AutoField(primary_key=True)
    station = ForeignKeyField(model=Station, backref='observations')
    time = DateTimeField()
    is_training = BooleanField()

    sample_frequency = FloatField()
    sample_count = IntegerField()
Exemple #11
0
}
db_state = ContextVar("db_state", default=db_state_default.copy())


class PeeweeGetterDict(GetterDict):
    def get(self, key: Any, default: Any = None):
        res = getattr(self._obj, key, default)
        if isinstance(res, peewee.ModelSelect):
            return list(res)
        return res


class PeeweeConnectionState(peewee._ConnectionState):
    def __init__(self, **kwargs):
        super().__setattr__("_state", db_state)
        super().__init__(**kwargs)

    def __setattr__(self, name, value):
        self._state.get()[name] = value

    def __getattr__(self, name):
        return self._state.get()[name]


db = PostgresqlExtDatabase(POSTGRES_DB,
                           user=POSTGRES_USER,
                           password=POSTGRES_PASSWORD,
                           host=POSTGRES_HOST,
                           port=POSTGRES_PORT)

db._state = PeeweeConnectionState()
Exemple #12
0
DATABASE_NAME = 'analytics'
DOMAIN = 'http://analytics.yourdomain.com'  # TODO: change me.
JAVASCRIPT = """(function(id){
    var d=document,i=new Image,e=encodeURIComponent;
    i.src='%s/a.gif?id='+id+'&url='+e(d.location.href)+'&ref='+e(d.referrer)+'&t='+e(d.title);
    })(%s)""".replace('\n', '')

# Flask settings.
DEBUG = bool(os.environ.get('DEBUG'))
SECRET_KEY = 'secret - change me'  # TODO: change me.

app = Flask(__name__)
app.config.from_object(__name__)

database = PostgresqlExtDatabase(
    DATABASE_NAME,
    user='******')

class BaseModel(Model):
    class Meta:
        database = database

class Account(BaseModel):
    domain = CharField()

    def verify_url(self, url):
        netloc = urlparse(url).netloc
        url_domain = '.'.join(netloc.split('.')[-2:])  # Ignore subdomains.
        return self.domain == url_domain

class PageView(BaseModel):
Exemple #13
0
import peewee as pw
from settings import get
from playhouse.postgres_ext import PostgresqlExtDatabase, JSONField

db = PostgresqlExtDatabase(
    host=get('POSTGRES_HOST'),
    port=get('POSTGRES_PORT'),
    database=get('POSTGRES_DB'),
    user='******',
    password=get('POSTGRES_PASSWORD')
)


class NetlytModel(pw.Model):
    class Meta:
        database = db
Exemple #14
0
DATABASE_NAME = 'analytics'
DOMAIN = 'http://analytics.yourdomain.com'  # TODO: change me.
JAVASCRIPT = """(function(id){
    var d=document,i=new Image,e=encodeURIComponent;
    i.src='%s/a.gif?id='+id+'&url='+e(d.location.href)+'&ref='+e(d.referrer)+'&t='+e(d.title);
    })(%s)""".replace('\n', '')

# Flask settings.
DEBUG = bool(os.environ.get('DEBUG'))
SECRET_KEY = 'secret - change me'  # TODO: change me.

app = Flask(__name__)
app.config.from_object(__name__)

database = PostgresqlExtDatabase(DATABASE_NAME,
                                 user='******',
                                 threadlocals=True)


class BaseModel(Model):
    class Meta:
        database = database


class Account(BaseModel):
    domain = CharField()

    def verify_url(self, url):
        netloc = urlparse(url).netloc
        url_domain = '.'.join(netloc.split('.')[-2:])  # Ignore subdomains.
        return self.domain == url_domain
from peewee import *
from playhouse.shortcuts import model_to_dict
from playhouse.postgres_ext import PostgresqlExtDatabase
from time import perf_counter

db = PostgresqlExtDatabase(
    "dc_heroes",
    host = "0.0.0.0",
    user = "******",
    password = "******", 
    port = 5432
    )

class SUPER_HEROE(Model):
    id = IntegerField()
    name = TextField()
    full_name = TextField()
    alter_egos = TextField()
    aliases = TextField()
    place_of_birth = TextField()
    first_appearance = TextField()
    publisher = TextField()
    alignment = TextField()
    gender = TextField()
    race = TextField()
    height = TextField()
    weight = TextField()
    eye_color = TextField()
    hair_color = TextField()
    occupation = TextField()
    base = TextField()
Exemple #16
0
from playhouse.postgres_ext import PostgresqlExtDatabase

from configs import DB_NAME, DB_USER, DB_PORT, DB_PASSWORD, DB_HOST

db = PostgresqlExtDatabase(
    database=DB_NAME,
    user=DB_USER,
    port=DB_PORT,
    password=DB_PASSWORD,
    host=DB_HOST,
    register_hstore=False,
)
Exemple #17
0
from playhouse.postgres_ext import Model, CharField, TextField, BooleanField, PostgresqlExtDatabase, UUIDField, ForeignKeyField
from werkzeug.security import generate_password_hash, check_password_hash

db = PostgresqlExtDatabase('test',
                           host='db',
                           user='******',
                           password='******',
                           port='5432')


class BaseModel(Model):
    class Meta:
        database = db


class User(BaseModel):
    login = CharField(unique=True)
    email = CharField(unique=True)
    pw_hash = TextField()
    authenticated = BooleanField(default=False)
    active = BooleanField(default=False)

    def is_authenticated(self):
        return self.authenticated

    def is_active(self):
        return self.active

    def is_anonymous(self):
        return False
Exemple #18
0
DATABASE_NAME = 'analytics'
DOMAIN = 'http://analytics.yourdomain.com'  # TODO: change me.
JAVASCRIPT = """(function(id){
    var d=document,i=new Image,e=encodeURIComponent;
    i.src='%s/a.gif?id='+id+'&url='+e(d.location.href)+'&ref='+e(d.referrer)+'&t='+e(d.title);
    })(%s)""".replace('\n', '')

# Flask settings.
DEBUG = bool(os.environ.get('DEBUG'))
SECRET_KEY = 'secret - change me'  # TODO: change me.

app = Flask(__name__)
app.config.from_object(__name__)

database = PostgresqlExtDatabase(DATABASE_NAME,
                                 register_hstore=True,
                                 user='******')


class BaseModel(Model):
    class Meta:
        database = database


class Account(BaseModel):
    domain = CharField()

    def verify_url(self, url):
        netloc = urlparse(url).netloc
        url_domain = '.'.join(netloc.split('.')[-2:])  # Ignore subdomains.
        return self.domain == url_domain
from peewee import *
from playhouse.shortcuts import model_to_dict
from playhouse.postgres_ext import PostgresqlExtDatabase

db = PostgresqlExtDatabase(
    "dc_heroes",
    host = "dc_db",
    user = "******",
    password = "******", 
    )

class SUPER_HEROE(Model):
    id = IntegerField()
    name = TextField()
    full_name = TextField()
    alter_egos = TextField()
    aliases = TextField()
    place_of_birth = TextField()
    first_appearance = TextField()
    publisher = TextField()
    alignment = TextField()
    gender = TextField()
    race = TextField()
    height = TextField()
    weight = TextField()
    eye_color = TextField()
    hair_color = TextField()
    occupation = TextField()
    base = TextField()
    group_affiliation = TextField()
    relatives = TextField()
Exemple #20
0
import yaml
import slackbot.bot
import peewee
from playhouse.postgres_ext import PostgresqlExtDatabase
from plugins import fakenumbers

# pylint: disable=protected-access

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG = os.path.join(BASE_DIR, '../config.yml')
with open(CONFIG, 'r') as fptr:
    CFG = yaml.load(fptr.read(), Loader=yaml.FullLoader)
DBUSER = CFG['dbuser']
DBPASS = CFG['dbpass']
DB = CFG['db']
PSQL_DB = PostgresqlExtDatabase(DB, user=DBUSER, password=DBPASS)


def user(msg):
    """ Get user from slack message

        :param msg: Slack message
    """
    return msg._client.users[msg._get_user_id()]['name']


def users(msg):
    """ Get all users from slack message
        :param msg: Slack message
    """
    return [j['name'] for i, j in msg._client.users.items()]
Exemple #21
0
from playhouse.postgres_ext import PostgresqlExtDatabase
from utils import config

pg_db = PostgresqlExtDatabase(database=config.DATABASE,
                              user=config.USER,
                              password=config.PASSWORD,
                              host=config.HOST,
                              port=config.PORT)
Exemple #22
0
from peewee import *
from playhouse.shortcuts import model_to_dict
from playhouse.postgres_ext import PostgresqlExtDatabase, ArrayField, BinaryJSONField, BooleanField, JSONField
# support for arrays of uuid
import psycopg2.extras
psycopg2.extras.register_uuid()

from flask import abort
import config

import logging
log = logging.getLogger("db")

database = PostgresqlExtDatabase(config.DATABASE_NAME,
                                 user=config.DATABASE_USER,
                                 password=config.DATABASE_PASSWORD,
                                 host=config.DATABASE_HOST,
                                 port=config.DATABASE_PORT)

# --------------------------------------------------------------------------
# Base model and common methods


class BaseModel(Model):
    """Base class for all database models."""

    # exclude these fields from the serialized dict
    EXCLUDE_FIELDS = []

    def serialize(self):
        """Serialize the model into a dict."""
Exemple #23
0
"""
Postgresql settings for peewee mappings.
"""
import os

from playhouse.postgres_ext import PostgresqlExtDatabase

DB_NAME = os.getenv('POSTGRESQL_DATABASE', "vulnerability").strip()
DB_USER = os.getenv('POSTGRESQL_USER', "ve_db_user_unknown").strip()
DB_PASS = os.getenv('POSTGRESQL_PASSWORD', "ve_db_user_unknown_pwd").strip()
DB_HOST = os.getenv('POSTGRESQL_HOST', "ve_database").strip()
DB_PORT = int(os.getenv('POSTGRESQL_PORT', "5432").strip())

DB = PostgresqlExtDatabase(DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)
Exemple #24
0
redis_kw = 'lsadfkj'

smtp_cfg = {
    'host': "smtp.ym.163.com",
    'user': "******",
    'pass': "******",
    'postfix': 'yunsuan.org',
}

Email_site_name = '云算笔记'
PORT = '8088'

dbconnect = PostgresqlExtDatabase(
    'torcms',
    user='******',
    password='******',
    host='127.0.0.1',
    autocommit=True,
    autorollback=True
)

app_url_name = 'map'

template_dir_name = 'templates'

torlite_template_name = 'tplite'
app_template_name = 'pycate'

lang = 'en_US'

# Used in HTML render files.
Exemple #25
0
from peewee import CharField, Model
from playhouse.postgres_ext import PostgresqlExtDatabase, HStoreField
import urlparse
import ujson as json
import os
from pastebot.config import config

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(config["database_url"])

pgs_db = PostgresqlExtDatabase(url.path[1:],
                               user=url.username,
                               password=url.password,
                               host=url.hostname,
                               port=url.port)


class User(Model):
    username = CharField(unique=True)
    gistauth = CharField()
    pastebinauth = CharField()
    operationstatus = HStoreField()

    # operationstatus template
    # {
    #     'operation': 'gist' or 'pastebin',
    #     # gist params
    #     'description': 'gist description',
    #     'public': true or false,
    #     '<num>name': '<file name>',
    #     '<num>content': '<file content>',
Exemple #26
0
import peewee
import os
import yaml
import traceback
from playhouse.postgres_ext import PostgresqlExtDatabase

import slackbot.bot

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
yaml_loc = os.path.join(BASE_DIR, '../config.yml')
with open(yaml_loc, 'r') as fptr:
    cfg = yaml.load(fptr.read())
dbuser = cfg['dbuser']
dbpass = cfg['dbpass']
db = cfg['db']
psql_db = PostgresqlExtDatabase(db, user=dbuser, password=dbpass)


class JeffCrisis(peewee.Model):
    nick = peewee.CharField()
    datetime = peewee.DateTimeField()
    level = peewee.CharField()

    class Meta:
        database = psql_db


class Level(peewee.Model):
    name = peewee.TextField(unique=True)
    text = peewee.TextField(default='black')
    font = peewee.TextField(default='Lucida Console')
Exemple #27
0
    ColumnFactory,
    DateTimeField,
    DeferredForeignKey,
    ForeignKeyField,
    BigIntegerField,
    ModelSelect,
    ProgrammingError,
    TextField,
    Model,
)
from playhouse.postgres_ext import BinaryJSONField, PostgresqlExtDatabase
from playhouse.signals import Model

import lena_tweets.config

database = PostgresqlExtDatabase(None, autorollback=True)


class ConnectionContext(ContextDecorator):
    db = None
    tables_created = None
    global_in_context = False

    def __init__(self):
        self.dont_close_connection = False

    def __enter__(self):
        if ConnectionContext.global_in_context:
            self.dont_close_connection = True

        if not ConnectionContext.db:
import os, urlparse
from playhouse.postgres_ext import PostgresqlExtDatabase

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])

db = PostgresqlExtDatabase(url.path[1:],
                           user=url.username,
                           host=url.hostname,
                           port=url.port,
                           password=url.password,
                           register_hstore=False)
Exemple #29
0
import os
import peewee as pw
import datetime
from playhouse.postgres_ext import PostgresqlExtDatabase

db = PostgresqlExtDatabase(os.getenv('DATABASE'))


class BaseModel(pw.Model):
    created_at = pw.DateTimeField(default=datetime.datetime.now)
    updated_at = pw.DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        self.updated_at = datetime.datetime.now()
        return super(BaseModel, self).save(*args, **kwargs)

    class Meta:
        database = db
        legacy_table_names = False


class Store(BaseModel):
    name = pw.CharField(unique=True)


class Warehouse(BaseModel):
    store = pw.ForeignKeyField(Store, backref='warehouses')
    location = pw.TextField()


class Product(BaseModel):
Exemple #30
0
from peewee import PostgresqlDatabase, Model, TextField, CharField, DateTimeField, ForeignKeyField, BooleanField, IntegerField, SQL
from playhouse.postgres_ext import PostgresqlExtDatabase  # necessary for full text search
from datetime import datetime
from config import Config
import urllib.parse

db_parsed_url = urllib.parse.urlparse(Config.DATABASE_URL)
username = db_parsed_url.username
password = db_parsed_url.password
database = db_parsed_url.path[1:]
hostname = db_parsed_url.hostname
postgres_db = PostgresqlExtDatabase(database=database,
                                    user=username,
                                    password=password,
                                    host=hostname,
                                    autocommit=True,
                                    autorollback=True,
                                    register_hstore=True)


class User(Model):
    name = TextField(unique=True)
    admin = BooleanField(default=False)
    password = TextField()
    active = BooleanField(default=True)
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)

    def get_id(self):
        return str(self.id)