def robots(request): """Generate the robots.txt file""" response = HttpResponse(mimetype='text/plain') t = loader.get_template('simple_pages/robots.txt') c = Context({}) response.write(t.render(c)) return response
def f(request, *args, **kwargs): # 1. check origin origin = request.META.get('HTTP_ORIGIN') if origin is None: origin = request.META.get('HTTP_REFERER') if origin: origin = cors.make_origin(origin) if not cors.check_origin(request, origin): return HttpResponseForbidden('bad origin') # 2. build response result = func(request, *args, **kwargs) json_str = json_dumps(result) response = HttpResponse(content_type='application/json') for variable in ('jsonpCallback', 'callback'): if variable in request.GET: identifier = request.GET[variable] if not re.match(r'^[$a-zA-Z_][0-9a-zA-Z_$]*$', identifier): return HttpResponseBadRequest('invalid JSONP callback name') json_str = '%s(%s);' % (identifier, json_str) break else: response['Access-Control-Allow-Origin'] = origin response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'x-requested-with' response.write(json_str) return response
def keypair(request): ec2data = request.session["ec2data"] response = HttpResponse(mimetype='text/plain') response['Content-Disposition'] = 'attachment; filename={kp_name}-key.pem'.format( **ec2data) response.write(ec2data['kp_material']) return response
def generar_pdf(request): print ("Genero el PDF"); response = HttpResponse(content_type='application/pdf') pdf_name = "proveedores.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) proveedores = [] styles = getSampleStyleSheet() header = Paragraph("Listado de Proveedores", styles['Heading1']) proveedores.append(header) headings = ('No. Proveedor','Nombre','RFC','Giro','Direccion','Ciudad','Estado','Pais','Telefono','Correo','Comentario') allproveedores = [(p.num_proveedor, p.nombre, p.RFC ,p.giro ,p.direccion ,p.ciudad ,p.estado ,p.pais ,p.telefono ,p.correo ,p.comentario) for p in Proveedor.objects.all()] print (allproveedores); t = Table([headings] + allproveedores) t.setStyle(TableStyle( [ ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) proveedores.append(t) doc.build(proveedores) response.write(buff.getvalue()) buff.close() return response
def insts_status(request, host_id): """ Instances block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = [] instances = [] compute = Compute.objects.get(id=host_id) try: conn = wvmInstances(compute.hostname, compute.login, compute.password, compute.type) get_instances = conn.get_instances() except libvirtError as msg_error: errors.append(msg_error.message) for instance in get_instances: instances.append({'name': instance, 'status': conn.get_instance_status(instance), 'memory': conn.get_instance_memory(instance), 'vcpu': conn.get_instance_vcpu(instance), 'uuid': conn.get_uuid(instance), 'host': host_id, 'dump': conn.get_instance_managed_save_image(instance) }) data = json.dumps(instances) response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(data) return response
def list_qualified_applicants(request, download=True): submission_infos = (SubmissionInfo .get_qualified_submissions() .select_related(depth=1) .all()) applicants = get_applicants_from_submission_infos(submission_infos) personal_infos = build_model_dict(PersonalInfo) # added more info to applicants for a in applicants: if a.id in personal_infos: a.national_id = personal_infos[a.id].national_id FIELD_LIST = [ 'ticket_number', 'first_name', 'last_name', 'get_doc_submission_method_display', 'national_id' ] output_list = [] for a in applicants: output_list.append(dump_fields(a, FIELD_LIST)) output = u'\n'.join(output_list) response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=applicants.csv' response.write(output) return response
def SaveExcel(request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment;filename=BugList_'+time.strftime('%Y%m%d%H%M%S')+'.xls' wb = xlwt.Workbook(encoding = 'utf-8') sheet = wb.add_sheet(u'Bugs') #1st line sheet.write_merge(0, 0, 0, 4, 'Bug List') sheet.write(1,0, 'Bug ID') sheet.write(1,1, 'Problem') sheet.write(1,2, 'Create Person') sheet.write(1,3, 'Create Time') sheet.write(1,4, 'Note') row = 2 for bug in Bug.objects.all(): sheet.write(row,0, bug.id) sheet.write(row,1, bug.problem) sheet.write(row,2, bug.create_person) sheet.write(row,3, str(bug.create_time)) sheet.write(row,4, bug.note) row=row + 1 output = StringIO.StringIO() wb.save(output) output.seek(0) response.write(output.getvalue()) return response
def resguardoPdf(request, pk): resguardo = Resguardo.objects.get(id=pk) nombre = 'resguardo_' + str(resguardo.id) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename=resguardo.pdf' buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=letter) def header(): c.drawImage('static/images/CFPPCH.png', 10, 670, 130, 130) c.setLineWidth(.3) c.setFont('Helvetica-Bold', 20) c.drawString(120, 750, 'CEFPP') c.drawString(160, 740, ) c.setFont('Helvetica-Bold', 15) c.drawString(480, 750, 'Inventario') c.setFillColorRGB(255, 0, 0) c.setFont('Helvetica', 12) c.drawString(485, 735, resguardo.inventario) c.line(460, 747, 560, 747) header() c.showPage() c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def makefile(request,projectID): response = HttpResponse() response['Content-Disposition'] = 'attachment; filename=my.txt' statement = filemaker.make_Statement(projectID) print(statement) response.write(statement) return response
def get_scanner(request, station_id): if request.method == "OPTIONS": return HttpResponse() ret = '{"detail":"%s"}' auth = VigilateAuthentication() try: auth_result = auth.authenticate(request) if not auth_result: return HttpResponse(ret % "Unauthenticated", status=403) request.user = auth_result[0] except AuthenticationFailed as e: return HttpResponse(ret % e, status=401) try: station_id_int = int(station_id) station = Station.objects.filter(id=station_id_int, user=request.user.id)[0] except (ValueError, IndexError): return HttpResponse(ret % "Not found", status=404) with open(os.path.join(BASE_DIR, 'program_scanner/scanner.py'), 'r') as raw_scan: conf_scan = raw_scan.read() conf_scan = conf_scan.replace('DEFAULT_ID', station_id) conf_scan = conf_scan.replace('DEFAULT_USER', request.user.email) conf_scan = conf_scan.replace('DEFAULT_TOKEN', Station.objects.get(id=station_id_int).token) conf_scan = conf_scan.replace('DEFAULT_URL', request.get_host()) conf_scan = conf_scan.replace('DEFAULT_SCHEME', request.scheme) rep = HttpResponse(content_type='text/x-python') rep['Content-Disposition'] = 'attachment; filename=scanner.py' rep.write(conf_scan) return rep
def wrap(request, *args, **kwargs): obj = func(request, *args, **kwargs) data = json.dumps(obj, ensure_ascii=False) status = kwargs.get('status', 200) response = HttpResponse(mimetype='application/json', status=status) response.write(data) return response
def render_response(self, content, response_type='json'): if response_type == 'json': response = HttpResponse(content_type="application/json; charset=UTF-8") response.write( json.dumps(content, cls=JSONEncoder, ensure_ascii=False)) return response return HttpResponse(content)
def event_excel(request, classroom_id): classroom = Classroom.objects.get(id=classroom_id) # 記錄系統事件 if is_event_open(request) : log = Log(user_id=request.user.id, event=u'下載事件到Excel') log.save() output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output) #workbook = xlsxwriter.Workbook('hello.xlsx') worksheet = workbook.add_worksheet() date_format = workbook.add_format({'num_format': 'dd/mm/yy hh:mm:ss'}) enrolls = Enroll.objects.filter(classroom_id=classroom_id); users = [] for enroll in enrolls: if enroll.seat > 0 : users.append(enroll.student_id) events = Log.objects.filter(user_id__in=users).order_by('-id') index = 1 for event in events: if event.user_id > 0 : worksheet.write('A'+str(index), event.user.first_name) else: worksheet.write('A'+str(index), u'匿名') worksheet.write('B'+str(index), event.event) worksheet.write('C'+str(index), str(localtime(event.publish))) index = index + 1 workbook.close() # xlsx_data contains the Excel file response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Report-'+classroom.name+'-'+str(localtime(timezone.now()).date())+'.xlsx' xlsx_data = output.getvalue() response.write(xlsx_data) return response
def ical(request): cal = icalendar.Calendar() cal.add('prodid', '-//Kiberpipa//NONSGML intranet//EN') cal.add('version', '2.0') events = Event.objects.order_by('-chg_date')[:20] for e in events: if e.public: classification = u'PUBLIC' else: continue cal_event = icalendar.Event() cal_event.add('uid', u'UID:event-%s-%[email protected]' % (e.id, e.slug)) cal_event.add('summary', u'%s: %s' % (e.project, e.title)) cal_event.add('url', u'https://www.kiberpipa.org%s' % e.get_absolute_url()) cal_event.add('location', e.place.name) cal_event.add('classification', classification) cal_event.add('categories', u','.join([e.project.name, e.category.name])) # http://www.kanzaki.com/docs/ical/transp.html cal_event.add('transp', 'OPAQUE') # dtstamp means when was the last time icalendar feed has changed cal_event.add('dtstamp', ljubljana_tz.localize(datetime.datetime.now())) cal_event.add('dtstart', ljubljana_tz.localize(e.start_date)) cal_event.add('dtend', ljubljana_tz.localize(e.end_date)) cal_event.add('last-modified', ljubljana_tz.localize(e.chg_date)) organizer = icalendar.vCalAddress(u'MAILTO:[email protected]') organizer.params['cn'] = u'Kiberpipa' cal_event.add('organizer', organizer) cal.add_component(cal_event) response = HttpResponse(mimetype='text/calendar; charset=UTF-8') response.write(cal.to_ical()) return response
def download_txt_file(request,content,filename): # Text file response = HttpResponse() response["Content-Type"] = "txt/plain; charset=utf-8" response["Content-Disposition"] = 'attachment; filename=%s'%filename response.write(content) return response
def header(request): title = "Cabecera menéame" globals = {} globals['favicon'] = "icon.jpg" globals['noindex'] = True globals['tags'] = 'test1, test2' globals['description'] = 'Pruebas de descripción' globals['server_name'] = 'www.meneame.net' globals['base_url'] = '/' globals['base_static'] = 'http://static.meneame.net' globals['js_main'] = 'general01.php' globals['security_key'] = 'xxxxxxxxxxxxxxxxxxxxxxx' globals['thumbnail'] = 'void.jpg' globals['thumbnail_logo'] = 'void.jpg' globals['extra_head'] = '' globals['extra_js'] = ('void.js', 'void1.js') globals['q'] = 'q=aslkdlñak ñlsakd ñlaks&kasjlkadjlajsdljkl' globals['lang'] = 'es' globals['css_main'] = 'main.css' globals['css_color'] = 'main.css' response = HttpResponse() t = get_template("header.html") response.write(t.render(Context({'globals': globals, 'title': title}))) response.write(t.render(Context({'globals': globals, 'title': title}))) response.write(t.render(Context({'globals': globals, 'title': title}))) return response
def queryMap(request): ''' Build the mapfile in a separate view ''' response = HttpResponse() params = {} for key, value in list(query_parms.items()): if type(value) in (list, tuple): params[key] = [request.GET.get(p, None) for p in value] else: params[key] = request.GET.getlist(key) # The Javascript that constructs the request items must remove any items that will make the # server busy with requests that have nothing to do with making a map; for example, removing # 'parameterparameterpng' and 'parameterparameterx3d' removed from 'only' helps speed things up. logger.debug('Instantiating STOQSQManager with params = %s', params) qm = STOQSQManager(request, response, request.META['dbAlias'], **params) qm.buildQuerySets() options = json.dumps(qm.generateOptions(), cls=encoders.STOQSJSONEncoder) ##logger.debug('options = %s', pprint.pformat(options)) _buildMapFile(request, qm, options) response['Content-Type'] = 'text/json' response.write(options) return response
def get(self, request): fields = [ User._meta.get_field(name) for name in [ 'id', 'name', 'username', 'email', 'role', 'wechat', 'phone', 'is_active', 'comment', ] ] spm = request.GET.get('spm', '') users_id = cache.get(spm, []) filename = 'users-{}.csv'.format( timezone.localtime(timezone.now()).strftime('%Y-%m-%d_%H-%M-%S') ) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % filename response.write(codecs.BOM_UTF8) users = User.objects.filter(id__in=users_id) writer = csv.writer(response, dialect='excel', quoting=csv.QUOTE_MINIMAL) header = [field.verbose_name for field in fields] header.append(_('User groups')) writer.writerow(header) for user in users: groups = ','.join([group.name for group in user.groups.all()]) data = [getattr(user, field.name) for field in fields] data.append(groups) writer.writerow(data) return response
def cpuusage(request): """ Return CPU Usage in % """ try: cpu_usage = get_cpu_usage() except Exception: cpu_usage = 0 cpu = [ { "value": cpu_usage['free'], "color": "#0AD11B" }, { "value": cpu_usage['used'], "color": "#F7464A" } ] data = json.dumps(cpu) response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(data) return response
def export_csv_vol(modeladmin, request, queryset): # instead of text/html, we render the response as a text/csv file response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachement; filename="volunteer.csv"' writer = csv.writer(response, csv.excel) # this will ensure that the encoding is utf8 so that excel can properly open the file response.write(u'\ufeff'.encode('utf8')) # these are the four fields that will be exported by django (first row) writer.writerow([ smart_str(u"Email"), smart_str(u"First Name"), smart_str(u"Last name"), smart_str(u"Start Date"), smart_str(u"Active") ]) # now we need to write every row that the Big C for obj in queryset: s = time.strptime(str(obj.start_date.month) + ' ' + str(obj.start_date.day) + ' ' + str(obj.start_date.year), "%m %d %Y") s = time.strftime("%m/%d/%Y", s) writer.writerow([ smart_str(obj.email), smart_str(obj.first_name), smart_str(obj.last_name), smart_str(s), smart_str(obj.is_active) ]) return response
def moduleDescriptions(request, module=None): logging.info("MODULE: " + module) html = render_to_string("01cts_uberheader.html", {"title": "Error"}) html += render_to_string("02cts_uberintroblock_nomodellinks.html", {"title2": "File not found"}) html += linksLeft.linksLeft() module_text = "" if module == "chemedit-description": module_text = chemeditDescription() elif module == "pchemprop-description": module_text = pchempropDescription() elif module == "reactsim-description": module_text = reactsimDescription() elif module == "mamm-metabo": module_text = mMetabolismDescription() # body of page: html += render_to_string("04ubertext_start.html", {"model_attributes": "", "text_paragraph": module_text}) html += render_to_string("04cts_ubertext_end.html", {}) html += render_to_string("05cts_ubertext_links_right.html", {}) html += render_to_string("06cts_uberfooter.html", {"links": ""}) response = HttpResponse() response.write(html) return response
def generar_pdf_Producto(request): response = HttpResponse(content_type='application/pdf') pdf_name = "productos.pdf" buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) productos = [] styles = getSampleStyleSheet() header = Paragraph("Listado de Productos", styles['Heading1']) productos.append(header) headings = ('Proveedor','Nombre', 'Descripcion', 'Marca', 'Precio','Stock Actual') allproductos = [(p.prov_id, p.pro_nom, p.pro_des, p.pro_mar, p.pro_pre, p.pro_sto_act) for p in Producto.objects.all()] t = Table([headings] + allproductos) t.setStyle(TableStyle( [ ('GRID', (0, 0), (6, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) productos.append(t) doc.build(productos) response.write(buff.getvalue()) buff.close() return response
def public_rss(request, username, all=True, reviews=False, short_reviews=False, comments=False, links=False): try: user = User.objects.get(username__iexact=username, is_active=True) profile = user.get_profile() except: raise Http404 activty_list=[] if all==True: activty_list = UserActivity.objects.select_related().filter(user=user).exclude(activity_type = UserActivity.TYPE_RATING).exclude(post__status=Post.DRAFT_STATUS).exclude(post__status=Post.DELETED_STATUS).order_by("-created_at") if reviews==True: activty_list = UserActivity.objects.select_related().filter(user=user, activity_type = UserActivity.TYPE_POST).exclude(post__status=Post.DRAFT_STATUS).exclude(post__status=Post.DELETED_STATUS).order_by("-created_at") if short_reviews==True: activty_list = UserActivity.objects.select_related().filter(user=user, activity_type = UserActivity.TYPE_SHORT_REVIEW).order_by("-created_at") if comments==True: activty_list = UserActivity.objects.select_related().filter(user=user, activity_type = UserActivity.TYPE_COMMENT).order_by("-created_at") if links==True: activty_list = UserActivity.objects.select_related().filter(user=user, activity_type = UserActivity.TYPE_LINK).order_by("-created_at") activities = activty_list response = HttpResponse(mimetype='application/rss+xml') t = loader.get_template(templates['PLANET_RSS']) c = Context({'activities': activities,'profile':profile}) response.write(t.render(c)) return response
def get_tasktemplate_fields(request, tasktemplateid): global CUSTOM_FIELD_PREFIX template = TaskTemplate.objects.get(pk=int(tasktemplateid)) arguments = json.loads(template.arguments) response = HttpResponse() row_template = "\t<tr><td class=\"label\">%(label)s:</td><td>%(control)s</td></tr>\n" response.write("<table class=\"vertical nested_table\">\n") # loop through the top-level arguments whose values are prefixed with "?" for k in arguments: val = arguments[k][1::] label = k.replace("_"," ") if val == "CheckboxInput": response.write(row_template % {'label': label, 'control': '<input type="checkbox" name="%s%s" />' % (CUSTOM_FIELD_PREFIX, k)}) elif val == "TextInput": response.write(row_template % {'label': label, 'control': '<input type="text" name="%s%s" />' % (CUSTOM_FIELD_PREFIX, k)}) else: response.write(row_template % {'label': label, 'control': '%s' % arguments[k]}) response.write("</table>\n") return response
def analyse(request): startswith = request.GET.get("startswith") def userFilter(userObject): if startswith: return userObject.username.startswith(startswith) return True analysis_dict = gen_analysis_dict(userFilter) format = request.GET.get("format", "html") if format == "json": data_array = listify(analysis_dict, ["user", "form_image"]) return HttpResponse(json.dumps(data_array, indent=4), mimetype="application/json") elif format == "csv": temp_file = tempfile.mktemp() csvfile = open(temp_file, "wb") data_array = listify(analysis_dict, ["user", "form_image"]) utils.dict_to_csv([flatten_dict(d) for d in data_array], csvfile) csvfile.close() response = HttpResponse(mimetype="application/octet-stream") response["Content-Disposition"] = "attachment; filename=output.csv" fo = open(temp_file) response.write(fo.read()) fo.close() return response else: t = loader.get_template("analyseTranscriptions.html") c = RequestContext(request, {"formImages": analysis_dict}) return HttpResponse(t.render(c))
def displayDoc(request, id, doc): # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip order = get_object_or_404(Order, pk=id) shopDetails = Config.objects.get_current() filename_prefix = shopDetails.site.domain if doc == "invoice": filename = "%s-invoice.pdf" % filename_prefix template = "invoice.rml" elif doc == "packingslip": filename = "%s-packingslip.pdf" % filename_prefix template = "packing-slip.rml" elif doc == "shippinglabel": filename = "%s-shippinglabel.pdf" % filename_prefix template = "shipping-label.rml" else: return HttpResponseRedirect("/admin") response = HttpResponse(mimetype="application/pdf") response["Content-Disposition"] = "attachment; filename=%s" % filename icon_uri = config_value("SHOP", "LOGO_URI") t = loader.get_template(os.path.join("pdf", template)) c = Context( { "filename": filename, "iconURI": icon_uri, "shopDetails": shopDetails, "order": order, } ) pdf = trml2pdf.parseString(smart_str(t.render(c))) response.write(pdf) return response
def author_json(request, author_id): author = Author.objects.get(id=author_id) retval = {} retval["directed"] = True retval["mulitgraph"] = False retval["graph"] = [] retval["nodes"] = [] retval["links"] = [] nodes = {} edges = [] papers = [] add_author_node(author, nodes, retval, 20) dfs_author(author, nodes, edges, papers, retval, 0) #convert edges to format expected by D3 for f,t in edges: retval["links"].append( { "source" : nodes[f], "target" : nodes[t]} ) #for legible json for debugging indent = 0 try: if "indent" in request.POST: indent=int(request.POST["indent"]) if "indent" in request.GET: indent=int(request.GET["indent"]) except: pass response = HttpResponse(content_type='text/json; charset=utf-8') if indent > 0: response.write(json.dumps(retval, indent=indent)) else: response.write(json.dumps(retval)) return response
def captcha_audio(request,key): if settings.CAPTCHA_FLITE_PATH: store = get_object_or_404(CaptchaStore,hashkey=key) text=store.challenge if 'captcha.helpers.math_challenge' == settings.CAPTCHA_CHALLENGE_FUNCT: text = text.replace('*','times').replace('-','minus') else: text = ', '.join(list(text)) import tempfile, os path = str(os.path.join(tempfile.gettempdir(),'%s.wav' %key)) cline = '%s -t "%s" -o "%s"' %(settings.CAPTCHA_FLITE_PATH, text, path) os.popen(cline).read() if os.path.isfile(path): response = HttpResponse() f = open(path,'rb') response['Content-Type'] = 'audio/x-wav' response.write(f.read()) f.close() os.unlink(path) return response raise Http404
def getObs(request, mrn, obs): patient = get_object_or_404(Patient, mrn = mrn) numericobservationtype = get_object_or_404(NumericObservationType, name = obs) obs = NumericObservation.objects.filter(patient = patient, observation_type = numericobservationtype) response = HttpResponse()#content_type='text/json') response.write(json.dumps([(o.datetime.isoformat(), o.value) for o in obs])) return response
def view(request, title, revision_pk=None): if not user_or_site(request): return redirect_to_login(request.get_full_path()) url_title = utils.urlize_title(title) if title != url_title: if revision_pk: return HttpResponseRedirect(reverse('djiki-page-revision', kwargs={'title': url_title, 'revision_pk': revision_pk})) return HttpResponseRedirect(reverse('djiki-page-view', kwargs={'title': url_title})) page_title = utils.deurlize_title(title) try: page = models.Page.objects.get(title=page_title) except models.Page.DoesNotExist: t = loader.get_template('djiki/not_found.html') c = RequestContext(request, {'title': page_title}) return HttpResponseNotFound(t.render(c)) if revision_pk: try: revision = page.revisions.get(pk=revision_pk) except models.PageRevision.DoesNotExist: return HttpResponseNotFound() messages.info(request, mark_safe(_("The version you are viewing is not the latest one, " "but represents an older revision of this page, which may have been " "significantly modified. If it is not what you intended to view, " "<a href=\"%(url)s\">proceed to the latest version</a>.") % { 'url': reverse('djiki-page-view', kwargs={'title': url_title})})) else: revision = page.last_revision() if request.REQUEST.get('raw', ''): response = HttpResponse(mimetype='text/plain') response['Content-Disposition'] = 'attachment; filename=%s.txt' % quote(title.encode('utf-8')) response.write(revision.content) return response return direct_to_template(request, 'djiki/view.html', {'page': page, 'revision': revision})
def ListarPermisoAusentismo(request): listar_permisos = PermisoAusentismo.objects.all() trabajador = '' cedula = request.GET.get('cedula') mes = request.GET.get('mes') if Trabajadores.objects.all().exists(): hay_trabajador = 1 else: hay_trabajador = 0 # print(cedula) # print(mes) if cedula: listar_permisos = PermisoAusentismo.objects.filter( idTrabajador__cedula=cedula).order_by('-idPermisoAusentismo') trabajador = Trabajadores.objects.filter(cedula=cedula) else: listar_permisos = PermisoAusentismo.objects.filter().order_by( '-idPermisoAusentismo') if mes and mes != '--': listar_permisos = PermisoAusentismo.objects.filter( periodoIncapacidadInicial__month=mes).order_by( 'periodoIncapacidadInicial') if mes and mes != '--' and cedula: listar_permisos = PermisoAusentismo.objects.filter( periodoIncapacidadInicial__month=mes, idTrabajador__cedula=cedula).order_by('periodoIncapacidadInicial') #print(listar_permisos.values()) #print(listar_permisos[1].get_mes_evento_display()) paginator = Paginator(listar_permisos, 10) page = request.GET.get('page') listar_permisos = paginator.get_page(page) permiso = [''] if request.POST.get('excel'): mes = 'Mes' periodo_inicial = 'Periodo inicial' periodo_final = 'Periodo final' total_dias_incapacidad = 'Total días' total_horas = 'Tiempo total' codigo_diagnostico = 'Código de diagnostico' tipo_evento = 'Tipo de evento' observaciones = 'Observaciones' data = [] data.append([ mes, periodo_inicial, periodo_final, total_dias_incapacidad, total_horas, tipo_evento, codigo_diagnostico, observaciones ]) cont = 0 nombre_mes = "ENERO" for x in listar_permisos.object_list.values(): #x['mes_evento'] = listar_permisos[cont].get_mes_evento_display() nombre_mes = str(x["periodoIncapacidadInicial"]), x['totalDiasIncapacidad'] = str(x['totalDiasIncapacidad']) if x['totalDiasIncapacidad'] == '0': x['totalDiasIncapacidad'] = 'No aplica' #print(x['totalDiasIncapacidad']) x['tipo_evento'] = listar_permisos[cont].get_tipo_evento_display() #print(x['observaciones']) if x['horaInicial'] != None and x['horaFinal'] != None: print(str(x['horaInicial']) + ' ' + str(x['horaFinal'])) FMT = '%H:%M:%S' tdelta = datetime.strptime(str(x['horaFinal']), FMT) - datetime.strptime( str(x['horaInicial']), FMT) else: tdelta = 'No aplica' if x['observaciones'] == None: x['observaciones'] = 'Sin registro' if x['codigoDiagnostico'] == None or x['codigoDiagnostico'] == '': x['codigoDiagnostico'] = 'No aplica' if x['tipo_evento'][0:3] == 'A.C': x['tipo_evento'] = 'A.C' if x['tipo_evento'][0:3] == 'O.E': x['tipo_evento'] = 'O.E' if x['tipo_evento'][0:3] == 'A.T': x['tipo_evento'] = 'A.T' if x['tipo_evento'][0:3] == 'E.L': x['tipo_evento'] = 'E.L' formato = '%B' permiso = [ x["periodoIncapacidadInicial"].strftime(formato), x["periodoIncapacidadInicial"], x["periodoIncapacidadFinal"], x["totalDiasIncapacidad"], tdelta, x["tipo_evento"], x["codigoDiagnostico"], x["observaciones"].lower(), ] #nombre_mes = listar_permisos[cont].get_mes_evento_display() cont = cont + 1 data.append(permiso) nombre = '' nombre_documento = 'Reporte_de_ausentismo' if trabajador: nombre = str(trabajador.first().nombres) nombre_documento = 'Reporte_de_ausentismo_' + nombre.replace( ' ', '_') if mes: nombre_documento = 'Reporte_de_ausentismo_' + nombre.replace( ' ', '_') + '_del_mes_' + permiso[0] if mes: nombre_documento = 'Reporte_de_ausentismo_del_mes_' + permiso[0] return ExcelResponse(data, nombre_documento, nombre) if request.POST.get('imprimir'): if trabajador: reponse = HttpResponse(content_type='application/pdf') # print(request.GET) reponse['Content-Disposition'] = 'filename=reporte.pdf' buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) # CABECERA DEL ARCHIVO archivo_imagen = settings.STATIC_ROOT + '/img/index.jpg' c.drawImage(archivo_imagen, 20, 750, 120, 80, preserveAspectRatio=True) c.setFont("Helvetica", 20) # Dibujamos una cadena en la ubicación X,Y especificada c.drawString(150, 800, u"Siete Colinas S.A.S") c.line(150, 795, 345, 795) c.setFont("Helvetica", 10) c.drawString(150, 780, u"REPORTE PERMISO DE AUSENTISMO") c.setFont("Helvetica", 15) c.drawString(430, 810, u"Colaborador:") c.setFont("Helvetica", 14) c.drawString(380, 794, str(trabajador.first())) c.setFont("Helvetica", 15) c.drawString(447, 773, u"Cedula:") c.setFont("Helvetica", 14) c.drawString(435, 756, cedula) #CABECERA DE LA TABLA styles = getSampleStyleSheet() styleBH = styles['Normal'] styleBH.aligment = TA_CENTER styleBH.fontSize = 10 mes = Paragraph('''Mes''', styleBH) periodo_inicial = Paragraph('''Periodo inicial''', styleBH) periodo_final = Paragraph('''Periodo final''', styleBH) total_dias_incapacidad = Paragraph('''Total días''', styleBH) total_horas = Paragraph('''Tiempo total''', styleBH) codigo_diagnostico = Paragraph('''Código de diagnostico''', styleBH) tipo_evento = Paragraph('''Tipo de evento''', styleBH) observaciones = Paragraph('''Observaciones''', styleBH) data = [] data.append([ mes, periodo_inicial, periodo_final, total_dias_incapacidad, total_horas, tipo_evento, codigo_diagnostico, observaciones ]) #TABLA styleN = styles['BodyText'] styleN.aligment = TA_CENTER styleN.fontSize = 7 high = 618 p = ParagraphStyle('parrafos', alignment=TA_LEFT, fontSize=9, fontName="Helvetica") cont = 0 nombre_mes = '' for x in listar_permisos.object_list.values(): #nombre_mes = x["periodoIncapacidadInicial"], x['totalDiasIncapacidad'] = str(x['totalDiasIncapacidad']) if x['totalDiasIncapacidad'] == '0': x['totalDiasIncapacidad'] = 'No aplica' #print(x['totalDiasIncapacidad']) x['tipo_evento'] = listar_permisos[ cont].get_tipo_evento_display() #print(x['observaciones']) if x['horaInicial'] != None and x['horaFinal'] != None: print(str(x['horaInicial']) + ' ' + str(x['horaFinal'])) FMT = '%H:%M:%S' tdelta = datetime.strptime(str(x['horaFinal']), FMT) - datetime.strptime( str(x['horaInicial']), FMT) else: tdelta = 'No aplica' if x['observaciones'] == None: x['observaciones'] = 'Sin registro' if x['codigoDiagnostico'] == None or x[ 'codigoDiagnostico'] == '': x['codigoDiagnostico'] = 'No aplica' if x['tipo_evento'][0:3] == 'A.C': x['tipo_evento'] = 'A.C' if x['tipo_evento'][0:3] == 'O.E': x['tipo_evento'] = 'O.E' if x['tipo_evento'][0:3] == 'A.T': x['tipo_evento'] = 'A.T' if x['tipo_evento'][0:3] == 'E.L': x['tipo_evento'] = 'E.L' formato = '%B' permiso = [ #datetime.strptime(str(x["periodoIncapacidadInicial"]),formato), x["periodoIncapacidadInicial"].strftime(formato), x["periodoIncapacidadInicial"], x["periodoIncapacidadFinal"], x["totalDiasIncapacidad"], tdelta, x["tipo_evento"], x["codigoDiagnostico"], Paragraph(x["observaciones"].lower(), p), ] high = high - len(x['observaciones']) cont = cont + 1 data.append(permiso) #TABLA width, height = A4 table = Table(data, colWidths=[ 2.1 * cm, 2.7 * cm, 2.7 * cm, 1.9 * cm, 1.8 * cm, 1.8 * cm, 2.9 * cm, 4.8 * cm, 4.0 * cm, ]) table.setStyle( TableStyle([ #Estilos de la tabla ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), #('GRID',(6,1),(6,-1),2,colors.orange), ('ALIGN', (3, 0), (5, -1), 'CENTER'), ])) table.wrapOn(c, width, height) table.drawOn(c, 5, high) print('-----') print(high) c.showPage() c.save() pdf = buffer.getvalue() buffer.close() reponse.write(pdf) return reponse elif mes: reponse = HttpResponse(content_type='application/pdf') # print(request.GET) reponse['Content-Disposition'] = 'filename=reporte.pdf' buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) # CABECERA DEL ARCHIVO archivo_imagen = settings.STATIC_ROOT + '/img/index.jpg' c.drawImage(archivo_imagen, 20, 750, 120, 80, preserveAspectRatio=True) c.setFont("Helvetica", 20) # Dibujamos una cadena en la ubicación X,Y especificada c.drawString(150, 800, u"Siete Colinas S.A.S") c.line(150, 795, 345, 795) c.setFont("Helvetica", 10) c.drawString(150, 780, u"REPORTE PERMISO DE AUSENTISMO") c.setFont("Helvetica", 15) c.drawString(430, 810, u"Mes:") c.setFont("Helvetica", 15) # CABECERA DE LA TABLA styles = getSampleStyleSheet() styleBH = styles['Normal'] styleBH.aligment = TA_CENTER styleBH.fontSize = 10 colaborador = Paragraph('''Colaborador''', styleBH) periodo_inicial = Paragraph('''Periodo inicial''', styleBH) periodo_final = Paragraph('''Periodo final''', styleBH) total_dias_incapacidad = Paragraph('''Total días''', styleBH) total_horas = Paragraph('''Tiempo total''', styleBH) codigo_diagnostico = Paragraph('''Código de diagnostico''', styleBH) tipo_evento = Paragraph('''Tipo de evento''', styleBH) observaciones = Paragraph('''Observaciones''', styleBH) data = [] data.append([ colaborador, periodo_inicial, periodo_final, total_dias_incapacidad, total_horas, tipo_evento, codigo_diagnostico, observaciones ]) # TABLA styleN = styles['BodyText'] styleN.aligment = TA_CENTER styleN.fontSize = 7 high = 618 p = ParagraphStyle('parrafos', alignment=TA_LEFT, fontSize=9, fontName="Helvetica") cont = 0 nombre_mes = '' for x in listar_permisos.object_list.values(): # nombre_mes = x["periodoIncapacidadInicial"], if x['totalDiasIncapacidad'] == '0': x['totalDiasIncapacidad'] = 'No aplica' # print(x['totalDiasIncapacidad']) x['tipo_evento'] = listar_permisos[ cont].get_tipo_evento_display() x["idTrabajador_id"] = Trabajadores.objects.get( id=str(listar_permisos[cont].idTrabajador_id)) # print(x['observaciones']) if x['horaInicial'] != None and x['horaFinal'] != None: #print(str(x['horaInicial']) + ' ' + str(x['horaFinal'])) FMT = '%H:%M:%S' tdelta = datetime.strptime(str(x['horaFinal']), FMT) - datetime.strptime( str(x['horaInicial']), FMT) else: tdelta = 'No aplica' if x['observaciones'] == None: x['observaciones'] = 'Sin registro' if x['codigoDiagnostico'] == None or x[ 'codigoDiagnostico'] == '': x['codigoDiagnostico'] = 'No aplica' if x['tipo_evento'][0:3] == 'A.C': x['tipo_evento'] = 'A.C' if x['tipo_evento'][0:3] == 'O.E': x['tipo_evento'] = 'O.E' if x['tipo_evento'][0:3] == 'A.T': x['tipo_evento'] = 'A.T' if x['tipo_evento'][0:3] == 'E.L': x['tipo_evento'] = 'E.L' formato = '%B' permiso = [ # datetime.strptime(str(x["periodoIncapacidadInicial"]),formato), x["idTrabajador_id"], x["periodoIncapacidadInicial"], x["periodoIncapacidadFinal"], x["totalDiasIncapacidad"], tdelta, x["tipo_evento"], x["codigoDiagnostico"], Paragraph(x["observaciones"].lower(), p), ] high = high - len(x['observaciones']) c.setFont("Helvetica", 14) c.drawString(420, 780, permiso[1].strftime(formato)) cont = cont + 1 data.append(permiso) # TABLA width, height = A4 table = Table(data, colWidths=[ 7.3 * cm, 2.7 * cm, 2.7 * cm, 1.9 * cm, 1.8 * cm, 1.8 * cm, 2.9 * cm, 4.8 * cm, 4.0 * cm, ]) table.setStyle( TableStyle([ # Estilos de la tabla ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), # ('GRID',(6,1),(6,-1),2,colors.orange), ('ALIGN', (3, 0), (5, -1), 'CENTER'), ])) table.wrapOn(c, width, height) table.drawOn(c, 5, high) print('-----') print(high) c.setPageSize((750, 850)) c.showPage() c.save() pdf = buffer.getvalue() buffer.close() reponse.write(pdf) return reponse """ if request.method == 'POST': if request.is_ajax(): #report(request) return render(request, 'Trabajadores/trabajadores.html', context) """ context = { 'listar_permisos': listar_permisos, 'trabajador': trabajador, 'cedula': cedula, 'mes': mes, 'hay_trabajador': hay_trabajador, } return render(request, 'permiso_ausentismo/permiso_ausentismo.html', context)
def generar_pdf(request, ubigeo): print "generar_pdf" MARGIN_SIZE = 17 * mm PAGE_SIZE = A4 response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = "attachment; filename=" + ubigeo + "001" + ".pdf" # response['Content-Disposition'] = "attachment; filename="+ubigeo+"001"+".pdf" pdf_name = "clientes.pdf" styles = getSampleStyleSheet() stylesTitle = getSampleStyleSheet() stylesCabe = getSampleStyleSheet() styleTitle = stylesTitle["Normal"] styleTitle.alignment = TA_CENTER styleBH = styles["Normal"] styleBH.alignment = TA_LEFT styleCa = stylesCabe["Normal"] styleCa.alignment = TA_CENTER buff = BytesIO() # destino = "Lista/" + str(ubigeo)+"00100"+ str(aeut)+ ".pdf" # # doc2 = SimpleDocTemplate(destino, pagesize=A4, # rightMargin=70, # leftMargin=70, # topMargin=0.5 *cm, # bottomMargin=0.5 *cm, ) doc = SimpleDocTemplate( buff, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5 * cm, bottomMargin=0.5 * cm, ) h_sub_tile = PS(name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER) h_sub_tile_2 = PS(name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER) h_center = PS(name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER) h1 = PS(name='Heading1', fontSize=7, leading=8) h11 = PS(name='Heading1', fontSize=7, leading=8, alignment=TA_CENTER) h2 = PS(name='Normal', fontSize=6, leading=16) h3 = PS(name='Normal', fontSize=7, leading=14, alignment=TA_CENTER) h4 = PS(name='Normal', fontSize=6, leading=16) h5 = PS(name='Normal', fontSize=8, leading=16, alignment=TA_CENTER) h_obser = PS(name='Normal', fontSize=8, leading=16) h_bar = PS(name='Normal', fontSize=7, leading=14, alignment=TA_CENTER) story = [] distrito = Distrito.objects.get(ubigeo=ubigeo) # ubigeo Z1 = Paragraph( "<strong>OBSERVACIONES: .............................................................................." "....................................................................................................." "....................................................................................................." "....................................................................................................." "....................................................................................................." "....................................................................................................." "................................................................................</strong>", h_obser) table_obs = Table(data=[[Z1]], colWidths=[18.8 * cm], rowHeights=[2 * cm], style=[('GRID', (0, 0), (-1, -1), 1, colors.black)]) Z2 = Paragraph("<strong>EMPADRONADOR</strong>", h5) Z3 = Paragraph( "<strong>Todas las viviendas que estén dentro de los límites de tu A.E.U. deben ser empadronadas. Debes tener<br/>cuidado de no omitir ninguna vivienda</strong>", h5) table_empa_cuerp = Table(data=[[Z2], [Z3]], colWidths=[18.8 * cm], rowHeights=[0.7 * cm, 1.5 * cm], style=[('GRID', (0, 0), (0, 0), 1, colors.black), ('GRID', (0, 1), (0, 1), 1, colors.black), ('ALIGN', (0, 0), (0, 0), 'CENTER')]) x = 0 caso = Seg_R_Secc_Ccpp.objects.filter(ubigeo=ubigeo)[0:1] for aeu_v in caso: idaer = aeu_v.idaer idscr = aeu_v.idscr secc_ini = idscr[6:8] secc_fin = idscr[8:10] aer_ini = idaer[6:9] aer_fin = idaer[9:12] print idaer print idscr x = x + 1 lista_distritos = [] lista_distritos.append(ubigeo) for ubigein in range(len(lista_distritos)): if os.path.exists( "\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" + str(ubigeo)) == False: os.mkdir("\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" + str(ubigeo)) # pdf = "{}-{}-{}.pdf".format(ubigeo, idscr[6:8], idscr[8:10]) # # print pdf destino = "\\\srv-fileserver\\CPV2017\\list_seg_esp_rur\\" + str( ubigeo) + "\\" + str(ubigeo) + ".pdf" print destino doc2 = SimpleDocTemplate( destino, pagesize=A4, rightMargin=70, leftMargin=70, topMargin=0.5 * cm, bottomMargin=0.5 * cm, ) p = Paragraph(str(1) + " - " + str(1), h2) extra = Paragraph("-", h2) p_page = Table(data=[[extra, p]], colWidths=[17 * cm, 2.3 * cm], style=[ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('ALIGN', (0, 0), (1, 0), 'RIGHT'), ]) # # string = str(ubigeo)+str(secc)+str(aeut) # st = code39.Extended39(string) # # bar_string = Paragraph(string, h_bar) pi = Paragraph("-", h2) # st_b = st # table_bar = Table( # data = [ # [pi, st_b], # ['', bar_string] # ], # colWidths= [13 * cm, 5 * cm], # style=[ # ('ALIGN', (0, 0), (-1, -1),'CENTER') # ] # ) # story.append(table_bar) viviendas_totales = Vw_Seg_Esp_R_Secdist_Secc.objects.filter( ubigeo=ubigeo).order_by('idscr', 'idaer', 'codccpp') total_secc_ini = Vw_Seg_Esp_R_Secdist_Secc.objects.filter( ubigeo=ubigeo).values_list('scr_ini', flat=True) total_secc_fin = Vw_Seg_Esp_R_Secdist_Secc.objects.filter( ubigeo=ubigeo).values_list('scr_fin', flat=True) cuchi_one = list(set(total_secc_ini)) cuchi_two = list(set(total_secc_fin)) secc_ini = min(cuchi_one) secc_fin = max(cuchi_two) total_aer_ini = Vw_Seg_Esp_R_Secdist_Secc.objects.filter( ubigeo=ubigeo).values_list('aer_ini', flat=True) total_aer_fin = Vw_Seg_Esp_R_Secdist_Secc.objects.filter( ubigeo=ubigeo).values_list('aer_fin', flat=True) cuchi_aer_one = list(set(total_aer_ini)) cuchi_aer_two = list(set(total_aer_fin)) aer_ini = min(cuchi_aer_one) aer_fin = max(cuchi_aer_two) total_viv = 0 for viviendon in viviendas_totales: total_viv = total_viv + viviendon.viv_ccpp data = [ ['', '', '', '', Paragraph('<strong>Doc. CPV</strong>', h4), ''], [ Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '', '', '', Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), '' ], [ Paragraph('<strong>DEPARTAMENTO</strong>', h1), Paragraph(str(distrito.ccdd.ccdd), h_center), Paragraph(str(distrito.ccdd.departamento), h1), '', Paragraph('<strong>SECCIÓN Nº</strong>', h1), Paragraph('Del ' + secc_ini + ' Al ' + secc_fin, h1) ], [ Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph(distrito.ccpp, h_center), Paragraph(distrito.cod_prov.provincia, h1), '', Paragraph('<strong>AER Nº</strong>', h1), Paragraph('Del ' + aer_ini + ' Al ' + aer_fin, h1) ], [ Paragraph('<strong>DISTRITO</strong>', h1), Paragraph(distrito.ccdi, h_center), Paragraph(distrito.distrito, h1), '', '', '' ], [ '', '', '', '', Paragraph( '<strong>C. TOTAL DE VIVIENDAS DEL DISTRITO.</strong>', h1), Paragraph(str(total_viv), h1) ], #Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL AER.</strong>', h1) ] tables = Table(data, colWidths=[ 3.7 * cm, 1 * cm, 7.1 * cm, 0.3 * cm, 4.5 * cm, 2.2 * cm ]) # , # rowHeights=[0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.4 * cm, 0.7 * cm]) tables.setStyle( TableStyle([ ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 1), (2, 4), 1, colors.black), ('GRID', (4, 5), (5, 5), 1, colors.black), ('GRID', (4, 1), (5, 3), 1, colors.black), ('GRID', (4, 3), (5, 3), 1, colors.black), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (5, 1)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('BACKGROUND', (0, 2), (0, 4), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('BACKGROUND', (4, 1), (4, 3), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('BACKGROUND', (4, 5), (4, 5), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('BACKGROUND', (4, 1), (5, 1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ])) t1 = Paragraph( "CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA<br/>Y III DE COMUNIDADES INDÍGENAS", h_sub_tile) t1_sub = Paragraph( "<strong>LISTADO DE ÁREAS DE EMPADRONAMIENTO RURAL DISTRITAL</strong>", h_sub_tile_2) fichero_imagen_inei = 'Reporte/Img/inei.png' imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=50) P2 = Paragraph('', styleBH) fichero_imagen = 'Reporte/Img/escudo.png' imagen_logo = Image(os.path.realpath(fichero_imagen), width=50, height=50) t1_croq = Paragraph( "<strong>CROQUIS DEL ÁREA DE EMPADRONAMIENTO URBANO</strong>", h_sub_tile_2) t = Table( data=[ # ['', t1, ''], [[imagen_logo, P2], t1, [imagen_logo_inei, P2]], ['', t1_croq, ''] ], colWidths=[2 * cm, 14 * cm, 2 * cm], style=[ ('GRID', (1, 1), (-2, -2), 1, colors.white), ('GRID', (0, 0), (-1, -1), 0.5, colors.white), ]) obs_data = [ [ Paragraph(e, h3) for e in [ "<strong>D. INFORMACIÓN DE LAS SECCIONES CENSALES Y ÁREAS DE EMPADRONAMIENTO DEL DISTRITO</strong>", "", "", "", "", "", "" ] ], [ Paragraph(e, h3) for e in [ "<strong>SECCIÓN Nº</strong>", "<strong>AER N°</strong>", "", "<strong>CENTRO POBLADO</strong>", "", "", "<strong>N° ESTIMADOS DE VIVIENDAS</strong>" ] ], [ Paragraph(e, h3) for e in [ "", "<strong>INICIAL</strong>", "<strong>FINAL</strong>", "<strong>CÓDIGO</strong>", "<strong>NOMBRE</strong>", "<strong>CATEGORÍA</strong>", "" ] ], ] c = Table(obs_data, colWidths=[ 2 * cm, 1.7 * cm, 1.7 * cm, 1.7 * cm, 7.3 * cm, 2 * cm, 2.3 * cm ], rowHeights=[0.6 * cm, 1.1 * cm, 0.7 * cm]) c.setStyle( TableStyle([ ('GRID', (1, 1), (-2, -2), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('BACKGROUND', (0, 0), (-1, -1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('SPAN', (0, 0), (6, 0)), ('SPAN', (1, 1), (2, 1)), ('SPAN', (3, 1), (5, 1)), ('SPAN', (0, 1), (0, 2)), ('SPAN', (6, 1), (6, 2)), ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ])) i = 0 data_croq = [ ['', '', '', '', Paragraph('<strong>Doc. CPV</strong>', h4), ''], [ Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '', '', '', Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), '' ], [ Paragraph('<strong>DEPARTAMENTO</strong>', h1), Paragraph(str(distrito.ccdd.ccdd), h_center), Paragraph(str(distrito.ccdd.departamento), h1), '', Paragraph('<strong>SECCIÓN Nº</strong>', h1), '' ], [ Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph(distrito.ccpp, h_center), Paragraph( str(distrito.cod_prov.provincia).decode('latin-1'), h1), '', Paragraph(str('<strong>A.E.R. Nº</strong>'), h1), '' ], [Paragraph('<strong>DISTRITO</strong>', h1), '', '', '', '', ''], [ '', '', '', '', Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL AER.</strong>', h1), '' ], ] tables_croq = Table( data_croq, colWidths=[3.7 * cm, 1 * cm, 8.3 * cm, 0.3 * cm, 4.7 * cm, 1 * cm]) tables_croq.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (1, 2), (1, 4), 'CENTER'), ('GRID', (0, 0), (2, 3), 1, colors.black), ('GRID', (4, 5), (1, 3), 1, colors.black), ('SPAN', (0, 1), (2, 1)), ('SPAN', (0, 1), (2, 1)), ('BACKGROUND', (0, 1), (-1, 1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ('BACKGROUND', (0, 1), (0, 6), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)), ])) fichero_imagen_inei = 'Reporte/Img/inei.png' imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=40) P2 = Paragraph('', styleBH) fichero_imagen = 'Reporte/Img/escudo.png' imagen_logo = Image(os.path.realpath(fichero_imagen), width=50, height=50) t = Table(data=[[[imagen_logo, P2], t1, [imagen_logo_inei, P2]], ['', t1_croq, '']], colWidths=[2 * cm, 14 * cm, 2 * cm], style=[ ('GRID', (1, 1), (-2, -2), 1, colors.white), ('GRID', (0, 0), (-1, -1), 0.5, colors.white), ]) t_croq = Table(data=[[[imagen_logo, P2], t1, [imagen_logo_inei, P2]], ['', t1_sub, '']], colWidths=[2 * cm, 14 * cm, 2 * cm], style=[ ('GRID', (1, 1), (-2, -2), 1, colors.white), ('GRID', (0, 0), (-1, -1), 0.5, colors.white), ]) # story.append(t) # story.append(Spacer(0, 1 * mm)) # story.append(tables) # story.append(Spacer(0, 1 * mm)) # story.append(Spacer(0, 1 * mm)) # story.append(table_obs) # story.append(PageBreak()) # story.append(table_bar) story.append(t_croq) story.append(Spacer(0, 2 * mm)) story.append(tables) story.append(Spacer(0, 3 * mm)) story.append(c) viviendas = Vw_Seg_Esp_R_Secdist_Secc.objects.filter( ubigeo=ubigeo).order_by('idscr', 'idaer', 'codccpp') #toti_viv = int(Vw_Seg_Esp_R_Secdist_Secc.objects.filter(idscr=idscr).count()) for vivienda in viviendas: if vivienda.categoria_o == None: categoria_o = '' else: categoria_o = vivienda.categoria_o i = i + 1 # Bloque Listado table2 = [(str(vivienda.scr_ini).decode('latin-1'), str(vivienda.aer_ini).decode('latin-1'), str(vivienda.aer_fin).decode('latin-1'), str(vivienda.codccpp).decode('latin-1'), vivienda.nomccpp, str(categoria_o).decode('latin-1'), str(vivienda.viv_ccpp).decode('latin-1'))] u = Table(table2, colWidths=[ 2 * cm, 1.7 * cm, 1.7 * cm, 1.7 * cm, 7.3 * cm, 2 * cm, 2.3 * cm ], rowHeights=[0.5 * cm]) u.setStyle( TableStyle([ ('GRID', (1, 1), (-2, -2), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (6, 0), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) story.append(u) doc2.build(story) doc.build(story) response.write(buff.getvalue()) buff.close() return response
def wrap_pdf_in_response(pdf_data): response = HttpResponse(content_type='application/pdf') response.write(pdf_data) return response
def login(request, provider_name): # We we need the response object for the adapter. response = HttpResponse() # Start the login procedure. result = authomatic.login(DjangoAdapter(request, response), provider_name) # If there is no result, the login procedure is still pending. # Don't write anything to the response if there is no result! if result: # If there is result, the login procedure is over and we can write to response. response.write('<a href="..">Home</a>') if result.error: # Login procedure finished with an error. response.write('<h2>Damn that error: {0}</h2>'.format(result.error.message)) elif result.user:# We need to update the user to get more info. if not (result.user.name and result.user.id): result.user.update() # Welcome the user. response.write(u'<h1>Hi {0}</h1>'.format(result.user.name)) response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id)) response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email)) # Seems like we're done, but there's more we can do... # If there are credentials (only by AuthorizationProvider), # we can _access user's protected resources. if result.user.credentials: # Each provider has it's specific API. if result.provider.name == 'fb': response.write('Your are logged in with Facebook.<br />') # We will access the user's 5 most recent statuses. url = 'https://graph.facebook.com/{0}?fields=feed.limit(5)' url = url.format(result.user.id) # Access user's protected resource. access_response = result.provider.access(url) if access_response.status == 200: # Parse response. statuses = access_response.data.get('feed').get('data') error = access_response.data.get('error') if error: response.write(u'Damn that error: {0}!'.format(error)) elif statuses: response.write('Your 5 most recent statuses:<br />') for message in statuses: text = message.get('message') date = message.get('created_time')response.write(u'<h3>{0}</h3>'.format(text)) response.write(u'Posted on: {0}'.format(date)) else: response.write('Damn that unknown error!<br />') response.write(u'Status: {0}'.format(response.status)) if result.provider.name == 'tw': response.write('Your are logged in with Twitter.<br />') # We will get the user's 5 most recent tweets. url = 'https://api.twitter.com/1.1/statuses/user_timeline.json' # You can pass a dictionary of querystring parameters. access_response = result.provider.access(url, {'count': 5}) # Parse response. if access_response.status == 200: if type(access_response.data) is list: # Twitter returns the tweets as a JSON list. response.write('Your 5 most recent tweets:') for tweet in access_response.data: text = tweet.get('text') date = tweet.get('created_at') response.write(u'<h3>{0}</h3>'.format(text)) response.write(u'Tweeted on: {0}'.format(date)) elif response.data.get('errors'): response.write(u'Damn that error: {0}!'.\ format(response.data.get('errors'))) else: response.write('Damn that unknown error!<br />') response.write(u'Status: {0}'.format(response.status)) return response
def image(request, path, token, autogen=False): original_token = token has_admin_perm = request.user.has_perm('admin') is_admin = False if ("is_admin=true" in token and request and has_admin_perm) or autogen: parameters = token is_admin = True if autogen: token = image_create_token(parameters) else: parameters = request.session.get(token, token) cached_image_file = os.path.join(path, token) now = timezone.now() expire_offset = timezone.timedelta(seconds=IMAGE_CACHE_HTTP_EXPIRATION) response = HttpResponse() response['Content-type'] = 'image/jpeg' response['Expires'] = (now + expire_offset).strftime("%a, %d %b %Y %T GMT") response['Last-Modified'] = now.strftime("%a, %d %b %Y %T GMT") response['Cache-Control'] = 'max-age=3600, must-revalidate' response.status_code = 200 # If we already have the cache we send it instead of recreating it if IMAGE_CACHE_STORAGE.exists(cached_image_file): if autogen: return 'Already generated' try: f = IMAGE_CACHE_STORAGE.open(cached_image_file, "rb") except IOError: raise Http404() response.write(f.read()) f.close() response['Last-Modified'] = IMAGE_CACHE_STORAGE.modified_time( cached_image_file).strftime("%a, %d %b %Y %T GMT") return response if parameters == token and not is_admin: if has_admin_perm and 'is_admin=true' in path: # Retrocompatibilidad. return image(request, original_token, path, autogen=autogen) return HttpResponse("Forbidden", status=403) qs = QueryDict(parameters) file_storage = MEDIA_STORAGE if qs.get('static', '') == "true": file_storage = STATIC_STORAGE format = qs.get('format', IMAGE_DEFAULT_FORMAT) quality = int(qs.get('quality', IMAGE_DEFAULT_QUALITY)) mask = qs.get('mask', None) mask_source = qs.get('mask_source', None) if mask is not None: format = "PNG" fill = qs.get('fill', None) background = qs.get('background', None) tint = qs.get('tint', None) center = qs.get('center', ".5,.5") mode = qs.get('mode', "crop") enlarge = qs.get('enlarge', "true") overlays = qs.getlist('overlay') overlay_sources = qs.getlist('overlay_source') overlay_tints = qs.getlist('overlay_tint') overlay_sizes = qs.getlist('overlay_size') overlay_positions = qs.getlist('overlay_position') width = qs.get('width', None) if width: width = int(width) height = qs.get('height', None) if height: height = int(height) pre_rotation = qs.get('pre_rotation', None) post_rotation = qs.get('post_rotation', None) try: padding = float(qs.get('padding', None)) except TypeError: padding = 0.0 grayscale = bool(qs.get('grayscale', False)) if "video" in qs: data, http_response = generate_thumb(file_storage, force_text(path)) response.status_code = http_response else: try: try: f = requests.get(qs['url']) data = f.content f.close() except KeyError: f = file_storage.open(path) data = f.read() f.close() except IOError: response.status_code = 404 data = "" if data: try: crop = (mode != "scale") force = (enlarge == "true") output_data = render(data, width, height, force=force, padding=padding, overlays=overlays, overlay_sources=overlay_sources, overlay_tints=overlay_tints, overlay_positions=overlay_positions, overlay_sizes=overlay_sizes, mask=mask, mask_source=mask_source, center=center, format=format, quality=quality, fill=fill, background=background, tint=tint, pre_rotation=pre_rotation, post_rotation=post_rotation, crop=crop, grayscale=grayscale) except IOError: traceback.print_exc() response.status_code = 500 output_data = "" else: output_data = data if response.status_code == 200: IMAGE_CACHE_STORAGE.save(cached_image_file, ContentFile(output_data)) if autogen: return 'Generated ' + six.text_type(response.status_code) else: if autogen: return 'Failed ' + cached_image_file response.write(output_data) return response
def captcha_image(request, key): store = get_object_or_404(CaptchaStore, hashkey=key) text = store.challenge if settings.CAPTCHA_FONT_PATH.lower().strip().endswith('ttf'): font = ImageFont.truetype(settings.CAPTCHA_FONT_PATH, settings.CAPTCHA_FONT_SIZE) else: font = ImageFont.load(settings.CAPTCHA_FONT_PATH) size = font.getsize(text) size = (size[0] * 2, size[1]) image = Image.new('RGB', size, settings.CAPTCHA_BACKGROUND_COLOR) try: PIL_VERSION = int(NON_DIGITS_RX.sub('', Image.VERSION)) except: PIL_VERSION = 116 xpos = 2 for char in text: fgimage = Image.new('RGB', size, settings.CAPTCHA_FOREGROUND_COLOR) charimage = Image.new('L', font.getsize(' %s ' % char), '#000000') chardraw = ImageDraw.Draw(charimage) chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff') if settings.CAPTCHA_LETTER_ROTATION: if PIL_VERSION >= 116: charimage = charimage.rotate( random.randrange(*settings.CAPTCHA_LETTER_ROTATION), expand=0, resample=Image.BICUBIC) else: charimage = charimage.rotate( random.randrange(*settings.CAPTCHA_LETTER_ROTATION), resample=Image.BICUBIC) charimage = charimage.crop(charimage.getbbox()) maskimage = Image.new('L', size) maskimage.paste( charimage, (xpos, 4, xpos + charimage.size[0], 4 + charimage.size[1])) size = maskimage.size image = Image.composite(fgimage, image, maskimage) xpos = xpos + 2 + charimage.size[0] image = image.crop((0, 0, xpos + 1, size[1])) draw = ImageDraw.Draw(image) for f in settings.noise_functions(): draw = f(draw, image) for f in settings.filter_functions(): image = f(image) out = StringIO() image.save(out, "PNG") out.seek(0) response = HttpResponse() response['Content-Type'] = 'image/png' response.write(out.read()) return response
def return_http_json(rst): r = HttpResponse() r.write(simplejson.dumps(rst, default=json_encode_decimal)) return r
def export_surveycall_report(request): """Export CSV file of Survey VoIP call record **Important variable**: * ``request.session['surveycall_record_qs']`` - stores survey voipcall query set **Exported fields**: ['starting_date', 'phone_number', 'duration', 'disposition', 'survey results'] """ format_type = request.GET['format'] # get the response object, this can be used as a stream. response = HttpResponse(content_type='text/%s' % format_type) # force download. response['Content-Disposition'] = 'attachment;filename=export.%s' % format_type if request.session.get('session_surveycalls_kwargs'): kwargs = request.session.get('session_surveycalls_kwargs') campaign_obj = kwargs['callrequest__campaign'] qs = VoIPCall.objects.filter(**kwargs) column_list_base = ['starting_date', 'phone_number', 'duration', 'disposition'] column_list = list(column_list_base) survey_qst = False if campaign_obj.content_type.model == 'survey': survey_qst = Section.objects.filter(survey_id=int(campaign_obj.object_id)) for i in survey_qst: column = unicode(i.question.replace(',', ' ')) column_list.append(column.encode('utf-8')) result_row = [] for voipcall in qs: result_row_list = [] # For each voip call retrieve the results of the survey nodes results = Result.objects.filter(callrequest=voipcall.callrequest_id).order_by('section') result_list = {} # We will prepare a dictionary result_list to help exporting the result for result in results: column = unicode(result.section.question.replace(',', ' ')) if result.record_file and len(result.record_file) > 0: result_list[column.encode('utf-8')] = result.record_file else: result_list[column.encode('utf-8')] = result.response # We will build result_row_list which will be a value for each element from column_list for ikey in column_list: if ikey in column_list_base: # This is not a Section result if ikey == 'starting_date' \ and format_type == Export_choice.JSON \ or format_type == Export_choice.XLS: starting_date = str(voipcall.__dict__[ikey]) result_row_list.append(starting_date) else: result_row_list.append(voipcall.__dict__[ikey]) else: # This is a Section result if ikey in result_list: result_row_list.append(result_list[ikey].encode('utf-8')) else: # Add empty result result_row_list.append("") result_row.append(result_row_list) data = tablib.Dataset(*result_row, headers=tuple(column_list)) if format_type == Export_choice.XLS: response.write(data.xls) elif format_type == Export_choice.CSV: response.write(data.csv) elif format_type == Export_choice.JSON: response.write(data.json) return response
def download_providers(request): f = feed.objects.get(pk=request.POST['feed']) today = str(datetime.datetime.today().year) + str( datetime.datetime.today().month) + str(datetime.datetime.today().day) response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition'] = 'attachment; filename=nalari_' + today + '_provider.csv' writer = csv.writer(response, csv.excel, quoting=csv.QUOTE_ALL) response.write(u'\ufeff'.encode('utf8')) practices = practice.objects.filter(feed=f) for p in practices: rels = provider_practice_rel.objects.filter(practice=p) for r in rels: prov = r.provider if prov.identifier_type == 'SSN': writer.writerow([ prov.source_id, prov.specialty_type, "1", prov.prefix, prov.first_name, prov.middle_initial, prov.last_name, prov.gender, str(prov.dob.year) + str(prov.dob.month) + str(prov.dob.day), prov.identifier, "", "", "", "", prov.address1, prov.address2, prov.city, prov.state, prov.zipcode, prov.country, prov.phone, str(prov.start_date.year) + str(prov.start_date.month) + str(prov.start_date.day), "99990101", "1", "1", "", "1", prov.username, prov.password, "1", "1", "", "2", "", "", "", "2", "1" ]) elif prov.identifier_type == 'EIN': writer.writerow([ prov.source_id, prov.specialty_type, "1", prov.prefix, prov.first_name, prov.middle_initial, prov.last_name, prov.gender, str(prov.dob.year) + str(prov.dob.month) + str(prov.dob.day), "", prov.identifier, "", "", "", prov.address1, prov.address2, prov.city, prov.state, prov.zipcode, prov.country, prov.phone, str(prov.start_date.year) + str(prov.start_date.month) + str(prov.start_date.day), "99990101", "1", "1", "", "1", prov.username, prov.password, "1", "1", "", "2", "", "", "", "2", "1" ]) elif prov.identifier_type == 'UPIN': writer.writerow([ prov.source_id, prov.specialty_type, "1", prov.prefix, prov.first_name, prov.middle_initial, prov.last_name, prov.gender, str(prov.dob.year) + str(prov.dob.month) + str(prov.dob.day), "", "", prov.identifier, "", "", prov.address1, prov.address2, prov.city, prov.state, prov.zipcode, prov.country, prov.phone, str(prov.start_date.year) + str(prov.start_date.month) + str(prov.start_date.day), "99990101", "1", "1", "", "1", prov.username, prov.password, "1", "1", "", "2", "", "", "", "2", "1" ]) elif prov.identifier_type == 'NPI': writer.writerow([ prov.source_id, prov.specialty_type, "1", prov.prefix, prov.first_name, prov.middle_initial, prov.last_name, prov.gender, str(prov.dob.year) + str(prov.dob.month) + str(prov.dob.day), "", "", "", prov.identifier, "", prov.address1, prov.address2, prov.city, prov.state, prov.zipcode, prov.country, prov.phone, str(prov.start_date.year) + str(prov.start_date.month) + str(prov.start_date.day), "99990101", "1", "1", "", "1", prov.username, prov.password, "1", "1", "", "2", "", "", "", "2", "1" ]) else: writer.writerow([ prov.source_id, prov.specialty_type, "1", prov.prefix, prov.first_name, prov.middle_initial, prov.last_name, prov.gender, str(prov.dob.year) + str(prov.dob.month) + str(prov.dob.day), "", "", "", "", prov.identifier, prov.address1, prov.address2, prov.city, prov.state, prov.zipcode, prov.country, prov.phone, str(prov.start_date.year) + str(prov.start_date.month) + str(prov.start_date.day), "99990101", "1", "1", "", "1", prov.username, prov.password, "1", "1", "", "2", "", "", "", "2", "1" ]) return response
def transaction_dump(request): response = HttpResponse(mimetype="text/plain") response.write('<?xml version="1.0" encoding="utf-8"?>\n') response.write('<?xml-stylesheet type="text/xsl" href="finance.xsl"?>\n\n') response.write('<finances>\n <accounts>\n') TYPE_MAP = { 'A': 'asset', 'L': 'liability', 'I': 'income', 'E': 'expense', 'Q': 'equity' } for a in Account.objects.order_by('name'): response.write(' <account id="acct%d" type="%s">%s</account>\n' % (a.id, TYPE_MAP[a.type], xml_escape(a.name))) response.write(' </accounts>\n\n <transactions>') for (t, splits) in Transaction.fetch_all(include_auto=True): auto = '' if t.auto_generated: auto = ' auto="true"' response.write( '\n <transaction id="t%d"%s>\n <date>%s</date>\n' % (t.id, auto, t.date)) response.write( ' <description>%s</description>\n <splits>\n' % (xml_escape(t.description), )) for s in splits: response.write( ' <split account="acct%d" value="%.02f">%s</split>\n' % (s.account.id, s.amount, xml_escape(s.memo))) response.write(' </splits>\n </transaction>\n') response.write(' </transactions>\n</finances>\n') return response
def entries_view(self, request, form_id, show=False, export=False, export_xls=False): """ Displays the form entries in a HTML table with option to export as CSV file. """ if request.POST.get("back"): bits = (self.model._meta.app_label, self.model.__name__.lower()) change_url = reverse("admin:%s_%s_change" % bits, args=(form_id, )) return HttpResponseRedirect(change_url) form = get_object_or_404(self.model, id=form_id) post = request.POST or None args = form, request, self.formentry_model, self.fieldentry_model, post entries_form = EntriesForm(*args) delete = "%s.delete_formentry" % self.formentry_model._meta.app_label can_delete_entries = request.user.has_perm(delete) submitted = entries_form.is_valid() or show or export or export_xls export = export or request.POST.get("export") export_xls = export_xls or request.POST.get("export_xls") if submitted: if export: response = HttpResponse(content_type="text/csv") fname = "%s-%s.csv" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = StringIO() try: csv = writer(queue, delimiter=CSV_DELIMITER) writerow = csv.writerow except TypeError: queue = BytesIO() delimiter = bytes(CSV_DELIMITER, encoding="utf-8") csv = writer(queue, delimiter=delimiter) writerow = lambda row: csv.writerow([ c.encode("utf-8") if hasattr(c, "encode") else c for c in row ]) writerow(entries_form.columns()) for row in entries_form.rows(csv=True): writerow(row) data = queue.getvalue() response.write(data) return response elif XLWT_INSTALLED and export_xls: response = HttpResponse( content_type="application/vnd.ms-excel") fname = "%s-%s.xls" % (form.slug, slugify(now().ctime())) attachment = "attachment; filename=%s" % fname response["Content-Disposition"] = attachment queue = BytesIO() workbook = xlwt.Workbook(encoding='utf8') sheet = workbook.add_sheet(form.title[:31]) for c, col in enumerate(entries_form.columns()): sheet.write(0, c, col) for r, row in enumerate(entries_form.rows(csv=True)): for c, item in enumerate(row): if isinstance(item, datetime): item = item.replace(tzinfo=None) sheet.write(r + 2, c, item, XLWT_DATETIME_STYLE) else: sheet.write(r + 2, c, item) workbook.save(queue) data = queue.getvalue() response.write(data) return response elif request.POST.get("delete") and can_delete_entries: selected = request.POST.getlist("selected") if selected: try: from django.contrib.messages import info except ImportError: def info(request, message, fail_silently=True): request.user.message_set.create(message=message) entries = self.formentry_model.objects.filter( id__in=selected) count = entries.count() if count > 0: entries.delete() message = ungettext("1 entry deleted", "%(count)s entries deleted", count) info(request, message % {"count": count}) template = "admin/forms/entries.html" context = { "title": _("View Entries"), "entries_form": entries_form, "opts": self.model._meta, "original": form, "can_delete_entries": can_delete_entries, "submitted": submitted, "xlwt_installed": XLWT_INSTALLED } return render(request, template, context)
raise msg = 'HDLR ERROR: %s %s' % (req.method, data_path) if settings.DEBUG: msg += ': %s' % e logging.debug(msg) return HttpResponseServerError(msg) if settings.DEBUG: exec_time = time.time() - start_time if req.method == 'GET': logging.debug("Return:") try: logging.debug(pprint.pformat(ujson.decode(ret))) except: logging.debug('%s' % ret) try: logging.debug("Length: %s" % len(ret)) except: pass logging.debug("Time: %s" % exec_time) logging.debug('=' * 60) # return the HttpResponse returned by the handler if isinstance(ret, HttpResponse): return ret r = HttpResponse() if req.method == 'GET': r.write(ret) return r
def _make_pdf_attestation(attestation_pdf, attestation_type): filename = "%s.pdf" % _(attestation_type) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"' % filename response.write(attestation_pdf) return response
def download_dynamic_report(request): """ Download dynamic report in some format. Query String Parameters: :id: ID of the report to export :values: Fields to include in the data, as well as the order in which to include them. :order_by: The the field to sort the records by :direction: 'ascending' or 'decescending', for sort order :report_presentation_id: id of report presentation to use for file format. Outputs: The report with the specified options rendered in the desired format. """ company = get_company_or_404(request) report_id = request.GET.get('id', 0) values = request.GET.getlist('values') order_by = request.GET.get('order_by') order_direction = request.GET.get('direction', 'ascending') report_presentation_id = request.GET.get('report_presentation_id') report = get_object_or_404( DynamicReport.objects.filter(owner=company), pk=report_id) report_presentation = ( ReportPresentation.objects.get(id=report_presentation_id)) config = report.report_data.configuration report_configuration = config.build_configuration() if order_by: report.order_by = order_by report.save() if len(values) == 0: values = report_configuration.get_header() records = [ report_configuration.format_record(r, values) for r in report.python ] sorted_records = records if order_by: reverse = False if order_direction == 'descending': reverse = True sorted_records = sort_records(records, order_by, reverse) presentation_driver = ( report_presentation.presentation_type.presentation_type) presentation = presentation_drivers[presentation_driver] response = HttpResponse(content_type=presentation.content_type) disposition = get_content_disposition( report.name, presentation.filename_extension) response['Content-Disposition'] = disposition output = StringIO() values = [ c.alias for value in values for c in report_configuration.columns if c.column == value ] presentation.write_presentation(values, sorted_records, output) response.write(output.getvalue()) return response
def render_to_geojson(query_set, geom_field=None, geom_attribute=None, extra_attributes=[],mimetype='text/plain', pretty_print=False, excluded_fields=[],included_fields=[],proj_transform=None, return_response=True): ''' Shortcut to render a GeoJson FeatureCollection from a Django QuerySet. Currently computes a bbox and adds a crs member as a sr.org link ''' excluded_fields.append('_state') collection = {} if hasattr(query_set,'_meta'): # its a model instance fields = query_set._meta.fields query_set = [query_set] else: fields = query_set.model._meta.fields if geom_attribute: geometry_name = geom_attribute geo_field = None if '.' in geom_attribute: prop, meth = geom_attribute.split('.') if len(query_set): p = getattr(query_set[0],prop) geo_field = getattr(p,meth) if callable(geo_field): geo_field = geo_field() else: if len(query_set): geo_field = getattr(query_set[0],geom_attribute) if callable(geo_field): geo_field = geo_field() if not geo_field: srid = 4326 else: srid = geo_field.srid else: geo_fields = [f for f in fields if isinstance(f, GeometryField)] #attempt to assign geom_field that was passed in if geom_field: geo_fieldnames = [x.name for x in geo_fields] try: geo_field = geo_fields[geo_fieldnames.index(geom_field)] except: raise Exception('%s is not a valid geometry on this model' % geom_field) else: if not len(geo_fields): raise Exception('There appears to be no valid geometry on this model') geo_field = geo_fields[0] # no support yet for multiple geometry fields #remove other geom fields from showing up in attributes if len(geo_fields) > 1: for field in geo_fields: if field.name not in excluded_fields: excluded_fields.append(field.name) geometry_name = geo_field.name srid = geo_field.srid if proj_transform: to_srid = proj_transform else: to_srid = srid # Gather the projection information crs = {} crs['type'] = "link" crs_properties = {} crs_properties['href'] = 'http://spatialreference.org/ref/epsg/%s/' % to_srid crs_properties['type'] = 'proj4' crs['properties'] = crs_properties collection['crs'] = crs collection['srid'] = to_srid # Build list of features features = [] if query_set.distinct(): for item in query_set: feat = {} feat['type'] = 'Feature' if included_fields: d = {} for f in included_fields: if hasattr(item,f): d[f] = getattr(item,f) else: d = item.__dict__.copy() for field in excluded_fields: if field in d.keys(): d.pop(field) if geometry_name in d: d.pop(geometry_name) for attr in extra_attributes: a = getattr(item,attr) # crappy way of trying to figure out it this is a # m2m, aka 'ManyRelatedManager' if hasattr(a,'values_list'): a = list(a.values_list('id',flat=True)) if callable(a): d[attr] = a() else: d[attr] = a if '.' in geometry_name: prop, meth = geometry_name.split('.') a = getattr(item,prop) g = getattr(a,meth) if callable(g): g = g() else: g = getattr(item,geometry_name) if g: if proj_transform: g.transform(proj_transform) feat['geometry'] = simplejson.loads(g.geojson) feat['properties'] = d features.append(feat) else: pass #features.append({'type':'Feature','geometry': {},'properties':{}}) # Label as FeatureCollection and add Features collection['type'] = "FeatureCollection" collection['features'] = features # Attach extent of all features # if query_set: # ex = None # query_set.query.distinct = False # if hasattr(query_set,'agg_extent'): # ex = [x for x in query_set.agg_extent.tuple] # elif '.' in geometry_name: # prop, meth = geometry_name.split('.') # a = getattr(item,prop) # if a: # ex = [x for x in a.extent()] # else: # import pdb # pdb.set_trace() # # make sure qs does not have .distinct() in it... # ex = [x for x in query_set.extent()] # if ex: # if proj_transform: # poly = Polygon.from_bbox(ex) # poly.srid = srid # poly.transform(proj_transform) # ex = poly.extent # collection['bbox'] = ex if return_response: # Return response response = HttpResponse() if pretty_print: response.write('%s' % simplejson.dumps(collection, indent=1)) else: response.write('%s' % simplejson.dumps(collection)) response['Content-length'] = str(len(response.content)) response['Content-Type'] = mimetype return response else: return collection
def download_products(request, domain): def _parse_custom_properties(product): product_data_model = CustomDataFieldsDefinition.get_or_create( domain, ProductFieldsView.field_type) product_data_fields = [f.slug for f in product_data_model.fields] model_data = {} uncategorized_data = {} for prop, val in six.iteritems(product.product_data): if prop in product_data_fields: model_data['data: ' + prop] = encode_if_needed(val) else: uncategorized_data['uncategorized_data: ' + prop] = encode_if_needed(val) return model_data, uncategorized_data def _get_products(domain): for p_doc in iter_docs(Product.get_db(), Product.ids_by_domain(domain)): # filter out archived products from export if not ('is_archived' in p_doc and p_doc['is_archived']): yield Product.wrap(p_doc) def _build_row(keys, product): row = [] for key in keys: row.append(product.get(key, '') or '') return row file = StringIO() writer = Excel2007ExportWriter() product_keys = [ 'id', 'name', 'unit', 'product_id', 'description', 'category', 'program_id', 'cost', ] model_data = set() uncategorized_data = set() products = [] for product in _get_products(domain): product_dict = product.to_dict() product_model, product_uncategorized = _parse_custom_properties( product) model_data.update(product_model) uncategorized_data.update(product_uncategorized) product_dict.update(product_model) product_dict.update(product_uncategorized) products.append(product_dict) keys = product_keys + list(model_data) + list(uncategorized_data) writer.open( header_table=[('products', [keys])], file=file, ) for product in products: writer.write([('products', [_build_row(keys, product)])]) writer.close() response = HttpResponse(content_type=Format.from_format('xlsx').mimetype) response['Content-Disposition'] = 'attachment; filename="products.xlsx"' response.write(file.getvalue()) return response
def get_friends_bioregions(request): friends = simplejson.loads(request.GET['friends']) user_ids = [] user_bioregion_mapping = {} draw_bioregion_ids = [] gen_bioregion_ids = [] friend_ids = [friend['id'] for friend in friends] u_settings_qs = UserSettings.objects.filter(user__id__in=friend_ids) for setting in u_settings_qs: if setting.has_bioregion(): user_bioregion_mapping[setting.user_id] = { 'type': setting.bioregion_type(), 'br_id': setting.get_bioregion().id } if setting.bioregion_type() == "Drawn": draw_bioregion_ids.append(setting.get_bioregion().id) else: gen_bioregion_ids.append(setting.get_bioregion().id) gen_qs = GeneratedBioregion.objects.filter(id__in=gen_bioregion_ids) draw_qs = DrawnBioregion.objects.filter(id__in=draw_bioregion_ids) collection = {} if gen_qs.count() > 0 : gen_bioregions_collection = render_to_geojson( gen_qs, geom_attribute='geometry_final', mimetype = 'text/plain', pretty_print=True, excluded_fields=['date_created', 'date_modified'], return_response=False ) collection = gen_bioregions_collection if draw_qs.count() > 0: draw_bioregions_collection = render_to_geojson( draw_qs, geom_attribute='geometry_final', mimetype = 'text/plain', pretty_print=True, excluded_fields=['date_created', 'date_modified'], return_response=False ) collection = draw_bioregions_collection if draw_qs.count() > 0 and gen_qs.count() > 0: collection['features'] = draw_bioregions_collection['features'] + gen_bioregions_collection['features'] collection['user_feature_mapping'] = user_bioregion_mapping response = HttpResponse() response.write('%s' % simplejson.dumps(collection, indent=1)) response['Content-length'] = str(len(response.content)) response['Content-Type'] = 'text/plain' return response
class RaceBuilder(object): def __init__(self): self.output = HttpResponse(content_type="text/plain") def ip(self, x, str): s = '' for i in range(x): s += " " self.output.write("%s%s\n" % (s, str)) print "%s%s" % (s, str) def buildRoutesForRace(self, race_id): """main function to build an entire race, given a start and finish point. calls our recursion.""" race = Race.objects.get(id=race_id) # start building routes using each potential routeleg self.ip( 0, '[race] %s [start] %s' % (race.name, race.checkpoint_start.name)) legs = RouteLeg.objects.filter(checkpoint_a__name="%s" % race.checkpoint_start.name).exclude( checkpoint_b__enabled=False) self.ip(0, 'found %i legs' % len(legs)) race = self.buildRoute(race, legs) self.ip(0, "num routes found: %i" % race.routes.count()) return race, self.output def buildRoute(self, race, legs, route=None): """primary recursive function""" # capture the route as-is before trying to add on new legs initialRoute = route x = 0 y = 0 # iterate through all potential legs for leg in legs: y = y + 1 # reset the route to what is was leading into each new leg route = initialRoute # make a new route if we weren't passed one via recursion. if not route: route = Route() route.name = 'Route %s' % (route.pk) route.race = race route.checkpoint_start = race.checkpoint_start route.checkpoint_finish = race.checkpoint_finish self.ip(x, '[NEW ROUTE] %s' % route.name) x = route.countRoutelegs() self.ip(x, "Trying %s for route: %s" % (leg, route)) # ensure that checkpoint b is not disabled if (leg.checkpoint_b.enabled == False): self.ip( x, '\tFAIL: %s is disabled. Skipping.' % leg.checkpoint_b.name) continue # check for bad distance if (leg.distance > race.max_leg_distance): self.ip( x, " FAIL: %s distance > max: %s" % (leg.distance, race.max_leg_distance)) continue self.ip( x, " PASS: %s distance <= max: %s" % (leg.distance, race.max_leg_distance)) if (leg.distance < race.min_leg_distance): self.ip( x, " FAIL: %s distance < min: %s" % (leg.distance, race.min_leg_distance)) continue self.ip( x, " PASS: %s distance >= min:%s" % (leg.distance, race.min_leg_distance)) # checkpoint_b should never be the starting line if (leg.checkpoint_b == race.checkpoint_start): self.ip( x, '\tFAIL: %s = starting line. Cannot be a checkpoint.' % leg.checkpoint_b.name) continue self.ip( x, " PASS: %s != the starting line" % (leg.checkpoint_b.name)) # additional checks when a route exists if route: numlegs = route.countRoutelegs() if (numlegs > race.checkpoint_qty): self.ip( x, '\tERROR: numlegs = %s > %s (checkpoint qty). Should not happen.' % (numlegs, race.checkpoint_qty + 1)) continue # finish line checks if (leg.checkpoint_b == race.checkpoint_finish): if (numlegs < race.checkpoint_qty - 1): self.ip( x, '\tFAIL: %s = finish line, route is %i/%i full' % (leg.checkpoint_b.name, numlegs, race.checkpoint_qty)) continue else: self.ip( x, '\tPASS: %s = finish line, route is %i/%i full' % (leg.checkpoint_b.name, numlegs, race.checkpoint_qty)) else: if (numlegs == race.checkpoint_qty - 1): self.ip( x, '\tFAIL: %s != finish line, route is %i/%i full' % (leg.checkpoint_b.name, numlegs, race.checkpoint_qty)) continue else: self.ip( x, '\tPASS: %s != finish line, route is %i/%i full' % (leg.checkpoint_b.name, numlegs, race.checkpoint_qty)) # if adding this leg makes the total distance too far potentialDistance = route.getLength() + leg.distance if potentialDistance > race.max_race_distance: self.ip( x, " FAIL: %s distance > max race distance %s" % (potentialDistance, race.max_race_distance)) continue self.ip( x, " PASS: %s distance < max race distance %s" % (potentialDistance, race.max_race_distance)) # fail if checkpoint_b is already used bad = False for r in route.routelegnode_set.all(): if r.routeleg.checkpoint_b == leg.checkpoint_b: bad = True if bad: self.ip( x, '\tFAIL: %s is already in use in this route.' % leg.checkpoint_b.name) continue self.ip( x, '\tPASS: %s is not yet in use in this route.' % leg.checkpoint_b.name) # if we made it this far, add a RouteLegNode to our routes list node = RouteLegNode() node.parent_route = route node.routeleg = leg node.order = route.countRoutelegs() self.ip(x, '[NEW NODE] %s [order: %s]' % (node, node.order)) # HACK: we should be able to add a route w/o a length. Not sure why mysql blows up # it's ok since we set the actual length a little ways down route.length = -1 # add the new node to the potential route route.save() route.routelegnode_set.add(node) # --------------------------------------------- # WINNING CONDITION!!! # these are the conditions for a winning route. additional tests are applied within. if (route.countRoutelegs() == race.checkpoint_qty) and (leg.checkpoint_b == race.checkpoint_finish): # additional tests that only apply to a completed route if route.getLength() < race.min_race_distance: self.ip( x, '\tFAIL: %s distance < min race distance %s' % (route.getLength(), race.min_race_distance)) else: # we're good. Save. self.ip(x, '[ WIN ] %s' % route) # copy our route (and the intermediate models) and save it to the route table. route_copy = route.clone() # TODO: check for duplicate first. see: # https://docs.djangoproject.com/en/1.2/topics/db/queries/#query-expressions # http://stackoverflow.com/questions/2055626/filter-many-to-many-relation-in-django route_copy.length = route_copy.getLength() race.routes.add(route_copy) route_copy.name = route_copy.id route_copy.save() race.save() # slide the highest node off the route, regardless of whether or not we saved it self.sliceLatestNode(route, x) else: # ok, so we didn't win, but we have a leg that's not failing out. Pursue additional recursion. # This case should not occur if (route.countRoutelegs() == race.checkpoint_qty): self.ip(x, 'Route has enough legs. Not recursing further.') else: sublegs = RouteLeg.objects.filter(checkpoint_a__name="%s" % leg.checkpoint_b.name) self.ip(x, '[sublegs] found %i' % len(sublegs)) # recurrrrrsion! race = self.buildRoute(race, sublegs, route) # ROUTE FAIL. Remove the most recent node and move on. if route: # and not route in race.routes.all(): # delete the latest node self.ip(x, "[END OF ROUTE POTENTIAL]") self.sliceLatestNode(route, x) # check to see if our route is length=0. if so, delete it if (route.countRoutelegs() == 0): self.ip(x, "Deleting route containing 0 nodes") # we only have to delete the route if it's not already in the DB if route.id is not None: route.delete() # return our completed race object. self.ip(x, "returning race") return race def sliceLatestNode(self, route, x): """Slices off the most recent routelegnode from a route""" try: totalNodes = route.countRoutelegs() deleteNode = RouteLegNode.objects.get(parent_route=route, order=totalNodes - 1) # order starts at 0 if deleteNode: self.ip(x, "[SLICE NODE] %s:" % deleteNode) deleteNode.delete() except Exception, e: self.ip(x, "[SLICE NODE] No node to delete OR problem.")
def generar_pdf(request): MARGIN_SIZE = 17 * mm PAGE_SIZE = A4 #from django.db import connection print "Genero el PDF" response = HttpResponse(content_type='application/pdf') pdf_name = "clientes.pdf" styles = getSampleStyleSheet() stylesTitle = getSampleStyleSheet() stylesCabe = getSampleStyleSheet() styleTitle = stylesTitle["Normal"] styleTitle.alignment = TA_CENTER styleBH = styles["Normal"] styleBH.alignment = TA_LEFT styleCa = stylesCabe["Normal"] styleCa.alignment = TA_CENTER # pdf_name = "clientes.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() c = canvas.Canvas(buff, pagesize=A4) doc = SimpleDocTemplate( buff, pagesize=letter, rightMargin=70, leftMargin=70, topMargin=60, bottomMargin=18, ) h1 = PS(name='Heading1', fontSize=9, leading=16) h2 = PS(name='centered', fontSize=7, leading=14, alignment=TA_CENTER) clientes = [] story = [] # allclientes = Pruebaaa.objects.filter(ubigeo='21806').order_by('id') # allclientes = [(p.zona, p.id, p.aeu) for p in Pruebaaa.objects.all()] # permisos = list(ViewPermisosMenuChild.objects.filter(id_usuario=id).values('cod_permiso', 'nom_permiso', 'des_rol', 'id_menu')) filtro = list( MaeProyecto.objects.filter(ubigeo='020601', frente_ord='1', id_reg_or='23').values( 'or_viv_aeu', 'manzana', 'frente_ord', 'p20', 'p21', 'p22_a', 'p23', 'p24', 'p25', 'p26', 'p27_a', 'p32')) #allclientes = [(p.zona, p.id, p.aeu) for p in Pruebaaa.objects.filter(ubigeo='21806')] alltodo = [(str(a['or_viv_aeu']).decode('utf-8'), str( a['manzana']).decode('utf-8'), str(a['frente_ord']).decode('utf-8'), str(a['p20']).decode('utf-8'), str(a['p21']).decode('utf-8'), str(a['p22_a']).decode('utf-8'), str(a['p23']).decode('utf-8'), str(a['p24']).decode('utf-8'), str(a['p25']).decode('utf-8'), str(a['p26']).decode('utf-8'), str(a['p27_a']).decode('utf-8'), str(a['p32']).decode('utf-8')) for a in filtro] # Paragraph('a['p32']', styleTitle) # for i, e in enumerate(allclientes): # p.drawString(x + (18 * diff_x), y - diff_y, str(data_models.pub_date)) # story.append(Paragraph(str(e.ubigeo), styleBH)) # for a in allclientes: # story.append(a.id) # Texts # descrpcion = Paragraph('long paragraph long paragraphlong paragraphlong paragraphlong paragraphlong paragraph', # DOCUMENT_STYLE["normal"]) # partida = Paragraph('1', DOCUMENT_STYLE["normal"]) # candidad = Paragraph('120', DOCUMENT_STYLE["normal"]) # precio_unitario = Paragraph('$52.00', DOCUMENT_STYLE["normal"]) # precio_total = Paragraph('$6240.00', DOCUMENT_STYLE["normal"]) # data= [[hdescrpcion, hcandidad,hcandidad, hprecio_unitario, hprecio_total], # [partida, candidad, descrpcion, precio_unitario, precio_total]] data = [ [ Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h1), '', '', '', Paragraph('<strong>B. UBICACION CENSAL</strong>', h1), '' ], [ Paragraph('<strong>DEPARTAMENTO</strong>', h1), Paragraph('15', h1), Paragraph('LIMA', h1), '', Paragraph('<strong>ZONA N</strong>', h1), Paragraph('001', h1) ], [ Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph('01', h1), Paragraph('LIMA', h1), '', Paragraph('<strong>SECCION N</strong>', h1), Paragraph('010', h1) ], [ Paragraph('<strong>DISTRITO</strong>', h1), Paragraph('15', h1), Paragraph('LA VICTORIA', h1), '', Paragraph('<strong>A.E.U. N</strong>', h1), Paragraph('008', h1) ], [ Paragraph('<strong>CENTRO POBLADO</strong>', h1), Paragraph('LA VICTORIA', h1), '', '', '', '' ], [ Paragraph('<strong>CATEGORIA CENTRO POBLADO</strong>', h1), Paragraph('CIUDAD', h1), '', '', Paragraph('<strong>C. TOTAL DE VIVIENDAS DEL A.E.U.</strong>', h1), Paragraph('16', h1) ], ] obs_data = [ [ Paragraph(e, h2) for e in [ "<strong>VIV. N</strong>", "<strong>MZ N</strong>", "<strong>FRENTE N</strong>", "<strong>DIRECCION DE LA VIVIENDA</strong>", "", "", "", "", "", "", "", "<strong>Apellidos y Nombres del JEFE DEL HOGAR</strong>" ] ], [ Paragraph(e, h2) for e in [ "", "", "", "<strong>Tipo de Via</strong>", "<strong>Nombre de Via</strong>", "<strong>N de Puerta</strong>", "<strong>Block</strong>", "<strong>Man-zana N</strong>", "<strong>Lote N</strong>", "<strong>Piso N</strong>", "<strong>Interior N</strong>", "" ] ], #[Paragraph('<strong>VIV. N</strong>', styleTitle), Paragraph('<strong>MANZANA N</strong>', styleTitle), Paragraph('<strong>FRENTE N</strong>', styleTitle), Paragraph('<strong>DIRECCION DE LA VIVIENDA</strong>', styleTitle), '', '', '', '', '', '', '', Paragraph('<strong>Apellidos y Nombres del JEFE DEL HOGAR</strong>', styleTitle)], #['', '', '', Paragraph('<strong>Tipo de Via</strong>',styleTitle), Paragraph('<strong>Nombre de Via</strong>', styleTitle), Paragraph('<strong>N de Puerta</strong>', styleTitle), Paragraph('<strong>Block</strong>', styleTitle), Paragraph('<strong>Manzana N</strong>', styleTitle), Paragraph('<strong>Lote N</strong>', styleTitle),Paragraph( '<strong>Piso N</strong>', styleTitle),Paragraph('<strong>Interior N</strong>',styleTitle),''], ] obs = [ [Paragraph('OBSERVACIONES', styleBH), ''], [ '', '', ], [ '', '', ], [ '', '', ], ] headings = ('Nombre', 'zona', 'repo', 'Nombre', 'zona', 'repo', 'Nombre', 'zona', 'repo', 'Nombre', 'zona') #t = Table([headings] + allclientes) d = Table(obs_data + alltodo, colWidths=[ 0.9 * cm, 0.9 * cm, 1.5 * cm, 1.4 * cm, None, 1.2 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1.3 * cm, 4.6 * cm ]) # t.setStyle(TableStyle( # [ # ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), # ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), # ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) # ] # )) d.setStyle( TableStyle([ # ('GRID', (0, 0), (10, -1), 1, colors.black), # ('GRID', (4, 0), (5, 3), 1, colors.black) ('GRID', (1, 1), (-2, -2), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue), ('BACKGROUND', (0, 0), (-1, 1), colors.lightskyblue), ('SPAN', (3, 0), (10, 0)), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (11, 0), (11, 1)), # ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black) # ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue) ])) # d.setStyle(TableStyle( # [ # ('GRID', (0, 0), (10, -1), 1, colors.black), # ('GRID', (4, 0), (5, 3), 1, colors.black), # ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black) # #('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue) # ] # )) table = Table( data, colWidths=[6 * cm, 1 * cm, 3.5 * cm, 0.1 * cm, 6 * cm, 1.5 * cm]) table.setStyle( TableStyle([ ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 0), (2, 5), 1, colors.black), ('GRID', (4, 0), (5, 3), 1, colors.black), ('GRID', (-2, -1), (-1, -1), 1, colors.black), ('SPAN', (0, 0), (2, 0)), ('SPAN', (4, 0), (5, 0)), ('SPAN', (1, 4), (2, 4)), ('SPAN', (1, 5), (2, 5)), ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue), ('BACKGROUND', (0, 0), (0, 5), colors.lightskyblue), ('BACKGROUND', (4, 0), (4, 5), colors.lightskyblue) # ('TEXTFONT',(0,0), (-1,-1), 'Roboto-Regular'), # ('FONTSIZE',(0,0), (-1,-1), 1), ])) otable = Table(obs_data, colWidths=[ 1 * cm, 1 * cm, 1.6 * cm, 1.4 * cm, None, 1.4 * cm, 1 * cm, 1.2 * cm, 1.2 * cm, 1.1 * cm, 1.5 * cm, 4 * cm ]) otable.setStyle( TableStyle([ ('TEXTCOLOR', (0, 0), (-1, -1), colors.blue), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.lightskyblue), ('BACKGROUND', (0, 0), (-1, 1), colors.lightskyblue), # ('FONTSIZE', (0, 0), (-1, -1), 7), # ('FONTNAME', (0, 0), (-1, -1), 7), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (3, 0), (10, 0)), ('SPAN', (11, 0), (11, 1)) #('SPAN', (0, 0), (0, 1)), #('SPAN', (1, 0), (1, 1)), #('SPAN', (2, 0), (2, 1)), #('SPAN', (3, 0), (10, 0)), #('SPAN', (11, 0), (11, 1)), ])) t1 = Paragraph( "<strong>INSTITUO NACIONAL DE ESTADISTICA E INFORMATICA CENSOS NACIONALES 2017: XII DE POBLACION, VII DE VIVIENDA</strong>", styleTitle) # story.append(Spacer(0, 001 * mm)) t2 = Paragraph("<strong>Y III DE COMUNIDADES INDIGENAS</strong>", styleTitle) fichero_imagen_inei = 'Reporte/Img/inei.png' imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=50) P2 = Paragraph('', styleBH) fichero_imagen = 'Reporte/Img/escudo.png' imagen_logo = Image(os.path.realpath(fichero_imagen), width=50, height=50) t = Table( data=[['', '', ''], [[imagen_logo, P2], t1, [imagen_logo_inei, P2]], ['', t2, '']], colWidths=[2 * cm, 12 * cm, 2 * cm], style=[ ('GRID', (1, 1), (-2, -2), 1, colors.white), #('BOX', (0, 0), (1, -1), 2, colors.black), #('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue), #('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink), #('BACKGROUND', (0, 0), (0, 1), colors.pink), #('BACKGROUND', (1, 1), (1, 2), colors.lavender), #('BACKGROUND', (2, 2), (2, 3), colors.orange), #('BOX', (0, 0), (-1, -1), 2, colors.black), ('GRID', (0, 0), (-1, -1), 0.5, colors.white), #('VALIGN', (3, 0), (3, 0), 'BOTTOM'), #('BACKGROUND', (3, 0), (3, 0), colors.limegreen), #('BACKGROUND', (3, 1), (3, 1), colors.khaki), #('ALIGN', (3, 1), (3, 1), 'CENTER'), #('BACKGROUND', (3, 2), (3, 2), colors.beige), #('ALIGN', (3, 2), (3, 2), 'LEFT'), ]) t1 = Paragraph("<strong>VIV.N</strong>", h2) t2 = Paragraph("<strong>MZ N</strong>", h2) t3 = Paragraph("<strong>FRENTE N</strong>", h2) t4 = Paragraph("<strong>Tipo de Via</strong>", h2) t5 = Paragraph("<strong>Nombre de Via</strong>", h2) t6 = Paragraph("<strong>N de Puerta</strong>", h2) t7 = Paragraph("<strong>Block</strong>", h2) t8 = Paragraph("<strong>Man-zana N</strong>", h2) t9 = Paragraph("<strong>Lote N</strong>", h2) t10 = Paragraph("<strong>Piso N</strong>", h2) t11 = Paragraph("<strong>Interior N</strong>", h2) t12 = Paragraph("<strong>Apellidos y Nombres del JEFE DEL HOGAR</strong>", h2) t13 = Paragraph("<strong>DIRECCION DE LA VIVIENDA</strong>", h2) z = Table( data=[[t1, t2, t3, t13, '', '', '', '', '', '', '', t12], ['', '', '', t4, t5, t6, t7, t8, t9, t10, t11, '']], colWidths=[ 0.9 * cm, 0.9 * cm, 1.5 * cm, 1.4 * cm, None, 1.2 * cm, 1 * cm, 1 * cm, 1 * cm, 1 * cm, 1.3 * cm, 3.4 * cm ], style=[ ('GRID', (1, 1), (-2, -2), 1, colors.black), # ('BOX', (0, 0), (1, -1), 2, colors.black), # ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue), # ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink), # ('BACKGROUND', (0, 0), (0, 1), colors.pink), # ('BACKGROUND', (1, 1), (1, 2), colors.lavender), # ('BACKGROUND', (2, 2), (2, 3), colors.orange), # ('BOX', (0, 0), (-1, -1), 2, colors.black), ('GRID', (0, 0), (-1, -1), 0.5, colors.black), # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'), # ('BACKGROUND', (3, 0), (3, 0), colors.limegreen), # ('BACKGROUND', (3, 1), (3, 1), colors.khaki), # ('ALIGN', (3, 1), (3, 1), 'CENTER'), # ('BACKGROUND', (3, 2), (3, 2), colors.beige), # ('ALIGN', (3, 2), (3, 2), 'LEFT'), ('SPAN', (0, 0), (0, 1)), ('SPAN', (1, 0), (1, 1)), ('SPAN', (2, 0), (2, 1)), ('SPAN', (11, 0), (11, 1)), ('SPAN', (3, 0), (10, 0)) ]) # imagen_logo.drawOn(canvas,20,20) # imagen_logo.drawWidth(10) # imagen_logo.drawWidth(5) # drawImage(archivo, x, y, width=None, height=None) # c.drawImage(fichero_imagen, 2, 2, width=100, height=100) # # table.wrapOn(c, A4, A4) # # table.drawOn(c, 20, 650) # c.showPage() # c.save() story.append(t) # story.append(z) # story.append(imagen_logo_inei) story.append(Spacer(0, 05 * mm)) story.append( Paragraph( "<strong>LISTADO DE VIVIENDAS DEL AREA DE EMPADRONAMIENTO URBANO (A.E.U.)</strong>", styleTitle)) story.append(Spacer(0, 5 * mm)) story.append(table) story.append(dist) story.append(Spacer(0, 5 * mm)) # story.append(otable) # story.append(Spacer(0,01 * mm)) story.append(d) doc.build(story) response.write(buff.getvalue()) buff.close() return response
def get_storypoints(request, user): from django.contrib.gis.geos import Point if not request.user.is_authenticated(): return HttpResponse(simplejson.dumps({ 'message': 'User is not authenticated', 'status': 401 })) usetting = UserSettings.objects.get(user=request.user) geom = usetting.get_bioregion().geometry_final if usetting.ns_tweets: # get centroid for twitter request centroid = geom.centroid max_point = geom.envelope[0][0] max_pt_obj = Point(max_point[0], max_point[1]) # get radius for twitter request radius = centroid.distance(max_pt_obj) centroid.transform(4326) geocode = str(centroid.y) + ',' + str(centroid.x) + ',' + str(radius/1000) + 'km' included_tweets = [] geo_tweets = [] for term in ['climate', 'ecology', 'resilience', 'agriculture']: url = 'https://api.twitter.com/1.1/search/tweets.json?count=100&q=%s&geocode=%s' % (term,geocode) broad_tweets = oauth_req(url, 'twitter') tweets = simplejson.loads(broad_tweets) geo_tweets += [x for x in tweets['statuses'] if x['geo']!=None] for tweet in geo_tweets: point = Point(tweet['geo']['coordinates'][1], tweet['geo']['coordinates'][0]) point.srid=4326 point.transform(3857) if point.within(geom): tweet['point'] = point if not any(x['id']== tweet['id'] for x in included_tweets): included_tweets.append(tweet) #TODO - don't store (most) storypoints locally - only posts. ### For example, if we had a 'stored' source type, we could continue to use the below if user == 'json': my_story_points = StoryPoint.objects.filter(Q(geometry__within=geom) | Q(source_user=usetting.user)) # qs = StoryPoint.objects.all() qs = my_story_points else: qs = StoryPoint.objects.filter(source_type='user', source_user=user) features = [] for point in qs.order_by('-created'): if point.source_type != 'user': image = point.image source_user_id = None source_user_name = None else: image = point.avatar() source_user_id = point.source_user.id source_user_name = point.source_user.get_full_name() feature = { 'id' : str(point.id), 'geometry': { 'type': 'Point', 'coordinates': [ point.geometry.coords[0], point.geometry.coords[1] ] }, 'type': 'Feature', 'properties': { 'storyPoint': { 'id': point.id, 'source_user_id': source_user_id, 'source_user_name': source_user_name, 'source_type': point.source_type, 'source_link': point.source_link, 'title': point.title, 'content': point.content, 'image': image, 'date': point.date_string(), 'isPerm': point.is_permanent, 'flagged': point.flagged, 'flag_reason': point.flag_reason }, 'source_type': point.source_type } } features.append(feature) for point in included_tweets: image = point['user']['profile_image_url'] source_user_id = None try: feature = { 'id' : str(point['id']), 'geometry': { 'type': 'Point', 'coordinates': [ point['point'].x, point['point'].y ] }, 'type': 'Feature', 'properties': { 'storyPoint': { 'id': point['id'], 'source_user_id': source_user_id, 'source_type': 'twitter', 'source_link': 'http://www.twitter.com/' + point['user']['screen_name'], 'title': '@' + point['user']['screen_name'], 'content': point['text'], 'image': image, 'date': point['created_at'], 'isPerm': False, 'flagged': False, #TODO 'flag_reason': None #point.flag_reason }, 'source_type': 'twitter' #point.source_type } } except: pass features.append(feature) storypoints = { "srid": 900913, "crs": { "type": "link", "properties": { "href": "http://spatialreference.org/ref/epsg/900913/", "type": "proj4" } }, "type": "FeatureCollection", "features": features } response = HttpResponse() response.write('%s' % simplejson.dumps(storypoints, indent=1)) response['Content-length'] = str(len(response.content)) response['Content-Type'] = 'text/plain' return response
def reporte_ventas(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ventas.pdf"' r = ReporteVenta() response.write(r.run()) return response
def dwn(request): try: if 'clear' in request.GET: request.session['saved'] = [] if 'delete' in request.GET: delList = request.GET['delete'].split('_') for delTag in delList: request.session['saved'] = [ x for x in request.session['saved'] if delTag not in x[3] ] if 'downloadAll' in request.GET: response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="data.csv"' writer = csv.writer(response) response.write('\ufeff') f = open('dwn/merge.csv', 'r') outList = [ ele[3].split("-")[1].lower() for ele in request.session['saved'] ] outList = ['id2'] + outList writer.writerow(outList) for row in csv.DictReader(f): line = [] for x in outList: try: line.append(row[x]) except: line.append('') writer.writerow(line) f.close() return response if 'downloadProg' in request.GET: response = HttpResponse(content_type='text/txt') response[ 'Content-Disposition'] = 'attachment; filename="program.txt"' outList = [ ele[3].split("-")[1] for ele in request.session['saved'] ] for keyword in outList: try: response.write(keyword + ':\r\n') for s in program.objects.filter( question__contains=keyword): response.write(str(s) + '\r\n') response.write('\r\n') except Exception as e: print(str(e)) return response if 'downloadList' in request.GET: response = HttpResponse(content_type='text/txt') response['Content-Disposition'] = 'attachment; filename="list.txt"' response.write(pformat(out).replace('\n', '\r\n')) return response if 'downloadProg_SPSS' in request.GET: response = HttpResponse(content_type='text/txt') response[ 'Content-Disposition'] = 'attachment; filename="program_SPSS.txt"' outList = [ ele[3].split("-")[1] for ele in request.session['saved'] ] for keyword in outList: try: response.write(keyword + ':\r\n') for s in spss.objects.filter(question__contains=keyword): response.write(str(s) + '\r\n') response.write('\r\n') except Exception as e: print(str(e)) return response if 'saved' not in request.session: request.session['saved'] = [] except Exception as e: print(str(e)) tags = {} data = {} global out out = [] for rec in request.session['saved']: try: pk = rec[3].split('-')[0] tag = rec[3].split('-')[1] except: request.session['saved'] = [] return render_to_response('download.html') try: tags[pk].append(tag) except: tags[pk] = [] tags[pk].append(tag) try: ques = subject.objects.get(pk=pk).question ques_top = subject.objects.get(pk=pk).question_top tagList = subject.objects.get(pk=pk).wave except: request.session['saved'] = [] return render_to_response('download.html') waveList = '' i = 0 for w in tagList.split(','): i += 1 if w != '': waveList += 'w' + str(i) + ' ' if ques != ques_top: data[pk] = [ rec[0], waveList, rec[1], rec[2], ques_top + ' ' + ques, ", ".join(tags[pk]) ] else: data[pk] = [ rec[0], waveList, rec[1], rec[2], ques, ", ".join(tags[pk]) ] for key in data: out.append(data[key]) return render_to_response('download.html', { 'saved': out, })
def new(request): newcodes = [] subproductform = SubProductForm() download = "false" productform = ProductForm() if request.method == "POST": if request.POST.get("select", "") == "subproduct": wb = load_workbook(request.FILES['subproduct']) ws = wb.active headers = [cell.value for cell in ws.rows.next()] subprods = [] for row in ws.iter_rows(row_offset=1): if row[0].value: rowDict = {} for cellnum in range(len(row) + 1): try: cell = row[cellnum] rowDict[headers[cellnum]] = cell.value except IndexError: pass try: productline = ProductLine.objects.get( code=rowDict.get("Existing Product Line Code")) except Exception as e: print(u"Could not find ProductLine '{0}' at row {1}". format(rowDict.get("Existing Product Line Code"), row[0].row)) debug() code = get_unused_code() description = rowDict.get("Igor / Sub PL Description", "") usage = rowDict.get("Usage") if usage: usage = Usage.objects.get(name=usage) igoritemclass = rowDict.get("Igor Item Class", None) if igoritemclass: igoritemclass = IgorItemClass.objects.get( name=igoritemclass) if len(description) > 30: print( u"New Subproduct Line '{0}' exceed 30 characters: {0}. Dropping into the debugger. You decide what to do." .format(description, len(description))) debug() subproductline, created = SubProductLine.objects.get_or_create( fproductline=productline, igor_or_sub_pl=code.code, description=description, igorclass=igoritemclass, usage=usage) if created: msg = subproductline.save() if msg: messages.warning(request, msg) subprods.append(subproductline) code.use(newcodes) wb = Workbook() ws = wb.active count = 1 tmp = NamedTemporaryFile(suffix=".xlsx") for header in bigheaders: ws.cell(row=1, column=count).value = header count += 1 count = 2 for subprod in subprods: subprod.excel_row(ws, count) count += 1 wb.save(tmp) tmp.flush() #tmp.seek(0) #response = HttpResponse(content_type='application/xlsx') #response['Content-Disposition'] = 'attachment; filename="{0}"'.format(os.path.basename(tmp.name)) #response.write(tmp.read()) #return(response) tmp.seek(0) request.session['download'] = base64.b64encode(tmp.read()) download = "true" elif request.POST.get('select') == "product": wb = load_workbook(request.FILES['product']) ws = wb.get_sheet_by_name(name='Product_Hierarchy') headers = [cell.value for cell in ws.rows.next()] prods = [] rowDictList = [] for row in ws.iter_rows(row_offset=1): if row[0].value: rowDict = {} for cellnum in range(len(row) + 1): try: cell = row[cellnum] rowDict[headers[cellnum]] = cell.value except IndexError: pass rowDictList.append(rowDict) """All product lines of the same name within a product line request should have the same Igor code, otherwise, abort.""" productLineGroupIgorDict = {} for rowDict in rowDictList: productLineGroupIgorDict[rowDict[ "Product Line Name"]] = productLineGroupIgorDict.get( rowDict["Product Line Name"], []) + [rowDict["Igor Item Class"]] for plName, igorCodeList in productLineGroupIgorDict.iteritems(): if len(set(igorCodeList)) > 1: newClass = "active" messages.warning( request, u"Igor Item Classes differ for identical Product Line Name: {0}. Aborting..." .format(plName)) return (render(request, "hierarchy/new.html", locals())) newProductLines = [] #List of ID's subprods = [] for rowDict in rowDictList: try: productlinegroup = ProductLineGroup.objects.get( code__iexact=rowDict.get( "Existing Product Line Group Code")) except Exception as e: print e print( u"Could not find Product Line Group Code '{0}'".format( rowDict.get("Existing Product Line Group Code"))) debug() code = get_unused_code() igorDescription = rowDict.get("Igor / Sub PL Description", "") usage = rowDict.get("Usage") productlinename = rowDict.get("Product Line Name") if usage: try: usage = Usage.objects.get(name__iexact=usage) except Exception as e: debug() print(u"Usage not found '{0}' at row {1}".format( usage, row[0].row)) igoritemclass = rowDict.get("Igor Item Class", None) if igoritemclass: igoritemclass = IgorItemClass.objects.get( name=igoritemclass) """Product line names are not unique in the database, but we don't want to create multiple product lines with the same description within a single new product line request. Check if we've created one in this new productline request, and if not create a new one. """ if len(productlinename) > 30: print( u"Product Line Name '{0}' exceed 30 characters: {1} dropping into the debugger. The database will trucate the name if you contine. Abort with ^c" .format(productlinename, len(productlinename))) try: productLine = ProductLine.objects.get( id__in=newProductLines, name__iexact=productlinename[:30]) except ProductLine.DoesNotExist: code = get_unused_code() productline = ProductLine( code=code.code, name=productlinename, fproductlinegroup=productlinegroup) productline.save() code.use(newcodes) newProductLines.append(productline.id) #Now we have a new productline code = get_unused_code() subproductline = SubProductLine(fproductline=productline, igor_or_sub_pl=code.code, description=igorDescription, igorclass=igoritemclass, usage=usage) msg = subproductline.save() if msg: messages.warning(request, msg) subprods.append(subproductline) code.use(newcodes) wb = Workbook() ws = wb.active ws.title = "Product_Hierarchy" wsProductCodes = wb.create_sheet() wsProductCodes.title = "Product_Codes" count = 1 tmp = NamedTemporaryFile(suffix=".xlsx") for header in bigheaders: ws.cell(row=1, column=count).value = header ws.cell(row=1, column=count).font = Font(bold=True) count += 1 count = 2 for subproduct in subprods: subproduct.excel_row(ws, count) count += 1 #tmp.seek(0) #response = HttpResponse(content_type='application/xlsx') #response['Content-Disposition'] = 'attachment; filename="{0}"'.format(os.path.basename(tmp.name)) #response.write(tmp.read()) #return(response) tmp.seek(0) #Write product codes into a 2nd sheet column = 1 for header in ["Code", "Description", "Type", "Date"]: wsProductCodes.cell(row=1, column=column).value = header wsProductCodes.cell(row=1, column=column).font = Font(bold=True) column += 1 row = 2 for newcodeList in newcodes: column = 1 for value in newcodeList: wsProductCodes.cell(row=row, column=column).value = value column += 1 row += 1 wb.save(tmp) tmp.flush() tmp.seek(0) request.session['download'] = base64.b64encode(tmp.read()) elif request.method == "GET": download = request.GET.get("download") if download in ["sub-product-template.xlsx", "product-template.xlsx"]: filepath = os.path.join(settings.BASE_DIR, "hierarchy", "static", "hierarchy", "downloads", download) response = HttpResponse(content_type="application/xlsx") response[ 'Content-Disposition'] = 'attachment; filename="{0}"'.format( download) spreadsheet = open(filepath, 'rb').read() response.write(spreadsheet) return (response) retrieve = "retrieve" in request.GET.keys() if retrieve: xlsx = base64.b64decode(request.session['download']) response = HttpResponse(content_type='application/xlsx') response[ 'Content-Disposition'] = 'attachment; filename="{0}"'.format( os.path.basename("productcodes.xlsx")) response.write(xlsx) return (response) newClass = "active" return (render(request, "hierarchy/new.html", locals()))
def mixteRamassagePdfParClasse(ramassage, total, parmois, full, colleur=False): """Renvoie le fichier PDF du ramassage par classe correspondant au ramassage dont l'id est id_ramassage si total vaut 1, les totaux par classe et matière sont calculés""" LISTE_MOIS = [ "", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" ] response = HttpResponse(content_type='application/pdf') if Ramassage.objects.filter(moisFin__lt=ramassage.moisFin).exists( ) and not full: # s'il existe un ramassage antérieur debut = Ramassage.objects.filter( moisFin__lt=ramassage.moisFin).aggregate( Max('moisFin'))['moisFin__max'] + timedelta(days=1) else: debut = Semaine.objects.aggregate(Min('lundi'))['lundi__min'] fin = ramassage.moisFin moisdebut = 12 * debut.year + debut.month - 1 decomptes = Ramassage.objects.decompteRamassage(ramassage, csv=False, parClasse=True, parMois=bool(parmois), full=full) nomfichier = "ramassagePdfParclasse{}_{}-{}_{}.pdf".format( debut.month, debut.year, fin.month, fin.year) response['Content-Disposition'] = "attachment; filename={}".format( nomfichier) pdf = easyPdf(titre="Ramassage des colles de {} {} à {} {}".format( LISTE_MOIS[debut.month], debut.year, LISTE_MOIS[fin.month], fin.year), marge_x=30, marge_y=30) largeurcel = (pdf.format[0] - 2 * pdf.marge_x) / (10 + parmois) hauteurcel = 30 total = int(total) for classe, listeClasse, nbMatieres in decomptes: totalclasse = 0 pdf.debutDePage(soustitre=classe) nbKolleurs = nbMatieres if total: nbKolleurs += 1 + len([ x for x, y, z in listeClasse ]) # on rajoute le nombre de matières et 1 pour la classe LIST_STYLE = TableStyle([('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8)]) data = [ ["Matière", "Établissement", "Grade", "Colleur"] + (["mois"] if parmois else []) + ["heures"] ] + [ [""] * (5 + parmois) for i in range(min(22, nbKolleurs)) ] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneMat = ligneEtab = ligneGrade = ligneColleur = ligneMois = 1 for matiere, listeEtabs, nbEtabs in listeClasse: totalmatiere = 0 data[ligneMat][0] = matiere if nbEtabs > 1: LIST_STYLE.add('SPAN', (0, ligneMat), (0, min(ligneMat + nbEtabs - 1, 22))) ligneMat += nbEtabs for etablissement, listeGrades, nbGrades in listeEtabs: data[ligneEtab][ 1] = 'Inconnu' if not etablissement else etablissement.title( ) if nbGrades > 1: LIST_STYLE.add('SPAN', (1, ligneEtab), (1, min(ligneEtab + nbGrades - 1, 22))) ligneEtab += nbGrades for grade, listeColleurs, nbColleurs in listeGrades: data[ligneGrade][2] = grade if nbColleurs > 1: LIST_STYLE.add( 'SPAN', (2, ligneGrade), (2, min(ligneGrade + nbColleurs - 1, 22))) ligneGrade += nbColleurs if parmois: # si on ramassage pour chaque mois for colleur, listeMois, nbMois in listeColleurs: data[ligneColleur][3] = colleur if nbMois > 1: LIST_STYLE.add( 'SPAN', (3, ligneColleur), (3, min(ligneColleur + nbMois - 1, 22))) ligneColleur += nbMois for moi, heures in listeMois: totalmatiere += heures if moi < moisdebut: LIST_STYLE.add('TEXTCOLOR', (4, ligneMois), (5, ligneMois), (1, 0, 0)) data[ligneMois][4] = LISTE_MOIS[moi % 12 + 1] data[ligneMois][5] = "{:.02f}h".format( heures / 60).replace('.', ',') ligneMois += 1 if ligneMois == 23 and nbKolleurs > 22: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t = Table(data, colWidths=[ 2 * largeurcel, 3 * largeurcel, largeurcel, 3 * largeurcel, largeurcel, largeurcel ], rowHeights=min( (1 + nbKolleurs), 23) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - hauteurcel / 2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage(soustitre=classe) LIST_STYLE = TableStyle([ ('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8) ]) nbKolleurs -= 22 data = [[ "Matière", "Établissement", "Grade", "Colleur", "mois", "heures" ]] + [ [""] * 6 for i in range(min(22, nbKolleurs)) ] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab -= 22 ligneGrade -= 22 ligneMat -= 22 ligneColleur -= 22 ligneMois = 1 if ligneMat > 1: data[1][0] = matiere if ligneMat > 2: LIST_STYLE.add( 'SPAN', (0, 1), (0, min(ligneMat - 1, 22))) if ligneEtab > 1: data[1][ 1] = 'Inconnu' if not etablissement else etablissement.title( ) if ligneEtab > 2: LIST_STYLE.add( 'SPAN', (1, 1), (1, min(ligneEtab - 1, 22))) if ligneGrade > 1: data[1][2] = grade if ligneGrade > 2: LIST_STYLE.add( 'SPAN', (2, 1), (2, min( ligneGrade - 1, 22))) if ligneColleur > 1: data[1][3] = colleur if ligneColleur > 2: LIST_STYLE.add( 'SPAN', (3, 1), (3, min( ligneColleur - 1, 22))) # fin matière else: # si on ne ramasse pas pour chaque mois mais globalement sur la période de ramassage for colleur, heures in listeColleurs: totalmatiere += heures data[ligneColleur][3] = colleur data[ligneColleur][4] = "{:.02f}h".format( heures / 60).replace('.', ',') ligneColleur += 1 if ligneColleur == 23 and nbKolleurs > 22: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t = Table( data, colWidths=[ 2 * largeurcel, 3 * largeurcel, largeurcel, 3 * largeurcel, largeurcel ], rowHeights=min( (1 + nbKolleurs), 23) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - hauteurcel / 2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage(soustitre=classe) LIST_STYLE = TableStyle([ ('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8) ]) nbKolleurs -= 22 data = [[ "Matière", "Établissement", "Grade", "Colleur", "heures" ]] + [ [""] * 5 for i in range(min(22, nbKolleurs)) ] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab -= 22 ligneGrade -= 22 ligneMat -= 22 ligneColleur = 1 if ligneMat > 1: data[1][0] = matiere.title() if ligneMat > 2: LIST_STYLE.add( 'SPAN', (0, 1), (0, min(ligneMat - 1, 22))) if ligneEtab > 1: data[1][ 1] = 'Inconnu' if not etablissement else etablissement.title( ) if ligneEtab > 2: LIST_STYLE.add( 'SPAN', (1, 1), (1, min(ligneEtab - 1, 22))) if ligneGrade > 1: data[1][2] = grade if ligneGrade > 2: LIST_STYLE.add( 'SPAN', (2, 1), (2, min( ligneGrade - 1, 22))) # fin matière totalclasse += totalmatiere if total: LIST_STYLE.add('SPAN', (0, ligneColleur), (3 + parmois, ligneColleur)) LIST_STYLE.add('BACKGROUND', (0, ligneColleur), (-1, ligneColleur), (.8, .8, .8)) data[ligneColleur] = ["total {}".format( matiere.title())] + [""] * (3 + parmois) + [ "{:.02f}h".format(totalmatiere / 60).replace('.', ',') ] ligneEtab += 1 ligneGrade += 1 ligneMat += 1 ligneColleur += 1 ligneMois += 1 if ligneColleur == 23 and nbKolleurs > 22: # si le tableau prend toute une page (et qu'il doit continuer), on termine la page et on recommence un autre tableau t = Table(data, colWidths=[ 2 * largeurcel, 3 * largeurcel, largeurcel, 3 * largeurcel, largeurcel ], rowHeights=min( (1 + nbKolleurs), 23) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - hauteurcel / 2) pdf.finDePage() # on redémarre sur une nouvelle page pdf.debutDePage(soustitre=classe) LIST_STYLE = TableStyle([ ('GRID', (0, 0), (-1, -1), 1, (0, 0, 0)), ('BACKGROUND', (0, 0), (-1, 0), (.6, .6, .6)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('FACE', (0, 0), (-1, -1), "Helvetica-Bold"), ('SIZE', (0, 0), (-1, -1), 8) ]) nbKolleurs -= 22 data = [ ["Matière", "Établissement", "Grade", "Colleur"] + (["mois"] if parmois else []) + ["heures"] ] + [ [""] * (5 + parmois) for i in range(min(22, nbKolleurs)) ] # on créé un tableau de la bonne taille, rempli de chaînes vides ligneEtab -= 22 ligneGrade -= 22 ligneMat -= 22 if parmois: ligneColleur -= 22 ligneMois = 1 else: ligneColleur = 1 # fin classe if total: LIST_STYLE.add('SPAN', (0, ligneColleur), (3 + parmois, ligneColleur)) LIST_STYLE.add('BACKGROUND', (0, ligneColleur), (-1, ligneColleur), (.7, .7, .7)) data[ligneColleur] = [ "total {}".format(classe) ] + [""] * (3 + parmois) + [ "{:.02f}h".format(totalclasse / 60).replace('.', ',') ] ligneEtab += 1 ligneGrade += 1 ligneMat += 1 ligneColleur += 1 t = Table(data, colWidths=[ 2 * largeurcel, 3 * largeurcel, largeurcel, 3 * largeurcel, largeurcel ], rowHeights=min((1 + nbKolleurs), 23) * [hauteurcel]) t.setStyle(LIST_STYLE) w, h = t.wrapOn(pdf, 0, 0) t.drawOn(pdf, (pdf.format[0] - w) / 2, pdf.y - h - hauteurcel / 2) pdf.finDePage() pdf.save() fichier = pdf.buffer.getvalue() pdf.buffer.close() response.write(fichier) return response
def ocompra_report(request, id): master = OrdenCompra.objects.get(id=id) detail = master.ordencompradetalle_set.all() response = HttpResponse(content_type='application/pdf') #pdf_name = "nota_recepcion.pdf" #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name elements = [] buffer = BytesIO() #doc = getDoc(buff,'nota de pedido') c = canvas.Canvas(buffer, pagesize=A4) #Header c.setTitle("Orden Compra") c.setLineWidth(.3) c.setFont("Times-Bold", 12) c.drawString(200, 790, 'ORDEN COMPRA') c.drawString(250, 770, 'Nº') nro = c.drawString(270, 770, str(master.nroOrdenCompra)) c.drawString(400, 790, master.fecha.strftime('%d-%m-%Y')) print(settings.STATIC_ROOT) archivo_imagen = settings.STATIC_ROOT + '/app/images/logo.png' c.drawImage(archivo_imagen, 80, 760, width=70, height=45) #Table Header styles = getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 8 parrafoStyle = ParagraphStyle('parrafos', alignment=TA_JUSTIFY, fontSize=8, fontName="Times-Roman") headings = ('Cantidad', 'Unidad de Medida', 'Descripción', 'Precio', 'Subtotal') results = [(d.cantidad, d.unidadMedida, d.articulo.descripcion, formatMoneda(d.precio), formatMoneda(d.subtotal)) for d in detail] #elements.append(tabla_encabezado(styles,titulo1,nro)) c.setFont("Times-Bold", 12) c.drawString(80, 740, "Proveedor: ") c.drawString(80, 720, "Fecha Entrega: ") c.drawString(350, 720, "Moneda: ") c.drawString(80, 240, "Total: ") c.drawString(80, 220, "Forma de Pago: ") c.drawString(200, 220, "Términos y Condiciones: ") c.drawString(80, 180, "Ref. Pedido: ") c.drawString(80, 160, "Usuario: ") c.setFont("Times-Roman", 12) c.drawString(165, 740, str(master.proveedor)) c.drawString(165, 720, str(master.fechaEntrega)) c.drawString(400, 720, str(master.moneda)) #c.drawString(480, 240, '{:,}'.format(master.total)) c.drawString(480, 240, str(formatMoneda(master.total))) c.drawString(80, 200, str(master.plazoPago)) c.drawString(330, 220, str(master.terminosCondiciones)) c.drawString(150, 180, str(master.pedido)) c.drawString(150, 160, str(master.usuario)) elements.append(headings) elements.append(results) #Detalle Tabla table = Table([headings] + results, colWidths=[ 0.7 * inch, 1.22 * inch, 3.0 * inch, 0.8 * inch, 0.8 * inch ], rowHeights=0.18 * inch) table.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 0), (4, -3), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.transparent), ('ALIGN', (4, 0), (-1, -1), 'CENTER'), ])) elements.append(table) table.wrapOn(c, 600, 500) table.drawOn(c, 80, 660) c.setFont("Times-Roman", 8) c.line(80, 70, 160, 70) c.line(250, 70, 340, 70) c.line(400, 70, 480, 70) c.drawString(90, 55, "Gerente de Área") c.drawString(280, 55, "Hecho por") c.drawString(430, 55, "Vº Bº") c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def index(request): response = HttpResponse() response.write("<h1>Blog</h1><hr>") return response
def nota_pedido_report(request, id): master = NotaPedido.objects.get(id=id) detail = master.notapedidodetalle_set.all() cant_elementos = len(detail) response = HttpResponse(content_type='application/pdf') #pdf_name = "nota_pedido.pdf" #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name elements = [] buffer = BytesIO() #doc = getDoc(buff,'nota de pedido') c = canvas.Canvas(buffer, pagesize=A4) width, height = A4 #Header c.setTitle("Nota Pedido") c.setLineWidth(.3) c.setFont("Times-Bold", 12) titulo1 = c.drawString(220, 790, 'NOTA DE PEDIDO') c.drawString(250, 770, 'Nº') nro = c.drawString(270, 770, str(master.nroPedido)) print(settings.STATIC_ROOT) archivo_imagen = settings.STATIC_ROOT + '/app/images/logo.png' #imagen = Image(archivo_imagen, width=50, height=50,hAlign='LEFT') c.drawString(400, 780, master.fecha.strftime('%d-%m-%Y')) c.drawImage(archivo_imagen, 80, 770, width=70, height=45) #Table Header styles = getSampleStyleSheet() styleBH = styles["BodyText"] styleBH.alignment = TA_CENTER styleBH.fontSize = 12 #parrafoStyle = ParagraphStyle('parrafos',alignment = TA_JUSTIFY,fontSize = 8,fontName="Times-Roman") c.setFont("Times-Bold", 12) c.drawString(80, 740, "Para: ") c.drawString(270, 740, "De: ") c.setFont("Times-Roman", 12) c.drawString(110, 740, str(master.departamentoDestino)) c.drawString(295, 740, str(master.departamentoOrigen)) c.drawString(80, 720, "Solicitamos nos provean de los siguientes: ") headings = ('Cantidad', 'Unidad de Medida', 'Descripción') results = [(d.cantidad, d.unidadMedida, d.articulo.descripcion) for d in detail] elements.append(headings) elements.append(results) #c.setFont("Times-Roman", 6) #Detalle Tabla table = Table([headings] + results, colWidths=[1.35 * inch, 1.35 * inch, 3.5 * inch], rowHeights=0.2 * inch, splitByRow=10) table.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ('GRID', (0, 0), (4, -3), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.transparent), ('ALIGN', (4, 0), (-1, -1), 'CENTER'), ])) #elements.append(table) table.wrapOn(c, width, height) table.drawOn(c, 29 * mm, (242 * mm) - (cant_elementos * mm * 5.2)) #table.wrapOn(c, 800, 600) #if cant_elementos < 5: # table.drawOn(c, 80, y-58) #else: # table.drawOn(c, 80, 400) c.setFont("Times-Bold", 12) c.drawString(80, 480, "Para uso en: ") c.drawString(80, 460, "Precio aproximado: ") c.setFont("Times-Roman", 12) c.drawString(190, 480, to_str(master.descripcionUso)) c.drawString(190, 460, to_str(master.precioAproximado)) c.line(80, 435, 220, 435) c.line(270, 435, 350, 435) c.line(410, 435, 500, 435) c.setFont("Times-Roman", 8) c.drawString(85, 420, "Vo.Bo. Gte. Administrativo") c.drawString(280, 420, "Jefe de Est.") c.drawString(415, 420, "Gerente de Área") #Header2 #c.setLineWidth(.3) #c.setFont("Times-Roman", 12) c.setFont("Times-Bold", 12) titulo1 = c.drawString(220, 380, 'NOTA DE PEDIDO') c.drawString(250, 360, 'Nº') nro = c.drawString(270, 360, str(master.nroPedido)) c.drawString(400, 380, master.fecha.strftime('%d-%m-%Y')) c.drawImage(archivo_imagen, 80, 360, width=70, height=45) c.drawString(80, 340, "Para: ") c.drawString(280, 340, "De: ") c.setFont("Times-Roman", 12) c.drawString(110, 340, str(master.departamentoDestino)) c.drawString(300, 340, str(master.departamentoOrigen)) c.drawString(80, 320, "Solicitamos nos provean de los siguientes: ") #Detalle Tabla 2 table2 = Table([headings] + results, colWidths=[1.35 * inch, 1.35 * inch, 3.5 * inch], rowHeights=0.2 * inch, splitByRow=10) table2.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ('GRID', (0, 0), (4, -3), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.transparent), ('ALIGN', (4, 0), (-1, -1), 'CENTER'), ])) #elements.append(table2) table2.wrapOn(c, width, height) table2.drawOn(c, 29 * mm, (100 * mm) - (cant_elementos * mm * 5.2)) c.setFont("Times-Bold", 12) c.drawString(80, 70, "Para uso en: ") c.drawString(80, 50, "Precio aproximado: ") c.setFont("Times-Roman", 12) c.drawString(190, 70, to_str(master.descripcionUso)) c.drawString(190, 50, to_str(master.precioAproximado)) #elements.append(Paragraph(c.drawString(80, 55, "Precio aproximado: " + to_str(master.precioAproximado)) ,parrafoStyle)) c.line(80, 30, 220, 30) c.line(270, 30, 350, 30) c.line(410, 30, 500, 30) c.setFont("Times-Roman", 8) c.drawString(85, 15, "Vo.Bo. Gte. Administrativo") c.drawString(280, 15, "Jefe de Est.") c.drawString(415, 15, "Gerente de Área") c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def render_data(request, data, status=200): """Render data as xml or json based on the request.""" if request.api: default = __default_list_dumps if isinstance(data, (tuple, list, set, QuerySet)) else __default_dumps if not request.api_json: response = HttpResponse(content_type='application/xml', status=status) xml.dumps(data, response, default=default) elif request.api_json is not True: response = HttpResponse(content_type='text/javascript', status=status) if request.api_callback: response.write(request.api_json + '(') response.write(json.dumps(data, default=default)) response.write(');') else: response.write(request.api_json + ' = ') response.write(json.dumps(data, default=default)) response.write(';') else: response = HttpResponse(json.dumps(data, default=default), content_type='application/json', status=status) apply_response_headers(request, response) return response else: raise Http404
def octoprint_http_tunnel(request, printer_id): get_printer_or_404(printer_id, request) prefix = f'/octoprint/{printer_id}' # FIXME method = request.method.lower() path = request.get_full_path()[len(prefix):] IGNORE_HEADERS = [ 'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_REFERER', 'HTTP_COOKIE', ] # Recreate http headers, because django put headers in request.META as "HTTP_XXX_XXX". Is there a better way? req_headers = { k[5:].replace("_", " ").title().replace(" ", "-"): v for (k, v) in request.META.items() if k.startswith("HTTP") and not k.startswith('HTTP_X_') and k not in IGNORE_HEADERS } if 'CONTENT_TYPE' in request.META: req_headers['Content-Type'] = request.META['CONTENT_TYPE'] ref = f'{printer_id}.{method}.{time.time()}.{path}' channels.send_msg_to_printer( printer_id, { "http.tunnel": { "ref": ref, "method": method, "headers": req_headers, "path": path, "data": request.body }, 'as_binary': True, }) redis.octoprinttunnel_update_sent_stats( now(), request.user.id, printer_id, 'http', len(request.body) ) data = redis.octoprinttunnel_http_response_get(ref) if data is None: return HttpResponse('Timed out. Either your OctoPrint is offline, or The Spaghetti Detective plugin version is lower than 1.4.0.') content_type = data['response']['headers'].get('Content-Type') or None resp = HttpResponse( status=data["response"]["status"], content_type=content_type, ) for k, v in data['response']['headers'].items(): if k in ['Content-Length', 'Content-Encoding']: continue resp[k] = v url_path = urllib.parse.urlparse(path).path content = data['response']['content'] redis.octoprinttunnel_update_received_stats( now(), request.user.id, printer_id, 'http', len(content) ) if content_type and content_type.startswith('text/html'): content = rewrite_html(prefix, ensure_bytes(content)) elif url_path.endswith('socket.js'): content = re.sub(_R_SOCKJS_TRANSPORTS, _rewrite_sockjs_transports, ensure_bytes(content)) elif url_path.endswith('packed_client.js'): content = re.sub(_R_SOCKJS_TRANSPORTS, _rewrite_sockjs_transports, ensure_bytes(content)) elif url_path.endswith('packed_libs.js'): content = re.sub(_R_WS_CONNECT_PATH, _rewrite_ws_connect_path, ensure_bytes(content)) elif url_path.endswith('sockjs.js'): content = re.sub(_R_WS_CONNECT_PATH, _rewrite_ws_connect_path, ensure_bytes(content)) elif url_path.endswith('sockjs.min.js'): content = re.sub(_R_WS_CONNECT_PATH, _rewrite_ws_connect_path, ensure_bytes(content)) resp.write(content) return resp
def recepcion_report(request, id): master = Recepcion.objects.get(id=id) detail = master.recepciondetalle_set.all() response = HttpResponse(content_type='application/pdf') cant_elementos = len(detail) #pdf_name = "nota_recepcion.pdf" #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name elements = [] buffer = BytesIO() #doc = getDoc(buff,'nota de pedido') c = canvas.Canvas(buffer, pagesize=A4) width, height = A4 #Header c.setTitle("Nota Recepcion") c.setLineWidth(.3) c.setFont("Times-Bold", 12) c.drawString(200, 790, 'NOTA DE RECEPCIÓN') c.drawString(250, 770, 'Nº') nro = c.drawString(270, 770, str(master.nroRecepcion)) c.drawString(400, 790, master.fecha.strftime('%d-%m-%Y')) print(settings.STATIC_ROOT) archivo_imagen = settings.STATIC_ROOT + '/app/images/logo.png' c.drawImage(archivo_imagen, 80, 760, width=70, height=45) #Table Header styles = getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 8 parrafoStyle = ParagraphStyle('parrafos', alignment=TA_JUSTIFY, fontSize=12, fontName="Times-Roman") headings = ('Cantidad', 'Unidad de Medida', 'Descripción') results = [(d.cantidad, d.unidadMedida, d.articulo.descripcion) for d in detail] c.setFont("Times-Bold", 12) c.drawString(80, 740, "Para: ") c.drawString(80, 720, "De: ") c.setFont("Times-Roman", 12) c.drawString(110, 740, str(master.departamentoDestino)) c.drawString(110, 720, str(master.departamentoOrigen)) elements.append(headings) elements.append(results) #Detalle Tabla table = Table([headings] + results, colWidths=[1.35 * inch, 1.35 * inch, 3.5 * inch], rowHeights=0.2 * inch, splitByRow=10) table.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ('GRID', (0, 0), (4, -3), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.transparent), ('ALIGN', (4, 0), (-1, -1), 'CENTER'), ])) elements.append(table) table.wrapOn(c, width, height) table.drawOn(c, 29 * mm, (243 * mm) - (cant_elementos * mm * 5.2)) c.setFont("Times-Roman", 8) c.line(80, 450, 210, 450) c.drawString(85, 440, str(master.departamentoOrigen)) #Header2 #c.setLineWidth(.3) c.setFont("Times-Bold", 12) c.drawString(200, 390, 'NOTA DE RECEPCIÓN') c.drawString(250, 375, 'Nº') nro = c.drawString(270, 375, str(master.nroRecepcion)) c.drawString(400, 390, master.fecha.strftime('%d-%m-%Y')) c.drawImage(archivo_imagen, 80, 370, width=70, height=45) c.drawString(80, 350, "Para: ") c.drawString(80, 330, "De: ") c.setFont("Times-Roman", 12) c.drawString(110, 350, str(master.departamentoDestino)) c.drawString(110, 330, str(master.departamentoOrigen)) #Detalle Tabla 2 table = Table([headings] + results, colWidths=[1.35 * inch, 1.35 * inch, 3.5 * inch], rowHeights=0.2 * inch, splitByRow=10) table.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ('GRID', (0, 0), (4, -3), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.transparent), ('ALIGN', (4, 0), (-1, -1), 'CENTER'), ])) elements.append(table) table.wrapOn(c, width, height) table.drawOn(c, 29 * mm, (104 * mm) - (cant_elementos * mm * 5.2)) c.line(80, 45, 210, 45) c.setFont("Times-Roman", 8) c.drawString(85, 30, str(master.departamentoOrigen)) c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response