CBV source flow 1, create URL2. Create a View class3, As_view method source codeBecause our custom attempt class inherits the view class, the As_view function in the URL executes when the project is started, and without this method in our custom function class, we find it in the parent class.4. View function5, Dispatch6. Supplement (Http_method_names)Execution in the view function in the URL# ## url (r ' ^login/', View.view), Apiview Execution Source
Source code Anatomy of the Django REST Framework authentication method
By the Django CBV mode flow, you can know the url匹配完成后,会执行自定义的类中的as_view方法 .
If there is no definition in the custom class as_view方法 , depending on the inheritance of classes in the object-oriented class, you can会执行其父类View中的as_view方法
在
fromApi.serializers.indexImportIndexserializerclassP2 (pagenumberpagination):#number of data bars displayed per pageMax_page_size = 5page_size= 2Page_size_query_param='size' #Page NumberPage_query_param ='page' classIndexview (viewsets. Modelviewset):#you can also not inherit Modelviewset, inherit a few of the above classes, there are only a few methodsQueryset =models. UserInfo.objects.all () Serializer_class=Indexserializer Pagination_class=P2
1. Previously Django-made paging components, when the amount of data is particularly large, performance is not very high, there are three ways to handle:A. Record the last data ID of the current access page, and fetch the number of entriesB. Display up to 120 pagesC. Encrypt page numbers (show previous page, next page only)2.rest Framework PagingFrom rest_framewo
Pagination_class=P2 Third class: Automatically help us to generate four kinds of url,index/$,index/(? p)$ fromRest_framework.routersImportDefaultrouter Router=Defaultrouter () router.register ('Index', views. Indexviewset) Urlpatterns=[url (r'^', include (Router.urls)),]classIndexviewset (viewsets. Modelviewset): Queryset=models. UserInfo.objects.all () Serializer_class=Indexserializer Pagination_class=P2classIndexserializer (serializers. Modelserializer):classMeta:model=models. UserInf
1. Parser: Parse the requested data-the request body for parsing. The parser is not called when you do not take the request body data.classUsersview (apiview):defGet (self,request,*args,**Kwargs):returnResponse ('...') defPost (self,request,*args,**Kwargs):## Application/json #print (request._request.body) # B "xxxxx" Decode () Json.loads #Print (request._request. POST) # None #when the data format of the POST request is Applic
': (
' DataAPI.common.api_exception.custom_exception_handler '
)
# ' Exception_ HANDLER ': ' My_project.my_app.utils.custom_exception_handler '
}
two. return value
As the exception shows, we often return the same type of value, as shown below, basic data format and paging format (later)
{
"desc": "Page Success", #描述信息
"code": #响应码 to start with 2 is the success of
"data": {
"detail": array[2], #当前页数据列表
" Total ": 6, #页面总数
" page ": 2 #当前页面
determines the correct content type based on the request header information of the client to return it to the client. You only need the following code:
Iii. Status Code
Do we know that various statuses will be returned when an http request is sent, but they are all simple numbers, such as 200 and 404, these pure numeric identifiers may not be clear enough, or the client may not be clear about the error message or even fail to see it, so django-
': 100 }}# class authentication (apiview ): # "# authentication class #" "# def authenticate (self, request): # token = request. _ request. get. get ('Token') # token_obj = models. usertoken. objects. filter (token = token ). first () # if not token_obj: # Raise exceptions. authenticationfailed ('user authentication failed') # the two fields are assigned to the request in the rest
token保存到这个用户数据库token_value字段中 Value.save () user_list = [] #取出对象 (query to the user data), this for can not because of the uniqueness of the data, direct index, too lazy to change, in fact, above have already taken, too lazy to change #想把用户名取出来返回出去 for the users in inster_token:name_info= [Users.user_name,users.token_value] User_list.append (name_info) usersinfo=user_l IST[0] # return Dictionary datas = {' status ': ' True ', ' message ': ' Login successful! '
Django-rest-framework quick start,
The first contact with django-rest-framework was during the internship. I didn't understand it at the time, and it was awesome to see that the view was written using the class method. Because the
Serialization of django-rest-framework,
Preface:I learned about rest-framework serialization yesterday, so I wrote a blog record. Official Website: http://www.django-rest-framework.org/tutorial/1-serialization/?working-with-serial
Django rest framework basic introduction and sample code, djangoframework
This article focuses on Django rest framework and shares example as follows.
The Django
The content of this section
Django Rest Framework Installation
Django Rest framwwork Environment configuration
Simple example Description
Using the rest framework i
Use Serializermethodfield in the Django REST framework to optimize unnecessary queriesFirst look at an example, in general, for objects that have parent-child relationships, we use the following method to create the class.A article class in which a article object can have multiple comment instances, the class in Django
foreign key dataSerializer = Myserializer (data=Request.data, context={"author": User})#if the deserialized object exists, it means that the data is valid and the data is saved to the database
ifserializer.is_valid ():#call Save () to invoke the Create () method of the serialized object, creating a piece of data
Serializer.save ()returnResponse (Serializer.data, status=status. HTTP_200_OK)returnResponse (Serializer.errors, Status=status. Http_400_bad_request) How the
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.