django框架(5)

十四、请求与响应

Django框架是一个web应用框架

请求和响应的流程:

输入网址,请求页面(GET请求),通过路径找到对应的视图函数。

django创建的HttpRequest对象,该对象包含关于请求的源数据

经过处理,视图return一个HttpResponse对象

查找 :先找根目录的url配置,然后一层一层往下找。

1.get

debug模式,先关闭原来的crm,然后打断点,然后点小虫子。运行到断点就暂停。

1.并且运行调试工具的时候,必须使用的是恢复程序执行,不能一次一次点,不然会特别麻烦。

 action="{% url 'teacher:form' %}" 
 2.对于这个代码,teacher后面的网页必须经过命名才可以使用。不然会报错哟

3.在网页上赋值的时候,使用http://127.0.0.1:8000/teacher/form/?username=summer&password=123&hoppy=basketball&hoppy=football

4.此时在获取参数时如果使用request.GET.get(‘hoppy’)将得到最后一个值。如果要多个赋值,那需要使用getlist

2.post

get在请求一个网页的时候是可以看到网页后面的参数的,但是使用post却可以让别人看不到。

注:

因为django自带一个安全措施csrf所以当你需要请求网页时,回进行报错。因此需要在的下面加上{% csrf_token %}。在页面上他会自己生产一些东西。

简单的登录代码。

def form(request):
    # return render(request, 'teacher/form.html')
    if request.method == 'GET':
        return render(request, 'teacher/form.html')
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'summer' and password == '123':
            return redirect('teacher:login')
        else:
            return render(request,'teacher/form.html')

优化:

if request.method == 'POST':
    username = request.POST.get('username')
    password = request.POST.get('password')
    if username == 'summer' and password == '123':
        return redirect('teacher:login')
    else:
        return render(request,'teacher/form.html')
return render(request, 'teacher/form.html')

总结:

  • get从服务器获取数据,不回去更改服务器的数据。
  • post:携带数据发送给服务器,一般会更爱服务器的数据。
  • get在url中携带参数发送给数据库。post不会在url中看到参数。

1.文件上传存储路径的设置

因为文件信息不同于get和post所以在debug的时候,需要有单独的请求代码。request.FILES.get(‘file’)

1.创建:一般放在ststic文件夹下。在项目根目录下static文件夹中创建media文件夹。

2.配置:在setting文件下的最后一行创建一行命令:MEDIA_ROOT = os.path.join(BASE_DIR, ‘static/media’)

3.创建提交表单

<form action="" method="post" enctype="multipart/form-data">{#文件上传必须使用enctype#}
    {% csrf_token %}
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>

4.修改视图函数

from datetime import datetime
import os
from CRM.settings import MEDIA_ROOT


def form(request):
    if request.method == 'POST':
        file = request.FILES.get('file')

        #每天的文件放到每天的文件夹里面
        day_dir = datetime.now().strftime('%Y%m%d')
        dir_path = os.path.join(MEDIA_ROOT, day_dir)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)


        filename = os.path.join(dir_path,file.name)#路径拼接
        with open(filename,'wb') as f:
            for line in file.chunks():#将上传文件过大时进行分块
                f.write(line)

注:如果需要多个文件上传,则需要在input为file的属性名添加一个mutiple。同时file=request.FILES.getlist(‘file’)并且之前是以此添加文件,这边加个循环就可以使整个文件都上传。for file in flies:下面的和之前一个文档的内容一样

2.HttpRequest对象

In [5]: response = HttpResponse("上传成功")               
In [6]: response.content 
Out[6]: b'\xe4\xb8\x8a\xe4\xbc\xa0\xe6\x88\x90\xe5\x8a\x9f'

In [7]: response.content.decode("utf-8") 
Out[7]: '上传成功'

In [8]: response  
Out[8]: <HttpResponse status_code=200, "text/html; charset=utf-8">

同时也支持先创建然后写入

In [11]: response = HttpResponse()  
In [12]: response.write("你好") 
In [14]: response.write("<h1>你好世界</h1>")              

In [15]: response.content                                 
Out[15]: b'\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x88\x91\xe5\xa5\xbd<h1>\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c</h1>'

In [16]: response.content.decode("utf-8")
Out[16]: '你好我好<h1>你好世界</h1>'

render:渲染

redirect:重定向,跳转另一个网页

JsonResponse

from teacher.models import Teacher
def test_json(request):
    sex = request.GET.get("sex")
    rex = Teacher.objects.values('name','age','sex').filter(sex=sex)
    res = list(rex)
    data = {'result' : res}
    # return HttpResponse("ok")
    return JsonResponse(data)

3.cookie

客户端访问服务器时(发送请求时)服务器在http协议里加上请求头,通过响应,传送到客户端,并保存在客户端,当客户端再次访问时,将携带这个cookie去访问,这样服务器才能区分不同的客户端。

注:+=必须左右两边同时为int不然会报错。

num = request.COOKIES.get('num')
if num:
    num = int(num) + 1
else:
    num = 1
response = render(request, 'student/test4.html',context={
    'num':num,
    'now':now,
    'lt':lt,
    'students':sts,
    'st':st,
    'date_format':date_format,
    'js':js,
    'dr':dr,
    'format_str':format_str})
response.set_cookie('num',num,max_age=5)#后面的max_age可以设置cookie的有效值,5秒后重置。
return response

如果想获取更多有关python的信息,和想玩python制作的小程序,可以关注微信公众号(dreamspy)。我们一起用python改变世界,一起用python创造梦想。
在这里插入图片描述

发布了43 篇原创文章 · 获赞 11 · 访问量 5401

猜你喜欢

转载自blog.csdn.net/jiangSummer/article/details/103390685