[解决] 我之前混淆了类方法和实例方法。所以当我
尝试在@classmethod函数中调用strptime(cls.ts,format),我实际上是在调用
ts = ndb.StringProperty()或StringProperty('ts'),但是 不是ts中的字符串值。
正确的是删除@ decorator并调用
strptime(self.ts,格式)。以下原始问题
1:创建Token实例时,调用init_created()将ts初始化为字符串。
2:用户请求验证处理程序,使用令牌作为arg,令牌用于检索 令牌实例。
3:我使用Token实例调用is_valid()。在is_valid中,我将ts转换回datetime obj, 与其他日期时间对象进行比较。
错误1:
当我设置(使用str()方法)
delta = (now-datetime.strptime(str(cls.ts),'%Y-%b-%d / %H:%M:%S:%f')).total_seconds()
我得到了
ValueError: time data "StringProperty('ts')" does not match format '%Y-%b-%d / %H:%M:%S:%f'
错误2: 所以我尝试另一种方式。我设置(没有str())
delta = (now-datetime.strptime(cls.ts,'%Y-%b-%d / %H:%M:%S:%f')).total_seconds()
我得到了
TypeError: must be string, not StringProperty
所以我的问题是如何正确地将stringproperty传递给strptime方法。
非常感谢你。下面是我的代码:
class Token(ndb.Model):
ts = ndb.StringProperty()
@classmethod
def init_created(cls):
ts = (datetime.utcnow() + timedelta(hours=8)).strftime(format='%Y-%b-%d / %H:%M:%S:%f')
return ts
@classmethod
def is_valid(cls):
now = (datetime.utcnow() + timedelta(hours=8))
delta = (now-datetime.strptime(cls.ts,'%Y-%b-%d / %H:%M:%S:%f')).total_seconds()
return (delta<expire_time)
class Verification(webapp2.RequestHandler):
def get(self , token ):
token_cls = Token.query(Token.token == token ).get()
if not (token_cls and token_cls.is_valid() ) :
template = jinja_environment.get_template('verification_error.html' )
pass
must be string, not StringProperty
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s/1.374948928179626607/main.py", line 216, in get
if not (token_cls and token_cls.is_valid() ) :
File "/base/data/home/apps/s~/1.374948928179626607/main.py", line 86, in is_valid
delta = (now-datetime.strptime(cls.ts,'%Y-%b-%d / %H:%M:%S:%f')).total_seconds()
TypeError: must be string, not StringProperty
答案 0 :(得分:1)
您的is_valid
方法不应该包含@classmethod
装饰器,因为您在Token
类上操作,而不是在查询返回的实体上操作。删除装饰器后,将cls
更改为self
是不恰当的。