文件目录结构
创建项目
django-admin startproject myweb
创建应用
python manage.py startapp myapp
修改myweb代码
myweb --> url.py
这里用myapp的urls.py 所以myweb urls.py需要 from django.urls import include
"""myweb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
#path('admin/', admin.site.urls),
path('', include("myapp.urls")),
]
myweb --> settings.py
"""
Django settings for myweb project.
Generated by 'django-admin startproject' using Django 2.2.24.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*^m)_4z9q$m!it7*=wm$%^snry%p!pc^^!fg5ho=496manc-ff'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myweb.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'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',
],
},
},
]
WSGI_APPLICATION = 'myweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
修改myapp代码
myapp --> urls.py(自行创建)
from django.urls import path
from . import views
from myapp.views import MyView
urlpatterns = [
path('', views.index, name="index"), # 首页
path('resp01', views.resp01, name="resp01"), # 首页 # 一个简单的视图
path('resp02', views.resp02, name="resp02"), # 返回一个错误
path('resp03', views.resp03, name="resp03"), # 重定向
path('resp04', MyView.as_view(), name="resp04"), # 基本类的视图
path('resp05', views.resp05, name="resp05"), # 响应json数据
path('resp06', views.resp06, name="resp06"), # Cookie的使用
path('resp07', views.resp07, name="resp07"), # 测试request请求对象
path('resp08', views.verifycode, name="resp08"), # 测试验证码
]
myapp --> views.py
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseNotFound,Http404,JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.views import View
# Create your views here.
def index(request):
return render(request, "myapp/index.html")
def resp01(request):
return HttpResponse("<h3>一个简单的视图</h3>")
def resp02(request):
# 直接返回一个404,没有去加载404的模板页面
return HttpResponseNotFound("<h3>404</h3>")
# 可以直接返回一个status状态码
#return HttpResponse(status=403)
# 返回一个404的错误页面
#raise Http404("Poll does not exist")
# 重定向
def resp03(request):
# redirect重定向 reverse方向解析url地址
#return redirect(reverse('resp01'))
# 执行一段js代码,用js进行重定向
return HttpResponse('<script>alert("跳转成功");location.href = "/resp01";</script>')
# 加载一个提醒信息的跳转页面
# context = {'info':'数据添加成功','u':'/resp01'}
# return render(request, 'info.html',context)
# 视图类的定义
class MyView(View):
def get(self, request, *args, **kwargs):
return HttpResponse('hello, Views!')
# json 数据的响应
def resp05(request):
data = [
{'id':1001,'name':'zhangshan','age':20},
{'id':1002,'name':'lisi','age':22},
{'id': 1003,'name':'xiaoshan','age': 22},
]
return JsonResponse({"data":data})
# cookie的使用
def resp06(request):
# 读取
m = request.COOKIES.get('num',None)
if m:
m = int(m) + 1
else:
m = 1
# 获取当前的响应对象
response = HttpResponse('cookie记录的计数器值:'+str(m))
# print(request.COOKIES.get('a',None))
# 使用响应对象进行cookie的设置
response.set_cookie('num',m)
# 返回响应对象
return response
# 测试request对象
def resp07(request):
print("请求路径",request.path)
print("请求方法",request.method)
print("请求编号",request.encoding)
#print(request.GET)
print(request.GET['id'])
print(request.GET.get('name'))
print(request.GET.get('age',0))
return HttpResponse("测试request请求对象")
# 验证码的输出
def verifycode(request):
# 引入绘图模块
from PIL import Image, ImageDraw, ImageFont
# 引入随机函数模块
import random
# 定义变量,用于画面的背景色,宽,高
bgcolor = (random.randrange(20, 100),random.randrange(20, 100), 255)
width = 100
height = 25
# 创建画面对象
im = Image.new('RGB', (width, height),bgcolor)
# 创建画面对象
draw = ImageDraw.Draw(im)
# 调用画笔的point()函数绘制躁点
for i in range(0, 100):
xy = (random.randrange(0, width), random.randrange(0, height))
fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
draw.point(xy, fill=fill)
# 定义验证码的备选值
str1 ='ABCD123EFGHIJK456LMNOPQRS789TUVWXYZO'
# 随机选取4个值作为验证码
rand_str = ''
for i in range(0, 4):
rand_str += str1[random.randrange(0, len(str1))]
# 构造字体对象
font = ImageFont.truetype('static/ariali.ttf', 23)
#font = ImageFont.load_default().font # 默认使用系统字体
# 构造字体颜色
fontcolor = (255, random.randrange(0,255), random.randrange(0,255))
# 绘制4个字
draw.text((5,2), rand_str[0], font=font, fill=fontcolor)
draw.text((25,2), rand_str[1], font=font, fill=fontcolor)
draw.text((50,2), rand_str[2], font=font, fill=fontcolor)
draw.text((75,2), rand_str[3], font=font, fill=fontcolor)
# 释放画笔
del draw
# 存入session,用于做进一步验证
#request.session['verifycode'] = rand_str
# 内存文件操作
"""
python2的为
# 内存文件操作
import cStringIO
buf = cStringIO.StringIO()
"""
# 内存文件操作-->此方法为pyhton3
import io
buf = io.BytesIO()
# 将图片保存在内存中,文件类型为png
im.save(buf, 'png')
# 将内存中的图片数据返回给客户端,MIME类型为图片png
return HttpResponse(buf.getvalue(), 'image/png')
创建static 目录,字体获取可以从window font文件夹下获取
创建 templates--> myapp--> index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django的视图层</title>
</head>
<body>
<h2>Django的视图层</h2>
<ul>
<li><a href="{% url 'resp01' %}">1.一个简单的视图</a> </li>
<li><a href="{% url 'resp02' %}">2.返回404</a> </li>
<li><a href="{% url 'resp03' %}">3.重定向</a> </li>
<li><a href="{% url 'resp04' %}">4.基于类的操作</a> </li>
<li><a href="{% url 'resp05' %}">5.响应json格式</a> </li>
<li><a href="{% url 'resp06' %}">6.Cookies的使用</a> </li>
<li><a href="{% url 'resp07' %}?id=100&name=zhangsan&age=22">7.request请求</a> </li>
<li><a href="{% url 'resp08' %}">8.验证码的输出</a> </li>
</ul>
<img id='verifycode' src="{% url 'resp08' %}" alt="CheckCode" />
</body>
</html>