[urls.py设置技巧]Django urls.py的了解与基本配置

        注:如下内容转载自 现代魔法学院 网站的 Django urls.py的了解与基本配置 一文,仅供学习使用。python

        在 Django 框架中,urls.py 的设置很关键,它决定了全部页面的 URL 长什么样子。因此颇有必要咱们开一个专题来探讨它的使用。正则表达式

        咱们先来粗略看看 urls.py 的样子,虽然前面也有介绍,咱们这里算是复习一下吧:django

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('',
    # Examples:
    # url(r'^$', 'nowamagic.views.home', name='home'),
    # url(r'^nowamagic/', include('nowamagic.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

        前面也谈过,只要配置这么一条规则:框架

(r'^hello/$', hello),

        就能够定义 http://127.0.0.1:8000/hello/ 路径显示 views.py 中的 hello 函数。函数

        模式包含了一个尖号(^)和一个美圆符号($)。这些都是正则表达式符号,而且有特定的含义:上箭头要求表达式对字符串的头部进行匹配,美圆符号则要求表达式对字符串的尾部进行匹配。^hello/$ 匹配 hello/ 字符串,即在网址 http://127.0.0.1:8000/hello/ 找到 hello/ 后,使用 hello() 函数显示出来,若是没有'$'结尾,则网址中输入 hello1/;hello2/ 都会对应以 hello() 函数显示出来。学习

        hello 函数咱们随便写写:网站

from django.http import HttpResponse,Http404

def hello(request): 	#每一个视图函数至少要有一个参数,一般被叫做request。 
    return HttpResponse("Hello NowaMagic!")	#一个视图功能必须返回一个HttpResponse

        那么我须要显示首页,就是域名直接映射到某个 view 函数下,那么又怎么写呢?url

(r'^$', index),

        index 函数就是生成首页的 view 函数。spa

        顺便说下,在 view 函数里,return HttpResponseRedirect('../'):返回主页,即127.0.0.1。
.net