05_Tutorial 5: Relationships & Hyperlinked APIs

1、关系和超链接

0、文档

https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

https://q1mi.github.io/Django-REST-framework-documentation/tutorial/5-relationships-and-hyperlinked-apis_zh/

1、效果

2、name用法,配合reverse

第一,我们使用REST框架的reverse功能来返回完全限定的URL;

第二,URL模式是通过方便的名称来标识的,我们稍后将在snippets/urls.py中声明。

view

from rest_framework.reverse import reverse
urlpatterns = format_suffix_patterns([
    path(‘‘, views.api_root),       # 主index页面

    path(‘snippets/‘, views.SnippetList.as_view(), name=‘snippet-list‘),        # name用法,配合reverse(‘snippet-list‘)
    path(‘snippets/<int:pk>/‘, views.SnippetDetail.as_view(), name=‘snippet-detail‘),
    path(‘snippets/<int:pk>/highlight/‘, views.SnippetHighlight.as_view(), name=‘snippet-highlight‘),

    path(‘users/‘, views.UserList.as_view(), name=‘user-list‘),
    path(‘users/<int:pk>‘, views.UserDetail.as_view(), name=‘user-detail‘),
])

model

@api_view([‘GET‘])
def api_root(request, format=None):     # 入口,首页
    return Response({
        ‘users‘: reverse(‘user-list‘, request=request, format=format),      # reverse 反转
        ‘snippets‘: reverse(‘snippet-list‘, request=request, format=format),
    })

3、 超链接序列化:HyperlinkedModelSerializer

处理好实体之间的关系:希望在实体之间使用超链接方式

view视图不变

class UserList(generics.ListAPIView):  # user/ get方式
    queryset = User.objects.all().order_by(‘id‘)
    serializer_class = UserSerializer

序列化:继承HyperModelSerilizer

class UserSerializer(serializers.HyperlinkedModelSerializer):   # 实体之间使用超链接方式
    # snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())  # 添加一个显式字段 外键
    # 关联关系,alex的snippet的详情
    # many=True,多个字段,
    snippets = serializers.HyperlinkedRelatedField(many=True, view_name=‘snippet-detail‘, read_only=True)

    class Meta:
        model = User
        fields = [‘url‘, ‘id‘, ‘username‘, ‘snippets‘]

class SnippetSerializer(serializers.ModelSerializer):

    owner = serializers.ReadOnlyField(source=‘owner.username‘)        # source参数控制哪个属性用于填充字段
    # # 它包含一个url字段  该snippet的highlight
    # 单个字段,继承与HyperlinkedRelatedField
    highlight = serializers.HyperlinkedIdentityField(view_name=‘snippet-highlight‘, format=‘html‘)

    class Meta:
        model = Snippet
        fields = [‘url‘, ‘id‘, ‘title‘, ‘code‘, ‘linenos‘, ‘language‘, ‘style‘, ‘owner‘, ‘highlight‘]

4、HyperlinkedModelSerialize与ModelSerializer区别

HyperlinkedModelSerializerModelSerializer有以下区别:

  • 默认情况下不包括id字段。
  • 包含一个url字段,使用HyperlinkedIdentityField
  • 关联关系使用HyperlinkedRelatedField,而不是PrimaryKeyRelatedField

5、高亮代码

model层

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)
    # choices = [(1,‘java‘),(2,‘python‘),(3,‘‘golang‘)]  # 下拉框选择,指代
    language = models.CharField(choices=LANGUAGE_CHOICES, default=‘python‘, max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default=‘friendly‘, max_length=100)

    # Tutorial 4: Authentication & Permissions
    owner = models.ForeignKey(‘auth.User‘, related_name=‘snippets‘, on_delete=models.CASCADE)
    # 设置related_name参数来覆盖原名称owner_id(ORM查询时),实质,DB中还是owner_id
    highlighted = models.TextField()

    class Meta:
        ordering = [‘created‘]

    # def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    def save(self, *args, **kwargs):
        """
        使用pygments库,创建一个高亮显示的HTML,表示代码段
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and ‘table‘ or False
        options = self.title and {‘title‘: self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)  # 继承父类Model的save

6、HTML渲染器

一个HTML渲染器类,简单地返回预渲染的HTML
data = ‘<html><body>example</body></html>‘return Response(data)

view层

from rest_framework import renderers
class SnippetHighlight(generics.GenericAPIView):
    queryset = Snippet.objects.all()
    renderer_classes = [renderers.StaticHTMLRenderer]

    def get(self, request, *args, **kwargs):
        snippet = self.get_object()             # 视图显示的对象。
        return Response(snippet.highlighted)    # 某个字段

原文地址:https://www.cnblogs.com/venicid/p/12012542.html

时间: 2024-08-29 19:44:56

05_Tutorial 5: Relationships & Hyperlinked APIs的相关文章

Tutorial 5: Relationships &amp; Hyperlinked APIs

转载自:http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/ Tutorial 5: Relationships & Hyperlinked APIs At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll

API(五)之Relationships &amp; Hyperlinked APIs

目前,我们的API中的关系用主键表示.在本教程的这一部分中,我们将改进API的内聚力和可发现性,而不是使用关联的超链接. 为我们的API的根创建一个端点 现在我们有'snippets'和'users'的端点,但是我们的API没有一个入口点.为了创建一个入口点,我们将使用一个常规的基于函数的视图和我们之前介绍的装饰器@api_view.在你的snippets/views.py添加: from rest_framework.decorators import api_view from rest_f

Django REST framework 第五章 Relationships &amp; Hyperlinked APIs

到目前为止,API内部的关系是使用主键来代表的.在这篇教程中,我们将提高API的凝聚力和可发现性,通过在相互关系上使用超链接. Creating an endpoint for the root of our API 现在,我们已经有了snippets和users的终端,但是没有一个单独的终端指向我们的API.使用之前常规的FBV方式和@api_view装饰器创建一个.在你的app的views文件内 from rest_framework.decorators import api_view f

django-rest-framework学习之Relationships &amp; Hyperlinked APIs--2017年4月17日至18日

Relationships & Hyperlinked APIs 参考链接: http://www.weiguda.com/blog/23/ http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/ 目前我们API中的关系用primary keys展示,这部分我们会通过hyperlinking提高我们API的内聚性和扩展性 [1]给API的根节点传建一个端点 在views.py中添加:

django restframework 简单总结

官方文档:http://www.django-rest-framework.org/ model.py 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.BooleanFiel

APPCORE Routine APIs

Introduction to APPCORE Routine APIs This chapter provides you with specifications for calling many Oracle E-Business Suite APIs from your PL/SQL procedures. Most routines in the APPCORE library are described here. Some APPCORE routines are described

Java EE 7 教程 第一部分 简介 第1章 概述 第1.7节 Java EE 7 APIs

原文:http://docs.oracle.com/javaee/7/tutorial/doc/overview007.htm 翻译:石卓林 [email protected] 注意:此章是1.8章前移而来,不知为何oracle删除了原1.7开发角色章节 1.7 Java EE 7 APIs Figure 1-6 shows the relationships among the Java EE containers. Figure 1-6 Java EE Containers Descript

Kernel logging: APIs and implementation

Kernel API Logging within the kernel is performed using the printk function int printk( const char * fmt, ... ); The kernel code simply defines the log level as the first argument of the message, as illustrated in the following example for a critical

[Node.js] Creating Demo APIs with json-server

json-server makes it extremely easy to setup robust JSON apis to use for demos and proof of concepts. John walks you through the process of using pre-built json files for a server and how to generate larger datasets using lodash and faker. Install: n