Sample to use after OAuth authentication of BOX API with Python

Introduction

I will introduce a sample that uses the API of the file sharing cloud service "BOX" from Python.

Various people have introduced how to use the API, including the "BOX" document. I didn't have any information close to what I wanted to do, so I wrote an article.

What I wanted to do

https://github.com/box/box-python-sdk/blob/master/docs/usage/authentication.md First of all, I wanted to run the following sample code on this SDK site quickly.

client = Client(auth)
user = client.user().get()
print('User ID is {0}'.format(user.id))

If you just move it, you can manually pass OAuth authentication, but this time I tried to realize OAuth by a simple method.

environment

Mac   10.14.6
Python  3.7.4
boxsdk  2.6.1 

Preparation

Install BOX SDK

Please install with pip or other tools according to your environment.

pip install boxsdk

Register the app on the BOX management screen

https://developer.box.com


スクリーンショット 2019-12-22 20.22.49.png
スクリーンショット 2019-12-22 20.19.46.png
スクリーンショット 2019-12-22 20.17.20.png

Copy the client ID and client sensitive code displayed here to the source.

Enter "http: // localhost: 8080" for the redirect URI.

Sample code

sample.py


from boxsdk import OAuth2, Client
import webbrowser
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs

#Get from the BOX management screen
CLIENT_ID = 'Client ID'
CLIENT_SECRET = 'Client sensitive code'

#Set on the BOX management screen
REDIRECT_URI = 'http://localhost:8080'

HOST = '127.0.0.1'
PORT = 8080

#Variable to put the authentication code issued by BOX
global auth_code

auth_code = None

oauth = OAuth2(
    client_id = CLIENT_ID,
    client_secret = CLIENT_SECRET,
    store_tokens = None     #Token storage is omitted this time
)

#Start OAuth
auth_url, csrf_token = oauth.get_authorization_url(REDIRECT_URI)

#Start your browser and enter your BOX ID and password
#REDIRECT when entered_Redirected to URI
webbrowser.open(auth_url)

# REDIRECT_Processing when URI is hit
class ServerHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        global auth_code
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b"<h1>Authenticated</h1>")
        parsed_path = urlparse(self.path)
        query = parse_qs(parsed_path.query)
        auth_code = query['code'][0]

with socketserver.TCPServer((HOST, PORT), ServerHandler) as server:
    print('http server start')
    # server.serve_forever()    # Ctrl+Continue processing until there is an interrupt such as C being pressed
    server.handle_request()     #Exit after processing one request
    print('http server shutdown')

# auth_Now that you have the code, you can use the API from here
access_token, refresh_token = oauth.authenticate(auth_code)

client = Client(oauth)
me = client.user().get()
print('My user ID is {0}'.format(me.id))

Run

important point

Finally

I wanted to run it in JupyterLab, so I wrote it in one file.

It's easy to start a simple web server in Python. This time, I like the fact that the web server is terminated after processing one request.

On the contrary, I don't like the fact that the do_GET method assigns directly to a global variable. Is there a beautiful way to write it?

I don't think it's working strangely, but I'm not familiar with Python yet, so I'd appreciate it if you could point out any strange points or improvements.

Recommended Posts

Sample to use after OAuth authentication of BOX API with Python
I tried to get the authentication code of Qiita API with Python.
Use Trello API with python
Hit the Twitter API after Oauth authentication with Django
How to use Service Account OAuth and API with Google API Client for python
Use subsonic API with python3
Easy to use Nifty Cloud API with botocore and python
Python: How to use async with
[Python] Use Basic/Digest authentication with Flask
How to use OpenPose's Python API
How to use FTP with Python
[Python] How to use Typetalk API
[September 2020 version] Explains the procedure to use Gmail API with Python
How to use Python Kivy (reference) -I translated Kivy Language of API reference-
[Python] Summary of how to use pandas
[Introduction to Python] Let's use foreach with Python
[Python2.7] Summary of how to use unittest
How to use CUT command (with sample)
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
Sample to convert image to Wavelet with Python
[Question] How to use plot_surface of python
I tried to get the movie information of TMDb API with Python
[Python] How to use two types of type ()
I want to use MATLAB feval with python
Procedure to use TeamGant's WEB API (using python)
Specify the Python executable to use with virtualenv
Use multiple versions of python environment with pyenv
Summary of how to use MNIST in Python
Try slack OAuth authentication with flask (Slack API V2)
How to specify attributes with Mock of python
The easiest way to use OpenCV with python
Story of trying to use tensorboard with pytorch
Sample to send slack notification with python lambda
I want to use Temporary Directory with Python2
How to use tkinter with python in pyenv
Summary of studying Python to use AWS Lambda
[Python] Mention to multiple people with Slack API
Flow to complete Slack authentication with Flask (Python)
Memo to create your own Box with Pepper's Python
[First API] Try to get Qiita articles with Python
[Python] Use JSON with Python
I tried to summarize how to use matplotlib of python
Change IP settings to ACL of conoha with python
Use mecab with Python3
[Chapter 5] Introduction to Python with 100 knocks of language processing
Use DynamoDB with Python
How to use python interactive mode with git bash
How to use Python Kivy ① ~ Basics of Kv Language ~
Let's use the Python version of the Confluence API module.
Use Python 3.8 with Anaconda
[Chapter 3] Introduction to Python with 100 knocks of language processing
Use python with docker
After hitting the Qiita API with Python to get a list of articles for beginners, we will visit the god articles
Specify MinGW as the compiler to use with Python
[Chapter 2] Introduction to Python with 100 knocks of language processing
Site notes to help you use NetworkX with Python
[Python] Use the Face API of Microsoft Cognitive Services
How to operate Discord API with Python (bot registration)
Use python installed with Pyenv with Sublime REPL of Sublime Text 3
[Chapter 4] Introduction to Python with 100 knocks of language processing