-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
147 lines (123 loc) · 6.58 KB
/
api.py
File metadata and controls
147 lines (123 loc) · 6.58 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import json
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
class PetFriends:
"""API-библиотека к веб-приложению PetFriends"""
def __init__(self):
self.base_url = "https://petfriends.skillfactory.ru/"
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 с текстом уведомления об успешном удалении."""
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
def add_new_pet_simple(self, auth_key: json, name: str, animal_type: str,
age: str) -> json:
"""Метод отправляет на сервер данные о добавляемом питомце без фотографии и возвращает
статус запроса на сервер и результат в формате JSON с данными добавленного питомца"""
data = MultipartEncoder(
fields={
'name': name,
'animal_type': animal_type,
'age': age
})
headers = {'auth_key': auth_key['key'], 'Content-Type': data.content_type}
res = requests.post(self.base_url + 'api/create_pet_simple', 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 add_pet_photo(self, auth_key: json, pet_id: str, pet_photo: str) -> json:
"""Метод отправляет запрос на сервер о добавлении фотографии питомца по указанному ID
и возвращает статус запроса и result в формате JSON с обновлёнными данными питомца"""
data = MultipartEncoder(
fields={'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/set_photo/' + pet_id, 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