在Django中将用户上传的文件存储在哪里 [英] Where to store user uploaded files in Django

查看:543
本文介绍了在Django中将用户上传的文件存储在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Django应用,用户可以在其中上传CSV文件。然后,将CSV文件中的每一行添加到数据库中(在验证数据之后)。然后可以丢弃该文件。

I'm building a Django app where users will upload a CSV file. Each row in the CSV file will then be added to the DB (after validating the data). The file can then be discarded.

从Django文档中,我使用它来保存文件。

From the Django documentation, I'm using this to save the file.

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

上有很多警告Django网站关于处理用户上传的文件,所以我的问题是,这些文件应保存在哪里?我的猜测是没关系,但我想确定。

There's a lot of warnings on the Django site about handling user uploaded files so my question is, where should these files be saved? My guess is it doesn't matter, but I want to be sure.

目前,我打算在设置文件中创建一个名为UPLOADS_URL的变量。然后,所有上传的文件都将存储在该文件中。

At the moment I plan to create a variable called UPLOADS_URL in my settings file. All uploaded files will then be stored in there.

推荐答案

实际上,将这些文件放在什么位置都没关系,特别是如果您将其丢弃。唯一重要的是将它们放置在Web服务器无法访问的位置。因此,例如,如果您的静态文件和/或应用程序代码存储在 / var / www 目录中,请不要将上传的文件放在此处。

Indeed it does not matter so much where you put these files, especially if you discard them after. The only important thing is to put them in a place that is not accessible by your webserver. So for example if your static files and/or your app code is stored in the /var/www directory, do NOT put the uploaded files there.

现有的Django设置称为 MEDIA_ROOT MEDIA_URL 用作存储上载文件的默认位置。 MEDIA_ROOT 是文件存储的路径, MEDIA_URL 是http客户端可用来检索文件的URL路径。上传的文件(因此不需要)。

There are existing Django settings called MEDIA_ROOT and MEDIA_URL that are used as the default place to store the uploaded files. MEDIA_ROOT is the path where the files are stored, MEDIA_URL is the URL path that a http client may use to retrieve the uploaded files (so in your case it is not needed).

您需要特别注意的是CSV文件的内容 。当您将它们存储在数据库中并在以后重新使用时,应在存储内容之前仔细验证其内容。例如,如果您要存储一个字符串,稍后将在网站上显示,则要确保该字符串不包含任何javascript ...

What you need to be really careful about is the content of the CSV files. As you are going to store them in DB and re-use them later, you should validate carefully the content before storing it. For example, if you are storing a string that you will later display on the site, you want to make sure it doesn't contain any javascript...

这篇关于在Django中将用户上传的文件存储在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆