问题描述
MarshallingException 我试图让瓶子宁静地返回一个datetime字段, :'datetime.date'对象没有属性'utctimetuple'
模型(sqlalchemy)如下:
class目标(db.Model):
id = db.Column(db.Integer,primary_key = True )
uuid = db.Column(db.String(256))
title = db.Column(db.String(80))
description = db.Column(db.String(250) ))
done = db.Column(db.Boolean,default = False)
startDate = db.Column(db.DateTime,default = datetime.utcnow)
timeDuration = db.Column db.teger,default = 0)
isActive = db.Column(db.Boolean,default = True)
目标字段是:
$ p $ lt; code> target_fields = {
'id':fields.Integer,
'uuid':fields.String,
'title':fields.String,
'description' :fields.String,
'done':fields.Boolean,
'startDate':fields.DateTime
#'uri':fields.Url('target')
}
实际剩余资源为:
<$ p
def __init __(self):$ b $ self.reqparse = reqparse。 RequestParser()
self.reqparse.add_argument('title',type = str,location ='json')
self.reqparse.add_argument('description',type = str,location ='json' )
self.reqparse.add_argument('done',type = bool,location ='json')
self.reqparse.add_argument('startDate',type = datetime,location ='json')
self.reqparse.add_argument('timeDuration',type = int,location ='json')
self.reqparse.add_argument('isActive',type = bool,location ='json')
super(TargetAPI,self).__ init __()
$ b $ get $(b
$ b $ target
$ 404)
return {'target':marshal(target,target_fields)}
$ b $ pre $ Traceback(最近调用最后一个):
文件/ usr / local /lib/python2.7/site-packages/flask/app.py,第1836行,在__call__
中返回self.wsgi_app(environ,start_response)
文件/ usr / local / lib / python2在/usr/local/lib/python2中输入.7 / site-packages / flask / app.py,第1820行,在wsgi_app
response = self.make_response(self.handle_exception(e))
.7 / site-packages / flask_restful / __init__.py,第258行,在error_router
中返回original_handler(e)
文件/usr/local/lib/python2.7/site-packages/flask /app.py,第1403行,在handle_exception
reraise(exc_type,exc_value,tb)
文件/usr/local/lib/python2.7/site-packages/flask/app.py ,第18行17,在wsgi_app
response = self.full_dispatch_request()
文件/usr/local/lib/python2.7/site-packages/flask/app.py,第1477行,在full_dispatch_request
rv = self.handle_user_exception(e)
文件/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py,第258行,在error_router
return original_handler e)
文件/usr/local/lib/python2.7/site-packages/flask/app.py,第1381行,在handle_user_exception
reraise(exc_type,exc_value,tb)
在full_dispatch_request
rv = self.dispatch_request()
文件/usr/local/lib/python2.7/site-packages/flask/app.py,第1475行,/ usr /本地/ lib / python2.7 / site-packages / flask / app.py,第1461行,在dispatch_request
返回self.view_functions [rule.endpoint](** req.view_args)
文件 /usr/local/lib/python2.7/site-packages/flask_restful/__init__.py,第397行,在包装中
resp = resource(* args,** kwargs)
文件/ usr /local/lib/python2.7/site-packages /flask_httpauth.py,第53行,装饰
返回f(* args,** kwargs)
文件/usr/local/lib/python2.7/site-packages/flask/views。 py,第84行,在
返回self.dispatch_request(* args,** kwargs)
文件/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py ,第487行,在dispatch_request
resp = meth(* args,** kwargs)
文件/Users/nahuel/proj/ptcp/app/resources/targetListAPI.py,第60行, post
'target':marshal(newTarget,target_fields)},201
文件/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py,第533行,在marshal
return OrderedDict(items)
文件/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py,第52行,在__init__
self .__ update(* args,** kwds)
文件/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib /python2.7/_abcoll.py,第547行,更新
作为键值,其他值:
文件/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py,第532行,在< genexpr>
for k,v in fields.items())
输出$ b中的/usr/local/lib/python2.7/site-packages/flask_restful/fields.py,第109行$ b返回self.format(value)
文件/usr/local/lib/python2.7/site-packages/flask_restful/fields.py,第271行,格式为
raise MarshallingException(ae )
我不能理解为什么要访问datetime.date,因为我总是使用datetime.datetime对象!任何想法?
最后解决了问题!为了完整起见,我将发布答案:
本质上,问题是下面的postgresql数据库使用日期类型作为startDate字段,而不是时间戳。所以当Target.startDate对象被sqlalchemy检索的时候,它会为它分配类型datetime.date而不是datetime.datetime。
之前:
表public.target
列|类型|修饰符|存储|统计目标|描述
-------------- + ------------------------ + ----- ------------------------------------------------ + - --------- + -------------- + -------------
id |整数| not null default nextval('target_id_seq':: regclass)|平原| |
uuid |字符变化(256)| |扩展| |
title |字符变化(80)| |扩展| |
描述|字符变化(250)| |扩展| |
完成|布尔| |平原| |
startDate |日期| |平原| |
timeDuration |整数| |平原| |
isActive |布尔| |平原| |
userId |整数| |平原| |
startDate |时间戳没有时区| |平原| |
I'm trying to get flask-restful to return a datetime field, however it fais with the error:
MarshallingException: 'datetime.date' object has no attribute 'utctimetuple'
The model(sqlalchemy) is the following:
class Target(db.Model):
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(db.String(256))
title = db.Column(db.String(80))
description = db.Column(db.String(250))
done = db.Column(db.Boolean, default = False)
startDate = db.Column(db.DateTime, default=datetime.utcnow)
timeDuration = db.Column(db.Integer, default = 0)
isActive = db.Column(db.Boolean, default = True)
The target fields are:
target_fields = {
'id': fields.Integer,
'uuid' : fields.String,
'title': fields.String,
'description': fields.String,
'done': fields.Boolean,
'startDate' : fields.DateTime
# 'uri': fields.Url('target')
}
The actual rest resouce is:
class TargetAPI(Resource):
decorators = [auth.login_required]
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('title', type = str, location = 'json')
self.reqparse.add_argument('description', type = str, location = 'json')
self.reqparse.add_argument('done', type = bool, location = 'json')
self.reqparse.add_argument('startDate', type = datetime, location = 'json')
self.reqparse.add_argument('timeDuration', type = int, location = 'json')
self.reqparse.add_argument('isActive', type = bool, location = 'json')
super(TargetAPI, self).__init__()
def get(self,username, id):
target = Target.query.get(id)
if not target:
abort(404)
return { 'target': marshal(target, target_fields) }
The full stack trace is:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 258, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 258, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 397, in wrapper
resp = resource(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flask_httpauth.py", line 53, in decorated
return f(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 487, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/nahuel/proj/ptcp/app/resources/targetListAPI.py", line 60, in post
'target': marshal(newTarget, target_fields) }, 201
File "/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 533, in marshal
return OrderedDict(items)
File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 52, in __init__
self.__update(*args, **kwds)
File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py", line 547, in update
for key, value in other:
File "/usr/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 532, in <genexpr>
for k, v in fields.items())
File "/usr/local/lib/python2.7/site-packages/flask_restful/fields.py", line 109, in output
return self.format(value)
File "/usr/local/lib/python2.7/site-packages/flask_restful/fields.py", line 271, in format
raise MarshallingException(ae)
I can't for the life of me understand why is it trying to access datetime.date, since I always use datetime.datetime objects! Any ideas?
Finally fixed the issue! For the sake of completness, I'll post the answer:Essentially, the problem was that the postgresql database underneath was using a date type for the 'startDate' field, instead of a timestamp one. So when the Target.startDate object was retrieved by sqlalchemy, it was assigning it the type datetime.date instead of datetime.datetime.
Before:
Table "public.target"
Column | Type | Modifiers | Storage | Stats target | Description
--------------+------------------------+-----------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('target_id_seq'::regclass) | plain | |
uuid | character varying(256) | | extended | |
title | character varying(80) | | extended | |
description | character varying(250) | | extended | |
done | boolean | | plain | |
startDate | date | | plain | |
timeDuration | integer | | plain | |
isActive | boolean | | plain | |
userId | integer | | plain | |
After:
startDate | timestamp without time zone | | plain | |
这篇关于与日期和瓶平静的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!