Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django,请求下载文件_Python_Django_Web Applications_Python Requests - Fatal编程技术网

Python django,请求下载文件

Python django,请求下载文件,python,django,web-applications,python-requests,Python,Django,Web Applications,Python Requests,我正在尝试从另一台服务器下载一个文件,我想将其保存在本地服务器并创建一个下载链接,以便用户能够从我们的网站下载它 我可以通过请求下载它,它工作得很好,但我不知道如何将文件保存在静态文件目录中并为其创建url。请引导我 import requests def download_file(url): local_filename = url.split('/')[-1] r = requests.get(url, stream=True) with open(local_filen

我正在尝试从另一台服务器下载一个文件,我想将其保存在本地服务器并创建一个下载链接,以便用户能够从我们的网站下载它

我可以通过请求下载它,它工作得很好,但我不知道如何将文件保存在静态文件目录中并为其创建url。请引导我

import requests
def download_file(url):
   local_filename = url.split('/')[-1]
   r = requests.get(url, stream=True)
   with open(local_filename, 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024):
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)
return local_filename

我想您可能会使用
FileField
。您可以使用
User
的外键为此类文件创建模型。此字段将文件保存到
存储器中
,并通过调用
url()
方法生成url。

您应该将生成的和用户上传的文件保存到
媒体根目录
文件夹,而不是
静态根目录
。它们将以默认设置在
localhost:8000/media/test.txt
上提供。 因此,您应该在函数中执行类似于
返回重定向(settings.MEDIA\u URL+'/'+local\u filename)
的操作

查看博客文章了解更多信息