Пример #1
0
def test_watching():
    # Enable watching
    os.environ['PYCONFIG_ETCD_WATCH'] = 'true'

    pyconfig.Config().clear()
    pyconfig.set('pyconfig.etcd.prefix', 'pyconfig_test/watching')
    pyconfig.reload()

    # Wait for 20ms before writing to ensure the watcher thread is ready
    time.sleep(0.020)

    # Write a new value directly to etcd
    pyconfig.etcd().client.write('pyconfig_test/watching/it.works', 
            pytool.json.as_json(True))

    # Try to get the value... this is a bit sloppy but good luck doing
    # something better
    retry = 50
    while retry:
        retry -= 1
        if pyconfig.get('it.works', None) is not None:
            break
        # Wait 20ms more for it to show up
        time.sleep(0.020)

    eq_(pyconfig.get('it.works', False), True)
Пример #2
0
def test_allow_default():
    eq_(pyconfig.get('test_allow_default1'), None)
    eq_(pyconfig.get('test_allow_default2', default=None), None)
    eq_(
        pyconfig.get('test_allow_default3',
                     'default_value',
                     allow_default=True), 'default_value')
Пример #3
0
 def __init__(self):
     self.host = cfg.get('DBHOST')
     self.port = cfg.get('DBPORT')
     self.name = cfg.get('DBNAME')
     self.collection = cfg.get('COLLECTION')
     self.url = self.get_database_url()
     self.client = MongoClient(self.url)
     self.database = self.client[self.name]
Пример #4
0
 def __init__(self):
     self.host = cfg.get('DBHOST')
     self.port = cfg.get('DBPORT')
     self.name = cfg.get('DBNAME')
     self.collection = cfg.get('COLLECTION')
     self.url = self.get_database_url()
     self.client = MongoClient(self.url)
     self.database = self.client[self.name]
Пример #5
0
def run_tlsanl(pdb_file_path,
               xyzout,
               pdb_id,
               log_out_dir=".",
               verbose_output=False):
    """Run TLSANL.

    A REFMAC file with residual isotropic B-factors and proper TLS descriptions
    is expected. Total isotropic B-factors are written out in the ATOM and
    ANISOU records.

    WARNING: it is assumed that ATOM & HETATM records in the input PDB must
    first be sorted on chain ID and residue number before the TLS ranges
    can be interpreted.

    Detailed documentation for TLSANL can be found at
    http://www.ccp4.ac.uk/html/tlsanl.html.
    """
    _log.info("Preparing TLSANL run...")
    success = False
    keyworded_input = "BINPUT t\nBRESID t\nISOOUT FULL\nNUMERIC\nEND\n"
    p = subprocess.Popen(["tlsanl", "XYZIN", pdb_file_path, "XYZOUT", xyzout],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    (stdout, stderr) = p.communicate(input=keyworded_input)
    try:
        with open(os.path.join(log_out_dir, pyconfig.get("TLSANL_LOG")),
                  "w") as tlsanl_log:
            tlsanl_log.write(stdout)
            if verbose_output:
                print(stdout)
        with open(os.path.join(log_out_dir, pyconfig.get("TLSANL_ERR")),
                  "w") as tlsanl_err:
            tlsanl_err.write(stderr)
            if verbose_output:
                print(stderr)
    except IOError as ex:
        _log.error(ex)
    if p.returncode != 0:
        message = "Problem with TLS group definitions (TLSANL run unsuccessful)"
        write_whynot(pdb_id, message)
        _log.error("{0:s}".format(message))
    elif os.stat(xyzout).st_size <= 2000:
        # from script at http://deposit.rcsb.org/adit/REFMAC.html
        message = "TLSANL problem"
        write_whynot(pdb_id, message)
        _log.error("{0:s}".format(message))
    elif os.stat(os.path.join(log_out_dir,
                              pyconfig.get("TLSANL_ERR"))).st_size > 0:
        message = "Problem with TLS group definitions (TLSANL run unsuccessful)"
        write_whynot(pdb_id, message)
        _log.error("{0:s}".format(message))
    else:
        success = True
        _log.info("TLSANL ran without problems.")
    return success
Пример #6
0
def run_tlsanl(pdb_file_path, xyzout, pdb_id, log_out_dir=".",
               verbose_output=False):
    """Run TLSANL.

    A REFMAC file with residual isotropic B-factors and proper TLS descriptions
    is expected. Total isotropic B-factors are written out in the ATOM and
    ANISOU records.

    WARNING: it is assumed that ATOM & HETATM records in the input PDB must
    first be sorted on chain ID and residue number before the TLS ranges
    can be interpreted.

    Detailed documentation for TLSANL can be found at
    http://www.ccp4.ac.uk/html/tlsanl.html.
    """
    _log.info("Preparing TLSANL run...")
    success = False
    keyworded_input = "BINPUT t\nBRESID t\nISOOUT FULL\nNUMERIC\nEND\n"
    p = subprocess.Popen(["tlsanl", "XYZIN", pdb_file_path, "XYZOUT", xyzout],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    (stdout, stderr) = p.communicate(input=keyworded_input)
    try:
        with open(os.path.join(log_out_dir, pyconfig.get("TLSANL_LOG")),
                  "w") as tlsanl_log:
            tlsanl_log.write(stdout)
            if verbose_output:
                print(stdout)
        with open(os.path.join(log_out_dir, pyconfig.get("TLSANL_ERR")),
                  "w") as tlsanl_err:
            tlsanl_err.write(stderr)
            if verbose_output:
                print(stderr)
    except IOError as ex:
        _log.error(ex)
    if p.returncode != 0:
        message = "Problem with TLS group definitions (TLSANL run unsuccessful)"
        write_whynot(pdb_id, message)
        _log.error("{0:s}".format(message))
    elif os.stat(xyzout).st_size <= 2000:
        # from script at http://deposit.rcsb.org/adit/REFMAC.html
        message = "TLSANL problem"
        write_whynot(pdb_id, message)
        _log.error("{0:s}".format(message))
    elif os.stat(os.path.join(log_out_dir,
                              pyconfig.get("TLSANL_ERR"))).st_size > 0:
        message = "Problem with TLS group definitions (TLSANL run unsuccessful)"
        write_whynot(pdb_id, message)
        _log.error("{0:s}".format(message))
    else:
        success = True
        _log.info("TLSANL ran without problems.")
    return success
Пример #7
0
def _set_config_file(override=None):
    config_home = get_config_dir_base_path(override)
    config_file = os.path.join(config_home, ".ultron8", "cli.yml")
    do_set_flag("config_file", os.path.abspath(config_file))
    clusters_path = os.path.join(pyconfig.get("config_file"), "clusters")
    cache_path = os.path.join(pyconfig.get("config_file"), "cache")
    workspace_path = os.path.join(pyconfig.get("config_file"), "workspace")
    templates_path = os.path.join(workspace_path, "templates")
    do_set_flag("clusters_path", os.path.abspath(clusters_path))
    do_set_flag("cache_path", os.path.abspath(cache_path))
    do_set_flag("workspace_path", os.path.abspath(workspace_path))
    do_set_flag("templates_path", os.path.abspath(templates_path))
Пример #8
0
def test_mongo_uri_with_database():
    if _version._lt('2.6.0'):
        raise SkipTest("Needs version 2.6.0 or later")

    host = pyconfig.get('humbledb.test.db.host', 'localhost')
    port = pyconfig.get('humbledb.test.db.port', 27017)
    uri = 'mongodb://{}:{}/{}'.format(host, port, database_name())

    class DBuri(Mongo):
            config_uri = uri

    with DBuri:
        eq_(DBuri.database.name, database_name())
        eq_(Mongo.context.database.name, database_name())
Пример #9
0
def main():
    """Create mongo-bdb."""

    parser = argparse.ArgumentParser(
        description='Create a MongoDB document store from bdb json files.')
    parser.add_argument(
        '-q', '--quiet',
        help='show less verbose output',
        action='store_true')
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument('-i', '--insall', help='Insert all documents without ' +
                      'checking if they already exist in the store.',
                      action='store_true')
    mode.add_argument('-u', '--upsert', help='Update all documents. If the ' +
                      'document does not yet exist, it is created.',
                      action='store_true')
    args = parser.parse_args()

    # Set the log level depending on verbosity
    if args.quiet:
        LOG.setLevel(logging.INFO)
        LOG.debug('Configured less verbose logging.')

    crawler = DocumentFinder(cfg.get('DOCUMENT_WILDCARD'))
    LOG.info('Preparing to store {0:d} bdb documents...'.format(
        len(crawler.document_paths)))
    database = Database()

    if args.insall:
        insert_all(database, crawler)
    elif args.upsert:
        upsert_all(database, crawler)

    LOG.info('Finished creating mongo-bdb.')
Пример #10
0
def create_strava_authorization():
        id = idgen.getId()
        redirect_url = request.args.get('redirect_uri')

        if redirect_url is None:
            abort(400, 'no redirect_uri parameter provided')

        params = {
                  'client_id': pyconfig.get('strava.client_id'),
                  'redirect_uri': redirect_url,
                  'response_type': 'code',
                  'scope': 'public',
                  'approval_prompt': 'force',
                  'state': id
        }

        auth = {
                'id': id,
                'url': 'https://www.strava.com/oauth/authorize?{params}'.format(params=urllib.urlencode(params)),
                'createdTs': datetime.datetime.utcnow()
        }
        con.authorizations.insert(auth)

        return Response(dumps({
            'id': auth['id'],
            'url': auth['url'],
            'createdTs': str(auth['createdTs'])
        }), mimetype='application/json')
Пример #11
0
def test_get_default_with_various_values():
    eq_(pyconfig.get('default_num', 1), 1)
    eq_(pyconfig.get('default_num', 1.0), 1.0)
    eq_(pyconfig.get('default_none', None), None)
    eq_(pyconfig.get('default_true', True), True)
    eq_(pyconfig.get('default_false', False), False)
    eq_(pyconfig.get('default_unicode', 'Test'), 'Test')
    eq_(pyconfig.get('default_expr', 60*24), 60*24)
    eq_(pyconfig.get('ns.test_namespace', 'pyconfig'), 'pyconfig')
Пример #12
0
def test_get_default_with_various_values():
    eq_(pyconfig.get('default_num', 1), 1)
    eq_(pyconfig.get('default_num', 1.0), 1.0)
    eq_(pyconfig.get('default_none', None), None)
    eq_(pyconfig.get('default_true', True), True)
    eq_(pyconfig.get('default_false', False), False)
    eq_(pyconfig.get('default_unicode', 'Test'), 'Test')
    eq_(pyconfig.get('default_expr', 60 * 24), 60 * 24)
    eq_(pyconfig.get('ns.test_namespace', 'pyconfig'), 'pyconfig')
Пример #13
0
def create_help():
    config = yaml.load(open(pyconfig.get('config_file')))

    class Help(telepot.aio.helper.ChatHandler):
        async def send_help(self, msg):
            """sends the user a combined help message for all plug-ins"""
            retstr = ""
            try:
                retstr += config.__userhelp__
            except AttributeError:
                retstr += ("My help message is unconfigured. To display "
                           "something here, add a docstring to my config.py.")

            userhelps = await fetch_user_help()
            userhelps = await format_user_helps(userhelps)
            retstr += "\n\n{}".format(userhelps)
            await self.sender.sendMessage(retstr, parse_mode='html')

        async def send_paginated_help(self, msg):
            """sends the user a combined help message for all plug-ins"""
            retstr = ""
            try:
                retstr += config.__userhelp__
            except AttributeError:
                retstr += ("My help message is unconfigured. To display "
                           "something here, add a docstring to my config.py.")

            userhelps = await fetch_user_help()
            userhelps = await format_user_helps_paginated(userhelps)

            async def identity(x):
                return x

            await self.send_paginated_message(userhelps, identity)
            # retstr += "\n\n{}".format(userhelps)
            # await self.sender.sendMessage(retstr, parse_mode='html')

        async def cmd_helps(self, msg):
            """sends the user a formatted list of commands for easy registering with
            botfather"""
            await self.sender.sendMessage(
                "Forward the following to the BotFather when he asks for your "
                "list of commands.")
            await self.sender.sendMessage(get_all_cmd_helps(),
                                          parse_mode="HTML")

    class BeardedHelp(Help, PaginatorMixin, BeardChatHandler):
        """Beard for interfacing help functionality with telegram"""
        _timeout = 2
        __commands__ = [
            ('help', 'send_help', "Shows verbose help message."),
            ('helppaged', 'send_paginated_help',
             "Shows verbose help message, paginated."),
            ('cmdhelps', 'cmd_helps', "Lists all commands available."),
        ]

        __userhelp__ = "I'm the default help beard."

    return BeardedHelp
Пример #14
0
def _reload():
    global sites
    cfg_file = pyconfig.get("sunetpages.config",
                            os.environ.get('SUNET_PAGES_CONFIG', None))
    if cfg_file is not None:
        with open(cfg_file) as fd:
            sites = yaml.load(fd)
        logging.debug(sites)
Пример #15
0
 def __enter__(self):
     self.db = dataset.connect(pyconfig.get('db_url'))
     self.db.__enter__()
     self.table = self.db.get_table(self.table_name, **self.kwargs)
     logger.debug(
         "BeardDBTable initalised with: self.table: {}, self.db: {}".format(
             self.table, self.db))
     return self
Пример #16
0
async def make_binary_entry_filename(table, key):
    # Assume the random string has been found, until it's not been found.
    random_string_found = True
    while random_string_found:
        random_string = "".join(
            [random.choice(string.ascii_letters) for x in range(50)])
        for d in os.listdir(pyconfig.get('db_bin_path')):
            if random_string in d:
                break
        else:
            random_string_found = False

    primary_key = "_".join(table.table.table.primary_key.columns.keys())

    return os.path.join(
        pyconfig.get('db_bin_path'),
        "{}_{}_{}_{}.dbbin".format(table.table_name, primary_key, key,
                                   random_string))
Пример #17
0
def test_mongo_uri_database_with_conflict_raises_error():
    if _version._lt('2.6.0'):
        raise SkipTest("Needs version 2.6.0 or later")

    host = pyconfig.get('humbledb.test.db.host', 'localhost')
    port = pyconfig.get('humbledb.test.db.port', 27017)
    uri = 'mongodb://{}:{}/{}'.format(host, port, database_name())

    class DBuri(Mongo):
            config_uri = uri

    from humbledb import Document
    class TestDoc(Document):
        config_database = database_name() + '_is_different'
        config_collection = 'test'

    with DBuri:
        TestDoc.find()
Пример #18
0
 def start(cls):
     """ Public function for manually starting a session/context. Use
         carefully!
     """
     if cls in Mongo.contexts:
         raise NestedConnection("Do not nest a connection within itself, it "
                 "may cause undefined behavior.")
     if pyconfig.get('humbledb.allow_explicit_request', True):
         pass#cls.connection.start_request()
     Mongo.contexts.append(cls)
Пример #19
0
def init_logger(pdb_id, verbose):
    log_name = pdb_id + ".log"
    log_file_path = os.path.join(pyconfig.get("BDB_FILE_DIR_PATH"), log_name)

    fmt = "%(asctime)s | %(levelname)-7s | {0:4s} | %(message)s".format(pdb_id)

    logging.basicConfig(filename=log_file_path,
                        filemode="w",
                        level=logging.INFO if not verbose else logging.DEBUG,
                        format=fmt)
Пример #20
0
 def end(cls):
     """ Public function for manually closing a session/context. Should be
         idempotent. This must always be called after :meth:`Mongo.start`
         to ensure the socket is returned to the connection pool.
     """
     if pyconfig.get('humbledb.allow_explicit_request', True):
         pass#cls.connection.end_request()
     try:
         Mongo.contexts.pop()
     except (IndexError, AttributeError):
         pass
Пример #21
0
 def start(cls):
     """ Public function for manually starting a session/context. Use
         carefully!
     """
     if cls in Mongo.contexts:
         raise NestedConnection("Do not nest a connection within itself, it "
                 "may cause undefined behavior.")
     if (pyconfig.get('humbledb.allow_explicit_request', True)
             and _version._lt('3.0.0')):
         cls.connection.start_request()
     Mongo.contexts.append(cls)
Пример #22
0
    def reload(self):
        self.client = MongoClient(pyconfig.get('mongodb.host', 'strava-mongodb'), int(pyconfig.get('mongodb.port', '27017')))
        self.db = self.client.stravasocial
        self.comparisons = self.db.comparisons
        self.authorizations = self.db.authorizations
        self.roles = self.db.roles

        self.gearman_connections = [
            'strava-gearmand:4730'
        ]
        self.gearmanClient = GearmanClient(self.gearman_connections)
        self.ff = FeatureFlags()
Пример #23
0
async def relay_to_telegram(request):
    command_for_telegram = request.match_info['command']
    key = request.match_info['key']
    with RelayBeard.key_table as table:
            e = table.find_one(key=key)

    session = pyconfig.get('aiohttp_session')
    if e:
        if await request.read():
            data = await request.json()
        else:
            data = None
        async with session.request(
                request.method,
                "https://api.telegram.org/bot{botkey}/{cmd}".format(
                    botkey=pyconfig.get('key'),
                    cmd=command_for_telegram),
                data=data) as resp:
            ret_json = await resp.json()

    return web.json_response(ret_json)
Пример #24
0
 def end(cls):
     """ Public function for manually closing a session/context. Should be
         idempotent. This must always be called after :meth:`Mongo.start`
         to ensure the socket is returned to the connection pool.
     """
     if (pyconfig.get('humbledb.allow_explicit_request', True)
             and _version._lt('3.0.0')):
         cls.connection.end_request()
     try:
         Mongo.contexts.pop()
     except (IndexError, AttributeError):
         pass
Пример #25
0
def test_auto_increment_errors_with_wrong_db():
    if _version._lt('2.6.0'):
        raise SkipTest

    host = pyconfig.get('humbledb.test.db.host', 'localhost')
    port = pyconfig.get('humbledb.test.db.port', 27017)
    uri = 'mongodb://{}:{}/{}'.format(host, port, database_name())

    class DBuri(Mongo):
        config_uri = uri

    class MyDoc2(Document):
        config_database = database_name()
        config_collection = 'test'

        auto = 'a', auto_increment(database_name() + '_is_different', SIDECAR,
                                   'MyDoc2')

    doc = MyDoc2()
    with DBuri:
        doc.auto
Пример #26
0
    def as_live(self):
        """
        Return this call as if it were being assigned in a pyconfig namespace,
        but load the actual value currently available in pyconfig.

        """
        key = self.get_key()
        default = pyconfig.get(key)
        if default:
            default = repr(default)
        else:
            default = self._default() or NotSet()
        return "%s = %s" % (key, default)
Пример #27
0
    def as_live(self):
        """
        Return this call as if it were being assigned in a pyconfig namespace,
        but load the actual value currently available in pyconfig.

        """
        key = self.get_key()
        default = pyconfig.get(key)
        if default:
            default = repr(default)
        else:
            default = self._default() or NotSet()
        return "%s = %s" % (key, default)
Пример #28
0
def test_auto_increment_errors_with_wrong_db():
    if _version._lt('2.6.0'):
        raise SkipTest

    host = pyconfig.get('humbledb.test.db.host', 'localhost')
    port = pyconfig.get('humbledb.test.db.port', 27017)
    uri = 'mongodb://{}:{}/{}'.format(host, port, database_name())

    class DBuri(Mongo):
        config_uri = uri

    class MyDoc2(Document):
        config_database = database_name()
        config_collection = 'test'

        auto = 'a', auto_increment(database_name() + '_is_different', SIDECAR,
                'MyDoc2')


    doc = MyDoc2()
    with DBuri:
        doc.auto
Пример #29
0
    def ensure(self, cls):
        """ Does an ensure_index call for this index with the given `cls`.

            :param cls: A Document subclass

        """
        # Allow disabling of index creation
        if not pyconfig.get('humbledb.ensure_indexes', True):
            return

        # Map the attribute name to its key name, or just let it ride
        index = self._resolve_index(cls)

        # Make the ensure index call
        cls.collection.ensure_index(index, **self.kwargs)
Пример #30
0
def write_whynot(pdb_id, reason):
    """Create a WHY NOT file.

    Return a Boolean.
    """
    directory = pyconfig.get("BDB_FILE_DIR_PATH")
    filename = pdb_id + ".whynot"
    _log.warn("Writing WHY NOT entry.")
    try:
        with open(os.path.join(directory, filename), "w") as whynot:
            whynot.write("COMMENT: " + reason + "\n" +
                         "BDB," + pdb_id + "\n")
            return True
    except IOError as ex:
        _log.error(ex)
        return False
Пример #31
0
    def __init__(self, **keyword_facts):
        self.facts = keyword_facts

        # Look for facts passed in via the environment.
        for key, value in os.environ.items():
            if key.startswith('TEDI_FACT_'):
                fact = key.split('_', 2)[-1]
                self[fact] = value

        if 'image_tag' not in self:
            self['image_tag'] = 'latest'

        # Then look for facts from the command line.
        cli_facts = pyconfig.get(f'cli.flags.fact')
        if cli_facts:
            for fact, value in cli_facts.items():
                self[fact] = value

        # FIXME: Make this something you can switch off or on.
        for var, value in os.environ.items():
            self[f'ENV_{var}'] = value

        logger.debug(f'New Factset: {self}')
Пример #32
0
    def test_import_all_beards_return_None(self):

        pyconfig.set('config_file', os.path.abspath('config.yml.example'))
        with open(pyconfig.get('config_file')) as config_file:
            for k, v in yaml.load(config_file).items():
                pyconfig.set(k, v)
        beard_paths = pyconfig.get('beard_paths')
        pyconfig.set('beard_paths',
                     [os.path.expanduser(x) for x in beard_paths])
        stache_paths = pyconfig.get('stache_paths')
        pyconfig.set('stache_paths',
                     [os.path.expanduser(x) for x in stache_paths])

        for path in pyconfig.get('beard_paths'):
            with PythonPathContext(path):
                for beard in pyconfig.get('beards'):
                    try:
                        importlib.import_module(beard)
                    except ImportError:
                        pass

        # Once the modules are imported (or not), reimporting will return only
        # the module. If we get an ImportError here, then one of them has gone
        # wrong

        successfully_imported_modules = []
        import_exceptions = []
        for beard in pyconfig.get('beards'):
            try:
                mod = importlib.import_module(beard)
                successfully_imported_modules.append(mod)
            except ImportError as e:
                import_exceptions.append(e)

        if import_exceptions:
            self.fail("We got problems: {}".format("\n".join(
                str(e) for e in import_exceptions)))
Пример #33
0
def test_set_and_get():
    pyconfig.set('set_and_get', 'tested')
    eq_(pyconfig.get('set_and_get'), 'tested')
Пример #34
0
def test_localconfig_py_actually_works():
    eq_(pyconfig.get('conf.local', False), True)
    eq_(pyconfig.get('conf.inp1', False), True)
    eq_(pyconfig.get('conf.inp2', False), True)
Пример #35
0
def test_get_no_default():
    pyconfig.get('get_no_default1', allow_default=False)
Пример #36
0
def test_set_and_get():
    pyconfig.set('set_and_get', 'tested')
    eq_(pyconfig.get('set_and_get'), 'tested')
Пример #37
0
 def reload(self):
     self.mongo = MongoClient(pyconfig.get('mongodb.host', 'strava-mongodb'), int(pyconfig.get('mongodb.port', '27017')))
     self.db = self.mongo.stravasocial
     self.plans = self.db.plans
     self.comparisons = self.db.comparisons
Пример #38
0
def get_flag(flag: str, default: Any = None) -> Any:
    """Get a CLI flag from the config."""
    return pyconfig.get(f"cli.flags.{flag}", default)
Пример #39
0
def test_autoloading_etcd_config_works():
    pyconfig.Config().clear()
    pyconfig.set('pyconfig.etcd.prefix', 'pyconfig_test/test2')
    pyconfig.reload()
    eq_(pyconfig.get('pyconfig.string'), 'Value')
    eq_(pyconfig.get('pyconfig.number'), 2)
Пример #40
0
def database_name():
    """ Return the test database name. """
    return pyconfig.get('humbledb.test.db.name', 'nose_humbledb')
Пример #41
0
def test_set_flag_assigns_facts_in_config():
    set_flag('explode', False)
    assert pyconfig.get('cli.flags.explode') is False
Пример #42
0
 def reload(self):
     self.client = MongoClient(pyconfig.get('mongodb.host', 'strava-mongodb'), int(pyconfig.get('mongodb.port', '27017')))
     self.db = self.client.stravasocial
     self.features = self.db.features
Пример #43
0
#Author: Jeff Crocker
#Purpose: The Object Relational Mapping for the Freedom.db

from sqlalchemy.orm import sessionmaker, scoped_session, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
import pyconfig

db = pyconfig.get('database')
path = pyconfig.get('database_path')

engine = create_engine(db + '://' + path)
Base = declarative_base(bind=engine)
Session = scoped_session(sessionmaker(engine))

class Game(Base):
    __tablename__ = 'games'
    id = Column(String, primary_key=True)
    player1 = Column(String)
    player2 = Column(String)
    scenario = Column(String) # this should eventually be tied to a scenario table?
    stacks = relationship("Stack", backref=backref("game", uselist=False))
    planets = relationship("Planet", backref=backref("game", uselist=False))
    phasing_player = Column(String)
    segment = Column(String)

    def __init__(self, id, player1, player2, scenario):
        self.id = id
        self.player1 = player1
        self.player2 = player2
        self.scenario = scenario
Пример #44
0
import logging.handlers

from flask_jwt import JWT, jwt_required, current_user, verify_jwt

log = logging.getLogger("stravacompare")
log.setLevel(logging.DEBUG)

file = logging.handlers.RotatingFileHandler('/data/log/stravacompare-api.log', backupCount=5)
file.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file.setFormatter(formatter)
log.addHandler(file)

app = Flask(__name__)
app.debug = bool(pyconfig.get('api.debug', 'True'))
app.config['SECRET_KEY'] = pyconfig.get('api.secret_key', 'xxx')
app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=31)

if app.config['SECRET_KEY'] == 'xxx':
    log.warn("api.secret_key value is the default development value, please set it to something else")

jwt = JWT(app)

idgen = IdGenerator()

class Container():
    def __init__(self):
        self.reload()

    @pyconfig.reload_hook
Пример #45
0
def test_get_no_default():
    pyconfig.get('get_no_default1', allow_default=False)
Пример #46
0
def test_set_get_change():
    pyconfig.set('set_get_change', 'testing')
    eq_(pyconfig.get('set_get_change'), 'testing')
    pyconfig.set('set_get_change', 'tested')
    eq_(pyconfig.get('set_get_change'), 'tested')
Пример #47
0
#Author: Jeff Crocker
#Purpose: The Object Relational Mapping for the Freedom.db

from sqlalchemy.orm import sessionmaker, scoped_session, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
import pyconfig

db = pyconfig.get('database')
path = pyconfig.get('database_path')

engine = create_engine(db + '://' + path)
Base = declarative_base(bind=engine)
Session = scoped_session(sessionmaker(engine))


class Game(Base):
    __tablename__ = 'games'
    id = Column(String, primary_key=True)
    player1 = Column(String)
    player2 = Column(String)
    scenario = Column(
        String)  # this should eventually be tied to a scenario table?
    stacks = relationship("Stack", backref=backref("game", uselist=False))
    planets = relationship("Planet", backref=backref("game", uselist=False))
    phasing_player = Column(String)
    segment = Column(String)

    def __init__(self, id, player1, player2, scenario):
        self.id = id
        self.player1 = player1
Пример #48
0
 def reload(self):
     self.client = MongoClient(pyconfig.get('mongodb.host', 'strava-mongodb'), int(pyconfig.get('mongodb.port', '27017')))
     self.db = self.client.stravasocial
     self.comparisons = self.db.comparisons
     self.gmworker = gearman.GearmanWorker(['strava-gearmand:4730'])
Пример #49
0
def test_case_sensitive():
    pyconfig.set('pyconfig.case_sensitive', True)
    pyconfig.set('CaseSensitive', True)
    eq_(pyconfig.get('CaseSensitive'), True)
    eq_(pyconfig.get('casesensitive'), None)
    pyconfig.reload(clear=True)
Пример #50
0
def test_localconfig_py_actually_works():
    eq_(pyconfig.get('conf.local', False), True)
Пример #51
0
def test_case_insensitivity():
    pyconfig.set('SomeSetting', True)
    eq_(pyconfig.get('SomeSetting'), True)
    eq_(pyconfig.get('somesetting'), True)
Пример #52
0
def test_allow_default():
    eq_(pyconfig.get('test_allow_default1'), None)
    eq_(pyconfig.get('test_allow_default2', default=None), None)
    eq_(pyconfig.get('test_allow_default3', 'default_value', allow_default=True),
        'default_value')
Пример #53
0
def _load_and_set_cli_config_opts():
    # Load the config file and put it into pyconfig
    with open(pyconfig.get("config_file")) as config_file:
        for k, v in yaml.load(config_file).items():
            do_set_flag(k, v)
Пример #54
0
def test_set_get_change():
    pyconfig.set('set_get_change', 'testing')
    eq_(pyconfig.get('set_get_change'), 'testing')
    pyconfig.set('set_get_change', 'tested')
    eq_(pyconfig.get('set_get_change'), 'tested')
Пример #55
0
def get_stravadao():
    if current_user is not None and hasattr(current_user, 'access_token'):
        return Strava(current_user.access_token)

    return Strava(pyconfig.get('strava.default_access_token', '7f8e5ab7ec53926c6165c96d64a22a589d8c48b6'))