Coder Social home page Coder Social logo

muxinc / mux-python Goto Github PK

View Code? Open in Web Editor NEW
47.0 41.0 13.0 1.01 MB

Official Mux API wrapper for python projects, supporting both Mux Data and Mux Video.

License: MIT License

Python 94.17% Shell 0.10% Makefile 0.04% Mustache 5.69% Ruby 0.01%
mux video video-streaming video-processing video-analytics python

mux-python's Introduction

Mux Python Banner

PyPI | Mux Docs | Mux API Reference

Mux Python

Official Mux API wrapper for python projects, supporting both Mux Data and Mux Video.

Mux Video is an API-first platform, powered by data and designed by video experts to make beautiful video possible for every development team.

Mux Data is a platform for monitoring your video streaming performance with just a few lines of code. Get in-depth quality of service analytics on web, mobile, and OTT devices.

Not familiar with Mux? Check out https://mux.com/ for more information.

Requirements

Python 2.7 or 3.4+

Compatibility with Ubuntu 14.04

Mux uses cross signed TLS root certificates, which may not be compatible with Ubuntu 14.04 LTS as documented in this issue. We suggest upgrading to a later LTS operating system if you encounter this issue.

Installation

Via pip

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

(you may need to run pip with root permission)

Via source

git checkout https://github.com/muxinc/mux-python.git
cd mux-python
python setup.py install --user

Getting Started

Overview

Mux Python is a code generated lightweight wrapper around the Mux REST API and reflects them accurately. This has a few consequences you should watch out for:

  1. For almost all API responses, the object you're looking for will be in the data field on the API response object, as in the example below. This is because we designed our APIs with similar concepts to the JSON:API standard. This means we'll be able to return more metadata from our API calls (such as related entities) without the need to make breaking changes to our APIs. We've decided not to hide that in this library.

  2. We don't use a lot of object orientation. For example API calls that happen on a single asset don't exist in the asset class, but are API calls in the AssetsApi which require an asset ID.

Authentication

To use the Mux API, you'll need an access token and a secret. Details on obtaining these can be found here in the Mux documentation.

Its up to you to manage your token and secret. In our examples, we read them from MUX_TOKEN_ID and MUX_TOKEN_SECRET in your environment.

Example Usage

Below is a quick example of using mux-python to list the Video assets stored in your Mux account.

Be sure to also checkout the examples directory:

There's also example usage of every API call (also used for testing):

import os
import mux_python
from mux_python.rest import ApiException

# Authentication Setup
configuration = mux_python.Configuration()
configuration.username = os.environ['MUX_TOKEN_ID']
configuration.password = os.environ['MUX_TOKEN_SECRET']

# API Client Initialization
assets_api = mux_python.AssetsApi(mux_python.ApiClient(configuration))

# List Assets
print("Listing Assets: \n")
try:
    list_assets_response = assets_api.list_assets()
    for asset in list_assets_response.data:
        print('Asset ID: ' + asset.id)
        print('Status: ' + asset.status)
        print('Duration: ' + str(asset.duration) + "\n")
except ApiException as e:
    print("Exception when calling AssetsApi->list_assets: %s\n" % e)

Exceptions & Error Handling

All exceptions inherit from ApiException, you can catch it as in the example above, or you can catch one of the more specific exceptions below. You can check the fields error_type and error_messages in all Exceptions to see what error the Mux API reported.

NotFoundException

NotFoundException is thrown when a resource is not found. This is useful when trying to get an entity by its ID, for example get_asset("some-id-here") in the AssetsApi.

UnauthorizedException

UnauthorizedException is thrown when Mux cannot authenticate your request. You should check you have configured your credentials correctly.

ServiceException

ServiceException is thrown when Mux returns a HTTP 5XX Status Code. If you encounter this reproducibly, please get in touch with [email protected].

Documentation

Be sure to check out the documentation in the docs directory.

Issues

If you run into problems, please raise a GitHub issue, filling in the issue template. We'll take a look as soon as possible.

Contributing

Please do not submit PRs against this package. It is generated from our OpenAPI definitions - Please open an issue instead!

License

MIT License. Copyright 2019 Mux, Inc.

mux-python's People

Contributors

aelchertmux avatar alexdechaves avatar dcrodman avatar eropple avatar jaredsmith avatar jsanford8 avatar philcluff avatar sbdchd 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

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mux-python's Issues

Could we add license information to PyPI metadata?

Hello!

Currently pip show mux-python returns blank License info:

Name: mux-python
Version: 3.10.0
Summary: Mux API
Home-page: https://github.com/muxinc/mux-python
Author: Mux DevEx
Author-email: [email protected]
License:
Location: ...
Requires: python-dateutil, six, urllib3
Required-by:

Some company's custom package index might check for eligible values in License field before allowing the package to be added. Curious if we could add the license info here? Thanks!

Uploading asset in Python is not working

Hi

This is my code to upload my video to Mux via Python:

assets_api = mux_python.AssetsApi(mux_python.ApiClient(configuration))

# Create an Asset
input_settings = [mux_python.InputSettings(url=modelVideoFirebaseURL)]
create_asset_request = mux_python.CreateAssetRequest(input=input_settings, playback_policy=[mux_python.PlaybackPolicy.PUBLIC])
create_asset_response = assets_api.create_asset(create_asset_request=create_asset_request)

However, when I upload it I cannot view it in Assets (it says video is not public and is not viewable).

Also, when I view my video client side it says "Unsupported error" and that it is not playable on my browser.. But if I play a directly uploaded video on my client side it works.. The API does not work. Please help

Impossible to import Exceptions

A number of exceptions are thrown by muxpython but none of them can by caught by clients because:

  1. They are not exported.
  2. the function rest() in __init__.py is making it impossible to import them directly from rest.py

The simplest solution would be to export them all in __init__.py.

I'm happy to make a pull request if you'd like?

Create .mp4 stream instead of m3u8

Hello, I am trying to create the mp4 format stream for playback. However setting the parameter :
new_asset_settings = mux_python.CreateAssetRequest(playback_policy=[mux_python.PlaybackPolicy.PUBLIC], mp4_support = "standard")

This gives the response :
'new_asset_settings': {'input': None, 'master_access': None, 'mp4_support': 'standard', 'normalize_audio': False, 'passthrough': None, 'per_title_encode': None, 'playback_policy': None, 'test': None},

How can I use .mp4 format with the playback ID to make it work?

Realtime engagement counts not working properly for views

Hello!
I’m trying to obtain data for the real-time engagement counts. but looks like it’s not working correctly.
I use code from the example, like a

# video_id = ''  # Enter your video id here
    signing_key_id = '2pFHlr6WB9npEwHvONm8CRTZOxjpJHXyPCpjEGDIwZI'  # Enter your signing key id here
    private_key_base64 = 'HERE IS THE PRIVATE KEY AS IT WAS RECEIVED FROM DASHBOARD'  # Enter your base64 encoded private key here

    private_key = base64.b64decode(private_key_base64)
    time_issued = int(time.time()) + 3600
    payload = {
        'vid': video_id,
        'exp': time_issued,  # 1 hour
        'kid': signing_key_id
    }
    encoded = jwt.encode(payload, private_key, algorithm="RS256")
    return jsonify({
        'result': {
            'token': encoded,
            'expire': time_issued
        }
    })

So, if i use it like this - i will receive python error binascii.Error: Incorrect padding . It can be fixed with simple adding == at the end of private key string, and after that code is working fine - i receive encoded token.
But when I try to hit the url https://stats.mux.com/counts?token=TOKEN_TEXT_HERE i receive error :

{
    "error": {
        "type": "forbidden",
        "messages": [
            "Signing key not found."
        ]
    }
}

Anything we can do here?

How to enable MP4 on already created asset

Dear coolleagues. Thanks so much for the amazing work done.

I am trying to update an asset, just like presented here, but passing the asset id to be updated from the list I got from assets_api.list_assets(), instead of an assets_api.create_asset(create_asset_request) object.

Error message I got is:

mux_python.exceptions.NotFoundException: (404)
Reason: Not Found
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'max-age=0, private, must-revalidate', 'Content-Length': '121', 'Content-Type': 'application/json; charset=utf-8', 'Date': 'Thu, 16 Sep 2021 12:57:44 GMT', 'Server': 'Mux API Server v1.131.2', 'X-Request-Id': 'FqVOyN_5MDLCiXUBWLmD'})
HTTP response body: {"error":{"type":"not_found","messages":["The requested resource either doesn't exist or you don't have access to it."]}}

The asset id exists and is the correct one. So, I am wondering if:

  • to do an update I need a special access?
  • to update an asset the same must be an recently created asset and not an old one?

thanks in advance

Change "hls_segment_type" from .ts to .fmp4

Hello, Currently my live stream is broadcasting the chunks in ".ts" format. I would like to change the "HLS_segement_type" to .fmp4. Is there a parameter I can tune to convert the .ts chunk into .fmp4?

DeprecationWarning: HTTPResponse.getheaders() is deprecated and will be removed in urllib3 v2.1.0

When using mux-python I get this warning:

DeprecationWarning: HTTPResponse.getheaders() is deprecated and will be removed in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.

The problem is here at this line:

return self.urllib3_response.getheaders()

It should be changed to:

return self.urllib3_response.headers

If I prepare a pull request, are you willing to accept it? Thanks

Documentation for creating audio-only assets

Is there any documentation on creating audio-only assets? I see the announcement from years ago that it became available as a feature, but I'm struggling to find relevant documentation.

Lower video resolution before download

Is there such an option? E.g. defining the width and height of the video before downloading it with mux_python.AssetsApi(mux_python.ApiClient(config)).get_asset()?

Direct Upload Signed URL PUT failing with CORS error

I generated a signed_url by passing appropriate cors_origin as per my domain yet the generated URL, I am unable to PUT the video file from browser.

Here is the error I am getting:
Access to fetch at 'https://storage.googleapis.com/video-storage-us-east1-....' from origin 'https://youreact.tv' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

And here is my backend code that generates the signed URL:

uploads_api = mux_python.DirectUploadsApi(mux_python.ApiClient(configuration))

create_asset_request = mux_python.CreateAssetRequest(playback_policy=[mux_python.PlaybackPolicy.PUBLIC],passthrough="123")

create_upload_request = mux_python.CreateUploadRequest(timeout=3600, new_asset_settings=create_asset_request, cors_origin="https://youreact.tv")

create_upload_response = uploads_api.create_direct_upload(create_upload_request)

and here is the client side code that tries to PUT the video file:

const upload = async (file) => {

        const upload = UpChunk.createUpload({
            endpoint: '{{ signed_url }}',                
            file: file            
        });

        console.log("res:",upload) 
    }

Additional cases where UnauthorizedException may raise?

Are there undocumented situations which might cause Mux to return a 401 (and therefore cause the client to raise an UnauthorizedException)?

I can't really share the code, but I can share the context:

  • We are connecting to Mux via the Python client to create assets and create/delete tracks.
  • We are currently using the same database locally and when deployed to production.
  • We are currently using the same codebase locally and when deployed to production.
  • We are currently using the same access tokens locally and when deployed to production.

Attempts to create or delete assets functions well enough in local. Attempts to create or delete assets raises an UnauthorizedException across our development, staging, and production environments.

The kicker, though, is that this all worked as recently as a week ago, and there were no new deploys to our production system before the issues started arising.

I'm wondering if there is potential that Mux would blacklist a server? All of our environments are deployed via managed Docker containers in DigitalOcean, so that seems the most noteworthy similarity between the three environments having issue.

Upload local file(not from URL) and get playbackID as response

Hello.

Case 1: Use the MUX direct upload SDK for react

I created a component for frontend which works but the problem there is that the response from event doesn't contain the playbackID for the uploaded video. I find the video on my MUX assets, but I want to get the playbackID directly from response and that is not there. Is something I miss here?

Case 2: Uploade video from python wrapper

I can upload an asset using mux-python package, but when I want to upload it, it's required the video URL... I want to upload a file in my platform, so it would be a local file (not an URL). Can you help me here?

My goal is to upload a video (with the upload interface from MUX-UPLOADER or by creating my own interface in frontend) and get as a response the assetID and playbackID which I will store in my DB to be able to create a video content platform.

Thanks

"max_continuous_duration" parameter

Please add an example for "max_continuous_duration". There is no example available on how to use the "duration" parameter for a live stream.
I am not able to find how to set the duration in API request.
I am getting the following error : "'Server': 'Mux API Server v1.158.3', 'X-Request-Id': 'FvnrJ5bJcVMDeN0Hi62B'})
HTTP response body: {"error":{"type":"invalid_parameters","messages":["Cannot use max continuous duration with test live streams"]}}"

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.