How to use list_attachments method in Kiwi

Best Python code snippet using Kiwi_python

emlview

Source:emlview Github

copy

Full Screen

1#!/usr/bin/python32import base643import tempfile4from PyQt5.QtCore import Qt, QModelIndex5import os6import sys, email, quopri7import PyQt58from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QMessageBox, QMenu, QFileDialog9from PyQt5.QtGui import QIcon, QStandardItemModel, QStandardItem10from PyQt5.uic import loadUi11import signal12import re13import subprocess14signal.signal(signal.SIGINT, signal.SIG_DFL)15ui_files = ('mainwindow.ui', '/usr/share/emlview/mainwindow.ui')16def find_file(file_set):17 return [file for file in file_set if os.path.exists(file)][0]18class App(QMainWindow):19 def __init__(self):20 QMainWindow.__init__(self)21 self.initUI()22 self.loadEml()23 def initUI(self):24 loadUi(find_file(ui_files), self)25 def keyPressEvent(self, e):26 if e.key() == Qt.Key_Escape:27 self.close()28 def decode(self, content, transfer_encoding, text_encoding=None):29 if transfer_encoding == 'quoted-printable':30 decoded = quopri.decodestring(content)31 if text_encoding:32 decoded = decoded.decode(text_encoding)33 return decoded34 elif transfer_encoding == 'base64':35 return base64.b64decode(content)36 elif transfer_encoding == '8bit':37 return base64.b64decode(content)38 def loadEml(self):39 try:40 if len(sys.argv) == 1:41 raise IOError("No file provided")42 filename = sys.argv[1]43 if not os.path.exists(filename):44 raise IOError("emlview: error loading document", "Cannot load file (does not exist)")45 fp = open(filename, 'r')46 message = email.message_from_file(fp)47 fp.close()48 attacments_model = QStandardItemModel()49 self.list_attachments.setModel(attacments_model)50 self.list_attachments.doubleClicked.connect(self.onAttachmentClicked)51 self.list_attachments.setContextMenuPolicy(Qt.CustomContextMenu)52 self.list_attachments.customContextMenuRequested.connect(self.showAttachmentMenu)53 text_body = ''54 html_body = ''55 for part in message.walk():56 if part['Content-Type'] is None:57 part['Content-Type'] = ''58 59 print (part['Content-Type'])60 if part['Content-Type'].startswith('text/'):61 meta_parts = part['Content-Type'].split(';')62 content_type = meta_parts[0]63 encoding = None64 if len(meta_parts) == 2:65 encoding = part['Content-Type'].split(';')[1].split('=')[1]66 transfer_encoding = part['Content-Transfer-Encoding']67 if content_type == 'text/html':68 if transfer_encoding == '8bit':69 html_body = part.get_payload()70 elif transfer_encoding is None:71 html_body = part.get_payload()72 else:73 html_body = self.decode(part.get_payload(), transfer_encoding, encoding)74 elif content_type == 'text/plain':75 text_body = part.get_payload()76 else:77 content_disposition = part['Content-Disposition']78 if content_disposition and content_disposition.startswith('attachment'):79 data = (part.get_filename(), part['Content-Transfer-Encoding'], part.get_payload())80 item = QStandardItem(part.get_filename())81 item.setData(data, Qt.UserRole)82 attacments_model.appendRow(item)83 tos = ' '.join([string.strip().strip("'") for string in message['to'].split("\n") if len(string.strip().strip("'")) >0])84 self.label_subject.setText(message['subject'].replace('\n', ''))85 self.label_from.setText(message['from'].replace('\n', ''))86 self.label_to.setText(tos)87 self.label_date.setText(message['date'].replace('\n', ''))88 self.textBrowser.setText(text_body)89 self.webView.setHtml(html_body)90 self.tb_raw.setText(str(message))91 92 if message['cc']:93 self.label_cc.setText(message['cc'].replace('\n', ''))94 if message['bcc']:95 self.label_bcc.setText(message['bcc'].replace('\n', ''))96 if html_body is None:97 self.bodies.tabBar().removeTab(0)98 self.bodies.setCurrentIndex(1)99 100 self.statusBar().showMessage('Loaded: %s' % os.path.abspath(filename))101 if attacments_model.rowCount() == 0:102 self.frame_attachments.setVisible(False)103 except IOError as e:104 print(e)105 QMessageBox.critical(self, "emlview: error loading document", str(e)).show()106 def onAttachmentClicked(self, index):107 item = self.list_attachments.model().itemData(index)[Qt.UserRole]108 filename = item[0]109 transfer_encoding = item[1]110 content = item[2]111 tmp_filename = '/tmp/' + filename112 handle = open(tmp_filename, 'wb')113 handle.write(self.decode(content, transfer_encoding))114 handle.close()115 subprocess.call(['xdg-open', tmp_filename])116 def showAttachmentMenu(self, pos):117 def openAttachment():118 index = self.list_attachments.indexAt(pos)119 self.onAttachmentClicked(index)120 def saveAttachment():121 index = self.list_attachments.indexAt(pos)122 item = self.list_attachments.model().itemData(index)[Qt.UserRole]123 filename = item[0]124 transfer_encoding = item[1]125 content = item[2]126 dest_filename = QFileDialog.getSaveFileName(self, 'Save attachment', filename)127 if dest_filename[0] != "":128 handle = open(dest_filename[0], 'wb')129 handle.write(self.decode(content, transfer_encoding))130 handle.close()131 menu = QMenu()132 openAction = menu.addAction("Open")133 openAction.triggered.connect(openAttachment)134 saveAction = menu.addAction("Save")135 saveAction.triggered.connect(saveAttachment)136 menu.exec_(self.list_attachments.mapToGlobal(pos))137if __name__ == '__main__':138 app = QApplication(sys.argv)139 window = App()140 window.show()...

Full Screen

Full Screen

danfe_join.py

Source:danfe_join.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# © 2016 Danimar Ribeiro, Trustcode3# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).4from osv import osv, fields5from openerp.osv import fields, orm6from openerp.tools.translate import _7from datetime import datetime, date8from PyPDF2 import PdfFileReader, PdfFileWriter9from tempfile import mkstemp10from werkzeug.wrappers import Response11import base6412import pytz13import os14class danfe_join(osv.osv):15 _name = 'danfe.join'16 def danfe_join(self, cr, uid, ids, context=None):17 account_i_obj = self.pool.get('account.invoice').browse(cr, uid, context['active_ids'], context=context)18 output = PdfFileWriter()19 list_attachments = []20 for rec_account_invoice in account_i_obj:21 attach_pool = self.pool.get('ir.attachment')22 attach_ids = attach_pool.search(cr, uid, [('res_id', '=', rec_account_invoice.id), ('res_model', '=', 'account.invoice')])23 if attach_ids:24 for ir_attachment in attach_pool.browse(cr, uid, attach_ids, context=None):25 if ir_attachment.name[-3:] == 'pdf':26 list_attachments.append(ir_attachment)27 for ir_attachment_obj in list_attachments:28 fd, file_name = mkstemp()29 os.write(fd, base64.decodestring(attach_pool.browse(cr, uid, ir_attachment_obj.id).datas))30 pdf = PdfFileReader(file(file_name, 'rb'))31 pg_pdf = pdf.getNumPages()32 for i in range(0, pg_pdf):33 output.addPage(pdf.getPage(i))34 os.remove(os.path.join(file_name))35 if not list_attachments:36 raise orm.except_orm(_('Error'), 'The PDF file is empty, no exists attachments for join the file.')37 fd_fl, file_name_fl = mkstemp()38 outputStream = file(file_name_fl, 'w+b')39 output.write(outputStream)40 outputStream.seek(0)41 ps = outputStream.read()42 outputStream.close()43 w_file = base64.b64encode(ps)44 w_timezone = self.pool.get('res.users').browse(cr, uid, uid).tz45 now = datetime.now(pytz.timezone(w_timezone))46 filename = 'DANFE_UN_%04d-%02d-%02d.pdf' % (now.year, now.month, now.day)47 id_danfe_join = self.create(48 cr, uid, {'data': w_file,49 'filename': filename,50 'invisible': True}, context=context)51 os.remove(os.path.join(file_name_fl))52 return {53 'type': 'ir.actions.act_window',54 'res_model': 'danfe.join',55 'view_mode': 'form',56 'view_type': 'form',57 'res_id': id_danfe_join,58 'views': [(False, 'form')],59 'target': 'new'60 }61 _columns = {62 'filename': fields.char('Filename'),63 'data': fields.binary('File', readonly=True),64 'invisible': fields.boolean('Button Invisible')...

Full Screen

Full Screen

test_attachment.py

Source:test_attachment.py Github

copy

Full Screen

...13 branch = type(self).branch14 node = branch.create_node()15 with open('./res/cloudcms.png', 'rb') as cloudcmsImage:16 node.upload_attachment(cloudcmsImage, 'image/png', attachment_id='default', filename='myImage')17 attachments = node.list_attachments()18 attachment = attachments['default']19 self.assertEqual('default', attachment.id)20 self.assertEqual('myImage', attachment.filename)21 self.assertEqual('image/png', attachment.content_type)22 self.assertTrue(attachment.length > 0)23 self.assertIsNotNone(attachment.object_id)24 25 dl = attachment.download_attachment()26 self.assertTrue(len(dl) > 0)27 dl_copy = node.download_attachment('default')28 self.assertEqual(dl, dl_copy)29 with open('./res/headphones.png', 'rb') as headphonesImage:30 node.upload_attachment(headphonesImage, 'image/png', attachment_id='another')31 attachments = node.list_attachments()32 self.assertEqual(2, len(attachments))33 node.delete_attachment('default')34 attachments = node.list_attachments()35 self.assertEqual(1, len(attachments))36 attachment = attachments['another']37 self.assertEqual('another', attachment.id)38 self.assertEqual('another', attachment.filename)39 self.assertEqual('image/png', attachment.content_type)40 self.assertTrue(attachment.length > 0)41 self.assertIsNotNone(attachment.object_id)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kiwi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful