Login

get and image object

Author:
grillermo
Posted:
March 1, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

I use this snippet to save images to my imagefields on django models. This uses the very awesome requests library, so install it first

pip install requests

You probably want to have this be done on a celery queu, if the image is big enough.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import requests #get it http://docs.python-requests.org/en/latest/index.html

def get_img_obj(url='',relativefile='',absolutefile=''):
    ''' Takes a url or a relative path to a file in the static dir and returns
    an object suitable to be asigned in an imagefield = get_img_obj(url='url')'''
    if url and relativefile:
        raise UserWarning('Function save_image_in_field expects a URL or a Filename not both.')
        
    if url:
        r = requests.get(url)
        data = r.content
        
    if relativefile:
        r = open(os.path.join(settings.STATICFILES_DIRS[0],relativefile),'rb')
        data = r.read()

    if absolutefile:
        r = open(absolutefile,'rb')
        data = r.read()
        
    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(data)
    img_temp.flush()
    return File(img_temp)

##### And you can use it like this:
## Asume that profile is some model and image is an imagefield of that model
profile.image.save('some name.jpg',get_img_obj('http://google.com/logo.jpg'))#url
profile.image.save('some name.jpg',get_img_obj(relativefile='images/logo.jpg'))# the file is on ~/django_project/static/image/logo.jpg
profile.image.save('some name.jpg',get_img_obj(absolutefile='~/userfile.jpg'))# you pass the full path to the file

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.