基于Django的《计算机网络》教学平台设计与实现外文翻译资料

 2021-12-11 08:12

Views and URLconfs

Your First Django-Powered Page: Hello World

As our first goal, letrsquo;s create a Web page that outputs that famous example message: “Hello world.”

If you were publishing a simple “Hello world” Web page without a Web framework, yoursquo;d simply type “Hello world” into a text file, call it hello.html, and upload it to a directory on a Web server somewhere. Notice, in that process, yoursquo;ve specified two key pieces of information about that Web page: its contents (the string 'Hello world') and its URL ( http://www.example.com/hello.html, or maybe http://www.example.com/files/hello.htmlif you put it in a subdirectory).

With Django, you specify those same two things, but in a different way. The contents of the page are produced by a view function, and the URL is specified in a URLconf. First, letrsquo;s write our “Hello world” view function.

Your First View

Within the mysite directory that django-admin.py startproject made in the last chapter, create an empty file called views.py. This Python module will contain our views for this chapter. Note that therersquo;s nothing special about the name views.py – Django doesnrsquo;t care what the file is called, as yoursquo;ll see in a bit – but itrsquo;s a good idea to call it views.py as a convention, for the benefit of other developers reading your code.

Our “Hello world” view is simple. Herersquo;s the entire function, plus import statements, which you should type into the views.py file:

from django.http import HttpResponse

def hello(request):

return HttpResponse('Hello world')

Letrsquo;s step through this code one line at a time:

  • First, we import the class HttpResponse, which lives in the django.http module. We need to import this class because itrsquo;s used later in our code.
  • Next, we define a function called hello – the view function.

Each view function takes at least one parameter, called request by convention. This is an object that contains information about the current Web request that has triggered this view, and itrsquo;s an instance of the class django.http.HttpRequest. In this example, we donrsquo;t do anything with request, but it must be the first parameter of the view nonetheless.

Note that the name of the view function doesnrsquo;t matter; it doesnrsquo;t have to be named in a certain way in order for Django to recognize it. Wersquo;re calling it hello here, because that name clearly indicates the gist of the view, but it could just as well be named hello_wonderful_beautiful_world, or something equally revolting. The next section, “Your First URLconf”, will shed light on how Django finds this function.

  • The function is a simple one-liner: it merely returns an HttpResponse object that has been instantiated with the text 'Hello world'.

The main lesson here is this: a view is just a Python function that takes an HttpRequest as its first parameter and returns an instance of HttpResponse. In order for a Python function to be a Django view, it must do these two things. (There are exceptions, but wersquo;ll get to those later.)

Your First URLconf

If, at this point, you ran python manage.py runserver again, yoursquo;d still see the “Welcome to Django” message, with no trace of our “Hello world” view anywhere. Thatrsquo;s because our mysite project doesnrsquo;t yet know about the helloview; we need to tell Django explicitly that wersquo;re activating this view at a particular URL. (Continuing our previous analogy of publishing static HTML files, at this point wersquo;ve created the HTML file but havenrsquo;t uploaded it to a directory on the server yet.) To hook a view function to a particular URL with Django, use a URLconf.

A URLconf is like a table of contents for your Django-powered Web site. Basically, itrsquo;s a mapping between URLs and the view functions that should be called for those URLs. Itrsquo;s how you tell Django, “For this URL, call this code, and for that URL, call that code.” For example, “When somebody visits the URL /foo/, call the view function foo_view(), which lives in the Python module views.py.”

When you executed django-admin.py startproject in the previous chapter, the script created a URLconf for you automatically: the file urls.py. By default, it looks something like this:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:

# from django.contrib import admin

# admin.autodiscover()

urlpatterns = patterns(#39;#39;,

# Examples:

# url(r#39;^$#39;, #39;mysite.views.home#39;, name=#39;home#39;),

# url(r#39;^mysite/#39;, include(#39;mysite.foo.urls#39;)),

# Uncomment the admin/doc line below to enable admin documentation:

# url(r#39;^admin/doc/#39;, include(#39;django.contrib.admindocs.urls#39;)),

# Uncomment the next line to enable the admin:

# url(r#39;^admin/#39;, include(admin.site.urls)),

)

This default URLconf includes some commonly used Django features commented out, so that activating those features is as easy as uncommenting the appropriate lines. If we ignore the commented-out code, herersquo;s the essence of a URLconf:

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns(#39;#39;,

)

Letrsquo;s step through this code one line at a time:

  • The first line imports three functions from the django.conf.urls.defaults module, which is Djangorsquo;s URLconf infrastructure: patterns, include, and urls.
  • The second line calls the function patterns and saves the result into a variable called urlpatterns. The patterns function gets passed only a single argument – the empty string. (The string can be used to supply a common prefix for view functions, which wersquo;ll cover in Chapter 8: Advanced Views and URLconfs.)

The main

视图和URLconfs

你的第一个Django驱动页面:Hello World

作为我们的第一个目标,让我们创建一个Web页面,输出著名的示例消息:“HelloWorld”。

如果您正在发布一个没有Web框架的简单的“Hello World”网页,只需在文本文件中键入“Hello World”,就可以称它hello.html,并将其上传到Web服务器的某个目录中。注意,在这个过程中,您已经指定了关于该网页的两个关键信息:它的内容(字符串“Hello World”)及其URL(http://www.example.com/hello.html,或者http://www.example.com/files/hello.html如果你把它放在子目录中)。

对于Django,您可以使用不同的方式指定这两件事。网页的内容由视图函数生成,并且URL位于URLconf中。首先,让我们编写“Hello World”视图函数。

你的第一视图

在上一章中创建的mysite目录中,创建一个名为views.py的空文件。 这个Python模块将包含我们对本章的看法。 请注意,名称views.py没有什么特别之处 - Django并不关心文件的名称,因为您稍后会看到 - 但最好将其称为views.py作为约定,有利于其他开发人员阅读您的代码。

我们的“Hello World”视图很简单。下面是整个函数,加上导入语句,你应该将这些语句键入views.py档案:

from django.http import HttpResponse

def hello(request):

return HttpResponse('Hello world')

  • 我们逐行逐句地分析一遍这段代码:
  • 首先,我们导入类HttpResponse,它存在于django.http模块。我们需要导入这个类,因为它稍后会在我们的代码中使用。
  • 接下来,我们定义了一个名为Hello的视图函数。

每个视图函数至少有一个参数,称为请求按照惯例。这是一个包含触发此视图的当前Web请求的信息的对象,它是类的一个实例django.http.HttpRequest。在这个例子中,我们不做任何事情请求,但它必须是视图的第一个参数。

请注意,视图函数的名称并不重要;它不必以某种方式命名,Django才能识别它。我们在这里称之为Hello,因为该名称清楚地表示视图的要点,但也可以将其命名为hello_wonderful_beautiful_world。或者同样的东西。下一节“您的第一个URLconf”将说明Django如何找到这个函数。

  • 函数是一个简单的一行:它只是返回一个HttpResponse已用文本实例化的“Hello World”.

这里的主要教训是:视图只是一个Python函数,它接受HttpRequest的第一个参数,并返回HttpResponse。为了使Python函数成为Django视图,它必须做以下两件事。(也有例外,但我们稍后再谈。)

你的第一个URLCONF

此时,如果你再次运行python manage.py runserver,你仍然会看到“欢迎使用Django”消息,并且在任何地方都没有我们的“Hello world”视图的痕迹。 那是因为我们的mysite项目还不知道hello view; 我们需要明确地告诉Django我们在特定的URL上激活这个视图。 (继续我们之前发布静态HTML文件的类比,此时我们已经创建了HTML文件但尚未将其上传到服务器上的目录。)要使用Django将视图函数挂钩到特定URL,请使用URL配置。

URLconf就像是Django支持的Web站点的目录。 基本上,它是URL和应该为这些URL调用的视图函数之间的映射。 这是你告诉Django的方式,“对于这个URL,调用这个代码,并为该URL调用该代码。”例如,“当有人访问URL / foo /时,调用视图函数foo_view(),它存在于 Python模块views.py。”

在前一章中执行django-admin.py startproject时,脚本会自动为您创建一个URLconf文件urls.py. 默认情况下,它看起来像这样:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:

# from django.contrib import admin

# admin.autodiscover()

urlpatterns = patterns(#39;#39;,

# Examples:

# url(r#39;^$#39;, #39;mysite.views.home#39;, name=#39;home#39;),

# url(r#39;^mysite/#39;, include(#39;mysite.foo.urls#39;)),

# Uncomment the admin/doc line below to enable admin documentation:

# url(r#39;^admin/doc/#39;, include(#39;django.contrib.admindocs.urls#39;)),

# Uncomment the next line to enable the admin:

# url(r#39;^admin/#39;, include(admin.site.urls)),

)

这个默认的URLconf包含一些常用的Django特性,因此激活这些特性就像取消适当的行注释一样容易。如果忽略注释掉的代码,下面是URLconf的本质:

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns(#39;#39;,

)

让我们一次只执行一行代码:

  • 第一行从django.conf.urls.默认值模块,它是Django的URLconf基础设施:patterns, include和URL.

第二行调用函数模式并将结果保存到名为urlpatterns的变量中。 patterns函数只传递一个参数 - 空字符串。

这里要注意的主要是变量urlpatterns,Django希望在你的URLconf模块中找到它。 此变量定义URL与处理这些URL的代码之间的映射。 默认情况下,正如我们所看到的,URLconf是空的 - 您的Django应用程序是空白的。 (作为旁注,这就是Django在上一章中向你展示“欢迎来到Django”页面的方式。如果你的URLconf为空,Django假设你刚开始一个新项目,因此显示该消息。)

要向URLconf添加URL和视图,只需添加URL模式与视图函数之间的映射即可。下面是如何连接我们的Hello视图:

from django.conf.urls.defaults import patterns, include, url

from mysite.views import hello

urlpatterns = patterns(#39;#39;,

url(r#39;^hello/$#39;, hello),

)

(请注意,为了简洁起见,我们已经删除了注释掉的代码。如果你愿意的话,你可以选择把这些行留在里面。)

我们在这里做了两个改动:

  • 首先,我们从其模块中导入了hello视图 - mysite / views.py,它转换为Python导入语法中的mysite.views。 (这假设mysite / views.py在您的Python路径上;有关详细信息,请参阅侧栏。)

接下来,我们在urlpatterns中添加了行url(r#39;^ hello / $#39;,hello)。 此行称为URLpattern。 url()函数告诉Django如何处理你正在配置的url。 第一个参数是模式匹配字符串(正则表达式;稍微更多),第二个参数是用于该模式的视图函数。

我们在这里介绍的另一个重要细节是r正则表达式字符串前面的字符。这告诉Python,字符串是“原始字符串”-它的内容不应该解释反斜杠。在普通Python字符串中,反斜杠用于转义特殊字符,例如字符串中的字符。lsquo;nrsquo;,它是一个包含换行符的单字符串。添加r为了使它成为一个原始字符串,Python不应用它的反斜杠转义-所以,Rlsquo;nrsquo;是一个包含文字反斜杠和小写“n”的双字符串。Python对反斜杠的使用与正则表达式中的反斜杠之间存在着自然的冲突,因此强烈建议您在使用Python定义正则表达式时使用原始字符串。本书中的所有URL模式都是原始字符串。

简而言之,我们只是告诉Django任何对URL的请求/hello/应由hello视图函数

你的Python路径

你的Python路径是Python使用Python时在系统中查找的目录列表。进口声明。

例如,假设您的Python路径设置为[#39;#39;,#39;/ usr / lib / python2.7 / site-package#39;,#39;/ home / username / djcode#39;]。 如果从foo import bar执行Python语句,Python将在当前目录中查找名为foo.py的模块。 (Python路径中的第一个条目,一个空字符串,表示“当前目录。”)如果该文件不存在,Python将查找文件/usr/lib/python2.7/site-packages/foo。PY。 如果该文件不存在,它将尝试/home/username/djcode/foo.py。 最后,如果该文件不存在,则会引发ImportError。

如果您对查看Python路径的值感兴趣,请启动Python交互式解释器并键入以下内容:

gt;gt;gt; import sys

gt;gt;gt; print sys.path

通常,您不必担心设置Python路径-Python和Django在幕后自动为您处理事务。(设置Python路径是Manage.py)

这个URL模式的语法值得讨论,因为它可能并不是立即就显而易见的。虽然我们想要匹配URL/hello/,模式看起来有点不同。原因如下:

  • Django在检查URL模式之前从每个传入URL的前面删除斜杠。这意味着我们的URL模式不包括/hello/。(起初,这似乎是不直观的,但这一要求简化了一些事情-比如将URLconf包含在其他URLconf中)
  • 该模式包括一个插入符(^)和一个美元符号($).这些正则表达式字符具有特殊的含义:插入符号表示“要求模式匹配字符串的开头”,美元符号的意思是“要求模式与字符串的结尾匹配”。

这个概念最好用例子来解释。如果我们用这个模式lsquo;^hello/rsquo;(最后没有美元符号)任何URL以/hello/匹配,例如/Hello/foo和/Hello/bar,而不仅仅是/Hello/。同样,如果我们取消了最初的插入字符(即lsquo;Hello/$rsquo;),Django将匹配任何以Hello/,如/foo/bar/hello/。如果我们只是用你好/,没有插入符号或美元签名,则任何包含以下内容的URLHello/匹配,例如/foo/hello/bar。因此,我们使用插入符号和美元符号来确保只有URL/Hello/没有更多,也没有更少。

大多数URL模式将以插入符号开头,以美元符号结尾,但具有执行更复杂匹配的灵活性是很好的。

您可能在想,如果有人请求URL,会发生什么?/Hello(也就是说,尾随的斜线)因为我们的URL模式需要一个尾随斜杠,所以该URL将不匹配。但是,默认情况下,对URL的任何请求不匹配一个URL模式不以斜杠结尾将被重定向到带有尾随斜杠的同一个URL。(这是由附加斜杠Django设置,见附录D)

如果您是那种喜欢所有URL以斜杠结尾的人(Django的开发人员的首选),那么您所需要做的就是向每个URL模式添加一个尾斜杠,然后离开附加斜杠设为千真万确。如果你喜欢你的网址,若要具有尾斜杠,或如果要根据每个URL来决定,请设置附加斜杠到假的并在你的URL模式中放上你认为合适的斜线。

关于这个URLconf要注意的另一件事是,我们已经通过了Hello将函数视为对象而不调用该函数。这是Python(和其他动态语言)的一个关键特性:函数是一流的对象,这意味着您可以像任何其他变量一样传递它们。很酷的东西,嗯?

要测试对URLconf的更改,请运行命令启动Django开发服务器,就像您在第2章中所做的那样Python Manage.py 运行服务器。(如果你让它运行,那也没关系。开发服务器会自动检测到Python代码的更改,并在必要时重新加载,因此您不必在更改之间重新启动服务器。)服务器正在地址运行。http://127.0.0.1:8000/,所以打开一个Web浏览器,然后转到http://127.0.0.1

资料编号:[5816]

原文和译文剩余内容已隐藏,您需要先支付 30元 才能查看原文和译文全部内容!立即支付

以上是毕业论文外文翻译,课题毕业论文、任务书、文献综述、开题报告、程序设计、图纸设计等资料可联系客服协助查找。