Create a dynamic view in Django.

Source: Internet
Author: User

Create a dynamic view in Django.

In our ''current_datetime ''view example, although the content is dynamic, the URL (/time/) is static. In most dynamic web applications, URLs usually contain related parameters. For example, an online bookstore provides a URL for each book, such as/books/243/AND/books/81196 /.

Let's create a third view to display the current time and the time with the time difference. The design is as follows: /time/plus/1/display current time + 1 hour page/time/plus/2/display current time + 2 hours page/time/plus/3/display current Time + 3 hours page, and so on.

New users may consider writing different view functions to handle each time deviation. The URL configuration looks like this:

urlpatterns = patterns('',  ('^time/$', current_datetime),  ('^time/plus/1/$', one_hour_ahead),  ('^time/plus/2/$', two_hours_ahead),  ('^time/plus/3/$', three_hours_ahead),  ('^time/plus/4/$', four_hours_ahead),)

Obviously, this is not appropriate. There are not only a lot of redundant view functions, but the entire application is also limited to support only pre-defined time periods, 2 hours, 3 hours, or 4 hours. If we need to implement it for five hours one day, we have to create new view functions and configure URLs separately, which is repetitive and confusing. We need to make a little abstraction here to extract some common things.

Some Suggestions on beautiful URLs

If you have development experience on other web platforms (such as PHP or Java), you may think: Hey! Let's query string parameters! Like/time/plus? The hour in hours = 3 should be specified by the parameter hours in the query string (the parameter following the question mark ).

You can do the same in Django (if you really want to do this, we will tell you how to do it later), but one core idea of Django is that the URL must look beautiful. URL/time/plus/3/is clearer, simpler, and more readable. It can be easily read out because it is plain text and not as complex as query strings. A beautiful URL is like a sign of a high-quality Web application.

The Django URL configuration system allows you to easily set beautiful URLs, rather than the opposite side.

So, how do we design a program to deal with any number of time differences? The answer is: Use the wildcard (wildcard URLpatterns ). As we mentioned before, a URL pattern is a regular expression. Therefore, you can use d + to match more than one number.

urlpatterns = patterns('',  # ...  (r'^time/plus/\d+/$', hours_ahead),  # ...)

Use #... To indicate that other possible URL mode definitions are omitted. This URL mode will match any URL like/time/plus/2/,/time/plus/25/, or even/time/plus/100000000000. Furthermore, let's limit it to a maximum of 99 hours, so that we can only allow one or two numbers. The regular expression syntax is \ d {1, 2 }:

(r'^time/plus/\d{1,2}/$', hours_ahead),

Remarks

When building Web applications, it is important to think as much as possible about possible data input, and then decide which ones are acceptable. Here we have set a limit of 99 hours.

Another important point is that the regular expression string starts with the letter "r ". It tells Python that this is an original string and does not need to process the backslash (Escape Character) in it ). In a common Python string, the backslash is used to escape special characters. For example, escape n into a line break. After you use r to mark it as an original string, Python no longer regards the backslash as an escape character. That is to say, "n" is two strings: "" and "n ". Because the backslash conflicts between the Python code and the regular expression, we recommend that you use the original string when defining the Regular Expression in Python. From now on, all URL modes in this article use the original string.

Now we have designed a URL with a wildcard character. We need a method to pass it to the view function, so that we can process all the time periods with only one view function. We use parentheses to mark the parameters in URL mode. In this example, we want to use these numbers as parameters to enclose \ d {} in parentheses:

(r'^time/plus/(\d{1,2})/$', hours_ahead),

If you are familiar with regular expressions, you should know that regular expressions use parentheses to extract data from text.

The final URLconf contains the preceding two views, for example:

from django.conf.urls.defaults import *from mysite.views import hello, current_datetime, hours_aheadurlpatterns = patterns('',  (r'^hello/$', hello),  (r'^time/$', current_datetime),  (r'^time/plus/(\d{1,2})/$', hours_ahead),)

Now, write the hours_ahead view.

Encoding order

In this example, we first write URLpattern and then the view, but in the previous example, we first write the view and then URLpattern. Which method is better?

Well, every developer is different.

If you like to grasp things in general (Note: or translated as "overall situation View"), you should want to write all the URL configurations at the beginning of the project.

If you are a developer from the bottom up, you may prefer to write the view first and then link them to the URL. This is also possible.

Finally, either of the two methods is acceptable depending on the technology you like. (See above)

Hours_ahead is very similar to the previously written current_datetime. The key difference is that it has an additional parameter and time difference. The following is the view code:

from django.http import Http404, HttpResponseimport datetimedef hours_ahead(request, offset):  try:    offset = int(offset)  except ValueError:    raise Http404()  dt = datetime.datetime.now() + datetime.timedelta(hours=offset)  html = "

Let's analyze the code line by line:

View function, hours_ahead, has two parameters: request and offset. (See the preceding Section)

Request is an HttpRequest object, just like in current_datetime. Once again: each view always uses an HttpRequest object as its first parameter. (See above)

Offset is extracted from the matching URL. For example, if the request URL is/time/plus/3/, the offset value is 3. If the request URL is/time/plus/21/, the offset value is 21. Note: The captured values are always of the string type rather than the integer type, even if the string is composed of digits (such as "21 ").

(Technically, the captured value is always Unicode objects, rather than a simple Python byte string, but there is no need to worry about these differences at present .)

Here we name the variable offset. You can also name it as long as it complies with the Python syntax. The variable name is irrelevant. What matters is its location. It is the second parameter of the function (after the request ). You can also use keywords to define it, rather than location.

The first thing we need to do in this function is to call int () on offset. This will convert this string value to an integer.

Note: If you call int () on a value that cannot be converted to an integer type, Python will throw a ValueError exception. For example, int ('foo '). In this example, if we encounter a ValueError exception, we will throw the django. http. Http404 exception -- as you think: The 404 page is displayed (the prompt message: the page does not exist ).

Clever readers may ask: in URL mode, we use a regular expression (d {}) to constrain it. What if we only accept numbers? In any case, offset is composed of numbers. The answer is: we will not do this because URLpattern provides "moderate but useful" level input validation. In case this view function is called by other methods, we still need to check the ValueError. Practice has proved that it is better not to speculate the parameter value when implementing a view function. Loose coupling, remember?

Next line, calculate the current date/time, and add the appropriate hours. In the current_datetime view, we have seen datetime. datetime. now (). The new concept here is to execute arithmetic operations on the date/time. We need to create a datetime. timedelta object and add a datetime. datetime object. The result is saved in the dt variable.

This line also explains why the hours parameter must be of the integer type when we call int () -- datetime. timedelta function on offset.

A tiny difference between this line and the previous line is that it uses the format string function of Python with two values, not just a value. Therefore, the string contains two % s symbols and a tuple of values to be inserted: (offset, dt ).

Finally, an HTML HttpResponse is returned. Today, this method is outdated.

After the view function and URL configuration are completed, start the Django development server and access http: // 127.0.0.1: 8000/time/plus/3/in the browser to confirm that it works properly. Then http: // 127.0.0.1: 8000/time/plus/5 /. Then http: // 127.0.0.1: 8000/time/plus/24 /. Finally, access http: // 127.0.0.1: 8000/time/plus/100/to check whether the mode set in the URL configuration only accepts one or two numbers; django will display a Page not found error Page, which is the same as the 404 error. Access URL http: // 127.0.0.1: 8000/time/plus/(no time difference defined) will also throw a 404 error.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.