Chinaunix

标题: pymongo eval [打印本页]

作者: ws00310976    时间: 2015-11-15 21:04
标题: pymongo eval
请问 pymongo 模块中的eval怎么使用
作者: icymirror    时间: 2015-11-16 09:15
回复 1# ws00310976
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.

arameters:
  - `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.
作者: ws00310976    时间: 2015-11-16 21:55
官方的例子,我看不太懂,能 举个实际的例子吗
作者: wq4113    时间: 2015-11-17 15:08
def update(request):
    id = eval("request." + request.method + "['id']")
    post = Post.objects(id=id)[0]
   
    if request.method == 'POST':
        # update field values and save to mongo
        post.title = request.POST['title']
        post.last_update = datetime.datetime.now()
        post.content = request.POST['content']
        post.save()
        template = 'index.html'
        params = {'Posts': Post.objects}

    elif request.method == 'GET':
        template = 'update.html'
        params = {'post':post}
   
能已经注意到用来索引文档 ID 的 eval 语句。使用该语句是为了避免编写以下语句:
if request.method == 'POST':
        id = request.POST['id']
    elif request.method == 'GET':
        id = request.GET['id']
    return render_to_response(template, params, context_instance=RequestContext(request))




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2