def _render_doc(doc_type, template_name, context_instance=None, debug=None): """Render odf file content, save rendered file and return its name Args: template_name - name of template. Template is odf file with special syntax. context_instance - see django.template.Context debug - if True - print some additional information to console Returns: (output_file_name, template_name) output_file_name is the name of temporary file with rendered content template_name - real path to template odf file """ if not "tbl" in context_instance: context = { "tbl": DefaultTbl(), } else: context = {} ret2 = None with context_instance.push(context): if not "tbl" in context_instance: context_instance["tbl"] = DefaultTbl() if template_name.__class__ in (list, tuple): test = False for tname in template_name: if tname[0] == "/": name = tname if os.path.exists(name): test = True break else: for template_dir in template_dirs: name = template_dir + "/" + tname if os.path.exists(name): test = True break if test: break if not test: raise TemplateDoesNotExist(";".join(template_name)) else: name = template_name name_out = get_temp_filename() if doc_type == "ODF": doc = OdfDocTemplateTransform(name, name_out) else: doc = OOXmlDocTemplateTransform(name, name_out) ret = doc.process(context_instance, debug) if ret != 1: ret2 = (None, name) os.remove(name_out) else: ret2 = (name_out, name) return ret2
def render_to_response(self, request, template, context_instance): odfdata = request.FILES['odf_file'] file_name = get_temp_filename("temp.ods") plik = open(file_name, 'wb') plik.write(odfdata.read()) plik.close() return render_to_response_odf(file_name, context_instance=context_instance)
def process(self, request, queryset=None): status = self.cleaned_data['status'] if status: if status == '1': if 'INSTALL_FILE_NAME' in request.session: file_name = request.session['INSTALL_FILE_NAME'] archive = zipfile.ZipFile(file_name, 'r') accept_license = self.cleaned_data['accept_license'] if accept_license: initdata = archive.read('install.ini') config = configparser.ConfigParser() config.read_string(initdata.decode('utf-8')) if 'APPSET_NAME' in config['DEFAULT']: appset_name = config['DEFAULT']['APPSET_NAME'] if appset_name: ret = extract_ptig(archive, appset_name) return { 'object_list': ret, 'status': 2 } return { 'object_list': [['Invalid install file'],], 'status': 2 } else: readmedata = archive.read('README.txt') licensedata = archive.read('LICENSE.txt') return { 'object_list': None, 'status': 1, 'readmedata': readmedata.decode('utf-8'), 'licensedata': licensedata.decode('utf-8'), 'first': False } return { 'object_list': None, 'status': None } else: if 'ptig' in request.FILES: ptig = request.FILES['ptig'] file_name = get_temp_filename("temp.ptig") request.session['INSTALL_FILE_NAME'] = file_name plik = open(file_name, 'wb') plik.write(ptig.read()) plik.close() archive = zipfile.ZipFile(file_name, 'r') readmedata = archive.read('README.txt') licensedata = archive.read('LICENSE.txt') archive.close() self.initial = { 'accept_license': False, } return { 'object_list': None, 'status': 1, 'readmedata': readmedata.decode('utf-8'), 'licensedata': licensedata.decode('utf-8'), 'first': True } else: return { 'object_list': None, 'status': None }
def process(self, request, queryset=None): qlikviewdata= self.cleaned_data['rabat_file'] data = qlikviewdata.read() ret = [] file_name = get_temp_filename("temp.xlsx") plik = open(file_name, 'wb') plik.write(data) plik.close() workbook = openpyxl.load_workbook(filename=file_name, read_only=True) worksheets = workbook.get_sheet_names() worksheet = workbook.get_sheet_by_name(worksheets[0]) with settings.DB as db: db.execute(sel4, True) def insert_rabat(logo, data_od, data_do, grupa, symkar, rabat): upd = sel5 % (logo, data_od, data_do, grupa, symkar, rabat) db.execute(upd, True) for row in worksheet.rows: logo = row[0].value if logo: try: logo2 = int(logo) if logo2>0: insert_rabat(row[0].value, row[1].value.isoformat().replace('-','')[:8], row[2].value.isoformat().replace('-','')[:8], row[3].value, row[4].value, float(row[5].value)) ret.append([row[0].value, row[1].value.isoformat().replace('-','')[:8], row[2].value.isoformat().replace('-','')[:8], row[3].value, row[4].value, float(row[5].value)]) except: pass else: break return { "object_list": ret }
def draw_image(self, x, y, dx, dy, scale, png_data): png_stream = io.BytesIO(png_data) image = PIL.Image.open(png_stream) w, h = image.size (x_scale, y_scale) = self._scale_image( x, y, dx, dy, scale, w, h, ) if scale < 4: if scale != 0 and x_scale < 0.25 and y_scale < 0.25: image.thumbnail((4 * w * x_scale, 4 * h * y_scale), PIL.Image.ANTIALIAS) file_name = get_temp_filename("temp.png") image.save(file_name, "PNG") self.dc.image(file_name, x, y, w * x_scale, h * y_scale) os.remove(file_name) else: pass BaseDc.draw_image(self, x, y, dx, dy, scale, png_data)
def process_import(data, sel1, sel2, sel3): ret_messages = [] file_name = get_temp_filename("temp.xlsx") plik = open(file_name, 'wb') plik.write(data) plik.close() workbook = openpyxl.load_workbook(filename=file_name, read_only=True) worksheets = workbook.get_sheet_names() worksheet = workbook.get_sheet_by_name(worksheets[0]) ret = [] def_date = str(datetime.date.today().year) with settings.DB as db: def insert_tkw(symkary, symkar2, symkar, f1, f2, f3, f4, f5, f6): upd = sel2 % ( symkary, symkar2, symkar, f1, f2, f3, f4, f5, f6 ) db.execute(upd, True) def update_tkw(symkary, symkar2, symkar, f1, f2, f3, f4, f5, f6): upd = sel3 % ( f1, f2, f3, f4, f5, f6, symkary ) db.execute(upd, True) def is_in_database(symkary): symkar2 = str(symkary).replace("'","").replace("\"","") sel = sel1 % symkar2 db.execute(sel) tab = db.fetchall() if int(tab[0][0]) == 0: return False else: return True def is_in_database(symkary): symkar2 = str(symkary).replace("'","").replace("\"","") sel = sel1 % symkar2 db.execute(sel) tab = db.fetchall() if int(tab[0][0]) == 0: return False else: return True for row in worksheet.rows: symkar = row[0].value if symkar: symkar = symkar.replace("'","").replace("\"","") if '/' in symkar: parts = symkar.split('/') if len(parts)==2: ysymkar = def_date + "/" + symkar else: ysymkar = symkar ret.append([ysymkar, parts[-1], symkar, row[1].value, row[2].value, row[3].value, row[4].value, row[5].value, row[6].value ] ) else: break for pos in ret: if not is_in_database(pos[0]): insert_tkw(pos[0], pos[1], pos[2], float(pos[3]), float(pos[4]), float(pos[5]), float(pos[6]), float(pos[7]), float(pos[8])) ret_messages.append(("Insert:", pos[1:])) else: update_tkw(pos[0], pos[1], pos[2], float(pos[3]), float(pos[4]), float(pos[5]), float(pos[6]), float(pos[7]), float(pos[8])) ret_messages.append(("Update:", pos[1:])) return ret_messages
def render_to_response(self, request, template, context_instance): firma = None if 'firm' in request.GET: firma = request.GET['firm'] print("Get:", firma) if firma: qlikviewdata= request.FILES['qlikview_file'] data = qlikviewdata.read() try: syg = data[:2].decode('utf-8') except: syg = 'bi' print("Syg:", syg) if syg=='PK': file_name = get_temp_filename("temp.xlsx") plik = open(file_name, 'wb') plik.write(data) plik.close() workbook = xlrd.open_workbook(file_name) worksheets = workbook.sheet_names() def lokalizacja_from_row(row): obj = models.qlik_lokalizacje() obj.FIRMA_ID = firma obj.MagSprz = row[0] obj.Opis = row[1] obj.Region = row[2] return obj def segmentacja_from_row(row): obj = models.qlik_segmentacja() obj.FIRMA_ID = firma try: obj.LogoP = str(int(row[0])) except: obj.LogoP = row[0] obj.Klastrowanie_BEH_FD = row[1] obj.Klastrowanie_VAL_FD = row[2] obj.Klastrowanie_BEH_Hurtownie = row[3] obj.Klastrowanie_VAL_Hurtownie = row[4] obj.Segment_2 = row[5] return obj def grupa_as_from_row(row): obj = models.qlik_grupa_asortyment() obj.FIRMA_ID = firma obj.GrupaAsortymentuNazwa = row[0] obj.GrupaAsortymentuNazwa2 = row[1] return obj for worksheet_name in worksheets: if worksheet_name == 'qlik_lokalizacje': model = models.qlik_lokalizacje obj_from_row = lokalizacja_from_row elif worksheet_name == 'qlik_grupa_asortyment': model = models.qlik_grupa_asortyment obj_from_row = grupa_as_from_row elif worksheet_name == 'qlik_segmentacja': model=models.qlik_segmentacja obj_from_row = segmentacja_from_row else: break model.objects.filter(FIRMA_ID=firma).delete() tab_obj = [] worksheet = workbook.sheet_by_name(worksheet_name) num_rows = worksheet.nrows - 1 if num_rows>1: curr_row = 1 ret = [] titles = [] first_row = worksheet.row(0) for item in first_row: if item.value: titles.append(item.value) else: break width = len(titles) if width>0: print("TITLE:", titles) while curr_row <= num_rows: row = worksheet.row(curr_row) row2 = [] for i in range(0,width): row2.append(row[i].value) curr_row += 1 obj = obj_from_row(row2) tab_obj.append(obj) print("ROW:", row2) if len(tab_obj)>500: model.objects.bulk_create(tab_obj) tab_obj = [] if len(tab_obj)>0: model.objects.bulk_create(tab_obj) return HttpResponseRedirect("../../table/qlik_firmy/-/form/list?schtml=1")
def import_table(request, app, table): if request.FILES: if 'import_file' in request.FILES: data = request.FILES['import_file'] name = data.name ext = name.split('.')[-1].lower() model = import_model(app, table) table = [] if ext in ('xlsx', 'xls', 'ods'): if ext == 'ods': d = get_data(data) #print("F0", d) #buf = json_dumps(d) for key in d: table = d[key] break else: first_line = True width = 0 file_name = get_temp_filename("temp.xlsx") f = open(file_name, 'wb') f.write(data.read()) f.close() workbook = openpyxl.load_workbook(filename=file_name, read_only=True) worksheets = workbook.get_sheet_names() worksheet = workbook.get_sheet_by_name(worksheets[0]) for row in list(worksheet.rows): if first_line: first_line = False buf = [] i = 0 for pos in row: value = pos.value if value: buf.append(value) else: break i += 1 if len(buf) > 0: count = len(buf) table.append(buf) else: break else: if row[0].value: buf = [] i = 0 for pos in row: if i >= count: break buf.append(pos.value) i += 1 table.append(buf) else: break os.remove(file_name) elif ext in ('txt', 'csv'): first_line = True sep_list = [ '\t', ';', ',', '|', ] sep = None txt = data.read().decode('utf-8').replace('\r', '').split('\n') for line in txt: for pos in sep_list: if pos in line: sep = pos break break if sep: csv_reader = csv.reader(txt, delimiter=sep) for row in csv_reader: table.append(row) if table and len(table) > 1: header = list([pos.strip() for pos in table[0] if pos]) tree = False tmp = [] for pos in header: if not pos in tmp: tmp.append(pos) else: tree = True id1 = tmp.index(pos) id2 = len(tmp) break for row in table[1:]: if len(row) == len(header): x = model() parent = None for index, (attr_name, value) in enumerate(zip(header, row)): if tree: if index == id1: if row[id2]: objs = model.objects.filter( **{attr_name: value}) if len(objs) == 1: parent = objs[0] else: setattr(x, attr_name, value) elif index == id2: if row[id2]: setattr(x, attr_name, value) if parent: setattr(x, 'parent', parent) else: setattr(x, attr_name, value) else: setattr(x, attr_name, value) x.save() return {'redirect': '/schsys/ok/'} else: form = ImportTableForm(request.POST, request.FILES) else: form = ImportTableForm() return {'form': form}
def _open_binary_data(self, http_ret, page): if "application/vnd.oasis.opendocument" in http_ret.ret_content_type: cd = http_ret.response.headers.get("content-disposition") if cd: name = cd.split("filename=")[1] else: name = None p = http_ret.ptr() postfix = name.split("_")[-1][-12:] fname = get_temp_filename(postfix) with open(fname, "wb") as f: f.write(p) file_name = fname if not name: name = file_name if not hasattr(wx.GetApp(), "download_files"): wx.GetApp().download_files = [] wx.GetApp().download_files.append( (file_name, name, datetime.datetime.now())) return self.new_main_page("^standard/odf_view/odf_view.html", name, parameters=name) elif "application/pdf" in http_ret.ret_content_type: p = http_ret.ptr() f = NamedTemporaryFile(delete=False) f.write(p) name = f.name f.close() href = ( "http://127.0.0.2/static/vanillajs_plugins/pdfjs/web/viewer.html?file=" + name) return self.new_main_page(href, name, parameters={"schtml": 0}) elif "zip" in http_ret.ret_content_type: p = http_ret.ptr() f = NamedTemporaryFile(delete=False) f.write(p) name = f.name f.close() return self.new_main_page("^standard/html_print/html_print.html", name, parameters=name) else: cd = http_ret.response.headers.get("content-disposition") if cd: name = cd.split("filename=")[1].replace('"', "") else: name = "data.dat" p = http_ret.ptr() path = gettempdir() with open(os.path.join(path, name), "wb") as f: f.write(p) if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": subprocess.Popen(["open", path]) else: subprocess.Popen(["xdg-open", path]) return True