Django:视图和URL配置

一、视图
     1.在mysite文件夹下,创建views.py文件(文件名没有特别的要求);
from django.http import HttpResponse
     def hello(request):
          return HttpResponse("Hello world")
     2.修改mysite文件夹下的urls.py文件;    
from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
]
     3.运行命令:python manage.py runserver。在浏览器访问http://127.0.0.1:8000/hello/;
     4.你的URL申请在URLconf中没有定义,“404错误”页面就会显示,它精确的告诉你Django调用在哪个URLconf及其包含的每个模式,该页面只会在调试模式(debug mode)下显示;
     
     5.使用URL模式”^$“匹配网站根目录URL模式;
二、Django是如何处理请求
     1.当你运行python manage.py runserver,在manage.py同一个目录下查找名为setting.py的文件,该文件包含了关于所有Django项目的配置信息;
          ROOT_URLCONF='mysite.urls'#指向自动生产的urls.py
     2.浏览器里敲http://127.0.0.1:8000/hello访问时候,根据ROOT_URLCONF的设置装载URLconf,然后按顺序逐个匹配URLConf里面的URLpatterns,直到找到一个匹配的;
     3.当找到这个匹配的URLpatterns就调用相关联的view函数,并把HttpRequest对象作为第一个参数;
     4.Django转换成HttpResponse为一个适合的HTTP reponse,以Web page显示出来;
三、动态内容
     1.在项目views.py中添加,如下视图:
from django.http import HttpResponse
import datetime

    def hello(request):
        return HttpResponse("Hello world")

    def current_datetime(request):
        now = datetime.datetime.now()
        html = "It is now %s." % now
        return HttpResponse(html)
     2.在项目urls.py中添加,如下配置:
from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello , current_datetime

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
    url(r'^time/$', current_datetime),
]
     3.重新启动服务,访问http://127.0.0.1:8000/time
     
     4.松耦合原则,URL的定义和视图函数之间的松耦合;
四、动态URL
 1.在项目views.py中添加,如下视图:
from django.http import HttpResponse , Http404
import datetime
... ... 
def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "In %s hours(s), it will be %s." % (offset, dt)
    return HttpResponse(html)
     2.在项目urls.py中添加,如下配置:
from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello , current_datetime , hours_ahead

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    ... ... 
    url(r'^time/plus/(\d{1,2})/$', hours_ahead),
]
     3.重新启动服务,访问http://127.0.0.1:8000/time/1
      

你可能感兴趣的:(Django)