I'm trying to retreive some OAuth information that I've stored using Datastore, but I'm getting this error when I'm instantiating my OAuthConsumer class:
TypeError: __init__() got an unexpected keyword argument 'consumer_secret'
This is also my first time experimenting with Namespace, and I'm wondering if that has something to do with it. The class is as follows:
creds = OAuthConsumer('google')
class OAuthConsumer(db.Model):
'''the oauth consumer information'''
consumer_key = db.StringProperty()
consumer_secret = db.StringProperty()
def __init__(self, service):
namespace_manager.set_namespace(service)
query = db.GqlQuery('SELECT * FROM OAuthConsumer')
creds = query.get()
self.consumer_key = creds.consumer_key
self.consumer_secret = creds.consumer_secret
Here's what I've got using Data V开发者_开发问答iewer:
Any ideas as to what I'm doing wrong?
You're overriding the __init__
method on a Datastore Model class, and you're not passing the keyword arguments through to the parent constructor (or calling it at all!).
As a general rule, you shouldn't override the constructor of a Datastore Model class. It's possible to do it right, but it's tricky, and it's far safer to provide a class method as a factory, like this:
class OAuthConsumer(db.Model):
'''the oauth consumer information'''
consumer_key = db.StringProperty()
consumer_secret = db.StringProperty()
@classmethod
def new(cls, service):
namespace_manager.set_namespace(service)
query = db.GqlQuery('SELECT * FROM OAuthConsumer')
creds = query.get()
return cls(consumer_key=creds.consumer_key, consumer_secret=creds.consumer_secret)
creds = OAuthConsumer('google')
Your code is more than a little odd for a couple of reasons, though:
- When constructing a new instance, you fetch and copy the fields from another, (effectively) randomly selected instance of the same model!
- You're setting the namespace inside a constructor (or in the rewritten version, in a factory method). The namespace is a global setting, and you really shouldn't do this inside a library method. You don't set it back afterwards, either.
精彩评论