Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: datetime.date object has no Attribute '__dict__'

Tags:

python

resp = web.Response(body=json.dumps(r, cls=CJsonEncoder, ensure_ascii=False, default=lambda o: o.__dict__).encode('utf-8'))

when I used jinja2, and retrieve date form MYSQL, but the error shown. data:

2015-09-01
2015-09-04

how to fix it? may i need convert jinja2 to django??

like image 761
kennen.cai Avatar asked Sep 06 '15 02:09

kennen.cai


1 Answers

This has nothing to do with Django or Jinja2 or your Web framework. Your data contains date objects, and JSON has no date type, so the json module doesn't know how to store them. It tries to fall back to your default function, which just dumps all of an object's attributes, but the date type is implemented in C and doesn't have a Python dict of attributes.

You can fix this by expanding upon your default:

import datetime

def json_default(value):
    if isinstance(value, datetime.date):
        return dict(year=value.year, month=value.month, day=value.day)
    else:
        return value.__dict__

resp = web.Response(body=json.dumps(r, cls=CJsonEncoder, ensure_ascii=False, default=json_default).encode('utf-8'))

I recommend against using .__dict__ as a catch-all fallback, though — your output might contain private junk, and your JSON may not produce anything like your original data when decoded.

like image 140
Eevee Avatar answered Nov 16 '22 05:11

Eevee