如何在Django中将FileField查询对象转换为字节?

2024-10-04 07:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

在这个Django项目中,“root”是主项目,“crypt”是应用程序。我试图做的是,获取用户输入(文件),然后对其进行加密。用户输入通过表单提交。表单工作正常,并且还存储了文件输入

这是models.py

FUNCTION_CHOICE = (
  ('ENCRYPT', 'Encrypt'),
  ('DECRYPT', 'Decrypt'),
)
class Cryptdb(models.Model):
    function = CharField(max_length=7, choices=FUNCTION_CHOICE, default='Encrypt')
    userinputfile = FileField(upload_to='inputs/')
    key = CharField(max_length=100, null=True)
    encryptedfile = FileField(upload_to='encrypted/', null=True)

forms.py

class InputForm(forms.ModelForm):
class Meta:
    model = Cryptdb
    fields = ('function', 'type', 'userinputfile')

views.py

def upload_file(request):
if request.method == 'POST':
    save_the_form = InputForm(request.POST, request.FILES)
    if save_the_form.is_valid():
        save_the_form.save()
        return HttpResponseRedirect('/success/url')
else:
    form = InputForm()
return render(request, 'home.html', {'form': form})

class MainpageView(CreateView):
    model = Cryptdb
    form_class = InputForm
    success_url = 'download'
    template_name = 'home.html'

class DownloadpageView(ListView):
    model = Cryptdb
    template_name = 'download.html'
    context_object_name = 'obj'

def get(self, request):
    form = InputForm()
    thefile = Cryptdb.objects.order_by('-id')[:1].get()
    foo = thefile.userinputfile
    keyy = Fernet.generate_key()
    key_object = Fernet(keyy)
    enc = key_object.encrypt(foo)
    foo.encryptedfile = enc
    args = {'form': form, 'thefile': thefile}
    return render(request, self.template_name, args)

这里,我使用queryset get()方法来获取对象,而不是queryset list,我使用该对象来分隔文件并将其存储在变量中。我需要使用这个变量来加密文件。(另外,对象foo是一个文件字段,对吗?) 该错误发生在开始加密文件时,即在enc = key_object.encrypt。它在/download/处抛出类型错误,数据必须是字节。但是,当我尝试使用while open(foo, 'rb') as f将文件对象foo转换为字节时,它再次将错误显示为预期的str、bytes或os.PathLike对象,而不是FieldFile。是否有其他方法将其转换为字节

这里是download.html,如果成功,我只想显示加密文件的路径

<html>
<h2>File uploaded successfully</h2>
{% for i in thefile %}
    <p>{{ i.userinputfile }}</p>
    <p>{{ i.encryptedfile }}</p>
{% endfor %}
</html>

谢谢<;三,


Tags: 文件对象keynameformfoorequestdownload