LoginSignup
0
0

More than 5 years have passed since last update.

pythonでconohaのトークンを取得する

Last updated at Posted at 2016-08-10

公式のAPIを使用して色々やるのに必要

ちょっと説明

  • Requestsでデータを取得
  • 得られるデータはJSON形式なのでjsonモジュールで処理
  • トークンの期限が有効なときは取得しない

コード

get_token.py
#!/usr/bin/env python

import requests
import json
import datetime
import os

class get_token:
        def __init__(self): #初期化
                self.values = {"auth":{"passwordCredentials":{"username":"","password":""},"tenantId":""}}

        def set(self,user,passwd,tnid): #ユーザ名、パスワード、テナントIDの取得
                self.user = user
                self.passwd = passwd
                self.tnid = tnid

        def getter(self): #トークンの取得処理
                get_flag = True #フラグの初期化
                if os.path.exists("./my_token_expire.txt"): #すでにトークンを取得していれば、ファイルの中の期限を確認
                        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: #期限が有効であれば、取得しない
                                        get_flag = False
                                        print 'active token'
                                else:
                                        print 'expired token'

                else:
                        print 'token file not found'


                if get_flag: #フラグが立っていればトークンの取得
                        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 = 'ユーザ名'
        ps = 'ユーザパスワード'
        tenantId = 'テナントID'
        token_get_main(user,ps,tenantId)

取得したJSON形式のデータは`my_token.json`へ保存、トークンは`my_token.txt`へ保存、トークンの期限は`my_token_expire.txt`へ保存されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0