1 Python object-oriented programming

Object oriented programming in Python is to treat everything as an object. Object oriented programming is like creating a world in which you are God and everything around you is an object, and everything can be createdCopy the code

2 Design Mode

Singleton pattern: One instance in a class Factory pattern: define an interface for creating objects and let subclasses decide which class decorator pattern to instantiate: dynamically add some extra responsibilities to objectsCopy the code

3 GIL lock

In the CPython interpreter, there is no way to take advantage of multiple cores to implement tasks in parallel, so we see concurrent execution only as concurrency, not true simultaneity. In order to ensure that multiple tasks make changes to the shared data, data contamination or corruption will occur. The global interpreter lock turns multitasking on shared data into a serial GIL and enables cpu-intensive programs to be implemented with multiple processesCopy the code

4 haystack

Django-haystack is a django-haystack plugin for full text retrieval. Import Django-Haystack, and set the price 'Haystack' in INSTALLD_APPS. Then add haystack to the url of the entire project. Patterns = [... url(r'^search/', include('haystack.urls')),]Copy the code

5 WSGI

WSGI Server is responsible for receiving requests from the client, forwarding the request to the Application, and forwarding the response of the application to the clientCopy the code

6 Djangos request lifecycle

When the client enters a route in the browser, it calls the local DNS server to resolve the domain name into an IP address. Then the browser takes the IP address and the route and the action, namely get request or POST request, through the WSGI middleware, and finally reaches the specified URL. After the URL is resolved, it goes to the view layer, to the model layer and the data. Finally, the response is returned to the clientCopy the code

7 Network Programming

When we talk about network programming we talk about the hierarchy of the Internet the physical layer, the physical link layer, the network layer, the network transport layer, the application layer the physical layer is the hardware of one computer at a time the physical link layer has to make sure that there are network cards and IP protocols on the network layer, Make sure that a computer has an IP address and then at the network transport layer you have TCP/UDP applications and HTTP on top of that you talk about TCP/UDP three-way handshake and four-way wave three-way handshake where the client sends the link request, the server agrees to the request, The client sends data four times to wave is the client to send a disconnection request to the server, the server check when there is transmission, there is no direct disconnection of the client link, if there is transmission, then disconnection; The server sends a request to disconnect, and the client agrees to the request, thus, a network transmission is disconnected. Speaking of HTTP protocol, HTTP protocol is used to transfer hypertext between the client and the server at the application layer. It is called hypertext Transfer Protocol (HTTP)1Application layer protocol based on TCP/IP2Based on request and response3Stateless saving itself does not store the state of the request, so sessions and cookies are born4No connection: Limit processing to one request per connection and disconnect as soon as the client repliesCopy the code

5 Ways to Use Django Middleware? And Django middleware scenarios?

In DJango, the middleware is essentially a class method that executes the corresponding middleware method process_request at the beginning and end of a request according to its own rules:The # method is called when the request arrives
process_response:  Prepare the view data after execution even if the response is sent to the client
Copy the code

If you want to do something when a request comes in or a response comes back, add middleware or think of it as adding an interceptor

Nine FBV and CBV

FBV is a function-based view that integrates request into the view

A CBV is a class-based view, where the class in the view inherits the View

10 How to add decorators to CBV program

Add directly to the class
@method_decorator(wrapper,name='dispatch')
class Foo(View) :
    def get(self,request) :
        pass
def post(self,request) :
        passMust be imported before adding decoratorsfrom django.utils.decorators importMethod_decorator must add the decorator in the form of @method_decorator(), parentheses for the function name of the decorator. Class addition must declare name. Note that the cSRF-token decorator is special, it can only be added to dispatchCopy the code

11 Django ORM

The objects that Django queries directly are QuerySet objects, which are generally collectionsfilter  # filter
exclude  # remove
annotate  # polymerization
order_by  # sort
reverse  # anyway
distinct()  Select * from query result where duplicate rows exist
values  # iterating returns dictionaries instead of model instance objects
values_list  # return tuples instead of dictionaries


Copy the code

Django ORM provides three ways to write SQL

# 1 is implemented directly using ORM
Books.objects.filter(publish_name=Tsinghua University Press).extra(where={'price>60'})

# 2 Use RAW
books = books.objects.rqw('select * from books')

# Customize SQL
from django.db import connection  
connection.curseor()
cursor = excute('elect * from hello_author')
cursor.fethome()
cursor.fintchall()



Copy the code

Student: 13 the role of F and Q?

F Query the allowed value of a columnfrom djangp.db.model import F,Q
Books.objects.ipdate(F('price') +20%) Q for complex object query and | or ~notThe relationship between search_obj = Asset. The objects.filter(Q(hostname__icontains=keyword)|Q(ip=keyword))

Copy the code

14 Difference between value and value_list

Neither of them returns a queryset.

Values is a dictionary and values_list is a tuple

15 How to batch create data with Django ROM

1Using save() accesses the database each time data is created2Use Bulk_CREATE to reduce SQL query times QuerySetList =[]for i in range(10):
    auerysetlist.append(Account(name=i))
Account.objects.bulk_create(querysetlist)

Copy the code

Djangos cache system

Hotspot data, frequently queried data, SMS verification code, etc

Set the cache

Set CACHES in settings.py,

1 pip install django-redis
2Configure CACHES in settings.py3 SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

4Use the cachefrom django_redis import get_redis_connection
con = get_redis_connection()  get_redis_connection
con.set(key,code)  # set cache
con.expire(key,80)  Add idle time to the cache

con.get(key)  Get the value in the cache


Copy the code

17 Db_first and code first

So db first is to create the database and then generate the model code in reverseCopy the code

Generate the model from the database

python manage.py inspectdb
python manage.py inspectdb > blogapp/models.py

Copy the code

18 The pros and cons of Django ORM versus native SQL?

Djangoorm is quick to develop, hiding data access details, associating data tables with object models, and implementing object-relational mapping to facilitate object migration

The advantage of SQL is that it is much more convenient to perform complex queries

The downside of SQL is the problem of SQL injection

19 the MVC and MTV

MVC is model, view and controller

MTV is the model, the template, the view

Tell us what you know about restful specifications

1API and user communication protocol, always use HTTPs protocol2The API interface should be deployed under a domain name whenever possible3You should put the API version number in the URL4Nodes in the URL are represented by nouns5HTTP verb GET POST DELET PUT6Status code200Operation is successful201A new user is created or modified successfully301Permanent redirection302Temporary redirection400Client error401Have no legal power402Parameter error403Blocking access404No resources found500Server errorCopy the code

21 What does interface idempotency mean

No matter how many times it is called, it will only produce the same result, like our GET request

22 Differences between HTTP and HTTPS

HTTP transmits data in plain text, and is not suitable for transmitting sensitive information, such as payments

If an attacker steals the traffic between a Web browser and a server, he can read the information,

In order to solve these defects, we need to use another protocol: HTTPS, which adds SSL on the basis of HTTP to verify the identity of the server through certificates, without encrypting the communication between the browser and the server

Port 80 for HTTP, port 443 for HTTPS

Djangos Models is null and blank

Null is for a database. If null=True, the database field can be null

Blank is for forms. If blank=True, it means that your form does not need to fill in this field, for example, when adding a model record to the Admin interface. Intuitively, the field is not bold

24 the ORM optimization

1Add a foreign key2Adding indexes3Avoid repeated queries and cache hotspot dataCopy the code

High concurrency and solutions

High concurrency: It appears to run simultaneously, with multiple clients accessing data at the same time1Caching from the front end, setting up sprites,2Large file compression3Add a layer between database and program, using Redis as cache, reduce the pressure of mysql database4Optimize query statements and add indexes5Optimize the uwsgi6Nginx does load balancing, reverse proxy7Put data such as pictures and videos on OSSCopy the code

26 Custom frequency components

Such as limiting access to three times per minute

1 Make a dictionary where key is the user’s IP address,value is a list, and the element is time

2 If the IP address is not in the dictionary, add the IP address to the dictionary and return True, indicating the first access

3 Loop to judge the current IP list, the current time minus the last view of the list is more than 60 seconds, pop off the data, so that the access time in the table is only one minute

4 Check that the list is less than 3, return True, pass

If 5 is equal to 3, Fan will False and block

27 Django Rest Framework framework

The routing layer

from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('company',CompayVietSet)

Copy the code

The view layer

from rest_framework import mixins, viewsets, status
from rest_framework.decorators import throttle_classes, action
from django.db import connection, transaction

class AccessoryViewSet(viewsets.ModelViewSet) :
   	queryset = Accessory.objects.all().order_by('id')
    serializer_class = AccessorySerializer
    pagination_class = AccessoryListPagination
    authentication_classes = (JWTTokenUserAuthentication,)
    permission_classes = (IsAuthenticatedOrReadOnly,)

    def get_queryset(self) :
        return queryset
    
    
     # affairs
	 @transaction.atomic
    # Implement FBV view
     @action(detail=False, methods=['GET', ], authentication_classes=[JWTTokenUserAuthentication, ], permission_classes=[IsAuthenticatedOrReadOnly, ])
    def market(self, request, *args, **kwargs) :
        return Response({'code': '10001'.'data': {}, 'msg': str(e)})
    
    
        

class ModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet) :

Copy the code

Serialization component

from rest_framework import serializers
class AccessorySerializer(serializers.ModelSerializer) :
    accessory_img = serializers.CharField(read_only=True)
	brand = serializers.SerializerMethodField()
    class Meta:
        model = Accessory
        fields = ('id'.'category_name'.'accessory_img'.'brand')
    
    def get_brand(self,obj) :
        return ' '
    
    
        
        
    

Copy the code

Model layer

from django.db import models
class Company(models.Modesl) :
    cimpany_id = models.IntegerField(verbase_name='XXX')
    
    class Meta:
        verbose_name = 'sss'
        verbose_name_plural = verbose_name
        db_table='company'

Copy the code

Django optimistic and pessimistic locks

Pessimistic lock: think all the operation is harmful, first get the lock, in the operation, 1 lock 2 check 3 update

Optimistic lock: Assume that all operations are harmless, modify first, and roll back when errors are found

Django ORM implements pessimistic locking

from django.db import transaction


@transaction.atomic
def post(self,request) :
    
    # get parameters
    Get savepoints
    sid = transaction.savepoint()
    
    Write data
    order_info = OrderInfo.objects.create(
            order_id = order_id,
            user = request.user,
            addr = address,
            pay_method = pay_method,
            total_count = total_count,
            total_price = total_amount
        )

    try:
        # try to query the newly created data
    except :
        Rollback to savepoint
        transaction.rullback(sid)
 
        
    

Copy the code

Django ORM implements optimistic locking

from django.db import transaction


# optimistic locking

class OrderCommitView(View) :
    """ Optimistic Lock """
    Open the transaction decorator
    @transaction.atomic
	def post(self,request) :
        # get parameters.# create savepoint
        sid = transaction.savepoint()
        
        Write data
        try:
            pass
        except:
            Rollback to savepoint
            transaction.savepoint_rollback(sid)

    

Copy the code