Summary of common Django interview questions (2)

Continued from the previous article: /YZL40514131/article/details/125813096?spm=1001.2014.3001.5501

21. What is the difference between selected_related and prefetch_related? (important)

In Django, all Querysets are lazy, which means that when a queryset is created, there is no interaction with the database. Therefore, we can perform cascaded filter operations on the queryset. Only when the content of the Queryset is accessed, Django will actually access the database. And multi-frequency and complex database queries are often the biggest source of performance problems.
However, in our actual development, we often need to access other properties of the foreign key object. If the default query method is used to traverse the value, it will cause multiple database queries, and the efficiency can be imagined.

When querying the object collection, the specified foreign key objects are also fully loaded with the query to avoid subsequent repeated queries.
1. select_relatedApplicable to foreign key and many-to-one relational queries;
2. prefetch_relatedApplicable to one-to-many or many-to-many queries.

22. What is a cookie, how to obtain and set a cookie

Session tracking technology that retains a user
cookie is a key-value pair created by the server and then sent to the client in response.
A specific key-value ({}) stored by a browser for a server

set cookies

response.set_cookie("is_login",True)

Obtain

request.COOKIES.get("is_login")

23. What is [session] , compare with cookie, set, get, clear session

Session is a server-side technology. Using this technology, the server can create an exclusive session object for each user’s browser at runtime. Since the session is exclusive to the user’s browser, when the user accesses the server’s web resources, The respective data can be placed in their respective sessions, and when the user accesses other web resources in the server, the other web resources take out data from the user’s respective session to serve the user.

set session

request.session[ 'username' ]= "kobe" 
request.session.set_expiry(7*24*3600)        # Set the session expiration time to one week later

get session

username=request.session.get('age','')

delete session

request.session.flush()

24. Briefly describe what is FBV and CBV

FBV (function base views) is to use functions in the view function to process requests
CBV (class base views) is to use classes in the view to process requests

Twenty-five, the difference between the command migrate and makemigrations

Generate migration files

perform migration

python manage.py migrate

26. In the view function, what are the common methods and attributes of the received request object?

request.get: query string parameter request.post:
form form parameter
request.body: non-form data
request.FILES: a dictionary-like object containing all uploaded files
request.user: request user
request.path: request url
request.method: request method

27. There are several forms of [Django ‘s Model inheritance, what are they?]

Focus: Describe abstract model classes

28. Which function in Form needs to be used to verify whether the form is submitted correctly in Django

*serializer.is_valid()*

29. What are the two characteristics of query sets? What is lazy execution (important)

*Lazy execution, caching. 
Using the same query set, a database query will occur when it is used for the first time, and then Django will cache the results. When using the query set again, the cached data will be used, reducing the number of database queries.
Create a new query set object. accomplish
*

30. What are the list filters returned by the query set?

all()
filter()
exclude()
order_by()

31. In Django, how many ways does the server respond to the client? What are they?

HttpResponse,
JsonResponse,
redirect

Thirty-two, the difference between QueryDict and dict

*In the HttpRequest object, the GET and POST properties are instances of the django.http.QueryDict class.*
QueryDict is a dictionary-like custom class used to handle the situation where a single key corresponds to multiple values.
In python’s original dictionary, a conflict occurs when there are multiple values ​​for a key, and only the last value is kept . In HTML forms, it usually happens that a key has more than one value, such as (multi-select box) is a very common situation.****

Thirty-three, how to set a primary key for a field

primary_key

Thirty-four, explain blank and null

blank

When set to True, the field can be empty. When set to False, the field is mandatory. Character fields CharField and TextField use empty strings to store null values. If True, the field is allowed to be empty, the default is not allowed.

null

When set to True, django uses Null to store empty values. Date, time, and number fields do not accept empty strings. Therefore, when the IntegerField and DateTimeField fields can be set to be empty, blank and null need to be set to True.

35. How to register routes in django urlpatterns

router=routers.SimpleRouter()
router.register('project', view class)

urlpatterns=[
    path('',include(router.urls))

]

Thirty-six, how to load initialization data in Django

After Django uses the save() method when creating an object, the ORM framework will convert the attributes of the object to be written into the database to initialize the database; by operating the object, querying the database, and returning the query set to the view function, Displayed on front-end pages through template language

Thirty-seven, create Django projects, Django apps, and run commands

django-admin  startproject django_project create a project 
python  manage.py runserver run project 
python  manage.py startapp sub-application name create sub-application 
python  manage.py makemigrations sub-application name create migration script 
python  manage.py migrate generate migration script 
python  manage,py createsuperuser Create admin user 
python  manage.py shell terminal to debug code

38. Briefly describe the authentication process of the django rest framework. (Very important)

1 Create a sub-app

python manage.py startapp users

2 Register sub-apps

INSTALLED_APPS = [
     'django.contrib.admin' ,
     'django.contrib.auth' ,
     'django.contrib.contenttypes' ,
     'django.contrib.sessions' ,
     'django.contrib.messages' ,
     'django.contrib.staticfiles' ,
     'corsheaders' ,   # Same-origin policy 
    'rest_framework' ,
     'drf_yasg' ,   # Generate interface document sub-application 
    'django_filters' ,   # DRF filter sub-application 
    'users' ,
]

3 Adopt JWT TOKEN certification

a Download django-restframework-jwt

pip install djangorestframework-jwt

Specify the use of jwt TOKEN authentication class in the b settings.py file

REST_FRAMEWORK = {
     # Specify the search engine class 
    'DEFAULT_FILTER_BACKENDS' : [ 'rest_framework.filters.SearchFilter' ,
                                 'rest_framework.filters.OrderingFilter' , ],

    # 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'],
    # 'SEARCH_PARAM': 'se',

    # Specify the paging engine class 
    'DEFAULT_PAGINATION_CLASS' : 'rest_framework.pagination.PageNumberPagination' ,
     'PAGE_SIZE' : 3,

    # Specify the schema used to support coreapi 
    'DEFAULT_SCHEMA_CLASS' : 'rest_framework.schemas.coreapi.AutoSchema' ,

    # Specify the authentication class to use 
    # a. Specify the default authentication class (authentication method) globally 
    'DEFAULT_AUTHENTICATION_CLASSES' : [
         # 1. Specify jwt token authentication 
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication' ,
         'rest_framework.authentication.SessionAuthentication' ,
         'rest_framework .authentication.BasicAuthentication' ,
    ],
}

4 Configure routing, you can perform user name and password authentication

global routing

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('',include('projects.urls')),

    path( 'docs/' ,include_docs_urls(title= 'Interface test platform API document' ,description= 'This is the interface platform document' )),


    path('user/',include('users.urls'))
]

Subroute:

urlpatterns=[
    path('',include(router.urls)),
    re_path(r'^(?P<username>\w{6,20})/count/$', views.UsernameIsExistedView.as_view()),
    re_path(r'^(?P<email>[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+)/count/$',
            views.EmailIsExistedView.as_view()),
    path('login/', obtain_jwt_token),
]

test

5 Rewrite the method of generating token: output the username and user id together

a. In the project public file utils, create a new handle_jwt_response.py file

def jwt_response_payload_handler(token,user=None,response=None):
    return {
        'user_id':user.id,
        'username':user.username,
        'token':token
    }

b. It is also necessary to specify the token expiration time and the specified access path in the settings.py file. The purpose is to allow the project to find its own rewriting method when it is running;

# JWT configuration
JWT_AUTH = {
    # Specify the token expiration time as 1 day 
    'JWT_EXPIRATION_DELTA' : datetime.timedelta(days=1),
     # Use your own jwt_response_payload_handler, the purpose is to return the username and id in the response result 
    'JWT_RESPONSE_PAYLOAD_HANDLER' : 'utils.handle_jwt_response.jwt_response_payload_handler' ,

}

test

39. How does django rest framework implement user access frequency control? (Very important)

1 Global configuration in the settings.py file, all class views that inherit APIView will take effect

REST_FRAMEWORK = {
    ...
    ...
    ...

    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES' : {
         'anon' : '100/day' ,   # anonymous user 
        'user' : '10/day'
    }
}

2 Local configuration (add throttle_classes = [CustomAnonRateThrottle] to the specified class view that inherits APIVIew, this class view has the current limiting function)

Create a new throttle_class.py file in the public file

utils—–>throttle_class.py, defines CustomAnonRateThrottle (optional), but must inherit UserRateThrottle
UserRateThrottle: indicates that it is facing the logged-in user

from rest_framework.throttling import UserRateThrottle

class CustomAnonRateThrottle(UserRateThrottle):
    THROTTLE_RATES = {"user": "5/day"}

from utils.throttle_class import CustomAnonRateThrottle

class ProjectsViewSet(viewsets.ModelViewSet):
    queryset=Projects.objects.all()
    serializer_class = ProjectsSerializer
    pagination_class = PageNumberPagination
    permission_classes = [permissions.IsAuthenticated]
    throttle_classes = [CustomAnonRateThrottle]

    def list(self, request, *args, **kwargs):
        response=super().list(request, *args, **kwargs)
        for item in response.data['results']:
            item['interfaces']=Interfaces.objects.filter(project_id__exact=item['id']).count()
            item['testsuits']=Testsuits.objects.filter(project_id__exact=item['id']).count()
            item['testcases']=Testcases.objects.filter(interface__project_id__exact=item['id']).count()
            item['configures']=Configures.objects.filter(interface__project_id__exact=item['id']).count()
        return response

3 tests:

Forty, what is the difference between values() and values_list()?

values ​​: take the queryset of the dictionary
values_list : take the queryset of the tuple

Leave a Comment

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