def upload_image(self, media): media = get_file_path(media) register_url = "https://api.linkedin.com/v2/assets?action=registerUpload" body = { "registerUploadRequest": { "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"], "owner": "urn:li:organization:{0}".format(self.company_id), "serviceRelationships": [{ "relationshipType": "OWNER", "identifier": "urn:li:userGeneratedContent" }] } } headers = { "Authorization": "Bearer {}".format(self.access_token) } response = self.http_post(url=register_url, body=body, headers=headers) if response.status_code == 200: response = response.json() asset = response["value"]["asset"] upload_url = response["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"] headers['Content-Type']='image/jpeg' response = self.http_post(upload_url, headers=headers, data=open(media,"rb")) if response.status_code < 200 and response.status_code > 299: frappe.throw(_("Error While Uploading Image"), title="{0} {1}".format(response.status_code, response.reason)) return None return asset return None
def get_transaction_entries(filename, headers): header_index = {} rows, transactions = [], [] if (filename.lower().endswith("xlsx")): from frappe.utils.xlsxutils import read_xlsx_file_from_attached_file rows = read_xlsx_file_from_attached_file(file_id=filename) elif (filename.lower().endswith("csv")): from frappe.utils.file_manager import get_file_path from frappe.utils.csvutils import read_csv_content filepath = get_file_path(filename) with open(filepath, 'rb') as csvfile: rows = read_csv_content(csvfile.read()) elif (filename.lower().endswith("xls")): rows = get_rows_from_xls_file(filename) else: frappe.throw("Only .csv and .xlsx files are supported currently") stmt_headers = headers.values() for row in rows: if len(row) == 0 or row[0] == None or not row[0]: continue #print("Processing row {0}".format(row)) if header_index: transaction = get_transaction_info(stmt_headers, header_index, row) transactions.append(transaction) elif is_headers_present(stmt_headers, row): header_index = get_header_index(stmt_headers, row) return transactions
def get_records_for_upload(import_doc): filename = get_file_path(import_doc.import_file) data = pd.read_excel(filename, skiprows=0) # print('upload_child') child_field_name = data.iloc[1:2].to_dict() child_field_name = child_field_name['Unnamed: 1'][1] # rename columns data.columns = list(data.iloc[7]) child_data = data.iloc[11:] child_data = child_data.drop(['Column Name:'], axis=1) final_data = {} for parentid, j in child_data.groupby('parent'): for index, row in j.iterrows(): child_rows = {} for act_row in row.keys(): child_rows.update({act_row: row[act_row]}) final_data.setdefault(parentid, []).append(child_rows) # print('ch',child_rows,'\n\n') # for m in j.iterrows(): # print('m--------',dict(m)) # print(final_data) return final_data, child_field_name
def get_transaction_entries(filename, headers): header_index = {} rows, transactions = [], [] if (filename.lower().endswith("xlsx")): from frappe.utils.xlsxutils import read_xlsx_file_from_attached_file rows = read_xlsx_file_from_attached_file(file_id=filename) elif (filename.lower().endswith("csv")): from frappe.utils.file_manager import get_file_path from frappe.utils.csvutils import read_csv_content filepath = get_file_path(filename) with open(filepath,'rb') as csvfile: rows = read_csv_content(csvfile.read()) elif (filename.lower().endswith("xls")): rows = get_rows_from_xls_file(filename) else: frappe.throw("Only .csv and .xlsx files are supported currently") stmt_headers = headers.values() for row in rows: if len(row) == 0 or row[0] == None or not row[0]: continue #print("Processing row {0}".format(row)) if header_index: transaction = get_transaction_info(stmt_headers, header_index, row) transactions.append(transaction) elif is_headers_present(stmt_headers, row): header_index = get_header_index(stmt_headers, row) return transactions
def upload_file(path, transactiontype, pos_transaction_date, filename, client=None): try: if client == 'yes': path = get_file_path(path) with open(encode(path), 'r') as f: content = f.read() rows = read_csv_content(content) result = importer.upload(rows, submit_after_import=True, update_only=False, ignore_encoding_errors=True, no_email=True) # generate JV name title = result['messages'][0]['title'] st = title.rfind('J') en = title.rfind('<') JV_name = title[st:en] transaction_link = JV_name error_status = result['error'] # failed due to content error if error_status == True: log_name = make_sync_log("Failed", transactiontype, result, '#fff168', pos_transaction_date, None) attachments = [{'fname': filename, 'fcontent': content}] send_email('Failed', transactiontype, result, pos_transaction_date, log_name, attachments) os.remove(path) return log_name #import is successful elif error_status == False: log_name = make_sync_log("Successful", transactiontype, result, '#9deca2', pos_transaction_date, transaction_link) os.remove(path) send_email('Successful', transactiontype, result, pos_transaction_date) return log_name except Exception as e: error = True log_name = make_sync_log("File not found failure", transactiontype, frappe.get_traceback(), '#ff4d4d', None, None) send_email('File not found failure', transactiontype, frappe.get_traceback(), pos_transaction_date, log_name) return log_name if error: frappe.db.rollback() else: frappe.db.commit() return {"error": error}
def get_rows_from_xls_file(filename): from frappe.utils.file_manager import get_file_path filepath = get_file_path(filename) import xlrd book = xlrd.open_workbook(filepath) sheets = book.sheets() rows = [] for row in range(1, sheets[0].nrows): row_values = [] for col in range(1, sheets[0].ncols): row_values.append(sheets[0].cell_value(row, col)) rows.append(row_values) return rows
def get_rows_from_xls_file(filename): from frappe.utils.file_manager import get_file_path filepath = get_file_path(filename) import xlrd book = xlrd.open_workbook(filepath) sheets = book.sheets() rows = [] for row in range(1, sheets[0].nrows): row_values = [] for col in range(1, sheets[0].ncols): row_values.append(sheets[0].cell_value(row, col)) rows.append(row_values) return rows
def pdf_to_base64(filename): from frappe.utils.file_manager import get_file_path if '../' in filename or filename.rsplit('.')[-1] not in ['pdf', 'PDF']: return file_path = get_file_path(filename) if not file_path: return with open(file_path, 'rb') as pdf_file: base64_string = base64.b64encode(pdf_file.read()) return base64_string
def read_xlsx_file_from_attached_file(file_id=None, fcontent=None): if file_id: from frappe.utils.file_manager import get_file_path filename = get_file_path(file_id) elif fcontent: from io import BytesIO filename = BytesIO(fcontent) else: return rows = [] wb1 = load_workbook(filename=filename, read_only=True) ws1 = wb1.active for row in ws1.iter_rows(): tmp_list = [] for cell in row: tmp_list.append(cell.value) rows.append(tmp_list) return rows
def read_xlsx_file_from_attached_file(file_id=None, fcontent=None): if file_id: from frappe.utils.file_manager import get_file_path filename = get_file_path(file_id) elif fcontent: from io import BytesIO filename = BytesIO(fcontent) else: return rows = [] wb1 = load_workbook(filename=filename, read_only=True, data_only=True) ws1 = wb1.active for row in ws1.iter_rows(): tmp_list = [] for cell in row: tmp_list.append(cell.value) rows.append(tmp_list) return rows
def upload_image(self, media): media = get_file_path(media) api = self.get_api() media = api.media_upload(media) return media.media_id
def upload_image(self, media): media = get_file_path(media) api = self.get_api(self.access_token, self.access_token_secret) media = api.media_upload(media) return media.media_id