-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
135 lines (114 loc) · 6.21 KB
/
Copy pathapi.py
File metadata and controls
135 lines (114 loc) · 6.21 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
import requests
import json
from requests_toolbelt.multipart.encoder import MultipartEncoder
class PetFriends:
def __init__(self):
self.base_url = "https://petfriends.skillfactory.ru/"
self.idp = ""
def get_api_key(self, email,password):
'''делаем запрос к Api сервера и возвращаем статусзапроса и результат
в формате JSON с уникальным ключом пользователя, найденого по email , passwor'''
headers = {
'email': email,
'password': password
}
res = requests.get(self.base_url + 'api/key', headers=headers)
status = res.status_code
result = ""
try:
result = res.json()
except:
result = res.text
return status, result
def get_list_of_pets(self,auth_key,filter):
'''Метод делает запрос к 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:
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
def post_add_new_pet_without_photo(self,auth_key:json, name:str,animal_type:str, age:str) -> json:
"""добовляем питомца без фото"""
headers = {'auth_key': auth_key['key']}
data = {'name':name,'animal_type':animal_type,'age':age}
res = requests.post(self.base_url + 'api/create_pet_simple', headers=headers, data=data)
status = res.status_code
try:
result = res.json()
self.idp = res.json().get("id")
except json.decoder.JSONDecodeError:
result = res.text
return status, result
def post_change_pet_photo(self, auth_key: json, pet_id: str, pet_photo: str) -> json:
"""Метод отправляет запрос на сервер о добавлении фото к данным питомуа по указанному ID и
возвращает статус запроса и результат в формате JSON с обновлённыи данными питомца"""
data = MultipartEncoder(fields={'pet_photo': (pet_photo, open(pet_photo, 'rb'), 'images/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
return status, result