Get a token for conoha in python

Needed to do various things using the official API

A little explanation

code

get_token.py


#!/usr/bin/env python

import requests
import json
import datetime
import os

class get_token:
        def __init__(self): #Initialization
                self.values = {"auth":{"passwordCredentials":{"username":"","password":""},"tenantId":""}}
 
        def set(self,user,passwd,tnid): #Obtaining user name, password, and tenant ID
                self.user = user
                self.passwd = passwd
                self.tnid = tnid
 
        def getter(self): #Token acquisition process
                get_flag = True #Flag initialization
                if os.path.exists("./my_token_expire.txt"): #If you already have a token, check the expiration date in the file
                        with open('my_token_expire.txt','r') as f:
                                tk_ex = f.read()
                                tk_ex = tk_ex.replace("T"," ")
                                tk_ex = tk_ex.replace("Z","")
                                tk_ex_time =  datetime.datetime.strptime(tk_ex, '%Y-%m-%d %H:%M:%S')
                                today =  datetime.datetime.utcnow()

                                if today < tk_ex_time: #If the deadline is valid, do not get
                                        get_flag = False
                                        print 'active token'
                                else:
                                        print 'expired token'

                else:
                        print 'token file not found'


                if get_flag: #Get token if flag is set
                        url = 'https://identity.tyo1.conoha.io/v2.0/tokens'
                        self.values["auth"]["passwordCredentials"]["username"]=self.user
                        self.values["auth"]["passwordCredentials"]["password"]=self.passwd
                        self.values["auth"]["tenantId"]=self.tnid
                        head = {'Accept':'application/json'}
                        r = requests.post(url,data=json.dumps(self.values),headers=head)
                        with open('my_token.json','w') as f:
                                f.write(r.text)
                                f.flush()

                        with open('my_token.json','r') as f:
                                jsonData = json.loads(f.read())

                        with open('my_token.txt','w') as f:
                                f.write(jsonData["access"]["token"]["id"])
                                f.flush()
                                print 'write token'

                        with open('my_token_expire.txt','w') as f:
                                f.write(jsonData["access"]["token"]["expires"])
                                f.flush()
                                print 'expires='+jsonData["access"]["token"]["expires"]


def token_get_main(user,passwd,tenantId):
        token_get = get_token()
        token_get.set(user,passwd,tenantId)
        token_get.getter()

if __name__ == '__main__':
        user = 'User name'
        ps = 'User password'
        tenantId = 'Tenant ID'
        token_get_main(user,ps,tenantId)

The acquired JSON format data is saved in `my_token.json```, the token is saved in my_token.txt``, and the token expiration date is saved in ``my_token_expire.txt``. ..

Recommended Posts

Get a token for conoha in python
How to get a stacktrace in python
Get date in Python
Get a ticket for a theme park with python
Get the caller of a function in Python
Get a glimpse of machine learning in Python
Get YouTube Comments in Python
Take a screenshot in Python
Create a function in Python
Create a dictionary in Python
Get last month in python
Search for strings in Python
Try searching for a million character profile in Python
Techniques for sorting in Python
Get Terminal size in Python
Make a bookmarklet in Python
BigQuery-If you get a Reason: responseTooLarge error in Python
Explicitly get EOF in python
Python: Get a list of methods for an object
Draw a heart in Python
Get Evernote notes in Python
About "for _ in range ():" in python
Set a proxy for Python pip (described in pip.ini)
Get Japanese synonyms in Python
Create a child account for connect with Stripe in Python
Get the number of specific elements in a python list
Building a development environment for Android apps-creating Android apps in Python
Developed a library to get Kindle collection list in Python
How to define multiple variables in a python for statement
I tried "How to get a method decorated in Python"
How to get the last (last) value in a list in Python
Get Leap Motion data in Python.
Check for memory leaks in Python
I get a UnicodeDecodeError in mecab-python3
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
[python] Manage functions in a list
Check for external commands in python
Hit a command in Python (Windows)
I get a KeyError in pyclustering.xmeans
Get the desktop path in Python
Draw a scatterplot matrix in python
ABC166 in Python A ~ C problem
Write A * (A-star) algorithm in Python
Get the script path in Python
Create a binary file in Python
Solve ABC036 A ~ C in Python
Write a vim plugin in Python
Write a depth-first search in Python
Implementing a simple algorithm in Python 2
Create a Kubernetes Operator in Python
Get the desktop path in Python
Run unittests in Python (for beginners)
Get the host name in Python
Solve ABC037 A ~ C in Python
Run a simple algorithm in Python
Draw a CNN diagram in Python
Create a random string in Python
Schedule a Zoom meeting in Python
Get started with Python in Blender
When writing a program in Python