[Stoq-devel] Movendo c?digo de reporting/__init__ para
reporting/utils
Henrique Romano
henrique at async.com.br
Mon Feb 6 21:19:09 BRST 2006
Ol?,
O patch que segue em anexo tem como objetivo mover o c?digo que
atualmente se encontra no constructor do pacote Stoqlib Reporting
para o m?dulo utils, seguindo assim o padr?o utilizado no projeto
Stoq. Callsites tamb?m foram atualizados.
--
Henrique Romano
<henrique at async.com.br>
Index: stoqlib/gui/slaves.py
===================================================================
--- stoqlib/gui/slaves.py (revisão 2361)
+++ stoqlib/gui/slaves.py (cópia de trabalho)
@@ -33,7 +33,7 @@
from kiwi.python import Settable
from stoqlib.gui.editors import BaseEditorSlave
-from stoqlib.reporting import print_preview, build_report
+from stoqlib.reporting.utils import print_preview, build_report
_ = lambda msg: gettext.dgettext('stoqlib', msg)
Index: stoqlib/gui/dialogs.py
===================================================================
--- stoqlib/gui/dialogs.py (revisão 2361)
+++ stoqlib/gui/dialogs.py (cópia de trabalho)
@@ -38,7 +38,7 @@
from stoqlib.exceptions import ModelDataError
from stoqlib.gui.gtkadds import change_button_appearance
-from stoqlib.reporting import print_file
+from stoqlib.reporting.utils import print_file
from stoqlib.reporting.template import BaseDocTemplate
_ = lambda msg: gettext.dgettext('stoqlib', msg)
Index: stoqlib/reporting/__init__.py
===================================================================
--- stoqlib/reporting/__init__.py (revisão 2361)
+++ stoqlib/reporting/__init__.py (cópia de trabalho)
@@ -1,117 +0,0 @@
-# -*- Mode: Python; coding: iso-8859-1 -*-
-# vi:si:et:sw=4:sts=4:ts=4
-#
-# Copyright (C) 2005 Async Open Source
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-
-""" Stoqlib Reporting ? um pacote criado para facilitar a constru??o de
-relat?rios com o ReportLab. O maior destaque do pacote est? em suas rotinas
-para gera??o de tabelas, que fornecem suporte para cria??o do mais simples
-tipo de tabela, onde dispomos informa??es alinhadas, at? tabelas objeto, que
-permitem a cria??o de relat?rios tendo somente uma lista de inst?ncias (que
-pode ser obtida atrav?s de, por exemplo, uma pesquisa em uma base de dados).
-
-"""
-
-import os
-import tempfile
-
-__name__ = "Stoqlib Reporting"
-__version__ = "0.1"
-__author__ = "Async Open Source"
-__email__ = "async at async.com.br"
-__license__ = "GNU LGPL 2.1"
-
-# Editores padr?es ? serem utilizados para visualiza??o de documentos
-PROGRAMS = ['xpdf', 'ggv']
-
-def build_report(report_class, *args):
- """ Fun??o respons?vel pela constru??o do relat?rio.
- Par?metros:
-
- - report_class: a classe utilizada para a constru??o do relat?rio,
- isto ?, a classe criada pelo usu?rio (uma subclasse de
- ReportTemplate) que define os elementos ? serem inseridos no
- relat?rio e como eles podem ser constru?dos.
- - args: argumentos extras que podem ser passados ? classe
- especificada no par?metro report_class.
- """
- filename = tempfile.mktemp()
- report = report_class(filename, *args)
- report.save()
- return filename
-
-def print_file(filename, printer=None, extra_opts=[]):
- """ Fun??o utilizada para impress?o de arquivos. Geralmente utilizada para
- impress?o do arquivo criado por uma chamada pr?via ? fun??o build_report.
- Par?metros:
-
- - filename: o nome do arquivo a ser impresso.
- - printer: nome da impressora ? ser utilizada; se n?o especificado, a
- impressora padr?o ser? utilizada.
- - extra_opts: par?metros *opcionais* que precisam ser passados ao
- comando de impress?o do documento.
- """
- if not os.path.exists(filename):
- raise ValueError, "File %s not found" % filename
- options = " ".join(extra_opts)
- if printer:
- options += " -P%s" % printer
- ret = os.system("lpr %s %s" % (options, filename))
- os.remove(filename)
- return ret
-
-def print_preview(filename, keep_file=0):
- """ Fun??o utilizada para visualiza??o de arquivos pdf e ps, geralmente
- criados por build_report. Alguns editores (e suas devidas op??es) est?o
- definidos na vari?vel PROGRAMS; o primeiro editor encontrado no sistema
- ser? utilizado. Parametros:
-
- - filename: o nome do arquivo ? visualizar.
- - keep_file: TRUE, caso o arquivo deva ser salvo no disco ap?s sua
- visualiza??o.
- """
- if not os.path.exists(filename):
- raise OSError, "the file does not exist"
-
- path = os.environ['PATH'].split(':')
-
- for program in PROGRAMS:
- args = []
- if isinstance(program, tuple):
- # grab args and program from tuple
- args.extend(program[1:])
- program = program[0]
- elif not isinstance(program, str):
- raise AssertionError
- args.append(filename)
- for part in path:
- full = os.path.join(part, program)
- if not os.access(full, os.R_OK|os.X_OK):
- continue
- if not os.fork():
- args = " ".join(args)
- os.system("%s %s" % (full, args))
- if not keep_file:
- os.remove(filename)
- # See http://www.gtk.org/faq/#AEN505 -- _exit()
- # keeps file descriptors open, which avoids X async
- # errors after we close the child window.
- os._exit(-1)
- return
- print "Could not find a pdf viewer, aborting"
-
Index: stoqlib/reporting/utils.py
===================================================================
--- stoqlib/reporting/utils.py (revisão 0)
+++ stoqlib/reporting/utils.py (revisão 0)
@@ -0,0 +1,103 @@
+# -*- Mode: Python; coding: iso-8859-1 -*-
+# vi:si:et:sw=4:sts=4:ts=4
+#
+# Copyright (C) 2005 Async Open Source
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+""" Useful functions related to reports building and visualization. """
+
+import os
+import tempfile
+
+# a list of programs to be tried when a report needs be viewed
+PROGRAMS = ['xpdf', 'ggv']
+
+def build_report(report_class, *args):
+ """ Given a class (BaseReportTemplate instance), build a report. It is
+ important to note that this function create a temporary file where the
+ report will be drawed to -- the name of the temporary file is returned.
+
+ @param report_class: The report class to be build.
+ @type: A BaseReportTemplate instance
+
+ If specified, extra parameters will be send to the report class
+ constructor.
+ """
+ filename = tempfile.mktemp()
+ report = report_class(filename, *args)
+ report.save()
+ return filename
+
+def print_file(filename, printer=None, extra_opts=[]):
+ """ Given a filename try to print it. If no printer is specified, print
+ the file on the default one.
+
+ @param filename: The filename to print.
+ @type: str
+
+ @param printer: The printer name where to print.
+ @type: str
+
+ @param extra_opts: Extra options to be passed to the printing command.
+ @type: list of strings
+ """
+ if not os.path.exists(filename):
+ raise ValueError, "File %s not found" % filename
+ options = " ".join(extra_opts)
+ if printer:
+ options += " -P%s" % printer
+ ret = os.system("lpr %s %s" % (options, filename))
+ os.remove(filename)
+ return ret
+
+def print_preview(filename, keep_file=False):
+ """ Try preview the filename using one of the PDF viewers registred in
+ the package.
+
+ @param keep_file: If the file don't must be deleted after the program
+ finish.
+ @type: bool
+ """
+ if not os.path.exists(filename):
+ raise OSError, "the file does not exist"
+
+ path = os.environ['PATH'].split(':')
+
+ for program in PROGRAMS:
+ args = []
+ if isinstance(program, tuple):
+ # grab args and program from tuple
+ args.extend(program[1:])
+ program = program[0]
+ elif not isinstance(program, str):
+ raise AssertionError
+ args.append(filename)
+ for part in path:
+ full = os.path.join(part, program)
+ if not os.access(full, os.R_OK|os.X_OK):
+ continue
+ if not os.fork():
+ args = " ".join(args)
+ os.system("%s %s" % (full, args))
+ if not keep_file:
+ os.remove(filename)
+ # See http://www.gtk.org/faq/#AEN505 -- _exit()
+ # keeps file descriptors open, which avoids X async
+ # errors after we close the child window.
+ os._exit(-1)
+ return
+ print "Could not find a pdf viewer, aborting"
+
Index: examples/reporting/contract_example.py
===================================================================
--- examples/reporting/contract_example.py (revisão 2361)
+++ examples/reporting/contract_example.py (cópia de trabalho)
@@ -5,7 +5,7 @@
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_JUSTIFY
-from stoqlib.reporting import build_report, print_preview
+from stoqlib.reporting.utils import build_report, print_preview
from stoqlib.reporting.printing import ReportTemplate
from stoqlib.reporting.default_style import STYLE_SHEET
Index: examples/reporting/vehicles_production.py
===================================================================
--- examples/reporting/vehicles_production.py (revisão 2361)
+++ examples/reporting/vehicles_production.py (cópia de trabalho)
@@ -3,7 +3,7 @@
from sys import path
path.insert(0, "..")
-from stoqlib.reporting import build_report, print_preview
+from stoqlib.reporting.utils import build_report, print_preview
from stoqlib.reporting.printing import ReportTemplate
from stoqlib.reporting.common import read_file, safe_int
Index: examples/reporting/object_table_column.py
===================================================================
--- examples/reporting/object_table_column.py (revisão 2361)
+++ examples/reporting/object_table_column.py (cópia de trabalho)
@@ -2,7 +2,7 @@
from sys import path
path.insert(0, '..')
-from stoqlib.reporting import print_preview, build_report
+from stoqlib.reporting.utils import print_preview, build_report
from stoqlib.reporting.printing import ReportTemplate
from stoqlib.reporting.tables import (ObjectTableColumn as OTC,
Index: examples/reporting/clients_report.py
===================================================================
--- examples/reporting/clients_report.py (revisão 2361)
+++ examples/reporting/clients_report.py (cópia de trabalho)
@@ -2,7 +2,7 @@
from sys import path
path.insert(0, "..")
-from stoqlib.reporting import build_report, print_preview
+from stoqlib.reporting.utils import build_report, print_preview
from stoqlib.reporting.printing import ReportTemplate
from stoqlib.reporting.tables import TableColumn as TC
from stoqlib.reporting.common import read_file, safe_int
Index: examples/reporting/first_report.py
===================================================================
--- examples/reporting/first_report.py (revisão 2361)
+++ examples/reporting/first_report.py (cópia de trabalho)
@@ -3,7 +3,7 @@
from sys import path
path.insert(0, '..')
-from stoqlib.reporting import print_preview, build_report
+from stoqlib.reporting.utils import print_preview, build_report
from stoqlib.reporting.printing import ReportTemplate
# Classe utilizada como "container", simplesmente utilizada para
Index: examples/reporting/purchase_order.py
===================================================================
--- examples/reporting/purchase_order.py (revisão 2361)
+++ examples/reporting/purchase_order.py (cópia de trabalho)
@@ -5,7 +5,7 @@
import operator
-from stoqlib.reporting import build_report, print_preview
+from stoqlib.reporting.utils import build_report, print_preview
from stoqlib.reporting.printing import ReportTemplate
from stoqlib.reporting.flowables import RIGHT, CENTER
from stoqlib.reporting.tables import ObjectTableColumn as OTC
More information about the Stoq-devel
mailing list