How to reference Python elixir object items
I am trying to swap in the key name from a request.param
for an Elixir object attribute. Below, the Elixir object bk
is a Book()
which has an attribute PrintTitle
. PrintTitle
also comes in from a form as 开发者_运维技巧a request.param
. Rather than manually map all the parameters to the Book attributes, I would like to map them based on a simple if in
. However, it doesn't work, because I have the wrong syntax or method at bk.k
.
if len(request.params) != 0:
bk = Book()
for k, v in request.params.items():
print k, v # gives me love
bk.k = v # no love here
print 'Print Title:', bk.PrintTitle # value is None (obviously)
Unfortunately you can't just set the attribute of a Python object with a variable in this way. One way to do this is to use the setattr
method to accomplish this, for example here is a crude example:
from elixir import *
metadata.bind = 'sqlite://'
metadata.bind.echo = False
class Book(Entity):
PrintTitle = Field(String(50))
setup_all()
create_all()
params = {'PrintTitle':'Ethyl the Aardvark goes Quantity Surveying'}
bk = Book()
print "Title in database (before): {}".format(bk.PrintTitle)
for k, v in params.items():
setattr(bk, k, v)
print "Title in database (after): {}".format(bk.PrintTitle)
The result of this script is:
Title in database (before): None
Title in database (after): Ethyl the Aardvark goes Quantity Surveying
Here I'm faking out your elixir model, and I'm just using a params
dictionary to fake out whatever you're getting in request.params
.
So in this example setattr(bk, k, v)
is pretty much what you're trying to do with bk.k=v
.
EDIT: I should add that you need to be careful using setattr, in that you need to be sure the key from your params exists in your db model first, as elixer/sqlalchemy may not like trying to set the value of a non-existent database field.
精彩评论