Python full-stack, back-end engineers to answer common interview ideas and share high-quality (how seemingly free to make the interviewer think you are very simple)

Django
1.Django, the Flask, compare Tornado framework?
Django:

For Django, large and more its internal frame assembly, provided internally: ORM, Admin, middleware, Form, ModelForm, Session, buffers, signal, CSRF; all came to perfect function

Flask :

flask, miniature frame, the internal components relatively small, but there are many third-party components to extend it with, say, the wtform (with django of modelform similar, form validation),, flask-session flask-sqlalchemy (database operation) , flask-migrate, flask-script, blinker scalability strong, rich third-party components. So there is kind of short and pithy sense of his own

Tornado:

Web framework is a lightweight, non-blocking asynchronous + WebSocket functionality built.

'Target': N concurrent processing request (processing IO) via a thread.

Internal components:
  A interior achieve their Socket.
  B routing system.
  C view.
  D template.
  E.cookie
  f.csrf

Common:

django and flask in common is that they do not have to write two frame socket, so they are using third-party modules wsgi; and Tornado comes socket assembly.

difference:

But internal use wsgi is somewhat different: django itself up and running using wsgiref, and the flask using werkzeug wsgi, there is a difference between their request management are not the same: django is packaged into a request by the request object, and then passed through parameters , while the flask through the context management mechanism

2. Django request lifecycle?
WSGI incoming user request to go, then the request to django middleware, the middleware through django (process_request method), followed by routing to match, after a successful route matches the corresponding view function is executed, you may view the function call orm do database operations, and then will get a template from the template path, then the template rendered in the background, after the completion of rendering the template becomes a string, then the string through all of the middleware (method: process_response) and return wsgi to the user

3. List Django's built-in components?
form components:

- the data requested by the user for verification
- to generate HTML tags

PS:

- form object is an iterable.
- problem: choice if the data retrieved from the database may result in data can not be updated in real time
- override the constructor method, the database again to get the value in the constructor.
- ModelChoiceField field

signal:

django signal is actually hook a number of customized features for developers inside django reserved. Just register the function in a signal, then the process inside django will automatically trigger the execution of code in your signal.

Scene:
When adding certain data in a database table, for logging purposes.

CSRF (cross-site request forgery):

Objective: To prevent the user initiates a POST request to the server directly.

It is very different with XSS, user confidence in using the site XSS, CSRF and trust through the camouflage from the user's request to use a trusted site by.

Make a request for verification of all post / Django transmits the generated string of a string to the client, one is made up from the request body, one is placed inside a hidden tag is process_view

When first sends a GET request, the token Save to:: Program cookie, Form Form (hidden input tag), and then later when sending the request to carry over as long as you can.

Currently there are three main CSRF attacks defense strategies: 1) Verify the Referer HTTP field; 2) adding the address in the request token and authentication; 3) in the HTTP header and validate custom properties..

ContentType:

ContentType is a component (app) django find all tables in all app in django program for us and added to the record. You can use it on the table plus two fields to achieve: a table and N tables create FK (field) relationship. (Understood as a simple correlation between the effect of multi-table)

- Field: Table Name

- field: rows of data ID
table coupons internal purchase systems: application.

Middleware:

Batch processing of all requests, to customize the operation performed before or after the view function.
Application: User login verification

Question: Why not use a decorator?
If you do not use middleware, you need to add a decorator to each view function, too cumbersome

Certification components:

Only authenticated users can access the specified url address, such as: purchase items of information, then sign-in required, not logged in, you can not see, at this time need to use certified components

Django Auth module is built-in user authentication module

Details: https: //www.cnblogs.com/liuqingzheng/articles/9628105.html

Permissions components:

After the user logs into the session permission, each time a request comes in all, according to the current session to match the url in middleware, the judge whether the current user has access to the current url, will continue to have permission to access, there is no return, (check the things you can put middleware for unified treatment) method in which process_request do, our middleware is placed behind the session, because the middleware needed to get inside the session data

Details: https: //www.cnblogs.com/liuqingzheng/articles/9628105.html

session:

 cookie differs session:
(A) cookie is stored in the browser of key-value pairs, and the session key is stored on the server, but rely on cookie. (Cookie may not rely on, can be placed url, cookie, or more convenient, but the request header)
(B) to log an example, cookie through the login is successful, the setting key for plaintext, and the key to the sending client deposit, there may be a leak plaintext, unsafe; session is to generate a random string, to users, and wrote the browser cookie while they themselves would keep a server.
(C) when the login authentication, cookie: The accompanying key transmission request to the browser cookie judgment, if present, is verified; session: to obtain random string in the cookie request of a user, according to a random string obtaining a value corresponding to verify in the session
cache:

Commonly used data in the cache inside, do not take the view function, the request came in through all process_request, will check the data to the cache inside, there take a direct, no view left function
key: 1: complete the implementation of all process_request before going take the data cache
    2: complete the implementation of all of the data into the cache before process_response

About Cache question
: Why in the last process_request before going to the cache
because of the need to verify the user's request finished, to return data

2: When the data into the cache
first go middleware, there is no cache data, will take the view function, which takes data from the database,
when completed process_response, only the data into the cache, because the time to go process_response may add to our treatment response

Why use caching
frequently used and less frequently modified data into the cache.
After the user access again, go to the cache to see if there is, if there is returned
. Otherwise, go to the database and get back to the user (adding to the cache so that the next visit)

5. The method recited Django middleware 5? Django middleware and application scenarios?
process_request (self, request) go through a routing request returns matching
process_view (Self, request, the callback, callback_args, callback_kwargs) 
    (. 1) after executing the request method all middleware '
    (2) successful match URL
    (3) to get the view function name, parameters, (note not executed) process_view then execute () method
    (4) to perform the final view function

process_template_response (self, request, response) when the return value of the object function are the render view, the method will be called
process_exception (self, request, exception) performed when an error view function, returns an error message
process_response (self, request , response)

The difference 6.FBV and CBV
- no difference, because they are essentially a function. The CBV .as_view () dispatch method returns the function of the view, view class calls the function, performed by the reflection get / post / delete / put or the like in the dispatch process.
I have to say the words the difference between:
- the CBV is relatively simple, GET / POST and other business functions were placed in different get / post function. FBV make their own judgment to distinguish.

7.Django orm how to set up separate read and write?
A mode: using the manual method used queryset

Second way: write configuration file

 8. When Django send post request using ajax based, all of which method you can use to carry csrf token?
One way: ajax are coupled to each request header

Second way: you have to download jQuery-cookie, in order to get the cookie token

Three ways: put forward a function ajaxSetup, when a number of ajax request that will perform this function

9.Django in how to create a log record data is added orm table.
Registration to the signal function:

Using a signal mechanism django may be added, provided the logging after dropping the data
before the object model pre_init # Django in performing its constructor, automatically trigger
the model object post_init # Django in the execution of its construction method, triggered automatically
pre_save # Django in the former model objects saved automatically trigger
model of the object post_save # Django save, automatically trigger
before pre_delete # Django model objects in the deleted automatically triggered
after post_delete # Django model objects in the deleted automatically trigger

10. Talk about your understanding of RESTful specification?
RESTful actually a set of written 'agreement' interface specifies how to write and how to set the return value, status codes.
# The most notable features:
# with restful:
give the user a url, different back end processed differently according to method
example: post created data, get data acquisition, put patch and modify data, delete delete data.
# Do not restful:
to the caller a lot of url, url each representing a function, such as: add_user / delte_user / edit_user /
# of course, there are other protocols, such as:
'Version' program to control the situation so that there are multiple versions of coexistence version can be placed url, the request header
(accept / custom), the GET parameter
'status code' 200/300/400/500
    200 is the OK - [the GET]: the server returns the data requested by the user successfully, the operation is idempotent (Idempotent).
    400 INVALID REQUEST - [POST / PUT / PATCH]: request issued by a user mistake, the server does not create or modify the operation data, the operation is idempotent.
    404 NOT FOUND - [*]: user issues a request for recording is not present, the server is not operated, the operation is idempotent.
    500 INTERNAL SERVER ERROR - [*] : server error occurs, the user will be unable to determine whether the request is sent successfully.

'url to make use of the term' restful also called "Resource-oriented programming '
' API marked '
    api.sex.com API will try to deploy a dedicated domain name (there will be cross-domain problems)
    www.sex.com/api/     

11. What is RPC?
'Remote procedure call protocol' is a request for service from a remote computer through a network, without having to understand the underlying network protocol technology.
The order of evolution: the conventional RPC, and then some RESTful specification

12. Why use django rest framework framework?
Internal helped us a lot of convenience components, we can complete the corresponding operation by arranging
for, such as: 'serialization' may be the user data check request queryset + serialized object called JSON, 'parser' Get user request data request.data, automatically requests the header of the data can not be parsed according to the content-type, 'tab' from the acquired data database pages in the page display.
There are other components: 'certification', 'authority', 'access frequency control

 

The Flask
1.Flask advantage?
Flask free, flexible, scalable, transparent and controllable the choice of many third-party libraries, can be combined with the most popular and powerful Python library development time.

2.Flask framework components that depend on what?
Dependence jinja2 template engine
relies werkzurg agreement

3.Flask action blueprint
blueprint to separate the different functions of the module also is to a large App module into each implement different functions.
In a blueprint blueprint can call another function of view, but to add the appropriate blueprint name.

? Flask context management process 4. DESCRIPTION
: # a, simply, falsk context management can be divided into three phases
  ' request came '1: requesting data relating to the context management placed in
  2,' in view of the function in ': the value of the context management going
        3' request response ': to clear the data in the context management
# b, is elaborate:
  1,' the request just came ':
the request, session classes in the package RequestContext app, g AppContext encapsulated in the class, and by localStack AppContext into the RequestContext local class
  2, 'view function':
by localproxy ---> partial function ---> localstack ---> local value
  3 , 'in response to a request':
first execution save.session () then each perform POP (), the data in the local clearance

G 5.Flask role in?
g throughout the global variable is a request, when the request comes and current_app g AppContext packaged as a class, then by LocalStack AppContext into the Local, the value in LocalStack, local time by a partial function value; the response g in the local data deletion:

6.Flask execution process?


7. What is the partial function?
Simply put functools.partial role is to put some parameters to a function of the fixed (that is, set the default value), returns a new function, call this new function will be easier

For example:

#假设对int(x, base = 10),进行二次封装
#通常做法
def to_int2(x):
    return  int(x, base = 2)
print(to_int2(‘101‘))
#偏函数 做法
import functools
to_int2_partial = functools.partial(int, base = 2)
print(to_int2_partial(‘101‘,base=2))
#partial的函数声明
#def __init__(self, func, *args, **keywords):
#由此处可以看到其实就是做了
#int(**keywords)  ==>kw = {‘base‘ = 2} 然而‘101’会以*args的形式传入到函数
print(to_int2_partial(‘101‘,base=10))
#result --> 101

Xiao Bian recommend a study group 315,346,913 python learning, whether you are big or small white cow, or would want to switch into the line can come together to learn to understand progress together! There are tools within the group, a lot of dry goods and technical information sharing

Guess you like

Origin blog.csdn.net/weixin_44995023/article/details/92426773