电商网站的建设与运营开公司注册空头公司做网站
电商网站的建设与运营,开公司注册空头公司做网站,怎样做好营销推广,虚拟机怎么做多个网站前言
Django自带了一个名为FileField的字段#xff0c;用于处理文件上传。然而#xff0c;有时我们需要更多的控制权#xff0c;例如定义文件的存储路径、文件名以及文件类型。在本篇文章中#xff0c;我们将探讨如何自定义Django附件存储模型。
创建attachment应用
pyt…前言
Django自带了一个名为FileField的字段用于处理文件上传。然而有时我们需要更多的控制权例如定义文件的存储路径、文件名以及文件类型。在本篇文章中我们将探讨如何自定义Django附件存储模型。
创建attachment应用
python manage.py startapp attachment然后在项目的settings.py文件中将应用注册到INSTALLED_APPS列表中如下所示
INSTALLED_APPS [django.contrib.admin,django.contrib.auth,django.contrib.contenttypes,django.contrib.sessions,django.contrib.messages,django.contrib.staticfiles,rest_framework,drf_yasg2,django_filters,account.apps.AccountConfig,oauth,attachment
]创建模型
定义Attachment
from django.db import models# Create your models here.
from rest_framework.reverse import reversefrom CodeVoyager.mixins import BaseModelMixin
import uuidclass BlobField(models.Field):description Blobdef db_type(self, connection):return mediumblobclass Attachment(BaseModelMixin):file_id models.UUIDField(auto_createdTrue, defaultuuid.uuid4, editableFalse)file_name models.CharField(文件名, max_length200, uniqueTrue)mime_type models.CharField(MIME类型, max_length100)file_size models.PositiveIntegerField(文件长度)blob BlobField(文件内容)class Meta:verbose_name 附件verbose_name_plural verbose_namedef get_url(self, request):return reverse(attachment:download, requestrequest, kwargs{attachment_id: self.file_id})
字段名称类型用途file_idUUIDField存储文件的唯一标识符file_nameCharField存储文件的名称即原始文件名mime_typeCharField存储文件的MIME类型file_sizePositiveIntegerField存储文件的大小以字节为单位blob自定义 BlobField存储文件的二进制内容即文件的实际数据
将更改应用到数据库
python manage.py makemigrations
python manage.py migrate自定义Django存储
定义存储类
#!/usr/bin/python
# -*- coding: utf-8 -*-from django.core.files.base import ContentFile, File
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructibledeconstructible
class AttachmentStorage(Storage):附件存储def __init__(self, modelNone):from .models import Attachmentself.model Attachmentdef _open(self, file_id, moderb):instance self.model.objects.get(file_idfile_id)file ContentFile(instance.blob)file.filename instance.file_namefile.mimetype instance.mime_typereturn filedef _save(self, name, content: File):blob content.read()mime_type getattr(content, content_type, text/plain)self.model.objects.create(file_namename,blobblob,file_sizecontent.size,mime_typemime_type)return namedef exists(self, name):return self.model.objects.filter(file_namename).exists()attachment_storage AttachmentStorage()
方法名称参数返回值用途_openfile_id, moderbContentFile打开文件以供读取根据给定的file_id从Attachment模型中获取文件记录并返回ContentFile对象。_savename, content: File文件名保存文件将文件名和文件内容作为参数创建Attachment模型记录并将文件信息保存到数据库。existsname布尔值 (True 或 False)检查文件是否存在根据给定的文件名查询Attachment模型返回True如果文件存在否则返回False。
这些方法共同组成了AttachmentStorage类用于处理附件文件的存储和访问。_open 方法用于读取文件_save 方法用于保存文件而exists 方法用于检查文件是否存在。请注意初始化方法__init__接受一个model参数。
定义视图
上传视图
class AttachmentUploadView(APIView):permission_classes (permissions.IsAdminUser,)def post(self, request, version):try:file request.FILES[file]except MultiValueDictKeyError:raise ValidationError(参数错误)name attachment_storage.save(file.name, file)attachment get_object_or_404(Attachment, file_namename)return JsonResponse({download_url: attachment.get_url(request)}, statusstatus.HTTP_201_CREATED)作用处理附件的上传操作。功能当接收到POST请求时该视图尝试从请求中获取名为 ‘file’ 的文件然后使用自定义的存储后端 attachment_storage 来保存文件。接着它在数据库中查找与文件名匹配的附件记录并返回包含下载链接的 JSON 响应。这个视图的主要目的是允许用户上传附件并提供上传后的附件的下载链接。
下载视图
class AttachmentDownloadView(APIView):permission_classes (permissions.IsAuthenticated,)def get(self, request, version, attachment_idNone):attachment attachment_storage.open(attachment_id)response HttpResponse(attachment, content_typeattachment.mimetype)response[Content-Disposition] attachment;filename{name}.format(nameattachment.filename).encode(utf-8)return response作用处理附件的下载操作。功能当接收到GET请求时该视图使用传递的 attachment_id 参数来打开相应的附件。然后它创建一个包含附件内容的 HTTP 响应对象设置响应的内容类型为附件的 MIME 类型并设置响应头 Content-Disposition指定附件的文件名。最后它返回包含附件内容的 HTTP 响应。这个视图的主要目的是允许用户通过提供附件的唯一标识符来下载附件。 Content-Disposition 是一个HTTP响应头它用于指示浏览器如何处理接收到的文件。具体来说Content-Disposition 头的值告诉浏览器应该如何处理响应的内容通常用于文件下载操作。 注册视图
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.urls import re_path, pathfrom .views import AttachmentUploadView, AttachmentDownloadViewapp_name attachmenturlpatterns [re_path(rupload, AttachmentUploadView.as_view(), nameupload),path(rdownload/uuid:attachment_id, AttachmentDownloadView.as_view(), namedownload),
]使用swagger测试接口
上传 下载 结语
在开发Web应用程序时文件上传和下载是常见的功能之一但同时也需要特别关注安全性。通过合理的安全性配置你可以保护应用程序和用户的数据免受潜在的威胁。在实际的项目中我们可以增加一些重要的安全性措施包括文件类型验证、文件大小限制、CSRF保护、存储路径安全性和其他关键措施以确保文件上传和下载功能的安全性。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/91197.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!