zmm064
4/24/2018 - 12:35 PM

Django Restful Framework

Django Restful Framework

In [1]: from datetime import datetime
   ...: from django.utils import timezone
   ...: from django.utils.six import BytesIO
   ...: from rest_framework.renderers import JSONRenderer
   ...: from rest_framework.parsers import JSONParser
   ...: from games.models import Game
   ...: from games.serializers import GameSerializer
   ...:
# 创建两个instance
In [2]: gamedatetime = timezone.make_aware(datetime.now(),
   ...: timezone.get_current_timezone())
   ...: game1 = Game(name='Smurfs Jungle', release_date=gamedatetime,
   ...: game_category='2D mobile arcade', played=False)
   ...: game1.save()
   ...: game2 = Game(name='Angry Birds RPG', release_date=gamedatetime,
   ...: game_category='3D RPG', played=False)
   ...: game2.save()
   ...:
# 对其中一个序列化
In [3]: GameSerializer(game1)
Out[3]:
GameSerializer(<Game: Game object>):
    pk = IntegerField(read_only=True)
    name = CharField(max_length=200)
    release_date = DateTimeField()
    game_category = CharField(max_length=200)
    played = BooleanField(required=False)
# 获取序列化后的数据
In [4]: GameSerializer(game1).data
Out[4]:
ReturnDict([('pk', 1),
            ('name', 'Smurfs Jungle'),
            ('release_date', '2018-04-24T19:44:53.443503Z'),
            ('game_category', '2D mobile arcade'),
            ('played', False)])
# 将数据render成json格式
In [5]: renderer = JSONRenderer()
In [7]: renderer.render(GameSerializer(game1).data)
Out[7]: b'{"pk":1,"name":"Smurfs Jungle","release_date":"2018-04-24T19:44:53.443503Z","game_category":"2D mobile arcade","played":false}'

  
# 将json格式的数据转为字典
In [9]: json_string_for_new_game = '{"name":"Tomb Raider Extreme Edition","release_date":"2016-05-18T03:02:00.776594Z","game_category"
   ...: :"3D RPG","played":false}'
   ...: json_bytes_for_new_game = bytes(json_string_for_new_game , encoding="UTF-8")
   ...: stream_for_new_game = BytesIO(json_bytes_for_new_game)
   ...: parser = JSONParser()
   ...: parsed_new_game = parser.parse(stream_for_new_game)
   ...: print(parsed_new_game)
   ...:
{'name': 'Tomb Raider Extreme Edition', 'release_date': '2016-05-18T03:02:00.776594Z', 'game_category': '3D RPG', 'played': False}
# 将字典格式的数据序列化,并对序列化后的数据调用save方法
In [10]: new_game_serializer = GameSerializer(data=parsed_new_game)
    ...: if new_game_serializer.is_valid():
    ...:     new_game = new_game_serializer.save()
    ...:     print(new_game.name)
    ...:
Tomb Raider Extreme Edition

In [11]: new_game_serializer.data
Out[11]:
ReturnDict([('pk', 3),
            ('name', 'Tomb Raider Extreme Edition'),
            ('release_date', '2016-05-18T03:02:00.776594Z'),
            ('game_category', '3D RPG'),
            ('played', False)])