pyros_api.py
2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import requests, sys, yaml
class PyrosAPI:
"""
Request Pyros API with an PyrosUser account linked to the username and password
"""
BASE_PYROS_URL = "http://localhost:8000/api/"
def __init__(self, username : str, password : str ) -> None:
"""
Initialize PyrosAPI class by getting the authentification token required to use the API
Args:
username : Username of the user (mail adress)
password : Password of the user
"""
self.get_token(username, password)
def get_token(self,username : str,password : str):
"""
get the authentification token linked to the user account
Args:
username : Username of the user (mail adress)
password : Password of the user
"""
url = f"{self.BASE_PYROS_URL}api-token-auth/"
request = requests.post(url, data={"username":username,"password":password})
json_response = request.json()
self.token = json_response["token"]
print(f"Token is {self.token}")
def get_url(self,url : str) -> dict:
"""
Query the url and return the response as json
Args:
url : Url to be requested without the base url of the website
Returns:
dict : Json object that represents the response of the API
"""
headers = {"Authorization" : f"Token {self.token}"}
request = requests.get(self.BASE_PYROS_URL+url, headers=headers)
return request.json()
def submit_sequence_file(self,file : str) -> dict:
"""
Submit sequence file by querying the API via PUT method
Args:
file : File path to the sequence file to be uploaded
Returns:
dict : Json object that represents the response of the API
"""
headers = {
"Authorization" : f"Token {self.token}",
'Content-type': 'application/json',
}
url = f"{self.BASE_PYROS_URL}submit_sequence"
yaml_file = open(file,"r")
sequence_file_as_dict = yaml.safe_load(yaml_file)
print(f"File content : {sequence_file_as_dict}")
request = requests.put(url, headers=headers, json=sequence_file_as_dict)
print(f"Request status code {request.status_code}")
return request.json()
def main():
username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
yaml_file = None
api = PyrosAPI(username,password)
if len(sys.argv) > 4 and sys.argv[4]:
yaml_file = sys.argv[4]
print(api.submit_sequence_file(yaml_file))
else:
print(username,password,url)
print(api.get_url(url))
if __name__ == "__main__":
main()