【问题标题】:How do I access files hosted on web via python?如何通过 python 访问托管在网络上的文件?
【发布时间】:2021-05-24 10:04:37
【问题描述】:

我正在开发一个在本地机器上运行的系统(python 程序),但它需要获取托管在网络上某处的数据(在我的例子中是图像)。 它的作用是:

  1. 向网络主机发送 SQL 查询(当前为localhost)
  2. 响应发回图像的名称(假设它存储在一个名为 fetchedImages 的数组中)。

现在,一旦我有了所需图像的所有名称,我想做的就是直接从localhost 访问文件并将其复制到本地计算机。但这是我的问题:

我正在尝试以以下方式访问它:

source = "localhost/my-site/images"
localDir = "../images"

for image in fetchedImages:
    copy(source+image,localDir)

但问题是,本地主机是使用 XAMPP 创建的,我无法访问 localhost,因为 python 不接受它作为路径。如果不是通过SimpleHTTPServer 而是通过 XAMPP 创建的,如何访问 localhost?

【问题讨论】:

  • localhost 只是表示您尝试访问的 IP 地址的另一种方式,但如果您只想将其复制到本地驱动器上,为什么不使用XAMP 包含所有信息的正常路径?例如,source = "C:\Xampp\htdocs\my-site\images\" 用于 Windows。
  • 这正是我目前正在做的事情,但我计划稍后将网站托管在远程主机上 (www.my-site.com)。这就是为什么我不想选择source = "C:\Xampp\htdocs\my-site\images\"。如果我现在这样设计它,采用路径更改将是灵活的,因为它不再适用于静态路径。

标签: python localhost remote-access


【解决方案1】:

可以使用requests解决:

import requests as req
from StringIO import StringIO
from PIL import Image

source = "http://localhost/my-site/images/"
localDir = "../images"

for image in fetchedImages:
    remoteImage = req.get(source+image)
    imgToCopy = Image.open(StringIO(remoteImage.content))
    imgToCopy.save(localDir+image)

requests 将访问网络资源,从而使系统易于使用动态路径(localhost/my-site 或www.my-site.com),然后将这些资源复制到本地机器进行处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多