Forums

Local python download PyAnywhere files?

Hi guys,

I currently access my P.A. Django's MySQL from my local through SSH. I want access to my media files.

I don't know of a way to do this through the Django ORM (which I've cloned on P.A. and my local), so I'm searching for how to let python download files from P.A. to local. The Django ORM gives me the filepath on P.A.

Help!

Thanks, Pete

I suppose you could simulate a login to PythonAnywhere with something like requests and then GET the files like that. Alternatively, you could use scp to get the files.

GET sounds like a great option. Can you give me some direction on it? Do I build an API-like-thing? Or is it handled in my views?

Pointers thankfully appreciated.

Hmmm, looking at this a little more, I think that scp would be a really good option, especially if you're already using SSH. Check out the scp module.

Thanks giles.

Here's what I ended up doing. Works well. Can you see any holes?

On Django:

#urls.py
urlpatterns = [   
    ...
    url(r'^download/(?P<image_id>[0-9]+)/$', views.download, name='download'),    
    ]

#views.py
def download(request, image_id):
    image = get_object_or_404(StoredImage, pk=image_id)
    path = os.path.join(settings.MEDIA_ROOT, image.image.name) #The image file is in my image model
    fsock = open(path, 'rb')
    response = HttpResponse(fsock, content_type='image')
    response['Content-Disposition'] = "attachment; filename=%s" % (image.image.name)
    return response

On Local (with django.setup() called):

from tempfile import NamedTemporaryFile

def download_image(image):
    #Create download url for image
    url = HOST_URL + reverse('myapp:download', args=[image.id])
    #Get file extension
    file_extension = os.path.splitext(image.image.name)[1]
    #Request the image
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        #Save it to harddrive
        image = NamedTemporaryFile(mode='wb', delete=False, suffix=file_extension)
        for chunk in r:
            image.write(chunk)
        return image

Great! That looks OK to me.