6

在我的应用程序中,MongoDB 集合需要由服务器端脚本作业更新(即:每 30 分钟从其他 API 抓取/拉取的 cron 作业)。我真正想做的是对 MongoDB 集合进行更新,但要根据架构验证数据并包含元数据(更新、创建等)。

想到解决这个问题的两种方法是:

  1. 有一个假客户端来做 HTTP POST/PUT/PATCHES。但是,这意味着这个假客户端必须处理诸如身份验证/授权/上次修改后的事情。
  2. 使用 PyMongo 直接与数据库交互。但是,这意味着我不会进行数据验证或存储元数据。

Eve 是否有数据库挂钩,以便我可以在没有 HTTP 的情况下进行丰富的 Eve 数据库更新?

4

3 回答 3

4

我能够在一个单独的脚本中运行它,该脚本可以由 jenkins 定期运行。我正在导入的 run.py 中的应用程序是我在前夕 quickstart结束时拥有的应用程序。

from run import app
from eve.methods.post import post_internal

payload = {
    "firstname": "Ray",
    "lastname": "LaMontagne",
    "role": ["contributor"]
}

with app.test_request_context():
    x = post_internal('people', payload)
    print(x)

post_internal 运行eve.utils.parse_request,它依赖于flask.request,所以with app.test_request_context()是必需的。app.app_context()对于这种方法是不够的。

如果您是烧瓶新手(像我一样),请阅读appcontextreqcontext的文档。

于 2014-08-25T19:39:25.187 回答
3

As of v0.5 (currently on the development branch but you can pull and use it right away) you can use post_internal for adding data:

   Intended for internal post calls, this method is not rate limited,
   authentication is not checked and pre-request events are not raised.
   Adds one or more documents to a resource. Each document is validated
   against the domain schema. If validation passes the document is inserted
   and ID_FIELD, LAST_UPDATED and DATE_CREATED along with a link to the
   document are returned. If validation fails, a list of validation issues
   is returned.

It would probably make sense to add more internal methods to cover all CRUD operation which are now available via HTTP. You can still invoke them right away, though.

Update: v0.5 has been released with _internal methods available for all CRUD operations.

于 2014-08-15T09:38:21.923 回答
1

如果您想在自定义端点中执行以下操作...

  1. 接受一些POSTed 数据
  2. 以某种方式操纵数据
  3. 执行一个post_internal()
  4. 将结果作为响应返回

...你会这样做:

from eve.methods.post import post_internal
from eve.render import send_response

def my_custom_endpoint(**kwargs):

    data = json.loads(request.data.decode())

    # <manipulate data here>    

    resp = post_internal('crew', data)
    return send_response('crew', resp)

实际上,您最好使用 Eve 的事件挂钩来执行此类操作。但是如果有一些事件挂钩没有涵盖的情况,这种方法可能会很有用。

于 2016-05-13T11:40:01.370 回答