Django Study Notes (2): Django view and URL

Source: Internet
Author: User
Tags django server

I. A simple demo to describe the django processing process

1. Create a view)

First, create a new view in the current directory. py (view), and then edit it as follows: (in the subsequent tutorial, This is just created manually. We can create an app, including IT) (You can also create a url ing before creating the corresponding view function)

1 # coding = UTF-8 2 3 # from django. import the HttpResponse class [1] 4 from django in the http module. http import HttpResponse 5 import datetime 6 7 def current_datetime (request): # [2] 8 now = datetime. datetime. now () 9 html = "

Note: This is a simple and simple example. For more information about optimization, see the following section.
Analysis:

[1].The HttpResponse class is located in the django. http module and is manually created. Unlike the HttpRequest object automatically created by Django, each view needs to be instantiated, processed, and returned with an HttpResponse object.

Generally, when an HttpResponse is created, the page content is transmitted as a string to the HttpResponse constructor:

1 >>>response=HttpResponse('I am BeginMan! ')2 >>>response=HttpResponse('HelloWorld',mimetype='text/plain')

If you want to add content, you can use response as a class file object:

1 response=HttpResponse()2 response.write("<p>i am beginman </p>")3 response.write("<p>coding for fun! </p>")

For more information, see the content in the Appendix of Django Book.

[2].In this (views. py) view, each function is called a view function. A view function uses an HttpRequest object as the first parameter, which is usually named request.

2. URL ing View

The url is like a bridge. Through this bridge, we can find the corresponding code in the view and render the template (this chapter is not included in the template at the moment ), all of this is done by calling URLConf (that is, urls. py), after we django-admin.py startproject mysite, the script will automatically create a URLConf (that is, urls. in the settings. find its real body in py, as shown below:

1 ...... 2 ROOT_URLCONF = 'mysite. urls' 3 ...... Omitted

Enable urls. py as follows:

 1 from django.conf.urls.defaults import *  #[1] 2  3 # Uncomment the next two lines to enable the admin: 4 # from django.contrib import admin 5 # admin.autodiscover() 6  7 urlpatterns = patterns('',         #[2] 8     # Example: 9     # (r'^mysite/', include('mysite.foo.urls')),10 11     # Uncomment the admin/doc line below to enable admin documentation:12     # (r'^admin/doc/', include('django.contrib.admindocs.urls')),13 14     # Uncomment the next line to enable the admin:15     # (r'^admin/', include(admin.site.urls)),16 )

Analysis:
[1]. Import all objects from django. conf. urls. defaults, including a function called patterns
[2]. the patterns () function saves the processing result to the urlpatterns variable. Note that there is a blank block in patterns ('',). Its existence is the it worked previously displayed in the browser.

For more information about URL configuration, see the following blog:"Common URL configurations"

Edit the file to display the current_datetime View:

1 from django.conf.urls.defaults import *2 from mysite.views import current_datetime3 4 urlpatterns = patterns('',5     (r'^time/$',current_datetime)6 )

The parameters in the patterns function are actually a ancestor. The front side is a regular expression, and the back side is the corresponding view function (in this demo). In the browser, input http: // 127.0.0.1: 8000/time, Django searches for the first matched/time/entry in all URL modes in URLconf. If the matching is successful, the view function returns an HttpResponse and calls the current_datetime view function. Django converts HttpResponse to an appropriate HTTP response, which is displayed on the Web page, (without the template definition) display the output result.

So far, this series of simple Django processing procedures have been completed.

2. Django's request processing mechanism

Remember:

1.When the Django server is started with manage. py runserver, the settings. py in the same directory is loaded. This file contains the configuration information in the project, such as the URLConf mentioned above. The most important configuration is ROOT_URLCONF, which tells Django which Python module should be used as the URLConf of this site, the default value is urls. py

2.When accessing the url, Django loads the URLConf according to the ROOT_URLCONF settings.

3.Then, match the URLpatterns in URLConf one by one. If this parameter is found, the associated view function is called and the HttpRequest object is used as the first parameter (usually request)

4.The view function returns an HttpResponse object,

4. Further steps: Dynamic URL

The above simple example introduces the dynamic content. Next, let's take a deeper look at url ing to implement dynamic URLs.

We need to enter some parameters after the url to implement different calling content (for example, enter a number (hours) after the url to display the time after the current time accumulation, for example, if the current time is, enter... in the browser .... time/plus/3, then) Small instance (see Django Book)

We can implement the following three methods:

First: Write all data to the url

1 urlpatterns = patterns('',2     (r'^time/$',current_datetime),3     (r'^time/plus/1/$',one_hour_ahead),4     (r'^time/plus/2/$',two_hour_ahead),5     (r'^time/plus/3/$',three_hour_ahead),6     ...............................7     ..................8 )

This kind of explanation is not enough. Pass

Second: the URL query string format, in the form? Such as/time/plus? Hours = 3. This is a common method in asp.net, but in django, it looks bloated and inefficient. Pass

Third: URL matching mode with wildcard characters
Because the URL mode is a regular expression, you can use the regular expression and URL configuration skills. For details, see the other two blog posts:Python fragmentation knowledge (5): Regular Expressions and Django Summary (1): Common URL configuration methods

For this instance, you can use \ d + to match one or more numbers:

1 urlpatterns = patterns ('', 2 (R' ^ time/$ ', current_datetime), 3 (R' ^ time/plus/\ d +/$', hours_ahead ), 4 (R' ^ time/plus/(\ d {1, 2})/$ ', hours_ahead), # or a maximum of 995 allowed)

Then, compile the hours_ahead view function as follows:

1 # coding = UTF-8 2 3 # from django. import the HttpResponse class [1] 4 from django in the http module. http import HttpResponse 5 import datetime 6 7 def current_datetime (request): # [2] 8 now = datetime. datetime. now () 9 html = "

Note: hours_ahead has two parameters. The first request has been discussed previously;The second parameter offset is extracted from the matching URL., Such as/time/plus/10, extract offset is 10 (note that the string must be int to an integer before it can be added)

V. Summary

MASTER: 1. url ing basics, 2. View functions, 3. Django's request processing mechanism, 4. Dynamic URL thinking

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.