路由源码流程
#urls.py中ctrl+鼠标点击
path = partial(_path, Pattern=RoutePattern)
#partial的功能:
from functools import partial
def _path(v1, v2, v3):
return v1 + v2 + v3
path = partial(_path, v3=55)
print(path(11, 22))
_path:
def _path(route, view, kwargs=None, name=None, Pattern=None):
if isinstance(view, (list, tuple)):
# For include(...) processing.
pattern = Pattern(route, is_endpoint=False)
#
return URLResolver(
pattern,
urlconf_module,
kwargs,
app_name=app_name,
namespace=namespace,
)
#本质
urlpatterns = [
对象(URL地址、函数),
对象(URL地址、函数),
对象,
对象,
对象,
URLPattern(RoutePattern("login/", name=None, is_endpoint=True), views.login, None, None),
]
urlpattern和routepattern:
class URLPattern:
def __init__(self, pattern, callback, default_args=None, name=None):
self.pattern = pattern
self.callback = callback # the view
self.default_args = default_args or {}
= name
class RoutePattern(CheckURLMixin):
regex = LocaleRegexDescriptor('_route')
def __init__(self, route, name=None, is_endpoint=False):
self._route = route
self._regex_dict = {}
self._is_endpoint = is_endpoint
= name
self.converters = _route_to_regex(str(route), is_endpoint)[1]
项目启动:
wsgi.py
#call方法就是程序的入口
class WSGIHandler(base.BaseHandler):
request_class = WSGIRequest
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load_middleware()
def __call__(self, environ, start_response):
set_script_prefix(get_script_name(environ))
signals.request_started.send(sender=self.__class__, environ=environ)
request = self.request_class(environ)
response = self.get_response(request)
response._handler_class = self.__class__
看到:
response = self.get_response(request)
再进get_response, middleware_chain:
进入handler:
跳过异步的函数,看
callback, callback_args, callback_kwargs = self.resolve_request(request)
匹配成功:
# Resolve the view, and assign the match object back to the request.
resolver_match = resolver.resolve(request.path_info)
request.resolver_match = resolver_match
return resolver_match
1.resolver = get_resolver(), 即return URLResolver(RegexPattern(r'^/'), urlconf)
2.resolver.resolve路由匹配
3.request.resolver_match = 返回的resolver_match
进入resolve_request:
name别名:
path('login/', views.login, name='n1'),
URLPattern(RoutePattern("login/", name="n1", is_endpoint=True), views.login, None, "n1"),
from django.urls import reverse
result = reverse("n1")
print(result) # "login/"
from django.urls import reverse
result = reverse("n1",kwargs={"v1":123})
print(result) # "/api/auth/login/123/"
result = reverse("n1",kwargs={"v1":999})
print(result) # "/api/auth/login/999/"
意义:
/api/auth/login/ -> 函数登录
/api/user/account/ -> 函数账单
def login(request):
# 当用户登录成功之后,需要让用户跳转到 /api/user/account/ 页面
# return redirect("/api/user/account/")
# url = reverse("n2") # "/api/user/account/"
# return redirect(url)
return redirect("n2")
def account(request):
return HttpResponse("用户信息")