Advertisement
200cm3

Untitled

Feb 12th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.64 KB | None | 0 0
  1. Vitaliy, [12.02.20 11:22]
  2. import json
  3. import requests
  4.  
  5. from requests import HTTPError
  6.  
  7.  
  8. class YandexImages(object):
  9.     def init(self):
  10.         self.SESSION = requests.Session()
  11.         self.API_URL = 'https://dialogs.yandex.net/api/v1/'
  12.  
  13.  
  14.     def set_auth_token(self, token):
  15.         self.SESSION.headers.update(self.get_auth_header(token))
  16.  
  17.     def get_auth_header(self, token):
  18.  
  19.       return {
  20.           'Authorization': 'OAuth %s' % token
  21.         }
  22.  
  23.     def log(self, error_text,response):
  24.         log_file = open('YandexApi.log','a')
  25.         log_file.write(error_text+'\n')#+response)
  26.         log_file.close()
  27.  
  28.     def validate_api_response(self, response, required_key_name=None):
  29.         content_type = response.headers['Content-Type']
  30.         content = json.loads(response.text) if 'application/json' in content_type else None
  31.  
  32.         if response.status_code == 200:
  33.             if required_key_name and required_key_name not in content:
  34.                 self.log('Unexpected API response. Missing required key: %s' % required_key_name, response=response)
  35.                 return None
  36.         elif content and 'error_message' in content:
  37.             self.log('Error API response. Error message: %s' % content['error_message'], response=response)
  38.             return None
  39.         elif content and 'message' in content:
  40.             self.log('Error API response. Error message: %s' % content['message'], response=response)
  41.             return None
  42.         else:
  43.             response.raise_for_status()
  44.  
  45.         return content
  46.  
  47.     ################################################
  48.     # Проверить занятое место                      #
  49.     #                                              #
  50.     # Вернет массив                                #
  51.     # - total - Сколько всего места осталось       #
  52.     # - used - Занятое место                       #
  53.     ################################################
  54.     def checkOutPlace(self):
  55.         result = self.SESSION.get(self.API_URL+'status')
  56.         content = self.validate_api_response(result)
  57.         if content != None:
  58.             return content['images']['quota']
  59.         return None
  60.  
  61.     ################################################
  62.     # Загрузка изображения из интернета            #
  63.     #                                              #
  64.     # Вернет массив                                #
  65.     # - id - Идентификатор изображения             #
  66.     # - origUrl - Адрес изображения.               #
  67.     ################################################
  68.     def downloadImageUrl(self,url):
  69.         path = 'skills/{skills_id}/images'.format(skills_id=self.skills)
  70.         result = self.SESSION.post(url=self.API_URL+path,data=json.dumps({"url":url}))
  71.         content = self.validate_api_response(result)
  72.         if content != None:
  73.             return content['image']
  74.         return None
  75.  
  76.  
  77.     ################################################
  78.     # Загрузка изображения из файла                #
  79.     #                                              #
  80.     # Вернет массив                                #
  81.     # - id - Идентификатор изображения             #
  82.     # - origUrl - Адрес изображения.               #
  83.     ################################################
  84.     def downloadImageFile(self, img):
  85.         path = 'skills/{skills_id}/images'.format(skills_id=self.skills)
  86.  
  87.         result = self.SESSION.post(url = self.API_URL+path,files={'file':(img,open(img,'rb'))})
  88.         content = self.validate_api_response(result)
  89.         if content != None:
  90.             return content['image']
  91.         return None
  92.  
  93. Vitaliy, [12.02.20 11:22]
  94. ################################################
  95.     # Просмотр всех загруженных изображений        #
  96.     #                                              #
  97.     # Вернет массив из изображений                 #
  98.     # - id - Идентификатор изображения             #
  99.     # - origUrl - Адрес изображения.             #
  100.     ################################################
  101.     def getLoadedImages(self):
  102.         path = 'skills/{skills_id}/images'.format(skills_id=self.skills)
  103.         result = self.SESSION.get(url = self.API_URL+path)
  104.         content = self.validate_api_response(result)
  105.         if content != None:
  106.             return content['images']
  107.         return None
  108.  
  109.     ################################################
  110.     # Удаление выбранной картинки                  #
  111.     #                                              #
  112.     # В случае успеха вернет 'ok'                 #
  113.     ################################################
  114.     def deleteImage(self, img_id):
  115.         path = 'skills/{skills_id}/images/{img_id}'.format(skills_id=self.skills,img_id = img_id)
  116.         result = self.SESSION.delete(url=self.API_URL+path)
  117.         content = self.validate_api_response(result)
  118.         if content != None:
  119.             return content['result']
  120.         return None
  121.  
  122.     def deleteAllImage(self):
  123.         success = 0
  124.         fail = 0
  125.         images = self.getLoadedImages()
  126.         for image in images:
  127.             image_id = image['id']
  128.             if image_id:
  129.                 if self.deleteImage(image_id):
  130.                     success+=1
  131.                 else:
  132.                     fail += 1
  133.             else:
  134.                 fail += 1
  135.  
  136.         return {'success':success,'fail':fail}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement