2012-02-12 3 views
2

필터링 tojson :직렬화 날짜는 내가이 오류를 받고 있어요

var root_node_info = eval({{ nd|tojson|safe }}); 

내 몽고 데이터베이스에서 bson 개체를 포함 차 :

TypeError: datetime.datetime(2012, 2, 12, 0, 47, 6, 542000) is not JSON serializable 

신사가이 줄을 구문 분석을 시도 할 때. 필드 중 하나는 datetime 객체입니다. 어떻게 이것을 올바르게 직렬화 할 플라스크를 얻을 수 있습니까?

이것은

class Item(Document): 
    structure = { 
     "tldr": unicode, 
     "body": unicode, 
     "user": unicode, 
     "time_submitted": datetime.datetime, 
     "upvotes": int, 
     "downvotes": int, 
     "tags": [unicode] 
    } 

    validators = { 
    } 

    indexes = [ 
     {'fields':['user']}, 
     {'fields':['tags']} 
    ] 

    use_dot_notation = True 

    required_fields = ['body', 'user', 'time_submitted'] 
    default_values = {'time_submitted': datetime.datetime.utcnow} 

    def __repr__(self): 
     return '<item %r>' % (self._id) 

답변

5

JSON은 datetime 개체를 처리하지 않습니다 (ITS 관련 경우) 내 mongokit 모델이다. 표준 실습은 ISO 형식으로 문자열로 인코딩하는 것입니다. 이 SO question about JSON은 예제를 제공합니다. 새로운 JSON 인코더 필터를 직접 register해야합니다.

2

주목할 사항.

v0.10부터 플라스크에는 자신의 json_encoder을 지정할 수있는 기능이 있습니다.

플라스크의 기본값 은 날짜 (및 기타 몇 가지 추가 사항)를 알고 있습니다.

관련 문제