第56天:django学习(五)

HttpResponse对象

响应对象主要有三种形式:

HttpResponse()、render()、redirect()

HttpResponse()括号内直接跟一个具体的字符串作为响应体,比较直接很简单,所以这里主要介绍后面两种形式。

render()

render(request, template_name[, context])` `结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

参数:

request: 用于生成响应的请求对象。

template_name:要使用的模板的完整名称,可选的参数

context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。

render方法就是将一个模板页面中的模板语法进行渲染,最终渲染成一个html页面作为响应体。

python 复制代码
def render(request, template_name, context=None, content_type=None, status=None, using=None):
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

redirect()

python 复制代码
def my_view(request):
    ...
    return redirect('/some/url/')

也可以是一个完整的URL

python 复制代码
def my_view(request):
    ...
    return redirect('/some/url/')

JsonResponse类

json作用:

跨语言传输-------序列化:json.dumps--------反序列化:json.loads

向前端返回一个json格式字符串的两种方式

方式一:

python 复制代码
import json
data = {'name': 'kevin', 'age': 22}
def index(request):
	return HttpResponse(json.dumps(data))

方式二:

python 复制代码
from django.http import JsonResponse

def index(request):	
    user_dic = {'name': 'kevin', 'age': 22}
    return JsonResponse(user_dict, json_dumps_params={'ensure_ascii': False})

CBV和FBV

CBV和FBV:

FBV: function based view # 写的都是函数

CBV: class based view # 写的都是类

视图函数的写法(CBV)

python 复制代码
class MyLogin(View):
    def get(self, request):
        print('get。。。')
        return HttpResponse("get")

    def post(self, request):
        return HttpResponse("hello postman!!!")

路由文件的写法(CBV):

python 复制代码
url(r'^login/', views.MyLogin.as_view()), # 注意:as_view后要加括号

简单文件上传

表单上传数据需要满足的条件

1.请求方式必须是post

2.enctype="multipart/form-data"

模板中的写法

html 复制代码
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <input type="submit">
</form>

视图函数写法

python 复制代码
def index(request):
    user_dict = {'name': 'kevin', 'age': 22}
    file_obj = request.FILES.get('myfile')
    file_name = file_obj.name
    with open(file_name, 'wb') as f:
        for line in file_obj:
            f.write(line)

    return render(request, 'index.html')
相关推荐
m0_74870805几秒前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
A_nanda1 分钟前
vue快速学习框架
前端·javascript·vue.js·学习·c#
Dingdangcat865 分钟前
视杯视盘分割与青光眼检测_faster-rcnn_hrnetv2p-w32-1x_coco模型应用实践
python
喵手6 分钟前
Python爬虫实战:携程景点数据采集实战:从多页列表到结构化数据集(附SQLite持久化存储)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·携程景点数据采集·sqlite存储采集数据
无垠的广袤6 分钟前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:人脸检测
linux·人工智能·python·opencv·开发板
yuankoudaodaokou6 分钟前
突破大型工件测量瓶颈:思看科技在风电与船舶制造中的革新应用
python·科技·制造
WTCLLB6 分钟前
取消文件隐藏属性,找到winre.wim和boot.sdi
windows·学习
其美杰布-富贵-李8 分钟前
门控模型与Mixture of Experts (MOE) 学习笔记
笔记·学习·moe·门控神经网络
Allen_LVyingbo13 分钟前
面向70B多模态医疗大模型预训练的工程落地(医疗大模型预训练扩展包)
人工智能·python·分类·知识图谱·健康医疗·迁移学习
Deng87234734814 分钟前
电脑使用 Gemini出了点问题解决办法
人工智能·python