【问题标题】:Get file path from a remote server从远程服务器获取文件路径
【发布时间】:2018-08-14 12:38:48
【问题描述】:

您好,我很难从远程服务器获取文件路径。这里有没有人可以帮助我?

我想要实现的是播放一个已经保存在远程服务器中的音频文件。

这就是我的代码现在的样子。这还不行。

<audio controls>
<source 
src="user@host:/file/path/from/remote/server/{{record.filename}}" type="audio/ogg">
</audio>

我想知道的是我怎样才能得到这条路径user@hostname:/file/path/from/remote/server

我正在使用 Django 和 Python。

非常感谢任何可以提供帮助的人!

【问题讨论】:

  • 为什么不先把文件下载到本地,然后像这样使用 src="location/in/local"?您可以使用 requests.get("user@host:/file/path/from/remote/server/{{record.filename}}") 来获取资源。有什么不使用这个的具体原因吗?
  • 我将上传数千个文件。我不想在我的磁盘中堆积所有这些文件。感谢您的回复,我会尝试您的建议。
  • 嗨!您能否详细说明如何使用 requests.get("user@host:/file/path/from/remote/server/{{record.filename}}")。我对此很陌生。谢谢!
  • 评论太大,作为答案添加。希望对您有所帮助。
  • 如果解决了您的问题,请接受。谢谢。

标签: python django server


【解决方案1】:

您必须从 views.py 函数呈现模板(您在问题中显示的部分)。在该视图中,将文件下载到本地:

import requests
# Before rendering the template 
r = requests.get("user@host:/file/path/from/remote/server/" + record.filename)
local_file = "/path/on/local/" + record.filename
with open(local_file, 'wb') as f:
    f.write(r.content)
# Now pass the location of the local file in template render 
...render(local_file = local_file)

在您的模板中进行相应更改

<audio controls>
<source 
src="{{local_file}}" type="audio/ogg">
</audio>

现在,如果您担心本地内存或混乱,您无需一次下载所有文件。此外,为了提高效率,您可以通过在记录中引入 bool 'downloaded' 字段来维护所有下载文件的映射。然后,您可以在下载之前检查此字段,仅当您的本地尚未下载时才可以下载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多