GithubHelp home page GithubHelp logo

joshdeanmcdonald / box-python-sdk Goto Github PK

View Code? Open in Web Editor NEW

This project forked from box/box-python-sdk

0.0 2.0 0.0 2.84 MB

Box SDK for Python

Home Page: http://opensource.box.com/box-python-sdk/

License: Apache License 2.0

Python 99.85% Smarty 0.15%

box-python-sdk's Introduction

box-python-sdk

image

image

Documentation Status

image

image

Installing

pip install boxsdk

Authorization

The Box API uses OAuth2 for auth. The SDK makes it relatively painless to work with OAuth2 tokens.

Get the authorization url

from boxsdk import OAuth2

oauth = OAuth2(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    store_tokens=your_store_tokens_callback_method,
)

auth_url, csrf_token = oauth.get_authorization_url('http://YOUR_REDIRECT_URL')

store_tokens is a callback used to store the access token and refresh token. You might want to define something like this:

def store_tokens(access_token, refresh_token):
    # store the tokens at secure storage (e.g. Keychain)

The SDK will keep the tokens in memory for the duration of the Python script run, so you don't always need to pass store_tokens.

Authenticate (get access/refresh token)

If you navigate the user to the auth_url, the user will eventually get redirected to http://YOUR_REDIRECT_URL?code=YOUR_AUTH_CODE. After getting the code, you will be able to use the code to exchange for access token and fresh token.

The SDK handles all the work for you; all you need to do is run:

# Make sure that the csrf token you get from the `state` parameter
# in the final redirect URI is the same token you get from the
# get_authorization_url method.
assert 'THE_CSRF_TOKEN_YOU_GOT' == csrf_token
access_token, refresh_token = oauth.authenticate('YOUR_AUTH_CODE')

Create an authenticated client

from boxsdk import Client

client = Client(oauth)

And that's it! You can start using the client to do all kinds of cool stuff and the SDK will handle the token refresh for you automatically.

Usage

Get user info

me = client.user(user_id='me').get()
print 'user_login: ' + me['login']

Get folder info

root_folder = client.folder(folder_id='0').get()
print 'folder owner: ' + root_folder.owned_by['login']
print 'folder name: ' + root_folder['name']

Get items in a folder

items = client.folder(folder_id='0').get_items(limit=100, offset=0)

Create subfolder

# creates folder structure /L1/L2/L3
client.folder(folder_id='0').create_subfolder('L1').create_subfolder('L2').create_subfolder('L3')
shared_link = client.folder(folder_id='SOME_FOLDER_ID').get_shared_link()

Get file name

client.file(file_id='SOME_FILE_ID').get()['name']

Rename an item

client.file(file_id='SOME_FILE_ID').rename('bar-2.txt')

Move an item

client.file(file_id='SOME_FILE_ID').move(client.folder(folder_id='SOME_FOLDER_ID'))

Get content of a file

client.file(file_id='SOME_FILE_ID').content()

Lock/unlock a file

client.file(file_id='SOME_FILE_ID').lock()
client.file(file_id='SOME_FILE_ID').unlock()
client.search('some_query', limit=100, offset=0)

Events

# Get events
client.events().get_events(limit=100, stream_position='now')

# Generate events using long polling
for event in client.events().generate_events_with_long_polling():
    pass  # Do something with the event

# Get latest stream position
client.events().get_latest_stream_position()

Metadata

# Get metadata
client.file(file_id='SOME_FILE_ID').metadata().get()

# Create metadata
client.file(file_id='SOME_FILE_ID').metadata().create({'key': 'value'})

# Update metadata
metadata = client.file(file_id='SOME_FILE_ID').metadata()
update = metadata.start_update()
update.add('/key', 'new_value')
metadata.update(update)

As-User

The Client class and all Box objects also have an as_user method.

as-user returns a copy of the object on which it was called that will make Box API requests as though the specified user was making it.

See https://box-content.readme.io/#as-user-1 for more information about how this works via the Box API.

# Logged in as admin, but rename a file as SOME USER
user = client.user(user_id='SOME_USER_ID')
client.as_user(user).file(file_id='SOME_FILE_ID').rename('bar-2.txt')


# Same thing, but using file's as_user method
client.file(file_id='SOME_FILE_ID').as_user(user).rename('bar-2.txt')

Box Developer Edition

The Python SDK supports your Box Developer Edition applications.

Developer Edition support requires some extra dependencies. To get them, simply

pip install boxsdk[jwt]

Instead of instantiating your Client with an instance of OAuth2, instead use an instance of JWTAuth.

from boxsdk import JWTAuth

auth = JWTAuth(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    enterprise_token='YOUR_ENTERPRISE_TOKEN',
    rsa_private_key_file_sys_path='CERT.PEM',
    store_tokens=your_store_tokens_callback_method,
)

access_token = auth.authenticate_instance()

from boxsdk import Client

client = Client(auth)

This client is able to create application users:

ned_stark_user = client.create_user('Ned Stark')

These users can then be authenticated:

ned_auth = JWTAuth(
   client_id='YOUR_CLIENT_ID',
   client_secret='YOUR_CLIENT_SECRET',
   enterprise_token='YOUR_ENTERPRISE_TOKEN',
   rsa_private_key_file_sys_path='CERT.PEM',
   store_tokens=your_store_tokens_callback_method,

) ned_auth.authenticate_app_user(ned_stark_user) ned_client = Client(ned_auth)

Requests made with ned_client (or objects returned from ned_client's methods) will be performed on behalf of the newly created app user.

Contributing

See CONTRIBUTING.rst.

Developer Setup

Create a virtual environment and install packages -

mkvirtualenv boxsdk
pip install -r requirements-dev.txt

Testing

Run all tests using -

tox

The tox tests include code style checks via pep8 and pylint.

The tox tests are configured to run on Python 2.6, 2.7, 3.3, 3.4, and PyPy.

Support

Need to contact us directly? Email [email protected] and be sure to include the name of this project in the subject. For questions, please contact us directly rather than opening an issue.

Copyright 2015 Box, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

box-python-sdk's People

Contributors

alexei-matveev avatar aptxkid avatar djgoku avatar hnguyen08 avatar jeff-meadows avatar jmoldow avatar potrebic avatar samkuehn avatar walgitrus avatar

Watchers

 avatar  avatar

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.