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 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 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 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 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 writepkg(self, pkg_filename, include_media): "Code copied from gramps/plugins/export/exportpkg.py" try: archive = tarfile.open(pkg_filename, 'w:gz') except EnvironmentError as msg: log.warning(str(msg)) self.user.notify_error( _('Failure writing %s') % pkg_filename, str(msg)) return 0 # Write media files first, since the database may be modified # during the process (i.e. when removing object) if include_media: for m_id in self.db.get_media_handles(sort_handles=True): mobject = self.db.get_media_from_handle(m_id) filename = media_path_full(self.db, mobject.get_path()) archname = str(mobject.get_path()) if os.path.isfile(filename) and os.access(filename, os.R_OK): archive.add(filename, archname, filter=fix_mtime) # Write XML now g = BytesIO() gfile = XmlWriter(self.db, self.user, 2, compress=1, material_type=self.material_type, description=self.description) gfile.write_handle(g) tarinfo = tarfile.TarInfo('data.gramps') tarinfo.size = len(g.getvalue()) tarinfo.mtime = time.time() if not win(): tarinfo.uid = os.getuid() tarinfo.gid = os.getgid() g.seek(0) archive.addfile(tarinfo, g) archive.close() g.close() return True
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 downloadfile1(allfile, facebookdata): panjang = len(allfile) if panjang == 3: ##do something f = StringIO() wb = Workbook() ws = wb.active for row in facebookdata: f.write(row.name + ',' + row.status + ',' + str(row.like) + ',' + str(row.comment) + ',' + str(row.share)) f.write('\n') ws.append([row.name, row.status, row.like, row.comment, row.share]) f.flush() f.seek(0) ##make json g = StringIO() data = [] for row in facebookdata: data1 = {} data1["NAME"] = row.name data1["STATUS"] = row.status data1["LIKE"] = row.like data1["COMMENT"] = row.comment data1["SHARE"] = row.share data.append(data1) json.dump(data, g, indent=3) g.flush() g.seek(0) output = BytesIO() zip = ZipFile(output, 'w') zip.writestr("Data_facebook.csv", f.getvalue()) zip.writestr("Data_facebook.JSON", g.getvalue()) zip.writestr("Data_facebook.xlsx", save_virtual_workbook(wb)) zip.close() response = HttpResponse(output.getvalue(), content_type='application/octet-stream') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.zip' return response elif panjang == 2: ##read list if '0' and '1' in allfile: ##return csv and json print('csv and jsn') #make csv f = StringIO() for row in facebookdata: f.write(row.name + ',' + row.status + ',' + str(row.like) + ',' + str(row.comment) + ',' + str(row.share)) f.write('\n') f.flush() f.seek(0) ##make json g = StringIO() data = [] for row in facebookdata: data1 = {} data1["NAME"] = row.name data1["STATUS"] = row.status data1["LIKE"] = row.like data1["COMMENT"] = row.comment data1["SHARE"] = row.share data.append(data1) json.dump(data, g, indent=3) g.flush() g.seek(0) output = BytesIO() zip = ZipFile(output, 'w') zip.writestr("Data_facebook.csv", f.getvalue()) zip.writestr("Data_facebook.JSON", g.getvalue()) zip.close() response = HttpResponse(output.getvalue(), content_type='application/octet-stream') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.zip' return response elif '0' and '2' in allfile: #return csv and xls print('csv and xls') f = StringIO() for row in facebookdata: f.write(row.name + ',' + row.status + ',' + str(row.like) + ',' + str(row.comment) + ',' + str(row.share)) f.write('\n') f.flush() f.seek(0) g = StringIO() wb = Workbook() ws = wb.active for row in facebookdata: ws.append( [row.name, row.status, row.like, row.comment, row.share]) output = BytesIO() zip = ZipFile(output, 'w') zip.writestr("Data_facebook.csv", f.getvalue()) zip.writestr("Data_facebook.xlsx", save_virtual_workbook(wb)) zip.close() response = HttpResponse(output.getvalue(), content_type='application/octet-stream') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.zip' return response else: #return json xls #make json file f = StringIO() data = [] for row in facebookdata: data1 = {} data1["NAME"] = row.name data1["TWEET"] = row.tweet data1["RETWEET_USER"] = row.Retweet_user data1["HASHTAGS"] = row.hashtag data1["DATE"] = str(row.date) data.append(data1) json.dump(data, f, indent=3) f.flush() f.seek(0) #make xls file g = StringIO() wb = Workbook() ws = wb.active for row in facebookdata: ws.append( [row.name, row.status, row.like, row.comment, row.share]) output = BytesIO() zip = ZipFile(output, 'w') zip.writestr("Data_facebook.csv", f.getvalue()) zip.writestr("Data_facebook.xlsx", save_virtual_workbook(wb)) zip.close() response = HttpResponse(output.getvalue(), content_type='application/octet-stream') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.zip' return response elif panjang == 0: ##asli print('do nothing') return HttpResponseRedirect('../search2') else: if '0' in allfile: f = StringIO() writer = csv.writer(f) for row in facebookdata: writer.writerow( [row.name, row.status, row.like, row.comment, row.share]) f.flush() f.seek(0) response = HttpResponse(FileWrapper(f), content_type='text/csv') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.csv' return response elif '1' in allfile: f = StringIO() data = [] for row in facebookdata: data1 = {} data1["NAME"] = row.name data1["STATUS"] = row.status data1["LIKE"] = row.like data1["COMMENT"] = row.comment data1["SHARE"] = row.share data.append(data1) json.dump(data, f, indent=3) f.flush() f.seek(0) response = HttpResponse(FileWrapper(f), content_type='js/json') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.json' return response else: f = StringIO() wb = Workbook() ws = wb.active for row in facebookdata: ws.append( [row.name, row.status, row.like, row.comment, row.share]) response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel') response[ 'Content-Disposition'] = 'attachment; filename=Data_facebook.xlsx' return response
#myyfactory = qrcode.image.svg.SvgImage #image.models. img = qr.make_image() #print(img) #ssuy = open("Blu_QR"+localuu[1:6]+".txt","w") #img.save("Blu_QR"+localuu[1:6]+".png", format='PNG') #img.save("Blu_QR"+localuu[1:6]+"_RLE.bmp", format='BMP', compression="bmp_rle") #img.save("Blu_QR"+localuu[1:6]+".bmp", format='BMP') bbuu = BytesIO() uiee = BytesIO() img.save(bbuu, format='PNG') bbuu.seek(0) #ssuy.flush() #bytesobj = img.tobytes('raw') #bytesobj = img.tobytes('PNG') FAILS bytesobj = bbuu.getvalue() #khyz = img.get_image() img_str = binascii.b2a_base64(bytesobj) #img_str = binascii.b2a_base64(ravdec.net_compression(bytesobj)) #img_str = ravdec.net_compression(binascii.b2a_base64(bytesobj)) #compresst = ravdec.net_compression(img_str) #compresst = ravdec.net_compression(img_str) #ssuy.writelines(img_str) #ssuy.flush() #img_str = bytesobj.format("02X") #img = qr.make(CurQuery,mfactory=myyfactory) #testbase64data = "DEFAULT ERROR" testbase64data = img_str #testbase64data = base64.b64encode(img_str) #buffer = cStringIO.StringIO(yuinn)
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
''' @author: xilh @since: 20200128 ''' from _io import BytesIO from demo.tools.tool import pline # 创建对象 f = BytesIO() f.write('hello'.encode(encoding='utf_8')) f.write(' '.encode(encoding='utf_8')) f.write('world'.encode(encoding='utf_8')) f.write(' '.encode(encoding='utf_8')) f.write('张三'.encode(encoding='utf_8')) # 获取值 ret = f.getvalue() print(ret) pline() f = BytesIO('张三是程序员'.encode('utf-8')) print(f.readline()) # 关闭 f.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Created on 2018年11月13日 @author: zzk ''' # StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。 # StringIO顾名思义就是在内存中读写str。 from io import StringIO from _io import BytesIO f=StringIO('hello\nworld\n zzk') f2=StringIO() f2.write('my\nname\nis\nzzk') print(f2.getvalue()) print('====================') while True: s=f.readline() if s=='': break print(s.strip()) print('====================') # BytesIO fb = BytesIO() fb.write('哈哈哈'.encode('utf-8')) print(fb.getvalue()) fb2 = BytesIO(b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88') print(fb2.read().decode('utf-8'))
from _io import StringIO, BytesIO f = open('E:/a.txt', 'r') for line in f.readlines(): print(line.strip()) f.close() #readline 和 readlines #像open()函数返回的这种有个read()方法的对象, #在Python中统称为file-like Object with open('E:/a.txt', 'w') as f: f.write("en") f = StringIO() f.write("hello") f.write(" ") f.write("world") print(f.getvalue()) b = BytesIO() b.write("中文".encode(encoding='utf_8', errors='strict')) str = b.getvalue() print(str)
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
''' Created on 2017年6月21日 @author: admin ''' from io import StringIO #StringIO模块的作用是在内存中读写 from _io import BytesIO f = StringIO() s = f.write('wskd fkdsa ') print(f.getvalue()) #获取写入的值 print(s) #获取长度 n = BytesIO() n.write('中文'.encode('utf_8')) #写入的不是str类型,而是经过utf-8编码的。 #n.write('中文'.encode(encoding='utf_8', errors='strict')) print(n) print(n.getvalue()) data = '人闲桂花落,夜静春山空。月出惊山鸟,时鸣春涧中。'.encode('utf-8') n = BytesIO(data) print(n) print(n.read())
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