コード例 #1
0
ファイル: main.py プロジェクト: ws-mps/odoo
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.env['report']
        context = dict(request.env.context)

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from the webclient *but* if
            # the user explicitely wants to change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])
        if converter == 'html':
            html = report_obj.with_context(context).get_html(docids,
                                                             reportname,
                                                             data=data)
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report_obj.with_context(context).get_pdf(docids,
                                                           reportname,
                                                           data=data)
            pdfhttpheaders = [('Content-Type', 'application/pdf'),
                              ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(
                description='Converter %s not implemented.' % converter)
コード例 #2
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from the webclient *but* if
            # the user explicitely wants to change the lang, this mechanism overwrites it. 
            data_context = simplejson.loads(data['context'])
            if data_context.get('lang'):
                del data_context['lang']
            context.update(data_context)

        if converter == 'html':
            html = report_obj.get_html(cr, uid, docids, reportname, data=options_data, context=context)
            return request.make_response(html)
        elif converter == 'xls':
            xls = report_obj.get_xls(cr, uid, docids, reportname, data=options_data, context=context)
            xlshttpheaders = [('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                              ('Cache-Control', 'max-age=0'),
                              ('Content-Length', len(xls))]
            return request.make_response(xls, headers=xlshttpheaders)
        elif converter == 'pdf':
            pdf = report_obj.get_pdf(cr, uid, docids, reportname, data=options_data, context=context)
            pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='Converter %s not implemented.' % converter)
コード例 #3
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        options_data = None
        if data.get('options'):
            options_data = simplejson.loads(data['options'])
        if data.get('context'):
            context.update(simplejson.loads(data['context']))

        if converter == 'html':
            html = report_obj.get_html(cr,
                                       uid,
                                       docids,
                                       reportname,
                                       data=options_data,
                                       context=context)
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report_obj.get_pdf(cr,
                                     uid,
                                     docids,
                                     reportname,
                                     data=options_data,
                                     context=context)
            pdfhttpheaders = [('Content-Type', 'application/pdf'),
                              ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(
                description='Converter %s not implemented.' % converter)
コード例 #4
0
ファイル: listener.py プロジェクト: Sirius21c/octavia
 def _check_listener_exists(self, listener_id):
     # check if we know about that listener
     if not os.path.exists(util.config_path(listener_id)):
         raise exceptions.HTTPException(response=webob.Response(json=dict(
             message='Listener Not Found',
             details="No listener with UUID: {0}".format(listener_id)),
                                                                status=404))
コード例 #5
0
    def report_barcode(self,
                       type,
                       value,
                       width=600,
                       height=100,
                       humanreadable=0):
        """Contoller able to render barcode images thanks to reportlab.
        Samples: 
            <img t-att-src="'/report/barcode/QR/%s' % o.name"/>
            <img t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' % 
                ('QR', o.name, 200, 200)"/>

        :param type: Accepted types: 'Codabar', 'Code11', 'Code128', 'EAN13', 'EAN8', 'Extended39',
        'Extended93', 'FIM', 'I2of5', 'MSI', 'POSTNET', 'QR', 'Standard39', 'Standard93',
        'UPCA', 'USPS_4State'
        :param humanreadable: Accepted values: 0 (default) or 1. 1 will insert the readable value
        at the bottom of the output image
        """
        try:
            width, height, humanreadable = int(width), int(height), bool(
                humanreadable)
            barcode = createBarcodeDrawing(type,
                                           value=value,
                                           format='png',
                                           width=width,
                                           height=height,
                                           humanReadable=humanreadable)
            barcode = barcode.asString('png')
        except (ValueError, AttributeError):
            raise exceptions.HTTPException(
                description='Cannot convert into barcode.')

        return request.make_response(barcode,
                                     headers=[('Content-Type', 'image/png')])
コード例 #6
0
ファイル: keepalivedlvs.py プロジェクト: wind-fire/octavia
 def _check_udp_listener_exists(self, listener_id):
     if not os.path.exists(util.keepalived_lvs_cfg_path(listener_id)):
         raise exceptions.HTTPException(
             response=webob.Response(json=dict(
                 message='UDP Listener Not Found',
                 details="No UDP listener with UUID: {0}".format(
                     listener_id)), status=404))
コード例 #7
0
    def _bring_if_up(cls, interface, what, flush=True):
        # Note, we are not using pyroute2 for this as it is not /etc/netns
        # aware.
        # Work around for bug:
        # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=845121
        int_up = "ip netns exec {ns} ip link set {int} up".format(
            ns=consts.AMPHORA_NAMESPACE, int=interface)
        addr_flush = "ip netns exec {ns} ip addr flush {int}".format(
            ns=consts.AMPHORA_NAMESPACE, int=interface)

        cmd = ("ip netns exec {ns} ifup {params}".format(
            ns=consts.AMPHORA_NAMESPACE, params=interface))
        try:
            out = subprocess.check_output(int_up.split(),
                                          stderr=subprocess.STDOUT)
            LOG.debug(out)
            if flush:
                out = subprocess.check_output(addr_flush.split(),
                                              stderr=subprocess.STDOUT)
                LOG.debug(out)
            out = subprocess.check_output(cmd.split(),
                                          stderr=subprocess.STDOUT)
            LOG.debug(out)
        except subprocess.CalledProcessError as e:
            LOG.error('Failed to ifup %s due to error: %s %s', interface, e,
                      e.output)
            raise exceptions.HTTPException(response=webob.Response(json=dict(
                message='Error plugging {0}'.format(what), details=e.output),
                                                                   status=500))
コード例 #8
0
 def _check_lb_exists(self, lb_id):
     # check if we know about that lb
     if lb_id not in util.get_loadbalancers():
         raise exceptions.HTTPException(response=webob.Response(json=dict(
             message='Loadbalancer Not Found',
             details="No loadbalancer with UUID: {0}".format(lb_id)),
                                                                status=404))
コード例 #9
0
def _check_listener_exists(listener_id):
    # check if we know about that listener
    if not os.path.exists(util.config_path(listener_id)):
        raise exceptions.HTTPException(
            response=flask.make_response(flask.jsonify(dict(
                message='Listener Not Found',
                details="No listener with UUID: {0}".format(
                    listener_id))), 404))
コード例 #10
0
    def report_barcode(self, type, value, width=None, height=None, humanreadable=0, lines=1):
        # TODO: Add "PDF417" support.
        # TODO: Support for multiple barcode lines for all codes.
        try:
            bs = barcode.createBarcodeImageInMemory(type, value, width=width and int(width) or None, height=height and int(height) or None, human_readable=bool(humanreadable), lines=lines and int(lines) or 1)
        except (ValueError, AttributeError) as e:
            raise exceptions.HTTPException(description='Cannot convert into barcode.')

        return request.make_response(bs, headers=[('Content-Type', 'image/png')])
コード例 #11
0
ファイル: plug.py プロジェクト: mallow111/octavia
def _interface_by_mac(mac):
    for interface in netifaces.interfaces():
        if netifaces.AF_LINK in netifaces.ifaddresses(interface):
            for link in netifaces.ifaddresses(interface)[netifaces.AF_LINK]:
                if link.get('addr', '').lower() == mac.lower():
                    return interface
    raise exceptions.HTTPException(
        response=flask.make_response(flask.jsonify(dict(
            details="No suitable network interface found")), 404))
コード例 #12
0
 def _interface_by_mac(self, mac):
     for interface in netifaces.interfaces():
         if netifaces.AF_LINK in netifaces.ifaddresses(interface):
             for link in netifaces.ifaddresses(interface)[
                     netifaces.AF_LINK]:
                 if link.get('addr', '').lower() == mac.lower():
                     return interface
     raise exceptions.HTTPException(response=webob.Response(json=dict(
         details="No suitable network interface found"),
                                                            status=404))
コード例 #13
0
    def conecta(self, ids):
        print "CONTROLLER ##########################################################"
        self.cr, self.uid, self.pool = request.cr, request.uid, request.registry

        def append_pdf(input, output):
            [
                output.addPage(input.getPage(page_num))
                for page_num in range(input.numPages)
            ]

        if isinstance(ids, unicode):
            ids = eval(ids)  # (int(i) for i in ids.split(','))
            contracts = request.env['hr.contract'].sudo().search([('id', 'in',
                                                                   ids)])

            combined = StringIO()
            output = PdfFileWriter()
            pdf_form = PdfTemplate()  # ? template. contract.type_id_template

            for contract in contracts:
                fields = [
                    ('ID_EMPR', contract.company_id.vat),
                    ('Texto4', contract.company_id.manager_id.name),
                    ('Texto5',
                     contract.company_id.manager_id.identification_id),
                    ('Texto6', 'APODERADO'),
                    ('Texto7', contract.company_id.name),
                    ('Texto8', contract.company_id.street),
                    ('Texto9', u'ESPAÑA'),
                    ('Texto10', '724'),
                    ('NOM_TRA', contract.employee_id.name_id.firstname),
                    ('APE1_TRA', contract.employee_id.name_id.lastname),
                    ('APE2_TRA', contract.employee_id.name_id.lastname2),
                ]

                result = pdf_form.render(fields, contract.type_id.template)
                append_pdf(PdfFileReader(StringIO(result)), output)
                for clause in contract.clause_ids:
                    append_pdf(
                        PdfFileReader(StringIO(base64.b64decode(clause.file))),
                        output)

            output.write(combined)

            pdfhttpheaders = [
                ('Content-Type', 'application/pdf'),
                ('Content-Length', len(combined.getvalue())),
                ('Content-Disposition',
                 content_disposition('Contratos' + '.pdf')),
            ]
            return request.make_response(combined.getvalue(),
                                         headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='NOT implemented.')
コード例 #14
0
ファイル: plug.py プロジェクト: mallow111/octavia
def _bring_if_up(params, what):
    # bring interface up
    cmd = "ifup {params}".format(params=params)
    try:
        subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        LOG.debug("Failed to if up %s", e)
        raise exceptions.HTTPException(
            response=flask.make_response(flask.jsonify(dict(
                message='Error plugging {0}'.format(what),
                details=e.output)), 500))
コード例 #15
0
ファイル: errors.py プロジェクト: komodo108/flask-limiter
    def __init__(self, limit):
        self.limit = limit

        # Set defaults
        self.code = 429
        self.body = self.get_body()
        self.headers = self.get_headers()

        # Get the description
        if limit.error_message:
            self.description = limit.error_message if not callable(
                limit.error_message) else limit.error_message()
        else:
            self.description = text_type(limit.limit)

        # If error is given, get body & headers
        if self.limit.error_code:
            self.code = limit.error_code
            exception = exceptions.HTTPException(description=self.description)

            # Some common error codes, can add more here
            if self.code == 400:
                exception = exceptions.BadRequest()
            elif self.code == 401:
                exception = exceptions.Unauthorized()
            elif self.code == 403:
                exception = exceptions.Forbidden()
            elif self.code == 404:
                exception = exceptions.NotFound()
            elif self.code == 405:
                exception = exceptions.MethodNotAllowed()
            elif self.code == 406:
                exception = exceptions.NotAcceptable()
            elif self.code == 418:
                exception = exceptions.ImATeapot()  # <3
            elif self.code == 500:
                exception = exceptions.InternalServerError()
            elif self.code == 501:
                exception = exceptions.NotImplemented()

            # Update body & headers
            self.body = exception.get_body()
            self.headers = exception.get_headers()
        else:
            exception = exceptions.TooManyRequests(
                description=self.description)

            # Update body & headers
            self.body = exception.get_body()
            self.headers = exception.get_headers()
        super(RateLimitExceeded,
              self).__init__(description=self.description,
                             response=Response(self.body, self.code,
                                               self.headers))
コード例 #16
0
ファイル: osutils.py プロジェクト: xinhuoxing/octavia
 def _bring_if_up(self, interface, what):
     # Note, we are not using pyroute2 for this as it is not /etc/netns
     # aware.
     cmd = ("ip netns exec {ns} ifup {params}".format(
         ns=consts.AMPHORA_NAMESPACE, params=interface))
     try:
         subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
     except subprocess.CalledProcessError as e:
         LOG.error('Failed to if up %s due to error: %s', interface, e)
         raise exceptions.HTTPException(response=webob.Response(json=dict(
             message='Error plugging {0}'.format(what), details=e.output),
                                                                status=500))
コード例 #17
0
    def setUp(self):
        super(AppTestCase, self).setUp()

        self.app = app
        self.api_utils = api_utils
        self.flask = flask
        self.auth_token = auth_token

        self.render = self.patch(self.api_utils, 'render')
        self.fake_ff = self.patch(self.auth_token, 'filter_factory')

        self.ex = werkzeug_exceptions.HTTPException()
        self.ex.code = 1313
        self.ex.description = "my favourite error"
コード例 #18
0
ファイル: plug.py プロジェクト: paperandsoap/octavia
def _bring_if_up(interface, what):
    # Note, we are not using pyroute2 for this as it is not /etc/netns
    # aware.
    cmd = ("ip netns exec {ns} ifup {params}".format(
        ns=consts.AMPHORA_NAMESPACE, params=interface))
    try:
        subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        LOG.error(_LE('Failed to if up {0} due to '
                      'error: {1}').format(interface, str(e)))
        raise exceptions.HTTPException(
            response=flask.make_response(flask.jsonify(dict(
                message='Error plugging {0}'.format(what),
                details=e.output)), 500))
コード例 #19
0
ファイル: test_exceptions.py プロジェクト: lidayan/werkzeug
def test_exception_repr():
    exc = exceptions.NotFound()
    assert text_type(exc) == (
        "404 Not Found: The requested URL was not found on the server."
        " If you entered the URL manually please check your spelling"
        " and try again.")
    assert repr(exc) == "<NotFound '404: Not Found'>"

    exc = exceptions.NotFound("Not There")
    assert text_type(exc) == "404 Not Found: Not There"
    assert repr(exc) == "<NotFound '404: Not Found'>"

    exc = exceptions.HTTPException("An error message")
    assert text_type(exc) == "??? Unknown Error: An error message"
    assert repr(exc) == "<HTTPException '???: Unknown Error'>"
コード例 #20
0
def test_exception_repr():
    exc = exceptions.NotFound()
    assert text_type(exc) == (
        '404 Not Found: The requested URL was not found '
        'on the server.  If you entered the URL manually please check your '
        'spelling and try again.')
    assert repr(exc) == "<NotFound '404: Not Found'>"

    exc = exceptions.NotFound('Not There')
    assert text_type(exc) == '404 Not Found: Not There'
    assert repr(exc) == "<NotFound '404: Not Found'>"

    exc = exceptions.HTTPException('An error message')
    assert text_type(exc) == '??? Unknown Error: An error message'
    assert repr(exc) == "<HTTPException '???: Unknown Error'>"
コード例 #21
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.registry['report']
        cr, uid, context = request.cr, request.uid, request.context

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the
            # one from the webclient *but* if the user explicitely
            # wants to change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])

        if converter == 'xls':
            xls = report_obj.get_xls(cr,
                                     uid,
                                     docids,
                                     reportname,
                                     data=data,
                                     context=context)
            xlsxhttpheaders = [
                ('Content-Type',
                 'application/vnd.openxmlformats-officedocument.'
                 'spreadsheetml.sheet'), ('Content-Length', len(xls))
            ]
            return request.make_response(xls, headers=xlsxhttpheaders)
        elif converter == 'ods':
            ods = report_obj.get_ods(cr,
                                     uid,
                                     docids,
                                     reportname,
                                     data=data,
                                     context=context)
            odshttpheaders = [
                ('Content-Type',
                 'application/vnd.oasis.opendocument.spreadsheet'),
                ('Content-Length', len(ods))
            ]
            return request.make_response(ods, headers=odshttpheaders)
        else:
            raise exceptions.HTTPException(
                description='Converter %s not implemented.' % converter)
コード例 #22
0
 def _interface_by_mac(self, mac):
     for interface in netifaces.interfaces():
         if netifaces.AF_LINK in netifaces.ifaddresses(interface):
             for link in netifaces.ifaddresses(interface)[
                     netifaces.AF_LINK]:
                 if link.get('addr', '').lower() == mac.lower():
                     return interface
     # Poke the kernel to re-enumerate the PCI bus.
     # We have had cases where nova hot plugs the interface but
     # the kernel doesn't get the memo.
     filename = '/sys/bus/pci/rescan'
     flags = os.O_WRONLY
     if os.path.isfile(filename):
         with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
             rescan_file.write('1')
     raise exceptions.HTTPException(response=webob.Response(json=dict(
         details="No suitable network interface found"),
                                                            status=404))
コード例 #23
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        if converter != 'py3o':
            return super(ReportController,
                         self).report_routes(reportname=reportname,
                                             docids=docids,
                                             converter=converter,
                                             **data)
        context = dict(request.env.context)

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the
            # one from the webclient *but* if the user explicitely wants to
            # change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])

        ir_action = request.env['ir.actions.report.xml']
        action_py3o_report = ir_action.get_from_report_name(
            reportname, "py3o").with_context(context)
        if not action_py3o_report:
            raise exceptions.HTTPException(
                description='Py3o action report not found for report_name '
                '%s' % reportname)
        context['report_name'] = reportname
        py3o_report = request.env['py3o.report'].create({
            'ir_actions_report_xml_id':
            action_py3o_report.id
        }).with_context(context)

        res, filetype = py3o_report.create_report(docids, data)

        filename = action_py3o_report.gen_report_download_filename(
            docids, data)
        content_type = mimetypes.guess_type("x." + filetype)[0]
        http_headers = [('Content-Type', content_type),
                        ('Content-Length', len(res)),
                        ('Content-Disposition', content_disposition(filename))]
        return request.make_response(res, headers=http_headers)
コード例 #24
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        if converter != "py3o":
            return super(ReportController,
                         self).report_routes(reportname=reportname,
                                             docids=docids,
                                             converter=converter,
                                             **data)
        context = dict(request.env.context)

        if docids:
            docids = [int(i) for i in docids.split(",")]
        if data.get("options"):
            data.update(json.loads(data.pop("options")))
        if data.get("context"):
            # Ignore 'lang' here, because the context in data is the
            # one from the webclient *but* if the user explicitely wants to
            # change the lang, this mechanism overwrites it.
            data["context"] = json.loads(data["context"])
            if data["context"].get("lang"):
                del data["context"]["lang"]
            context.update(data["context"])

        ir_action = request.env["ir.actions.report"]
        action_py3o_report = ir_action.get_from_report_name(
            reportname, "py3o").with_context(context)
        if not action_py3o_report:
            raise exceptions.HTTPException(
                description="Py3o action report not found for report_name "
                "%s" % reportname)
        res, filetype = action_py3o_report._render(docids, data)
        filename = action_py3o_report.gen_report_download_filename(
            docids, data)
        if not filename.endswith(filetype):
            filename = "{}.{}".format(filename, filetype)
        content_type = mimetypes.guess_type("x." + filetype)[0]
        http_headers = [
            ("Content-Type", content_type),
            ("Content-Length", len(res)),
            ("Content-Disposition", content_disposition(filename)),
        ]
        return request.make_response(res, headers=http_headers)
コード例 #25
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        if converter != 'docx':
            return super(ReportController,
                         self).report_routes(reportname=reportname,
                                             docids=docids,
                                             converter=converter,
                                             **data)
        context = dict(request.env.context)

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the
            # one from the webclient *but* if the user explicitely wants to
            # change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])

        ir_action = request.env['ir.actions.report']
        action_docx_report = ir_action.get_from_report_name(
            reportname, "docx").with_context(context)
        if not action_docx_report:
            raise exceptions.HTTPException(
                description='Docx action report not found for report_name '
                '%s' % reportname)
        res, filetype = action_docx_report.render(docids, data)
        filename = action_docx_report.gen_report_download_filename(
            docids, data)
        if not filename.endswith(filetype):
            filename = "{}.{}".format(filename, filetype)

        content_type = self.TYPES_MAPPING.get(filetype, 'octet-stream')

        http_headers = [('Content-Type', content_type),
                        ('Content-Length', len(res)),
                        ('Content-Disposition', content_disposition(filename))]
        return request.make_response(res, headers=http_headers)
コード例 #26
0
    def _interface_by_mac(self, mac):
        try:
            with pyroute2.IPRoute() as ipr:
                idx = ipr.link_lookup(address=mac)[0]
                addr = ipr.get_links(idx)[0]
                for attr in addr['attrs']:
                    if attr[0] == 'IFLA_IFNAME':
                        return attr[1]
        except Exception as e:
            LOG.info('Unable to find interface with MAC: %s, rescanning '
                     'and returning 404. Reported error: %s', mac, str(e))

        # Poke the kernel to re-enumerate the PCI bus.
        # We have had cases where nova hot plugs the interface but
        # the kernel doesn't get the memo.
        filename = '/sys/bus/pci/rescan'
        flags = os.O_WRONLY
        if os.path.isfile(filename):
            with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
                rescan_file.write('1')
        raise exceptions.HTTPException(
            response=webob.Response(json=dict(
                details="No suitable network interface found"), status=404))
コード例 #27
0
 def _check_ssl_filename_format(self, filename):
     # check if the format is (xxx.)*xxx.pem
     if not re.search('(\w.)+pem', filename):
         raise exceptions.HTTPException(response=webob.Response(
             json=dict(message='Filename has wrong format'), status=400))
コード例 #28
0
def test_response_header_content_type_should_contain_charset():
    exc = exceptions.HTTPException("An error message")
    h = exc.get_response({})
    assert h.headers["Content-Type"] == "text/html; charset=utf-8"
コード例 #29
0
    def conecta(self, ids):
        print "controller ---------------------------------------------------------"
        self.cr, self.uid, self.pool = request.cr, request.uid, request.registry

        ids = eval(ids)

        def append_pdf(input, output):
            [
                output.addPage(input.getPage(page_num))
                for page_num in range(input.numPages)
            ]

        print ids
        if ids:
            print "HOLA"
            employees = request.env['hr.employee'].sudo().search([('id', 'in',
                                                                   ids)])

            combined = StringIO()
            output = PdfFileWriter()
            pdf_form = PdfTemplate()  # ? template. contract.type_id_template

            for employee in employees:
                fields = [
                    ('dato.nif.1',
                     employee.fiscal_last_id.employee_id.identification_id
                     ),  # dni empleado
                    ('dato.1', employee.name),  # nombre empleado
                    ('dato.2',
                     time.strftime(
                         '%Y', time.strptime(employee.birthday,
                                             '%Y-%m-%d'))),  # nombre empleado
                    ('dato.3', 1 if employee.fiscal_last_id.situation == '1'
                     else 0),  # situacion
                    ('dato.4', 1 if employee.fiscal_last_id.situation == '2'
                     else 0),  # situacion
                    ('dato.nif.2', employee.fiscal_last_id.conyuge_nif
                     if employee.fiscal_last_id.situation == '2' else
                     ''),  # situacion
                    ('dato.6', 1 if employee.fiscal_last_id.situation == '3'
                     else 0),  # situacion:
                    ('dato.7', 1 if employee.fiscal_last_id.minus == '3' else
                     0),  # minusvalia: Entre 33% y 65%,
                    ('dato.7', 1 if employee.fiscal_last_id.minus == 'A' else
                     0),  # minusvalia: Entre 33% y 65%, con asistencia
                    ('dato.9', 1 if employee.fiscal_last_id.minus == 'A'
                     or employee.fiscal_last_id.minus == 'B' else
                     0),  # minusvalia: Entre 33% y 65%, con asistencia
                    ('dato.8', 1 if employee.fiscal_last_id.minus == '6' else
                     0),  # minusvalia Igual/Superior a 65%
                    ('dato.8', 1 if employee.fiscal_last_id.minus == 'B' else
                     0),  # minusvalia: Igual/Superior a 65%, con asistencia
                    #('dato.9', 1 if employee.fiscal_last_id.minus == 'B' else 0), # minusvalia: Igual/Superior a 65%, con asistencia
                    ('dato.10',
                     time.strftime(
                         '%d/%m/%Y',
                         time.strptime(employee.fiscal_last_id.geo_date,
                                       '%Y-%m-%d'))
                     if employee.fiscal_last_id.geo_move == 'S' else ''
                     ),  # fecha movilidad
                    ('dato.11', 0),  # rendimientos periodo superior 2 años
                    ('dato.53', 1 if employee.fiscal_last_id.loan == 'S' else
                     0),  # vivienda
                    ('dato.54', employee.home_city),  # employee city
                    ('dato.55',
                     time.strftime(
                         '%d',
                         time.strptime(employee.fiscal_last_id.date_from,
                                       '%Y-%m-%d'))),  # fecha movilidad
                    ('dato.56',
                     time.strftime(
                         '%B',
                         time.strptime(employee.fiscal_last_id.date_from,
                                       '%Y-%m-%d'))),  # fecha movilidad
                    ('dato.57',
                     time.strftime(
                         '%Y',
                         time.strptime(employee.fiscal_last_id.date_from,
                                       '%Y-%m-%d'))),  # fecha movilidad
                    ('dato.58', employee.name),  # Empleado
                    ('dato.59', employee.company_id.name),  # company
                    ('dato.60', employee.company_id.city),  # company city
                    ('dato.61',
                     time.strftime(
                         '%d',
                         time.strptime(employee.fiscal_last_id.date_from,
                                       '%Y-%m-%d'))),  # fecha movilidad
                    ('dato.62',
                     time.strftime(
                         '%B',
                         time.strptime(employee.fiscal_last_id.date_from,
                                       '%Y-%m-%d'))),  # fecha movilidad
                    ('dato.63',
                     time.strftime(
                         '%Y',
                         time.strptime(employee.fiscal_last_id.date_from,
                                       '%Y-%m-%d'))),  # fecha movilidad
                    ('dato.64',
                     employee.company_id.manager_id.name),  # Manager
                ]
                i = 0
                for fam in employee.fiscal_last_id.fam_ids:
                    if fam.type in ['2', '6']:
                        fields.append(
                            ('dato.' + str(12 + i),
                             time.strftime(
                                 '%Y', time.strptime(fam.birthday, '%Y-%m-%d'))
                             if fam.birthday != False else ''))
                        fields.append(
                            ('dato.' + str(13 + i),
                             time.strftime(
                                 '%Y',
                                 time.strptime(fam.date_adoption, '%Y-%m-%d'))
                             if fam.date_adoption != False else ''))
                        fields.append(
                            ('dato.' + str(14 + i), 1 if fam.minus == '3' else
                             0))  # minusvalia:  Entre 33% y 65%,
                        fields.append(
                            ('dato.' + str(14 + i), 1 if fam.minus == 'A' else
                             0))  # minusvalia: Entre 33% y 65%, con asistencia
                        fields.append(
                            ('dato.' + str(16 + i),
                             1 if fam.minus == 'A' or fam.minus == 'B' else
                             0))  # minusvalia: Entre 33% y 65%, con asistencia
                        fields.append(
                            ('dato.' + str(15 + i),
                             1 if fam.minus == '6' else 0)
                        )  # minusvalia:Igual/Superior a 33% e inferior 65%
                        fields.append(
                            ('dato.' + str(15 + i),
                             1 if fam.minus == 'B' else 0)
                        )  # minusvalia: Igual/Superior a 65%, con asistencia
                        fields.append(
                            ('dato.' + str(17 + i), 1 if fam.factor == '3' else
                             0))  # computo: totalidad del minimo
                        i += 6

                i = 0
                for fam in employee.fiscal_last_id.fam_ids:
                    if fam.type in ['11']:
                        fields.append(
                            ('dato.' + str(40 + i),
                             time.strftime(
                                 '%Y', time.strptime(fam.birthday, '%Y-%m-%d'))
                             if fam.birthday != False else ''))
                        fields.append(
                            ('dato.' + str(41 + i), 1 if fam.minus == '3' else
                             0))  # minusvalia:  Entre 33% y 65%,
                        fields.append(
                            ('dato.' + str(41 + i), 1 if fam.minus == 'A' else
                             0))  # minusvalia: Entre 33% y 65%, con asistencia
                        fields.append(
                            ('dato.' + str(42 + i),
                             1 if fam.minus == 'A' or fam.minus == 'B' else
                             0))  # minusvalia: Entre 33% y 65%, con asistencia
                        fields.append(
                            ('dato.' + str(43 + i),
                             1 if fam.minus == '6' else 0)
                        )  # minusvalia:Igual/Superior a 33% e inferior 65%
                        fields.append(
                            ('dato.' + str(43 + i),
                             1 if fam.minus == 'B' else 0)
                        )  # minusvalia: Igual/Superior a 65%, con asistencia
                        fields.append(('dato.' + str(44 + i),
                                       fam.conviven if fam.conviven != '0' else
                                       0))  # computo: totalidad del minimo
                        i += 6

                result = pdf_form.render(
                    fields,
                    "G:\odoo\V9\conecta\hr_employee_fiscal\pdfs\Mod145.pdf")
                append_pdf(PdfFileReader(StringIO(result)), output)

            output.write(combined)

            pdfhttpheaders = [
                ('Content-Type', 'application/pdf'),
                ('Content-Length', len(combined.getvalue())),
                ('Content-Disposition',
                 content_disposition('Mod145' + '.pdf')),
            ]

            return request.make_response(combined.getvalue(),
                                         headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='NOT implemented.')
コード例 #30
0
def _check_ssl_filename_format(filename):
    # check if the format is (xxx.)*xxx.pem
    if not re.search('(\w.)+pem', filename):
        raise exceptions.HTTPException(
            response=flask.make_response(flask.jsonify(dict(
                message='Filename has wrong format')), 400))