Вопрос

I'm doing a simple object marshalling thing that goes between a simple RESTful API to a peewee-managed data store. However, this pattern keeps on coming up (form being the output of cgi.FieldStorage()):

if form.getfirst('From'): msg.msg_from=form.getfirst('From')
if form.getfirst('To'): msg.msg_to=form.getfirst('To')
if form.getfirst('Body'): msg.msg_body=form.getfirst('Body')

This is, of course, crufty and hard to maintain. What I'd much rather do is have something like this:

keyMapping = { 'From': 'msg_from',
               'To': 'msg_to',
               'Body': 'msg_body' }
for k, v in keyMapping:
    if form.getfirst(k): msg.SET_FIELD_VALUE(v, form.getfirst(k))

Obviously it's the SET_FIELD_VALUE that I'm unable to find. I know how I can do it using eval but I'd rather avoid that, obviously, and I realize that the actual pattern might actually involve some form of field reference or reflection API or the like instead, but I'm unable to find anything about how one would do that either.

Это было полезно?

Решение

Use setattr:

keyMapping = { 'From': 'msg_from',
               'To': 'msg_to',
               'Body': 'msg_body' }
for k, v in keyMapping.items():
    if form.getfirst(k):
        setattr(msg, v, form.getfirst(k))

BTW, you should use items() or iteritesm(). Otherwise, iterating dictiaonary yields keys only.


Example usage of setattr:

>>> class Klass:
...     def __init__(self):
...         self.a = 1
...         self.b = 2
...
>>> x = Klass()
>>> setattr(x, 'a', 3)
>>> x.a
3
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top