Rest-framework-API参考-Class-based Views

Class-based Views

Django's class-based views are a welcome departure from the old-style views.

Reinout van Rees

REST framework provides anAPIViewclass, which subclasses Django'sViewclass.

REST框架提供了一个apiview类,这类是Django视图类。

APIViewclasses are different from regularViewclasses in the following ways:

APIView类不同于普通视图类在以下方面:

Requests passed to the handler methods will be REST framework'sRequestinstances, not Django'sHttpRequestinstances.

通过对处理方法要求将REST框架的要求的情况下,不是Django的HttpRequest实例。

Handler methods may return REST framework'sResponse, instead of Django'sHttpResponse. The view will manage content negotiation and setting the correct renderer on the response.

Handler方法可以返回REST框架的响应,而不是Django的HttpResponse。视图将管理内容协商和响应设置正确的渲染器。

AnyAPIExceptionexceptions will be caught and mediated into appropriate responses.

任何APIException异常将被介导的适当的反应。

Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.

传入的请求在运行之前将被验证,并将适当的权限或节流检查后发送到处理程序的方法。

Using theAPIViewclass is pretty much the same as using a regularViewclass, as usual, the incoming request is dispatched to an appropriate handler method such as.get()or.post(). Additionally, a number of attributes may be set on the class that control various aspects of the API policy.

使用APIView类是相当经常使用的视图类,传入的请求被分派到一个合适的处理方法,例如.get()or.post()。此外,可以在控制API策略的各个方面的类上设置若干属性。

For example:

fromrest_framework.viewsimportAPIViewfromrest_framework.responseimportResponsefromrest_frameworkimportauthentication,permissionsclassListUsers(APIView):"""

View to list all users in the system.

* Requires token authentication.

* Only admin users are able to access this view.

"""authentication_classes=(authentication.TokenAuthentication,)permission_classes=(permissions.IsAdminUser,)defget(self,request,format=None):"""

Return a list of all users.

"""usernames=[user.usernameforuserinUser.objects.all()]returnResponse(usernames)

API policy attributes

The following attributes control the pluggable aspects of API views.

下列属性控制API视图的可插入方面。

.renderer_classes

.parser_classes

.authentication_classes

.throttle_classes

.permission_classes

.content_negotiation_class

API policy instantiation methods

The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.

.get_renderers(self)

.get_parsers(self)

.get_authenticators(self)

.get_throttles(self)

.get_permissions(self)

.get_content_negotiator(self)

.get_exception_handler(self)

API policy implementation methods

The following methods are called before dispatching to the handler method.

在分发给处理程序方法之前调用以下方法。

.check_permissions(self, request)

.check_throttles(self, request)

.perform_content_negotiation(self, request, force=False)

Dispatch methods

The following methods are called directly by the view's.dispatch()method. These perform any actions that need to occur before or after calling the handler methods such as.get(),.post(),put(),patch()and.delete().

以下的方法是由视图中直接调用。dispatch()方法。这些执行任何操作,需要发生之前或调用处理方法之后,例如.get(),.post(),put(),patch()

.initial(self, request, *args, **kwargs)

Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation.

在处理方法调用之前执行任何需要发生的操作。此方法用于强制权限和节流,并执行内容协商。

You won't typically need to override this method.

.handle_exception(self, exc)

Any exception thrown by the handler method will be passed to this method, which either returns aResponseinstance, or re-raises the exception.

处理方法抛出的任何异常都将传递给该方法,该方法返回响应实例,或重新引发异常。

The default implementation handles any subclass ofrest_framework.exceptions.APIException, as well as Django'sHttp404andPermissionDeniedexceptions, and returns an appropriate error response.

默认的实现处理的任何子类rest_framework.exceptions.apiexception,像Django的Http404和PermissionDenied例外,并返回适当的错误响应。

If you need to customize the error responses your API returns you should subclass this method.

如果需要自定义API返回的错误响应,则应将该方法的子类化为子类。

.initialize_request(self, request, *args, **kwargs)

Ensures that the request object that is passed to the handler method is an instance ofRequest, rather than the usual DjangoHttpRequest.

确保传递给处理程序方法的请求对象是请求的一个实例,而不是通常的HttpRequest。

You won't typically need to override this method.

.finalize_response(self, request, response, *args, **kwargs)

Ensures that anyResponseobject returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.

确保从处理程序方法返回的任何响应对象将被呈现为正确的内容类型,由内容协商确定。

You won't typically need to override this method.

Function Based Views

Saying [that class-based views] is always the superior solution is a mistake.

Nick Coghlan

REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance ofRequest(rather than the usual DjangoHttpRequest) and allows them to return aResponse(instead of a DjangoHttpResponse), and allow you to configure how the request is processed.

REST框架允许您使用基于正则函数的视图。它提供了一套简单的装饰,把你的功能观确保他们接受请求的实例(而不是通常的Django HttpRequest)并允许他们返回响应(而不是一个Django HttpResponse),并允许您配置如何处理请求。

@api_view()

Signature:@api_view(http_method_names=['GET'], exclude_from_schema=False)

The core of this functionality is theapi_viewdecorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:

此功能的核心是api_view装饰,以一个列表的HTTP方法视图应该回应。例如,您将如何编写一个非常简单的视图,该视图只手动返回一些数据:

fromrest_framework.decoratorsimportapi_view@api_view()defhello_world(request):returnResponse({"message":"Hello, world!"})

This view will use the default renderers, parsers, authentication classes etc specified in thesettings.

这种视图将使用默认的renderers, parsers, authentication等类的设置指定

By default onlyGETmethods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:

这种默认只适用于GET方法,其他方法将返回"405 Method Not Allowed",若要更改此行为,请指定视图允许的方法,例如:

@api_view(['GET','POST'])defhello_world(request):ifrequest.method=='POST':returnResponse({"message":"Got some data!","data":request.data})returnResponse({"message":"Hello, world!"})

You can also mark an API view as being omitted from anyauto-generated schema, using theexclude_from_schemaargument.:

你也可以标记一个API视图是从任何自动生成的架构略,使用exclude_from_schema。

@api_view(['GET'],exclude_from_schema=True)defapi_docs(request):...

API policy decorators

To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must comeafter(below) the@api_viewdecorator. For example, to create a view that uses athrottleto ensure it can only be called once per day by a particular user, use the@throttle_classesdecorator, passing a list of throttle classes:

为了覆盖默认设置,REST框架提供了一套额外的装饰可以被添加到你视图里。这些必须经过@api_view装饰。例如,创建一个视图,使用油门确保它只能由特定用户每天一次,使用@throttle_classes装饰,通过节流阀类的列表:

fromrest_framework.decoratorsimportapi_view,throttle_classesfromrest_framework.throttlingimportUserRateThrottleclassOncePerDayUserThrottle(UserRateThrottle):rate='1/day'@api_view(['GET'])@throttle_classes([OncePerDayUserThrottle])defview(request):returnResponse({"message":"Hello for today! See you tomorrow!"})

These decorators correspond to the attributes set onAPIViewsubclasses, described above.

The available decorators are:

@renderer_classes(...)

@parser_classes(...)

@authentication_classes(...)

@throttle_classes(...)

@permission_classes(...)

Each of these decorators takes a single argument which must be a list or tuple of classes.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容

  • API Reference GenericAPIView This class extends REST fram...
    阳光小镇少爷阅读 2,577评论 0 1
  • 日子决了堤 在看不见的眼前,你默许
    凉白唐阅读 145评论 2 2
  • 自 画 像□叔兮伯兮 有谁不想当好笔杆子假如不能酝酿大手笔也要炮制一个新说法这是必然的,也是必须的纠结于标点符号、...
    程文敏阅读 328评论 0 4
  • 星期四我和妈妈复习了,就为了准备今天的期中考试,我做完了就检查了一遍,不知道我能不能的一百分,我希望能得一百分。我...
    王文哲同学阅读 200评论 0 0
  • 我小的时候,同龄人的一个大乐趣是:淘宝。我这里所说的淘宝是真的:每到不上学的时候,我们这些男孩子,就去村子里的垃圾...
    东语西言阅读 294评论 0 0