python Django views

目录结构
在这里插入图片描述
views.py

from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world ! ")

urls.py

from django.conf.urls import url
from csdn import views
urlpatterns = [
url(r'^hello$', views.hello),
]

运行结果
在这里插入图片描述

ps:自定义的视图等级

from django.http import HttpResponse
from django.template import Template, Context
from django.template.loader import get_template
from django.shortcuts import render
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)

# 黄金
def current_datetime(request):
now = datetime.datetime.now()
t = Template("It is now {{ current_date }}.")
html = t.render(Context({'current_date': now}))
return HttpResponse(html)

# 铂金
# 打开HTML文件
def current_datetime(request):
now = datetime.datetime.now()
with open(r'templates/mytemplate.html', encoding='utf-8') as fp:
t = Template(fp.read())
html = t.render(Context({'current_date': now}))
return HttpResponse(html)

# 钻石
# 动态打开模板文件
def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)

# 星耀
# 数据自动注入
def current_datetime(request):
now = datetime.datetime.now()
return render(request,'current_datetime.html', {'current_date': now})

# 王者
# 简单到丧心病狂的数据注入
def current_datetime(request):
current_date = datetime.datetime.now()
return render(request,'current_datetime.html', locals())


作者:魏振东

相关推荐

图片

nginx常用命令【linux版】

python之装饰器,多重装饰器,多层函数装饰器

python内置函数简单应用示例

Django2.0打包生成exe,在win10或7环境开机自启动