Created
October 24, 2021 21:53
-
-
Save bart02/9004960212b006e88ff3e1a6faacff02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # USAGE: | |
| # Get creds on https://stepik.org/oauth2/applications/ | |
| # s = Stepik('client_id', | |
| # 'client_secret') | |
| # link = s.upload_file(path_to file, stepik_filename, course=102606) | |
| from os import PathLike | |
| from typing import Union | |
| import requests as r | |
| from requests.auth import HTTPBasicAuth | |
| class Stepik: | |
| api_host = 'https://stepik.org' | |
| def __init__(self, client_id: str, client_secret: str): | |
| auth = HTTPBasicAuth(client_id, client_secret) | |
| response = r.post('{}/oauth2/token/'.format(self.api_host), | |
| data={'grant_type': 'client_credentials'}, | |
| auth=auth) | |
| self.token = response.json().get('access_token', None) | |
| if not self.token: | |
| raise Exception('Unable to authorize with provided credentials') | |
| def upload_file(self, filename: Union[PathLike, str], stepik_filename: str = None, **data): | |
| api_url = '{}/api/attachments'.format(self.api_host) | |
| with open(filename, "rb") as a_file: | |
| if stepik_filename is None: | |
| file_dict = {'file': a_file} | |
| else: | |
| file_dict = {'file': (stepik_filename, a_file)} | |
| response = r.post(api_url, headers={'Authorization': 'Bearer ' + self.token}, data=data, files=file_dict) | |
| return self.api_host + response.json()['attachments'][0]['file'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment