学习python,从入门到放弃(52)(Learning python, from getting started to giving up (52))

学习python,从入门到放弃(52)

虚拟环境

诸多项目在你的机器上如何无障碍的打开并运行

1.把所有需要用到的模块全部下载下来,如果有相同模块不同版本每次都重新下载替换

2.提前准备好多个解释器环境,针对不同的项目切换即可

django版本区别

  • 路由匹配的方法不一样
    url() 支持正则
    path() 第一个参数不支持正则
    如果想使用正则 也提供了方法
    from django.urls import path,re_path

  • path方法提供了转换器功能
    path(‘index//’, index)

    匹配对应位置的数据并且自动转换类型
    有五种转换器可供选择

视图函数返回值

视图函数必须返回一个HttpResonse对象

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

JsonResponse对象

user_dict = {'name': 'jason', 'pwd': 123, 'hobby': '好好学习'}
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)

使用JsonResponse不是原始的json模块,django对json序列化的数据类型的范围做了扩充

form表单上传文件

form表单上传的数据中如果含有文件 那么需要做以下几件事

1.method必须是post
2.enctype必须修改为multipart/form-data
默认是application/x-www-form-urlencoded
3.后端需要使用request.FILES获取

django会根据数据类型的不同自动帮你封装到不同的方法中

request其他方法

request.method
request.POST
request.GET
request.FILES
request.body
存放的是接收过来的最原始的二进制数据
request.POST、request.GET、request.FILES这些获取数据的方法其实都从body中获取数据并解析存放的
request.path
获取路径
request.path_info
获取路径
request.get_full_path()
获取路径并且还可以获取到路径后面携带的参数

FBV与CBV

  • FBV:基于函数的视图
    url(r’^index/’,函数名)

  • CBV:基于类的视图
    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())

如果请求方式是GET 则会自动执行类里面的get方法
如果请求方式是POST 则会自动执行类里面的post方法

CBV源码剖析

  • 路由匹配
    类名点属性as_view并且还加了括号
    as_view可能是普通的静态方法
    as_view可能是绑定给类的方法
  • 对象查找属性的顺序
    先从对象自身开始、再从产生对象的类、之后是各个父类
    MyLoginView.as_view()
    先从我们自己写的MyLoginView中查找
    没有再去父类Views中查找
  • 函数名加括号执行优先级最高
    url(r’^ab_cbv/’, views.MyLoginView.as_view())

    项目已启动就会执行as_view方法,查看源码返回了一个闭包函数名view。
    def as_view(cls):
    def view(cls):
    pass
    return view
    url(r’^ab_cbv/’, views.view)

    CBV与FBV在路由匹配本质是一样的

  • 路由匹配成功之后执行view函数
    def view():
    self = cls()
    return self.dispatch(request, *args, **kwargs)

  • 执行dispatch方法
    需要注意查找的顺序
    def dispatch():
    handler = getattr(self, request.method.lower())
    return handler(request, *args, **kwargs)

    查看源码也可以修改 但是尽量不要这么做 很容易产生bug

模板语法传值

django提供的模板语法只有两个符号
:主要用于变量相关操作(引用)
:主要用于逻辑相关操作(循环、判断)

{{}}
{%%}

传值的两种方式

  • 指名道姓的传
    适用于数据量较少的情况,可以节省资源
    return render(request, ‘ab_temp.html’, {‘name’:name})

  • 打包传值
    适用于数据量较多的情况,但是会浪费资源
    locals() 将当前名称空间中所有的名字全部传递给html页面
    return render(request, ‘ab_temp.html’, locals())

传值的范围

基本数据类型都可以

函数名
模板语法会自动加括号执行并将函数的返回值展示到页面上
不支持传参(模板语法会自动忽略有参函数)
文件名
直接显示文件IO对象
类名
自动加括号实例化成对象
对象名
直接显示对象的地址 并且具备调用属性和方法的能力

django模板语法针对容器类型的取值 只有一种方式 句点符

既可以点key也可以点索引 django内部自动识别

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

Learning python, from getting started to giving up (52)

virtual environment

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

1. Download all the modules that need to be used. If there are different versions of the same module, download it again and replace it every time

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

django版本区别

  • Route matching methods are different
    url() Support regular
    The first parameter of path() does not support regular
    If you want to use regular, you also provide methods
    from django. urls import path,re_ path
  • The path method provides converter functionality
    path(‘index//’, index)
    Match the data of 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对象

user_dict = {'name': 'jason', 'pwd': 123, 'hobby': '好好学习'}
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 extends the range of data types serialized by JSON

Form upload file

If the data uploaded from the form contains files, you need to do the following

1.method必须是post
2.enctype必须修改为multipart/form-data
默认是application/x-www-form-urlencoded
3.后端需要使用request.FILES获取

Django will automatically help you encapsulate into different methods according to different data types

request其他方法

request. method
request. POST
request. GET
request. FILES
request. body
It stores the most original binary data received
request. POST、request. GET、request. Files these methods of obtaining data 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 you can also get the parameters carried behind the path

FBV与CBV

  • FBV: function based view
    URL (R ‘^ index /’, function name)
  • CBV:基于类的视图
    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 executed automatically
If the request method is post, the post method in the class will be executed automatically

CBV source code analysis

  • Route matching
    Class name point attribute as_ And added parentheses
    as_ View may be an ordinary static method
    as_ View may be a method bound to a class
  • The order in which the object finds properties
    Start with the object itself, then the class that generates the object, and then each parent class
    MyLoginView. as_ view()
    First find it from the myloginview we wrote
    No more searching in the parent class views
  • 函数名加括号执行优先级最高
    url(r’^ab_cbv/’, views.MyLoginView.as_view())

    项目已启动就会执行as_view方法,查看源码返回了一个闭包函数名view。
    def as_view(cls):
    def view(cls):
    pass
    return view
    url(r’^ab_cbv/’, views.view)

    CBV与FBV在路由匹配本质是一样的

  • 路由匹配成功之后执行view函数
    def view():
    self = cls()
    return self.dispatch(request, *args, **kwargs)

  • 执行dispatch方法
    需要注意查找的顺序
    def dispatch():
    handler = getattr(self, request.method.lower())
    return handler(request, *args, **kwargs)

    查看源码也可以修改 但是尽量不要这么做 很容易产生bug

Template syntax value transfer

The template syntax provided by Django has only two symbols
: mainly used for variable related operations (Reference)
: mainly used for logic related operations (loop and judgment)

{{}}
{%%}

Two methods of value transmission

  • Biography by name
    It is applicable to the case of less data and can save resources
    return render(request, ‘ab_temp.html’, {‘name’:name})
  • Package value transfer
    It is applicable to the situation with a large amount of data, but it will waste resources
    Locals () passes all the names in the current namespace to the HTML page
    return render(request, ‘ab_temp.html’, locals())

Range of values transmitted

Basic data types are OK

Function name
The template syntax will be automatically executed in parentheses and the return value of the function will be displayed on the page
Parameter passing is not supported (template syntax will automatically ignore parameterized functions)
file name
Direct display of file IO objects
Class name
Automatic bracketed instantiation into objects
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 get the value of container type, period character

You can click either key or index to automatically identify Django

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