案例学Python--案例四:Django实现一个网站的雏形(2)

 

续上篇,用Django创建了一个Web,我们肯定想展示自己的页面,简单点,我们想看到自己的HelloWorld。此处要从项目的配置说起,方法和路径配对了,展现页面分分钟的事情。

 

先上效果图吧:

 

   

 

项目结构:

实现:

首先我们在App同级目录建文件夹templates存放我们的html页面,index.html 简单写写东西,如下:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello world
{{ hello }}
</body>
</html>

{{hello}} 之所以加大括号是方便我们动态生成页面,用过不同类的渲染引擎,大相径庭。

 

html写好了,我们要写配置文件了,让程序在启动后能跳转到templates下的这些页面,这个可以在setings.py里更改;

setings.py  中TEMPLATES更改如下

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/templates",],      #更改处,寻址templates文件夹
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

然后就是写方法响应http请求了,类似于java中的Controller 说白了就是一些接口。不过Python接口长这样,可能目前比较白,理解偏差比较大。

from django.contrib import admin
from django.urls import path
from movieApp import views   #导入我们自己的views.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('hello', views.hello, name='welcome')    #此行为增加的
]

 

看到此,深深折服Python代码的简短啊,Python也有强大的各种封装包,大道至简的感觉。简单分析一下这段代码:

urlpatterns = [
   # path('正则表达式', 函数,参数,别名) 
    path('hello', views.hello, name='welcome')   
]
  • 一个正则表达式字符串
  • 一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串
  • 一个可选的要传递给视图函数的默认参数(字典形式)
  • 一个可选的name参数

 

然后我们看一下views.py里写了些什么东东:

from django.shortcuts import render
from django.shortcuts import HttpResponse  #此行增加
# Create your views here.
def hello(request):                   #此函数增加
    return render(request,'index.html',{'hello':'hello 慢城'})

def index(request):                   #此函数增加
    return HttpResponse('welcome play my games')

依然短的有点不适应,但是的确好用,这就是Python吧。

这些都改完后,执行命令行:

python manage.py runserver

 

打开浏览器输入:

http://localhost:8000/

http://localhost:8000/hello

http://localhost:8000/admin

测试一下,完全OK。http://localhost:8000/admin跳转的是登录界面,这个应该是Django封装自带的,有时间再研究。在案例学Python--案例四:Django实现一个网站的雏形(3)中我们就会引入数据库配置,我想应该也会写点js啥的吧,页面不能太丑吧。

 

posted @ 2018-11-21 14:38  斑马森林  阅读(511)  评论(0编辑  收藏  举报