AppEngine Python - 无需二十个 elif 语句即可更新实体属性

发布于 2024-09-18 12:21:52 字数 595 浏览 2 评论 0原文

假设我有一个用二十个不同的 StringProperty 属性定义的 AppEngine 模型。然后我有一个 Web 表单,它发布该模型实体的更新值。在读取表单数据后,我最终得到类似的结果:

entity_key['name'] = 'new_name'
entity_key['city'] = 'new_city'
entity_key['state'] = 'new_state'
etc...

为了实际将这些值分配给实体,我目前正在做这样的事情:

if property == 'name':
  entity.name = entity_key['name']
elif property == 'city':
  entity.city = entity_key['city']
elif property == 'state':
  entity.state = entity_key['state']
etc...

有没有办法在没有二十个 elif 语句的情况下分配属性值?我看到有 model.properties() 函数,但无论如何我看不到将所有这些结合在一起。

感谢所有帮助。

谢谢。

Suppose I have an AppEngine model defined with twenty different StringProperty properties. And then I have a web form, which POSTs updated values for an entity of this model. I end up with something like this after reading in the form data:

entity_key['name'] = 'new_name'
entity_key['city'] = 'new_city'
entity_key['state'] = 'new_state'
etc...

To actually assign these values to the entity, I'm presently doing something like this:

if property == 'name':
  entity.name = entity_key['name']
elif property == 'city':
  entity.city = entity_key['city']
elif property == 'state':
  entity.state = entity_key['state']
etc...

Is there any way to assign the property values without twenty elif statements? I see that there is the model.properties() function, but I don't see anyway to tie all this together.

All help is appreciated.

Thank you.

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

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

发布评论

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

评论(2

久伴你 2024-09-25 12:21:52

通过一条语句可以获得与 if / elif 树相同的效果:

setattr(entity, property, entity_key[property])

这只是基本的 Python,自 1.5.2 以来的每个 Python 版本都以相同的方式工作(也许更早——很多年前我并没有使用Python!——),并且与App Engine、Django 或两者的组合没有任何具体关系。

The same effect as for your if / elif tree could be obtained by a single statement:

setattr(entity, property, entity_key[property])

This is just elementary Python, working the same way in every Python version since 1.5.2 (and perhaps earlier -- I wasn't using Python that many years ago!-), and has nothing specifically to do with App Engine, nor with Django, nor with the combination of the two.

帅的被狗咬 2024-09-25 12:21:52

凉爽的。仅供其他人参考,以下两个片段是相同的:

entity.some_property = "cat";

setattr(entity, "some_property", "cat")

我确实知道 setattr 函数,Alex,所以感谢您帮助我。

Cool. Just for others' reference, the following two snippets are identical:

entity.some_property = "cat";

setattr(entity, "some_property", "cat")

I did know about the setattr function, Alex, so thanks for helping me out.

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