1024programmer Java The reason why class view.as_view() can be used for mapping in URL in Django

The reason why class view.as_view() can be used for mapping in URL in Django

Note: When I was learning to practice daily fresh projects, I was a little confused about using class views to map URLs matched by regular rules. I finally figured it out after checking other people’s blogs and self-analysis, so Record it

Reference: https://www.zmrenwu.com/post/53/

There are many ways to send HTTP requests. Here are POST and GET as examples. When entering the url address in the browser (such as http://127.0.0.1:8000/userr/register)

will perform regular matching and map to ActiveView.as_view(), which will ultimately achieve the effect of displaying the registration page for the following reasons:

class RegisterView(View):
”’Register”’
def get(self, request):
”’Display registration page”’
return render (request, ‘register.html’)
def post(self, request):
”’Perform registration processing”’
”’Perform registration processing”’
# Receive data
username = request.POST.get(‘user_name’)
password = request.POST.get(‘pwd’)
email = request.POST.get(’email’)
allow = request.POST.get(‘allow’)
# Perform data processing
if not all([username, password, email]):
return render(request, ‘register.html’, {‘errmsg ‘: ‘Incomplete data’})
# Verify email
if not re.match(r’^[a-z0-9][\w.\-]*@[a-z0-9 \-]+(\.[a-z]{2,5}){1,2}$’, email):
return render(request, ‘register.html’, {‘errmsg’: ‘The email format is incorrect Correct’})
# Verification agreement
if allow != ‘on’:
return render(request, ‘register.html’, {‘errmsg’: ‘Please agree to the agreement’})
# Verify whether the user name is repeated
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# The user does not exist
user = None
# Perform business processing: Register user
user = User.objects.create_user(username, email, password)
user.is_active = 0
user.save()
# Send activation email
serializer = Serializer(settings.SECRET_KEY, 3600)
info = {‘confirm’:user.id}
token = serializer.dumps(info) # bytes
token = token.decode()
# Send email
send_register_active_email.delay(email, username, token)
# subject = ‘Fresh welcome message every day’
# message = ”
# sender = settings.EMAIL_FROM
# receiver = [email]
# html_message = ‘%s, Welcome to become a registered member of Tiansheng Fresh. Please click the link below to activate your account
http://127.0.0.1:8000/userr/ active/%s’ % (
# username, token, token)
# send_mail(subject, message, sender, receiver, html_message=html_message)
# Return the response and jump to the homepage
return redirect(reverse(‘goods:index’))

 

There is no as_view() method in the RegisterView class, but there is an as_view() method in its parent class View. So this method of the parent class is called. The original code of the parent class View is as follows

class View(object):
“””
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
“””
http_method_names = [‘get’, ‘post’, ‘put’, ‘patch’, ‘delete’, ‘head’, ‘options’ , ‘trace’]
def __init__(self, **kwargs):
“””
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
“””
# Go through keyword arguments, and either save their values ​​to our
# instance, or raise an error.
for key, value in six.iteritems(kwargs):
setattr (self, key, value)
@classonlymethod
def as_view(cls, **initkwargs):
“””
Main entry point for a request-response process.
“””
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(“You tried to pass in the %s method name as a “
“keyword argument to %s(). Don’t do that.”
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError(“%s() received an invalid keyword %r. as_view “
“only accepts arguments that are already “
“attributes of the class.” % (cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, ‘get’) and not hasattr(self, ‘head’):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn’t exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn’t on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower( ), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
def http_method_not_allowed(self, request, *args, **kwargs ):
logger.warning(
‘Method Not Allowed (%s): %s’, request.method, request.path,
extra={‘status_code’: 405, ‘request’: request }
)
return http.HttpResponseNotAllowed(self._allowed_methods())
def options(self, request, *args, **kwargs):
“””
Handles responding to requests for the OPTIONS HTTP verb.
“””
respOnse= http.HttpResponse()
response[‘Allow’] = ‘, ‘.join(self._allowed_methods())
response[‘ Content-Length’] = ‘0’
return response
def _allowed_methods(self):
return [m.upper() for m in self.http_method_names if hasattr(self, m)]

The functions implemented by the dispatch() method are as follows:

First, it passes request.method (i.e. HTTP Requested method) determines whether the requested method is allowed by the HTTP protocol. If it is illegal, the error handling function self.http_method_not_allowed will be called; if the request method is legal, it will try to find the corresponding processing in the class based on request.method Method, if it cannot be found, it will still be delegated to self.http_method_not_allowed for processing.

Code implementation process:

When entering the url address in the browser (such as http://127.0.0.1:8000/userr/register) , after regular matching and mapping, the View.as_view() method is first called, and then the view() method in the as_view() method is called. The view() method further calls the dispatch() method in the View class. , in the dispatch() method, request.method determines that the HTTP request method is GET, request.method.lower() converts GET into get, and the getattr method gives the negative get value to the handler, and then returns handler() Calling the handler() method is the get() method in the RegisterView class, and the get() method will return the html file in the template (ie register.html). The results returned are returned to the caller of the method in turn. The final result returned to the View.as_view() method is the register.html file in the template, which displays the registration page, as follows

When you click to register (fill in the relevant information), the HTTP The request method changes to POST. In the same way, the corresponding page can eventually be displayed (here, the home page is displayed)

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/the-reason-why-class-view-as_view-can-be-used-for-mapping-in-url-in-django/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索