Search code examples
pythonlocalhostremote-access

How do I access files hosted on web via python?


I am working on a system (python program) that runs on local machine but it needs to fetch data hosted somewhere on web (images in my case). What it does is:

  1. Send a SQL query to webhost (localhost currently)
  2. The response sends back the names of images (it is stored in an array called fetchedImages lets assume).

Now once I have all the names of required images all I want to do is access the file directly from localhost and copy it to local machine. But this is what my problem is:

I am trying to access it as:

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

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

but the problem is that, the localhost is created using XAMPP and I cannot access localhost since python doesn't accept it as path. How can I access localhost if it isn't created via SimpleHTTPServer but XAMPP?


Solution

  • It can be solved using requests as:

    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)
    

    the requests will access the web resource thus making system easy to work with dynamic paths (localhost/my-site or www.my-site.com) and then copy those resources to local machine for processing.