コード例 #1
0
ファイル: main.py プロジェクト: carriercomm/charla
def setup_database(config, logger):
    if config["embedded"]:
        connection_setup()
        db = get_client()
        db.flushall()

        return db

    dbhost = config["dbhost"]
    dbport = config["dbport"]

    logger.debug(
        "Waiting for Redis Service on {0:s}:{1:d} ...".format(dbhost, dbport)
    )

    waitfor(dbhost, dbport)

    logger.debug(
        "Connecting to Redis on {0:s}:{1:d} ...".format(dbhost, dbport)
    )

    connection_setup(host=dbhost, port=dbport)

    logger.debug("Success!")

    db = get_client()
    db.flushall()

    return db
コード例 #2
0
def register_extensions(app):
    if app.config.get('ELASTICSEARCH_SUPPORT', False):
        es.init_app(app)
    mail.init_app(app)
    redis.init_app(app)

    login_manager.session_protection = 'strong'
    login_manager.login_view = '/admin/login'
    login_manager.init_app(app)
    """init redis connection"""
    redisco.connection_setup(host=app.config['REDIS_CONFIG']['HOST'],
                             port=app.config['REDIS_CONFIG']['PORT'],
                             db=app.config['REDIS_CONFIG']['DB'])

    def filter_func(kv):
        print(kv)

    app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
    from application.services.theme import RedisLoader
    app.jinja_env.loader = RedisLoader()

    from pyjade import Compiler
    Compiler.register_autoclosecode('load')

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects.get_by_id(user_id)

    if not app.config['DEBUG'] and not app.config['TESTING']:
        sentry.init_app(
            app,
            dsn=
            'https://*****:*****@app.getsentry.com/93431'
        )
コード例 #3
0
ファイル: backend.py プロジェクト: rafaelmadeira/elmutt
 def __init__(self):
     self.clients = list()
     self.pubsub = redis.pubsub()
     self.pubsub.subscribe(REDIS_CHAN)
     redis_url = urlparse.urlparse(REDIS_URL)
     redisco.connection_setup(
         host=redis_url.hostname, port=redis_url.port, password=redis_url.password)
コード例 #4
0
def connection_setup(db_url):
    """ Setup DB connnection.
        redis://host:port/testdb
        db_url example: redis://127.0.0.1:6379/0
    """
    match = re.search(r'redis://(?P<host>.*):(?P<port>\d*)/(?P<dbname>.*)', db_url)
    redisco.connection_setup(host=match.group('host'),
                             port=match.group('port'),
                             db=match.group('dbname'))
コード例 #5
0
def connection_setup(db_url):
    """ Setup DB connnection.
        redis://host:port/testdb
        db_url example: redis://127.0.0.1:6379/0
    """
    match = re.search(r'redis://(?P<host>.*):(?P<port>\d*)/(?P<dbname>.*)',
                      db_url)
    redisco.connection_setup(host=match.group('host'),
                             port=match.group('port'),
                             db=match.group('dbname'))
コード例 #6
0
ファイル: tests.py プロジェクト: ulule/gplab
    def setUp(self):
        """Before each test, set up a blank database"""
        gplab.app.config["TESTING"] = True
        gplab.app.config["CSRF_ENABLED"] = False

        connection_setup(host="localhost", port=6379, db=4)

        client = get_client()
        client.flushdb()

        self.app = gplab.app.test_client()
コード例 #7
0
    def test_rediscoConnFaild(self):
        '''
        测试redisco连接失败
        :return:
        '''
        host = 'localhost'
        port = 123
        db = 0
        redisco.connection_setup(host=host, port=port, db=db)

        try:
            redisco.connection.ping()
        except ConnectionError:
            print '错误连接,正常断开...'
コード例 #8
0
ファイル: main.py プロジェクト: prologic/todoapp
def setup_database():
    dbhost = environ.get("REDIS_PORT_6379_TCP_ADDR", "localhost")
    dbport = int(environ.get("REDIS_PORT_6379_TCP_PORT", "6379"))

    print("Waiting for Redis Service on {0:s}:{1:d} ...".format(dbhost, dbport))

    waitfor(dbhost, dbport)

    print("Connecting to Redis on {0:s}:{1:d} ...".format(dbhost, dbport))

    connection_setup(host=dbhost, port=dbport)

    print("Success!")

    db = get_client()

    return db
コード例 #9
0
def setup_database(args, logger):
    dbhost = args.dbhost
    dbport = args.dbport

    logger.debug("Waiting for Redis Service on {0:s}:{1:d} ...".format(
        dbhost, dbport))

    waitfor(dbhost, dbport)

    logger.debug("Connecting to Redis on {0:s}:{1:d} ...".format(
        dbhost, dbport))

    connection_setup(host=dbhost, port=dbport)

    logger.debug("Success!")

    db = get_client()

    return db
コード例 #10
0
ファイル: __init__.py プロジェクト: marconi/devqus
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application. """
    config = Configurator(settings=settings)

    redisco.connection_setup(host=settings.get('redis.host', 'localhost'),
                             port=int(settings.get('redis.port', 6379)),
                             db=int(settings.get('redis.db', 0)))

    # init session
    session_factory = session_factory_from_settings(settings)
    config.set_session_factory(session_factory)

    # templating
    config.include('pyramid_jinja2')

    # include app routes
    config.include('devqus.settings')

    config.add_static_view('static', 'static')  # cache_max_age=3600
    config.scan()
    return config.make_wsgi_app()
コード例 #11
0
ファイル: server.py プロジェクト: carriercomm/udns
def setup_database(args, logger):
    dbhost = args.dbhost
    dbport = args.dbport

    logger.debug(
        "Waiting for Redis Service on {0:s}:{1:d} ...".format(dbhost, dbport)
    )

    waitfor(dbhost, dbport)

    logger.debug(
        "Connecting to Redis on {0:s}:{1:d} ...".format(dbhost, dbport)
    )

    connection_setup(host=dbhost, port=dbport)

    logger.debug("Success!")

    db = get_client()

    return db
コード例 #12
0
ファイル: main.py プロジェクト: spaceone/charla
def setup_database(config, logger):
    dbhost = config["dbhost"]
    dbport = config["dbport"]

    logger.debug(
        "Waiting for Redis Service on {0:s}:{1:d} ...".format(dbhost, dbport)
    )

    waitfor(dbhost, dbport)

    logger.debug(
        "Connecting to Redis on {0:s}:{1:d} ...".format(dbhost, dbport)
    )

    connection_setup(host=dbhost, port=dbport)

    logger.debug("Success!")

    db = get_client()
    db.flushall()

    return db
コード例 #13
0
    def setUp(self):
        '''
        :return:
        '''
        settings.DEBUG = True
        ''' 配置测试用的redis配置信息  '''
        settings.REDIS_HOST = "localhost"
        settings.REDIS_PORT = 8911
        # settings.REDIS_DB = 0
        ''' redisco连接 '''
        settings.rd = redisco.connection_setup(host=settings.REDIS_HOST,
                                               port=settings.REDIS_PORT,
                                               db=settings.REDIS_DB)

        # ''' 额外的redis连接 '''
        self.redis = redis.StrictRedis(host=settings.REDIS_HOST,
                                       port=settings.REDIS_PORT,
                                       db=settings.REDIS_DB)
        ''' 启动服务 '''
        web.config.debug = settings.DEBUG

        self.appM = web.application(URLS, HANDLER, autoreload=False)
        application = self.appM.wsgifunc()

        self.appM.notfound = notfound
        self.appM.internalerror = internalerror
        self.appM.add_processor(web.loadhook(header_html))

        session.init(
            web.session.Session(
                self.appM,
                web.session.DiskStore('sessions'),
                initializer=Initializer(
                    User=models.user.User,
                    UserGroup=models.usergroup.UserGroup,
                    BanLogin=controllers.login_handler.BanLogin,
                    settings=settings,
                    session=session,
                )))
        ''' 校验session, 添加到app的 processor 流程中,顺序需要在 session初始化之后 '''
        self.appM.add_processor(web.loadhook(verify_session))
        ''' 初始化 html 头, 添加到app的 processor 流程中 '''
        self.appM.add_processor(web.loadhook(header_html))

        web.config.session_parameters['cookie_name'] = 'webpy_session_id'
        web.config.session_parameters['cookie_domain'] = None
        web.config.session_parameters['timeout'] = 10
        web.config.session_parameters['ignore_expiry'] = True
        web.config.session_parameters['ignore_change_ip'] = False
        web.config.session_parameters['secret_key'] = 'akdnA0FJsdJFLSlvno92'
        web.config.session_parameters['expired_message'] = 'Session expired'
コード例 #14
0
ファイル: test_counter.py プロジェクト: lamter/WBFSystem
    def setUp(self):
        '''
        :return:
        '''

        ''' 配置测试用的redis配置信息  '''
        settings.REDIS_HOST = "localhost"
        settings.REDIS_PORT = 8911
        settings.REDIS_DB = 0

        ''' redisco连接 '''
        settings.rd = redisco.connection_setup(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)

        ''' 额外的redis连接 '''
        self.redis = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)
コード例 #15
0
ファイル: test_static.py プロジェクト: lamter/WBFSystem
    def setUp(self):
        '''
        :return:
        '''
        settings.IS_UNITTEST = True
        settings.DEBUG = True
        ''' 配置测试用的redis配置信息  '''
        settings.REDIS_HOST = "localhost"
        # settings.REDIS_PORT = 8911
        # settings.REDIS_DB = 0

        ''' redisco连接 '''
        settings.rd = redisco.connection_setup(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)

        # ''' 额外的redis连接 '''
        self.redis = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)

        ''' 启动服务 '''
        web.config.debug = settings.DEBUG

        self.appM = web.application(URLS, HANDLER, autoreload=False)
        application = self.appM.wsgifunc()

        self.appM.notfound = notfound
        self.appM.internalerror = internalerror
        self.appM.add_processor(web.loadhook(header_html))

        session.init(web.session.Session(self.appM, web.session.DiskStore('sessions'), initializer=Initializer(
                                                                                                              User=models.user.User,
                                                                                                              UserGroup=models.usergroup.UserGroup,
                                                                                                              BanLogin=controllers.login_handler.BanLogin,
                                                                                                              settings=settings,
                                                                                                              session=session,
                                                                                                              ))
        )

        ''' 校验session, 添加到app的 processor 流程中,顺序需要在 session初始化之后 '''
        self.appM.add_processor(web.loadhook(verify_session))
        ''' 初始化 html 头, 添加到app的 processor 流程中 '''
        self.appM.add_processor(web.loadhook(header_html))

        web.config.session_parameters['cookie_name'] = 'webpy_session_id'
        web.config.session_parameters['cookie_domain'] = None
        web.config.session_parameters['timeout'] = 10
        web.config.session_parameters['ignore_expiry'] = True
        web.config.session_parameters['ignore_change_ip'] = False
        web.config.session_parameters['secret_key'] = 'akdnA0FJsdJFLSlvno92'
        web.config.session_parameters['expired_message'] = 'Session expired'
コード例 #16
0
 def setUp(self):
     '''
     :return:
     '''
     ''' 配置测试用的redis配置信息  '''
     settings.REDIS_HOST = "localhost"
     settings.REDIS_PORT = 8911
     settings.REDIS_DB = 0
     ''' redisco连接 '''
     settings.rd = redisco.connection_setup(host=settings.REDIS_HOST,
                                            port=settings.REDIS_PORT,
                                            db=settings.REDIS_DB)
     ''' 额外的redis连接 '''
     self.redis = redis.StrictRedis(host=settings.REDIS_HOST,
                                    port=settings.REDIS_PORT,
                                    db=settings.REDIS_DB)
コード例 #17
0
ファイル: record.py プロジェクト: x3n0nme/Hyuga
import re

from redisco import connection_setup, models

from hyuga.lib.option import CONFIG

connection_setup(host=CONFIG.REDIS_SERVER,
                 port=int(CONFIG.REDIS_PROT),
                 db=int(CONFIG.REDIS_DB))


def not_domain_name(field_name, value):
    if isinstance(value, str):
        if not re.match(
                r'^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$',
                value):
            return ((field_name, 'Not domain name'), )


class BaseModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)


class DnsRecord(BaseModel):
    uidentify = models.Attribute(required=True, indexed=True)
    name = models.Attribute(required=True, validator=not_domain_name)
    remote_addr = models.Attribute(required=True)


class HttpRecord(BaseModel):
    uidentify = models.Attribute(required=True, indexed=True)
コード例 #18
0
ファイル: settings.py プロジェクト: mobishift2011/amzn
            {'host_string':'[email protected]', 'port':12355},
        ],
        'POWER_PEERS': [
            {'host_string':'[email protected]', 'port':1230},
            {'host_string':'[email protected]', 'port':1231},
            {'host_string':'[email protected]', 'port':1232},
            {'host_string':'[email protected]', 'port':1233},
        ],
        'TEXT_PEERS': [
            {'host_string':'[email protected]', 'port':1237},
            {'host_string':'[email protected]', 'port':1238},
        ],
        'USE_INDEX': '',
        'MONGODB_HOST': '10.236.137.117',
        'REDIS_HOST': '10.236.137.117',
        'MASTIFF_HOST': "http://integrate.favbuy.org:8001/api/v1"
    },
}

env = os.environ.get("ENV")
if not env:
    env = "DEV"

for key, value in chain(envs['COMMON'].iteritems(), envs[env].iteritems()):
    globals()[key] = value

PEERS = CRAWLER_PEERS + POWER_PEERS + TEXT_PEERS

import redisco
redisco.connection_setup(host=REDIS_HOST)
コード例 #19
0
 code4lib 2012 presentation includes both sources and testing fixures
"""
import redis,config
from redisco import connection_setup
import lib.marc21 as marc21
import lib.frbr_rda as frbr
import lib.mods as mods
from lxml import etree

redis_server = redis.StrictRedis(host=config.REDIS_HOST,
                                 port=config.REDIS_PORT,
                                 db=config.REDIS_CODE4LIB_DB)


connection_setup(host=config.REDIS_HOST,
                 port=config.REDIS_PORT,
                 db=config.REDIS_CODE4LIB_DB)



LOC_MODS_FIXURES = ['modsbook.xml',
                    'modsejournal.xml',
                    'modsmotionpicture.xml',
                    'modsmusic.xml']

LOC_FRBR = []
##for fixure in LOC_MODS_FIXURES:
##    raw_file = open('fixures/%s' % fixure,'rb')
##    mods_file = raw_file.read()
##    raw_file.close()
##    mods_doc = etree.XML(mods_file)
コード例 #20
0
ファイル: client.py プロジェクト: carriercomm/udns
def setup_database(args):
    dbhost = args.dbhost
    dbport = args.dbport

    connection_setup(host=dbhost, port=dbport)
コード例 #21
0
ファイル: models.py プロジェクト: wuhfen/eva
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from accounts.models import CustomUser as User
from assets.models import Server
import uuid
import datetime

import redisco
redisco.connection_setup(host='localhost', port=6379, db=1)

from redisco import models as re_models


class DomainInfo(re_models.Model):
    name = re_models.Attribute(required=True)
    created_at = re_models.DateTimeField(auto_now_add=True)
    res_code = re_models.IntegerField(default=0)
    alert = re_models.BooleanField(default=False)
    new_msg = re_models.BooleanField(default=True)
    address = re_models.ListField(str)
    no_ip = re_models.ListField(str)
    info = re_models.Attribute()


class Business(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4,
                            editable=False,
                            primary_key=True)
コード例 #22
0
ファイル: settings.py プロジェクト: esimionato/Repos.io
WORKER_FETCH_FULL_ERROR_KEY = 'fetch_full_error'

WORKER_UPDATE_RELATED_DATA_KEY = 'update_related_data'
WORKER_UPDATE_RELATED_DATA_SET_KEY = 'update_related_data_set'

WORKER_UPDATE_COUNT_KEY = 'update_count'


# metasettings
try:
    import metasettings
    METASETTINGS_DIR    = os.path.normpath(os.path.join(PROJECT_PATH, 'settings'))
    try:
        from settings_rules import method, rules
    except ImportError, e:
        raise e
    else:
        METASETTINGS_PATTERNS = rules
        METASETTINGS_METHOD = getattr(metasettings, method)
        metasettings.init(globals())
except Exception, e:
    sys.stderr.write("Error while loading metasettings : %s\n" % e )
    try:
        from local_settings import *
    except ImportError, e:
        sys.stderr.write("Error: You should define your own settings, see settings_rules.py.sample (or just add a local_settings.py)\nError was : %s\n" % e)
        sys.exit(1)

import redisco
redisco.connection_setup(**REDIS_PARAMS)
コード例 #23
0
ファイル: redis_dao.py プロジェクト: Xebin/coding
__author__ = "xebin"
import sys

reload(sys)
sys.setdefaultencoding("utf8")
import redisco
from redisco import models

# r = redis.StrictRedis(host='ip',port='6379')
# pool = redis.ConnectionPool(host='ip', port=6379, db=0)
# r = redis.Redis(connection_pool=pool)
#
redisco.connection_setup(host="localhost", port=6379, db=7)
# 182.92.72.69


class Upoi(models.Model):
    latitude = models.FloatField(required=True)
    longitude = models.FloatField(required=True)
    upoiid = models.Attribute(required=True, unique=True)
    user_id = models.Attribute(required=True)
    cluster_type = models.Attribute(required=True)
    poi_address = models.Attribute(required=True)
    created_at = models.DateTimeField(auto_now_add=True)


def insert_upois(userid, upois):
    for upoione in upois:
        upoi = Upoi(
            latitude=upoione.get("location").latitude,
            longitude=upoione.get("location").longitude,
コード例 #24
0
DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
]

INTERNAL_IPS = ('127.0.0.1','::1','61.135.172.68','10.97.32.188','1.15.113.109','61.135.172.68',)

import redisco
#redisco.connection_setup(host='123.206.69.25', port=6379, db=0)
redisco.connection_setup(host='172.31.28.109', port=7000, db=0)
#redisco.connection_setup(host='localhost', port=6379, db=0)
#redisco.connection_setup(host='localhost', port=22121, db=0)
#res = redisco.connection_setup(host='localhost', port=7001, db=0)
#print (pyUsage.get_cur_info(), 'res= ', res)
#from rediscluster import StrictRedisCluster
#startup_nodes = [{"host": "127.0.0.1", "port": "19000"}]
#rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)



コード例 #25
0
ファイル: conn.py プロジェクト: lanix516/happycards
# -*- coding:utf-8 -*-
import redis
import redisco

from redisco import models
redisco.connection_setup(host='127.0.0.1', port=6379, db=8)


class DeskModel(models.Model):
    desk_id = models.Attribute(unique=True)
    desk_owner = models.Attribute()
    desk_points = models.Counter()

    def add_id(self):
        self.desk_id = str(1000+int(self.id))
        self.save()


class PlayerModel(models.Model):
    playerId = models.Attribute()
    player_phone = models.Attribute(required=True)
    player_name = models.Attribute(required=True)
    player_password = models.Attribute()
    last_login = models.DateTimeField()
    player_points = models.Counter()
    player_vip = models.IntegerField(default=0)
    player_desk = models.Attribute()


class CardModel(models.Model):
    card_suit = models.Attribute()
コード例 #26
0
ファイル: models.py プロジェクト: wangfuwen000/lushi8
# coding=utf-8
from __future__ import unicode_literals

import json

from redisco import models

import redisco

from lushi.settings import REDIS_HOST, REDIS_DB, REDIS_PASSWORD

redisco.connection_setup(host=REDIS_HOST, db=REDIS_DB, password=REDIS_PASSWORD)
# redisco.connection_setup(host='127.0.0.1', db=7)

# Create your models here.
# class Chairman(models.Model):
#     # id = models.CharField(primary_key=True, max_length=128)
#     title = models.CharField(max_length=128)
#     name = models.CharField(max_length=128)
#     href = models.TextField(max_length=2048)
#     img = models.TextField(max_length=2048)
#     num = models.IntegerField()
#     desc = models.TextField(max_length=2048)
#     type = models.CharField(max_length=128)
#     avatar = models.TextField(max_length=2048)
#
#     def set_num(self, num):
#         if '万' in num:
#             self.num = round(float(num.replace('万','').replace('\r', '').replace('\n', '')) * 10000)
#         else:
#             self.num = int(num)
コード例 #27
0
# Load from config
REDIS_HOST = app.config['REDIS_HOST']
REDIS_PORT = app.config['REDIS_PORT']
REDIS_DB = app.config['REDIS_DB']
AWS_KEY = app.config['AWS_KEY']
AWS_SECRET_KEY = app.config['AWS_SECRET_KEY']
BUCKET_NAME = app.config['BUCKET_NAME']
LOGOS_BUCKET_NAME = app.config['LOGOS_BUCKET_NAME']
SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME', '')
SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD', '')

redis_url = os.environ.get('REDISTOGO_URL', None)
if redis_url:
    redis_url = urlparse.urlparse(redis_url)
    redisco.connection_setup(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password)
else:
    redisco.connection_setup(host='localhost', port=6379, db=0)

ALLOWED_EXTENSIONS = set(('txt', 'pdf', 'ppt', 'pptx', 'zip', 'tar', 'rar'))
ALLOWED_IMAGE_EXTENSIONS = set(('png', 'jpg'))

################################
####### helper methods #########
################################

def allowed_file(filename, extensions):
    return '.' in filename and \
        filename.rsplit('.', 1)[1] in extensions

コード例 #28
0
ファイル: test_hash.py プロジェクト: serg0987/python
# -*- coding: utf-8 -*-
"""
Created on Jul 27, 2013
filedesc:
@author: serg
"""

from redisco.containers import Hash
import unittest
import time
import redisco
import uuid
from redisco import containers
import collections

redisco.connection_setup(db=123)

class TestModel(unittest.TestCase):
    def setUp(self):
        self.client = redisco.get_client()
        self.client.flushdb()
    
    def create_model(self):
        pass
    
    def test_hash(self):
#         start_time = time.time()
#         while time.time() - start_time < 1:
            print collections.MutableMapping
            id = uuid.uuid4().hex  # @ReservedAssignment
            h = Hash(id, pipeline=True)
コード例 #29
0
ファイル: desk_pool.py プロジェクト: st199051/majiong
# coding=utf-8

import redisco
import random
from redisco import containers
from share.espoirjson import EspoirJson


redis_json = EspoirJson.loads("service_config.json").get("db").get("redis")
redis_config = redis_json.get(redis_json.get("use_env"))
redisco.connection_setup(host=redis_config.get("host"), port=redis_config.get("port")
                         , db=redis_config.get("db"), password=redis_config.get("password"))


class DeskPool(object):
    """
    桌子id池
    """
    POOL_KEY = 'DESK_POOL'

    _instance = {}

    def __init__(self, db=0):
        self.desk_pool = containers.Set(self.POOL_KEY, db=db)

    @classmethod
    def get_instance(cls, db=0):
        if not cls._instance.get(db, None):
            cls._instance[db] = DeskPool()
        return cls._instance[db]
コード例 #30
0
ファイル: __init__.py プロジェクト: Grokzen/redisco
import os
import unittest
from redisco.containerstests import (SetTestCase, ListTestCase, TypedListTestCase, SortedSetTestCase, HashTestCase)
from redisco.models.basetests import (ModelTestCase, DateFieldTestCase, FloatFieldTestCase,
                                      BooleanFieldTestCase, ListFieldTestCase, ReferenceFieldTestCase,
                                      DateTimeFieldTestCase, CounterFieldTestCase, CharFieldTestCase,
                                      MutexTestCase)

import redisco
REDIS_DB = int(os.environ.get('REDIS_DB', 15))  # WARNING TESTS FLUSHDB!!!
REDIS_PORT = int(os.environ.get('REDIS_PORT', 6379))
redisco.connection_setup(host="localhost", port=REDIS_PORT, db=REDIS_DB)

typed_list_suite = unittest.TestLoader().loadTestsFromTestCase(TypedListTestCase)


def all_tests():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(SetTestCase))
    suite.addTest(unittest.makeSuite(ListTestCase))
    suite.addTest(unittest.makeSuite(TypedListTestCase))
    suite.addTest(unittest.makeSuite(SortedSetTestCase))
    suite.addTest(unittest.makeSuite(ModelTestCase))
    suite.addTest(unittest.makeSuite(DateFieldTestCase))
    suite.addTest(unittest.makeSuite(FloatFieldTestCase))
    suite.addTest(unittest.makeSuite(BooleanFieldTestCase))
    suite.addTest(unittest.makeSuite(ListFieldTestCase))
    suite.addTest(unittest.makeSuite(ReferenceFieldTestCase))
    suite.addTest(unittest.makeSuite(DateTimeFieldTestCase))
    suite.addTest(unittest.makeSuite(CounterFieldTestCase))
    #suite.addTest(unittest.makeSuite(MutexTestCase))
コード例 #31
0
_author__ = 'xebin'

#from ..dao import av_dao
import redisco
from redisco import models
import sys
reload(sys)
sys.setdefaultencoding('utf8')

# r = redis.StrictRedis(host='120.27.30.239',port='6379')
# pool = redis.ConnectionPool(host='120.27.30.239', port=6379, db=0)
# r = redis.Redis(connection_pool=pool)
#
redisco.connection_setup(host='127.0.0.1', port=6379, db=10)


class Upoi(models.Model):
    latitude= models.FloatField(required=True)
    longitude= models.FloatField(required=True)
    upoiid=models.Attribute(required=True,unique=True)
    user_id=models.Attribute(required=True)
    cluster_type=models.Attribute(required=True)
    poi_address=models.Attribute(required=True)
    created_at = models.DateTimeField(auto_now_add=True)


def insert_upois (userid,upois):
    for upoione in upois:
        upoi=Upoi(latitude=upoione.get('location').latitude,
                        longitude=upoione.get('location').longitude,
                        upoiid=upoione.id,
コード例 #32
0
# -*- coding: utf-8 -*-
from flask import Flask,send_file, send_from_directory,jsonify
from flask import request
import json,os
import redis
import hashlib
import time
from PIL import Image,ImageDraw,ImageFont
from redisco import models
import redisco
import requests
from flask_socketio import SocketIO, rooms, join_room, leave_room


redisco.connection_setup(host='qianqiulin.com', port=6379, password='******')


app = Flask(__name__)
socketio = SocketIO(app)

r = redis.Redis(host='127.0.0.1', port=6379, password='******')


def md5(strs):
    hl = hashlib.md5()
    hl.update(strs.encode(encoding='utf-8'))
    return hl.hexdigest()


def getAllAppointMentFromRedis(type,area):
    data = r.hgetall(type)
コード例 #33
0
HASH_KEY = ''
VALIDATE_KEY = ''
ENCRYPT_KEY = ''
SECRET_KEY = ''

REDIS_HOST = 'localhost'
REDIS_PW = ''
REDIS_PORT = 8911
REDIS_DB = 1

''' 日志文件 '''
LOG = '../www/log/wbfs.log'

try:
    redisco.connection_setup(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
    if not redisco.connection.ping():
        raise redis.exceptions.ConnectionError('redisco 链接失败!!\n请检查 redis 服务是否启动')
except redis.exceptions.ConnectionError:
    raise redis.exceptions.ConnectionError('redisco 链接失败!!\n请检查 redis 服务是否启动')



def absolute(path):
  """Get the absolute path of the given file/folder.

  ``path``: File or folder.
  """
  import os
  PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
  return os.path.normpath(os.path.join(PROJECT_DIR, path))
コード例 #34
0
import os
import unittest
from redisco.containerstests import (SetTestCase, ListTestCase, TypedListTestCase, 
        SortedSetTestCase, HashTestCase)
from redisco.models.basetests import (ModelTestCase, DateFieldTestCase, FloatFieldTestCase,
        BooleanFieldTestCase, ListFieldTestCase, ReferenceFieldTestCase,
        TimeDeltaFieldTestCase, DateTimeFieldTestCase, CounterFieldTestCase,
        CharFieldTestCase, MutexTestCase)

import redisco
REDIS_DB = int(os.environ.get('REDIS_DB', 15)) # WARNING TESTS FLUSHDB!!!
REDIS_PORT = int(os.environ.get('REDIS_PORT', 6379))
redisco.connection_setup(host="localhost", port=REDIS_PORT, db=REDIS_DB)

typed_list_suite = unittest.TestLoader().loadTestsFromTestCase(TypedListTestCase)

def all_tests():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(SetTestCase))
    suite.addTest(unittest.makeSuite(ListTestCase))
    suite.addTest(unittest.makeSuite(TypedListTestCase))
    suite.addTest(unittest.makeSuite(SortedSetTestCase))
    suite.addTest(unittest.makeSuite(ModelTestCase))
    suite.addTest(unittest.makeSuite(DateFieldTestCase))
    suite.addTest(unittest.makeSuite(FloatFieldTestCase))
    suite.addTest(unittest.makeSuite(BooleanFieldTestCase))
    suite.addTest(unittest.makeSuite(ListFieldTestCase))
    suite.addTest(unittest.makeSuite(ReferenceFieldTestCase))
    suite.addTest(unittest.makeSuite(DateTimeFieldTestCase))
    suite.addTest(unittest.makeSuite(TimeDeltaFieldTestCase))
    suite.addTest(unittest.makeSuite(CounterFieldTestCase))
コード例 #35
0
WORKER_UPDATE_COUNT_KEY = 'update_count'

# sentry
SENTRY_DSN = None
SENTRY_PUBLIC_DSN = None

# metasettings
try:
    import metasettings
    METASETTINGS_DIR = os.path.normpath(os.path.join(PROJECT_PATH, 'settings'))
    try:
        from settings_rules import method, rules
    except ImportError, e:
        raise e
    else:
        METASETTINGS_PATTERNS = rules
        METASETTINGS_METHOD = getattr(metasettings, method)
        metasettings.init(globals())
except Exception, e:
    sys.stderr.write("Error while loading metasettings : %s\n" % e)
    try:
        from local_settings import *
    except ImportError, e:
        sys.stderr.write(
            "Error: You should define your own settings, see settings_rules.py.sample (or just add a local_settings.py)\nError was : %s\n"
            % e)
        sys.exit(1)

import redisco
redisco.connection_setup(**REDIS_PARAMS)
コード例 #36
0
ファイル: app.py プロジェクト: ulule/gplab
from raven.contrib.flask import Sentry

app = Flask(__name__)
app.config.from_object('gplab.settings.Config')


class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]


app.url_map.converters['regex'] = RegexConverter

connection_setup(**app.config['REDIS_CONF'])

assets = Environment(app)
babel = Babel(app)
sentry = Sentry(app=app)

js = Bundle('js/plugins.js', 'js/scripts.js',
            filters='jsmin', output='js/all.js')
assets.register('js_all', js)

css = Bundle('css/landing.css', 'css/generic.css',
            filters='yui_css', output='css/all.css')
assets.register('css_all', css)


@babel.localeselector
コード例 #37
0
"""
  :mod:`marc21` - MARC21 Vocabulary Redis set-up and support
"""
__author__ = 'Jeremy Nelson'

import common,pymarc,sys,time
from redisco import models,connection_setup

connection_setup(host=common.REDIS_HOST,
                 port=common.REDIS_PORT)

MARC21_006_RDF_URL = 'http://metadataregistry.org/vocabulary/show/id/211.rdf'


def load_form_of_material(rdf_url=MARC21_006_RDF_URL):
    common.load_rdf_skos('info.marc21rdf/terms/formofmaterial',rdf_url)


class MARC21Subfield(models.Model):
    """
    MARC Subfield in the Redis datastore
    """
    code = models.Attribute()
    value = models.Attribute()

class MARC21Field(models.Model):
    """
    Basic MARC Field in the Redis datastore
    """
    tag = models.Attribute()
    data = models.Attribute()
コード例 #38
0
#!/usr/bin/env python

from __future__ import print_function

from dnslib import CLASS, QTYPE  # noqa
from redisco import connection_setup, get_client

from udns.server import Zone, Record  # noqa

connection_setup()
db = get_client()
コード例 #39
0
ファイル: flushdb.py プロジェクト: ecrespo/udns
#!/usr/bin/env python


from redisco import connection_setup, get_client


connection_setup()
db = get_client()
db.flushall()
コード例 #40
0
ファイル: client.py プロジェクト: mlytics/udns
def setup_database(args):
    dbhost = args.dbhost
    dbport = args.dbport

    connection_setup(host=dbhost, port=dbport)
コード例 #41
0
ファイル: bm_write.py プロジェクト: cinemascop89/redisco
import random
from redisco import models, connection_setup, get_client
from datetime import datetime
import timeit
from functools import partial

class Person(models.Model):
    first_name = models.Attribute()
    last_name = models.Attribute()
    address = models.Attribute()
    description = models.Attribute()
    created_at = models.DateTimeField(auto_now_add=True)
    date = models.DateTimeField()

if __name__ == '__main__':
    connection_setup(db=11)
    db = get_client()
    db.flushdb()

    def rand_date():
        s = random.randrange(883584000, 1577808000)
        return datetime.fromtimestamp(s)


    def init():
        persons = []
        for i in range(100000):
            p = Person(first_name=random.choice(('Tim', 'Alec', 'Jim')),
                       last_name=random.choice(('Medina', 'Baldwin', "O'brien")),
                       address="36174 Kraig Well",
                       description="cum et corporis hic dolorem ullam omnis aut quis enim quisquam rem earum est commodi at asperiores autem id magni consectetur dignissimos vero ut et perferendis sequi voluptas voluptatibus assumenda molestiae tempore debitis et consequuntur ipsa voluptatum ut facilis officia dolores quia fuga quia aliquam architecto tenetur iure velit dicta ad alias et corrupti est sit quod possimus quasi accusantium est qui totam autem ea optio veritatis et et nostrum modi quibusdam natus laboriosam aut aspernatur et vel eaque soluta rerum recusandae vitae qui quo voluptatem exercitationem deserunt non placeat ut inventore numquam et enim mollitia harum labore deleniti quia doloribus ipsam nisi sed nihil laudantium quas dolor occaecati eum in aut ex distinctio minima quia accusamus ut consequatur eos adipisci repellendus voluptas expedita impedit beatae est fugiat officiis sint minus aliquid culpa libero nihil omnis aperiam excepturi atque dolor sunt reprehenderit magnam itaque repellat provident eos et eum sed odio fugit nesciunt dolorum sapiente qui pariatur sit iusto tempora ipsum maiores dolores nobis doloremque non facere praesentium explicabo aut dolorem qui veniam nemo ut suscipit eveniet voluptatem eligendi esse quis ab eius necessitatibus a delectus repudiandae molestiae vel aut ut qui consequatur quidem perspiciatis qui quaerat saepe neque animi voluptate non omnis in consequatur cupiditate quo ducimus velit rerum dolore nam et quos illum laborum id sunt ea molestias voluptas et est sint quam sit porro sed unde rerum voluptates temporibus odit nulla ratione blanditiis amet voluptatem aut cumque quae iste error similique voluptatem illo maxime reiciendis incidunt"
コード例 #42
0
import unittest,redis,config
from redisco import connection_setup
from lxml import etree
import lib.common as common
import lib.mods  as mods
import lib.namespaces as ns



redis_server = redis.StrictRedis(host=config.REDIS_HOST,
                                 port=config.REDIS_PORT,
                                 db=config.REDIS_TEST_DB)


connection_setup(host=config.REDIS_HOST,
                 port=config.REDIS_PORT,
                 db=config.REDIS_TEST_DB)

mods_file = open('fixures/mods-thesis-cc.xml','rb')
raw_thesis_xml = mods_file.read()
mods_file.close()

class TestThesis(unittest.TestCase):

    def setUp(self):
        mods_doc = etree.XML(raw_thesis_xml)
        self.mods = mods.mods()
        self.mods.load_xml(mods_doc)
        self.maxDiff = None
        self.thesis_note1 = self.mods.notes[0]
        self.thesis_note2 = self.mods.notes[1]
コード例 #43
0
ファイル: settings.py プロジェクト: openov2/gvnfm-vnfmgr
    )
}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DB_NAME,
        'HOST': DB_IP,
        'PORT': DB_PORT,
        'USER': DB_USER,
        'PASSWORD': DB_PASSWD,
    },
}

redisco.connection_setup(host=REDIS_HOST,
                         port=REDIS_PORT,
                         password=REDIS_PASSWD,
                         db=0)
# CACHE_BACKEND = 'redis_cache.cache://%s@%s:%s' % (REDIS_PASSWD, REDIS_HOST, REDIS_PORT)

TIME_ZONE = 'UTC'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
コード例 #44
0
def redis_init(db=0):
    host = config.redis.host
    port = config.redis.port
    pwd = config.redis.pwd

    connection_setup(host=host, port=port, password=pwd, db=db)