第二章 视图和URL配置

一、第一个视图:hello world

     创建视图views.py

from django.http import HttpResponse

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

    代码说明:

    1、从django.http中导入HttpResponse类

    2、创建一个视图函数hello,至少包含一个参数,这是一个对象,包含触发这个视图的web请求信息,是django.http.Request的实例

    3、返回一个django.http.Response的实例。

   urls.py默认代码说明:

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

     1、从django.contrib导入admin函数,加载django后台管理的url

     2、从django.urls 导入path函数,用于匹配浏览器中的URL,把它映射到django项目的某个模块,(也可以导入re_path函数,用于匹配浏览器中的URL正则表达式;也可以导入include,用于导入另一个urls配置)

     3、urlpatterns,即path()实例列表,

 以下是修改后的urls.py文件

from django.contrib import admin
from django.urls import path,re_path
from mysite.views import hello

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^hello/$',hello),
]

代码说明:1、导入views.py中的hello函数

                  2、urlpatterns中增加re_path(r'^hello/$',hello),  -----------匹配以hello开头结尾的浏览器webURL,并将该URL映射到hello视图。

二、正则表达式

符号 匹配内容
.(点号) 单个字符
d 单个数字
[A-Z] A-Z(大写)之间单个字母
[a-z] a-z(小写)之间单个字母
[A-Za-z] 匹配所有单个字母,不区分大小写
+ 一个或多个前述表达式
[^/]+ 一个或多个字符,直到遇到斜线(不含)
? 0个或一个前述表达式
* 0个或多个前述表达式
{1,3} 介于一个或三个(含)前述表达式

三、django处理请求过程

1、请求/hello/

2、django查看ROOT_URLCONF设置,找到根URL配置

3、django比较URL配置中各个URL模式,找到匹配/hello/的那个URL模式

4、如果找到匹配URL模式,调用对应的视图函数

5、视图函数返回一个HttpResponse对象

6、django将返回的HttpResponse对象转化为HTTP响应,得到对应的网页

settings.py中的ROOT_URLCONF设置:

ROOT_URL_CONF = 'mysite.urls'   --------------设置根URL为mysite下的urls.py

四、动态视图

from django.http import HttpResponse
import datetime

def current_time(request):
    now = datetime.datetime.now()
    html = "It is now %s." %now
    return HttpResponse(html)
views.py
1 from django.contrib import admin
2 from django.urls import path,re_path
3 from mysite.views import hello,current_time
4 
5 urlpatterns = [
6     path('admin/', admin.site.urls),
7     re_path(r'^hello/$',hello),
8     re_path(r'^time/$',current_time()),
9 ]
urls.py

五、动态URL

urls.py:

from django.contrib import admin
from django.urls import path,re_path
from mysite.views import hello,current_time,hours_ahead

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^hello/$',hello),
    re_path(r'^time/$',current_time),
    re_path(r'^time/plus/(d{1,2})/$',hours_ahead),   #动态URL配置,括号括起来的匹配内容将作为参数传给视图函数,例如/time/plus/20/
]

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 hour(s), it willl be %s.' %(offset,dt)
    return HttpResponse(html)
原文地址:https://www.cnblogs.com/wenwu5832/p/11871272.html