0
0 комментариев

Есть сервис, который дает токен на 15 минут. Решил написать функцию, которая проверяет истек ли период токена и, если да, то получает новый и записывает его в token.txt вместе с текущим временем. Вот код:

def auth():
    global url # url = 'http://path_to_server'
    global aParams # aParams = {'login': 'user', 'pass': 'pass'}
    with open('token.txt', 'r') as data:
        load = json.load(data)
        loaded = load['tstmp']
        print('__', loaded)
        if int(datetime.datetime.now().strftime('%s')) - int(loaded) >= 900:
            print('old token:', load['key'])
            return load['key']
        else:
            with open('token.txt', 'w') as data:
                get_token = requests.get(url + '/api/auth', params=aParams).text
                timestamp = int(datetime.datetime.now().strftime('%s'))
                load = json.dump({'key': get_token, 'tstmp': timestamp}, data)
                print('new token', load['key'])
                return load['key']

получаю ошибку:

"/Volumes/My Files/Python/slack/slackenv/bin/python" "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/getreport.py"
__ 1469428422
Traceback (most recent call last):
old token: 243c2e38-f329-aeda-4d03-4a631f247415
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/getreport.py", line 85, in <module>
<function auth at 0x101a7ad08>
    get_report(t=auth())
__ 1469428422
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/getreport.py", line 77, in get_report
old token: 243c2e38-f329-aeda-4d03-4a631f247415
    r = requests.get(reportUrl, cookies=str(token)).json()
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/requests/api.py", line 71, in get
    return request('get', url, params=params, **kwargs)
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/requests/api.py", line 57, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/requests/sessions.py", line 461, in request
    prep = self.prepare_request(req)
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/requests/sessions.py", line 371, in prepare_request
    cookies = cookiejar_from_dict(cookies)
  File "/Volumes/My Files/Python/slack/slackenv/lib/python3.5/site-packages/requests/cookies.py", line 469, in cookiejar_from_dict
    cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
TypeError: string indices must be integers

Подскажите в чем ошибка?

функция get_report:

def get_report(t):
# по логике функция получает токен, подставляет его в куки и получает отчет в json.
    global url
    global reportUrl
    global auth
    token = t
#    if df is None:
#        df = datetime.date.strftime(datetime.date.today(), '%Y-%m-%dT00:00:00')
#    if dt is None:
#        dt = datetime.date.strftime(datetime.date.today(), '%Y-%m-%dT23:59:59')
    r = requests.get(reportUrl, cookies=str(token)).json()
    report = json.dump(r, ensure_ascii=False, indent=4, sort_keys=True)
    requests.get(url + 'api/logout?key=' + str(token))
    print('logged out')
    print(report)
    return report
 
 
get_report(t=auth())


Добавить комментарий