国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專(zhuān)欄INFORMATION COLUMN

Django框架的學(xué)習(xí)筆記

freecode / 2958人閱讀

摘要:注意,在提供序列化器對(duì)象的時(shí)候,會(huì)向?qū)ο蟮膶傩匝a(bǔ)充三個(gè)數(shù)據(jù),這三個(gè)數(shù)據(jù)對(duì)象可以在定義序列化器時(shí)使用。舉例以圖書(shū)與英雄案例如水滸傳與英雄對(duì)應(yīng)的路由數(shù)據(jù)查詢集數(shù)據(jù)庫(kù)查詢集數(shù)據(jù)庫(kù)查詢構(gòu)建序列化器對(duì)象進(jìn)行序列化操作對(duì)應(yīng)的路由查詢單個(gè)

基于Django的REST framework 框架的視圖說(shuō)明(二)

開(kāi)發(fā)環(huán)境:Ubuntu16.04+Python3.5x+Pycharm2018.2

包含方法和屬性的通用視圖基類(lèi)及擴(kuò)展類(lèi)的繼承關(guān)系

兩個(gè)基類(lèi) APIView類(lèi) GenericAPIView類(lèi)

本篇主要說(shuō)明GenericAPIView類(lèi)
rest_framework.generics.GenericAPIView

繼承自APIView,增加了對(duì)于列表視圖和詳情視圖可能用到的通用支持方法。通常使用時(shí),可搭配一個(gè)或多個(gè)Mixin擴(kuò)展類(lèi).

支持定義的屬性:

列表視圖與詳情視圖通用:
queryset 列表視圖的查詢集
serializer_class 視圖使用的序列化器

列表視圖使用:
pagination_class 分頁(yè)控制類(lèi)
filter_backends 過(guò)濾控制后端

詳情頁(yè)視圖使用:
lookup_field 查詢單一數(shù)據(jù)庫(kù)對(duì)象時(shí)使用的條件字段,默認(rèn)為"pk"
lookup_url_kwarg 查詢單一數(shù)據(jù)時(shí)URL中的參數(shù)關(guān)鍵字名稱(chēng),默認(rèn)與look_field相同

源代碼如下:

    queryset = None
    serializer_class = None

    # If you want to use object lookups other than pk, set "lookup_field".
    # For more complex lookup requirements override `get_object()`.
    lookup_field = "pk"
    lookup_url_kwarg = None

    # The filter backend classes to use for queryset filtering
    filter_backends = api_settings.DEFAULT_FILTER_BACKENDS

    # The style to use for queryset pagination.
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS

支持定義的方法:

列表視圖與詳情視圖通用:

get_queryset(self)
源碼如下:

   def get_queryset(self):
        """
        Get the list of items for this view.
        This must be an iterable, and may be a queryset.
        Defaults to using `self.queryset`.

        This method should always be used rather than accessing `self.queryset`
        directly, as `self.queryset` gets evaluated only once, and those results
        are cached for all subsequent requests.

        You may want to override this if you need to provide different
        querysets depending on the incoming request.

        (Eg. return a list of items that is specific to the user)
        """
        assert self.queryset is not None, (
            ""%s" should either include a `queryset` attribute, "
            "or override the `get_queryset()` method."
            % self.__class__.__name__
        )

        queryset = self.queryset
        if isinstance(queryset, QuerySet):
            # Ensure queryset is re-evaluated on each request.
            queryset = queryset.all()
        return queryset

返回視圖使用的查詢集,是列表視圖與詳情視圖獲取數(shù)據(jù)的基礎(chǔ),默認(rèn)返回queryset屬性,可以重寫(xiě),例如:

def get_queryset(self):
    user = self.request.user
    return user.accounts.all()      

get_serializer_class(self)

    def get_serializer_class(self):
        """
        Return the class to use for the serializer.
        Defaults to using `self.serializer_class`.

        You may want to override this if you need to provide different
        serializations depending on the incoming request.

        (Eg. admins get full serialization, others get basic serialization)
        """
        assert self.serializer_class is not None, (
            ""%s" should either include a `serializer_class` attribute, "
            "or override the `get_serializer_class()` method."
            % self.__class__.__name__
        )

        return self.serializer_class

返回序列化器類(lèi),默認(rèn)返回serializer_class,可以重寫(xiě),例如:

def get_serializer_class(self):
    if self.request.user.is_staff:
        return FullAccountSerializer
    return BasicAccountSerializer
    

get_serializer(self, args, **kwargs)
返回序列化器對(duì)象,被其他視圖或擴(kuò)展類(lèi)使用,如果我們?cè)谝晥D中想要獲取序列化器對(duì)象,可以直接調(diào)用此方法。

注意,在提供序列化器對(duì)象的時(shí)候,REST framework會(huì)向?qū)ο蟮腸ontext屬性補(bǔ)充三個(gè)數(shù)據(jù):request、format、view,這三個(gè)數(shù)據(jù)對(duì)象可以在定義序列化器時(shí)使用。

詳情視圖使用:

get_object(self)

   def get_object(self):
        """
        Returns the object the view is displaying.

        You may want to override this if you need to provide non-standard
        queryset lookups.  Eg if objects are referenced using multiple
        keyword arguments in the url conf.
        """
        queryset = self.filter_queryset(self.get_queryset())

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in self.kwargs, (
            "Expected view %s to be called with a URL keyword argument "
            "named "%s". Fix your URL conf, or set the `.lookup_field` "
            "attribute on the view correctly." %
            (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        obj = get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, obj)

        return obj

返回詳情視圖所需的模型類(lèi)數(shù)據(jù)對(duì)象,默認(rèn)使用lookup_field參數(shù)來(lái)過(guò)濾queryset。 在試圖中可以調(diào)用該方法獲取詳情信息的模型類(lèi)對(duì)象。

若詳情訪問(wèn)的模型類(lèi)對(duì)象不存在,會(huì)返回404。

def get_object_or_404(queryset, *filter_args, **filter_kwargs):
    """
    Same as Django"s standard shortcut, but make sure to also raise 404
    if the filter_kwargs don"t match the required types.
    """
    try:
        return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
    except (TypeError, ValueError, ValidationError):
        raise Http404

該方法會(huì)默認(rèn)使用APIView提供的check_object_permissions方法檢查當(dāng)前對(duì)象是否有權(quán)限被訪問(wèn)。

舉例:以圖書(shū)與英雄案例(如水滸傳與英雄)

# GET /books/
# url(r"^books/$", views.BookListAPIView.as_view()) 對(duì)應(yīng)的路由
class BookListAPIView(GenericAPIView):
    """
    數(shù)據(jù)查詢集
    """
    queryset = BookInfo.objects.all()  # 數(shù)據(jù)庫(kù)查詢集
    serializer_class = BookInfoSerializer

    def get(self,request):
        # 數(shù)據(jù)庫(kù)查詢
        qs = self.get_queryset()
        # 構(gòu)建序列化器對(duì)象,進(jìn)行序列化操作
        serializer = self.get_serializer(qs,many = True)

        return  Response(serializer.data)

# GET /books//
# url(r"^books/(?Pd+)/$", views.BookDetailView.as_view()) 對(duì)應(yīng)的路由
class BookDetailAPIView(GenericAPIView):
    queryset = BookInfo.objects.all()

    serializer_class = BookInfoSerializer


    def get(self,request,pk):
        """
        查詢單個(gè)
        :param query:
        :return:
        """
        book = self.get_object()
        serializer = self.get_serializer(book)

        return Response(serializer.data)

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/42434.html

相關(guān)文章

  • python第三方庫(kù)之Django學(xué)習(xí)筆記

    摘要:上一節(jié)項(xiàng)目框架已經(jīng)搭建完畢,現(xiàn)在開(kāi)始連接數(shù)據(jù)庫(kù),創(chuàng)建數(shù)據(jù)庫(kù)設(shè)置默認(rèn)安裝了數(shù)據(jù)庫(kù)打開(kāi)文件數(shù)據(jù)庫(kù)引擎數(shù)據(jù)庫(kù)的名字小貼士如果你選擇,數(shù)據(jù)庫(kù)是以文件的形式生成,要設(shè)置成絕對(duì)路徑創(chuàng)建表結(jié)構(gòu)創(chuàng)建模型激活模型執(zhí)行命令執(zhí)行成功后目錄結(jié)構(gòu)如下圖 上一節(jié)項(xiàng)目框架已經(jīng)搭建完畢,現(xiàn)在開(kāi)始連接數(shù)據(jù)庫(kù),創(chuàng)建model 1、數(shù)據(jù)庫(kù)設(shè)置python默認(rèn)安裝了sqlite數(shù)據(jù)庫(kù) 打開(kāi)文件:dayang/settings...

    Java3y 評(píng)論0 收藏0
  • Python學(xué)習(xí)筆記:Web后端開(kāi)發(fā)一覽

    摘要:試想,在多線程服務(wù)器中,多個(gè)線程同時(shí)處理不同客戶端發(fā)送的不同請(qǐng)求時(shí),每個(gè)線程看到的對(duì)象必然不同。多線程服務(wù)器會(huì)創(chuàng)建一個(gè)線程池,再?gòu)木€程池中選擇一個(gè)線程用于處理接收到的請(qǐng)求。 框架 Django flask flask是一個(gè)輕量的web開(kāi)發(fā)應(yīng)用示例開(kāi)發(fā)一個(gè)小應(yīng)用 from flask import Flask app = Flask(__name__) @app.route(/) d...

    DrizzleX 評(píng)論0 收藏0
  • 第一本 gitbook: Flask Web 開(kāi)發(fā)筆記

    摘要:月份發(fā)布了第版,收到不少網(wǎng)友的良好建議,所以又抽空進(jìn)行了完善,當(dāng)然也拖了不少時(shí)間。本書(shū)主要介紹的基本使用,這也是我一開(kāi)始在學(xué)習(xí)過(guò)程中經(jīng)常用到的。第章實(shí)戰(zhàn),介紹了如何開(kāi)發(fā)一個(gè)簡(jiǎn)單的應(yīng)用。聲明本書(shū)由編寫(xiě),采用協(xié)議發(fā)布。 showImg(https://segmentfault.com/img/remote/1460000007484050?w=200&h=152); 書(shū)籍地址 head-f...

    KevinYan 評(píng)論0 收藏0
  • django rest framework個(gè)人學(xué)習(xí)筆記(一)————Install

    摘要:本文主要是用來(lái)記錄自己學(xué)習(xí)的過(guò)程。其中可能會(huì)有很多自己的錯(cuò)誤理解。這里主要會(huì)用到的知識(shí)有百度百科阮一峰理解架構(gòu)其余請(qǐng)自行百度。所有的全局設(shè)置都放在的字典中。使用標(biāo)準(zhǔn)的權(quán)限,未認(rèn)證的用戶只讀權(quán)限不要忘記將添加到你的中。 本文主要是用來(lái)記錄自己學(xué)習(xí)django-rest-framework的過(guò)程。其中可能會(huì)有很多自己的錯(cuò)誤理解。 這里主要會(huì)用到的知識(shí)有 1. [django](https:...

    yuxue 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<