django知识点 Day01

生成requirements.txt

pip freeze > requirements.txt

建议

  • Pycharm不要汉化
  • 虚拟环境目录要没有中文
  • pycharm用专业版

django必备知识点

虚拟环境(不是完整python)

pip install virtualenv
virtualenv [路径或名字] --python=python3.9 

虚拟环境会有activate文件,执行后激活

python通过字符串引入库

path = "apps.api.urls"
import importlib
md = importlib.import_moudle(path)

python 反射

1. getattr()函数是Python自省的核心函数,具体使用大体如下:
print getattr(Instance , 'age', 'not find') #如果Instance 对象中有属性age则打印self.age的值,否则打印'not find'
2. hasattr(object, name)

说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)

3. setattr(object, name, value)

这是相对应的getattr()。参数是一个对象,一个字符串和一个任意值。字符串可能会列出一个现有的属性或一个新的属性。这个函数将值赋给属性的。该对象允许它提供。例如,setattr(x,“foobar”,123)相当于x.foobar = 123

4. delattr(object, name)

setattr()相关的一组函数。参数是由一个对象(记住python中一切皆是对象)和一个字符串组成的。string参数必须是对象属性名之一。该函数删除该obj的一个由string指定的属性。delattr(x, 'foobar')=del x.foobar

__import__() 函数用于动态加载类和函数 。

如果一个模块经常变化就可以使用 import() 来动态载入。

__import__(name[, globals[, locals[, fromlist[, level]]]])

import(name, globals=None, locals=None, fromlist=(), level=0)

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.import) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of import() is also discouraged in favor of importlib.import_module().

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling import() (see PEP 328 for the details).

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

说明:

  1. 函数功能用于动态的导入模块,主要用于反射或者延迟加载模块。

  2. import(module)相当于import module

python 路由

name

给路由提一个名字,根据名字反向生成url

urlpatterns = [
path('api/v1/',include('api.auth.urls'),name="v1"),
]
  • 用于页面跳转(反向生成)
from django.shortcuts import render
from django.views import View
from django.shortcuts import redirect
from django.http import HttpResponse,JsonResponse
# Create your views here.
class LoginView(View):
def post(self,request):
return JsonResponse({"code":200,"msg":"ok"})
def get(self,request):
from django.urls import reverse
url = reverse("v1") #即/api/v1/
return redirect(url)

  • 用html模板
<a href="{% url 'v1' %}">跳转</a>
  • 扩展(可用于权限管理 name属性配合)

动态生成(正则表达式模式)

urlpatterns = [
path('api/<str:role>',include('api.auth.urls'),name="v1"),
re_path(r'auth/(/d+)/(w+)',include('api.auth.urls'),name = "auth")#分组无名字
re_path(r'xxx/(?P<nid>\d+)/(?P<tpl>\w+)',include('api.auth.urls'),name = "v3")
]
from django.shortcuts import render
from django.views import View
from django.shortcuts import redirect
from django.http import HttpResponse,JsonResponse
# Create your views here.
class LoginView(View):
def post(self,request,role):
return JsonResponse({"code":200,"msg":"ok"})
def get(self,request,role):
from django.urls import reverse
#url = reverse("v1",kwargs={"role","hgggg"}) #即/api/v1/
#url = reverse("v2",args={666,"hgggg"}) #即/api/v1/
url = reverse("v2",kwargs={'nid':666,"tpl":"ddd"}) #即/api/v1/
return redirect(url)

<a href="{% url 'v1' role='xx'  %}">跳转</a> #字典
<a href="{% url 'v2' 666 '213213' %}">跳转</a>#元组
<a href="{% url 'v3' nid=666 'tpl'="fsdf" %}">跳转</a> #字典

namespace(辅助name)

这样name不能重名

  • 主路由:
urlpatterns = [
path('api/',include('api.auth.urls'),name="v1",),
path('web/',include('api.web.urls'),name="web"),
path('auth/',views.auth,name="auth"),
]
  • api/urls.py
urlpatterns = [
path('login/',views.login,name="login"),
path('auth/',views.auth,name="auth"),
]
  • web/urls.py
urlpatterns = [
path('home/',views.home,name="home"),
path('order/',views.order,name = 'order'),
]

在某个url或者视图中需要反向生成url,当路由出现相同名字的时候程序无法找到需要哪个路由

需要使用namespace

这样name不能重名

  • 主路由:
urlpatterns = [
path('api/',include('api.auth.urls'),namespace = "x1"),
path('web/',include('api.web.urls'),namespace="x2"),
]
  • api/urls.py
urlpatterns = [
path('login/',views.login,name="login"),
path('auth/',views.auth,name="auth"),
]
  • web/urls.py
urlpatterns = [
path('home/',views.home,name="home"),
path('order/',views.order,name = 'auth'),
]

反向生成写法

from django.shortcuts import render
from django.views import View
from django.shortcuts import redirect
from django.http import HttpResponse,JsonResponse
# Create your views here.
class LoginView(View):
def post(self,request,role):
return JsonResponse({"code":200,"msg":"ok"})
def get(self,request,role):
from django.urls import reverse
url = reverse("x1:auth") # namespace:name
return redirect(url)

扩展

namespace编写的时候,需要提供app_name

加入namespace要设置appname,在url

urlpatterns = [
path('home/',views.home,name="home"),
path('order/',views.order,name = 'order'),
]
app_name=""

namespace可以多层嵌套

路由slash

最后的“/”如何解决

默认(setting.py):APPEND_SLASH= True 加“/”会重定向

urlpatterns = [
path('home/',views.home,name="home"), #用户访问时带不带最后的“/”都可以访问,不带“/”会进行一个重定向
path('order',views.order,name = 'order'),#用户访问时必须 不 带“/”
]

路由当前匹配对象

通过request.resolver_math获取

有什么用?

做权限处理,某用户,有一些权限,permissions=["xx1","login","xx"]

小结:

  • 必须掌握

    • 传统路由
    • 路由分发
    • name

  • 了解

    • 正则
    • namespace
    • 当前对象
  • 补充小知识点(看源码有关)

    • 关于partial改造函数(主要用于默认去传一个值)

      def xx(a1,a2):
      return a1+a2
      yy = partial(xx,a2=100)
      data = yy(2)
      print(data)