def test_send_with_files(self): file1 = BytesIO(get_binay('blablabla\blabla.')) file2 = open(join(dirname(__file__), 'static', 'lucterios.mailing', 'images', 'config_mail.png'), mode='rb') try: configSMTP('localhost', 1025) self.assertEqual(0, self.server.count()) self.assertEqual(True, will_mail_send()) send_email('*****@*****.**', 'send with files', '2 files sent!', [('filename1.txt', file1), ('filename2.png', file2)]) self.assertEqual(1, self.server.count()) self.assertEqual('*****@*****.**', self.server.get(0)[1]) self.assertEqual(['*****@*****.**'], self.server.get(0)[2]) msg, msg_f1, msg_f2 = self.server.check_first_message( 'send with files', 3) self.assertEqual('text/plain', msg.get_content_type()) self.assertEqual('base64', msg.get('Content-Transfer-Encoding', '')) self.assertEqual('2 files sent!', decode_b64(msg.get_payload())) self.assertEqual(None, self.server.smtp.auth_params) self.assertTrue('filename1.txt' in msg_f1.get('Content-Type', ''), msg_f1.get('Content-Type', '')) self.assertEqual('blablabla\blabla.', decode_b64(msg_f1.get_payload())) self.assertTrue('filename2.png' in msg_f2.get('Content-Type', ''), msg_f2.get('Content-Type', '')) file2.seek(0, SEEK_END) self.assertEqual(file2.tell(), len(b64decode(msg_f2.get_payload()))) finally: file1.close() file2.close()
def test_csv(self): d = dict() with open(__file__) as f: for c in re.findall('[A-Z]', f.read()): try: d[c] += 1 except: d[c] = 1 path = PathSpliter(__file__).dirname save_counter_as_csv(d, path + 'counter.csv', ['KEY', 'NUM']) b = b'''a,b,c,d,e,f,g,h,j,k 1,2,3,4,5,6,7,8,9,0 0,9,8,7,6,5,4,3,2,1 1,2,3,4,5,6,7,8,9,0 0,9,8,7,6,5,4,3,2,1 1,2,3,4,5,6,7,8,9,0 6,6,6,6,6,6,6,6,6,6''' csv = CSV() csv.read(BytesIO(b), withhead=1, convert=int) csv.show() csv.read(BytesIO(b), withhead=1, convert=float) print(csv.to_matrix()) csv.write(path + 'test.csv', delim=',', body_format=','.join(['%.2f'] * 10)) m = numpy.array([['a', 'b', 'c'], ['b', 'c', 'd'], ['d', 'e', 'f'], ['a', 'f', 'c'], ['g', 'd', 'e']]) print(indexed_all(m))
def create(): totp_ = totp.TOTP(random_base32()) outn = BytesIO() img = make(totp_.provisioning_uri("*****@*****.**",issuer_name = "Cinara-Lyca Network Co.LTD")) img.save(outn) data = standard_b64encode(outn.getvalue()) data_uri = "data:image/png;base64," + data.decode() return jsonify({"qr_code_url":data_uri,"auth_vendor_id":totp_.secret})
def get(self, request, transaction_number, challan_number): r = requests.get(url=SALES_TRANSACTION, params={'transaction_number': transaction_number}) if r.status_code is 200: json_data = r.json() if hasUpdatePurchaseRecordAccess(request.user): item_list = json.loads(requests.get(SALES_ITEM_LIST).text) uom = json.loads(requests.get(UNIT_OF_MEASURE).text) po_line_statuses = json.loads( requests.get(PURCHASE_ORDER_LINES_STATUS).text) po_header_statuses = json.loads( requests.get(PURCHASE_ORDER_HEADER_STATUS).text) po_type = json.loads(requests.get(PURCHASE_ORDER_TYPE).text) supplier_list = json.loads(requests.get(SUPPLIER_LIST).text) data = { 'user': request.user.username, 'po_type': po_type['purchaseOrderType'], 'supplier_list': supplier_list['supplierLists'], 'item_list': item_list['itemDetailsList'], 'uom': uom['UnitOfMeasure'], 'header_status': po_header_statuses['purchaseOrderHeaderStatus'], 'line_status': po_line_statuses['purchaseOrderLineStatus'], 'details': json_data['sales_trx_details'][0] } template = jinja_template.get_template( 'pdf-templates/sales-challan.html') html = template.render(request, data=data) response = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), response) if not pdf.err: resp = HttpResponse(response.getvalue(), content_type='application/pdf') resp[ 'Content-Disposition'] = 'attachment; filename="SalesChallan.pdf"' return resp else: return HttpResponse("Error Rendering PDF", status=400) else: template = jinja_template.get_template( 'sales/sales-line-view.html') return HttpResponse( template.render(request, data=json_data['purchase_trx_details'][0])) else: template = jinja_template.get_template( 'internal_server_error.html') return HttpResponse(template.render(request))
def content(self): from _io import BytesIO if isfile(self.file_path): with ZipFile(self.file_path, 'r') as zip_ref: file_list = zip_ref.namelist() if len(file_list) > 0: doc_file = zip_ref.open(file_list[0]) return BytesIO(doc_file.read()) return BytesIO(b'')
def decompress(frequencyTable, valueData): buffer = BytesIO(valueData) uncompressedSize = readUnsignedLeb128(buffer) compressedSize = len(valueData) - buffer.tell() # create a buffer to decompress into inputData = buffer.read(compressedSize) outputData = ctypes.create_string_buffer(uncompressedSize) decompDLL.decompressData(frequencyTable, inputData, compressedSize, outputData, uncompressedSize) return BytesIO(outputData.raw)
def get(self, request, *args, **kwargs): data = request.query_params.copy() device = app_device(request) if not device: device = data.get('username', '') f = BytesIO() img, code = check_code.create_validate_code() DeivceVcode.objects.update_or_create(device=device, defaults={'vcode': upper(code)}) img.save(f, 'GIF') return HttpResponse(f.getvalue(), content_type='image/gif')
def content(self): from _io import BytesIO file_path = get_user_path("documents", "document_%s" % six.text_type(self.id)) if isfile(file_path): with ZipFile(file_path, 'r') as zip_ref: file_list = zip_ref.namelist() if len(file_list) > 0: doc_file = zip_ref.open(file_list[0]) return BytesIO(doc_file.read()) return BytesIO(b'')
def bytesio_helper(): return (BytesIO(bytearray(b'')), BytesIO(bytearray(b'a')), BytesIO(bytearray(b'ab')), BytesIO(bytearray(b'abc')), BytesIO(bytearray(b'abcd')), BytesIO(bytearray(b'abcde')), BytesIO(bytearray(b'abcdef')), BytesIO(bytearray(b'abcdefg')), BytesIO(bytearray(b'abcdefgh')), BytesIO(bytearray(b'abcdefghi')) )
def test_issue25862(): # CPython issue #25862 # Assertion failures occurred in tell() after read() and write(). from _io import TextIOWrapper, BytesIO t = TextIOWrapper(BytesIO(b'test'), encoding='ascii') t.read(1) t.read() t.tell() t = TextIOWrapper(BytesIO(b'test'), encoding='ascii') t.read(1) t.write('x') t.tell()
def test4atom_no_match_missing_value_string_set(self): """ This test case sets up a set of values, which are all expected to be matched. The missing value string is set to a value, so when a string does not match this value is used instead. """ description = "Test4MatchValueStreamWriter" output_stream = BytesIO() match_context = MatchContext( b'25537Euro 25538Euro 25539Euro 25540Pfund ') decimal_integer_value_me = DecimalIntegerValueModelElement( 'd1', DecimalIntegerValueModelElement.SIGN_TYPE_NONE, DecimalIntegerValueModelElement.PAD_TYPE_NONE) fixed_dme = FixedDataModelElement('s1', self.euro) sequence_model_element = SequenceModelElement( 'sequence', [decimal_integer_value_me, fixed_dme]) match_value_stream_writer = MatchValueStreamWriter( output_stream, [self.match_sequence_d1, self.match_sequence_s1], b';', b'-') self.analysis_context.register_component(match_value_stream_writer, description) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) match_element = decimal_integer_value_me.get_match_element( 'match', match_context) match_element.path = self.match_sequence_d1 log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) self.assertEqual(output_stream.getvalue().decode(), '25537;Euro \n25538;Euro \n25539;Euro \n25540;-\n')
def test2all_atoms_match_no_seperator(self): """ This test case sets up a set of values, which are all expected to be matched. The seperator string is None, so all values are expected to be one string. """ description = "Test2MatchValueStreamWriter" output_stream = BytesIO() match_context = MatchContext( b'25537Euro 25538Euro 25539Euro 25540Euro ') decimal_integer_value_me = DecimalIntegerValueModelElement( 'd1', DecimalIntegerValueModelElement.SIGN_TYPE_NONE, DecimalIntegerValueModelElement.PAD_TYPE_NONE) fixed_dme = FixedDataModelElement('s1', self.euro) sequence_model_element = SequenceModelElement( 'sequence', [decimal_integer_value_me, fixed_dme]) match_value_stream_writer = MatchValueStreamWriter( output_stream, [self.match_sequence_d1, self.match_sequence_s1], b'', b'-') self.analysis_context.register_component(match_value_stream_writer, description) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) match_element = sequence_model_element.get_match_element( 'match', match_context) log_atom = LogAtom(match_context.match_data, ParserMatch(match_element), 1, match_value_stream_writer) match_value_stream_writer.receive_atom(log_atom) self.assertEqual(output_stream.getvalue().decode(), '25537Euro \n25538Euro \n25539Euro \n25540Euro \n')
def create_thumbnail(image_model_instance): image_path = image_model_instance.original.name image_name = image_path.split('/').pop() pil_image = open_image(MEDIA_ROOT + image_path) pil_image.thumbnail(thumbnail_size, Image.ANTIALIAS) f = BytesIO() try: pil_image.save(f, format=u'JPEG') s = f.getvalue() image_model_instance.thumbnail.save("thumb_%s" % image_name, ContentFile(s)) finally: f.close()
def pdf_response(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="test.pdf"' buff = BytesIO() p = canvas.Canvas(buff) p.drawString(100, 100, "hello world.") p.showPage() p.save() pdf = buff.getvalue() buff.close() response.write(pdf) return response
def __readNdxFile(self, file, dic): fileName = file.filename sizeFile = file.file_size fileData = self.__zipFile.read(fileName, 'rU') bt = BytesIO(fileData) bt.seek(0) lenBytes = bt.read(2) # lenSum = self.BytesToInt(lenBytes) # print "lenSum = ", lenSum while bt.tell() < sizeFile: lenBytes12 = bt.read(12) # NULL bytes bytesNull = lenBytes12[0:2] bytesNullInt = self.BytesToInt(bytesNull) # FILETIME bytes bytesFileTime = lenBytes12[2:10] bytesFileTimeInt = self.BytesToInt(bytesFileTime) # offset in PDT bytes bytesOffsetPdt = lenBytes12[10:12] bytesOffsetPdtInt = self.BytesToInt(bytesOffsetPdt) startTimeInt = self.FiletimeToUnixtimestamp(bytesFileTimeInt) if bytesOffsetPdtInt not in dic.keys(): dic[bytesOffsetPdtInt] = [None, None] dic[bytesOffsetPdtInt][1] = startTimeInt bt.close()
def parse_data(src): # HTML解析 et = html.fromstring(src) # 整理数据 product_items_list = et.xpath( "//div[@class='list-product']//div[@class='plp-slide']") final_list = [] for i in product_items_list: data = {} data["img_box_src"] = i.xpath(".//div[@class='img-box']//img/@lazysrc") data["img_box_src"] = data["img_box_src"][0] if data[ "img_box_src"] else "" data["goods_tit"] = i.xpath(".//p[@class='goods-tit']/a/text()") data["goods_tit"] = data["goods_tit"][0] if data["goods_tit"] else "" data["goods_introudce"] = i.xpath( ".//p[@class='goods-introudce']/a/text()") data["goods_introudce"] = data["goods_introudce"][0] if data[ "goods_introudce"] else "" goods_classify = i.xpath(".//div[@class='goods-classify']//span") gc_list = data["goods_classify"] = [] for gc in goods_classify: dgc = {} dgc["title"] = gc.xpath("./img/@title") dgc["title"] = dgc["title"][0] if dgc["title"] else "" dgc["title"] = dgc["title"].replace('\xa0', ' ') dgc["code"] = gc.xpath("./@data-code") dgc["code"] = dgc["code"][0] if dgc["code"] else "" dgc["saleprice"] = gc.xpath("./@data-saleprice") dgc["saleprice"] = dgc["saleprice"][0] if dgc["saleprice"] else "" dgc["img_src"] = gc.xpath("./img/@src") dgc["img_src"] = dgc["img_src"][0] if dgc["img_src"] else "" # 解析SKU颜色值 if dgc["img_src"]: req_img = requests.get(dgc["img_src"], verify=False) img_data = req_img.content bio = BytesIO() bio.write(img_data) bio.seek(0) pimg = Image.open(bio) # 读入PIL图像 pimg.thumbnail((1, 1)) # 转换为1x1像素的图片 r, g, b = pimg.getcolors( pimg.size[0] * pimg.size[1])[0][1] # 形式:[(1, (223, 218, 212))] dgc["img_color"] = '#%02x%02x%02x' % (r, g, b) pimg.close() bio.close() else: dgc["img_color"] = "" gc_list.append(dgc) final_list.append(data) return final_list
def restore_tokens(self, file: _io.BytesIO): self.tokens.clear() while True: flag = int.from_bytes(file.read(1), "big") if flag == 0: self.tokens.append(stl.Token((stl.EOF, None))) break else: line = int(stl.read_string(file)) file_name = stl.read_string(file) lf = line, file_name if flag == 1: token: stl.NumToken = stl.NumToken(lf, stl.read_string(file)) elif flag == 2: token: stl.LiteralToken = stl.LiteralToken( lf, stl.read_string(file)) elif flag == 3: token: stl.IdToken = stl.IdToken(lf, stl.read_string(file)) elif flag == 4: token: stl.DocToken = stl.DocToken(lf, stl.read_string(file)) else: raise stl.ParseException("Unknown flag: {}".format(flag)) self.tokens.append(token)
async def __call__(self, scope: Scope, receive: Receive, send: Send): if scope["type"] == "lifespan": if (await receive())["type"] == "lifespan.startup": self.executor = ThreadPoolExecutor(max_workers=20, ) await send({'type': 'lifespan.startup.complete'}) if (await receive())["type"] == "lifespan.shutdown": fut = ConcFuture() def _shutdown(): try: self.executor.shutdown() finally: fut.set_result(None) Thread(target=_shutdown).start() await asyncio.wrap_future(fut) await send({'type': 'lifespan.shutdown.complete'}) return if scope["type"] != "http": return input_io = BytesIO() loop = get_running_loop() send_sync = lambda data: asyncio.run_coroutine_threadsafe( send(data), loop=loop).result() server = scope.get("server", ["localhost", 80]) environ = { "REQUEST_METHOD": scope["method"], "SERVER_NAME": server[0], "SERVER_PORT": server[1], "SCRIPT_NAME": "", "PATH_INFO": scope["path"], "QUERY_STRING": scope["query_string"].decode("ascii"), "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], "wsgi.version": (1, 0), "wsgi.url_scheme": scope.get("scheme", "http"), "wsgi.input": input_io, "wsgi.errors": sys.stderr, "wsgi.multithread": True, "wsgi.multiprocess": True, "wsgi.run_once": False, } fut = get_running_loop().run_in_executor( self.executor, lambda: self.run_wsgi(environ, send_sync)) task = get_running_loop().create_task( self.run_wsgi_feeder(scope, receive, fut, input_io)) await fut if not task.done(): task.cancel() try: await task except CancelledError: pass
def func4(): """ StringIO顾名思义就是在内存中读写str。 """ f = StringIO("可以这样初始化#\t#\t") # f = StringIO() f.write("HelloWorld!") # 后面写入会覆盖初始化 print(f.getvalue()) # getvalue()方法用于获得写入后的str。 """ StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO """ fb = BytesIO() # f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')#也可以这样初始化 fb.write("测试中文".encode(encoding='utf_8')) print(fb.getvalue()) pass
def open_as_bytes_stream(filename) -> _io.BufferedReader: """ If file's size < 2GB, read whole file as BytesIO object """ filesize = os.path.getsize(filename) if filesize < MAX_FILE_SIZE_32BIT: with open(filename, 'rb') as f: return BytesIO(f.read(filesize)) else: return open(filename, 'rb', buffering=BEST_IO_BUFFER_SIZE)
def read_tick(filename): if isinstance(filename, BytesIO): gf = GzipFile(fileobj=filename) elif isinstance(filename, bytes): gf = GzipFile(fileobj=BytesIO(filename)) else: gf = GzipFile(filename) return list(select(gf))
def test_read_string(): a = b" test1 test2" with BytesIO(a) as sp: print("first time", utils.read_string(sp)) print("second time", utils.read_string(sp)) print("third time", utils.read_string(sp))
def get(self, request, *args, **kwargs): #Indicamos el tipo de contenido a devolver, en este caso un pdf response = HttpResponse(content_type='application/pdf') #La clase io.BytesIO permite tratar un array de bytes como un fichero binario, se utiliza como almacenamiento temporal buffer = BytesIO() #Canvas nos permite hacer el reporte con coordenadas X y Y pdf = canvas.Canvas(buffer) #Llamo al método cabecera donde están definidos los datos que aparecen en la cabecera del reporte. self.cabecera(pdf) self.tabla(pdf) self.razas(pdf) #Con show page hacemos un corte de página para pasar a la siguiente pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def get(self, request, transaction_number, challan_number): item_list = json.loads(requests.get(PURCHASE_ITEM_LIST).text) uom = json.loads(requests.get(UNIT_OF_MEASURE).text) # po_line_statuses = requests.get(PURCHASE_ORDER_LINES_STATUS) po_receipt_statuses = json.loads( requests.get(PURCHASE_ORDER_HEADER_STATUS).text) receipt_details = json.loads( requests.get(RECEIPT_SEARCH + 'challan_number=' + challan_number).text) if receipt_details['receipt_details'][0]['challan_date']: receipt_details['receipt_details'][0][ 'challan_date'] = receipt_details['receipt_details'][0][ 'challan_date'].split(' ')[0] # po_type = json.loads(requests.get(PURCHASE_ORDER_TYPE).text) # supplier_list = json.loads(requests.get(SUPPLIER_LIST).text) # # data= {'user' : request.user.username, # 'po_type' : po_type['purchaseOrderType'], # 'supplier_list' : supplier_list['supplierLists'], # 'item_list' : item_list['itemDetailsList'], # 'uom' : uom['UnitOfMeasure'] # } data = { 'transaction_number': transaction_number, 'item_list': item_list['itemDetailsList'], 'uom': uom['UnitOfMeasure'], 'po_receipt_statuses': po_receipt_statuses['purchaseOrderHeaderStatus'], 'details': receipt_details['receipt_details'][0] } template = jinja_template.get_template( 'pdf-templates/purchase_challan.html') html = template.render(request, data=data) response = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), response) if not pdf.err: resp = HttpResponse(response.getvalue(), content_type='application/pdf') resp[ 'Content-Disposition'] = 'attachment; filename="PurchaseChallan.pdf"' return resp else: return HttpResponse("Error Rendering PDF", status=400)
def __readPdtFile(self, file, dic): fileName = file.filename sizeFile = file.file_size fileData = self.__zipFile.read(fileName, 'rU') bt = BytesIO(fileData) bt.seek(int('0x01A', 0)) while bt.tell() < sizeFile: pos = bt.tell() lenBytes = bt.read(2) lenBytesHex = "0x" + ''.join( [ "%02X" % ord( x ) for x in reversed(lenBytes) ] ) lenSum = int(lenBytesHex, 0) bytesProName = unicode(bt.read(lenSum), self.__jtvEncodeProgrammName) if pos not in dic.keys(): dic[pos] = [None, None] dic[pos][0] = bytesProName bt.close()
def file_downloaded(self, response, request, info): filenames = re.findall(r'filename="(.+)\.pgn"', response.headers['Content-Disposition']) hash = filenames[0] body = response.body.decode('gbk') Event = re.findall(r'Event\s+"(.+)"', body)[0] Date = re.findall(r'Date\s+"(.+)"', body)[0] RedTeam = re.findall(r'RedTeam\s+"(.+)"', body)[0] Red = re.findall(r'Red\s+"(.+)"', body)[0] BlackTeam = re.findall(r'BlackTeam\s+"(.+)"', body)[0] Black = re.findall(r'Black\s+"(.+)"', body)[0] Result = re.findall(r'Result\s+"(.+)"', body)[0] ECCO = re.findall(r'ECCO\s+"(.+)"', body)[0] Opening = re.findall(r'Opening\s+"(.+)"', body)[0] sql = "INSERT INTO qipu (`date`, ecco, result, event, hash, redTeam, red, blackTeam, black, opening) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % ( Date, ECCO, Result, Event, hash, RedTeam, Red, BlackTeam, Black, Opening) print(sql) con = pymysql.Connect( host='rm-bp149hof32gt0cewt7o.mysql.rds.aliyuncs.com', port=3306, db='aichess', user='******', passwd='Java19786028', charset='utf8') cursor = con.cursor() try: cursor.execute(sql) con.commit() except: con.rollback() finally: cursor.close() con.close() buf = BytesIO(response.body) checksum = md5sum(buf) buf.seek(0) self.store.persist_file(hash + '.pgn', buf, info) return checksum
def __GetIcon(self): icon_png = None icon_jpg = None icon_fallback = None try: iconList = self.FindInDescription('d:device/d:iconList') for icon in iconList: width = int(self.FindInDescription('d:width', icon).text) mimetype = self.FindInDescription('d:mimetype', icon).text if width >= 32 and mimetype == 'image/png': icon_png = icon break elif width >= 32 and mimetype == 'image/jpeg': icon_jpg = icon else: if icon_fallback: fallback_width = int( self.FindInDescription('d:width', icon_fallback).text) if fallback_width < width: icon_fallback = icon else: icon_fallback = icon except Exception as e: self._logger.warning("{}: {}".format(self.name, str(e))) self.__icon = None return if icon_png: icon = icon_png elif icon_jpg: icon = icon_jpg elif icon_fallback: icon = icon_fallback try: icon_url = self.FindInDescription('d:url', icon).text icon_url = self.path_to_url(icon_url) icon_data = urlopen(icon_url).read() sbuf = BytesIO(icon_data) image = wx.Image(sbuf) image = image.Scale(32, 32, wx.IMAGE_QUALITY_BICUBIC) self.__icon = image.ConvertToBitmap() except Exception as e: self._logger.warning("{}: {}".format(self.name, str(e))) self.__icon = wx.Bitmap.FromRGBA(32, 32, 255, 255, 255, 255) return
def update_item_pic(self, args): job_item = args[0] file_name = job_item.file_name item_obj = job_item.item_obj # ----此处二次处理图片为缩略图,避免内存溢出,并使用高斯模糊滤镜---- # PIL打开图片 img = Image.open(file_name) # 锁定长宽比缩小图片 w, h = img.size ratio = self.PIC_SIZE / (h if h >= w else w) img = img.resize((int(w * ratio), int(h * ratio)), Image.ANTIALIAS) w, h = img.size # 顺便重新获取大小,供后面计算使用 # 高斯模糊 img = img.filter(ImageFilter.GaussianBlur(radius=2)) # 暂存于内存中,使用BytesIO bio = BytesIO() img.save(bio, 'jpeg') # 关闭PIL图像句柄 img.close() # 利用QPainter将图片在QImage内居中显示 qimg = QImage.fromData(bio.getvalue()) new_qimg = QImage(self.PIC_SIZE, self.PIC_SIZE, QImage.Format_ARGB32) new_qimg.fill(Qt.white) # 填充白色作为背景,否则显示效果会有些诡异 pnt = QPainter() pnt.begin( new_qimg ) # 经测试,在slot里面一定要用QPainter.begin()、QPainter.end(),否则会报错“QPaintDevice: Cannot destroy paint device that is being painted” pnt.drawImage(max((self.PIC_SIZE - w) / 2, 0), max((self.PIC_SIZE - h) / 2, 0), qimg) # 居中画图 pnt.end() # 将QImage显示在QListWidgetItem上 icon = QIcon(QPixmap.fromImage(new_qimg)) item_obj.setIcon(icon) # 将QListWidgetItem对象添加到界面上的QListWidget中 with self.data_lock: self.lwPicsList.addItem(item_obj) self.update_label_text(self.LABEL_FMT.format(len(self.data_list))) # 关闭BytesIO句柄 bio.close()
def sideeffect(url_, timeout=None): try: url = url_.get_full_url() except AttributeError: url = url_ if "geofon" in url: if isinstance(geofon_retval, Exception): raise geofon_retval # pylint: disable=raising-bad-type if geofon_retval is None: with open(os.path.join(DATADIR, "ZE.network.xml")) as opn: return BytesIO(opn.read()) else: return BytesIO(geofon_retval) elif 'doi.org' in url: if isinstance(doicit_retval, Exception): raise doicit_retval # pylint: disable=raising-bad-type if doicit_retval is None: return BytesIO("Marc Smith (2002): A Paper. %s" % url.encode('utf8')) return BytesIO(doicit_retval) else: if isinstance(others_retval, Exception): raise others_retval # pylint: disable=raising-bad-type if others_retval is None: with open(os.path.join(DATADIR, "other_stations.xml")) as opn: return BytesIO(opn.read()) else: return BytesIO(others_retval)
class BaseBitcoinClient(object): def __init__(self, socket): self.socket = socket self.buffer = BytesIO() self.stop_client = False def close_stream(self): self.socket.close() def send_message(self, message): self.socket.sendall(message.to_bytes()) def handshake(self): # Send a "version" message to start the handshake msg = msg_version() # See BIP 111 (https://github.com/bitcoin/bips/blob/master/bip-0111.mediawiki) msg.nVersion = 70011 msg.fRelay = False # If false then broadcast transactions will not be announced until a filter{load,add,clear} command is received self.send_message(msg) def handle_version(self, _): # Respond with a "verack" message to a "version" message msg = msg_verack() self.send_message(msg) def handle_ping(self, ping_message): # Respond with a pong message to a ping message msg = msg_pong() msg.nonce = ping_message.nonce self.send_message(msg) def run(self): while self.stop_client != True: # Read and store the data from the socket data = self.socket.recv(64) self.buffer.write(data) try: # Go at the beginning of the buffer self.buffer.seek(0) # Deserialize the message message = MsgSerializable().stream_deserialize(self.buffer) # Reset the buffer remaining = self.buffer.read() self.buffer = BytesIO() self.buffer.write(remaining) # Call handle function if message is not None: handle_func_name = "handle_" + message.command.decode( "utf-8") handle_func = getattr(self, handle_func_name, None) if handle_func: handle_func(message) except SerializationTruncationError: # Read more data from the socket pass
def generate(width, height, image_format='PNG'): image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) text = "{}x{}".format(width, height) isexst = cache.get(text) if isexst is None: textwidth, textheight = draw.textsize(text) if textwidth < width and textheight < height: texttop = (height - textheight) // 2 textleft = (width - textwidth) // 2 draw.text((textleft, texttop), text, fill=(255, 0, 0)) content = BytesIO() image.save(content, image_format) content.seek(0) cache.set(text, content, 60 * 60) # image.show() return isexst # generate(100, 100)
def show_map(): f = open("map.png", "rb") img = ImageTk.PhotoImage(Image.open(BytesIO(f.read()))) maplabel.config(image=img) maplabel.img = img maplabel.place(x=window.winfo_width() / 2, y=window.winfo_height() / 2, anchor="center") giflabel.place_forget() global check_gif check_gif = False # GIF is no longer being played
async def filter(ctx, arg): sendfile = 0 for file in ctx.message.attachments: sendfile = 1 link = requests.get(file.url) img = Image.open(BytesIO(link.content)) img.save('image.jpg') image = cv2.imread('image.jpg') filename = 'filtered.jpg' if arg == 'blur': blurred = cv2.GaussianBlur(image,(33,33,),0) # blurred = cv2.medianBlur(image,55) cv2.imwrite(filename,blurred) await ctx.message.channel.send(file=discord.File(filename)) elif arg == 'gray': gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite(filename,gray) await ctx.message.channel.send(file=discord.File(filename)) elif arg == 'edge': gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray,(5,5,),0) edged = cv2.Canny(blurred,85,85) cv2.imwrite(filename,edged) await ctx.message.channel.send(file=discord.File(filename)) elif arg == 'reflect': flip = cv2.flip(image, 1) cv2.imwrite(filename,flip) await ctx.message.channel.send(file=discord.File(filename)) elif arg == 'bright': array = np.array([[0.01, 0.54, 0.9],[0.4, 0.01, 0.4],[0.01, 0.2, 0.01]]) bright = cv2.filter2D(image, -1, array) cv2.imwrite(filename,bright) await ctx.message.channel.send(file=discord.File(filename)) elif arg == '70s': gray = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) cv2.imwrite(filename,gray) await ctx.message.channel.send(file=discord.File(filename)) else: await ctx.message.channel.send('Improper Usage\nFilters: **blur, gray, edge, reflect, bright, 70s**\nFilter Usage Example: *&filter edge*') if sendfile == 0: await ctx.message.channel.send('Improper Usage\nFilters: **blur, gray, edge, reflect, bright, 70s**\nFilter Usage Example: *&filter edge*')
def _create_dataset(): examples_file, label_file = BytesIO(), BytesIO() examples_file.name = 'examples.csv' label_file.name = 'labels.csv' iris = load_iris() numpy.savetxt(examples_file, iris.data, delimiter=',') numpy.savetxt(label_file, iris.target, delimiter=',') examples_file.seek(0), label_file.seek(0) return examples_file, label_file
def test__BytesIO_seek(self): x = BytesIO() # these should all succeed x.seek(0) x.seek(long(0)) x.seek(0, 0) x.seek(long(0), 0) x.seek(0, long(0)) x.seek(long(0), long(0)) # these should all fail self.assertRaises(TypeError, x.seek, 0, 0.0) self.assertRaises(TypeError, x.seek, long(0), 0.0) self.assertRaises(ValueError, x.seek, 0, 1000) self.assertRaises(ValueError, x.seek, long(0), 1000) self.assertRaises(OverflowError, x.seek, 0, sys.maxsize+1) self.assertRaises(OverflowError, x.seek, long(0), sys.maxsize+1) self.assertRaises(TypeError, x.seek, 0.0) self.assertRaises(TypeError, x.seek, 0.0, 0) self.assertRaises(OverflowError, x.seek, sys.maxsize+1) self.assertRaises(OverflowError, x.seek, sys.maxsize+1, 0)
def useByteIO(): b = BytesIO() b.write('中文'.encode(encoding='utf_8')) printStrIO(b)
def export_pdf(de_thi, dapan): ''' export de thi trac nghiem ra pdf ''' socau = len(dapan) table_data=[] table_data.append([u'HỌC VIỆN HẬU CẦN', u'ĐỀ THI KẾT THÚC MÔN']) table_data.append([u'%s' %de_thi.logSinhDe.monHoc.khoa.ten_dv, u'MÔN: ' + de_thi.logSinhDe.monHoc.ten_mon_thi]) table_data.append([u'', u'Đối tượng: ' + de_thi.logSinhDe.doiTuong.ten_dt]) table_data.append([u'', u'Thời gian: ']) table_data.append([u'', u'Đề gồm: ' + str(socau) + u' câu']) buf = BytesIO() # file_name = 'dethi.pdf' doc = SimpleDocTemplate(buf) pars = [Spacer(1, 0.1*inch)] # pars = [] title_table = Table(table_data, colWidths=[(PAGE_WIDTH-100)/2.0]*2) title_table.setStyle(TableStyle([('FONT', (0,0), (1,1), 'TimesBd', 13), ('FONT', (0,2), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ])) pars.append(title_table) pars.append(Spacer(1, 0.5*inch)) sv_info_table_data = [[u'Mã môn học: '+ de_thi.logSinhDe.monHoc.ma_mon_thi + u' - Số tín chỉ (hoặc đvht): ' , u'Mã đề thi']] sv_info_table_data.append([u'Lớp: ' ,de_thi.maDeThi]) sv_info_table_data.append([u'Mã học viên, sinh viên: ','']) sv_info_table_data.append([u'Họ tên học viên, sinh viên: ','']) sv_info_table = Table(sv_info_table_data, colWidths=[PAGE_WIDTH-200, 100]) sv_info_table.setStyle(TableStyle([('FONT', (1,0), (-1,-1), 'TimesBd', 13), ('FONT', (0,0), (0,-1), 'Times', 13), ('ALIGN', (1,0), (-1,-1), 'CENTER'), ('BOX', (1,0), (-1,-1), 1.25, colors.black), ])) pars.append(sv_info_table) pars.append(Spacer(1, 0.5*inch)) n = 1 for question, answers in dapan: # question p = Paragraph(u'Câu ' + str(n) + ": " + question.noiDung, question_style) n += 1 pars.append(p) # answers ls = ['A. ', 'B. ', 'C. ', 'D. '] for l, answer in zip(ls, answers): pars.append(Spacer(1, 0.03*inch)) p = Paragraph(l + answer.dapAn, answer_stype) pars.append(p) pars.append(Spacer(1, 0.03*inch)) pars.append(Spacer(1, 0.05*inch)) # ký sig_table_data = [[u'-------HẾT--------', u'']] sig_table_data.append([u'' ,u'TRƯỞNG KHOA']) sig_table_data.append([u'' ,u'(Ký, họ tên)']) sig_table = Table(sig_table_data, colWidths=[PAGE_WIDTH-300, 200]) sig_table.setStyle(TableStyle([('FONT', (0,0), (1,0), 'Times', 13), ('FONT', (0,1), (1,1), 'TimesBd', 13), ('FONT', (0,2), (1,2), 'TimesIt', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('SPAN',(0,0),(1,0)), ])) pars.append(sig_table) doc.build(pars, onFirstPage=myFirstPage, onLaterPages=myLaterPages) # Get the value of the BytesIO buffer and write it to the response. pdf = buf.getvalue() buf.close() return pdf
def export_baithi_dapan_pdf(de_thi, dapan, baithi): ''' export de thi trac nghiem ra pdf ''' socau = len(dapan) table_data=[] table_data.append([u'HỌC VIỆN HẬU CẦN', u'ĐÁP ÁN MÔN THI']) table_data.append([u'%s' %de_thi.logSinhDe.monHoc.khoa.ten_dv, u'MÔN: ' + de_thi.logSinhDe.monHoc.ten_mon_thi]) table_data.append([u'', u'Đối tượng: ' + de_thi.logSinhDe.doiTuong.ten_dt]) table_data.append([u'', u'Thời gian: ']) table_data.append([u'', u'Đề gồm: ' + str(socau) + u' câu']) buf = BytesIO() # file_name = 'dethi.pdf' doc = SimpleDocTemplate(buf) pars = [Spacer(1, 0.1*inch)] # pars = [] title_table = Table(table_data, colWidths=[(PAGE_WIDTH-100)/2.0]*2) title_table.setStyle(TableStyle([('FONT', (0,0), (1,1), 'TimesBd', 13), ('FONT', (0,2), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ])) pars.append(title_table) pars.append(Spacer(1, 0.5*inch)) sv_info_table_data = [[u'Mã môn học: '+ de_thi.logSinhDe.monHoc.ma_mon_thi + u' - Số tín chỉ (hoặc đvht): ' , u'Mã đề thi']] sv_info_table_data.append([u'Lớp: ' ,de_thi.maDeThi + baithi.thi_sinh.ma_sv.split('-')[1]]) sv_info_table_data.append([u'Mã học viên, sinh viên: ','']) sv_info_table_data.append([u'Họ tên học viên, sinh viên: ','']) sv_info_table = Table(sv_info_table_data, colWidths=[PAGE_WIDTH-200, 100]) sv_info_table.setStyle(TableStyle([('FONT', (1,0), (-1,-1), 'TimesBd', 13), ('FONT', (0,0), (0,-1), 'Times', 13), ('ALIGN', (1,0), (-1,-1), 'CENTER'), ('BOX', (1,0), (-1,-1), 1.25, colors.black), ])) pars.append(sv_info_table) pars.append(Spacer(1, 0.5*inch)) for i in xrange(1, len(dapan)+1): cau_hoi = str(i) dap_an = dapan[cau_hoi] # question p = Paragraph(u'Câu ' + cau_hoi + ": " + dap_an, answer_stype) pars.append(p) pars.append(Spacer(1, 0.05*inch)) # ký sig_table_data = [[u'-------HẾT--------', u'']] sig_table_data.append([u'' ,u'TRƯỞNG KHOA']) sig_table_data.append([u'' ,u'(Ký, họ tên)']) sig_table = Table(sig_table_data, colWidths=[PAGE_WIDTH-300, 200]) sig_table.setStyle(TableStyle([('FONT', (0,0), (1,0), 'Times', 13), ('FONT', (0,1), (1,1), 'TimesBd', 13), ('FONT', (0,2), (1,2), 'TimesIt', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('SPAN',(0,0),(1,0)), ])) pars.append(sig_table) doc.build(pars, onFirstPage=myFirstPage, onLaterPages=myLaterPages) # Get the value of the BytesIO buffer and write it to the response. pdf = buf.getvalue() buf.close() return pdf
def export_bangdiem(baithi): ''' export bang diem ra pdf ''' rows_len = len(baithi) table_data=[] table_data.append([u'BỘ QUỐC PHÒNG', u'CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM']) table_data.append([u'HỌC VIỆN HẬU CẦN', u'Độc lập - Tự do - Hạnh phúc']) table_data.append([u'', u'Hà Nội, ngày ' + str(timezone.now().day) + u' tháng ' + str(timezone.now().month) + u' năm ' + str(timezone.now().year)]) buf = BytesIO() # file_name = 'dethi.pdf' doc = SimpleDocTemplate(buf) pars = [Spacer(1, 0.1*inch)] # pars = [] title_table = Table(table_data, colWidths=[250, PAGE_WIDTH-250]) title_table.setStyle(TableStyle([('FONT', (0,0), (1,1), 'TimesBd', 13), ('FONT', (0,2), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ])) pars.append(title_table) pars.append(Spacer(1, 0.5*inch)) bd_title_table_data = [[u'BÁO CÁO KẾT QUẢ THI']] bd_title_table_data.append([u'môn: ' + baithi[0].khthi.mon_thi.ten_mon_thi + u' đvht: ' + str(baithi[0].khthi.mon_thi.so_dvht)]) ngay_thi = '%d - %d - %d' %(baithi[0].khthi.ngay_thi.day, baithi[0].khthi.ngay_thi.month, baithi[0].khthi.ngay_thi.year) bd_title_table_data.append([u'lớp: ' + baithi[0].thi_sinh.lop.ten_lop + u' ngày thi: ' + ngay_thi]) bd_title_table = Table(bd_title_table_data, colWidths=[PAGE_WIDTH]) bd_title_table.setStyle(TableStyle([('FONT', (0,0), (0,0), 'TimesBd', 14), ('FONT', (0,1), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), #('BOX', (1,0), (-1,-1), 1.25, colors.black), ])) pars.append(bd_title_table) pars.append(Spacer(1, 0.5*inch)) bd_table_data = [[u'STT', u'Họ tên', u'Điểm', u'Ghi chú']] n = 1 for bt in baithi: row = [str(n), bt.thi_sinh.get_ho_ten, str(bt.diem), ""] bd_table_data.append(row) n = n + 1 bd_table = Table(bd_table_data, colWidths=[50, 250, 50, 100]) bd_table.setStyle(TableStyle([('FONT', (0,0), (3,0), 'TimesBd', 13), ('FONT', (0,1), (-1,-1), 'Times', 13), ('ALIGN', (0,0), (-1,0), 'CENTER'), #header ('ALIGN', (0,0), (0,-1), 'CENTER'), #STT ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.5, colors.black), ])) pars.append(bd_table) pars.append(Spacer(1, 0.5*inch)) # ký sig_table_data = [[u'-------HẾT--------', u'']] sig_table_data.append([u'' ,u'TRƯỞNG KHOA']) sig_table_data.append([u'' ,u'(Ký, họ tên)']) sig_table = Table(sig_table_data, colWidths=[PAGE_WIDTH-300, 200]) sig_table.setStyle(TableStyle([('FONT', (0,0), (1,0), 'Times', 13), ('FONT', (0,1), (1,1), 'TimesBd', 13), ('FONT', (0,2), (1,2), 'TimesIt', 13), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('SPAN',(0,0),(1,0)), ])) pars.append(sig_table) doc.build(pars, onFirstPage=myFirstPage, onLaterPages=myLaterPages) # Get the value of the BytesIO buffer and write it to the response. pdf = buf.getvalue() buf.close() return pdf