您的位置:首页 > 编程语言 > Go语言

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

2015-11-02 23:02 645 查看
注:以下内容转载自 现代魔法学院 网站的 Django urls.py的了解与基本配置 一文,仅供学习使用。

在 Django 框架中,urls.py 的设置很关键,它决定了所有页面的 URL 长什么样子。所以很有必要我们开一个专题来探讨它的使用。

我们先来粗略看看 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('',
# 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 函数下,那么又怎么写呢?

(r'^$', index),


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

顺便说下,在 view 函数里,return HttpResponseRedirect('../'):返回主页,即127.0.0.1。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: