當前位置: 首頁>>代碼示例>>Python>>正文


Python mongoengine.connect方法代碼示例

本文整理匯總了Python中mongoengine.connect方法的典型用法代碼示例。如果您正苦於以下問題:Python mongoengine.connect方法的具體用法?Python mongoengine.connect怎麽用?Python mongoengine.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mongoengine的用法示例。


在下文中一共展示了mongoengine.connect方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: establish_mongo_connection

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def establish_mongo_connection():
    mongo_name = os.environ.get('AASM_MONGO_DB_NAME', 'test_acts_as_state_machine')
    mongo_port = int(os.environ.get('AASM_MONGO_DB_PORT', 27017))
    mongoengine.connect(mongo_name, port=mongo_port) 
開發者ID:jtushman,項目名稱:state_machine,代碼行數:6,代碼來源:tests.py

示例2: connect

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def connect():
    global serializer, fernet
    crypto_info = settings.load()['database']['crypto']
    mongo_host = settings.load()['database']['mongo'].get('host', '127.0.0.1')
    mongo_port = settings.load()['database']['mongo'].get('port', '27017')
    serializer = URLSafeSerializer(crypto_info['key'])
    fernet = Fernet(crypto_info['fernet'])
    mongoengine.connect(name, host=mongo_host, port=mongo_port, tz_aware=True) 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:10,代碼來源:database.py

示例3: connect

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def connect(**kwargs):
    """
    Wrapper for mongoengine connect - connects with configuration details.
    """
    name = kwargs.pop('name', settings.database.name)
    host = kwargs.pop('host', settings.database.host)
    port = kwargs.pop('port', settings.database.port)

    return me.connect(name, host=host, port=port, **kwargs)

##########################################################################
## Models
########################################################################## 
開發者ID:DistrictDataLabs,項目名稱:baleen,代碼行數:15,代碼來源:models.py

示例4: connect_to_db

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def connect_to_db(config=None):
    """ connect_to_db at the begin of app initializing
    :param config: loaded config dict
    :return: None
    """
    uri = config.database["uri"]

    logging.critical(f"Connecting to {uri}")
    try:
        connect(host=uri)
        logging.critical("Database connected!")
    except MongoEngineConnectionError:
        logging.fatal("Failed connect to MongoDB!")
        raise 
開發者ID:DurianStallSingapore,項目名稱:Zilliqa-Mining-Proxy,代碼行數:16,代碼來源:basemodel.py

示例5: connect

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def connect():
    import mongoengine
    return mongoengine.connect('discograph') 
開發者ID:josiah-wolf-oberholtzer,項目名稱:discograph,代碼行數:5,代碼來源:__init__.py

示例6: run

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def run(parser, args):
    db_name = '%s-%s' % (DB_PREFIX, args.db_name)
    DB = connect(db_name)
    if args.verbose:
        logger.setLevel(level=logging.DEBUG)
    else:
        logger.setLevel(level=logging.INFO)
    al = AlleleGenerator(
        reference_filepath=args.reference_filepath,
        kmer=args.kmer)
    _variant_ids = get_non_singelton_variants(db_name)
    total = Variant.snps(id__in=_variant_ids).count()
    N = 100
    pages = math.ceil(total / N)
    for page in range(pages):
        logger.info("%i of %i - %f%%" %
                    (page*N, total, round(100*(page*N)/total, 2)))
        for variant in Variant.snps(id__in=_variant_ids).order_by("start").skip(N*page).limit(N):
            # for variant in Variant.snps().order_by("start"):
            variant_panel = make_variant_probe(al, variant, args.kmer, DB=DB)
            for i, ref in enumerate(variant_panel.refs):
                sys.stdout.write(
                    ">ref-%s?var_name=%snum_alts=%i&ref=%s&enum=%i\n" %
                    (variant_panel.variant.var_hash, variant.var_name[:100], len(
                        variant_panel.alts), variant_panel.variant.reference.id, i))
                sys.stdout.write("%s\n" % ref)
            for i, a in enumerate(variant_panel.alts):
                sys.stdout.write(">alt-%s?var_name=%s&enum=%i\n" %
                                 (variant_panel.variant.var_hash, variant.var_name[:100], i))
                sys.stdout.write("%s\n" % a) 
開發者ID:Mykrobe-tools,項目名稱:mykrobe,代碼行數:32,代碼來源:dump.py

示例7: __init__

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def __init__(self, *args, **kwargs):
        if hasattr(current_app.conf, "mongodb_scheduler_db"):
            db = current_app.conf.get("mongodb_scheduler_db")
        elif hasattr(current_app.conf, "CELERY_MONGODB_SCHEDULER_DB"):
            db = current_app.conf.CELERY_MONGODB_SCHEDULER_DB
        else:
            db = "celery"

        if hasattr(current_app.conf, "mongodb_scheduler_connection_alias"):
            alias = current_app.conf.get('mongodb_scheduler_connection_alias')
        elif hasattr(current_app.conf, "CELERY_MONGODB_SCHEDULER_CONNECTION_ALIAS"):
            alias = current_app.conf.CELERY_MONGODB_SCHEDULER_CONNECTION_ALIAS
        else:
            alias = "default"

        if hasattr(current_app.conf, "mongodb_scheduler_url"):
            host = current_app.conf.get('mongodb_scheduler_url')
        elif hasattr(current_app.conf, "CELERY_MONGODB_SCHEDULER_URL"):
            host = current_app.conf.CELERY_MONGODB_SCHEDULER_URL
        else:
            host = None

        self._mongo = mongoengine.connect(db, host=host, alias=alias)

        if host:
            logger.info("backend scheduler using %s/%s:%s",
                        host, db, self.Model._get_collection().name)
        else:
            logger.info("backend scheduler using %s/%s:%s",
                        "mongodb://localhost", db, self.Model._get_collection().name)
        self._schedule = {}
        self._last_updated = None
        Scheduler.__init__(self, *args, **kwargs)
        self.max_interval = (kwargs.get('max_interval')
                             or self.app.conf.CELERYBEAT_MAX_LOOP_INTERVAL or 5) 
開發者ID:zmap,項目名稱:celerybeat-mongo,代碼行數:37,代碼來源:schedulers.py

示例8: create_app

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def create_app(**config_overrides):
    """
    Creates a flask application with the desired configuration settings
    and connects it to the database.
    """
    app = Flask(__name__)

    # Initialize logging
    _configure_logging()

    # Initialize configuration
    app.config.from_object("teamserver.config")
    app.config["MODE"] = MODE

    app.config["MONGODB_SETTINGS"] = {"db": DB_NAME, "host": DB_HOST, "port": DB_PORT}
    if DB_USER and DB_PASS:
        app.config["MONGODB_SETTINGS"]["username"] = DB_USER
        app.config["MONGODB_SETTINGS"]["password"] = DB_PASS

    app.config["CELERY_BROKER_URL"] = CELERY_BROKER_URL
    app.config["CELERY_RESULT_BACKEND"] = CELERY_RESULT_BACKEND

    # Override configuration options
    app.config.update(config_overrides)

    # Initialize DEBUG
    if MODE.upper() == "DEBUG":
        # Enable debug logging
        app.logger.setLevel(logging.DEBUG)

        # Enable profiling
        from werkzeug.contrib.profiler import ProfilerMiddleware

        app.config["PROFILE"] = True
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[50], profile_dir=PROFILE_DIR)

        # Enable mongodb debug toolbar
        from flask_debugtoolbar import DebugToolbarExtension

        app.config["DEBUG_TB_PANELS"] = ["flask_mongoengine.panels.MongoDebugPanel"]
        app.debug_toolbar = DebugToolbarExtension(app)
    else:
        app.logger.setLevel(logging.WARNING)

    # Initialize the database
    try:
        DB.init_app(app)
    except MongoEngineConnectionError as conn_err:
        print(conn_err)
        sys.exit("Could not connect to database.")

    # Import endpoints
    from teamserver.router import API

    app.register_blueprint(API)

    app.logger.info(f"Initialized Arsenal Teamserver [{MODE}]")
    return app 
開發者ID:KCarretto,項目名稱:Arsenal,代碼行數:60,代碼來源:__init__.py

示例9: make_variant_probe

# 需要導入模塊: import mongoengine [as 別名]
# 或者: from mongoengine import connect [as 別名]
def make_variant_probe(al, variant, kmer, DB=None, no_backgrounds=False):
    if no_backgrounds:
        context = []
    else:
        if DB is not None:
            try:
                context = get_context(variant.start, kmer)
            except:
                DB = None
                context = []
                logger.warning(
                    "Could not connect to database. Continuing without using backgrounds")
        else:
            context = []
    if context:
        logger.debug(
            "Found %i variants in context of %s" %
            (len(context), variant))
    variant_probe = None
    contexts_seen_together = seen_together(context)
    alts = []
    for context in contexts_seen_together:
        if context:
            logger.debug("Processing variant:%s with context:%s" % (
                variant, ",".join([str(c) for c in context])))
        else:
            logger.debug("Processing variant:%s " % (variant))
        try:
            panel = al.create(variant, context)
        except ValueError as e:
            pass
            logger.warning("Failed to process variant:%s context:%s. %s" % (
                variant, ",".join([str(c) for c in context]), str(e)))
        else:
            if variant_probe is not None:
                variant_probe.alts.extend(panel.alts)
                variant_probe.refs.extend(panel.refs)
            else:
                variant_probe = panel
    if variant_probe:
        variant_probe.alts = unique(variant_probe.alts)
        variant_probe.refs = unique(variant_probe.refs)
    return variant_probe 
開發者ID:Mykrobe-tools,項目名稱:mykrobe,代碼行數:45,代碼來源:probe_generation.py


注:本文中的mongoengine.connect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。