313   Django Python

 

Django REST framework 是基于 Django ,以 REST 为规范的 API 框架,通过这些 API 来增删改查数据
此框架的核心流程如下

 

1,创建数据库表,对于 Django 来说,就是在具体 APP 里创建 model

 

[root@TENCENT64 snippets]#cat 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,序列号表格字段,便于 API 接口数据的传输转换

 

[root@TENCENT64 snippets]#cat serializers.py 
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

 

3,配置视图,对外提供具体操作方法

 

[root@TENCENT64 snippets]#cat views.py 
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics


class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


 

4,配置路由,将 uri 映射到具体视图的方法

 

[root@TENCENT64 snippets]#cat urls.py 
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
    url(r'^snippets/$', views.SnippetList.as_view()),
    url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

 

5,在 Django 的根目录配置 APP,包括 setting 和 url

 

# settings.py
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'snippets.apps.SnippetsConfig',
]

# urls.py
urlpatterns = [
    path('django/admin/', admin.site.urls),
    url(r'/', include('snippets.urls')),
]


 

至此,Django REST framework 的基本功能已经配置和编写完毕,就能通过 web 页面的 api 来增删改查数据了

 

 

企业微信截图_15279970018449



Leave a Reply

Your email address will not be published. Required fields are marked *