Python image and video upload

Clo

udinary provides an API for uploading images, videos and any other type of files to the cloud. Files uploaded to Cloudinary are safely stored in the cloud with secure backups and revision history. Cloudinary's API allows for secure uploads from your server, directly from your visitor's browser or mobile app, or via a remote public URL.
Cloudinary's Python SDK wraps Cloudinari's upload API and simplifies integration. Python methods can be used to easily upload Python images and videos to the cloud, and Python view helper methods can be used to upload to Cloudinary directly from the browser.
This page describes common usage patterns for uploading Python images and videos with Cloudinary.
For details on all available upload options and parameters, see the Media Upload documentation and Upload Methods for the Upload API Reference.

Note: Regardless of your framework, most of what Cloudinary offers can be implemented using Python. As stated in the documentation, some features are only available in Django.
Tip: Cloudinary's Upload widget provides an alternative to using the CloudinarySDK to add upload functionality to applications, eliminating the need to develop internal interactive upload functionality. The Upload widget is an interactive, feature-rich, easy-to-integrate UI that enables you to add Cloudinary upload support to your website. Widgets can be easily embedded into web applications with just a few lines of JavaScript code. See the Upload widget documentation for details.

 Server-Side Upload
You can upload images, videos, or any other raw files to Cloudinary from your Python code. Uploads are done over HTTPS using a secure protocol based on your account's api_key and api_secret parameters.
 

Python Image Upload
The following method uploads an image to the cloud:

def upload(file, **options)

For example, to upload a local image file named "my_image.jpg":

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

The file to upload can be specified as a local path, remote HTTP or HTTPS URL, whitelisted bucket (S3 or Google storage) URL, base64 data URI, or FTP URL. See File Source Options for details.
For details on all available upload options and parameters, see the Media Upload documentation and Upload Methods for the Upload API Reference.
 

Python Video Upload
You upload videos in exactly the same way as images. However, the upload method only supports uploading files up to 100 MB. To upload larger videos, use the upload_large method, which uploads large files to the cloud in chunks.
The upload_large method has the same signature and options as the upload method, with the addition of an optional chunk_size parameter (20 MB by default).
The following example uploads Dog.mp4 to Cloudinary and stores it in a two-level folder structure with public ID dog_closeup. It also performs two eager transformations, resizing the video to a square and a small rectangle.

cloudinary.uploader.upload_large("dog.mp4", 
  resource_type = "video",
  public_id = "myfolder/mysubfolder/dog_closeup",
  chunk_size = 6000000,
  eager = [
    { "width": 300, "height": 300, "crop": "pad", "audio_codec": "none"},
    { "width": 160, "height": 100, "crop": "crop", "gravity": "south",
        "audio_codec": "none"}],
  eager_async = true,
  eager_notification_url = "https://mysite.example.com/notify_endpoint")

Upload Responses
By default, uploads are performed synchronously. Once complete, uploaded images or videos are immediately available for conversion and delivery. The upload call returns a hash with the following contents:

{   
  u'bytes': 29802,
  u'created_at': u'2017-06-25T17:20:30Z',
  u'format': u'jpg',
  u'height': 282,
  u'public_id': u'hl22acprlomnycgiudor',
  u'resource_type': u'image',
  u'secure_url': u'https://res.cloudinary.com/demo/image/upload/v1571218039/hl22acprlomnycgiudor.jpg',
  u'signature': u'10594f028dbc23e920fd084f8482394798edbc68',
  u'type': u'upload',
  u'url': u'http://res.cloudinary.com/demo/image/upload/v1571218039/hl22acprlomnycgiudor.jpg',
  u'version': 1571218039,
  u'width': 292
}

 Note: If you need the upload response to return the actual image instead of a hash, then use the upload_resource method (it's the same as the upload method except for the response).

The response includes HTTP and HTTPS URLs for accessing the uploaded media asset, as well as additional information about the uploaded asset: public id, resource type, width and height, file format, file size in bytes, signature used to verify the response, etc.
 

Data Upload Options
Cloudinary's Python library supports file uploads from a variety of sources.
You can upload images by specifying a local path to the image file. For example:

cloudinary.uploader.upload('/home/my_image.jpg')

You can provide the created IO object:

cloudinary.uploader.upload(open('/tmp/image1.jpg', 'rb'))

If your image is already public online, you can specify its remote HTTP URL instead of uploading the actual data. In this case, Cloudinary will fetch the image from its remote URL for you. This option allows for faster migration of existing images. Here is an example:

cloudinary.uploader.upload('https://www.example.com/image.jpg')

 If you have existing images in an Amazon S3 bucket, you can point Cloudinary to its S3 URL. NOTE - This option requires a quick manual setup. Contact us and we will guide you on how to allow Cloudinary access to your relevant S3 bucket.

cloudinary.uploader.upload('s3://my-bucket/my-path/my-file.jpg')

Note: If you are writing an application in Django where users upload images via a web form, you can pass parameters to Django's request. File upload method:

cloudinary.uploader.upload(request.FILES['file'])

 Django Forms and Models
If you're using Django, you can use Cloudinary's helper classes to integrate Cloudinari's upload functionality into your forms and models. As shown in the example below, you can define the model class Photo in the models.py file. This class has an image field of CloudinaryField class.

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

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

in the form. py file defines a PhotoForm class that has a form field named image of CloudinaryFileField class (by default).

from django.forms import ModelForm      
from .models import Photo

class PhotoForm(ModelForm):
  class Meta:
      model = Photo

 view. py file defines a view called upload that displays an HTML upload form and handles posting of image files. These images are uploaded from the Django server to Cloudinary by the CloudinaryFileField class.

from django import forms
from django.http import HttpResponse

from cloudinary.forms import cl_init_js_callbacks      
from .models import Photo
from .forms import PhotoForm

def upload(request):
  context = dict( backend_form = PhotoForm())

  if request.method == 'POST':
    form = PhotoForm(request.POST, request.FILES)
    context['posted'] = form.instance
    if form.is_valid():
        form.save()

  return render(request, 'upload.html', context)

The following HTML template includes a form for uploading images to your server for upload to Cloudinary:

{% load cloudinary %}
{% load url from future %}

{% block body %}
  <div id='backend_upload'>
    <form action="{% url "photo_album.views.upload" %}" method="post"
          enctype="multipart/form-data">
      {% csrf_token %}
      {
   
   { backend_form }}
      <input type="submit" value="Upload">
    </form>
  </div>  
{% endblock %}

 With the image ID stored, the image or transformed version of the image can now be embedded using the cloudinary template tag:

{% load cloudinary %}      
{% cloudinary photo.image format="jpg" width=120 height=80 crop="fill" %}

Additionally, you can assign tags, apply transformations, or specify any of Cloudinary's upload options when initializing the CloudinaryFileField class.

from django.forms import ModelForm      
from cloudinary.forms import CloudinaryFileField      
from .models import Photo

class PhotoForm(ModelForm):
  class Meta:
    model = Photo
  image = CloudinaryFileField(
    attrs = { 'style': "margin-top: 30px" }, 
    options = { 
      'tags': "directly_uploaded",
      'crop': 'limit', 'width': 1000, 'height': 1000,
      'eager': [{ 'crop': 'fill', 'width': 150, 'height': 100 }]
    })

 Uploading directly from the browser
The upload example shown above allows your server-side Python code to upload media assets to Cloudinary. In this flow, if you have a web form that allows users to upload images or videos, the data for the media file is first sent to your server and then uploaded to Cloudinary.
A more efficient and robust option is to allow users to upload images and videos in client-side code directly from the browser to Cloudinary, rather than through the server. This approach allows for faster uploads and a better user experience. It also reduces the load on the server and reduces the complexity of Python applications.
You can upload files directly from the browser using signed or unsigned calls to the upload endpoint, as shown in the Uploading Multiple Files Using a Form example.
For signed uploads from client-side code, the secure signature must be generated in server-side Python code. You can use the api_sign_request method to generate a SHA signature:

cloudinary.utils.api_sign_request(params_to_sign, api_secret)

For a complete list of parameters available for signed uploads, see Upload Methods in the Upload API Reference. 

Guess you like

Origin blog.csdn.net/std7879/article/details/127782820