django学习手记(七)-----图像

原创
小哥 3年前 (2022-11-16) 阅读数 10 #大杂烩

视图

1.概念(views.py中)

1,角色:查看接受。web请求并响应web请求
2本质:视图是python中的函数
3,响应的内容:
(1)网页

  • 重定向
  • 错误视图----404,500,400

(2)JSON数据

4,响应过程

二、url配置

1,配置过程

(1)指定根级别(根的级别)url配置文件

通常无需修改,默认实现
project/settings.py文件中的 ROOT_URLCONF = project.urls

(2)urlpatterns----firstapp/urls.py文件

  • 一个url实例列表
  • path对象

(3)urls.py文件

一般来说URL,我们写道:

urlpatterns = [
path(正则表达式, views查看函数、参数、别名),
]

参数说明:

(1),正则表达式字符串
(2),一个可调用的对象,通常是视图函数或指定视图函数路径的字符串。
(3),传递给视图函数的可选默认参数(字典形式)
(4),可选name参数(别名)

  • 要从URL捕获值,使用尖括号。
  • 捕获的值可以选择性地包括转换器类型。例如,使用 <int:name> 捕获整数参数。如果不包括转换器,匹配将被分割。a/字符以外的任何字符串。 path(grades/<int:num>,views.gradesStudents),
  • 不需要添加前导斜杠,因为每个URL都有前导斜线。例如,它是一篇文章,而不是/文章因为在project/urls.py文件已添加。 path(firstapp/, include(firstapp.urls)), "firstapp/"添加了斜线,所以在中。firstapp/urls.py在中,路径前面没有斜杠,而是输入URL http://localhost:8000/firstapp/ 开头

例如:

2,介绍其他url配置

不同项目之间的管理很方便。

  • 在应用程序中创建urls.py文件,定义应用程序的url配置,整个项目中可以有多个项目,例如secondapp,thirdapp,fourthapp,等等。
  • 每次引入项目时project/urls.py它包含自己的,然后在自己的项目中url.py文件,匹配自己的url配置
  • project/urls.py只有一个
  • 可以有多个项目firatapp/urls.py,secondapp/urls.py,thirdapp/urls.py,fourthapp/urls.py

比如:
在project\urls.py文件中path后面添加

path(firstapp/, include(firstapp.urls)),#自定义
#可以是path(secondapp/, include(secondapp.urls)),等等


以下是您在项目中需要的虚拟路径。

3、URL反向分辨率

(1)概述:如果在视图和模板中使用硬编码链接url当配置更改时,将动态生成链接的地址。
(2)解决方案:使用链接时,传递url动态生成的配置的名称。url地址
(3)角色:使用url模板

3.查看功能

1,定义视图

  • 本质:功能
  • 视图参数:第一个参数request,一个HttpRequest的实例 ; 第二个参数,正则表达式获得的参数
  • 位置----一般在views.py文件下的定义

2,错误视图

  • 500视图----视图代码(服务器代码)中出错
  • 400视图----客户操作中出现错误
  • 404视图----找不到该网页(url匹配失败时返回)。
    (1)可以自己定义,在templates目录定义404.html----request_path----导致错误的URL。

    <!DOCTYPE html>

    404页面

    页面丢失

    {{request_path}}

(2)配置settings.py

  • DEBUG = True (调试)如果True,从不打电话404.html页面
  • ALLOWED_HOSTS = [] #默认是[],根据需要定制
  • ALLOWED_HOSTS = [*] #任何人都可以访问

四、HttpRequest对象

下面的request,可以写成其他东西(req),不影响

def index(request):
    #return HttpResponse("Hello, world. Youre at the polls index.")

1、概述

  • 服务器接收http在请求之后HttpRequest对象
  • 视图的第一个参数是HttpRequest对象
  • django创建,然后在调用视图时,将其传递给视图。

2、HttpRequest对象 属性

(1)path----请求的完整路径(不包括域名和端口)
(2)method----表示请求的方式,常用。GET,POST
(3)encoding----指示浏览器提交的数据通常是如何编码的。utf-8
(4)GET(大写)----包含get请求的所有参数
(5)POST(大写)----包含post请求的所有参数
(6)FILES(资本)(files)----包含所有上传的文件
(7)COOKIES(大写)(cookies)----字典,包含所有cookie
(8)session----表示当前会话的类似字典的对象。

(4),(5),(6),(7)大写是属性,小写不是

3、方法

is_ajax()
如果XMLHttpResquest启动,返回True

4、QueryDict对象

(1)request对象中的get,post都属于QueryDict对象
(2方法:(小写)

  • get()
    功能:根据密钥只能获得一个值,
    www.sunck.wang/abc?a=1&b=2&c=3
  • getlist()
    以列表形式返回键的值,您可以获得多个值。
    www.sunck.wang/abc?a=1&a=2&c=3,有两个a

5、GET属性

目的:获取浏览器传递给服务器的数据。
http://localhost:8000/firstapp/get1?a=1&b=2&c=3

1、(1)在firstapp/views.py文件,添加以下代码。

GET 是HttpRequest对象的属性,
get() 是QueryDict对象的方法。,根据获取值的键,只能获取一个值。

#获取get传递的数据
def get1(request):
    a=request.GET.get(a)#GET是HttpRequest对象的属性,get()是QueryDict对象的方法。
    b=request.GET.get(b)
    c=request.GET.get(c)
    return HttpResponse(a+" "+b+" "+c)

(2)在firstapp/urls.py文件,添加路径

path(get1/,views.get1),

(3)输入URL http://localhost:8000/firstapp/get1?a=1&b=2&c=3 得到下图

http://localhost:8000/firstapp/get2?a=1&a=2&c=3

2、(1)在在firstapp/views.py文件,添加以下代码。

GET 是HttpRequest对象的属性,
getlist() 是QueryDict对象的方法。,根据密钥获取值,可以获取多个值

def get2(request):
    a=request.GET.getlist(a)
    a1=a[0]
    a2=a[1]
    c=request.GET.get(c)
    return HttpResponse(a1+" "+a2+" "+c)

(2)在firstapp/urls.py文件,添加路径

path(get2/,views.get2),

(3)输入URL http://localhost:8000/firstapp/get2?a=1&a=2&c=3 得到下图

6、POST属性

1,使用表单提交来实现POST请求

(1)、在templates/firstapp在文件下,添加register.html文件(注册),
,,,,name=“gender”,标签name传递的键值为gender,另一个相同

#register.html



    
    注册
    
    
    
          
	      
	


    
姓名:
性别:

年龄:
爱好:权力金钱帅哥美女

(2)、在firstapp/views.py在内部添加以下代码

#POST
def showregister(request):
    return render(request,firstapp/register.html)

def register(request):
    return HttpResponse(********akakak)

(3)、在firstapp/urls.py在内部添加路径

path(showregister/,views.showregister),
path(showregister/register/,views.register),

(4),输入URL http://localhost:8000/firstapp/showregister/ ,得到下图

(5),输入URL localhost:8000/firstapp/showregister/register/ ,得到下图,返回的东西,在第2步,中在firstapp/views.py在内部定义register函数返回值 ********akakak

2,发生错误403,关闭csrf,没有错误,直接跳过,看3

在project/settings.py里面的这行被注释掉了。

3、

在firstapp/views.py里面修改register()函数

def showregister(request):
    return render(request,firstapp/register.html)
def register(request):
    name=request.POST.get(name)
    gender=request.POST.get(gender)
    age=request.POST.get(age)
    hobby=request.POST.getlist(hobby)#复选框,getlist
    print(name)
    print(gender)
    print(age)
    print(hobby)
    return HttpResponse(post)

五、HttpResponse对象

1、概述

  • 角色:将数据返回到浏览器。
  • HttpRequest对象由django创建的,HttpResponse对象由程序员创建。

2,返回数据使用情况

(1) 不调用模板,直接返回数据

def register(request):
    return HttpResponse(********akakak)

(2) 调用模板----使用render方法

  • 原型---->render(request,templateName[,context])
  • 作用---->结合数据和模板,返回完整的HTML页面
  • 参数
    1)request 请求正文对象
    2)templateName 模板路径
    3)context 传递给需要在模板上呈现的数据
  • 示例

    def showregister(request): return render(request,firstapp/register.html)

3、属性

  • content 指示返回的内容
  • chartset 编码格式
  • atatus_code 响应状态代码----200,304,404
  • content-type 指定输出MIME类型

    在firstapp/views.py里面

    response

    def showresponse(request): res=HttpResponse() res.content=bgood print(res.content) print(res.charset) print(res.status_code) return res

    在firstapp/urls.py里面

    path(showresponse/,views.showresponse),

4、方法

  • int 使用页面的内容实例化。HttpResponse对象
  • write(content) 作为文件写入
  • filsh() 将缓冲区输出为文件
  • set_cookie(key,value=’’,maxAge=None,exprise=None)
  • delete_cookie(key) 删除cookie如果要删除不存在的key,只是想什么都没发生

    cookie,在firstapp/views.py

    def cookietest(request): res=HttpResponse() cookie=res.set_cookie("sunck","good") return res

    在firstapp/urls.py里面

    path(cookietest/,views.cookietest),

输入网址 http://localhost:8000/firstapp/cookietest/


5、子类TttpResponseRedirect

TttpResponseRedirect是HttpResponse对象的子类

  • 功能: 重定向 ,服务器端的跳转,访问一个视图并执行另一个视图
    from django.http import HttpResponseRedirect
    return HttpResponseRedirect(/firstapp/redirect2)
  • 简写:redirect(to)
    from django.shortcuts import redirect
    return redirect(/firstapp/redirect2)
  • 上面的to建议反向解析。

(1)重定向

#重定向,在firstapp/views.py
from django.http import HttpResponseRedirect
def redirect1(request):
    return HttpResponseRedirect(/firstapp/redirect2)#请注意,这是/firstapp/redirect2,前面的/firstapp进入project/urls.py------>path(firstapp/, include(firstapp.urls)),----然后/redirect2进入到firstapp/urls.py
    #firstapp前面没有/,将直接跳转/redirect2,出错
def redirect2(request):
    return HttpResponse("我是重定向视图")

在firstapp/urls.py里面

path(redirect1/,views.redirect1),
path(redirect2/,views.redirect2),

输入网址 http://localhost:8000/firstapp/redirect1/ 将自动跳转 http://localhost:8000/firstapp/redirect2/ ,如下图

如果上述情况firstapp/views.py在里面,路径是/redirect2

def redirect1(request):
    return HttpResponseRedirect(/redirect2)

输入网址 http://localhost:8000/firstapp/redirect1/ 将自动跳转 http://localhost:8000/redirect2/ ,然后出错

(2)速记重定向

#重定向,在firstapp/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
def redirect1(request):
    return redirect(/firstapp/redirect2)
def redirect2(request):
    return HttpResponse("我是重定向视图")

6、子类JsonResponse

JsonResponse是HttpResponse对象的子类

  • 返回json数据,通常用于异步请求
  • __init__(self,data)
    from django.http import HttpResponseRedirect,JsonResponse
  • data:字典
  • 注意:Content-type类型为application/json

6.状态保持

1、概述

  • http协议是无状态的。每个请求都是一个新请求。我不记得以前的要求了。
  • 客户端和服务器之间的通信是会话。
  • 在客户端维护实现状态(cookie或者服务器存储有关会话的数据。
  • 如何存储
    cookie---->所有数据都存在于客户端中,不存储敏感数据、不安全的少量数据
    session---->所有数据都存储在服务器端,并在客户端使用。cookie存储session_id
  • 状态保留的目的是:在一段时间内跟踪请求者的状态,从而能够跨页面访问当前请求者的数据。
  • 注意:此数据不会在不同的请求者之间共享,而是与请求者一对一共享。

2、启用session

在settings.py文件中,通常,它是启用的。别担心。它未启用。它需要启用。
(1)INSTALLED_APPS---- django.contrib.sessions,
(2)MIDDLEWARE---- django.contrib.sessions.middleware.SessionMiddleware,

3、使用session

  • 启用session后,每个HttpRequest对象有一个session属性----是一个类似字典的对象。
  • request.session.get(key,default=None)----根据密钥获取session值,找不到返回以下内容的密钥default默认值
  • request.session.clear()----清空所有会话
  • request.session.flush()----删除当前会话并删除会话的cookie

(1)未登录---->登录---->返回我的界面

未登录,在templates/firstapp/main.py(我的)

#第9行,路径是单击登录后要传输的路径,href="/firstapp/login"



    
    我的
    
    
    
          
	      
	


    

欢迎:游客

登录

登录,在templates/firstapp/login.py

#第8行,路径是单击登录后要传输的路径,action="/firstapp/showmain/



    
    登录
    
    
    
          
	      
	


    

在firstapp/views.py里面

#session
from django.shortcuts import redirect
def main(request):
    return render(request,firstapp/main.html)
def login(request):
    return render(request,firstapp/login.html)
def showmain(request):
    #重定向到main函数
    return redirect(/firstapp/main)

在firstapp/urls.py里面

path(main/,views.main),
path(login/,views.login),
path(showmain/,views.showmain),

输入网址 http://localhost:8000/firstapp/main/
点击登录

然后单击登录

(2)在templates/firstapp/login.py




    
    我的
    
    
    
          
	      
	


    

欢迎:{{username}}

登录 退出登录

在firstapp/views.py里面

#session
def main(request):
    #取下session
    username=request.session.get(name,"游客")
    print(username)
    return render(request,firstapp/main.html,{username:username})   
def login(request):
    return render(request,firstapp/login.html)
def showmain(request):    
    username =request.POST.get("username")   
    #存储session
    request.session[name]=username
    request.session.set_expiry(10)#10秒后过期
    #request.session.clear()
    return redirect(/firstapp/main)
from django.contrib.auth import logout
def quit(request):
    #清除session
    logout(request)
    #request.session.clear()
    #request.session.flush()
    return redirect(/firstapp/main)

在firstapp/urls.py里面

path(main/,views.main),
path(login/,views.login),
path(showmain/,views.showmain),
path(quit/,views.quit),

4,设置过期时间

  • request.session.set_expiry(value)
  • 如果您不将其设置为两周后到期
  • 整数----request.session.set_expiry(10)#10秒后过期
  • 时间对象
  • 0----无法关闭浏览器
  • None----永不过期

5、存储session的位置

  • 数据库----默认缓存在数据库中。

  • 缓存----仅存储在本地内存中,如果丢失则无法检索,速度比数据库快。
    SESSION_ENGINE=django.contrib.session.backends.cache

  • 数据库和缓存----优先访问本地缓存,而不是从数据库读取。
    SESSION_ENGINE=django.contrib.session.backends.cached_db

6、使用redis缓存session

在D:\program\python3\python(2)目录输入。pip install django-redis-sessions安装,以下是成功安装
安装在C:\Users\DELL\AppData\Local\Programs\Python\Python37\Lib\site-packages

project/settings.py

SESSION_ENGINE=redis_sessions.session
SESSION_REDIS_HOST=localhost
SESSION_REDIS_PORT=3306
SESSION_REDIS_DB=0
SESSION_REDIS_PASSWORD=123456
SESSION_REDIS_PREFIX=session
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除