def postFileWithToken(self, url, localPath, tempPath, token, appName, query = None): """ @return: False if failed, json structure if success """ response = None httpSession = requests.Session() try: if Utils.isWindowsOS(): fileName = Utils.getNameFromPath(localPath) tempFileHanlder = open(tempPath, 'rb') else: fileName = Utils.getNameFromPath(localPath) tempFileHanlder = open(tempPath, 'rb') files = {'file': (fileName, tempFileHanlder, {'Expires': '0'})} if query is not None: query = self.prepareParams(query) if self.logger is not None: self.logger.debug('[HTTP] POST Url: ' + url) multipartMonitor = MultipartEncoderMonitor.from_fields(fields=files, callback=None) multipartMonitor.filePath = localPath headersToken = {'Content-Type': multipartMonitor.content_type, 'Auth-Token': token} if SyncConfiguration.EnableProxy: response = httpSession.post(url, params=query, data=multipartMonitor, headers=headersToken, timeout=600, verify=False) elif Utils.isMacOS(): response = httpSession.post(url, params=query, data=multipartMonitor, headers=headersToken, timeout=600, verify=Utils.getCertFile()) else: response = httpSession.post(url, params=query, data=multipartMonitor, headers=headersToken, timeout=600, proxies=self.getProxies()) self.logger.debug('[HTTP] Response status [%s] and content: %s', str(response.status_code), response.content) if response.status_code == StatusCode.Success: responseJson = response.json() if responseJson.get('success') == True: return (responseJson, None) else: return (False, '\xe8\xaf\xb7\xe9\x87\x8d\xe8\xaf\x95') else: errorMsg = '\xe8\xaf\xb7\xe9\x87\x8d\xe8\xaf\x95' if 400 == response.status_code or 500 == response.status_code: responseJson = response.json() if -1 != responseJson.find('failed_to_process_request'): errorMsg = u'\u4e91\u7aef\u6587\u4ef6\u4e0d\u5b58\u5728' elif 500 == response.status_code: errorMsg = u'\u60a8\u7684\u7f51\u7edc\u53ef\u80fd\u5b58\u5728\u95ee\u9898\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5' else: errorMsg = u'\u6743\u9650\u4e0d\u8db3\u65e0\u6cd5\u5b8c\u6210\u8be5\u64cd\u4f5c\uff0c\u8bf7\u68c0\u67e5\u60a8\u7684\u534f\u4f5c\u8005\u7b49\u7ea7' elif 401 == response.status_code: errorMsg = u'\u7528\u6237\u5df2\u9000\u51fa' + appName return (False, errorMsg) except Exception as exception: self.logger.error(exception, exc_info=1) finally: httpSession.close() if locals().has_key('tempFileHanlder'): tempFileHanlder.close() return (False, '\xe8\xaf\xb7\xe9\x87\x8d\xe8\xaf\x95')
def postLogFile(self, url, localPath, tempFile, query = None): response = None self.logger.debug('[HTTP] post log file, the path is %s', localPath) httpSession = requests.Session() try: if query is not None: query = self.prepareParams(query) fileName = Utils.getNameFromPath(localPath) files = {'log_file': (fileName, open(tempFile, 'rb'), {'Expires': '0'})} headers = self.getHeaders() if SyncConfiguration.EnableProxy: response = httpSession.post(url, params=query, files=files, timeout=600, headers=headers, proxies=self.getProxies(), verify=False) elif Utils.isMacOS(): response = httpSession.post(url, params=query, files=files, timeout=600, headers=headers, proxies=self.getProxies(), verify=Utils.getCertFile()) else: response = httpSession.post(url, params=query, files=files, timeout=600, headers=headers, proxies=self.getProxies()) if response.status_code == StatusCode.Success: responseJson = response.json() if responseJson.get('success') == True: return True raise WebAPIException except Exception as exception: if response is not None: self.logger.error('[HTTP] Error response content from server: %s', response.content) self.logger.error(exception, exc_info=1) raise WebAPIException finally: httpSession.close()
def uploadNewFileVersion(self, localPath, tempFilePath, resourceId, sequenceId, description = 'UpdateNewVersion'): if os.path.exists(localPath): if localPath != tempFilePath: shutil.copyfile(unicode(localPath), tempFilePath) else: raise WaitingOtherResourceException size = os.path.getsize(localPath) name = Utils.getNameFromPath(localPath) modifiedAt = Utils.getModifyTime(localPath) presignResponse = self.autoRepeatQuery(self.getFangCloudHttpClient().uploadNewFileVersionPresign, [-resourceId, sequenceId, size, name, modifiedAt]) if presignResponse.get('success', False): uploadURL = presignResponse['upload_url'] response = self.autoRepeatQuery(self.getFangCloudHttpClient().uploadNewFileVersion, [uploadURL, localPath, tempFilePath, description]) else: response = presignResponse if response['success']: result = self.__formatUploadNewFileResponse(response) else: result = response return result
def postFile(self, url, localPath, tempPath, query = None): """ @return: False if failed, json structure if success """ response = None httpSession = requests.Session() bConnectError = False try: fileName = Utils.getNameFromPath(localPath) tempFileHanlder = open(tempPath, 'rb') files = {'file': (fileName, tempFileHanlder, {'Expires': '0'})} if query is not None: query = self.prepareParams(query) if self.logger is not None: self.logger.debug('[HTTP] POST Url: ' + url) multipartMonitor = MultipartEncoderMonitor.from_fields(fields=files, callback=handleChunkFinish) multipartMonitor.filePath = localPath headers = self.getHeaders() headers['Content-Type'] = multipartMonitor.content_type if SyncConfiguration.EnableProxy: response = httpSession.post(url, params=query, data=multipartMonitor, headers=headers, timeout=600, proxies=self.getProxies(), verify=False) elif Utils.isMacOS(): response = httpSession.post(url, params=query, data=multipartMonitor, headers=headers, timeout=600, proxies=self.getProxies(), verify=Utils.getCertFile()) else: response = httpSession.post(url, params=query, data=multipartMonitor, headers=headers, timeout=600, proxies=self.getProxies()) self.logger.debug('[HTTP] Response status [%s] and content: %s', str(response.status_code), response.content) if response.status_code == StatusCode.Success: responseJson = response.json() if responseJson.get('success') == True: return responseJson else: return False else: return self.handleFailedResponseStatus(response.url, response.status_code, response.content) except (ProxyConnectionError, ConnectionError) as exception: self.logger.debug('[HTTP] post file stopped because connection abort') bConnectError = True self.logger.error(exception, exc_info=1) raise exception except (UnAuthorizedException, RefreshTokenFailedException, HttpQueryParameterError, StopSyncing) as exception: self.logger.debug('[HTTP] stop send file to server') raise exception except Exception as exception: if response is not None: self.logger.error('[HTTP] Error response content from server: %s', response.content) self.logger.error(exception, exc_info=1) raise WebAPIException finally: SyncUiInterface.SetNetworkAvailable(not bConnectError) HttpStatistic.FinishedUploadByte(localPath) httpSession.close() if locals().has_key('tempFileHanlder'): tempFileHanlder.close()
def uploadNewFilePresign(self, parentFolderId, localPath, description = None): try: postBody = {'folder_id': parentFolderId, 'file_name': Utils.getNameFromPath(localPath), 'file_size': str(os.path.getsize(localPath)), 'modified_at': Utils.getModifyTime(localPath)} if description is not None: postBody['description'] = description response = self.post(FangCloudUrl.URL['FILE_PRESIGN_UPLOAD'], jsonData=postBody, logData=True) self.callbackHandler.handleHttpResponse(response) return response except UnAuthorizedException as exception: self.logger.error(exception, exc_info=1) return self.__refreshTokenWhenUnAuthorized() except ConnectionError: return HttpResponseResult.Failed