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 .
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({ })
response.set_cookie("is_login",True)
request.COOKIES.get("is_login")
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 .
request.session['username']="kobe"
request.session.set_expiry(7*24*3600) # Set up session The expiration time is one week
username=request.session.get('age','')
request.session.flush()
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
python manage.py makemigration Subapplication name
python manage.py migrate
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
a key : Describe abstract model classes
serializer.is_valid()
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
all()
filter()
exclude()
order_by()
HttpResponse,
JsonResponse,
redirect
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 .
primary_key
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 .
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.
router=routers.SimpleRouter()
router.register('project', View class )
urlpatterns=[
path('',include(router.urls))
]
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
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
python manage.py startapp users
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',
]
pip install djangorestframework-jwt
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',
],
}
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'))
]
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),
]
def jwt_response_payload_handler(token,user=None,response=None):
return {
'user_id':user.id,
'username':user.username,
'token':token
}
# 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',
}
REST_FRAMEWORK = {
...
...
...
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day', # Anonymous users
'user': '10/day'
}
}
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
values : Dictionary taking queryset
values_list : Tuple queryset