-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
205 lines (174 loc) · 7.31 KB
/
classes.py
File metadata and controls
205 lines (174 loc) · 7.31 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from abc import ABC, abstractmethod
import json
import os
from datetime import datetime
import requests
from utils import get_USD_conversion_rate, get_from_and_up_salary
class JobSiteAPI(ABC):
@abstractmethod
def get_vacancies(self, filter_word):
pass
class HeadHunterAPI(JobSiteAPI):
def get_vacancies(self, filter_word):
params = {
'text': f'NAME:{filter_word}',
'per_page': 50,
'only_with_salary': True,
'area': 113
}
req = requests.get('https://api.hh.ru/vacancies', params)
jsObj = json.loads(req.content.decode())
req.close()
return jsObj
class SuperJobAPI(JobSiteAPI):
__api_key = os.getenv('SJ_API_KEY')
def get_vacancies(self, filter_word):
headers = {
'X-Api-App-Id': self.__api_key
}
params = {
'keyword': filter_word,
'no_agreement': 1,
'country_id': 1,
'count': 50
}
req = requests.get('https://api.superjob.ru/2.0/vacancies/', headers=headers, params=params)
jsObj = json.loads(req.content.decode())
req.close()
return jsObj
class Vacancy:
def __init__(self, dictionary):
for key, value in dictionary.items():
setattr(self, key, value)
@property
def published_at(self):
try:
date = datetime.strptime(self.published[:10], '%Y-%m-%d')
return f'{date.day}-{date.month}-{date.year}'
except ValueError:
return self.published
except TypeError:
date = datetime.fromtimestamp(int(self.published))
return f'{date.day}-{date.month}-{date.year}'
@property
def approximate_salary(self):
if self.salary_from and self.salary_to:
mean_salary = (self.salary_from + self.salary_to) // 2
else:
mean_salary = max(self.salary_from, self.salary_to)
if 'usd' == self.currency.lower():
return mean_salary * get_USD_conversion_rate()
else:
return mean_salary
def __str__(self):
response_0 = f'Вакансия на должность: {self.name} в компанию {self.employer} в г. {self.area}\n'
if self.salary_from and self.salary_to:
response_1 = f'Зарплата от {self.salary_from} до {self.salary_to} {self.currency}\n'
elif self.salary_from:
response_1 = f'Зарплата от {self.salary_from} {self.currency}\n'
else:
response_1 = f'Зарплата до {self.salary_to} {self.currency}\n'
response_2 = f'Требования\Описание:\n{self.requirements}\nТип занятости: {self.employment_type}\n' \
f'Вакансия опубликована {self.published_at}\n{self.url}\n{"-" * 80}'
return response_0 + response_1 + response_2
def __le__(self, other):
if isinstance(other, Vacancy):
return self.approximate_salary <= other.approximate_salary
return None
def __lt__(self, other):
if isinstance(other, Vacancy):
return self.approximate_salary < other.approximate_salary
return None
def __ge__(self, other):
if isinstance(other, Vacancy):
return self.approximate_salary >= other.approximate_salary
return None
def __gt__(self, other):
if isinstance(other, Vacancy):
return self.approximate_salary > other.approximate_salary
return None
class Saver:
def __init__(self):
self.vacancies = []
def add_vacancy(self, vacancy):
if isinstance(vacancy, Vacancy):
self.vacancies.append(vacancy)
else:
print('Error, next time input valid vacancy')
def add_hh_vacancies(self, search_query):
vacancies_hh = HeadHunterAPI().get_vacancies(search_query)
for vacancy_hh in vacancies_hh['items']:
try:
dic = {
'name': vacancy_hh['name'],
'employer': vacancy_hh['employer']['name'],
'url': vacancy_hh['alternate_url'],
'area': vacancy_hh['area']['name'],
'salary_from': vacancy_hh['salary']['from'] if vacancy_hh['salary']['from'] else 0,
'salary_to': vacancy_hh['salary']['to'] if vacancy_hh['salary']['to'] else 0,
'currency': vacancy_hh['salary']['currency'],
'requirements': vacancy_hh['snippet']['requirement'],
'published': vacancy_hh['published_at'],
'employment_type': vacancy_hh['employment']['name']
}
except KeyError:
continue
vacancy = Vacancy(dic)
self.add_vacancy(vacancy)
def add_sj_vacancies(self, search_query):
vacancies_sj = SuperJobAPI().get_vacancies(search_query)
for vacancy_sj in vacancies_sj['objects']:
try:
dic = {
'name': vacancy_sj['profession'],
'employer': vacancy_sj['client']['title'],
'url': vacancy_sj['link'],
'area': vacancy_sj['town']['title'],
'salary_from': vacancy_sj['payment_from'] if vacancy_sj['payment_from'] else 0,
'salary_to': vacancy_sj['payment_to'] if vacancy_sj['payment_to'] else 0,
'currency': vacancy_sj['currency'],
'requirements': vacancy_sj['candidat'],
'published': vacancy_sj['date_published'],
'employment_type': vacancy_sj['type_of_work']['title']
}
except KeyError:
continue
vacancy = Vacancy(dic)
self.add_vacancy(vacancy)
def delete_vacancy(self, vacancy):
try:
self.vacancies.remove(vacancy)
except ValueError:
print('Vacancy does not exist')
def get_vacancies_by_salary(self, salary: str):
try:
salary_ = get_from_and_up_salary(salary)
except ValueError:
raise ValueError(
'Введите запрос в одном из форматов "50 000- 100 000 руб." "1000-2000 USD" "100_000 руб."')
filtered_vacancies = []
if len(salary_) == 2:
from_, up_to = salary_
for vacancy in self.vacancies:
if from_ < vacancy.approximate_salary < up_to:
filtered_vacancies.append(vacancy)
else:
for vacancy in self.vacancies:
if vacancy.approximate_salary == salary_[0]:
filtered_vacancies.append(vacancy)
return filtered_vacancies
class JSONSaver(Saver):
def __init__(self):
super().__init__()
def save_to_json(self, file_name):
string = [elem.__dict__ for elem in self.vacancies]
with open(file_name, 'w', encoding='utf-8') as file:
json.dump(string, file, ensure_ascii=False)
def get_from_json(self, file_name):
self.vacancies.clear()
with open(file_name, 'r', encoding='utf-8') as file:
vacancies_json = json.load(file)
for dict_json in vacancies_json:
vacancy = Vacancy(dict_json)
self.add_vacancy(vacancy)
return