准备工作
一丶配置虚拟环境
1.安装虚拟包:pip install virtualenv
2.创建一个用于虚拟环境的目录,并进入到目录下
3.执行 python -m venv 虚拟环境名
4.执行 virtualenv 虚拟环境名
5.在目录下激活虚拟环境
windos下:source env\Scripts\activate
linux下:
source env/bin/activate
6.停止虚拟环境 deactivate指令或者关闭终端
二丶用于代码高亮显示pip install pygments
开始
一丶创建一个项目
1.新建一个项目目录,在目录中创建一个Django项目
cd 项目目标目录 django-admin.py startproject 项目名 cd 项目目录下
2.创建一个Django应用
python manage.py startapp snippets
3.将rest_framework和新建的应用注册到settings.py的INSTALLED_APPS中
INSTALLED_APPS = ( ... ‘rest_framework‘, ‘snippets.apps.SnippetsConfig‘, )
二丶编辑模型层
1.编辑模型层文件
应用下的models.py文件 from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default=‘‘) code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default=‘python‘, max_length=100) style = models.CharField(choices=STYLE_CHOICES, default=‘friendly‘, max_length=100) class Meta: ordering = (‘created‘,)
2.迁移数据
项目根目录下 python manage.py makemigrations 应用名 python manage.py migrate
三丶序列化
1.应用下建立serializers.py文件
from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={‘base_template‘: ‘textarea.html‘}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default=‘python‘) style = serializers.ChoiceField(choices=STYLE_CHOICES, default=‘friendly‘) def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get(‘title‘, instance.title) instance.code = validated_data.get(‘code‘, instance.code) instance.linenos = validated_data.get(‘linenos‘, instance.linenos) instance.language = validated_data.get(‘language‘, instance.language) instance.style = validated_data.get(‘style‘, instance.style) instance.save() return instance
四丶使用序列化器
一丶序列化
1.进入python shell:python manage.py shell
from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code=‘foo = "bar"\n‘) snippet.save() snippet = Snippet(code=‘print "hello, world"\n‘) snippet.save()
2.查看实例化的数据
serializer = SnippetSerializer(snippet) serializer.data
# {‘id‘: 2, ‘title‘: u‘‘, ‘code‘: u‘print "hello, world"\n‘, ‘linenos‘: False, ‘language‘: u‘python‘, ‘style‘: u‘friendly‘}
3.json数据
content = JSONRenderer().render(serializer.data) content # ‘{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}‘
二丶反序列化
1.解析字符串为python原生的数据类型
from django.utils.six import BytesIO stream = BytesIO(content) data = JSONParser().parse(stream)
2.将原生数据类型变为对象实例
serializer = SnippetSerializer(data=data) serializer.is_valid() # True serializer.validated_data # OrderedDict([(‘title‘, ‘‘), (‘code‘, ‘print "hello, world"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]) serializer.save() # <Snippet: Snippet object>
3.序列化querysets实例,将many=True参数加入序列化器
serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer.data # [OrderedDict([(‘id‘, 1), (‘title‘, u‘‘), (‘code‘, u‘foo = "bar"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]), OrderedDict([(‘id‘, 2), (‘title‘, u‘‘), (‘code‘, u‘print "hello, world"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]), OrderedDict([(‘id‘, 3), (‘title‘, u‘‘), (‘code‘, u‘print "hello, world"‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)])]
原文地址:https://www.cnblogs.com/cangshuchirou/p/9264909.html
时间: 2024-10-07 14:06:05