Beispiel #1
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = base.get_path_info(environ)
     if not path_info or path_info == script_name:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         #
         # (The comparison of path_info to script_name is to work around an
         # apparent bug in flup 1.0.1. See Django ticket #8490).
         path_info = "/"
     self.environ = environ
     self.path_info = path_info
     self.path = "%s%s" % (script_name, path_info)
     self.META = environ
     self.META["PATH_INFO"] = path_info
     self.META["SCRIPT_NAME"] = script_name
     self.method = environ["REQUEST_METHOD"].upper()
     _, content_params = self._parse_content_type(self.META.get("CONTENT_TYPE", ""))
     if "charset" in content_params:
         try:
             codecs.lookup(content_params["charset"])
         except LookupError:
             pass
         else:
             self.encoding = content_params["charset"]
     self._post_parse_error = False
     try:
         content_length = int(self.environ.get("CONTENT_LENGTH"))
     except (ValueError, TypeError):
         content_length = 0
     self._stream = LimitedStream(self.environ["wsgi.input"], content_length)
     self._read_started = False
Beispiel #2
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = base.get_path_info(environ)
     if not path_info:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         path_info = '/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/'))
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     _, content_params = self._parse_content_type(
         self.META.get('CONTENT_TYPE', ''))
     if 'charset' in content_params:
         try:
             codecs.lookup(content_params['charset'])
         except LookupError:
             pass
         else:
             self.encoding = content_params['charset']
     self._post_parse_error = False
     try:
         content_length = int(self.environ.get('CONTENT_LENGTH'))
     except (ValueError, TypeError):
         content_length = 0
     self._stream = LimitedStream(self.environ['wsgi.input'],
                                  content_length)
     self._read_started = False
     self.resolver_match = None
Beispiel #3
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', '/'))
     if not path_info or path_info == script_name:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         #
         # (The comparison of path_info to script_name is to work around an
         # apparent bug in flup 1.0.1. See Django ticket #8490).
         path_info = '/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     self._post_parse_error = False
     try:
         content_length = int(self.environ.get('CONTENT_LENGTH'))
     except (ValueError, TypeError):
         content_length = 0
     self._stream = LimitedStream(self.environ['wsgi.input'],
                                  content_length)
     self._read_started = False
Beispiel #4
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', u'/'))
     if not path_info or path_info == script_name:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         #
         # (The comparison of path_info to script_name is to work around an
         # apparent bug in flup 1.0.1. See Django ticket #8490).
         path_info = u'/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     self._post_parse_error = False
     try:
         content_length = int(self.environ.get('CONTENT_LENGTH'))
     except (ValueError, TypeError):
         content_length = 0
     self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
     self._read_started = False
        def __call__(self, environ, start_response):
            if self._request_middleware is None:
                with self.initLock:
                    try:
                        if self._request_middleware is None:
                            self.load_middleware()
                    except:
                        self._request_middleware = None
                        raise

            set_script_prefix(base.get_script_name(environ))
            signals.request_started.send(sender=self.__class__)
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                log.warning('Bad Request (UnicodeDecodeError)', exc_info=sys.exc_info(), extra={'status_code': 400, })
                response = http.HttpResponseBadRequest()
            else:
                response = yield self.get_response(request)

            response._handler_class = self.__class__

            try:
                status_text = STATUS_CODE_TEXT[response.status_code]
            except KeyError:
                status_text = 'UNKNOWN STATUS CODE'
            status = '%s %s' % (response.status_code, status_text)
            response_headers = [(str(k), str(v)) for k, v in response.items()]
            for c in response.cookies.values():
                response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
            start_response(force_str(status), response_headers)
            yield response
Beispiel #6
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = base.get_path_info(environ)
     if not path_info:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         path_info = '/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/'))
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     _, content_params = self._parse_content_type(self.META.get('CONTENT_TYPE', ''))
     if 'charset' in content_params:
         try:
             codecs.lookup(content_params['charset'])
         except LookupError:
             pass
         else:
             self.encoding = content_params['charset']
     self._post_parse_error = False
     try:
         content_length = int(self.environ.get('CONTENT_LENGTH'))
     except (ValueError, TypeError):
         content_length = 0
     self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
     self._read_started = False
     self.resolver_match = None
Beispiel #7
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.

        # 这里的检测: 因为 self._request_middleware 是最后才设定的, 所以如果为空,
        # 很可能是因为 self.load_middleware() 没有调用成功.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        因为 load_middleware() 可能没有调用, 调用一次.
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        signls.request_started.send(sender=self.__class__) # __class__ 代表自己的类

        try:
            # 实例化 request_class = WSGIRequest, 将在日后文章中展开, 可以将其视为一个代表 http 请求的类
            request = self.request_class(environ)

        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            # 调用 self.get_response(), 将会返回一个相应对象 response
            response = self.get_response(request)

        # 将 self 挂钩到 response 对象
        response._handler_class = self.__class__

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'

         # 状态码
        status = '%s %s' % (response.status_code, status_text)

        response_headers = [(str(k), str(v)) for k, v in response.items()]

        # 对于每个一个 cookie, 都在 header 中设置: Set-cookie xxx=yyy
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))

        # start_response() 操作已经在上节中介绍了
        start_response(force_str(status), response_headers)

        # 成功返回相应对象
        return response
Beispiel #8
0
    def __call__(self, environ, start_response):
        from django.conf import settings

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.initLock.acquire()
            # Check that middleware is still uninitialised.
            if self._request_middleware is None:
                self.load_middleware()
            self.initLock.release()

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)

        if hasattr(response, 'sendfile_filename') and response.has_header('Content-Length'):
            del response['Content-Length']
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append(('Set-Cookie', str(c.output(header=''))))
        start_response(status, response_headers)
        if hasattr(response, 'sendfile_filename'):
            filelike = open(response.sendfile_filename, 'rb')
            block_size = response.block_size
            if 'wsgi.file_wrapper' in environ:
                return environ['wsgi.file_wrapper'](filelike, block_size)
            else:
                return iter(lambda: filelike.read(block_size), '')

        return response
Beispiel #9
0
    def __call__(self, environ, start_response):
        from django.conf import settings

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.initLock.acquire()
            try:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise
            finally:
                self.initLock.release()

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
                    exc_info=sys.exc_info(),
                    extra={
                        'status_code': 400,
                        'request': request
                    }
                )
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append(('Set-Cookie', str(c.output(header=''))))
        start_response(status, response_headers)
        return response
    def get(self):
        from tornado.wsgi import HTTPRequest, WSGIContainer
        from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT
        import urllib

        environ = WSGIContainer.environ(self.request)
        environ["PATH_INFO"] = urllib.unquote(environ["PATH_INFO"])
        request = WSGIRequest(environ)

        request._tornado_handler = self

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response:
                return

            # Apply response middleware
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = "UNKNOWN STATUS CODE"
        status = "%s %s" % (response.status_code, status_text)

        self.set_status(response.status_code)
        for h in response.items():
            self.set_header(h[0], h[1])

        """
        if not hasattr(self, "_new_cookies"):
            self._new_cookies = []
        self._new_cookies.append(response.cookies)
        """
        # Tornado 2.3 has changed the _new_cookies methods. Its not an array.
        # revert back to old method
        for c in response.cookies.values():
            self.set_header("Set-Cookie", str(c.output(header="")))

        self.write(response.content)
        self.finish()
Beispiel #11
0
	def __call__(self, environ, start_response):
		from django.conf import settings

		# Set up middleware if needed. We couldn't do this earlier, because
		# settings weren't available.
		if self._request_middleware is None:
			self.initLock.acquire()
			try:
				try:
					# Check that middleware is still uninitialised.
					if self._request_middleware is None:
						self.load_middleware()
				except:
					# Unload whatever middleware we got
					self._request_middleware = None
					raise
			finally:
				self.initLock.release()

		set_script_prefix(base.get_script_name(environ))
		signals.request_started.send(sender=self.__class__)
		try:
			try:
				request = self.request_class(environ)
			except UnicodeDecodeError:
				logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
					exc_info=sys.exc_info(),
					extra={
						'status_code': 400,
						'request': request
					}
				)
				response = http.HttpResponseBadRequest()
			else:
				response = self.get_response(request)
		finally:
			signals.request_finished.send(sender=self.__class__)

		try:
			status_text = STATUS_CODE_TEXT[response.status_code]
		except KeyError:
			status_text = 'UNKNOWN STATUS CODE'
		status = '%s %s' % (response.status_code, status_text)
		response_headers = [(str(k), str(v)) for k, v in response.items()]
		for c in response.cookies.values():
			response_headers.append(('Set-Cookie', str(c.output(header=''))))
		start_response(status, response_headers)
		return response
Beispiel #12
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', u'/'))
     if not path_info:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         path_info = u'/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
Beispiel #13
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', '/'))
     if not path_info:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         path_info = '/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
Beispiel #14
0
    def get(self) :
        from tornado.wsgi import HTTPRequest, WSGIContainer
        from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT
        import urllib

        environ  = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
        request  = WSGIRequest(environ)

        request._tornado_handler     = self

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response :
                return 

            # Apply response middleware
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)

        self.set_status(response.status_code)
        for h in response.items() :
            self.set_header(h[0], h[1])

        for c in response.cookies.values():
            self.set_header('Set-Cookie', str(c.output(header='')))

        """
        if  hasattr(self, "_new_cookies"):
            print self._new_cookies
        self._new_cookies = response.cookies
        """

        self.write(response.content)
        self.finish()
Beispiel #15
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        import sys
        settings = sys.modules["settings"]
        if not hasattr(settings, "MULTI_TENANCY_DEFAULT_SCHEMA"):
            raise (Exception(
                "It look like you forgot delcare 'MULTI_TENANCY_DEFAULT_SCHEMA' in settings.py"
            ))
        signals.request_started.send(
            sender=self.__class__,
            schema=settings.MULTI_TENANCY_DEFAULT_SCHEMA)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                           exc_info=sys.exc_info(),
                           extra={
                               'status_code': 400,
                           })
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%s %s' % (response.status_code, response.reason_phrase)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append(
                (str('Set-Cookie'), str(c.output(header=''))))
        start_response(force_str(status), response_headers)
        return response
Beispiel #16
0
	def __init__(self, environ):
		script_name = base.get_script_name(environ)
		path_info = force_unicode(environ.get('PATH_INFO', u'/'))
		if not path_info:
			# Sometimes PATH_INFO exists, but is empty (e.g. accessing
			# the SCRIPT_NAME URL without a trailing slash). We really need to
			# operate as if they'd requested '/'. Not amazingly nice to force
			# the path like this, but should be harmless.
			#
			# (The comparison of path_info to script_name is to work around an
			# apparent bug in flup 1.0.1. Se Django ticket #8490).
			path_info = u'/'
		if path_info == script_name: 
			script_name = u'' 
		self.environ = environ
		self.path_info = path_info
		self.path = '%s%s' % (script_name, path_info)
		self.META = environ
		self.META['PATH_INFO'] = path_info
		self.META['SCRIPT_NAME'] = script_name
		self.method = environ['REQUEST_METHOD'].upper()
		self._post_parse_error = False
		if type(socket._fileobject) is type and isinstance(self.environ['wsgi.input'], socket._fileobject):
			# Under development server 'wsgi.input' is an instance of
			# socket._fileobject which hangs indefinitely on reading bytes past
			# available count. To prevent this it's wrapped in LimitedStream
			# that doesn't read past Content-Length bytes.
			#
			# This is not done for other kinds of inputs (like flup's FastCGI
			# streams) beacuse they don't suffer from this problem and we can
			# avoid using another wrapper with its own .read and .readline
			# implementation.
			#
			# The type check is done because for some reason, AppEngine
			# implements _fileobject as a function, not a class.
			try:
				content_length = int(self.environ.get('CONTENT_LENGTH', 0))
			except (ValueError, TypeError):
				content_length = 0
			self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
		else:
			self._stream = self.environ['wsgi.input']
		self._read_started = False
Beispiel #17
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', u'/'))
     if not path_info or path_info == script_name:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         #
         # (The comparison of path_info to script_name is to work around an
         # apparent bug in flup 1.0.1. Se Django ticket #8490).
         path_info = u'/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     self._post_parse_error = False
     if type(socket._fileobject) is type and isinstance(
             self.environ['wsgi.input'], socket._fileobject):
         # Under development server 'wsgi.input' is an instance of
         # socket._fileobject which hangs indefinitely on reading bytes past
         # available count. To prevent this it's wrapped in LimitedStream
         # that doesn't read past Content-Length bytes.
         #
         # This is not done for other kinds of inputs (like flup's FastCGI
         # streams) beacuse they don't suffer from this problem and we can
         # avoid using another wrapper with its own .read and .readline
         # implementation.
         #
         # The type check is done because for some reason, AppEngine
         # implements _fileobject as a function, not a class.
         try:
             content_length = int(self.environ.get('CONTENT_LENGTH', 0))
         except (ValueError, TypeError):
             content_length = 0
         self._stream = LimitedStream(self.environ['wsgi.input'],
                                      content_length)
     else:
         self._stream = self.environ['wsgi.input']
     self._read_started = False
Beispiel #18
0
    def __init__(self, environ): # 要传入环境变量
        script_name = base.get_script_name(environ) # 脚本
        path_info = base.get_path_info(environ)     # 路径

        if not path_info or path_info == script_name:
            # Sometimes PATH_INFO exists, but is empty (e.g. accessing
            # the SCRIPT_NAME URL without a trailing slash). We really need to
            # operate as if they'd requested '/'. Not amazingly nice to force
            # the path like this, but should be harmless.
            #
            # (The comparison of path_info to script_name is to work around an
            # apparent bug in flup 1.0.1. See Django ticket #8490).
            path_info = '/'

        self.environ = environ
        self.path_info = path_info
        self.path = '%s%s' % (script_name, path_info)

        self.META = environ
        self.META['PATH_INFO'] = path_info
        self.META['SCRIPT_NAME'] = script_name
        self.method = environ['REQUEST_METHOD'].upper()

        _, content_params = self._parse_content_type(self.META.get('CONTENT_TYPE', '')) # 分析请求内容类型

        if 'charset' in content_params:
            try:
                codecs.lookup(content_params['charset'])
            except LookupError:
                pass
            else:
                self.encoding = content_params['charset']

        self._post_parse_error = False

        try:
            content_length = int(self.environ.get('CONTENT_LENGTH')) # 长度
        except (ValueError, TypeError):
            content_length = 0

        self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
        self._read_started = False
Beispiel #19
0
    def get(self) :
        from tornado.wsgi import HTTPRequest, WSGIContainer
        from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT
        import urllib

        environ  = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
        request  = WSGIRequest(environ)

        request._tornado_handler     = self

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response :
                return 

            # Apply response middleware
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)

        self.set_status(response.status_code)
        for h in response.items() :
            self.set_header(h[0], h[1])

        if not hasattr(self, "_new_cookies"):
            self._new_cookies = []
        self._new_cookies.append(response.cookies)

        self.write(response.content)
        self.finish()
Beispiel #20
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', '/'))
     if not path_info or path_info == script_name:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         #
         # (The comparison of path_info to script_name is to work around an
         # apparent bug in flup 1.0.1. Se Django ticket #8490).
         path_info = '/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     self._post_parse_error = False
Beispiel #21
0
 def __init__(self, environ):
     script_name = base.get_script_name(environ)
     path_info = force_unicode(environ.get('PATH_INFO', u'/'))
     if not path_info or path_info == script_name:
         # Sometimes PATH_INFO exists, but is empty (e.g. accessing
         # the SCRIPT_NAME URL without a trailing slash). We really need to
         # operate as if they'd requested '/'. Not amazingly nice to force
         # the path like this, but should be harmless.
         #
         # (The comparison of path_info to script_name is to work around an
         # apparent bug in flup 1.0.1. Se Django ticket #8490).
         path_info = u'/'
     self.environ = environ
     self.path_info = path_info
     self.path = '%s%s' % (script_name, path_info)
     self.META = environ
     self.META['PATH_INFO'] = path_info
     self.META['SCRIPT_NAME'] = script_name
     self.method = environ['REQUEST_METHOD'].upper()
     self._post_parse_error = False
Beispiel #22
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        import sys
        settings = sys.modules["settings"]
        if not hasattr(settings,"MULTI_TENANCY_DEFAULT_SCHEMA"):
            raise (Exception("It look like you forgot delcare 'MULTI_TENANCY_DEFAULT_SCHEMA' in settings.py"))
        signals.request_started.send(sender=self.__class__,schema =settings.MULTI_TENANCY_DEFAULT_SCHEMA )
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%s %s' % (response.status_code, response.reason_phrase)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
        start_response(force_str(status), response_headers)
        return response
Beispiel #23
0
    def __call__(self, environ, start_response):
        from django.conf import settings

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.initLock.acquire()
            # Check that middleware is still uninitialised.
            if self._request_middleware is None:
                self.load_middleware()
            self.initLock.release()

        set_script_prefix(base.get_script_name(environ))
        dispatcher.send(signal=signals.request_started)
        try:
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            dispatcher.send(signal=signals.request_finished)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)
        response_headers = [(str(k), str(v))
                            for k, v in list(response.items())]
        for c in list(response.cookies.values()):
            response_headers.append(('Set-Cookie', str(c.output(header=''))))
        start_response(status, response_headers)
        return response
Beispiel #24
0
    def __call__(self, environ, start_response):
        from django.conf import settings

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.initLock.acquire()
            # Check that middleware is still uninitialised.
            if self._request_middleware is None:
                self.load_middleware()
            self.initLock.release()

        set_script_prefix(base.get_script_name(environ))
        dispatcher.send(signal=signals.request_started)
        try:
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            dispatcher.send(signal=signals.request_finished)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)
        response_headers = [(str(k), str(v)) for k, v in list(response.items())]
        for c in list(response.cookies.values()):
            response_headers.append(('Set-Cookie', str(c.output(header=''))))
        start_response(status, response_headers)
        return response
Beispiel #25
0
        def __call__(self, environ, start_response):
            if self._request_middleware is None:
                with self.initLock:
                    try:
                        if self._request_middleware is None:
                            self.load_middleware()
                    except:
                        self._request_middleware = None
                        raise

            set_script_prefix(base.get_script_name(environ))
            signals.request_started.send(sender=self.__class__)
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                log.warning('Bad Request (UnicodeDecodeError)',
                            exc_info=sys.exc_info(),
                            extra={
                                'status_code': 400,
                            })
                response = http.HttpResponseBadRequest()
            else:
                response = yield self.get_response(request)

            response._handler_class = self.__class__

            try:
                status_text = STATUS_CODE_TEXT[response.status_code]
            except KeyError:
                status_text = 'UNKNOWN STATUS CODE'
            status = '%s %s' % (response.status_code, status_text)
            response_headers = [(str(k), str(v)) for k, v in response.items()]
            for c in response.cookies.values():
                response_headers.append(
                    (str('Set-Cookie'), str(c.output(header=''))))
            start_response(force_str(status), response_headers)
            yield response
Beispiel #26
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning("Bad Request (UnicodeDecodeError)", exc_info=sys.exc_info(), extra={"status_code": 400})
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = "UNKNOWN STATUS CODE"
        status = "%s %s" % (response.status_code, status_text)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str("Set-Cookie"), str(c.output(header=""))))
        start_response(force_str(status), response_headers)
        return response