-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathapi.py
108 lines (90 loc) · 4.9 KB
/
api.py
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""Модуль 19"""
import json
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
class PetFriends:
"""апи библиотека к веб приложению Pet Friends"""
def __init__(self):
self.base_url = "https://petfriends1.herokuapp.com/"
def get_api_key(self, email: str, passwd: str) -> json:
"""Метод делает запрос к API сервера и возвращает статус запроса и результат в формате
JSON с уникальным ключем пользователя, найденного по указанным email и паролем"""
headers = {
'email': email,
'password': passwd,
}
res = requests.get(self.base_url+'api/key', headers=headers)
status = res.status_code
result = ""
try:
result = res.json()
except json.decoder.JSONDecodeError:
result = res.text
return status, result
def get_list_of_pets(self, auth_key: json, filter: str = "") -> json:
"""Метод делает запрос к API сервера и возвращает статус запроса и результат в формате JSON
со списком наденных питомцев, совпадающих с фильтром. На данный момент фильтр может иметь
либо пустое значение - получить список всех питомцев, либо 'my_pets' - получить список
собственных питомцев"""
headers = {'auth_key': auth_key['key']}
filter = {'filter': filter}
res = requests.get(self.base_url + 'api/pets', headers=headers, params=filter)
status = res.status_code
result = ""
try:
result = res.json()
except json.decoder.JSONDecodeError:
result = res.text
return status, result
def add_new_pet(self, auth_key: json, name: str, animal_type: str,
age: str, pet_photo: str) -> json:
"""Метод отправляет (постит) на сервер данные о добавляемом питомце и возвращает статус
запроса на сервер и результат в формате JSON с данными добавленного питомца"""
data = MultipartEncoder(
fields={
'name': name,
'animal_type': animal_type,
'age': age,
'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'image/jpeg')
})
headers = {'auth_key': auth_key['key'], 'Content-Type': data.content_type}
res = requests.post(self.base_url + 'api/pets', headers=headers, data=data)
status = res.status_code
result = ""
try:
result = res.json()
except json.decoder.JSONDecodeError:
result = res.text
print(result)
return status, result
def delete_pet(self, auth_key: json, pet_id: str) -> json:
"""Метод отправляет на сервер запрос на удаление питомца по указанному ID и возвращает
статус запроса и результат в формате JSON с текстом уведомления о успешном удалении.
На сегодняшний день тут есть баг - в result приходит пустая строка, но status при этом = 200"""
headers = {'auth_key': auth_key['key']}
res = requests.delete(self.base_url + 'api/pets/' + pet_id, headers=headers)
status = res.status_code
result = ""
try:
result = res.json()
except json.decoder.JSONDecodeError:
result = res.text
return status, result
def update_pet_info(self, auth_key: json, pet_id: str, name: str,
animal_type: str, age: int) -> json:
"""Метод отправляет запрос на сервер о обновлении данных питомуа по указанному ID и
возвращает статус запроса и result в формате JSON с обновлённыи данными питомца"""
headers = {'auth_key': auth_key['key']}
data = {
'name': name,
'age': age,
'animal_type': animal_type
}
res = requests.put(self.base_url + 'api/pets/' + pet_id, headers=headers, data=data)
status = res.status_code
result = ""
try:
result = res.json()
except json.decoder.JSONDecodeError:
result = res.text
return status, result