Giter Club home page Giter Club logo

filestack-python's Introduction

Filestack Python

This is the official Python SDK for Filestack - API and content management system that makes it easy to add powerful file uploading and transformation capabilities to any web or mobile application.

Resources

To learn more about this SDK, please visit our API Reference

Installing

Install filestack with pip

pip install filestack-python

or directly from GitHub

pip install git+https://github.com/filestack/filestack-python.git

Quickstart

The Filestack SDK allows you to upload and handle filelinks using two main classes: Client and Filelink.

Uploading files with filestack.Client

from filestack import Client
client = Client('<YOUR_API_KEY>')

new_filelink = client.upload(filepath='path/to/file')
print(new_filelink.url)

Uploading files using Filestack Intelligent Ingestion

To upload files using Filestack Intelligent Ingestion, simply add intelligent=True argument

new_filelink = client.upload(filepath='path/to/file', intelligent=True)

FII always uses multipart uploads. In case of network issues, it will dynamically split file parts into smaller chunks (sacrificing upload speed in favour of upload reliability).

Working with Filelinks

Filelink objects can by created by uploading new files, or by initializing filestack.Filelink with already existing file handle

from filestack import Filelink, Client

client = Client('<APIKEY>')
filelink = client.upload(filepath='path/to/file')
filelink.url  # 'https://cdn.filestackcontent.com/FILE_HANDLE

# work with previously uploaded file
filelink = Filelink('FILE_HANDLE')

Basic Filelink Functions

With a Filelink, you can download to a local path or get the content of a file. You can also perform various transformations.

file_content = new_filelink.get_content()

size_in_bytes = new_filelink.download('/path/to/file')

filelink.overwrite(filepath='path/to/new/file')

filelink.resize(width=400).flip()

filelink.delete()

Transformations

You can chain transformations on both Filelinks and external URLs. Storing transformations will return a new Filelink object.

transform = client.transform_external('http://<SOME_URL>')
new_filelink = transform.resize(width=500, height=500).flip().enhance().store()

filelink = Filelink('<YOUR_HANDLE'>)
new_filelink = filelink.resize(width=500, height=500).flip().enhance().store()

You can also retrieve the transformation url at any point.

transform_candidate = client.transform_external('http://<SOME_URL>')
transform = transform_candidate.resize(width=500, height=500).flip().enhance()
print(transform.url)

Audio/Video Convert

Audio and video conversion works just like any transformation, except it returns an instance of class AudioVisual, which allows you to check the status of your video conversion, as well as get its UUID and timestamp.

av_object = filelink.av_convert(width=100, height=100)
while (av_object.status != 'completed'):
    print(av_object.status)
    print(av_object.uuid)
    print(av_object.timestamp)

The status property makes a call to the API to check its current status, and you can call to_filelink() once video is complete (this function checks its status first and will fail if not completed yet).

filelink = av_object.to_filelink()

Security Objects

Security is set on Client or Filelink classes upon instantiation and is used to sign all API calls.

from filestack import Security

policy = {'expiry': 253381964415}  # 'expiry' is the only required key
security = Security(policy, '<YOUR_APP_SECRET>')
client = Client('<YOUR_API_KEY', security=security)

# new Filelink object inherits security and will use for all calls
new_filelink = client.upload(filepath='path/to/file')

# you can also provide Security objects explicitly for some methods
size_in_bytes = filelink.download(security=security)

You can also retrieve security details straight from the object:

>>> policy = {'expiry': 253381964415, 'call': ['read']}
>>> security = Security(policy, 'SECURITY-SECRET')
>>> security.policy_b64
'eyJjYWxsIjogWyJyZWFkIl0sICJleHBpcnkiOiAyNTMzODE5NjQ0MTV9'
>>> security.signature
'f61fa1effb0638ab5b6e208d5d2fd9343f8557d8a0bf529c6d8542935f77bb3c'

Webhook verification

You can use filestack.helpers.verify_webhook_signature method to make sure that the webhooks you receive are sent by Filestack.

from filestack.helpers import verify_webhook_signature

# webhook_data is raw content you receive
webhook_data = b'{"action": "fp.upload", "text": {"container": "some-bucket", "url": "https://cdn.filestackcontent.com/Handle", "filename": "filename.png", "client": "Computer", "key": "key_filename.png", "type": "image/png", "size": 1000000}, "id": 50006}'

result, details = verify_webhook_signature(
    '<YOUR_WEBHOOK_SECRET>',
    webhook_data,
    {
      'FS-Signature': '<SIGNATURE-FROM-REQUEST-HEADERS>',
      'FS-Timestamp': '<TIMESTAMP-FROM-REQUEST-HEADERS>'
    }
)

if result is True:
    print('Webhook is valid and was generated by Filestack')
else:
    raise Exception(details['error'])

Versioning

Filestack Python SDK follows the Semantic Versioning.

filestack-python's People

Contributors

bkwi avatar gowthamraj198 avatar hueyl77 avatar jdeepee avatar kracekumar avatar santhoshmoback avatar sidmitra avatar solyony avatar staturecrane 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

Watchers

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

filestack-python's Issues

Basic examples have broken imports

Hi team, there is some issue with your requests import from filestack.utils, recent commit break?

ImportError                               Traceback (most recent call last)
<ipython-input-6-b909760ba0a1> in <module>
----> 1 from filestack import Client, Security
      2 
      3 # policy expires on 5/6/2099
      4 policy = {'call': ['read', 'remove', 'store'], 'expiry': 4081759876}
      5 

~/venvs/filestack/lib/python3.6/site-packages/filestack/__init__.py in <module>
     29 
     30 
---> 31 from .models.client import Client
     32 from .models.filelink import Filelink
     33 from .models.security import Security

~/venvs/filestack/lib/python3.6/site-packages/filestack/models/__init__.py in <module>
----> 1 from .filelink import Filelink
      2 from .client import Client
      3 from .transformation import Transformation
      4 from .security import Security
      5 from .audiovisual import AudioVisual

~/venvs/filestack/lib/python3.6/site-packages/filestack/models/filelink.py in <module>
      1 from filestack import config
----> 2 from filestack.utils import requests
      3 from filestack.mixins import CommonMixin
      4 from filestack.mixins import ImageTransformationMixin
      5 

ImportError: cannot import name 'requests'

Support configuring timeouts on Filestack client

As a user of the Filestack client, I would like to be able to specify a maximum duration of time that I am willing to wait for Filestack API operations to complete before deciding that the request/operation has timed out. This is a pretty common feature of API client libraries.

Limitation on "requests" version

The requests requested is limited to just version 2.23.0 hence any other version higher or lower isn't compatible and causes pip conflicts
requests==2.23.0

AudioVisual should have uuid

Hi, the av_convert method returns a AudioVisual object but there is no reference to know what is the conversion request id and hence it is impossible to know which handle has been converted from the callback.

Add Minify CSS task

New minify_css task should be added to ImageTransformationMixin

Filestack docs can be found here

This task takes two arguments: level and gzip.
It should be implemented similarly to resize, crop or rotate.

Expected usage:

filelink.minify_css()
filelink.minify_css(level=1, gzip=False)

Tests are required.

For reference, please see PR #38

filelink.get_metadata returns response object when error

The following returns invalid metadata.

filelink = client.upload(url)
metadata = filelink.get_metadata()
print(metadata)

TypeError: 'Response' object does not support item assignment
<Response [400]>
  1. The metadata url returned 400 bad request.
  2. The utils.make_call should throw an exception instead of returning the failed response without errors.

Cheers

endpoint missing in documentations

Hi i am building an app with Filestack API python sdk while i am uploading the image it is redirecting to upload.filestackapi.com and this endpoint is neither in filestack.com/docs nor in python sdk API reference i couldnt find this endpoint, i am using pythonanywhere web services for my deployed app but it is not working they need the proof that this endpoint is belong to filestack or not but unfortunately i didnt find this endpoint in docs so hence kindly add this to documentation or api reference so my app would work. thanks

"Parameters are inalid" error

Full error message:
{"error":"Parameters are inalid","c":"8be69984-9626-48b9-88fe-201863fa4958","i":"UPL-us-e-1-22","t":1516679849}

I'm not sure what this error means, but it happens on upload.

Add Auto Image Conversion task

New auto_image task should be added to ImageTransformationMixin

Filestack docs can be found here

This task takes no arguments. It should be implemented similarly to flip, flop or monochrome.

Expected usage:

filelink.auto_image()

Tests are required.

For reference, please see PR #38

Unable to upload files to filestack using security policy and app secret

Hi,
I'm using filestack to upload files.
Here's the code that I'm using

def main():


policy = {"call":["pick","store"],"expiry":1673461800}

p = Policy(policy,"APP_SECRET")
respSign = p.signature_params()

fpclient = FilepickerClientSecure('S3')
resp = fpclient.store_from_url("https://cdn.shopify.com/s/files/1/1390/1485/products/image_aacb3d0a-bed1-4265-99c5-5ec95dbf441b_1024x1024.jpg?v=1643292001",
                         respSign['policy'],
                         respSign['signature']
                        )


respStore = fpclient.store_local_file("/Users/user1/Desktop/user1.pdf",
                        respSign['policy'],
                        respSign['signature']
                        )
print(respStore)

The URL generated for the above calls are:

https://www.filestackapi.com/api/store/S3?policy=eyJjYWxsIjogWyJwaWNrIiwgInN0b3JlIl0sICJleHBpcnkiOiAxNjczNDYxODAwfQ%3D%3D&signature=fb265f83579e29ef11c047790a1b7a62755fa127d0b1f29d39ae8ab55ef395ae

When I pass the API_KEY in the URL query, I'm able to upload the files.

But if I use just the signature and policy I'm unable to upload the files. I get the following error.

response= Invalid Application status-code= 200

Can you please tell me how to fix this error ? Is it possible to upload files with policy and signature ?

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.