1 | # coding=utf-8 |
---|
2 | """ |
---|
3 | Simulador Integral de Cadenas Productivas (SICP) |
---|
4 | |
---|
5 | Copyleft (@) 2015 CENDITEL nodo Mérida - https://miv.cenditel.gob.ve/simulacion/ |
---|
6 | """ |
---|
7 | ## @package apps.simulacion.encuesta.views |
---|
8 | # |
---|
9 | # Funciones a implementar en las vistas del módulo de la Encuesta Industrial |
---|
10 | # @author Ing. Erwin Paredes (eparedes at cenditel.gob.ve) |
---|
11 | # @author <a href='http://www.cenditel.gob.ve'>Centro Nacional de Desarrollo e Investigación en Tecnologías Libres |
---|
12 | # (CENDITEL) nodo Mérida - Venezuela</a> |
---|
13 | # @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
14 | # @date 21-08-2015 |
---|
15 | # @version 3.0.0 |
---|
16 | |
---|
17 | ## Muestra el autor del script cuando es invocado |
---|
18 | __author__ = "Ing. Erwin Paredes (eparedes at cenditel.gob.ve)" |
---|
19 | ## Muestra documentación breve sobre el script |
---|
20 | __doc__ = "Funciones a implementar en las vistas del módulo de la Encuesta Industrial" |
---|
21 | |
---|
22 | from django.conf import settings |
---|
23 | from django.contrib.auth.decorators import login_required |
---|
24 | from django.shortcuts import render_to_response |
---|
25 | from django.template import RequestContext |
---|
26 | from django.core.context_processors import csrf |
---|
27 | from django.contrib.messages.views import SuccessMessageMixin |
---|
28 | from django.views.generic import FormView |
---|
29 | from django.utils.encoding import smart_unicode, force_unicode |
---|
30 | from apps.comun.functions import render_cadena |
---|
31 | from django.http import HttpResponse |
---|
32 | from apps.simulacion.encuesta.models import Encuesta |
---|
33 | from datetime import date |
---|
34 | |
---|
35 | import os |
---|
36 | import logging |
---|
37 | import subprocess |
---|
38 | from PIL import Image |
---|
39 | |
---|
40 | def graficar(request): |
---|
41 | """! |
---|
42 | Función que ejecuta la instrucción necesaria para mostrar el correspondiente gráfico de la Encuesta Industrial |
---|
43 | asociada al escenario en estudio |
---|
44 | |
---|
45 | @author Ing. Erwin Paredes (eparedes at cenditel.gob.ve) |
---|
46 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
47 | @date 21-08-2015 |
---|
48 | @param request <b>{object}</b> Objeto que contiene la petición |
---|
49 | @return Devuelve el correspondiente response con los datos de la consulta correspondiente al gráfico de la encuesta industrial a mostrar |
---|
50 | """ |
---|
51 | rif = request.GET['rif'] |
---|
52 | ahora = request.GET.get('ahora') |
---|
53 | |
---|
54 | existe_encuesta = None |
---|
55 | |
---|
56 | try: |
---|
57 | |
---|
58 | existe_encuesta = Encuesta.objects.using('encuesta_2006').filter(rif=rif).count() |
---|
59 | salida = os.path.join(settings.BASE_DIR, "tmp/%s_%s.svg" % (str(request.user),ahora)) |
---|
60 | |
---|
61 | narriba = '4' |
---|
62 | nabajo = '4' |
---|
63 | os.system("cd " + os.path.join(settings.BASE_DIR, "tmp/")) |
---|
64 | os.system( os.path.join(settings.BASE_DIR, "apis/chains/print_prod_chain") + " --host=" + settings.DATABASES['encuesta_2006']['HOST'] + " --port=" + settings.DATABASES['encuesta_2006']['PORT'] + " --username=" + settings.DATABASES['encuesta_2006']['USER'] + " --password=" +settings.DATABASES['encuesta_2006']['PASSWORD'] + " --dbname=" + settings.DATABASES['encuesta_2006']['NAME'] + " --levelsup=" + narriba + " --levelsdown=" + nabajo + " --output=" + str(request.user) + "_" + ahora + " RIF " + rif) |
---|
65 | archivo = str(request.user) + "_" + ahora + ".svg " |
---|
66 | os.system("mv -f " + os.path.join(settings.BASE_DIR, archivo) + os.path.join(settings.BASE_DIR, "tmp/")+";"+"chmod -R 755 "+ os.path.join(settings.BASE_DIR, "tmp/")) |
---|
67 | |
---|
68 | cadena = render_cadena(str(request.user)) |
---|
69 | except Exception, e: |
---|
70 | print e |
---|
71 | |
---|
72 | return render_to_response("grafico.html",{"username":request.user, "existe_encuesta":existe_encuesta,"rif":rif,'ahora':ahora}, context_instance=RequestContext(request)) |
---|
73 | |
---|
74 | |
---|
75 | def image_as_png_pdf(request): |
---|
76 | """! |
---|
77 | Función que ejecuta la instrucción para convertir un archivo .svg a un formato .png y posteriormente ser mostrado en un archivo .pdf |
---|
78 | |
---|
79 | @author Ing. Erwin Paredes (eparedes at cenditel.gob.ve) |
---|
80 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
81 | @date 21-08-2015 |
---|
82 | @pre Se requiere tener instalado el comando rsvg-convert |
---|
83 | @param request <b>{object}</b> Objeto que contiene la petición |
---|
84 | @return Devuelve el correspondiente response con el archivo pdf a descargar |
---|
85 | """ |
---|
86 | output_format = request.GET.get('format') |
---|
87 | usuario = smart_unicode(request.GET["usuario"], encoding='utf-8', strings_only=False, errors='strict') |
---|
88 | |
---|
89 | comando = "cd %s;%s %s%s.svg %s %s%s.png" |
---|
90 | |
---|
91 | # Excepciones que permiten verificar si el comando que convierte archivos svg a png o pdf existe, |
---|
92 | # en caso contrario asigna el comando rsvg-convert |
---|
93 | # Agregado por: Ing. Roldan D. Vargas G. |
---|
94 | # fecha: 31/07/2014 |
---|
95 | try: |
---|
96 | command_exists = subprocess.check_output(["rsvg", "--help"], stderr=subprocess.STDOUT) |
---|
97 | convert = "rsvg" |
---|
98 | flag_output = "" |
---|
99 | except subprocess.CalledProcessError: |
---|
100 | convert = "rsvg-convert" |
---|
101 | flag_output = "-o" |
---|
102 | except OSError: |
---|
103 | convert = "rsvg-convert" |
---|
104 | flag_output = "-o" |
---|
105 | |
---|
106 | os.system(comando % ( |
---|
107 | os.path.join(settings.BASE_DIR, "tmp/"), convert, os.path.join(settings.BASE_DIR, "tmp/"), usuario, flag_output, |
---|
108 | os.path.join(settings.BASE_DIR, "tmp/"), usuario |
---|
109 | )) |
---|
110 | |
---|
111 | archivo = os.path.join(settings.BASE_DIR, "tmp/") + usuario + ".png" |
---|
112 | |
---|
113 | im = Image.open(archivo) # any Image object should work |
---|
114 | filename = str(request.user) |
---|
115 | if output_format == 'png': |
---|
116 | response = HttpResponse(content_type='image/png') |
---|
117 | response['Content-Disposition'] = 'attachment; filename=%s.png' % filename |
---|
118 | im.save(response, 'png') # will call response.write() |
---|
119 | else: |
---|
120 | # Temporary disk space, server process needs write access |
---|
121 | tmp_path = '/tmp/' |
---|
122 | # Full path to ImageMagick convert binary |
---|
123 | convert_bin = '/usr/bin/convert' |
---|
124 | im.save(tmp_path + filename + '.png', 'png') |
---|
125 | response = HttpResponse(content_type='application/pdf') |
---|
126 | response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename |
---|
127 | ret = subprocess.Popen([convert_bin, "%s%s.png" % (tmp_path, filename), "pdf:-"], stdout=subprocess.PIPE) |
---|
128 | response.write(ret.stdout.read()) |
---|
129 | return response |
---|
130 | |
---|