please excuse me for my ugly english ;-)
Imagine this very simple model :
class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).
I think that I need to do something like this :
from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
I hope that I've well explained the problem, if not tell me.
Thank you :)
Edit :
This may work but I don't know how to convert content to a django File :
from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
I just created http://www.djangosnippets.org/snippets/1890/ for this same problem. The code is similar to pithyless' answer above except it uses urllib2.urlopen because urllib.urlretrieve doesn't perform any error handling by default so it's easy to get the contents of a 404/500 page instead of what you needed. You can create callback function & custom URLOpener subclass but I found it easier just to create my own temp file like this:
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
im.file.save(img_filename, File(img_temp))
from myapp.models import Photo
import urllib
from urlparse import urlparse
from django.core.files import File
img_url = 'http://www.site.com/image.jpg'
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
# See also: http://docs.djangoproject.com/en/dev/ref/files/file/
photo.image.save(name, File(open(content[0])), save=True)
Combining what Chris Adams and Stan said and updating things to work on Python 3, if you install Requests you can do something like this:
from urllib.parse import urlparse
import requests
from django.core.files.base import ContentFile
from myapp.models import Photo
img_url = 'http://www.example.com/image.jpg'
name = urlparse(img_url).path.split('/')[-1]
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
response = requests.get(img_url)
if response.status_code == 200:
photo.image.save(name, ContentFile(response.content), save=True)
More relevant docs in Django's ContentFile documentation and Requests' file download example.
ImageField is just a string, a path relative to your MEDIA_ROOT setting. Just save the file (you might want to use PIL to check it is an image) and populate the field with its filename.
So it differs from your code in that you need to save the output of your urllib.urlopen to file (inside your media location), work out the path, save that to your model.
I do it this way on Python 3, which should work with simple adaptations on Python 2. This is based on my knowledge that the files I’m retrieving are small. If yours aren’t, I’d probably recommend writing the response out to a file instead of buffering in memory.
BytesIO is needed because Django calls seek() on the file object, and urlopen responses don’t support seeking. You could pass the bytes object returned by read() to Django's ContentFile instead.
from io import BytesIO
from urllib.request import urlopen
from django.core.files import File
# url, filename, model_instance assumed to be provided
response = urlopen(url)
io = BytesIO(response.read())
model_instance.image_field.save(filename, File(io))
Recently I use the following approach within python 3 and Django 3, maybe this might be interesting for others aswell. It is similar to Chris Adams solution but for me it did not work anymore.
import urllib.request
from django.core.files.uploadedfile import SimpleUploadedFile
from urllib.parse import urlparse
from demoapp import models
img_url = 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png'
basename = urlparse(img_url).path.split('/')[-1]
tmpfile, _ = urllib.request.urlretrieve(img_url)
new_image = models.ModelWithImageOrFileField()
new_image.title = 'Foo bar'
new_image.file = SimpleUploadedFile(basename, open(tmpfile, "rb").read())
new_image.save()
Just discovered that you don't have to generate a temporary file:
Stream url content directly from django to minio
I have to store my files in minio and have django docker containers without much disk space and need to download big video files, so this was really helpful to me.
Its been almost 11 years since the question and the most reputed answer has been posted. Thanks To #chris-adams for the response. I am Just reposting the same answer along with the updated packages and support.
#! /usr/bin/python3
# lib/utils.py
import urllib3 # http Request Package.
from typing import Optional
from django.core.files import File # Handle Files in Django
from django.core.files.temp import NamedTemporaryFile # handling temporary files.
def fetch_image(url: str, instance: models.Model, field: str, name: Optional[str]=None):
"""
fetch_image Fetches an image URL and adds it to the model field.
the parameter instance does not need to be a saved instance.
:url: str = A valid image URL.
:instance: django.db.models.Model = Expecting a model with image field or file field.
:field: str = image / file field name as string;
[name:str] = Preferred file name, such as product slug or something.
:return: updated instance as django.db.models.Model, status of updation as bool.
"""
conn = urllib3.PoolManager()
response = conn.request('GET', url)
if response.status <> 200:
print("[X] 404! IMAGE NOT FOUND")
print(f"TraceBack: {url}")
return instance, False
file_obj = NamedTemporaryFile(delete=True)
file_obj.write( response.data )
file_obj.flush()
img_format = url.split('.')[-1]
if name is None:
name = url.split('/')[-1]
if not name.endswith(img_format):
name += f'.{img_format}'
django_file_obj = File(file_obj)
(getattr(instance, field)).save(name, django_file_obj)
return instance, True
Tested with Django==2.2.12 in Python 3.7.5
if __name__ == '__main__':
instance = ProductImage()
url = "https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png"
instance, saved = fetch_image(url, instance, field='banner_image', name='intented-image-slug')
status = ["FAILED! ", "SUCCESS! "][saved]
print(status, instance.banner_image and instance.banner_image.path)
instance.delete()
this is the right and working way
class Product(models.Model):
upload_path = 'media/product'
image = models.ImageField(upload_to=upload_path, null=True, blank=True)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.image_url:
import urllib, os
from urlparse import urlparse
filename = urlparse(self.image_url).path.split('/')[-1]
urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
self.image = os.path.join(upload_path, filename)
self.image_url = ''
super(Product, self).save()
Related
I use django-storages and have user related content stored in folders on S3. Now I want users to have the ability to download all their files at once, preferably in a zip file. All the previous posts related to this are old or not working for me.
The closest to working code I have so far:
from io import BytesIO
import zipfile
from django.conf import settings
from ..models import Something
from django.core.files.storage import default_storage
class DownloadIncomeTaxFiles(View):
def get(self, request, id):
itr = Something.objects.get(id=id)
files = itr.attachments
zfname = 'somezip.zip'
b = BytesIO()
with zipfile.ZipFile(b, 'w') as zf:
for current_file in files:
try:
fh = default_storage.open(current_file.file.name, "r")
zf.writestr(fh.name, bytes(fh.read()))
except Exception as e:
print(e)
response = HttpResponse(zf, content_type="application/x-zip-compressed")
response['Content-Disposition'] = 'attachment; filename={}'.format(zfname)
return response
This creates what looks like a zipfile but the only content it has is '<zipfile.ZipFile [closed]>'
I got many different results, mainly with errors like zipfile expecting string or bytes content while a FieldFile is provided. At this point I'm completely stuck.
The problem was that I needed to revert back to the beginning of the file by adding
zf.seek(0)
just before returning the file in the HttpResponse.
My web application has the following structure:
backend with Django
frontend with React.
I have a form with React. I send a file from client form and I receive the file in my Django application with an APIView.
I receive a m3u file as bytes object.
b'------WebKitFormBoundaryIaAPDyj9Qrx8DrWA\r\nContent-Disposition:
form-data; name="upload";
filename="test.m3u"\r\nContent-Type: audio/x-
mpegurl\r\n\r\n#EXTM3U\n#EXTINF:-1 tvg-ID="" tvg-name="...
I would save the file in a Django model to a models.FileField and convert bytes object to m3u file.
How you do it?
models.FileField(models.ImageField) needs django.core.files.base.File like objects
ex)
django.core.files.base.File
django.core.files.images.ImageFile
File or ImageFile needs two args.
IO object : which has seek() method (ex) io.BytesIO).
name : str. (important! without name, it will not work).
bytes object doesn't have IO's methods(ex) seek()). it should be converted to IO object.
models.py
class Message(models.Model):
image = models.ImageField(upload_to='message_image/%Y/%m', null=True)
views.py or consumers.py or some-where.py
import io
from django.core.files.images import ImageFile
from myapp.models import Message
def create_image_message(image_bytes):
image = ImageFile(io.BytesIO(image_bytes), name='foo.jpg') # << the answer!
new_message = Message.objects.create(image=image)
You can try:
from django.core.files.base import ContentFile
import base64
file_data = ContentFile(base64.b64decode(fileData))
object.file.save(file_name, file_data)
You can use your file_name with an .m3u extension, and you shall have it.
I solved using temporary file. I used this code:
extM3u = str.encode(body.decode('utf8').split('EXTM3U\n#')[1].split('------WebKitFormBoundary')[0])
fileTemp = NamedTemporaryFile(delete=True, dir='media/tmp')
fileTemp.write(extM3u)
filenameRe = re.compile('.*?filename=[\'"](.*?)[\'"]')
filename = regParse(filenameRe, body.decode('utf8'))
file = File(fileTemp, name=filename)
m3u = M3u(titleField=filename, fileField=file)
m3u.save()
You can use a ContentFile. To do so:
from django.core.files.base import ContentFile
content_file = ContentFile(file_bytes, name=file_name)
# Assumes MyModel has a FileField called `file`
MyModel.objects.create(file=content_file)
convert string to bytes
bytes_data = ... # bytes
string_data = bytes_data.hex() # this is a string that you can save in TextField in django model
then, to get bytes from the string:
bytes_data_2 = bytes.fromhex(string_data)
I apologize for the crooked translation, I'm still only learning English.
I have 5 image fields in my model , imageA, imageB, imageC, imageD and imageE
I am trying to save the images in the following manner.The image are of type Base64ImageField
images=["imageA","imageB","imageC","imageD","imageE"]
for field in images:
if field in serializer.validated_data:
content = serializer.validated_data[field]
dict = {field : content}
modelJob.objects.filter(id=modjob.id).update(**dict)
In the above code content contains the raw data.I am trying to update the image using the dict I created (the key is the field name and value is the content).
However the images saved in the imageField of the model are raw and not an actual image. How can I fix this ? This is what my serializer looks like
class Serializer_Custom_RX(serializers.ModelSerializer):
imageA = Base64ImageField(max_length=None, use_url=True, )
imageB = Base64ImageField(max_length=None, use_url=True, )
imageC = Base64ImageField(max_length=None, use_url=True, )
imageD = Base64ImageField(max_length=None, use_url=True, )
class Meta:
model = modelTest
fields = [
'title',
'zip',
'imageA','imageB','imageC','imageD',
]
More info:
If I do something like this
modelJob.instance.imageA.save(content=content,name="image.jpeg")
it works fine and the problem is solved.However there are two problems with this approach first of all I do not know the extension. How do I extract an extension ? I am just guessing a jpeg here and it works. The next thing is Ill have to check for imageA,B,C,D and E if they exist and then save each one individually. If I could come up with a dynamic solution close to something that I have that would work as well. This is what my jsondata looks like that I am posting
{
"title" : "Some Title",
"zip":12345,
"imageA":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUUEhMWFhUXGSIbGBgYGSIgHhogIB8fHSAbHyAeICghHR8lHh0dITElJSsrLi4uICAzODMsNygtLisBCgoKDg0OGxAQGy0lICUtLS01LS8tLS0tLS8vLy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAKgBLAMBIgACEQEDEQH/xAAbAAACAgMBAAAAAAAAAAAAAAAFBgMEAAIHAf/EADwQAAIBAgUDAwMCBAU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MQwKshoLoh6QoFPLPAP30z54iPxq/ng39PVKJksGDiFlTAIEWsPbGYzFvql4s2T8UM9LoPr0aoQEI6sLmQpg2BFxuDB845p03IvVohqaMzoDq8KsbmeQQf3xmMxLD4Y21+hYx8Q50Oq4NNwwAMNpYxIncCL2Jv7DFv6ncNW21KpUm/tt7b8YzGYVdsbG7iyhWrNDFQdWrUSPG554XV+wxX6bnR6iyAqxpaQD2vIJv/qiRtjMZiuNJoawglSqilAzEUyQVB22KsFkwCsG35xQzrBxpYR3C/LR88W2EYzGYX+qxn0DurUdK038uwJtMAJA/mcEMjmgS2knUtMhSdzYGLbxP8sZjMWa5Q2Izc5liQ0drD2uY8jbFLMZ0qYifyMZjMShBOVUc0ls//9k="
}
The images encoding should come from the client, this is how you can know which format of each one has. Example:
base_64 = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739......
You will receive it from the client and you know that is a .gif
Once you have validated the extensions and the base64 you can convert it to images and save it in your OS:
Convert string in base64 to image and save on filesystem in Python or Decoding base64 from POST to use in PIL
Once you have the images in your OS, you can link them to your ImageField in the model changing the name property: Set Django's FileField to an existing file
I hope that is clear and helpful!!
Here is how I solved this problem. None of the answers above had this information
However there are two problems with this approach first of all I do
not know the extension.How do I extract an extension ?
The extension can be extracted by using the following code
from PIL import Image
decodedbytes = base64.decodebytes(str.encode(image_content))
image_stream = io.BytesIO(decodedbytes)
image = Image.open(image_stream)
filetype = image.format #Contains the extension
The next thing is Ill have to check for imageA,B,C,D and E if they
exist and then save each one individually. If I could come up with a
dynamic solution close to something that I have that would work as
well.
The solution to this was simple to use
getattr(job_inst, field).save(content=data , name="img"+filetype)
Short answer is :
import imghdr
extension = imghdr.what(file_name, decoded_file)
ref : https://docs.python.org/2/library/imghdr.html OR https://docs.python.org/3/library/imghdr.html
Basically import imghdr is the key in function Base64ImageField.get_file_extension to get / extract the extension of the function.
With below class extend / code you don't need to do modelJob.instance.imageA.save(content=content,name="image.jpeg")
You need to add this class in your codebase to call or for trial purpose you can add in same Serializer class file itself.
from django.core.files.base import ContentFile
import base64
import six
import uuid
class Base64ImageField(serializers.ImageField):
"""
A Django REST framework field for handling image-uploads through raw post data.
It uses base64 for encoding and decoding the contents of the file.
Heavily based on
https://github.com/tomchristie/django-rest-framework/pull/1268
Updated for Django REST framework 3.
"""
def to_internal_value(self, data):
# Check if this is a base64 string
if isinstance(data, six.string_types):
# Check if the base64 string is in the "data:" format
if 'data:' in data and ';base64,' in data:
# Break out the header from the base64 content
header, data = data.split(';base64,')
# Try to decode the file. Return validation error if it fails.
try:
decoded_file = base64.b64decode(data)
except TypeError:
self.fail('invalid_image')
# Generate file name:
file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
# Get the file name extension:
file_extension = self.get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
data = ContentFile(decoded_file, name=complete_file_name)
return super(Base64ImageField, self).to_internal_value(data)
def get_file_extension(self, file_name, decoded_file):
import imghdr
extension = imghdr.what(file_name, decoded_file)
extension = "jpg" if extension == "jpeg" else extension
return extension
One more information is you can have
Base64ImageField(
max_length=None,
use_url=True,
required=False,
allow_null=True,
allow_empty_file=True
)
these params in case you want to make this optional.
NOTE :: I had got this code from StackOverflow only, but not remembered from where I got this I had liked this answer too.
I'm working with Django 1.7 and Python 3.4.
I have a model like this one:
class ImageModel(models.Model):
image = models.ImageField(verbose_name='image', upload_to='uploaded_images/')
Now I want to download image which is saved in /static/uploaded_images/.
For example I have a link like this: www.example.com/image/download/1, where 1 is id of ImageModel object.
Now i have a view:
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
( what I need to do? )
What next? How to create a view that will force download of that image?
You can try this code, maybe need some caveats:
from django.core.servers.basehttp import FileWrapper
import mimetypes
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
wrapper = FileWrapper(open(img.file)) # img.file returns full path to the image
content_type = mimetypes.guess_type(filename)[0] # Use mimetypes to get file type
response = HttpResponse(wrapper,content_type=content_type)
response['Content-Length'] = os.path.getsize(img.file)
response['Content-Disposition'] = "attachment; filename=%s" % img.name
return response
I'm assuming there is a field .name in your ImageModel to get the name of the file in the second-to-last line ...filename=%s" % img.name You should edit the code to fit your project.
There is a field in an ImageField that is file, in the code here I use img.file to get the path to the file, you should change that for img.YOUR_IMAGE_FIELD.file or anything you need to get the path to the image
You need to use Content-Disposition header, take a look here:
Generating file to download with Django
Django Serving a Download File
A class based views-type exampe of this would be like this (i'm using python-magic to get the correct content-type for the file):
import os
import magic
from django.views.generic import View
from django.http import HttpResponse
from .models import ImageModel
class ImageDownloadView(View):
def get(self, request, *args, **kwargs):
image = ImageModel.objects.get(pk=self.kwargs['image_id'])
image_buffer = open(image.file.path, "rb").read()
content_type = magic.from_buffer(image_buffer, mime=True)
response = HttpResponse(image_buffer, content_type=content_type);
response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(image.file.path)
return response
This works for Django 1.10.7 but shouldn't be that different for Django 1.7
The other two answers are ok, but as advertised in many places using Django to serve an static file is not recommended for performance reasons. It is better to serve it using your web server (nginx/apache...).
You don't need an extra view to serve static files. Simply render a link to the file in your template:
Download this image!
Where object is an instance of ImageModel.
See django.db.models.fields.files.FieldFile.url
If you really want to have a view in an URL like www.example.com/image/download/1 you can simply write a view that redirect to the image URL obtained from the field.
Here is your cross browser safe download for files containing any character type
# Even better as it works in any browser (mobile and desktop)
def safe_name(file_name):
"""
Generates a safe file name, even those containing characters like ? and &
And your Kanji and Cyrillics are supported!
"""
u_file_name = file_name.encode('utf-8')
s_file_name = re.sub('[\x00-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), u_file_name)
return s_file_name
# Handled by url(r'^/image/download/(\d+)/.+$
def safe_download_image(request, image_id):
"""
Safely downloads the file because the filename is part of the URL
"""
img = ImageModel.objects.get(id=image_id)
wrapper = FileWrapper(open(img.file)) # img.file returns full path to the image
content_type = mimetypes.guess_type(filename)[0] # Use mimetypes to get file type
response = HttpResponse(wrapper,content_type=content_type)
response['Content-Length'] = os.path.getsize(img.file)
# This works for most browsers, but IE will complain sometimes
response['Content-Disposition'] = "attachment;"
return response
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
redirect_do = safe_name(img.name)
return HttpResponseRedirect('/image/download/' + img_id + '/' + redirect_to)
It's doesn't work. I did something like this:
wrapper = FileWrapper(img.file) # img.file returns full path to the image
content_type = mimetypes.guess_type(str(img.file))[0] # Use mimetypes to get file type
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize(str(img.file))
response['Content-Disposition'] = "attachment; filename=%s" % img.name
where img points to my ImageField field. File is downloaded, but I can't open it. xUbuntu image viewer seys 'Not a JPEG file. starts with 0x89 0x50'
My images are stored in a MongoDB, and I'd like to return them to the client, here is how the code is like:
#app.route("/images/<int:pid>.jpg")
def getImage(pid):
# get image binary from MongoDB, which is bson.Binary type
return image_binary
However, it seems that I can't return binary directly in Flask? My idea so far:
Return the base64 of the image binary. The problem is that IE<8 doesn't support this.
Create a temporary file then return it with send_file.
Are there better solutions?
Create a response object with the data and then set the content type header. Set the content disposition header to attachment if you want the browser to save the file instead of displaying it.
#app.route('/images/<int:pid>.jpg')
def get_image(pid):
image_binary = read_image(pid)
response = make_response(image_binary)
response.headers.set('Content-Type', 'image/jpeg')
response.headers.set(
'Content-Disposition', 'attachment', filename='%s.jpg' % pid)
return response
Relevant: werkzeug.Headers and flask.Response
You can pass a file-like object and the header arguments to send_file to let it set up the complete response. Use io.BytesIO for binary data:
return send_file(
io.BytesIO(image_binary),
mimetype='image/jpeg',
as_attachment=True,
download_name='%s.jpg' % pid)
Prior to Flask 2.0, download_name was called attachment_filename.
Just wanted to confirm that dav1d's second suggestion is correct - I tested this (where obj.logo is a mongoengine ImageField), works fine for me:
import io
from flask import current_app as app
from flask import send_file
from myproject import Obj
#app.route('/logo.png')
def logo():
"""Serves the logo image."""
obj = Obj.objects.get(title='Logo')
return send_file(
io.BytesIO(obj.logo.read()),
download_name='logo.png',
mimetype='image/png'
)
Easier than manually creating a Response object and settings its headers.
Prior to Flask 2.0, download_name was called attachment_filename.
Suppose i have the stored image path with me. The below code helps to send image through.
from flask import send_file
#app.route('/get_image')
def get_image():
filename = 'uploads\\123.jpg'
return send_file(filename, mimetype='image/jpg')
uploads is my folder name where my image with 123.jpg is present.
[PS: The uploads folder should be in the current directory as of the your script file]
Hope it helps.
The following worked for me (for Python 3.7.3):
import io
import base64
# import flask
from PIL import Image
def get_encoded_img(image_path):
img = Image.open(image_path, mode='r')
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
my_encoded_img = base64.encodebytes(img_byte_arr.getvalue()).decode('ascii')
return my_encoded_img
...
# your api code
...
img_path = 'assets/test.png'
img = get_encoded_img(img_path)
# prepare the response: data
response_data = {"key1": value1, "key2": value2, "image": img}
# return flask.jsonify(response_data )