创建新模型时,应该在哪里放置代码以在 Google App Engine/Django 上自动递增分片计数器?

发布于 2024-08-03 21:50:07 字数 607 浏览 1 评论 0原文

我有一个模型 MyModel (扩展 Google 的 db.Model),并且我想跟踪已创建的模型数量。

我认为 Google 关于 分片计数器 的 I/O 演讲中的代码相当不错很好,所以我就用它。但我不确定创建新代码时应该在哪里调用增量。 (我正在使用 Django,并且我将熟悉的 models.py、views.py 等布局保留到项目的应用程序中。)

对于将递增代码放在哪里,我似乎想到了几种可能性:

  1. 重载 Model.put(),以便在第一次保存模型时递增计数器,并类似地重载 Model.delete() 以递减计数器

  2. 附加某种侦听器来保存/删除,并检查保存是否属于新模型(GAE 有这样的监听器吗?)

  3. 将计数器递增代码放在view.py 中创建/删除模型的函数

我非常感谢有关如何最好地做到这一点的建议和想法(以及每个选项的优点/缺点)。

感谢您的阅读。

最好的, 布莱恩

I've a model MyModel (extending Google's db.Model), and I want to keep track of the number of Models that have been created.

I think the code at from Google's I/O talk on Sharding Counters is quite good, so I'm using that. But I'm not sure where I ought to be calling the increment when creating a new code. (I'm using Django, and I've kept the familiar models.py, views.py, etc. layout to the project's applications.)

There are a couple possibilities that seem to come to mind for where to put the incrementing code:

  1. Overload the Model.put() so that it increments the counter when the model is saved for the first time, and similarly overload Model.delete() to decrement the counter

  2. Attach some sort of listener to saves/deletes, and check that the save is of a new model (does GAE have such listeners?)

  3. Put the counter incrementing code in the function in view.py that creates/deletes models

I'd be much obliged for suggestions and thoughts as to how to do this best (and pros/cons of each option).

Thank you for reading.

Best,
Brian

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

游魂 2024-08-10 21:50:07

我建议采用“App Engine Fan”此处(本质上是“设置场景”),尤其是此处(显示正确的解决方案:不是“猴子修补”,而是使用应用程序的架构良好的内置“钩子”设施引擎)。

他作为示例给出的两个“黑客”与您的用例足够接近,您在实现代码时应该不会遇到任何问题 - 事实上,它与您考虑的子点 (2) 的“监听器”解决方案并没有那么远,只是多了一些一般来说,因为“钩子”实际上可以“干扰”操作(并不是说您在这里需要它),并且能够在操作本身之前或之后运行(在您的情况下,我怀疑“之后”可能更好,只是在如果 put 以某种方式失败,在这种情况下我想你不想计算它)。

I suggest the approach (curiously close to "aspect oriented programming") suggested by "App Engine Fan" here (essentially "setting the scene") and especially here (showing the right solution: not "monkey patching" but rather the use of the well-architected built-in "hooks" facility of App Engine).

The two "Hacks" he gives as examples are close enough to your use case that you should have no trouble implementing your code -- indeed it's not all that far from the "listener" solution you considered sub point (2), just somewhat more general because "hooks" can actually "interfere" with the operation (not that you need that here) as well as being able to run either before or after the operation itself (in your case I suspect "after" may be better, just in case the put fails somehow, in which case I imagine you don't want to count it).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文