本文整理匯總了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)
示例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)
示例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)
示例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())
示例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)
示例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
示例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
示例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)
示例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)
示例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"]
示例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
示例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
示例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'))
示例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 -----
示例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)