当前位置: 首页>>代码示例>>Python>>正文


Python renderer.Renderer类代码示例

本文整理汇总了Python中appy.pod.renderer.Renderer的典型用法代码示例。如果您正苦于以下问题:Python Renderer类的具体用法?Python Renderer怎么用?Python Renderer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Renderer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _generate_facture

def _generate_facture(g, ncf, with_logo=True):
    cursor = g.db.cursor()
    commande = pg.select1r(cursor, 'commande', where={'no_commande_facture':ncf})
    client = pg.select1r(cursor, 'client', where={'no_client': commande['no_client']})
    doc_values = {'elems': []}
    doc_values.update(commande)
    doc_values.update(client)
    doc_values['representant_nom'] = pg.select1(cursor, 'representant', 'representant_nom',
                                                where={'representant_id': client['representant_id']})
    rows = pg.select(cursor, {'produit':'p', 'commande_item':'ci', 'producteur':'r', 'inventaire':'i'},
                     join={'p.no_produit_interne':'ci.no_produit_interne', 'p.no_producteur':'r.no_producteur',
                           'ci.no_produit_saq':'i.no_produit_saq'}, where={'ci.no_commande_facture': ncf,
                                                                           'statut_item': 'OK'},
                     order_by='type_vin')
    for row in rows:
        doc_values['elems'].append([row['quantite_bouteille'], row['type_vin'], row['nom_domaine'], row['millesime'],
                                    row['no_produit_saq'], row['format'], as_currency(row['montant_commission']),
                                    as_currency(row['montant_commission'] * row['quantite_bouteille'])])
    for f in ['sous_total', 'tps', 'tvq', 'montant']:
        doc_values[f] = as_currency(doc_values[f])
    out_fn = '/tmp/vinum_facture_%s.%s' % (ncf, 'odt' if hasattr(app, 'is_dev') else 'pdf')
    tmpl_fn = 'facture.odt' if with_logo else 'facture_sans_logo.odt'
    ren = Renderer('/home/christian/vinum/docs/%s' % tmpl_fn, doc_values,
                   out_fn, overwriteExisting=True)
    ren.run()
    return out_fn
开发者ID:cjauvin,项目名称:vinum,代码行数:26,代码来源:commande.py

示例2: download_invitationletter

    def download_invitationletter(self):
        if not self.get_review_state() in ('accepted', 'confirmed'):
            return "Error: paper not accepted?"
        
        from appy.pod.renderer import Renderer
        values = {
            'title':  self.title.strip(),
            'name':   ','.join(self.Creators())
        }

        pdfoutput = os.path.join(self._tempd, "TODOx.pdf")
        templatename = os.path.join("/tmp", "Letter.odt")
        renderer = Renderer(templatename, values, pdfoutput, pythonWithUnoPath='/usr/bin/python3') 
        renderer.run()


        pdffile = open(pdfoutput, "rb")

        output = StringIO()
        output.write(pdffile.read())

        ### TODO del file
        pdffile.close()
        
        output.seek(0)
        return output
开发者ID:jgrigera,项目名称:Journal-Commons,代码行数:26,代码来源:conferencepaper.py

示例3: test_01

    def test_01(self):

        if V(version.short) < V('0.9.0'):
            # "not supported with appy version %s" % version.short)
            return

        tpl = join(MYDIR, 'appy', 'template.odt')
        context = dict()
        context.update(
            appy_version=version.verbose,
            python_version=sys.version,
            platform=sys.platform,
        )
        target = join(tempfile.gettempdir(), 'result.odt')
        if exists(target):
            os.remove(target)
        renderer = Renderer(tpl, context, target, **PARAMS)
        try:
            renderer.run()
            self.fail("appy renderer failed to raise an error.")
        except Exception as e:
            s = str(e)
            if not s.startswith('Error while evaluating expression "foo".'):
                self.fail("Incorrect appy error message.")
            if not s.endswith("name 'foo' is not defined"):
                self.fail("Incorrect appy error message.")
开发者ID:zhuangyan,项目名称:lino,代码行数:26,代码来源:test_appy_pod.py

示例4: __call__

 def __call__(self):
     self.request.response.setHeader('Content-type', 'application/pdf')
     self.request.response.setHeader('Content-disposition', 'inline;filename="'
                         + removeSecurityProxy(self.report.report_type) + "_"
                         + removeSecurityProxy(self.report.start_date).strftime('%Y-%m-%d') + '.pdf"')
     
     
     session = Session()
     report = session.query(domain.Report).get(self.report.report_id)
     d = dict([(f.file_title, f.file_data) for f in report.attached_files])
     if "pdf" not in d.keys():
         params = {}
         params['body_text'] = self.cleanupText()
         openofficepath = getUtility(IOpenOfficeConfig).getPath()
         renderer = Renderer(self.odt_file, params, self.tempFileName, pythonWithUnoPath=openofficepath)
         renderer.run()
         f = open(self.tempFileName, 'rb')
         doc = f.read()
         f.close()
         os.remove(self.tempFileName)
         attached_file = domain.AttachedFile()
         attached_file.file_title = "pdf"
         attached_file.file_data = doc
         attached_file.language = report.language
         report.attached_files.append(attached_file)
         notify(ObjectCreatedEvent(attached_file))
         session.add(report)
         session.commit()
         return doc
     else:
         return d["pdf"].__str__()
开发者ID:BenoitTalbot,项目名称:bungeni-portal,代码行数:31,代码来源:reports.py

示例5: __init__

 def __init__(self, ar, template, context, result, **kw):
     self.ar = copy(ar)
     # self.ar.renderer = settings.SITE.kernel.html_renderer
     # self.ar.renderer = settings.SITE.plugins.bootstrap3.renderer
     self.ar.renderer = settings.SITE.plugins.jinja.renderer
     #~ context.update(appy_renderer=self)
     context.update(restify=self.restify_func)
     context.update(html=self.insert_html)
     context.update(jinja=self.insert_jinja)
     context.update(table=self.insert_table)
     context.update(story=self.insert_story)
     context.update(as_odt=self.as_odt)
     #~ context.update(html2odf=html2odf)
     context.update(ehtml=html2odf)
     context.update(toxml=toxml)
     #~ from lino.extjs import ui
     #~ self.extjs_ui = ui
     context.update(ui=settings.SITE.kernel)
     context.update(settings=settings)
     context.update(sc=settings.SITE.site_config)
     if False:
         context.update(settings.SITE.models)
         # 20150810 removed above line because this "feature"
         # caused the name `jinja` defined above to be overridden.
     kw.update(finalizeFunction=self.finalize_func)
     OriginalAppyRenderer.__init__(self, template, context, result, **kw)
     #~ self.my_automaticstyles = odf.style.automaticstyles()
     #~ self.my_styles = odf.style.styles()
     self.my_automaticstyles = []
     self.my_styles = []
开发者ID:lino-framework,项目名称:xl,代码行数:30,代码来源:appy_renderer.py

示例6: presupuesto_impresion_odt_full

def presupuesto_impresion_odt_full(request, idpresupuesto):
	#ruta de la plantilla
    plantilla_odt_path = os.path.join(labutiles.PLANTILLA_ODT_PATH,'presupuesto_impresion_odt_full.odt')
	#Necesito un nombre aleatorio en la carpeta de temporales
    file_odt_resultado = tempfile.NamedTemporaryFile(delete=True,prefix='lab_', suffix='.odt') 

    odt_resultado_path = file_odt_resultado.name #path al archivo de resultado
    file_odt_resultado.close() #Se debería eliminar el archivo	

    #print 'origen>>' + str(plantilla_odt_path)
    #print 'destino>>'+ str(file_odt_resultado)	
	
    dummy = presupuesto_impresion_odt.impresion(idpresupuesto)
	
    contexto = {"dummy":dummy}
    renderer = Renderer(plantilla_odt_path, contexto, odt_resultado_path)

    #estilos = renderer.getStyles() #Para consultar los estilos en la plantilla del documento
    #print estilos
    renderer.run()    	
    archivo_resultado = File(open(odt_resultado_path))
    wrapper = FileWrapper(archivo_resultado) 
    
    response = HttpResponse(wrapper, content_type='text/html')
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(odt_resultado_path)
    response['Content-Length'] = os.path.getsize(odt_resultado_path)
    return response
开发者ID:Camiiiiii,项目名称:LabWeb,代码行数:27,代码来源:viewpresupuestoimpresion_odt_full.py

示例7: resumido

    def resumido(self, data0, data1, subtotal0,tax0,total0, fechai0,fechaf0):
        global data, subtotal,tax,total, fechai,fechaf
        data = data0
        dataD = data1
        subtotal = subtotal0
        tax = tax0
        total = total0
        fechai = fechai0
        fechaf = fechaf0      
        date = time.localtime()[:6]
        for i in data:
            totales[0] = totales[0]+i[5]
            totales[1] = totales[1]+i[2]

            totales[2] = totales[2]+(i[2]-i[5])
            totales[3] = totales[3]+(i[3]*i[5])
            totales[4] = totales[4]+(i[3]*(i[2]-i[5]))
            totales[5] = totales[5]+(i[3]*i[2])
        f_name = "Ventas_%d-%d-%d-%d-%d-%d.ods" % date
        renderer = Renderer(self.ResourcePath('reports/templates/ventas.ods'), globals(), self.ResourcePath('reports/sales/'+f_name))
        renderer.run()
        path = self.ResourcePath('reports/sales/'+f_name)
        if sys.platform.startswith("linux"):
            os.system("libreoffice "+path)
        else:
            import subprocess
            p = subprocess.Popen(path, shell=True, bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
开发者ID:SpiraX13,项目名称:MiniPOS,代码行数:27,代码来源:sales_report.py

示例8: createReport

def createReport(
    self,
    inf_basicas_dic,
    num_proposicao,
    nom_arquivo,
    des_tipo_materia,
    num_ident_basica,
    ano_ident_basica,
    txt_ementa,
    materia_vinculada,
    dat_apresentacao,
    nom_autor,
    apelido_autor,
    modelo_proposicao,
):
    # Criacao ODT
    url = self.sapl_documentos.modelo.materia.absolute_url() + "/%s" % modelo_proposicao
    template_file = cStringIO.StringIO(urllib.urlopen(url).read())
    output_file_odt = "%s" % nom_arquivo
    renderer = Renderer(template_file, locals(), output_file_odt, pythonWithUnoPath="/usr/bin/python", forceOoCall=True)
    renderer.run()
    data = open(output_file_odt, "rb").read()
    for file in [output_file_odt]:
        os.unlink(file)
        self.sapl_documentos.materia_odt.manage_addFile(id=nom_arquivo, file=data)
开发者ID:dgoortega,项目名称:openlegis,代码行数:25,代码来源:materia_gerar_odt.py

示例9: pod_save

def pod_save(filename, ext, data, template, get_tmp_file=False):
    import time

    # strip comma's from filename
    filename = filename.replace(",", "")

    file_name = tempfile.gettempdir() + "/appy" + str(time.time()) + ext
    renderer = Renderer(template, data, file_name)
    renderer.run()

    if ext == ".doc":
        content = "application/msword"
    elif ext == ".docx":
        content = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    elif ext == ".pdf":
        content = "application/pdf"
    elif ext == ".rtf":
        content = "application/rtf"
    else:  # odt, prefered
        content = "application/vnd.oasis.opendocument.text"

    if get_tmp_file:
        return file_name

    wrapper = FileWrapper(file(file_name))  # notice not using the tmp file! Not ideal.
    response = HttpResponse(wrapper, content_type=content)
    response["Content-Length"] = os.path.getsize(file_name)
    response["Content-Disposition"] = "attachment; filename=" + filename + ext
    try:
        os.remove(file_name)
    except:
        pass  # this sucks. But Ubuntu can't run ooo as www-data

    return response
开发者ID:sicikle,项目名称:django-sis,代码行数:34,代码来源:report.py

示例10: __call__

 def __call__(self):
     self.request.response.setHeader("Content-type",
                                     "application/vnd.oasis.opendocument.text")
     self.request.response.setHeader("Content-disposition",
                                     'inline;filename="' +
                                     removeSecurityProxy(self.report.report_type) + "_" +
                                     removeSecurityProxy(self.report.start_date).strftime("%Y-%m-%d") + '.odt"')
     session = Session()
     report = session.query(domain.Report).get(self.report.report_id)
     d = dict([(f.file_title, f.file_data) for f in report.attached_files])
     if "odt" not in d.keys():
         params = {}
         params["body_text"] = self.cleanupText()
         renderer = Renderer(self.odt_file, params, self.tempFileName)
         renderer.run()
         f = open(self.tempFileName, "rb")
         doc = f.read()
         f.close()
         os.remove(self.tempFileName)
         attached_file = domain.AttachedFile()
         attached_file.file_title = "odt"
         attached_file.file_data = doc
         attached_file.language = report.language
         report.attached_files.append(attached_file)
         notify(ObjectCreatedEvent(attached_file))
         session.add(report)
         session.commit()
         return doc
     else:
         return d["odt"].__str__()
开发者ID:kohsah,项目名称:bungeni-portal,代码行数:30,代码来源:reports.py

示例11: generate_price

 def generate_price(self, folder):
     res_path=path.join(folder, self.get_price_name())
     context=self.get_template_context()
     if platform.system() == 'Linux':
         template=settings.PROJECT_PATH+self.template_file.url
         file_name=ntpath.basename(template)
         file_path=os.path.dirname(os.path.abspath(template))
         styles = ''
         fonts = ''
         images = []
         chunks_dict = {}
         for whole_chunk in Chunk.objects.all():
             res_chanks=whole_chunk.langchunk_set.filter(language=self.language, site=self.site)
             if len(res_chanks) == 0:
                 res_chanks=whole_chunk.langchunk_set.filter(language='default', site=self.site)
             if len(res_chanks) !=0:
                 chunk = res_chanks[0]
                 styles += self.replace_style_names(chunk.styles, whole_chunk.slug)
                 fonts += chunk.fonts
                 if chunk.image:
                     images.append(url_to_path(chunk.image.url))
                 chunk_with_no_blank = chunk.content.replace('    ','').replace('\n','').replace('\r','')
                 chunks_dict[whole_chunk.slug] = self.replace_style_names(chunk_with_no_blank, whole_chunk.slug)
         res_templ, path_to_temp =  self.add_info_to_odt(file_name, file_path, chunks_dict, styles, fonts, images)
         renderer = Renderer(res_templ, context, res_path,  overwriteExisting=True, pythonWithUnoPath="/usr/bin/python3")
         
         renderer.run()
         shutil.rmtree(path_to_temp, ignore_errors=False)
         pages=Page.objects.filter(reverse_id=self.price.price_page, published=True)
         for page in pages:
             page.last_publish_date=datetime.now()
             page._publisher_keep_state = True
             page.save()
开发者ID:124bit,项目名称:django_ukrhim,代码行数:33,代码来源:models.py

示例12: render_template

def render_template():
    # we are expecting a json payload
    payload = request.get_json()
    if not payload:
        abort(400, "No JSON content found")

    try:
        context = payload["context"]
    except KeyError:
        abort(400, "No context, no document!")

    suffix = payload.get("format", "pdf")

    template = _fetch_template(**payload['template'])

    fd, target = tempfile.mkstemp(suffix=".{}".format(suffix))
    os.close(fd)
    os.remove(target)

    try:
        # FIXME: we are not cleaning up our target documents, are we?
        r = Renderer(template, context, target,
                     pythonWithUnoPath=UNOPYTHON,
                     forceOoCall=True,
                     overwriteExisting=True)
        r.run()

        return send_file(target, as_attachment=True)
    finally:
        try:
            os.remove(target)
        except:
            pass
开发者ID:Hackership,项目名称:odt2pdf-docker,代码行数:33,代码来源:app.py

示例13: __init__

 def __init__(self, ar, template, context, result, **kw):
     self.ar = ar
     #~ context.update(appy_renderer=self)
     context.update(restify=self.restify_func)
     context.update(html=self.html_func)
     context.update(jinja=self.jinja_func)
     context.update(table=self.insert_table)
     context.update(as_odt=self.as_odt)
     #~ context.update(story=self.insert_story)
     #~ context.update(html2odf=html2odf)
     context.update(ehtml=html2odf)
     context.update(toxml=toxml)
     #~ from lino.extjs import ui
     #~ self.extjs_ui = ui
     #~ self.extjs_ui = settings.SITE.ui
     #~ context.update(ui=self.extjs_ui)
     context.update(ui=settings.SITE.ui)
     context.update(settings=settings)
     context.update(sc=settings.SITE.site_config)
     context.update(settings.SITE.modules)
     kw.update(finalizeFunction=self.finalize_func)
     AppyRenderer.__init__(self,template,context,result, **kw)
     #~ self.my_automaticstyles = odf.style.automaticstyles()
     #~ self.my_styles = odf.style.styles()
     self.my_automaticstyles = []
     self.my_styles = []
开发者ID:MaxTyutyunnikov,项目名称:lino,代码行数:26,代码来源:appy_pod.py

示例14: post

    def post(self, request, **kwargs):
        download_type = request.GET.get('type')
        context = self.get_context_data(**kwargs)
        if request.POST.get('data', None):
            data = simplejson.loads(request.POST['data'])
            self.report.handle_post_data(data)
            context['object_list'] = self.report.report_to_list(
                user=self.request.user, preview=True)
            context['headers'] = self.report.get_preview_fields()

        if download_type == "preview":
            preview_html = render_to_string(self.template_name, context)
            response_data = {}
            response_data['preview_html'] = preview_html
            response_data['filter_errors'] = self.report.filter_errors
            return HttpResponse(json.dumps(response_data), content_type="application/json")

        elif download_type == "xlsx":
            data = self.report.report_to_list(self.request.user)
            return self.list_to_xlsx_response(data)
        elif download_type == 'django_admin':
            ids = self.report.get_queryset().values_list('id', flat=True)
            ids = ",".join(str(x) for x in ids)
            response = redirect('admin:{}_{}_changelist'.format(
                self.model._meta.app_label, self.model._meta.model_name))
            response['Location'] += '?id__in={}'.format(ids)
            return response
        elif download_type == "appy":
            filename = 'report'
            ext = '.odt'
            appy_context = self.report.get_appy_context()
            template_name = self.report.get_appy_template()
            from appy.pod.renderer import Renderer
            outfile_name = tempfile.gettempdir() + '/appy' + str(time.time()) + ext
            renderer = Renderer(template_name, appy_context, outfile_name)
            renderer.run()
            
            if ext == ".doc":
                content = "application/msword"
            elif ext == ".docx":
                content = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            elif ext == ".pdf":
                content = "application/pdf"
            elif ext == ".rtf":
                content = "application/rtf"
            elif ext == '.ods':
                content = "application/vnd.oasis.opendocument.spreadsheet"
            else: # odt
                content = "application/vnd.oasis.opendocument.text"
            
            wrapper = FileWrapper(file(outfile_name))
            response = HttpResponse(wrapper, content_type=content)
            response['Content-Length'] = os.path.getsize(outfile_name)
            response['Content-Disposition'] = 'attachment; filename=' + filename + ext
            try: os.remove(file_name)
            except: pass # At least it's in the tmp folder
            return response
开发者ID:paulorfarah,项目名称:django-report-scaffold,代码行数:57,代码来源:views.py

示例15: renderOdt

def renderOdt(dictionary, tempfilename='tempcv', template=DEFAULT_TEMPLATE):

    # filename = dictionary['p'].name.encode('ascii', 'ignore') + ' - ' + dictionary['c'].title.encode('ascii', 'ignore').replace(",","").replace('/','') + ".odt"

    rsltFile = '/var/tmp/%s.odt' % tempfilename
    r = Renderer(template, dictionary, rsltFile, overwriteExisting=True)
    r.run()

    return rsltFile
开发者ID:altran,项目名称:Awesome-Competence-System,代码行数:9,代码来源:cvdownload.py


注:本文中的appy.pod.renderer.Renderer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。