search
HomeBackend DevelopmentPython TutorialDjango中URL视图函数的一些高级概念介绍

说到关于请求方法的分支,让我们来看一下可以用什么好的方法来实现它。 考虑这个 URLconf/view 设计:

# urls.py

from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
  # ...
  (r'^somepage/$', views.some_page),
  # ...
)

# views.py

from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response

def some_page(request):
  if request.method == 'POST':
    do_something_for_post()
    return HttpResponseRedirect('/someurl/')
  elif request.method == 'GET':
    do_something_for_get()
    return render_to_response('page.html')
  else:
    raise Http404()

在这个示例中,`` some_page()`` 视图函数对`` POST`` 和`` GET`` 这两种请求方法的处理完全不同。 它们唯一的共同点是共享一个URL地址: `` /somepage/.``正如大家所看到的,在同一个视图函数中对`` POST`` 和`` GET`` 进行处理是一种很初级也很粗糙的做法。 一个比较好的设计习惯应该是,用两个分开的视图函数——一个处理`` POST`` 请求,另一个处理`` GET`` 请求,然后在相应的地方分别进行调用。

我们可以像这样做:先写一个视图函数然后由它来具体分派其它的视图,在之前或之后可以执行一些我们自定的程序逻辑。 下边的示例展示了这个技术是如何帮我们改进前边那个简单的`` some_page()`` 视图的:

# views.py

from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response

def method_splitter(request, GET=None, POST=None):
  if request.method == 'GET' and GET is not None:
    return GET(request)
  elif request.method == 'POST' and POST is not None:
    return POST(request)
  raise Http404

def some_page_get(request):
  assert request.method == 'GET'
  do_something_for_get()
  return render_to_response('page.html')

def some_page_post(request):
  assert request.method == 'POST'
  do_something_for_post()
  return HttpResponseRedirect('/someurl/')

# urls.py

from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
  # ...
  (r'^somepage/$', views.method_splitter, {'GET': views.some_page_get, 'POST': views.some_page_post}),
  # ...
)

让我们从头看一下代码是如何工作的:

    我们写了一个新的视图,`` method_splitter()`` ,它根据`` request.method`` 返回的值来调用相应的视图。可以看到它带有两个关键参数,`` GET`` 和`` POST`` ,也许应该是* 视图函数* 。如果`` request.method`` 返回`` GET`` ,那它就会自动调用`` GET`` 视图。 如果`` request.method`` 返回的是`` POST`` ,那它调用的就是`` POST`` 视图。 如果`` request.method`` 返回的是其它值(如:`` HEAD`` ),或者是没有把`` GET`` 或`` POST`` 提交给此函数,那它就会抛出一个`` Http404`` 错误。

    在URLconf中,我们把`` /somepage/`` 指到`` method_splitter()`` 函数,并把视图函数额外需要用到的`` GET`` 和`` POST`` 参数传递给它。

    最终,我们把`` some_page()`` 视图分解到两个视图函数中`` some_page_get()`` 和`` some_page_post()`` 。这比把所有逻辑都挤到一个单一视图的做法要优雅得多。

    注意,在技术上这些视图函数就不用再去检查`` request.method`` 了,因为`` method_splitter()`` 已经替它们做了。 (比如,`` some_page_post()`` 被调用的时候,我们可以确信`` request.method`` 返回的值是`` post`` 。)当然,这样做不止更安全也能更好的将代码文档化,这里我们做了一个假定,就是`` request.method`` 能象我们所期望的那样工作。

现在我们就拥有了一个不错的,可以通用的视图函数了,里边封装着由`` request.method`` 的返回值来分派不同的视图的程序。关于`` method_splitter()`` 就不说什么了,当然,我们可以把它们重用到其它项目中。

然而,当我们做到这一步时,我们仍然可以改进`` method_splitter`` 。从代码我们可以看到,它假设`` Get`` 和`` POST`` 视图除了`` request`` 之外不需要任何其他的参数。那么,假如我们想要使用`` method_splitter`` 与那种会从URL里捕捉字符,或者会接收一些可选参数的视图一起工作时该怎么办呢?

为了实现这个,我们可以使用Python中一个优雅的特性 带星号的可变参数 我们先展示这些例子,接着再进行解释

def method_splitter(request, *args, **kwargs):
  get_view = kwargs.pop('GET', None)
  post_view = kwargs.pop('POST', None)
  if request.method == 'GET' and get_view is not None:
    return get_view(request, *args, **kwargs)
  elif request.method == 'POST' and post_view is not None:
    return post_view(request, *args, **kwargs)
  raise Http404

这里,我们重构method_splitter(),去掉了GET和POST两个关键字参数,改而支持使用*args和和**kwargs(注意*号) 这是一个Python特性,允许函数接受动态的、可变数量的、参数名只在运行时可知的参数。 如果你在函数定义时,只在参数前面加一个*号,所有传递给函数的参数将会保存为一个元组. 如果你在函数定义时,在参数前面加两个*号,所有传递给函数的关键字参数,将会保存为一个字典

例如,对于这个函数

def foo(*args, **kwargs):
  print "Positional arguments are:"
  print args
  print "Keyword arguments are:"
  print kwargs

看一下它是怎么工作的

>>> foo(1, 2, 3)
Positional arguments are:
(1, 2, 3)
Keyword arguments are:
{}
>>> foo(1, 2, name='Adrian', framework='Django')
Positional arguments are:
(1, 2)
Keyword arguments are:
{'framework': 'Django', 'name': 'Adrian'}

回过头来看,你能发现我们用method_splitter()和*args接受**kwargs函数参数并把它们传递到正确的视图。any 但是在我们这样做之前,我们要调用两次获得参数kwargs.pop()GETPOST,如果它们合法的话。 (我们通过指定pop的缺省值为None,来避免由于一个或者多个关键字缺失带来的KeyError)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to implement factory model in Python?How to implement factory model in Python?May 16, 2025 pm 12:39 PM

Implementing factory pattern in Python can create different types of objects by creating a unified interface. The specific steps are as follows: 1. Define a basic class and multiple inheritance classes, such as Vehicle, Car, Plane and Train. 2. Create a factory class VehicleFactory and use the create_vehicle method to return the corresponding object instance according to the type parameter. 3. Instantiate the object through the factory class, such as my_car=factory.create_vehicle("car","Tesla"). This pattern improves the scalability and maintainability of the code, but it needs to be paid attention to its complexity

What does r mean in python original string prefixWhat does r mean in python original string prefixMay 16, 2025 pm 12:36 PM

In Python, the r or R prefix is ​​used to define the original string, ignoring all escaped characters, and letting the string be interpreted literally. 1) Applicable to deal with regular expressions and file paths to avoid misunderstandings of escape characters. 2) Not applicable to cases where escaped characters need to be preserved, such as line breaks. Careful checking is required when using it to prevent unexpected output.

How to clean up resources using the __del__ method in Python?How to clean up resources using the __del__ method in Python?May 16, 2025 pm 12:33 PM

In Python, the __del__ method is an object's destructor, used to clean up resources. 1) Uncertain execution time: Relying on the garbage collection mechanism. 2) Circular reference: It may cause the call to be unable to be promptly and handled using the weakref module. 3) Exception handling: Exception thrown in __del__ may be ignored and captured using the try-except block. 4) Best practices for resource management: It is recommended to use with statements and context managers to manage resources.

Usage of pop() function in python list pop element removal method detailed explanation of theUsage of pop() function in python list pop element removal method detailed explanation of theMay 16, 2025 pm 12:30 PM

The pop() function is used in Python to remove elements from a list and return a specified position. 1) When the index is not specified, pop() removes and returns the last element of the list by default. 2) When specifying an index, pop() removes and returns the element at the index position. 3) Pay attention to index errors, performance issues, alternative methods and list variability when using it.

How to use Python for image processing?How to use Python for image processing?May 16, 2025 pm 12:27 PM

Python mainly uses two major libraries Pillow and OpenCV for image processing. Pillow is suitable for simple image processing, such as adding watermarks, and the code is simple and easy to use; OpenCV is suitable for complex image processing and computer vision, such as edge detection, with superior performance but attention to memory management is required.

How to implement principal component analysis in Python?How to implement principal component analysis in Python?May 16, 2025 pm 12:24 PM

Implementing PCA in Python can be done by writing code manually or using the scikit-learn library. Manually implementing PCA includes the following steps: 1) centralize the data, 2) calculate the covariance matrix, 3) calculate the eigenvalues ​​and eigenvectors, 4) sort and select principal components, and 5) project the data to the new space. Manual implementation helps to understand the algorithm in depth, but scikit-learn provides more convenient features.

How to calculate logarithm in Python?How to calculate logarithm in Python?May 16, 2025 pm 12:21 PM

Calculating logarithms in Python is a very simple but interesting thing. Let's start with the most basic question: How to calculate logarithm in Python? Basic method of calculating logarithm in Python The math module of Python provides functions for calculating logarithm. Let's take a simple example: importmath# calculates the natural logarithm (base is e) x=10natural_log=math.log(x)print(f"natural log({x})={natural_log}")# calculates the logarithm with base 10 log_base_10=math.log10(x)pri

How to implement linear regression in Python?How to implement linear regression in Python?May 16, 2025 pm 12:18 PM

To implement linear regression in Python, we can start from multiple perspectives. This is not just a simple function call, but involves a comprehensive application of statistics, mathematical optimization and machine learning. Let's dive into this process in depth. The most common way to implement linear regression in Python is to use the scikit-learn library, which provides easy and efficient tools. However, if we want to have a deeper understanding of the principles and implementation details of linear regression, we can also write our own linear regression algorithm from scratch. The linear regression implementation of scikit-learn uses scikit-learn to encapsulate the implementation of linear regression, allowing us to easily model and predict. Here is a use sc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool