Exemplo n.º 1
0
    def __call__(self, environ, start_response):
        http_origin = environ.get('HTTP_ORIGIN')
        if not self.allow_all_origins and http_origin not in self.allowed_origins:
            return self.application(environ, start_response)

        http_method = environ.get('REQUEST_METHOD')
        if http_method not in self.allowed_methods:
            method_not_allowed = HTTPMethodNotAllowed()
            start_response(
                method_not_allowed.status,
                [('Content-type', 'application/json')])
            return format_error_to_json(method_not_allowed)

        cors_headers = []
        if self.allow_all_origins:
            cors_headers.append(('Access-Control-Allow-Origin', '*'))
        else:
            cors_headers.append(('Access-Control-Allow-Origin', force_string(http_origin)))

        if http_method == 'OPTIONS':
            methods = environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
            if methods:
                cors_headers.append(('Access-Control-Allow-Methods', force_string(methods)))

            http_headers = environ.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')
            if http_headers:
                cors_headers.append(('Access-Control-Allow-Headers', force_string(http_headers)))

            if self.max_age is not None:
                cors_headers.append(('Access-Control-Max-Age', force_string(self.max_age)))

            start_response(HTTPNoContent().status, cors_headers)
            return []
        else:
            def start_response_decorator(status, headers, exc_info=None):
                headers.extend(cors_headers)
                return start_response(status, headers, exc_info)

            return self.application(environ, start_response_decorator)
Exemplo n.º 2
0
Arquivo: logs.py Projeto: hjalves/ines
    def log(self, code, message, level='INFO'):
        header = ('-' * 30) + ' ' + level + ' ' + ('-' * 30)
        print header

        arguments = [
            ('Application', self.request.application_name),
            ('Code', code),
            ('URL', self.request.url),
            ('Method', self.request.method),
            ('Date', NOW_DATE()),
            ('Language', self.request.locale_name),
            ('IP address', self.request.ip_address)]

        try:
            authenticated = self.request.authenticated
        except HTTPUnauthorized:
            authenticated = None

        if authenticated:
            arguments.extend([
                ('Session type', self.request.authenticated.session_type),
                ('Session id', self.request.authenticated.session_id)])
        else:
            arguments.append(('Session', 'Without autentication'))

        bigger = max(len(k) for k, v in arguments)
        for key, value in arguments:
            print key, ' ' * (bigger - len(key)), ':', force_string(value)

        print
        try:
            message = force_string(message)
            for line in message.split('\n'):
                print '  %s' % line
        except UnicodeEncodeError:
            pass

        print '-' * len(header)
Exemplo n.º 3
0
Arquivo: logs.py Projeto: hjalves/ines
    def log(self, code, message, level='INFO'):
        header = ('-' * 30) + ' ' + level + ' ' + ('-' * 30)
        print header

        arguments = [('Application', self.request.application_name),
                     ('Code', code), ('URL', self.request.url),
                     ('Method', self.request.method), ('Date', NOW_DATE()),
                     ('Language', self.request.locale_name),
                     ('IP address', self.request.ip_address)]

        try:
            authenticated = self.request.authenticated
        except HTTPUnauthorized:
            authenticated = None

        if authenticated:
            arguments.extend([
                ('Session type', self.request.authenticated.session_type),
                ('Session id', self.request.authenticated.session_id)
            ])
        else:
            arguments.append(('Session', 'Without autentication'))

        bigger = max(len(k) for k, v in arguments)
        for key, value in arguments:
            print key, ' ' * (bigger - len(key)), ':', force_string(value)

        print
        try:
            message = force_string(message)
            for line in message.split('\n'):
                print '  %s' % line
        except UnicodeEncodeError:
            pass

        print '-' * len(header)
Exemplo n.º 4
0
    def __call__(self, environ, start_response):
        content_type = get_content_type(environ.get('CONTENT_TYPE'))
        if content_type == 'application/json' and 'wsgi.input' in environ:
            body = environ['wsgi.input'].read()
            if body:
                arguments = []
                try:
                    body_json = loads(body)
                    for key, values in dict(body_json).items():
                        values = maybe_list(values)
                        value = ','.join('' if v is None else dump_query_value(v) for v in values)
                        arguments.append('%s=%s' % (force_string(key), value))
                    body = '&'.join(arguments)
                except (ValueError, UnicodeEncodeError):
                    headers = [('Content-type', 'application/json')]
                    error = HTTPInvalidJSONPayload()
                    start_response(error.status, headers)
                    return format_error_to_json(error)

            environ_add_POST(environ, body or '')

        return self.application(environ, start_response)
Exemplo n.º 5
0
    def __call__(self, environ, start_response):
        content_type = get_content_type(environ.get('CONTENT_TYPE'))
        if content_type == 'application/json' and 'wsgi.input' in environ:
            body = environ['wsgi.input'].read()
            if body:
                arguments = []
                try:
                    body_json = loads(body)
                    for key, values in dict(body_json).items():
                        values = maybe_list(values)
                        value = ','.join(
                            '' if v is None else dump_query_value(v)
                            for v in values)
                        arguments.append('%s=%s' % (force_string(key), value))
                    body = '&'.join(arguments)
                except (ValueError, UnicodeEncodeError):
                    headers = [('Content-type', 'application/json')]
                    error = HTTPInvalidJSONPayload()
                    start_response(error.status, headers)
                    return format_error_to_json(error)

            environ_add_POST(environ, body or '')

        return self.application(environ, start_response)
Exemplo n.º 6
0
def dump_query_value(value):
    if isinstance(value, basestring):
        return force_string(value)
    else:
        return force_string(dumps(value))
Exemplo n.º 7
0
 def __str__(self):
     if not is_nonstr_iter(self.value):
         return force_string(self.value)
     else:
         return self.value
Exemplo n.º 8
0
def dump_query_value(value):
    if isinstance(value, basestring):
        return force_string(value)
    else:
        return force_string(dumps(value))
Exemplo n.º 9
0
def get_content_type(value):
    if value:
        return force_string(value).split(';', 1)[0].strip()
Exemplo n.º 10
0
def validate_email(value):
    value = force_string(value)
    return bool(EMAIL_REGEX.match(value))