程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Summary of common interview questions in Django (II)

編輯:Python

Next to the last article :https://blog.csdn.net//article/details/125813096?spm=1001.2014.3001.5501

The 21st 、selected_related And prefetch_related What's the difference? ?( important )

stay Django in , be-all Queryset It's all inert , When creating a query set , No interaction with the database . Therefore, we can cascade query sets filter Wait for the operation , Only during the visit Queryset When ,Django Will really access the database . And multi frequency 、 Complex database queries are often the biggest source of performance problems .
But we are actually developing , You often need to access other properties of the foreign key object . If you traverse the values according to the default query method , Then it will cause multiple database queries , Efficiency is conceivable .

When querying a collection of objects , Load the specified foreign key object with a complete query , Avoid subsequent repeated queries .
1,select_related It is applicable to foreign key and many to one relational queries ;
2,prefetch_related It is suitable for one to many or many to many queries .

Twenty-two 、 What is? Cookie、 How to get 、 Set up Cookie

Session tracking technology , Reserved users
Cookie It's created by the server , Then send a key value pair to the client through the response .
Specifically, a browser stores data for a server key-value({ })

Set up Cookie

response.set_cookie("is_login",True)

obtain

request.COOKIES.get("is_login")

23 、 What is? session, And cookie Comparison of 、 Set up 、 obtain 、 Empty session

Session It's server-side technology , Using this technology , The server can Create a unique... For each user's browser session object , because session Exclusive for user browser , So the user is accessing the server web Resource time , You can put your own data in your own session in , When the user goes to visit other servers web Resource time , Other web Resources from the user's own session in Take out data to serve users .

Set up session

request.session['username']="kobe"
request.session.set_expiry(7*24*3600) # Set up session The expiration time is one week

obtain session

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

Delete session

request.session.flush()

Twenty-four 、 Briefly describe what is FBV and CBV

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

twenty-five 、 command migrate and makemigrations The difference between

Generate migration file

python manage.py makemigration Subapplication name

Perform the migration

python manage.py migrate

hexacosa- 、 In the view function , What are the common methods and properties of the received request object

request.get: Query string parameters
request.post:form Form parameters
request.body: Non form data
request.FILES: A dictionary like object , Include all uploads
request.user: Requesting users
request.path: request url
request.method: Request mode

twenty-seven 、Django Of Model There are several forms of inheritance , What are the differences

a key : Describe abstract model classes

Twenty-eight 、Django To verify that the form submission is in the correct format, you need Form Which function in

serializer.is_valid()

Twenty-nine 、 Two major features of query sets ? What is lazy execution ( important )

Inert execution 、 cache .
Use the same query set , The first time you use it, you will query the database , then Django Will cache the results , When this query set is used again, the cached data will be used , Reduce the number of database queries
You can create a new query set object

thirty 、 What are the list filters returned by the query set

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

Thirty-one 、 stay Django in , There are several ways for the server to respond to the client ? What are the differences ?

HttpResponse,
JsonResponse,
redirect

Thirty-two 、QueryDict and dict difference

stay HttpRequest In the object , GET and POST The attribute is django.http.QueryDict Class .
QueryDict A custom class similar to a dictionary , It is used to deal with the situation that single key corresponds to multiple values .
stay python In the original dictionary , When a key has multiple values, a conflict occurs , Keep only the last value . And in the HTML In the form , It usually happens that a key has multiple values , for example ( Checkbox ) 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

Set to True when , Field can be empty . Set to False when , Fields are required . Character field CharField and TextField Is to use an empty string to store null values . If True, Field is allowed to be empty , Not allowed by default .

null

Set to True when ,django use Null To store null values . Date type 、 Temporal and numeric fields do not accept empty strings . So set IntegerField,DateTimeField When the type field can be empty , Need to put blank,null All set to True.

thirty-five 、 How to be in django urlpatterns Registered routing

router=routers.SimpleRouter()
router.register('project', View class )
urlpatterns=[
path('',include(router.urls))
]

Thirty-six 、Django How to load initialization data in

Django Used when creating objects save() After the method ,ORM The framework will convert the properties of the object into writing to the database , Realize the initialization of the database ; By manipulating objects , Query the database , Returns the query set to the view function , Displayed on the front page through template language

Thirty-seven 、 establish Django engineering 、Django app、 And the command to run

django-admin startproject django_project Create a project
python manage.py runserver Run the project
python manage.py startapp Subapplication name Create subapplication
python manage.py makemigrations Subapplication name Create migration script
python manage.py migrate Generate migration scripts
python manage,py createsuperuser Create administrator user
python manage.py shell Terminal debugging code

Thirty-eight 、 sketch django rest framework Certification process of framework .( It's very important )

1 Create subapplication

python manage.py startapp users

2 Register subapplication

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

3 use JWT TOKEN authentication

a download django-restframework-jwt

pip install djangorestframework-jwt

b settings.py The file specifies the use of jwt TOKEN Certification

REST_FRAMEWORK = {
# Specify search engine classes
'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 for support coreapi Of Schema
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
# Specify the authentication class to use
# a、 Specify the default authentication class globally ( authentication )
'DEFAULT_AUTHENTICATION_CLASSES': [
# 1、 Appoint jwt token authentication
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
],
}

4 Configure the routing , You can authenticate with user name and password

Global routing

urlpatterns = [
path('admin/', admin.site.urls),
re_path('',include('projects.urls')),
path('docs/',include_docs_urls(title=' Interface test platform API file ',description=' This is the documentation of the interface platform ')),
re_path(r'^swagger(?P<format>.json|.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), # <-- here
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # <-- here
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), # <-- here
path('user/',include('users.urls'))
]

Sub route :

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 One - A kind of ][email protected][a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+)/count/$',
views.EmailIsExistedView.as_view()),
path('login/', obtain_jwt_token),
]

test

5 Rewrite generation token Methods : The user name and the user name id Output together

a、 In the project public file utils in , newly build 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、 Had in settings.py The document specifies token Expiration time and specified access path , The purpose is : Let the project runtime find its own rewriting method ;

# JWT To configure
JWT_AUTH = {
# Appoint token The failure time is 1 God
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
# Use your own jwt_response_payload_handler, The purpose is to return the user name and... In the response result id
'JWT_RESPONSE_PAYLOAD_HANDLER': 'utils.handle_jwt_response.jwt_response_payload_handler',
}

test

Thirty-nine 、django rest framework How to control user access frequency ?( It's very important )

1 settings.py Global configuration in the file , All inheritance APIView All class views will take effect

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

2 Local configuration ( In the specified inheritance APIVIew Add throttle_classes = [CustomAnonRateThrottle], This kind of view has current limiting function )

New in public file throttle_class.py file

utils----->throttle_class.py, Definition CustomAnonRateThrottle( at will ), But you have to inherit UserRateThrottle
UserRateThrottle: Indicates that it is facing the login 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 test :

Forty 、values() And values_list() What's the difference? ?

values : Dictionary taking queryset
values_list : Tuple queryset


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved