Guest User

Untitled

a guest
Apr 27th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. import hashlib
  2. import logging
  3. import base64
  4.  
  5. from suds import WebFault
  6. from suds.client import Client
  7.  
  8.  
  9. logger = logging.getLogger(__name__)
  10.  
  11. class AllegroWebAPI(object):
  12. country_code = 1 # Poland
  13. country_id = 1 # Poland
  14. endpoint = 'https://webapi.allegro.pl/service.php?wsdl'
  15.  
  16. def __init__(self, api_key, login, userPassword):
  17.  
  18. self.api_key = api_key
  19. self.login = login
  20. self.enc_passwd = base64.b64encode(hashlib.sha256(userPassword).digest())
  21. self.client = Client(self.endpoint)
  22. self.service = self.client.service
  23. self.versions = {}
  24.  
  25. # Retrieves component versions for each country.
  26. for row in self.service.doQueryAllSysStatus(countryId=self.country_id,
  27. webapiKey=self.api_key).item:
  28. self.versions[row.countryId] = row.verKey
  29.  
  30. self.sign_in()
  31.  
  32. def sign_in(self):
  33. """Authenticates using encrypted password."""
  34. self.session_id = self.service.doLoginEnc(
  35. userLogin=self.login,
  36. userHashPassword=self.enc_passwd,
  37. countryCode=self.country_code,
  38. webapiKey=self.api_key,
  39. localVersion=self.versions[self.country_id]
  40. ).sessionHandlePart
  41.  
  42. def __getattr__(self, name):
  43. return self._api_method(getattr(self.service, name))
  44.  
  45. def _api_method(self, component):
  46. """
  47. A wrapper around suds components. Adds common parameters
  48. to each call as well as handles session expiration gracefully.
  49. """
  50. def _service(*args, **kwargs):
  51. # Prefill basic parameters.
  52. kwargs['countryCode'] = self.country_code
  53. kwargs['countryId'] = self.country_id
  54. kwargs['webapiKey'] = self.api_key
  55. kwargs['localVersion'] = self.versions.get(self.country_id)
  56.  
  57. try:
  58. return component(*args, **kwargs)
  59. except WebFault as exc:
  60. # Session expired - login again and retry.
  61. if exc.fault.faultcode in ['ERR_NO_SESSION', 'ERR_SESSION_EXPIRED']:
  62. self.sign_in()
  63. return component(*args, **kwargs)
  64. raise
  65. return _service
  66.  
  67. api_key = "x"
  68. login = "x"
  69. userPassword = "x"
  70. a = AllegroWebAPI(api_key, login, userPassword)
Advertisement
Add Comment
Please, Sign In to add comment