Blame view

pyros_api.py 5.01 KB
4b904014   Alexis Koralewski   Add view to get s...
1
#!/usr/bin/env python3
0318e3c9   Alexis Koralewski   Add tests for F05...
2
3
4
5
6
7
8
9
from email import header
import os
import requests
import sys
import yaml
import click
import getpass

98621b46   Alexis Koralewski   add DRF, pyros ap...
10
11
12
13
14
15

class PyrosAPI:
    """
    Request Pyros API with an PyrosUser account linked to the username and password
    """
    BASE_PYROS_URL = "http://localhost:8000/api/"
540fa833   Etienne Pallier   New requirements....
16
    #BASE_PYROS_URL = "http://pyros.irap.omp.eu/api/"
4b904014   Alexis Koralewski   Add view to get s...
17

0318e3c9   Alexis Koralewski   Add tests for F05...
18
    def __init__(self) -> None:
98621b46   Alexis Koralewski   add DRF, pyros ap...
19
20
21
22
23
24
25
        """
        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
        """
0318e3c9   Alexis Koralewski   Add tests for F05...
26
        self.get_token()
98621b46   Alexis Koralewski   add DRF, pyros ap...
27

0318e3c9   Alexis Koralewski   Add tests for F05...
28
    def get_token(self):
98621b46   Alexis Koralewski   add DRF, pyros ap...
29
30
31
32
33
34
35
        """
        get the authentification token linked to the user account

        Args:
            username : Username of the user (mail adress)
            password : Password of the user
        """
0318e3c9   Alexis Koralewski   Add tests for F05...
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
        if os.path.exists("TOKEN"):
            with open("TOKEN", "r") as token_file:
                self.token = token_file.read()
                return
        else:
            url = f"{self.BASE_PYROS_URL}api-token-auth/"
            print("Token needs to be generated, you need to authentificate to PyROS :")
            username = input("Enter your username: ")

            try:
                password = getpass.getpass()
            except Exception as error:
                print('ERROR', error)
        request = requests.post(
            url, data={"username": username, "password": password})
        if request.status_code != 200:
            print("Authentification failed, please retry")
            exit(1)
98621b46   Alexis Koralewski   add DRF, pyros ap...
54
55
        json_response = request.json()
        self.token = json_response["token"]
0318e3c9   Alexis Koralewski   Add tests for F05...
56
57
        with open("TOKEN", "w+") as token_file:
            token_file.write(self.token)
98621b46   Alexis Koralewski   add DRF, pyros ap...
58

4b904014   Alexis Koralewski   Add view to get s...
59
    def get_url(self, url: str) -> dict:
98621b46   Alexis Koralewski   add DRF, pyros ap...
60
61
62
63
64
65
66
67
68
        """
        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
        """
0318e3c9   Alexis Koralewski   Add tests for F05...
69
        headers = {"Authorization": f"Token {self.token}"}
98621b46   Alexis Koralewski   add DRF, pyros ap...
70
71
72
73

        request = requests.get(self.BASE_PYROS_URL+url, headers=headers)
        return request.json()

4b904014   Alexis Koralewski   Add view to get s...
74
    def submit_sequence_file(self, file: str) -> dict:
98621b46   Alexis Koralewski   add DRF, pyros ap...
75
76
77
78
79
80
81
82
83
84
        """
        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 = {
0318e3c9   Alexis Koralewski   Add tests for F05...
85
            "Authorization": f"Token {self.token}",
98621b46   Alexis Koralewski   add DRF, pyros ap...
86
87
88
            'Content-type': 'application/json',
        }
        url = f"{self.BASE_PYROS_URL}submit_sequence"
4b904014   Alexis Koralewski   Add view to get s...
89
        yaml_file = open(file, "r")
98621b46   Alexis Koralewski   add DRF, pyros ap...
90
91
        sequence_file_as_dict = yaml.safe_load(yaml_file)
        print(f"File content : {sequence_file_as_dict}")
0318e3c9   Alexis Koralewski   Add tests for F05...
92
93
        request = requests.put(url, headers=headers,
                               json=sequence_file_as_dict)
98621b46   Alexis Koralewski   add DRF, pyros ap...
94
95
96
        print(f"Request status code {request.status_code}")
        return request.json()

0318e3c9   Alexis Koralewski   Add tests for F05...
97
    def get_sequences_for_period(self, start_date: str, end_date: str) -> dict:
4b904014   Alexis Koralewski   Add view to get s...
98
99
100
101
102
103
104
105
106
107
        """
        Return all the sequence between two dates
        Args:
            start_date : start date of the period we want to retrieve (format : day/month/year, example : 13/02/2022)
            end_date : end date of the period we want to retrieve (same format as start_date)
        Returns:
            dict : Json object that represents the response of the API
        """
        url = f"{self.BASE_PYROS_URL}full_sequences/get_sequences_for_period/"
        headers = {"Authorization": f"Token {self.token}"}
0318e3c9   Alexis Koralewski   Add tests for F05...
108
109
        response = requests.get(
            url, params={"start_date": start_date, "end_date": end_date}, headers=headers)
4b904014   Alexis Koralewski   Add view to get s...
110
111
        return response.json()

0318e3c9   Alexis Koralewski   Add tests for F05...
112
113
114
115
116
117
118
    def logout(self):
        url = f"{self.BASE_PYROS_URL}logout/"
        header = {"Authorization": f"Token {self.token}"}
        response = requests.get(url, headers=header)
        return response.content.decode("utf-8")


4b904014   Alexis Koralewski   Add view to get s...
119
@click.group()
4b904014   Alexis Koralewski   Add view to get s...
120
@click.pass_context
0318e3c9   Alexis Koralewski   Add tests for F05...
121
122
def cli(ctx):
    ctx.obj = PyrosAPI()
4b904014   Alexis Koralewski   Add view to get s...
123
124


c658ec80   Alexis Koralewski   Rename command fo...
125
@cli.command("get_sequences_for_period", help="Get sequences for a period of date (start/end)")
4b904014   Alexis Koralewski   Add view to get s...
126
127
128
129
130
131
132
133
@click.argument("start_date")
@click.argument("end_date")
@click.pass_obj
def get_sequences_for_period(api, start_date: str, end_date: str):
    response = api.get_sequences_for_period(start_date, end_date)
    print(response)


0318e3c9   Alexis Koralewski   Add tests for F05...
134
135
136
137
138
139
140
141
142
143
144
@cli.command("logout", help="Logout")
@click.pass_obj
def logout(api):
    response = api.logout()
    if os.path.exists("TOKEN"):
        os.remove("TOKEN")
    print("Token deleted")
    print(response)


@cli.command("submit_sequence", help="Submit a sequence file")
4b904014   Alexis Koralewski   Add view to get s...
145
146
147
148
149
150
@click.argument("file_path")
@click.pass_obj
def submit_sequence(api, file_path):
    response = api.submit_sequence_file(file_path)
    print(response)

0318e3c9   Alexis Koralewski   Add tests for F05...
151
152

@cli.command("query_url", help="Query an url to retrieve data")
4b904014   Alexis Koralewski   Add view to get s...
153
154
155
156
157
158
@click.argument("url")
@click.pass_obj
def query_url(api, url):
    response = api.get_url(url)
    print(response)

0318e3c9   Alexis Koralewski   Add tests for F05...
159

4b904014   Alexis Koralewski   Add view to get s...
160
161
if __name__ == '__main__':
    cli(obj={})