当前位置: 首页>>代码示例>>Python>>正文


Python code.Code方法代码示例

本文整理汇总了Python中bson.code.Code方法的典型用法代码示例。如果您正苦于以下问题:Python code.Code方法的具体用法?Python code.Code怎么用?Python code.Code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bson.code的用法示例。


在下文中一共展示了code.Code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: eval

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def eval(self, code, *args):
        """**DEPRECATED**: Evaluate a JavaScript expression in MongoDB.

        :Parameters:
          - `code`: string representation of JavaScript code to be
            evaluated
          - `args` (optional): additional positional arguments are
            passed to the `code` being evaluated

        .. warning:: the eval command is deprecated in MongoDB 3.0 and
          will be removed in a future server version.
        """
        warnings.warn("Database.eval() is deprecated",
                      DeprecationWarning, stacklevel=2)

        if not isinstance(code, Code):
            code = Code(code)

        result = self.command("$eval", code, args=args)
        return result.get("retval", None) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:22,代码来源:database.py

示例2: dumps

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def dumps(obj, *args, **kwargs):
    """Helper function that wraps :func:`json.dumps`.

    Recursive function that handles all BSON types including
    :class:`~bson.binary.Binary` and :class:`~bson.code.Code`.

    :Parameters:
      - `json_options`: A :class:`JSONOptions` instance used to modify the
        encoding of MongoDB Extended JSON types. Defaults to
        :const:`DEFAULT_JSON_OPTIONS`.

    .. versionchanged:: 3.4
       Accepts optional parameter `json_options`. See :class:`JSONOptions`.

    .. versionchanged:: 2.7
       Preserves order when rendering SON, Timestamp, Code, Binary, and DBRef
       instances.
    """
    json_options = kwargs.pop("json_options", DEFAULT_JSON_OPTIONS)
    return json.dumps(_json_convert(obj, json_options), *args, **kwargs) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:22,代码来源:json_util.py

示例3: eval

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def eval(self, code, *args):
        """Evaluate a JavaScript expression in MongoDB.

        Useful if you need to touch a lot of data lightly; in such a
        scenario the network transfer of the data could be a
        bottleneck. The `code` argument must be a JavaScript
        function. Additional positional arguments will be passed to
        that function when it is run on the server.

        Raises :class:`TypeError` if `code` is not an instance of
        :class:`basestring` (:class:`str` in python 3) or `Code`.
        Raises :class:`~pymongo.errors.OperationFailure` if the eval
        fails. Returns the result of the evaluation.

        :Parameters:
          - `code`: string representation of JavaScript code to be
            evaluated
          - `args` (optional): additional positional arguments are
            passed to the `code` being evaluated
        """
        if not isinstance(code, Code):
            code = Code(code)

        result = self.command("$eval", code,
                              read_preference=ReadPreference.PRIMARY,
                              args=args)
        return result.get("retval", None) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:29,代码来源:database.py

示例4: __setattr__

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def __setattr__(self, name, code):
        self._db.system.js.save({"_id": name, "value": Code(code)},
                                **self._db._get_wc_override()) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:5,代码来源:database.py

示例5: __getattr__

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def __getattr__(self, name):
        return lambda *args: self._db.eval(Code("function() { "
                                                "return this[name].apply("
                                                "this, arguments); }",
                                                scope={'name': name}), *args) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:7,代码来源:database.py

示例6: where

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def where(self, code):
        """Adds a $where clause to this query.

        The `code` argument must be an instance of :class:`basestring`
        (:class:`str` in python 3) or :class:`~bson.code.Code`
        containing a JavaScript expression. This expression will be
        evaluated for each document scanned. Only those documents
        for which the expression evaluates to *true* will be returned
        as results. The keyword *this* refers to the object currently
        being scanned.

        Raises :class:`TypeError` if `code` is not an instance of
        :class:`basestring` (:class:`str` in python 3). Raises
        :class:`~pymongo.errors.InvalidOperation` if this
        :class:`Cursor` has already been used. Only the last call to
        :meth:`where` applied to a :class:`Cursor` has any effect.

        :Parameters:
          - `code`: JavaScript expression to use as a filter
        """
        self.__check_okay_to_chain()
        if not isinstance(code, Code):
            code = Code(code)

        self.__spec["$where"] = code
        return self 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:28,代码来源:cursor.py

示例7: _get_code

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def _get_code(data, position, as_class, tz_aware, uuid_subtype, compile_re):
    code, position = _get_string(data, position,
                                 as_class, tz_aware, uuid_subtype, compile_re)
    return Code(code), position 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:6,代码来源:__init__.py

示例8: dumps

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def dumps(obj, *args, **kwargs):
    """Helper function that wraps :class:`json.dumps`.

    Recursive function that handles all BSON types including
    :class:`~bson.binary.Binary` and :class:`~bson.code.Code`.

    .. versionchanged:: 2.7
       Preserves order when rendering SON, Timestamp, Code, Binary, and DBRef
       instances. (But not in Python 2.4.)
    """
    if not json_lib:
        raise Exception("No json library available")
    return json.dumps(_json_convert(obj), *args, **kwargs) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:15,代码来源:json_util.py

示例9: __setattr__

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def __setattr__(self, name, code):
        self._db.system.js.replace_one(
            {"_id": name}, {"_id": name, "value": Code(code)}, True) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:5,代码来源:database.py

示例10: group

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def group(self, key, condition, initial, reduce, finalize=None, **kwargs):
        """Perform a query similar to an SQL *group by* operation.

        **DEPRECATED** - The group command was deprecated in MongoDB 3.4. The
        :meth:`~group` method is deprecated and will be removed in PyMongo 4.0.
        Use :meth:`~aggregate` with the `$group` stage or :meth:`~map_reduce`
        instead.

        .. versionchanged:: 3.5
           Deprecated the group method.
        .. versionchanged:: 3.4
           Added the `collation` option.
        .. versionchanged:: 2.2
           Removed deprecated argument: command
        """
        warnings.warn("The group method is deprecated and will be removed in "
                      "PyMongo 4.0. Use the aggregate method with the $group "
                      "stage or the map_reduce method instead.",
                      DeprecationWarning, stacklevel=2)
        group = {}
        if isinstance(key, string_type):
            group["$keyf"] = Code(key)
        elif key is not None:
            group = {"key": helpers._fields_list_to_dict(key, "key")}
        group["ns"] = self.__name
        group["$reduce"] = Code(reduce)
        group["cond"] = condition
        group["initial"] = initial
        if finalize is not None:
            group["finalize"] = Code(finalize)

        cmd = SON([("group", group)])
        collation = validate_collation_or_none(kwargs.pop('collation', None))
        cmd.update(kwargs)

        with self._socket_for_reads(session=None) as (sock_info, slave_ok):
            return self._command(sock_info, cmd, slave_ok,
                                 collation=collation)["retval"] 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:40,代码来源:collection.py

示例11: _get_code_w_scope

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def _get_code_w_scope(data, position, obj_end, opts, element_name):
    """Decode a BSON code_w_scope to bson.code.Code."""
    code_end = position + _UNPACK_INT(data[position:position + 4])[0]
    code, position = _get_string(
        data, position + 4, code_end, opts, element_name)
    scope, position = _get_object(data, position, code_end, opts, element_name)
    if position != code_end:
        raise InvalidBSON('scope outside of javascript code boundaries')
    return Code(code, scope), position 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:11,代码来源:__init__.py

示例12: _encode_code

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def _encode_code(name, value, dummy, opts):
    """Encode bson.code.Code."""
    cstring = _make_c_string(value)
    cstrlen = len(cstring)
    if value.scope is None:
        return b"\x0D" + name + _PACK_INT(cstrlen) + cstring
    scope = _dict_to_bson(value.scope, False, opts, False)
    full_length = _PACK_INT(8 + cstrlen + len(scope))
    return b"\x0F" + name + full_length + _PACK_INT(cstrlen) + cstring + scope 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:11,代码来源:__init__.py

示例13: _parse_canonical_code

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def _parse_canonical_code(doc):
    """Decode a JSON code to bson.code.Code."""
    for key in doc:
        if key not in ('$code', '$scope'):
            raise TypeError('Bad $code, extra field(s): %s' % (doc,))
    return Code(doc['$code'], scope=doc.get('$scope')) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:8,代码来源:json_util.py

示例14: get

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def get(self):
        # ----- Get count # in the request, 0 by default -----
        count = request.args.get('count',default=0, type=int)
        query = request.args.get('query')

        if request.args.get('query'):
            map = Code("function () {"
                        "   if (!this.brands) return;"
                        "   emit(this.brands.trim(), 1);"
                        "};")

            reduce = Code("function (key, values) {"
                        "   var count = 0;"
                        "       for (index in values) {"
                        "           count += values[index];"
                        "       }"
                        "       return count;"    
                        "   };")

            result = mongo.db.products.map_reduce(map, reduce, "brands_products")

            res = []
            for doc in result.find({"_id": {'$regex' : query, '$options' : '-i'}}):
                res.append(doc['_id'])
            if request.args.get('count') and count == 1:
                return len(res)
            else:
                return res
        else:
            if request.args.get('count') and count == 1:
                return  len(mongo.db.products.distinct('brands'))
            else:
                return  mongo.db.products.distinct('brands')


# ----- /products/categories ----- 
开发者ID:openfoodfacts,项目名称:OpenFoodFacts-APIRestPython,代码行数:38,代码来源:resources_products.py

示例15: eval

# 需要导入模块: from bson import code [as 别名]
# 或者: from bson.code import Code [as 别名]
def eval(self, code, *args):
        """Evaluate a JavaScript expression in MongoDB.

        Useful if you need to touch a lot of data lightly; in such a
        scenario the network transfer of the data could be a
        bottleneck. The `code` argument must be a JavaScript
        function. Additional positional arguments will be passed to
        that function when it is run on the server.

        Raises :class:`TypeError` if `code` is not an instance of
        :class:`basestring` (:class:`str` in python 3) or `Code`.
        Raises :class:`~pymongo.errors.OperationFailure` if the eval
        fails. Returns the result of the evaluation.

        :Parameters:
          - `code`: string representation of JavaScript code to be
            evaluated
          - `args` (optional): additional positional arguments are
            passed to the `code` being evaluated

        .. warning:: the eval command is deprecated in MongoDB 3.0 and
          will be removed in a future server version.
        """
        if not isinstance(code, Code):
            code = Code(code)

        result = self.command("$eval", code, args=args)
        return result.get("retval", None) 
开发者ID:leancloud,项目名称:satori,代码行数:30,代码来源:database.py


注:本文中的bson.code.Code方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。