[Mpuls-commits] r869 - wasko/branches/2.0/waskaweb/lib
scm-commit@wald.intevation.org
scm-commit at wald.intevation.org
Tue Jan 26 12:00:52 CET 2010
Author: torsten
Date: 2010-01-26 12:00:52 +0100 (Tue, 26 Jan 2010)
New Revision: 869
Removed:
wasko/branches/2.0/waskaweb/lib/evaluation_new.py
Log:
* waskaweb/lib/evaluation_new.py: Deleted. Not imported anywhere.
Deleted: wasko/branches/2.0/waskaweb/lib/evaluation_new.py
===================================================================
--- wasko/branches/2.0/waskaweb/lib/evaluation_new.py 2010-01-26 10:36:11 UTC (rev 868)
+++ wasko/branches/2.0/waskaweb/lib/evaluation_new.py 2010-01-26 11:00:52 UTC (rev 869)
@@ -1,314 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# (c) 2008 by Intevation GmbH
-# This is Free software under the GPLv3.
-# See LICENSE comming with the source of 'mpuls'
-# for details.
-#
-# author: Torsten Irländer <torsten.irlaender at intevation.de>
-#
-
-import logging
-import pylons
-import os
-import tempfile
-import time
-import traceback
-
-from StringIO import StringIO
-from lxml import etree
-from waskaweb.lib.db import db
-#from waskaweb.lib.base import render
-#from mpuls.lib.config import MpulsConfig
-#from mpuls.lib.helpers import build_map
-from pylons.i18n import _
-from pylons import g,c
-#from pylons.templating import pylons_globals
-from mako.template import Template
-from mako.lookup import TemplateLookup
-
-
-#log = logging.getLogger(__name__)
-XML_HEADER = """<PROJEKT_TEILNEHMER><PRJ_DOK_NR>%s</PRJ_DOK_NR><AUSW_VON>%s</AUSW_VON><AUSW_BIS>%s</AUSW_BIS>"""
-XML_BODY = """<TEILNEHMER><PJTN_TTYP_ID>%s</PJTN_TTYP_ID><PJTN_MANN>%s</PJTN_MANN><PJTN_FRAU>%s</PJTN_FRAU><PJTN_GESAMT>%s</PJTN_GESAMT></TEILNEHMER>"""
-XML_FOOTER = """</PROJEKT_TEILNEHMER>"""
-
-SQL_TABLE = "master_tbl_view m"
-SQL_GENDER_FIELD = 'geschlecht'
-SQL_BASE_QUERY = """SELECT %s, count(m.id) FROM %s WHERE %s GROUP BY %s"""
-
-SQL_TOTAL = "TRUE"
-EVALUATION = {'1': SQL_TOTAL}
-
-DEFAULT_EVALUATIONS = ['1']
-
-EVAL_NAMES = {'1': 'Total'}
-EVAL_DESCRIPTIONS = {'1': 'Evaluates how many cases are totally stored in the database.'}
-
-def render_with_mako(eval, data):
- mako = ''
- f = None
-
- #path = os.path.join(pylons.config.get('pylons.paths').get('templates')[0], 'tmp')
- #f = tempfile.NamedTemporaryFile(suffix='.mako', prefix='eval_', dir=path)
- #f.write("\n".join(out))
- #pylons.c.eval = eval
- #mako = render(os.path.join('/tmp', os.path.split(f.name)[1]))
- #f.close(); f = None
-
- try:
- path = os.path.join(pylons.config.get('pylons.paths').get('templates')[0], 'tmp', 'eval_xyz.mako')
- #f = open(path, 'w')
- mylookup = TemplateLookup(os.path.join(pylons.config.get('pylons.paths').get('templates')))
- #glob = pylons_globals()
- glob = {'g': g, 'c': c, 'h': h}
- template = Template(u"\n".join(data), lookup=mylookup)
- #f.write("\n".join(data))
- #f.close(); f = None
- pylons.c.eval = eval
- #mako = render(os.path.join('/tmp', os.path.split(path)[1]))
- return template.render(**glob)
- except StandardError, err:
- pass
- print traceback.format_exc()
- #log.error('Can not write file: %s' % err)
- except:
- print traceback.format_exc()
- #log.error('Unknown error: ' )
- pass
- if f:
- if f:
- f.close()
- return ''
-
-class EvaluationExport:
-
- def __init__(self, style=None):
- self.style = style
-
- def export(self, eval):
- return self.transform(self._toXML(eval))
-
- def _toXML(self, eval):
- data = eval.result_dic
- out = []
- out.append('<?xml version="1.0"?>')
- out.append(XML_HEADER % (data['agency'], data['start_date'], data['end_date']))
- for key in sorted([int(s) for s in data['evaluations'].keys()]):
- eval = date['evaluations'][str(key)]
- men = eval['result'][0]
- women = eval['result'][1]
- sum = eval['result'][2]
- out.append(XML_BODY % (key, men, women, sum))
- out.append(XML_FOOTER)
- return "\n".join(out)
-
- def transform(self, data):
- #log.debug('Transaforming: %s' % data)
- if self.style:
- try:
- path = os.path.join(pylons.config.get('pylons.paths').get('static_files'), 'xsl', self.style)
- xslt = open(path, 'r')
- xslt_doc = etree.parse(xslt)
- transform = etree.XSLT(xslt_doc)
- xml = StringIO(data)
- xml_doc = etree.parse(xml)
- result_doc = transform(xml_doc)
- xslt.close()
- # Find out how to get the payload even if the result doc does not have a rootnode. # e-g CSV-Export
- return etree.tostring(result_doc.getroot(), pretty_print=True)
- except StandardError, err:
- print traceback.format_exc()
- #log.error('Error while transforming error: %s' % err)
- result_doc = data
- else:
- result_doc = data
- #log.debug('No style defined returning untransformed xml')
- return result_doc
-
-class EvaluationExportXML(EvaluationExport):
-
- def __init__(self):
- EvaluationExport.__init__(self, None)
-
- def transform(self, data):
- return data
-
-class EvaluationExportCSV(EvaluationExport):
-
- def __init__(self):
- EvaluationExport.__init__(self, 'eval_csv.xsl')
-
- def export(self, eval):
- xml = self._toXML(eval)
- out = []
- out.append(self.transform(xml))
- #log.debug('generated csv: %s' % "\n".join(out))
- try:
- csv = render_with_mako(eval, out)
- without_whitespace = [l for l in csv.split('\n') if l]
- return "\n".join(without_whitespace[1:-1])
- except StandardError, err:
- #log.error('Error while rendering file: %s' % err)
- raise
-
-class EvaluationExportHTML(EvaluationExport):
-
- def __init__(self):
- EvaluationExport.__init__(self, 'eval_mako.xsl')
-
- def export(self, eval):
- xml = self._toXML(eval)
- return self.transform(xml)
-
-class EvaluationExportMAKO(EvaluationExport):
-
- def __init__(self):
- EvaluationExport.__init__(self, 'eval_mako.xsl')
-
- def export(self, eval):
- xml = self._toXML(eval)
- out = []
- out.append('<%inherit file="/main.mako"/>')
- out.append('<%! import waskaweb.lib.filters as F %>')
- out.append(self.transform(xml))
- try:
- return render_with_mako(eval, out)
- except StandardError, err:
- print traceback.format_exc()
- #log.error('Error while rendering file: %s' % err)
- raise
-
-class Evaluation:
- '''Evaluation holds a "set " of different EvaluationQuerys for a particular
- agency within a given timeframe. The result of the evaluation is stored in
- a dictionary. The parameters are given in form of a dictionary.
-
- INPUT
- -----
- The following dictionary defines a teh possible params:
-
- agencyid : Id of the agency. (e.g the FKZ)
- start_date : The start date of the timeframe given in YYYY-MM-DD format
- end_date : The end date of the timeframe given in YYYY-MM-DD format
- typelist : A comma seperated list of evaluation ids
-
- OUTPUT
- ------
- The following dictionary defines a result_set:
-
- {
- 'agency': $agencyid,
- 'start_date': $start_date,
- 'end_date': $end_date
- 'evaluations': {
- '$id': {
- 'name': $name,
- 'description': $description,
- 'result':[ men,women,men+women],
- }
- ... more evaluations
- }
- }
- '''
-
- def __init__(self, params):
- self.id = params.get('id', '0')
- self.agency = params.get('agencyid')
- self.start_date = params.get('start_date', '1970-01-01')
- self.end_date = params.get('end_date', )
- self.mapping = {} #build_map(MpulsConfig().get('database', 'mappingfile'))
- evaluations_str = str(params.get('typelist') or '')
- self._setup()
-
- if evaluations_str:
- self.evaluations = evaluations_str.split(',')
- else:
- self.evaluations = self.default_evaluations
-
- self.result_dic = {}
-
- def _setup(self):
- self.evaluation_mapping = EVALUATION
- self.default_evaluations = DEFAULT_EVALUATIONS
- self.sql_base_query = SQL_BASE_QUERY
- self.sql_table = SQL_TABLE
- self.sql_gender = SQL_GENDER_FIELD
-
- def _build_sql(self, where):
- return self.sql_base_query % (self.sql_gender, self.sql_table, where, self.sql_gender)
-
- def _set_header(self):
- agency = self.mapping.get(self.agency, self.agency)
- self.result_dic['agency'] = agency
- self.result_dic['start_date'] = self.start_date
- self.result_dic['end_date'] = self.end_date
- self.result_dic['evaluations'] = {}
-
- def _set_body(self, eval):
- body_dic = {}
- body_dic['name'] = self.get_name(eval.id)
- body_dic['description'] = self.get_description(eval.id)
- body_dic['result'] = [eval.men, eval.women, eval.men+eval.women]
- self.result_dic['evaluations'][eval.id] = body_dic
-
- def _set_footer(self):
- pass
-
- def perform(self):
- self._set_header()
- for eval_id in self.evaluations:
- try:
- sql = self._build_sql(self.evaluation_mapping.get(eval_id))
- evaluation = EvaluationQuery(eval_id, sql)
- evaluation.perform()
- self._set_body(evaluation)
- except StandardError, err:
- #log.error('Error on performing evaluation: %s' % err)
- pass
- self._set_footer()
- return self.result_dic
-
- def export(self, handler=None):
- return handler.export(self)
-
- def get_name(self, id=None):
- return EVAL_NAMES.get(str(id), _('Eval No: %s' % id))
-
- def get_description(self, id):
- return EVAL_DESCRIPTIONS.get(str(id), _('No description available'))
-
-class EvaluationQuery:
- def __init__(self, id=None, sql=None):
- self.id = id
- self.sql = sql
- self.result = {}
- self.men = 0
- self.women = 0
-
- def perform(self):
- conn, cur = None, None
- try:
- conn = db.getConnection()
- cur = conn.cursor()
- cur.execute(self.sql)
- #log.debug(cur.query)
- for r in cur.fetchall():
- self.result[r[0]] = r[1]
- # !!! Index of gender differs to WASKA !!!
- if r[0] == 0: # men
- self.men = int(r[1])
- if r[0] == 1: # women
- self.women = int(r[1])
- except StandardError, err:
- print err
- print cur.query
- #log.error("Error with query %s" % self.sql)
- pass
- except:
- #log.error("Error with query %s" % self.sql)
- pass
- if conn:
- db.recycleConnection(conn, cur)
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
More information about the Mpuls-commits
mailing list