Skip to content

Commit ee26b78

Browse files
committed
jconfig 2.0 and update vk_api
1 parent eb37746 commit ee26b78

3 files changed

Lines changed: 60 additions & 52 deletions

File tree

jconfig/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"""
1010

1111
__author__ = 'Kirill Python'
12-
__version__ = '1.2'
12+
__version__ = '2.0'
1313
__email__ = 'python273@ya.ru'
1414
__contact__ = 'https://vk.com/python273'
1515

jconfig/jconfig.py

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8,40 +8,41 @@
88
Copyright (C) 2015
99
"""
1010

11-
import os
1211
import json
1312

1413

1514
class Config(object):
16-
def __init__(self, section, filename=None):
17-
18-
if not filename:
19-
filename = 'config'
20-
21-
self.section = section # Секция настроек
22-
self.filename = filename # Файл с настройками
23-
self.all = self.parse() # Все настройки
24-
self.settings = self.all.get(section, {}) # Настройки секции
25-
26-
def __getitem__(self, item):
27-
return self.settings.get(item, {})
28-
29-
def __setitem__(self, key, value):
30-
self.settings.update({key: value})
31-
self.all.update({self.section: self.settings})
32-
self.update(self.all)
33-
34-
def parse(self):
35-
fileis = os.path.exists(self.filename)
36-
if fileis:
37-
settings = json.load(open(self.filename, 'r'))
38-
return settings
39-
else:
40-
self.update()
41-
return {}
42-
43-
def update(self, settings=None):
44-
if not settings:
15+
__slots__ = ('_section', '_filename', '_settings')
16+
17+
def __init__(self, section, filename='.jconfig'):
18+
self._section = section
19+
self._filename = filename
20+
self._settings = self.load()
21+
22+
def __getattr__(self, name):
23+
return self._settings[self._section].get(name)
24+
25+
def __setattr__(self, name, value):
26+
if name.startswith('_'):
27+
super(Config, self).__setattr__(name, value)
28+
return
29+
30+
self._settings[self._section][name] = value
31+
32+
def clear_section(self):
33+
self._settings[self._section] = {}
34+
35+
def load(self):
36+
try:
37+
with open(self._filename, 'r') as f:
38+
settings = json.load(f)
39+
except FileNotFoundError:
4540
settings = {}
4641

47-
json.dump(settings, open(self.filename, 'w'))
42+
settings.setdefault(self._section, {})
43+
44+
return settings
45+
46+
def save(self):
47+
with open(self._filename, 'w') as f:
48+
json.dump(self._settings, f)

vk_api/vk_api.py

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
Copyright (C) 2015
99
"""
1010

11-
import jconfig
1211
import re
13-
import requests
1412
import time
1513

14+
import requests
15+
16+
import jconfig
17+
1618
DELAY = 0.36 # 3 requests per second
1719
TOO_MANY_RPS_CODE = 6
1820
CAPTCHA_ERROR_CODE = 14
@@ -30,7 +32,6 @@
3032

3133

3234
class VkApi(object):
33-
3435
def __init__(self, login=None, password=None, number=None, sec_number=None,
3536
token=None,
3637
proxies=None, captcha_handler=None, config_filename='vk_config.json',
@@ -78,8 +79,8 @@ def __init__(self, login=None, password=None, number=None, sec_number=None,
7879
self.http = requests.Session()
7980
self.http.proxies = proxies # Ставим прокси
8081
self.http.headers = { # Притворимся браузером
81-
'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:38.0) '
82-
'Gecko/20100101 Firefox/38.0'
82+
'User-agent': 'Mozilla/5.0 (Windows NT 6.1; rv:40.0) '
83+
'Gecko/20100101 Firefox/40.0'
8384
}
8485

8586
self.last_request = 0.0
@@ -90,11 +91,19 @@ def __init__(self, login=None, password=None, number=None, sec_number=None,
9091
TOO_MANY_RPS_CODE: self.too_many_rps_handler
9192
}
9293

93-
def authorization(self):
94-
""" Полная авторизация с получением токена """
94+
def authorization(self, reauth=False):
95+
""" Полная авторизация с получением токена
96+
97+
:param reauth: Позволяет переавторизиваться, игнорируя сохраненные
98+
куки и токен
99+
"""
100+
95101
if self.login and self.password:
96-
self.sid = self.settings['remixsid']
97-
self.token = self.settings['access_token']
102+
if reauth:
103+
self.settings.clear_section()
104+
105+
self.sid = self.settings.remixsid
106+
self.token = self.settings.token
98107

99108
if not self.check_sid():
100109
self.vk_login()
@@ -136,14 +145,16 @@ def vk_login(self, captcha_sid=None, captcha_key=None):
136145
remixsid = self.http.cookies['remixsid6']
137146

138147
if remixsid:
139-
self.settings['remixsid'] = remixsid
148+
self.settings.remixsid = remixsid
140149

141150
# Нужно для авторизации в API
142-
self.settings['forapilogin'] = {
151+
self.settings.forapilogin = {
143152
'p': self.http.cookies['p'],
144153
'l': self.http.cookies['l']
145154
}
146155

156+
self.settings.save()
157+
147158
self.sid = remixsid
148159

149160
elif 'sid=' in response.url:
@@ -225,8 +236,8 @@ def check_sid(self):
225236
def api_login(self):
226237
""" Получение токена через Desktop приложение """
227238

228-
if not self.sid:
229-
raise AuthorizationError('API authorization error (no sid cookie)')
239+
if not self.sid or not self.settings.forapilogin:
240+
raise AuthorizationError('API authorization error (no cookies)')
230241

231242
url = 'https://oauth.vk.com/authorize'
232243
values = {
@@ -235,7 +246,7 @@ def api_login(self):
235246
'response_type': 'token',
236247
}
237248

238-
self.http.cookies.update(self.settings['forapilogin'])
249+
self.http.cookies.update(self.settings.forapilogin)
239250
self.http.cookies.update({'remixsid': self.sid})
240251

241252
response = self.http.post(url, values)
@@ -252,7 +263,8 @@ def api_login(self):
252263
x = i.split('=')
253264
token.update({x[0]: x[1]})
254265

255-
self.settings['access_token'] = token
266+
self.settings.token = token
267+
self.settings.save()
256268
self.token = token
257269
else:
258270
raise AuthorizationError('Authorization error (api)')
@@ -355,7 +367,6 @@ def method(self, method, values=None, captcha_sid=None, captcha_key=None):
355367

356368
if error.code in self.error_handlers:
357369
if error.code == CAPTCHA_ERROR_CODE:
358-
359370
error = Captcha(
360371
self,
361372
error.error['captcha_sid'],
@@ -433,7 +444,6 @@ class AccountBlocked(AuthorizationError):
433444

434445

435446
class SecurityCheck(AuthorizationError):
436-
437447
def __init__(self, phone_prefix, phone_postfix, response=None):
438448
self.phone_prefix = phone_prefix
439449
self.phone_postfix = phone_postfix
@@ -450,7 +460,6 @@ def __str__(self):
450460

451461

452462
class ApiError(Exception):
453-
454463
def __init__(self, vk, method, values, error):
455464
self.vk = vk
456465
self.method = method
@@ -471,7 +480,6 @@ def __str__(self):
471480

472481

473482
class ApiHttpError(Exception):
474-
475483
def __init__(self, vk, method, values, response):
476484
self.vk = vk
477485
self.method = method
@@ -490,7 +498,6 @@ def __str__(self):
490498

491499

492500
class Captcha(Exception):
493-
494501
def __init__(self, vk, captcha_sid,
495502
func, args=None, kwargs=None, url=None):
496503
self.vk = vk

0 commit comments

Comments
 (0)