Django-View and URL configuration

Source: Internet
Author: User
Tags assert timedelta

The scope of a man's Walk is his world;--North "Dim light"

The tone of a man's singing is his life. --Little Q "Ditty"

-------------------------------------------------------------------------------------------------

In the previous section we set up a Django project, which we'll look at the relationship between the view and the URL;

"First View root directory"

When we set up Django, there's no URL in urls.py, we'll see a welcome page, but when we have a few URLs, we'll see 404 when we go directly to http://10.0.18.33:8002/ . Because Django does not normally add anything in the root directory, because all URLs are not special needs to be specified.

Therefore, the root directory also needs to be specified as follows, there will be a view display, configuration similar: URL (' ^$ ', My_homepage_view),

"Second view: static Hello World"

As we learn a language, the first interface to create Hello World, first understand that the page content is by View Functioin (view function) and urlconf defined URL. Of course, the view file for the name does not have certain requirements, but as far as the canonical point named view.py

View functions:

cat/helloworld/helloworld/view.py

From django.http import HttpResponse def hello (request): The return HttpResponse ("Hello World!!!") #在django. Import HTTPR in the HTTP module Esponse Class # Defines the Hello view function, the view function has at least one function request, the class instance # returns the HttpResponse object, the object contains the Hello World text # #即一个视图就是一个Python函数, in order for Django to recognize , to include the following two parameters: # #函数第一个参数类型是HttpResponse; Returns an HttpResponse instance.

URLconf: After configuring the View function, we will give this view an access path to bind this view function

cat/helloworld/helloworld/urls.py

From django.conf.urls import URL from django.contrib Import admin * * from helloworld.view import Hello urlpatterns = [ * * URL (' ^hello/$ ', hello), url (r ' ^admin/', Admin.site.urls),] #导入django. Conf.urls all Url#django.contrib will be described later, management tools #在HelloWorld. The #urlpatterns variable called the Hello View function in the View module, Django finds it in the Root_urlconf module # progenitor, the first element urlpattern pattern matching, the second element is the view function name #r is the regular, Tell Oython this is an original string and does not need to handle the escape character

Urlpatterns = Patterns ("',

)

Some versions of django,urls.conf default to this configuration, calling the patterns function

There is no URL pointing by default, so Django will assume you've created a new project that shows the IT work welcome screen

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/8B/94/wKiom1hRj1mxU-BaAAAVWRvLElw745.png "title=" 1.png " alt= "Wkiom1hrj1mxu-baaaavwrvlelw745.png"/>


===============================================================================================

Additional 1: About import calls, invoking Hello modules for example

1, Python to find the current path there is no hello.py

2, Python to sys.path out the path to find hello.py

Additional 2: About the domain name hello behind the '/', access to do not add

We urls.conf that we are required to add '/', but the default tail does not '/' will be automatically redirected to add '/'; test, if we remove hello after '/' in urls.conf, we will not be accessing Hello world.

Key in: settings.py in the Append_slash = False/true, like the '/' end can be set to True, like the end of their own definition '/' is set to False (that is, the Web side will not automatically append '/').

Add 3: We are passing the Hello function as an object instead of calling

This is an important feature of Python: functions are one-level objects, that is, they can be passed as transitive variables.

"Request Handling Process"

When you visit a URL that exists, some people think about how Django works, and then we use Hello World to explain it to you:

(all generated from settings.py,django-admin.py startproject, file contains Django configuration information, all uppercase)

1, when we python manage.py runserver 0.0.0.0:8002 Run, the script will be in the same amount of directory to find settings.py

2, settings.py to see root_urlconf, at this time it points to ' helloworld.urls ';

3, when accessing the/hello/, Django will go through the URL ~/helloworld/urls.py, until found, or 404;

4, find the matching hello, will call the corresponding view function;

5, then the view function returns HttpResponse;

6, Django conversion HttpResponse object is an HTTP response, and is displayed as a Web page;

(some would think that a series of regular maps of URLs to functions would be slower, but the fact would surprise you, that's what the official website says, hahaha,,)

================================================================================================

"Third view: Dynamic DateTime"

We use the Hello view to demonstrate the basic Django work form, which we will use dynamic content to display on the Web page: the current date and time.

From django.http import httpresponse**import datetime #调用datetime函数def Hello (Request): Return HttpResponse ("Hello World !!!") **def Current_time (Request): #定义视图函数 * * now = Datetime.datetime.now () #python语法, fetch current value * * html = "

Cat ~/helloworld/helloworld/urls.py

From django.conf.urls import urlfrom django.contrib import admin**from helloworld.view import hello,current_time #调用curr Ent_time View function urlpatterns = [url (' ^hello/$ ', hello), * * URL (' ^time/$ ', current_time), #定义urlurl (R ' ^admin/', admin.site.u RLS),]

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/8B/94/wKiom1hRkCXR-oejAAAY5QZWxP8904.png "title=" 2.png " alt= "Wkiom1hrkcxr-oejaaay5qzwxp8904.png"/>

===============================================================================================

Note: This time and local difference is much better, because Django defaults to the UTC time zone, instead time_zone = ' Asia/shanghai '.

"URL configuration and Loose coupling"

Loose coupling principle: (The philosophy behind Django and URL configuration) is important to ensure interchangeability of software development methods, URL and view functions are loosely coupled.

For example: Deciding which view function the URL returns and implementing the View function is two different places, allowing the developer to modify one piece without affecting the other;

For example: In the second view, we want to change the URL/time/to/currenttime/, we just need to quickly modify the URL configuration, we also want to modify the internal implementation of the function, do not worry about the URL will be affected.

===============================================================================================

"Fourth dynamic URL of view"

In our "current_time" view example, although the content is dynamic, but the URL is still static, in most web programs, URLs usually contain related parameters, such as/books/654,/books/7868 ....

Design: Displays the current time + time offset, i.e.

/TIME/PLUS/1 = Current Time +1

/TIME/PLUS/2 = Current Time +2

/TIME/PLUS/3 = Current Time +3

.........

If we define it according to the method above, it will be the following configuration:

urlpatterns = [url (' ^hello/$ ', hello), url (' ^time/$ ', current_time), #定义url * * (' ^time/plus/1/$ ', one_hour_ahead), * * (' ^time/plus/2/$ ', two_hours_ahead), * * (' ^time/plus/3/$ ', three_hours_ahead), url (r ' ^admin/', admin.site.urls),]

Obviously, this configuration is cumbersome and redundant, and we have to constantly define new view functions; So we're going to do a little abstraction and extract the common stuff out.

have Web development experience (PHP or Java) would like to: Use the query string it! Just like the hours inside the/time/plus?hours=3 should be specified in the query string hours parameter. Of course Django can do the same, but Django's core idea is that URLs must look beautiful, and beautiful URLs are a hallmark of high-quality web applications.

Answer: wildcard characters. (as mentioned earlier, a URL is a regular expression, so you can match more than one number with d+)

Cat ~/helloworld/helloworld/urls.py

From django.conf.urls import urlfrom django.contrib import admin**from helloworld.view import Hello,current_time,hours_ aheadurlpatterns = [url (' ^hello/$ ', hello), url (' ^time/$ ', Current_time), # (R ' ^time/plus/\d+/$ ', hours_ahead), #此模 Type can match/TIME/PLUS/1 to/time/plus/100000/any url** (R ' ^time/plus/\d{1,2}/$ ', hours_ahead), #限制一下, match the deviation within 100 hours of the URL (r ' ^ Admin/', Admin.site.urls),]

Now start writing the Hours_ahead view (of course we can also use the first write view, then write the URL of the bottom-up development, does not matter):

Cat ~/helloworld/helloworld/view.py

From django.http import http404,httpresponseimport datetimedef Hello (Request): Return HttpResponse ("Hello World!!!") def current_time (Request): now = Datetime.datetime.now () HTML = "

Interpreting the Code:

The view function Hours_ahead with two parameters:

The request is a HttpRequest object, and again, each view will always have a HttpRequest object as the first parameter;

Offset is extracted from a matching URL, such as/time/plus/3/, offset is 3, and the captured value is a string type (more precisely, the Unicode objects type).

If we call int on a value that cannot be converted to an int type, a ValueError exception is generated

DT calculates the time operation, assigns the value of the offset variable to hours, it can be days, the variable name can also be Offds, etc.

Eventually returned to a HttpResponse, which is now obsolete.

================================================================================================

Error:TypeError:hours_ahead () takes exactly 2 arguments (1 given)

Workaround: URL plus parentheses to URL (r ' ^time/plus/(\d{1,2})/$ ', hours_ahead), because the parentheses of the \d{1,2} content represents the second parameter position of the view function

================================================================================================

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/8B/91/wKioL1hRkVjT-sEIAAAfpH6cv-E482.png "title=" 3.png " alt= "Wkiol1hrkvjt-seiaaafph6cv-e482.png"/>

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/8B/91/wKioL1hRkU2RDg1zAAAuCChEPEc514.png "title=" 4.png " alt= "Wkiol1hrku2rdg1zaaaucchepec514.png"/>

"Error Page"

First: In Dbug mode, Access does not exist in the page

At this point we define a Hello URL page with an admin page, what happens if we visit another URL?

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/8B/94/wKiom1hRkYKzm8XBAABO8QDzLz8267.png "title=" 5.png " Style= "width:700px;height:221px", "alt=" Wkiom1hrkykzm8xbaabo8qdzlz8267.png "width=" "vspace=" 0 "hspace=" 0 "Height = "221" border= "0"/>

The second type: syntax error in dbug mode

Using the above view example, we will convert the integer step comment, as follows, and then access:

def hours_ahead (Request, offset): # try: # offset = int (offset) # except ValueError: # Raise Http404 () DT = Datetime.datetime.now () + Datetime.timedelta (hours=offset) HTML = "

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/8B/91/wKioL1hRkeHyxsOUAAE2Xyhk0Bo763.png "title=" 6.png " Style= "width:700px;height:667px", "alt=" Wkiol1hrkehyxsouaae2xyhk0bo763.png "width=" "vspace=" 0 "hspace=" 0 "Height = "667" border= "0"/>

Error Interpretation:

At the top of the page, we can see the key information, the exception data type, the parameter of the exception ( "Unsupported type" in this example), the file in which the exception was thrown, the line number of the error, and so on;

Below the key information, the complete Python tracking information is displayed, but the latter is more interactive, showing the file name, function, method name, line number, source code for each frame in the stack;

The "local VARs" in any frame can see a list of all local variables and their values on the frame when the error occurs;

"Switch to Copy-and-paste View" text under "Traceback". Click will switch another view, it makes it easy to copy and paste the content, easy to share; Click "Share this traceback to a public Web site" You can get a separate URL to share with others easily;

The next "Request Information" section contains a lot of information about WEB requests that generate errors: GET and POST, cookie values, metadata (like CGI headers), and the following setting in addition to Django configuration information.

================================================================================================

Add: Some programmers are accustomed to placing print statement debugging, in fact, can be debugged with the Django error page, insert the Assert False trigger error page anywhere in the view to view local variables and program statements;

DT = Datetime.datetime.now () + Datetime.timedelta (hours=offset)

* * Assert False

html = "

================================================================================================

Third: Turn off the dbug mode, because we will find that the above-mentioned sensitive information should not be presented to the user

Change debug = True to debug = False (settings.py in the Dbug mode) will be returned as follows

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/8B/94/wKiom1hRkiKSRIXXAAApnQHpmlY124.png "title=" 7.png " alt= "Wkiom1hrkiksrixxaaapnqhpmly124.png"/>

-----------------------------------------------------------------------------------------------------



This article is from the "North Ice--q" blog, please be sure to keep this source http://beibing.blog.51cto.com/10693373/1882887

Django-View and URL configuration

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.