示例#1
0
def callservice(url__, headers__=None, **kargs):
    if not is_testing():
        kw = {}
        if headers__:
            kw["headers"] = headers__
        if kargs:
            # urlencode does not accept non-ascii data
            for k, v in kargs.iteritems():
                if isinstance(v, unicode):
                    kargs[k] = v.encode("utf-8")
            kw["data"] = urlencode(kargs)
        req = Request(url__, **kw)
        u = urlopen(req)
        return u.read()
    else:
        from paste.fixture import AppError

        headers = {}
        if headers__:
            headers.update(headers__)
        try:
            resp = get_testing_server().post(url=url__, headers=headers, params=kargs).body
            return resp
        except AppError, e:
            if "500" in e.message:
                raise ValueError(e.message.split("\n", 1)[1].strip())
            raise
示例#2
0
    def __call__(self, environ, start_response):
        base_url = self.config['controller']
        req_url = environ.get('PATH_INFO')
        if not req_url.startswith(base_url + '/') and req_url != base_url:
            return self.not_found(start_response)

        proc_start = time.time()

        try:
            assert self.access_key == environ.get('HTTP_AUTHORIZATION')
            log.debug('Access granted with key %s' % \
                environ.get('HTTP_AUTHORIZATION'))
        except:
            log.warn('Access unauthorized. Environment:\n%s' % environ)
            return self.auth_required(start_response)

        environ['SCRIPT_NAME'] = base_url
        environ['PATH_INFO'] = environ['PATH_INFO'].split(base_url)[1]

        servicename = path_info_pop(environ)
        # Describe myself
        if not servicename:
            desc = self.describe(start_response)
            log.info('Describing esb')
            log.debug('Returning %s' % desc[0])
            return desc

        try:
            service = self.services[servicename]['service']
        except:
            # There is no such service
            log.warn('Service %s not found or not working' % servicename)
            return self.not_found(start_response)
        
        methodname = path_info_pop(environ)
        if not methodname:
            # The request about the service itself
            desc = self.describe_service(servicename, start_response)
            log.info('Describing %s' % servicename)
            log.debug('Returning %s' % desc[0])
            return desc

        # A method was called
        try:
            method = getattr(service, methodname)
            assert getattr(method, 'webmethod', False)
        except:
            # The service does not have such a webmethod
            log.warn('A webmethod %s.%s not found' % (servicename, methodname))
            return self.not_found(start_response)

        kargs = dict()
        try:
            kargs = dict(parse_formvars(environ, include_get_vars=True))
            for karg in kargs.keys():
                kargs[karg] = from_json(kargs[karg])
        except:
            log.warn('Failed to parse parameters for %s.%s: %s' % (servicename,
                methodname, kargs))
            return self.request_error(start_response, 'Invalid parameters')

        # Extract the positional arguments:
        args = kargs.pop('__dwsargs__', [])

        # Call the method
        if is_testing():
            result = method(*args, **kargs)
            result = to_json(result)
        else:
            try:
                exec_start = time.time()
                result = method(*args, **kargs)
                exec_time = (time.time() - exec_start) * 1000

                log.info('%s.%s finished in %.2f ms' % (servicename,
                    methodname, exec_time))
                log.debug('\nArgs: %s\nKargs: %s\nResult: %s' % (args, kargs,
                    result))

                result = to_json(result)
                elixir.session.close()
            except Exception, e:
                exc = format_exc(e)
                start_response('500 Internal Server Error',
                    [('Content-Type', 'text/html')])

                log.error('%s.%s\n%s' % (servicename, methodname, exc))
                elixir.session.close()
                return ['Internal server error']