Google App Engine 모델의 JSON 직렬화
꽤 오랫동안 찾아봤지만 아무 성과도 없었다.제 프로젝트에서는 Django를 사용하지 않습니다. 앱 엔진 모델(google.appengine.ext.db)을 시리얼화하는 간단한 방법이 있습니까?모델)을 JSON으로 변환하거나 직접 시리얼라이저를 작성해야 합니까?
모델:
class Photo(db.Model):
filename = db.StringProperty()
title = db.StringProperty()
description = db.StringProperty(multiline=True)
date_taken = db.DateTimeProperty()
date_uploaded = db.DateTimeProperty(auto_now_add=True)
album = db.ReferenceProperty(Album, collection_name='photo')
간단한 재귀 함수를 사용하여 엔티티(및 참조)를 전달 가능한 중첩된 사전으로 변환할 수 있습니다.simplejson
:
import datetime
import time
SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
def to_dict(model):
output = {}
for key, prop in model.properties().iteritems():
value = getattr(model, key)
if value is None or isinstance(value, SIMPLE_TYPES):
output[key] = value
elif isinstance(value, datetime.date):
# Convert date/datetime to MILLISECONDS-since-epoch (JS "new Date()").
ms = time.mktime(value.utctimetuple()) * 1000
ms += getattr(value, 'microseconds', 0) / 1000
output[key] = int(ms)
elif isinstance(value, db.GeoPt):
output[key] = {'lat': value.lat, 'lon': value.lon}
elif isinstance(value, db.Model):
output[key] = to_dict(value)
else:
raise ValueError('cannot encode ' + repr(prop))
return output
이것이 내가 찾은 가장 간단한 해결책이다.3줄의 코드만 있으면 됩니다.
모델에 메소드를 추가하여 사전을 반환하기만 하면 됩니다.
class DictModel(db.Model):
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
Simple JSON이 정상적으로 동작하게 되었습니다.
class Photo(DictModel):
filename = db.StringProperty()
title = db.StringProperty()
description = db.StringProperty(multiline=True)
date_taken = db.DateTimeProperty()
date_uploaded = db.DateTimeProperty(auto_now_add=True)
album = db.ReferenceProperty(Album, collection_name='photo')
from django.utils import simplejson
from google.appengine.ext import webapp
class PhotoHandler(webapp.RequestHandler):
def get(self):
photos = Photo.all()
self.response.out.write(simplejson.dumps([p.to_dict() for p in photos]))
App Engine SDK의 최신 릴리스(1.5.2)에서는to_dict()
모델 인스턴스를 사전으로 변환하는 기능이 에 도입되었습니다.db.py
릴리스 노트를 참조해 주세요.
문서에는 아직 이 기능에 대한 언급은 없지만, 직접 사용해 본 결과 예상대로 동작합니다.
모델을 시리얼화하려면 다음 python과 같이 커스텀json 인코더를 추가합니다.
import datetime
from google.appengine.api import users
from google.appengine.ext import db
from django.utils import simplejson
class jsonEncoder(simplejson.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, db.Model):
return dict((p, getattr(obj, p))
for p in obj.properties())
elif isinstance(obj, users.User):
return obj.email()
else:
return simplejson.JSONEncoder.default(self, obj)
# use the encoder as:
simplejson.dumps(model, cls=jsonEncoder)
이것은, 다음과 같이 인코딩됩니다.
- (이 제안에 따라) isoformat 문자열과 같은 날짜,
- 모델을 그 성질에 대한 지시로 삼는 것,
- 사용자의 이메일입니다.
이 Javascript를 사용할 수 있는 날짜를 디코딩하려면:
function decodeJsonDate(s){
return new Date( s.slice(0,19).replace('T',' ') + ' GMT' );
} // Note that this function truncates milliseconds.
주의: 이 코드를 보다 읽기 쉽게 편집해 준 사용자 pydave 덕분입니다.원래 파이썬의 if/else 표현을 사용해서jsonEncoder
(몇 가지 코멘트를 추가해 사용하고 있습니다.google.appengine.ext.db.to_dict
(원본보다 선명하게 하기 위해서)
class jsonEncoder(simplejson.JSONEncoder):
def default(self, obj):
isa=lambda x: isinstance(obj, x) # isa(<type>)==True if obj is of type <type>
return obj.isoformat() if isa(datetime.datetime) else \
db.to_dict(obj) if isa(db.Model) else \
obj.email() if isa(users.User) else \
simplejson.JSONEncoder.default(self, obj)
직접 "파서"를 쓸 필요는 없지만(파서는 아마도 JSON을 Python 개체로 바꿀 수 있습니다), Python 개체를 직접 직렬화할 수 있습니다.
simplejson 사용:
import simplejson as json
serialized = json.dumps({
'filename': self.filename,
'title': self.title,
'date_taken': date_taken.isoformat(),
# etc.
})
간단한 경우, 나는 이 기사의 마지막 부분에서 다음과 같이 주장하는 접근방식이 마음에 든다.
# after obtaining a list of entities in some way, e.g.:
user = users.get_current_user().email().lower();
col = models.Entity.gql('WHERE user=:1',user).fetch(300, 0)
# ...you can make a json serialization of name/key pairs as follows:
json = simplejson.dumps(col, default=lambda o: {o.name :str(o.key())})
이 기사는 또한 스펙트럼의 다른 끝에는 django를 풍부하게 하는 복잡한 직렬화 클래스가 포함되어 있다._meta
--계산된 속성/메서드를 시리얼화할 수 있는 기능에서 _message missing, 아마도 여기에 설명된 버그) 에러가 발생하는 이유를 알 수 없습니다.대부분의 경우 시리얼라이제이션에 대한 요구는 중간 정도이며, @David Wilson과 같은 자기성찰적인 접근방식이 바람직할 수 있습니다.
django를 프레임워크로 사용하지 않더라도 이러한 라이브러리를 사용할 수 있습니다.
from django.core import serializers
data = serializers.serialize("xml", Photo.objects.all())
app-engine-patch를 사용하는 경우 자동으로 선언됩니다._meta
를 사용할 수 .django.core.serializers
장고하다
App-engine-patch는 하이브리드 인증(django + google 계정)을 가지고 있으며, django의 관리 부분은 작동합니다.
위의 Mtgred의 답변은 나에게 있어서 매우 효과가 있었습니다.- 엔트리 키도 취득할 수 있도록 약간 수정했습니다.코드 행이 적지는 않지만 독특한 키를 얻을 수 있습니다.
class DictModel(db.Model):
def to_dict(self):
tempdict1 = dict([(p, unicode(getattr(self, p))) for p in self.properties()])
tempdict2 = {'key':unicode(self.key())}
tempdict1.update(tempdict2)
return tempdict1
dpatru에 의해 작성된 JSON 인코더 클래스를 확장하여 다음을 지원합니다.
- 쿼리 결과 속성(예: car.owner_set)
- Reference Property - 재귀적으로 JSON으로 변환합니다.
- "A" - "A"가
verbose_name
는 JSONJSON으로됩니다.class DBModelJSONEncoder(json.JSONEncoder): """Encodes a db.Model into JSON""" def default(self, obj): if (isinstance(obj, db.Query)): # It's a reference query (holding several model instances) return [self.default(item) for item in obj] elif (isinstance(obj, db.Model)): # Only properties with a verbose name will be displayed in the JSON output properties = obj.properties() filtered_properties = filter(lambda p: properties[p].verbose_name != None, properties) # Turn each property of the DB model into a JSON-serializeable entity json_dict = dict([( p, getattr(obj, p) if (not isinstance(getattr(obj, p), db.Model)) else self.default(getattr(obj, p)) # A referenced model property ) for p in filtered_properties]) json_dict['id'] = obj.key().id() # Add the model instance's ID (optional - delete this if you do not use it) return json_dict else: # Use original JSON encoding return json.JSONEncoder.default(self, obj)
https://stackoverflow.com/users/806432/fredva,에서 설명한 바와 같이 to_module은 정상적으로 동작합니다.이게 내가 사용하는 코드야.
foos = query.fetch(10)
prepJson = []
for f in foos:
prepJson.append(db.to_dict(f))
myJson = json.dumps(prepJson))
모든 모델 클래스에 대해 정의된 메서드 "Model.properties()"가 있습니다.원하는 명령어가 반환됩니다.
from django.utils import simplejson
class Photo(db.Model):
# ...
my_photo = Photo(...)
simplejson.dumps(my_photo.properties())
문서의 모델 속성을 참조하십시오.
이러한 API(google.appengine.ext.db)는 더 이상 권장되지 않습니다.이러한 API를 사용하는 앱은 App Engine Python 2 런타임에서만 실행할 수 있으며 App Engine Python 3 런타임으로 마이그레이션하기 전에 다른 API 및 서비스로 마이그레이션해야 합니다.자세한 내용은 여기를 클릭해 주세요.
데이터스토어 모델 인스턴스를 직렬화하려면 json.dumps를 사용할 수 없습니다(테스트되지 않았지만 로렌조가 지적했습니다).아마 미래에는 다음과 같은 것이 효과가 있을 것입니다.
http://docs.python.org/2/library/json.html
import json
string = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
object = json.loads(self.request.body)
언급URL : https://stackoverflow.com/questions/1531501/json-serialization-of-google-app-engine-models
'itsource' 카테고리의 다른 글
데이터 테이블에 빈 데이터 메시지를 표시하는 방법 (0) | 2023.02.10 |
---|---|
json 형식의 키 값 쌍을 기호가 키로 있는 루비 해시로 변환하는 가장 좋은 방법은 무엇입니까? (0) | 2023.02.10 |
다른 ID로 여러 행을 동시에 업데이트 (0) | 2023.02.06 |
Python 함수가 예외를 발생시키는 것을 어떻게 테스트합니까? (0) | 2023.02.06 |
상수 포인터 vs 상수 값에서의 포인터 (0) | 2023.02.06 |