Exemple #1
0
class Database(object):
    def __init__(self):
        self.database_config = dict(settings.DATABASE_CONFIG)
        self.database_config['register_hstore'] = False
        self.database_name = self.database_config.pop('name')
        self.database = PostgresqlExtDatabase(self.database_name,
                                              **self.database_config)
        self.app = None
        self.pid = os.getpid()

    def init_app(self, app):
        self.app = app
        self.register_handlers()

    def connect_db(self):
        self._check_pid()
        self.database.connect()

    def close_db(self, exc):
        self._check_pid()
        if not self.database.is_closed():
            self.database.close()

    def _check_pid(self):
        current_pid = os.getpid()
        if self.pid != current_pid:
            logging.info("New pid detected (%d!=%d); resetting database lock.",
                         self.pid, current_pid)
            self.pid = os.getpid()
            self.database._conn_lock = threading.Lock()

    def register_handlers(self):
        self.app.before_request(self.connect_db)
        self.app.teardown_request(self.close_db)
Exemple #2
0
class Database(object):
    def __init__(self):
        self.database_config = dict(settings.DATABASE_CONFIG)
        self.database_config['register_hstore'] = False
        self.database_name = self.database_config.pop('name')
        self.database = PostgresqlExtDatabase(self.database_name, **self.database_config)
        self.app = None
        self.pid = os.getpid()

    def init_app(self, app):
        self.app = app
        self.register_handlers()

    def connect_db(self):
        self._check_pid()
        self.database.connect()

    def close_db(self, exc):
        self._check_pid()
        if not self.database.is_closed():
            self.database.close()

    def _check_pid(self):
        current_pid = os.getpid()
        if self.pid != current_pid:
            logging.info("New pid detected (%d!=%d); resetting database lock.", self.pid, current_pid)
            self.pid = os.getpid()
            self.database._conn_lock = threading.Lock()

    def register_handlers(self):
        self.app.before_request(self.connect_db)
        self.app.teardown_request(self.close_db)
Exemple #3
0
def test_connect_postgres():
    logger.debug("health: testing postgres connection to %s",
                 settings.POSTGRES_HOST)
    client = PostgresqlExtDatabase(
        settings.POSTGRES_DB,
        user=settings.POSTGRES_USER,
        password=settings.POSTGRES_PASSWORD,
        host=settings.POSTGRES_HOST,
        port=5432,
    )
    client.connect()
    return True, "Postgres db connection success !"
Exemple #4
0
class Database:
    def __init__(self):
        self.db: PostgresqlExtDatabase = None

    def is_closed(self) -> bool:
        if self.db is None:
            return True
        return self.db.is_closed()

    def is_open(self) -> bool:
        if self.db is None:
            return False
        return not self.db.is_closed()

    def close_connection(self) -> None:
        if self.db:
            self.db.close()
            self.db = None

    def open_connection(self) -> None:
        if not jh.is_jesse_project() or jh.is_unit_testing():
            return

        # if it's not None, then we already have a connection
        if self.db is not None:
            return

        options = {
            "keepalives": 1,
            "keepalives_idle": 60,
            "keepalives_interval": 10,
            "keepalives_count": 5
        }

        self.db = PostgresqlExtDatabase(
            ENV_VALUES['POSTGRES_NAME'],
            user=ENV_VALUES['POSTGRES_USERNAME'],
            password=ENV_VALUES['POSTGRES_PASSWORD'],
            host=ENV_VALUES['POSTGRES_HOST'],
            port=int(ENV_VALUES['POSTGRES_PORT']),
            sslmode=ENV_VALUES.get('POSTGRES_SSLMODE', 'disable'),
            **options)

        # connect to the database
        self.db.connect()
Exemple #5
0
from playhouse.postgres_ext import PostgresqlExtDatabase


db = PostgresqlExtDatabase(
    "mega_chat",
    user="******",
    host="localhost",
    port=5432,
    password="******",
)

from data import models

db.connect()
db.create_tables(
    [models.User, models.Message, models.Chat, models.Salt, models.UsersChats]
)
db.close()
Exemple #6
0
UNACCEPTABLE_HTML_TAGS = frozenset((
    "script",
    "noscript",
    "style"
))
ACCEPTABLE_DATA_TYPES = frozenset((
    "asp",
    "aspx",
    "html",
    "htm",
    "php",
    ""
))

db = PostgresqlExtDatabase("nosenew", user="******")
db.connect()


class HashPassedURL(Model):
    url_hash = IntegerField(unique=True)

    class Meta(object):
        database = db
        db_table = "search_hashpassedurl"


class RobotHandler(request.HTTPHandler):
    """
    Inherited HTTPHandler (A class to handle opening of HTTP URLs),
    that check robots.txt
    """
Exemple #7
0
__author__ = 'Ken'

import unittest
import requests

from playhouse.test_utils import test_database
from playhouse.postgres_ext import PostgresqlExtDatabase

from models import Student

TEST_DB = PostgresqlExtDatabase(database='test', user='******')
TEST_DB.connect()
TEST_DB.drop_tables([Student])
TEST_DB.create_tables([Student], safe=True)

STUDENT_DATA = {
    'th_username': '******',
    'email': '*****@*****.**',
    'first_name': 'Ken',
    'last_name': 'Alger',
    'password': '******',
    'github_username': '******',
    'city': 'Keizer',
    'state': 'OR',
    'country': 'USA'
}

STUDENT_LIST = ['kenalger', 'craigsdennis', 'kennethlove']


class StudentModelTestCase(unittest.TestCase):
Exemple #8
0
    # operationstatus template
    # {
    #     'operation': 'gist' or 'pastebin',
    #     # gist params
    #     'description': 'gist description',
    #     'public': true or false,
    #     '<num>name': '<file name>',
    #     '<num>content': '<file content>',
    # }
    class Meta:
        database = pgs_db
        db_table = '__test_pastebot__'


pgs_db.connect()
User.create_table(True)


# TODO: make this DatabaseHandler tornado yieldable class
class DatabaseHandler:
    def __init__(self, username, autosave=True):
        self.user, created = User.get_or_create(
            username=username,
            defaults={
                'gistauth': 'null',
                'pastebinauth':
                '["username", "password"]',  # json.dumps(('username', 'password'))
                'operationstatus': {},
            })
        self.autosave = autosave