Git Product home page Git Product logo

pycloudinary's Introduction

Build Status PyPI Version PyPI PyVersions PyPI DjangoVersions PyPI Version PyPI License

Cloudinary Python SDK

About

The Cloudinary Python SDK allows you to quickly and easily integrate your application with Cloudinary. Effortlessly optimize, transform, upload and manage your cloud's assets.

Note

This Readme provides basic installation and usage information. For the complete documentation, see the Python SDK Guide.

Table of Contents

Key Features

Version Support

SDK Version Python 2.7 Python 3.x
1.x
SDK Version Django 1.11 Django 2.x Django 3.x Django 4.x
1.x

Installation

pip install cloudinary

Usage

Setup

import cloudinary

Transform and Optimize Assets

cloudinary.utils.cloudinary_url("sample.jpg", width=100, height=150, crop="fill")

Upload

cloudinary.uploader.upload("my_picture.jpg")

Django

Security options

Sample projects

Contributions

  • Ensure tests run locally.
  • Open a PR and ensure Travis tests pass.
  • See CONTRIBUTING.

Get Help

If you run into an issue or have a question, you can either:

About Cloudinary

Cloudinary is a powerful media API for websites and mobile apps alike, Cloudinary enables developers to efficiently manage, transform, optimize, and deliver images and videos through multiple CDNs. Ultimately, viewers enjoy responsive and personalized visual-media experiences—irrespective of the viewing device.

Additional Resources

Licence

Released under the MIT license.

pycloudinary's People

Contributors

aleksandar-cloudinary avatar cloudinary-pkoniu avatar const-cloudinary avatar dependabot[bot] avatar epasos573 avatar galuszkak avatar idobarnoam avatar ilianiliev avatar itaibenari avatar lkiss80 avatar lukitsbrian avatar m0she avatar nadavs avatar nloadholtes avatar oohsai avatar or3liyahu avatar patrick-tolosa avatar ronen-burin avatar rtrajano avatar rubengrill avatar salomvary avatar shedar avatar tallevami avatar taragano avatar thexxturboxx avatar tocker avatar vdeub-cloudinary avatar wissam-khalili avatar yomesinc avatar zlira avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pycloudinary's Issues

Can't get it to work in Flask

I load in all my settings in Flask. But I keep getting this error:

django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

can't list video resources

when i was trying to see video resource details. i always get the problem:

File "uploader.py", line 151, in
result = cloudinary.api.resources_by_tag("in and out")
File "/usr/local/lib/python2.7/site-packages/cloudinary/api.py", line 55, in resources_by_tag
return call_api("get", uri, only(options, "next_cursor", "max_results", "tags", "context", "moderations", "direction"), **options)
File "/usr/local/lib/python2.7/site-packages/cloudinary/api.py", line 260, in call_api
raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.code, body, e))
cloudinary.api.GeneralError: Error parsing server response (400) - . Got - No JSON object could be decoded

cloudinary.api.resources cannot access video files, even you signed the resrouce type to be raw.

Error when using unicode for transformation name

When calling some of the api's like transform to get the transform details. It does a check to see if you passed a string or a dict representing a transform.

Problem is if you are using unicode and you pass a unicode transform name it fails here:

def transformation_string(transformation):
    return transformation if isinstance(transformation, str) else cloudinary.utils.generate_transformation_string(**transformation)[0]

Note when I call the api to get the list of transformation names they come back in unicode so if you use the name from the api it will fail.

A hack is to convert it to str before calling back into the api, but with unicode becoming the norm we shouldn't have to do that.

example code showing error:

In [10]: transformations = cloudinary.api.transformations()

In [11]: transformations['transformations'][0]['name']
Out[11]: u'a_exif,fl_progressive.force_strip/c_fill,h_50,w_66/jpg'

In [12]: cloudinary.api.transformation(transformations['transformations'][0]['name'])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-3f3d30faa965> in <module>()
----> 1 cloudinary.api.transformation(transformations['transformations'][0]['name'])

.../venv/lib/python2.7/site-packages/cloudinary/api.pyc in transformation(transformation, **options)
    128
    129 def transformation(transformation, **options):
--> 130     uri = ["transformations", transformation_string(transformation)]
    131     return call_api("get", uri, only(options, "max_results"), **options)
    132

.../venv/lib/python2.7/site-packages/cloudinary/api.pyc in transformation_string(transformation)
    240
    241 def transformation_string(transformation):
--> 242     return transformation if isinstance(transformation, str) else cloudinary.utils.generate_transformation_string(**transformation)[0]
    243

TypeError: generate_transformation_string() argument after ** must be a mapping, not unicode

Can't specify a width and/or height without a crop

I'm not sure I understand the purpose of this line:
https://github.com/cloudinary/pycloudinary/blob/master/cloudinary/utils.py#L37

if not crop and not has_layer:
    width = height = None

According to the docs (and my own usage) it's perfectly fine to give a height or width without a crop mode. However, this line causes them to be silently dropped without it.

utils.cloudinary_url() returns something like this:
('http://res.cloudinary.com/me/image/upload/test.jpg', {'width': 50})

Is there a way to chain transformations in python?

This is a contrived example, but it exhibits chaining transformations on to each other. How can I achieve something like this?

url = self.image.build_url(crop='crop', x=20, y=20, width=100, height=100)
scaled_url = url.build_url(crop='scale', width=500, height=500)

upload_image method doesn't work on python 3.4

upload_image() throws an exception

'Request' object has no attribute 'has_data'

in python 3.4. Mehods urllib.request.Request.has_data and urllib.request.Request.get_data were deprecated in Python 3.3 and have been removed in Python 3.4

Got this error using GAE

Anyone can help me ?

Thanks

Encountered unexpected error from ProtoRPC method implementation: TypeError (<type 'instance'> has type <type 'instance'>, but expected one of: str, unicode)
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/wsgi/service.py", line 181, in protorpc_service_app
response = method(instance, request)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/endpoints-1.0/endpoints/api_config.py", line 1332, in invoke_remote
return remote_method(service_instance, request)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/remote.py", line 412, in invoke_remote_method
response = method(service_instance, request)
File "/base/data/home/apps/ssprtsapp-api/1.385327187522572524/sprtsapp_api.py", line 202, in upload_cover
upload_result = upload(request.file)
File "/base/data/home/apps/s
sprtsapp-api/1.385327187522572524/lib/cloudinary/uploader.py", line 16, in upload
return call_api("upload", params, file = file, *_options)
File "/base/data/home/apps/ssprtsapp-api/1.385327187522572524/lib/cloudinary/uploader.py", line 199, in call_api
response = urllib2.urlopen(request, *_kw).read()
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(_args)
File "/base/data/home/apps/s
sprtsapp-api/1.385327187522572524/lib/cloudinary/poster/streaminghttp.py", line 172, in https_open
return self.do_open(StreamingHTTPSConnection, req)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 1189, in do_open
r = h.getresponse()
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/gae_override/httplib.py", line 522, in getresponse
*_extra_kwargs)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 270, in fetch
allow_truncated, follow_redirects, validate_certificate)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 326, in make_fetch_call
request.set_payload(payload)
File "cpp_message.pyx", line 124, in cpp_message.SetScalarAccessors.Setter (third_party/apphosting/python/protobuf/proto1/cpp_message.cc:2229)
TypeError: <type 'instance'> has type <type 'instance'>, but expected one of: str, unicode

transformation name with spaces causes 400 error

Making a call to get transformations, some of them come back with spaces in the name like this:

 {u'allowed_for_strict': False,
  u'name': u'fl_progressive,t_primary/t_t_primary@2x jpg.t_primary@2x jpg.display@2x',
  u'used': False},

Now trying to use that (ignoring issue #41 for now), generates a 400 server error:

In [10]: name = 'fl_progressive,t_primary/t_t_primary@2x jpg.t_primary@2x jpg.display@2x'

In [11]: cloudinary.api.transformation(name)
---------------------------------------------------------------------------
GeneralError                              Traceback (most recent call last)
<ipython-input-11-031ddf1dde0b> in <module>()
----> 1 cloudinary.api.transformation(name)

.../venv/lib/python2.7/site-packages/cloudinary/api.pyc in transformation(transformation, **options)
    129 def transformation(transformation, **options):
    130     uri = ["transformations", transformation_string(transformation)]
--> 131     return call_api("get", uri, only(options, "max_results"), **options)
    132
    133 def delete_transformation(transformation, **options):

.../venv/lib/python2.7/site-packages/cloudinary/api.pyc in call_api(method, uri, params, **options)
    225         # Error is parsing json
    226         e = sys.exc_info()[1]
--> 227         raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.code, body, e))
    228
    229     if "error" in result:

GeneralError: Error parsing server response (400) - . Got - No JSON object could be decoded

The fix it seems is to renencode the name using url encoding:

In [12]: name = 'fl_progressive,t_primary/t_t_primary@2x%20jpg.t_primary@2x%20jpg.display@2x'

In [13]: cloudinary.api.transformation(name)
Out[13]:
{u'allowed_for_strict': False,
 u'derived': [],
 u'info': [{u'flags': [u'progressive'], u'transformation': [u'primary']},
  {u'transformation': [u't_primary@2x jpg', u'display@2x']}],
 u'name': u'fl_progressive,t_primary/t_t_primary@2x jpg.t_primary@2x jpg.display@2x',
 u'used': False}

Exceptions raised when pycloudinary is not configured are impossible to catch with granularity

When Cloudinary is not configured, for instance because cloud_name is not included in the configuration or so forth, pycloudinary raises Exception(). This is impossible to catch and separate out from any other type of Exception subclass, so it can't be handled safely in a try/except block without risking accidentally catching termination signals, IOError, etc.

I am trying to build a reusable app with a graceful fail if the user does not have a Cloudinary account, so I would like to be able to catch this exception. In general, raising a bare Exception() instead of some kind of subclass (I think a ValueError might be appropriate in this kind of situation, but a custom subclass could work too) is not best practice in Python, largely for this reason.

I think the problem could be minimally solved by changing every instance of Exception() in the code to ValueError(), or alternatively a custom Exception subclass. This change would be backwards-compatible because anyone who is already trying to catch a bare Exception (which is not a good idea!) should also catch ValueError successfully.

Error on 'unicode' method in Python 3

Error name 'unicode' is not defined occurs in Python 3.

File: templatetags/cloudinary.py
Line: 43

38 @register.simple_tag
39 def cloudinary_direct_upload_field(field_name="image", request=None):
40     form = type("OnTheFlyForm", (Form,), {field_name : CloudinaryJsFileField() })()
41     if request:
42         cl_init_js_callbacks(form, request)
43     return unicode(form[field_name])

Deprecated CloudinaryField Argument

models.SubfieldBase, an argument to cloudinary.models.CloudinaryField was deprecated in Django 1.9. Thus, making CloudinaryField unusable in Django 1.9 and 1.10.

Cloudinaryfield in v1.1.2, public_id and failed migrations in django

I've been using cloudinary since long time, and recently noticed that the image field in database in not homogeneous, sometimes it is xxxx/xxx.jpg and /image/upload/xxx/xxx.png, and this has caused headaches.

Now, I updated to 1.1.2 and the migration fails, since the max_length is missing from the CloudinaryField, I added it there and the migration runs, but keeps saying that there is a new migration, and again puts image fields there without max_length. So, there is no way out of it I guess.

Is there a solution to this?

RemovedInDjango110Warning

i keep getting this warning even though everything works fine

python/lib/python2.7/site-packages/cloudinary/models.py:24: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.
  return meta(name, bases, d)

Configuration issue. Please help!

Here are the steps I followed to set up cloudinary in my Django app

installed cloudinary via pip.

Added this to my settings.py:

 # Cloudinary settings
CLOUDINARY = {
  'cloud_name': '[my_cloud_name]',  
'api_key': '[my_api_key]',  
 'api_secret': '[my_api_secret]',  
}

models.py looks like this:

from django.db import models
#what do I need to import here?

class Product (models.Model):
name=models.CharField(max_length=200)
image=cloudinary.models.CloudinaryField('image')
description=models.TextField()

When attempting to syncdb or runserver I get the following error:
NameError: name 'cloudinary' is not defined

Am I missing a step of configuration here? The documentation doesn't specify what I need to import into my models.py, so I am assuming I am missing something there?

Thanks in advance!

public_id UnicodeEncodeError

We are in the process of converting our images from upload to private and they way we were told was to use the api to 'upload' each one as you can't change type. Problem is some of our images have unicode in the public_id yet the uploaded can't handle it. Here is an example:

We get the following resource in a list of resources from the api:

{u'secure_url': u'https://res.cloudinary.com/pitchup-com/image/upload/v1415177888/Camping_Man%C3%A9_Guernehu%C3%A9_txftuc.jpg', u'public_id': u'Camping_Man\xe9_Guernehu\xe9_txftuc', u'format': u'jpg', u'url': u'http://res.cloudinary.com/pitchup-com/image/upload/v1415177888/Camping_Man%C3%A9_Guernehu%C3%A9_txftuc.jpg', u'backup': True, u'created_at': u'2014-11-05T08:58:08Z', u'bytes': 18311, u'height': 131, u'width': 272, u'version': 1415177888, u'type': u'upload', u'resource_type': u'image'}

We call 'upload' like so:

                meta = upload(
                    resource['url'],
                    public_id=resource['public_id'],
                    eager=eager,
                    eager_async=True,
                    tags=tags,
                    type=settings.CLOUDINARY_TYPE,
                    image_metadata=True,
                )

and then we get the following stack trace:

  File "/usr/local/lib/python2.7/dist-packages/cloudinary/uploader.py", line 16, in upload
    return call_api("upload", params, file = file, **options)
  File "/usr/local/lib/python2.7/dist-packages/cloudinary/uploader.py", line 158, in call_api
    params = utils.sign_request(params, options)
  File "/usr/local/lib/python2.7/dist-packages/cloudinary/utils.py", line 114, in sign_request
    params["signature"] = api_sign_request(params, api_secret)
  File "/usr/local/lib/python2.7/dist-packages/cloudinary/utils.py", line 120, in api_sign_request
    to_sign = "&".join(sorted([(k+"="+(",".join(v) if isinstance(v, list) else str(v))) for k, v in params_to_sign.items() if v]))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 11: ordinal not in range(128)

Issue Dumping fixtures

I get the following error when using the cloudinary field in my models:

Error: Unable to serialize database: get_db_prep_value() takes at least 3 arguments (2 given)

My models look like this:

class StoredImage(models.Model):
    image = CloudinaryField('image')
    caption = models.CharField(max_length=100)

    def __unicode__(self):
            return self.name

Use of os.fstat will fail for unflushed files

MultipartParam uses fstat to determine the size of a file object here:

self.filesize = os.fstat(fileobj.fileno()).st_size

This will only work for files which have been flush(). Other files can have buffered changes which are not yet visible to the operating system. The alternative approach of using

fileobj.seek(0, 2)
self.filesize = fileobj.tell()
fileobj.seek(0)

will always succeed, even for unflushed files. Is there any disadvantage to getting rid of fstat and replacing it with seek/tell? I believe this would help to make the library more robust.

How to pass parameters to CloudinaryField()

Right now I have in my user field for profile picture:
picture = CloudinaryField()
and it works great. The forms work and the Django Admin works perfectly. However, I want the picture to go to folder users//profile
Also, since it's a profile picture I would want it to NOT save the old one, and replace the old one with the new one. The CloudinaryField doesn't seem very customizable and curious how I would go about this.

uploading remote images

I am trying to upload an image hosted on a third party server. Here is the code I am using:

def saveEdit(request):
image = request.REQUEST.get('image','')
title = request.REQUEST.get('title','')
type = request.REQUEST.get('type','')
state = request.REQUEST.get('state','')

cimage = cloudinary.uploader.upload(image, public_id = 'img_'+request.user.__str__()+"_"+title, format='jpg')

return HttpResponse('Got '+image + " type: "+type + " state: "+state + " title:"+request.user.__str__() + "_"+title + " uploaded "+cimage.image.url)

I get the following error:
Invalid image file
Request Method: GET
Request URL: http://127.0.0.1:8000/saveEdit?image=http://app2.pixlr.com/_temp/507f95e1ec8d8337e5000002.jpg&type=jpg&state=copy&title=13838
Django Version: 1.4.1
Exception Type: Exception
Exception Value:
Invalid image file
Exception Location: /Library/Python/2.7/site-packages/cloudinary/uploader.py in call_api, line 155

I am not sure what I am doing wrong - can you help?

Thanks.

Can't set x=0 or y=0 when cropping

If the x or y parameters are set to 0 when generate_transformation_string(...) is called, the corresponding parameter will never be set in the url. If the default values for the x & y parameters were 0 then this wouldn't be an issue; but they're not.

For instance, the following two links do not render the same image:

http://res.cloudinary.com/demo/image/upload/w_300,h_200,c_crop/brown_sheep.jpg
http://res.cloudinary.com/demo/image/upload/x_0,y_0,w_300,h_200,c_crop/brown_sheep.jpg

CloudinaryField max_length needs to be specified

It looks like the max_length=100 restriction was removed in version 1.1.2, but it seems to cause problems for a new model migration. I'm running Django 1.8.2, Python 3.4.3, cloudinary 1.1.2.

Relevant commit: 73abd59

Error trace:

  Applying photos.0001_initial...Traceback (most recent call last):
  File "/home/wli/projects/hiking/.venv/lib/python3.4/site-packages/django/db/ba
ckends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
psycopg2.ProgrammingError: syntax error at or near "None"
LINE 1: ..."id" serial NOT NULL PRIMARY KEY, "image" varchar(None) NOT ...

Here's the relevant model file:

 from cloudinary.models import CloudinaryField
 from django.db import models


 class Photo(models.Model):
     image = CloudinaryField('image')

and the migration that it generated, which failed:

 from __future__ import unicode_literals

 from django.db import models, migrations
 import cloudinary.models


 class Migration(migrations.Migration):

     dependencies = [
     ]

     operations = [
         migrations.CreateModel(
             name='Photo',
             fields=[
                 ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
                 ('image', cloudinary.models.CloudinaryField(verbose_name='image')),
             ],
         ),
     ]

CloudinaryImage loses type information

upload an image with type private and see the metadata

In [19]: meta = cloudinary.uploader.upload('http://res.cloudinary.com/demo/image/upload/sample.jpg', type='private')

In [20]: meta
Out[20]:
{u'bytes': 120253,
 u'created_at': u'2015-02-04T18:39:07Z',
 u'etag': u'83340520d28b704ca4f4b019effb33dc',
 u'format': u'jpg',
 u'height': 576,
 u'public_id': u'oejox0ddaqtjt0piyzun',
 u'resource_type': u'image',
 u'secure_url': u'https://res.cloudinary.com/pitchup-com/image/private/s--kqiHRETu--/v1423075147/oejox0ddaqtjt0piyzun.jpg',
 u'signature': u'f4290d26ff6e3ecf543d8911f21dd06b327bb978',
 u'type': u'private',
 u'url': u'http://res.cloudinary.com/pitchup-com/image/private/s--kqiHRETu--/v1423075147/oejox0ddaqtjt0piyzun.jpg',
 u'version': 1423075147,
 u'width': 864}

Now create a CloudinaryImage from that metadata and store it on a model that uses CloudinaryField

In [21]: cloudinary_image = CloudinaryImage(metadata=meta)

In [22]: cloudinary_image.url
Out[22]: u'http://res-3.cloudinary.com/pitchup-com/image/private/v1423075147/oejox0ddaqtjt0piyzun.jpg'

In [23]: cloudinary_image.type
Out[23]: u'private'

In [24]: p.cloudinary_image = cloudinary_image

In [25]: p.save()

Reload the same model that was just saved.

In [26]: p = Photo.objects.get(id=p.id)

In [27]: p.cloudinary_image
Out[27]: <cloudinary.CloudinaryImage at 0x10ea3e390>

In [28]: p.cloudinary_image.type
Out[28]: 'upload'

In [29]: p.cloudinary_image.url
Out[29]: u'http://res-3.cloudinary.com/pitchup-com/image/upload/v1423075147/oejox0ddaqtjt0piyzun.jpg'

Type information is lost and url is broken.

Supported Django versions?

It's unclear to me (or I missed it) which versions of Django are supported. I'm trying to use pycloudinary with Django 1.3 and am getting

TypeError at /test/cloudinary/
simple_tag() got an unexpected keyword argument 'name'

This is due, I think, to the fact that name wasn't added as a valid arg to simple_tag until Django 1.4.

Missing an extension after transformation

Is it correct behavior that after transformation I get a link without any extension.
Basically, I have the wrong link, because I can get any image if I follow this link.

def getPublicId(filename):
    return ''.join(filename.split('/')[-1].split('.')[:-1])

def uploadCloudinary(filename, public_id=""):
    if public_id == "":
        public_id = getPublicId(filename)
    res = uploader.upload(filename, public_id = public_id)

    if 'url' in res:
        return res

def cropAndTransform(filename, x, y, w, h, public_id=""):
    if public_id == "":
        public_id = getPublicId(filename)
    res = cloudinary.utils.cloudinary_url(filename, x=x, y=y, width = w, height = h, crop = "crop", public_id=public_id)

    print res

    if 'url' in res:
        return res

#testing code
testFilename = 'http://d3sv7wwixvr3up.cloudfront.net/static/res500/s10273/10273511.1.jpg'
    testPublicId = getPublicId(testFilename)
    res = uploadCloudinary(testFilename, testPublicId)

    print cropAndTransform(res['public_id'], 50, 50, 400, 400)

And I got:

(u'http://res.cloudinary.com/name/image/upload/c_crop,h_400,w_400,x_50,y_50/102735111', {'public_id': '', 'height': 400, 'width': 400})

I can specify a format directly, but with default params I will get a wrong link

Wrong public_id in database after direct browser upload

After upgrading to v.1.1 plugin saves to the database a new format of the public_id: image/upload/v1428825384/ok9wh8hw4yspmjjlruhu.jpg. Previously the same code was saving public_id like this — v1428525785/gcfnujctdt9i0xephuzk.jpg.

It causes further errors in template tags. For example,
{% cloudinary_url photo.image resource_type="image" %}
now generates following url:

http://res.cloudinary.com/abcdefghi/image/upload/v1/image/upload/v1428825384/ok9wh8hw4yspmjjlruhu.jpg

CloudinaryField blank=True not working in 1.5.0: object of type 'NoneType' has no len()

Today I installed the latest 1.5.0 release in my Django 1.10 project, but CloudinaryField doesn't seem to be working when blank=True:

image = CloudinaryField('image', blank=True)

I'm getting the following error when accessing the object in the admin:

object of type 'NoneType' has no len()

I believe the error is connected to the from_db_value and to_python definitions in cloudinary/models.py. They are checking if value is None, but they should be checking if not value. CloudinaryField is a CharField type and the value of a blank CharField is an empty string, not None.

I am able to fix the error with the above changes, which look like this:

def from_db_value(self, value, expression, connection, context):
    if not value:
        return value
    return self.parse_cloudinary_resource(value)

def to_python(self, value):
    if isinstance(value, CloudinaryResource):
        return value
    elif isinstance(value, UploadedFile):
        return value
    elif not value:
        return value
    else:
        return self.parse_cloudinary_resource(value)

The previous version of cloudinary implemented this correctly, so I'm not sure why this was changed in 1.5.0.

delete fails when public_id has commas (,)

In [40]: public_ids
Out[40]: ['blair-castle-caravan-park/Motorhome in foreground, reception building in background']

In [41]: cloudinary.api.delete_resources(public_ids)
Out[41]:
{u'deleted': {u' reception building in background': u'not_found',
  u'blair-castle-caravan-park/Motorhome in foreground': u'not_found'},
 u'partial': False}

Seems to try split the comma even though it's already been given a list. Suspect it's on the cloudinary server end.

Can add Flask support

More of a request. If you don't have time, when I do I'll fork and try to add it myself. Then again, I'm running like crazy to build a few things as well.

CloudinaryField should be non nullable

See https://github.com/cloudinary/pycloudinary/blob/master/cloudinary/models.py#L78

If value is a blank string "", then it evaluates to False, and get_prep_value returns None instead, which then violates the not null constraint in the database when the django ORM attempts to insert the value of None.

Instead, get_prep_value should evaluate to False, and then return the default for that field if a default is set, else return None.

See PR #57 for fix and a better explanation

CloudinaryFileField In Admin Causing Errors

class UserAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserAdminForm, self).__init__(*args, **kwargs)
        try:
            username = self.instance.username
        except:
            username = "unknow"

        self.fields['image'] = CloudinaryFileField(
            options = {
                "public_id" : 'users/' + username + '/profile'
            }
        )

This is the custom Form. When I save it it says "Please correct the error below." but doesn't show the error.

Can't submit empty file in admin using CloudinaryFileField

If you submit registered model in django admin you will have following error:

Traceback:
File "/app/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1.                     response = callback(request, _callback_args, *_callback_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  2.             return self.admin_site.admin_view(view)(_args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  3.                 response = view_func(request, _args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  4.     response = view_func(request, _args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  5.         return view(request, _args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  6.         return bound_func(_args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  7.                 response = view_func(request, _args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  8.             return func(self, _args2, *_kwargs2)
    
    File "/app/lib/python2.7/site-packages/django/db/transaction.py" in inner
  9.             return func(_args, *_kwargs)
    
    File "/app/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
  10.         if form.is_valid():
    
    File "/app/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  11.     return self.is_bound and not bool(self.errors)
    
    File "/app/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  12.         self.full_clean()
    
    File "/app/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  13.     self._clean_fields()
    
    File "/app/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields
  14.                 value = field.clean(value, initial)
    
    File "/app/lib/python2.7/site-packages/django/forms/fields.py" in clean
  15.     return super(FileField, self).clean(data)
    
    File "/app/lib/python2.7/site-packages/django/forms/fields.py" in clean
  16.     value = self.to_python(value)
    
    File "/app/lib/python2.7/site-packages/cloudinary/forms.py" in to_python
  17. result = cloudinary.uploader.upload(value)
    
    File "/app/lib/python2.7/site-packages/cloudinary/uploader.py" in upload
  18. return call_api("upload", params, file = file, **options)
    File "/app/lib/python2.7/site-packages/cloudinary/uploader.py" in call_api
  19.   datagen, headers = multipart_encode({'file': file})
    
    File "/app/lib/python2.7/site-packages/poster/encode.py" in multipart_encode
  20. headers = get_headers(params, boundary)
    
    File "/app/lib/python2.7/site-packages/poster/encode.py" in get_headers
  21. headers['Content-Length'] = str(get_body_size(params, boundary))
    
    File "/app/lib/python2.7/site-packages/poster/encode.py" in get_body_size
  22. size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))
    
    File "/app/lib/python2.7/site-packages/poster/encode.py" in
  23. size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))
    
    File "/app/lib/python2.7/site-packages/poster/encode.py" in get_size
  24.         valuesize = len(self.value)
    

Bug: async flag during upload is ignored

Below is an example call for uploading a video from an external source (say S3 bucket).

 cloudinary.uploader.upload(video_url,
          async = True,
          public_id = cloudinary_id,
          resource_type = "video",
          eager = [
            {"streaming_profile" : "full_hd", "format" : "m3u8"},
            {"streaming_profile" : "full_hd", "format" : "mpd"},
          ],
          eager_async = True
        )

When I pass async = True. This parameter is not passed on the to final API call that is sent to the cloudinary.

When I dug deeper, I found that build_upload_params in https://github.com/cloudinary/pycloudinary/blob/master/cloudinary/utils.py#L542 does not include async while build the params list.

Gravatar Support

Hi Cloudinary Gravatar,

I'm asking for a gravatar support how it already exists in the ruby libary.

Thanks for your help!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.