django中“url映射规则”和“服务端响应顺序”

1、django搜索路径

  使用 import 语句时,Python 所查找的系统目录清单。
      查看方式:
          import sys
          print sys.path
      通常无需关心 Python 搜索路径的设置,Python 和 Django 会在后台自动帮你处理好。

2、url匹配模式

   基本结构:
        '^需要匹配的url字符串$'
     PS:实际上最终完整的url串是http://根路径:端口号/需要匹配的url字符串
     系统自动添加的部分'http://根路径:端口号/'
    eg:url匹配模式:'^latest_books/$'
           最终完整的url字符串:'http://127.0.0.1:8000/latest_books/'
    1)^:匹配“子串头”。

    eg:

 '^latest_books/'
 'http://127.0.0.1:8000/latest_books/''http://127.0.0.1:8000/latest_books/test1/',
 'http://127.0.0.1:8000/latest_books/test2/',
 'http://127.0.0.1:8000/latest_books/test1/aaa/'

       都会被匹配上。    
    2)$:匹配“子串结尾”。
        eg:

  'latest_books/$'
   'http://127.0.0.1:8000/latest_books/''http://127.0.0.1:8000/updir_1/latest_books/''http://127.0.0.1:8000/updir_2/latest_books/'

        都会被匹配上。
    3)子串末尾是否包含'/'
        默认情况下必须添加(django开发者的基本习惯),如果不添加将会出现如下情况:

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

urlpatterns = patterns('',
(r'^latest_books$', 'django_web_app.views.latest_books'),
)

   
        如果子串末尾不想包含'/',可在setting.py中添加设置:APPEND_SLASH=False
        但是必须安装了CommonMiddleware才会起作用。

  4)手动配置网站“根目录”

    在不手动配置网站“根目录”对应“视图函数”的情况下,会出现如下情况:

    

    手动配置“根目录”对应“视图函数”:

    a)urls.py

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

urlpatterns = patterns('',
                       (r'^$','django_web_app.views.home_page'),
                       (r'^latest_books/$', 'django_web_app.views.latest_books'),
)

    b)views.py

def home_page(request):
    return render_to_response('home_page.html')

    c)home_page.html

<!DOCTYPE html>
<html>
<head>
    <title>my home page</title>
</head>
<body>
    <h1>This is home page, welcome !</h1>
</body>
</html>

    运行结果:

    

  附:正则表达式基础

  

3、服务端响应url请求的执行顺序

   1)项目结构

  

  django_web

        __init__.py

        settings.py

        urls.py

        wsgi.py

  django_web_app

        __init__.py

        admin.py

        models.py

        tests.py

        views.py

  templates

        home_page.html

        latest_books.html

  manage.py

  2)执行顺序

     a)启动服务端——python manage.py runserver

     获取setting.py文件中的配置,主要包括:

     url映射关系文件路径

ROOT_URLCONF = 'django_web.urls'

       页面文件模板路径:

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

      数据库配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'USER': 'root',
        'PASSWORD': 'feng',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

     b)响应顺序

       第一步:浏览器提交请求

           http://127.0.0.1:8000/latest_books/

       第二步:服务端根据请求的url在urls.py中进行匹配,并找到对应的“视图函数”

       第三步:调用对应的“视图函数”

           返回一个HttpResponse对象

       第四步:django转换HttpResponse对象为一个适合的HTTP response,并返回给页面进行显示

 

 

 

posted @ 2014-05-27 14:57  edisonfeng  阅读(7180)  评论(0编辑  收藏  举报