Learn python, from entry to give up (52)

Learn python, from entry to give up (52)

virtual environment

How many projects can be opened and run on your machine without hassle

1. Download all the modules you need to use. If there are different versions of the same module, download and replace each time.

2. Prepare multiple interpreter environments in advance and switch for different projects

django version difference

  • The route matching method is different

    url() supports regular expressions
    The first parameter of path() does not support regular expressions

    If you want to use regular, there is also a method

    from django.urls import path,re_path
    
  • The path method provides the converter function

    path('index/<int:id>/', index)
    

    ​ Match the data in the corresponding position and automatically convert the type
    ​ There are five converters to choose from

view function return value

The view function must return an HttpResonse object

HttpResponse
class HttpResponse(...):
    pass
render
def render(...):
    return HttpResponse(...)
redirect
def redirect(...):

JsonResponse object

user_dict = {'name': 'jason', 'pwd': 123, 'hobby': 'study well'}
return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})

class JsonResponse(HttpResponse):
    def __init__(self, data,json_dumps_params=None, **kwargs):
        data = json.dumps(data, **json_dumps_params)

Using JsonResponse is not the original json module, django has expanded the range of json serialized data types

form upload file

If the data uploaded in the form contains files, then you need to do the following things

1.method must be post
2.enctype must be modified to multipart/form-data
The default is application/x-www-form-urlencoded
3. The backend needs to use request.FILES to obtain

django will automatically encapsulate it into different methods for you according to the data type

request other methods

request.method
request.POST
request.GET
request.FILES
request.body
Stores the most primitive binary data received
The methods of request.POST, request.GET, request.FILES actually obtain data from the body and parse the stored data.
request.path
get path
request.path_info
get path
request.get_full_path()
Get the path and also get the parameters carried behind the path

FBV and CBV

  • FBV: Function-Based Views

    url(r'^index/',Function name)
    
  • CBV: Class-Based Views

    from django import views
    
    
    class MyLoginView(views.View):
        def get(self, request):
            return HttpResponse("from CBV get view")
        def post(self, request):
            return HttpResponse("from CBV post view")
        url(r'^ab_cbv/', views.MyLoginView.as_view())
    

If the request method is GET, the get method in the class will be automatically executed
If the request method is POST, the post method in the class will be automatically executed.

CBV source code analysis

  • route matching

    The class name point attribute as_view and also add parentheses
    as_view may be a normal static method
    as_view may be a method bound to a class

  • The order in which objects look up properties

    Start with the object itself, then the class that produced the object, then the parent classes
    MyLoginView.as_view()
    First find it from MyLoginView we wrote ourselves
    I didn't go to the parent class Views to find it

  • The function name with parentheses has the highest execution priority

    url(r'^ab_cbv/', views.MyLoginView.as_view())
    

    When the project is started, the as_view method will be executed, and viewing the source code returns a closure function name view.

    def as_view(cls):
        def view(cls):
            pass
        return view
    url(r'^ab_cbv/', views.view)
    

    CBV and FBV are essentially the same in route matching

  • Execute the view function after the route is matched successfully

    def view():
        self = cls()
        return self.dispatch(request, *args, **kwargs)
    
  • Execute the dispatch method

    Need to pay attention to the search order

    def dispatch():
        handler = getattr(self, request.method.lower())
        return handler(request, *args, **kwargs)
    

    Viewing the source code can also be modified, but try not to do so, it is easy to generate bug s

template syntax pass by value

The template syntax provided by django has only two symbols
{{}}: Mainly used for variable-related operations (references)
{%%}: Mainly used for logic related operations (loop, judgment)

Two ways to pass values

  • biography by name

    It is suitable for situations with less data volume, which can save resources

    return render(request, 'ab_temp.html', {'name':name})
    
  • Pack and pass value

    Suitable for large amounts of data, but will waste resources

    locals() passes all names in the current namespace to the html page

    return render(request, 'ab_temp.html', locals())
    

range of values ​​passed

Basic data types can be

Function name
The template syntax will be automatically executed with parentheses and the return value of the function will be displayed on the page
Does not support parameter passing (template syntax will automatically ignore parameterized functions)
file name
Display file IO objects directly
class name
Automatically parenthesized instantiation into an object
object name
Directly display the address of the object and have the ability to call properties and methods

django template syntax has only one way to evaluate the value of container type period

You can click both the key and the index. django internal automatic identification

{{ data1.info.pro.3.msg }}

Posted by thepriest on Fri, 13 May 2022 20:56:01 +0300