This article is participating in Python Theme Month. See the link for details

Python

What is the Python garbage collection mechanism

As a Python user, garbage collection in Python is mainly based on reference counting, followed by the introduction of markup, cleaning, and generation to solve the problem of circular reference.

When an object is referenced, the reference count is incremented by one, and when the object is deled, the reference count is subtracted by one to zero, and the object is cleared. In general, the user does not operate Python’s garbage collection mechanism, but it has an API.

The difference between 2 tuples and lists

The main difference is that lists are mutable, whereas tuples are immutable.

>>> mylist=[1.3.3]
>>> mylist[1] =2


>>> mytuple=(1.3.3)
>>> mytuple[1] =2
Traceback (most recent call last):
File "<pyshell#97>", line 1.in <module>
Copy the code

Can a 3-tuple be a dictionary key?

Whether an object can be a dictionary key in the first place depends on whether it has a __hash__ method. So, except for container objects (list/dict/set) and tuples containing container objects, all objects can be used as dictionary keys.

4 Process thread coroutine

4.1 process

The basic unit of the operating system for resource allocation and scheduling. Multiple processes are independent of each other

2. Good stability. If a process crashes, it does not affect other processes, but the process consumes large resources and the number of open processes is limited

4.2 the thread

1. The basic unit of CPU resource allocation and scheduling. A thread is a part of a process and a basic unit smaller than a process that can run independently

2, if the IO operation intensive, you can multithreaded running efficiency is high, the disadvantage is that if a thread crash, will cause the process crash

4.3 coroutines

1, subroutine call is always an entry, a return, call order is clear. Coroutines are called differently from subroutines.

2. Coroutines appear to be subroutines as well, but can be interrupted inside the subroutine and then switched to another subroutine, returning to it at an appropriate time.

5 Assignment, shallow copy, and deep copy

Deep copy is copying one object into another, which means that if you make changes to a copy of an object, it doesn’t affect the original object. In Python, we use the function deepcopy() to perform a deepcopy

Shallow copies are copies of a reference to an object to another object, so if we make changes in the copy, the original object will be affected

6 GIL

GIL is a global interpreter lock for Python. If there are multiple threads running in the same process, one thread will occupy the Python interpreter when running a Python program (a lock is added to the GIL), so that other threads in the process cannot run, and other threads can run only after the thread runs. If a thread encounters a time-consuming operation while running, the interpreter lock is released, allowing another thread to run. So in multithreading, threads still run sequentially, not simultaneously.

In multi-process, each process can be allocated resources by the system, which is equivalent to each process has a Python interpreter. Therefore, multi-process can realize the simultaneous running of multiple processes, but the disadvantage is that the process system resource overhead is high

7 The list is deduplicated

First by converting to set to de-weight, in the transfer list

The most commonly used sorting algorithms and their complexity

8.1 Bubble Sort

The outer loop runs from 1 to n-1. The inner loop starts from the next position of the current outer element and compares it with the outer element in turn. When the reverse order occurs, the inner loop swaps the smaller number to the front by comparing and swapping it with the neighboring element.

def bubbleSort(array) :
    if len(array) < 2:
        return array
    else:
        isSorted = False
        counter = 0
        while not isSorted:
            isSorted = True
            for idx in range(len(array) - 1 - counter):
                if array[idx] > array[idx + 1]:
                    isSorted = False
                    (array[idx + 1], array[idx]) = (array[idx], array[idx + 1])
            counter += 1
        return array
Copy the code

8.3 QuickSort

Separate the records to be sorted into two independent parts through a sort. If the keywords of one part of the records are smaller than those of the other part, the two parts of the records can be sorted to achieve the order of the whole sequence.

1. Select the Pivot center axis

2. Starting with the R pointer, place the number greater than Pivot to the right of Pivot

3. Place the number less than Pivot to the left of Pivot

4. Repeat the first three steps for the left and right sub-sequences respectively

def quickSort(array) :
    print(array)
    if len(array) < 2:
        return array
    else:
        pivot_index = 0
        pivot = array[pivot_index]
        less_part = [i for i in array[pivot_index+1:] if i <= pivot]
        large_part = [i for i in array[pivot_index+1:] if i > pivot]
        return quickSort(less_part) + [pivot] + quickSort(large_part)
Copy the code

9 closure

The return value of the function is a function object, which can only be accessed by external functions, improving security

10 with

The use of with statement can simplify the code and effectively avoid the occurrence of resource leakage

There may be some exceptions when opening files for reading and writing, if the regular F.pen is followed

We need to try,except,finally to do exceptions, and finally f.close() no matter what happens to the file. With helps us implement f.close in finally

11 Instance method Static method

Instance methods can only be called by instances, while static methods (@ by the staticMethod decorator’s method) and class methods (@ by the @classMethod decorator’s method) can be called by classes or instance objects of classes.

The first argument to the instance method must be passed the instance object by default, usually using self. 2, static method, parameters are not necessary. Class method, the first parameter must be passed by default, usually using CLS.

Iterators and generators

12.1 the iterator

An iterator is an object that remembers the position of the iterator.

Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward and not backward.

Iterators have two basic methods: iter() and next().

String, list, or tuple objects can all be used to create iterators:

>>> list= [1.2.3.4]
>>> it = iter(list)    Create an iterator object
>>> print (next(it))   Print the next element of the iterator
1
>>> print (next(it))
2
>>>
Copy the code

12.2 the generator

Functions that use yield are called generators

A generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator

During a call generator run, each time yield is encountered, the function pauses and saves all current run information, returns the yield value, and continues from the current position on the next execution of the next() method

13 Anonymous Functions

print [(lambda x:x*x)(x)for x in range(5] [0.1.4.9.16.25]
Copy the code

14 map reduce filter

14.1 the map

Do the same for each element in the iterable

def fn(x) :
    return x+1

resp = map(fn,li)
print(list(resp))

[2.3.4]
Copy the code

14.2 the reduce

To combine a sequence into a single value by applying a two-parameter function cumulatively from left to right to the terms of a sequence. (e.g. adding or multiplying list elements, etc.)

from functools import reduce
nums=[1, 2, 3, 4]
def fn(x, y):
    return x * y

resp = reduce(fn, nums)
print(resp)

24
Copy the code

14.3 the filter

The filter function is used to filter a sequence, filter out the elements that do not meet the criteria, and return a new list of elements that meet the criteria. This takes two arguments: the first is a function, the second is a sequence, each element of the sequence is passed as an argument to the function for evaluation, then returns True or False, and finally puts the element that returns True into the new list

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def fn(a): Return a%2 == 1 newList = filter(fn, a) newList = [I for I in newList] print(newList) ##Copy the code

Django

1 What is WSGI

The Python Web Server Gateway Interface, which translates to the Python Web Server Gateway Interface, is actually a protocol that our application (Django,Flask) implements WSGI. You can work with a server that implements WSGI(uWSGI, Gunicorn)

Djangos request lifecycle

  • Front-end send request

  • Wsgi, which is the Socket server, is used to receive user requests, encapsulate them first, and then deliver them to a Web framework (Flask, Django)

  • The middleware processes the request and helps us validate the request or add other relevant data to the request object, such as CSRF and Request.session

  • Route matching, find the view function according to the current requested URL. If it is written in FBV, find the corresponding view function by judging the two types of method. If it is written in CBV, it automatically looks for the Dispatch method, and Django uses dispatch reflection to find the corresponding method in the class and execute it

  • View functions, in which business logic is processed, may involve: ORM, View view rendering data to the template template

  • When the view function completes, it returns the desired data to the Dispatch method, which returns the data to the client

  • Middleware processing response

  • Wsgi, which sends the content of the response to the browser

  • Browser rendering

3 List djangos built-in components

  • Admin: Add, delete, modify and check the provided components of the corresponding data table in model

  • Model: Responsible for operating the database

  • Form: 1. Generate HTML code 2. Verify data validity 3 Return and display verification information

  • ModelForm: both for database operations and for validation of user requests

List 5 ways to use Django middleware. And django middleware application scenarios

  • Process_request: Permission is authenticated when the request comes in

  • Process_view: After the route matches, you can get the view function

  • Process_exception: Executed when an exception occurs

  • Process_template_responseprocess: executed when the template is rendered

  • Process_response: The request is executed when there is a response

What are FBV and CBV

FBV and CBV are essentially the same. A function-based view is called FBV and a class-based view is called CBV

Advantages of using CBV in Python:

  • Improved code reusability and the ability to use object-oriented techniques such as mixins
  • You can use different functions for different HTTP methods, rather than a lot of if judgments, to improve code readability

When was djangos request object created

class WSGIHandler(base.BaseHandler):
    request = self.request_class(environ)
Copy the code

When the request goes to the WSGIHandler class, the cell method is executed to wrap environ as a request

7 How do I add decorators to CBV

7.1 methods

from django.utils.decorators import method_decorator

@method_decorator(check_login)
def post(self, request) :.Copy the code

7.2 dispatch

@method_decorator(check_login)
def dispatch(self, request, *args, **kwargs) :
Copy the code

7.3 class

@method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class HomeView(View) :.Copy the code

8 List all the django ORM methods

<1> all(): queries all results <2> filter(**kwargs): it contains objects that match the given filter criteria. None <3> get(**kwargs): Returns one and only one object that matches the given filter. An error is thrown if more than one or none of the objects match the filter criteria. < 4 > exclude (* * kwargs) : it contains and the filter condition given does not match the object of < 5 > order_by field (*) : to sort the query results < 6 > reverse () : the result of the query reverse ordering 8 > < the count () : Returns the number of objects matching a QuerySet in the database. <9> first(): returns the first record <10> Last (): returns the last record <11> exists(): returns True if QuerySet contains data, False otherwise <12> values(*field): ValueQuerySet -- a special QuerySet that returns not a set of model instantiations, but an iterable dictionary sequence <13> values_list(*field): It is very similar to values() in that it returns a sequence of tuples, and values returns a dictionary sequence <14> DISTINCT (): duplicate records are removed from the returned resultCopy the code

9 Select_related and prefetch_related differences

The presence of foreign keys can greatly reduce the number of database requests, Improve performance select_related with multiple table join associated query, get all data at one time, execute only one SQL query preFETch_RELATED query each table separately, and then process according to the relationship between them, execute two queries

Djangos CSRF implementation mechanism

Step 1: The first time Django responds to a request from a client, the backend randomly generates a token value and stores the token in the SESSION state. At the same time, the backend puts the token in the cookie to the front-end page;

Step 2: Next time the front-end needs to initiate a request (such as Posting), the token value will be added to the request data or header information, together with the back-end; Cookies:{csrftoken:xxxxx}

Step 3: The backend verifies that the tokens brought by the front-end request are consistent with the tokens in the SESSION.

11 How does Django create a log when adding data to an ORM table

Using Djangos signal mechanism, you can set logging before and after adding or deleting data:
pre_init    A Django model object automatically fires before executing its constructor
post_init   When a Model object in Django executes its constructor, it automatically fires
pre_save    # Djangos model object is automatically triggered before being saved
post_save   Djangos model objects are automatically triggered when they are saved
pre_delete  # Djangos automatically trigger before deleting a Model object
post_delete # Django will automatically trigger when a Model object is deleted

# use
@receiver(post_save, sender=Myclass)Signal receiver decorator. Because of the built-in signal, so direct reception
def signal_handler(sender, **kwargs) :      After receiving the signal, process it herelogger = logging.getLogger() logger.success('Saved successfully')
Copy the code

12 How to set up django cache

CACHES = {
 'default': {
  'BACKEND': 'django.core.cache.backends.dummy.DummyCache'.# cache the engine used in the background
  'TIMEOUT': 300.# Cache timeout (default 300 seconds, None means never expires, 0 means immediately expires)
  'OPTIONS': {'MAX_ENTRIES': 300.# Maximum number of cached records (default 300)
   'CULL_FREQUENCY': 3.CULL_FREQUENCY = 1/CULL_FREQUENCY}}},Copy the code

Can Djangos cache use Redis? If so, how to configure it

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache"."LOCATION": "Redis: / / 127.0.0.1:6379"."OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient"."CONNECTION_POOL_KWARGS": {"max_connections": 100}
            # "PASSWORD": "PASSWORD"}}}Copy the code

The role of name in Djangos routing system

It is mainly used to find the URL address by the value of name, which can be understood as reflection. The advantage of using names in HTML templates to reflect URLS is that when the URL rules change later on, you just need to adjust urls.py, and none of the template files need to be modified.

Djangos REST Framework frameworks have those components

  • certification
  • Permissions (Authorization)
  • Limit of user access times/frequency
  • version
  • Parser
  • serialization
  • paging
  • Routing system
  • view
  • The renderer

16 Describe the authentication process for the Django REST Framework

  1. When the user logs in, the as_view() method of the login class is run and the Dispatch method of the APIView class is entered
  2. Execute the self.initialize_request method, which encapsulates other parameters such as request and a list of authentication objects
  3. Execute self.perform_authentication in the self.initial method, which runs the user method
  4. Then execute self._authenticate() in the user method