コード例 #1
0
ファイル: wsgi.py プロジェクト: 0xool/DjangoTutorial
    def __call__(self, environ, start_response):
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        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 = '%d %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)
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
コード例 #2
0
ファイル: handlers.py プロジェクト: BakerWang/zulip
    def get(self, *args: Any, **kwargs: Any) -> None:
        environ = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO'])
        request = WSGIRequest(environ)
        request._tornado_handler = self

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

            if not response:
                return
        finally:
            signals.request_finished.send(sender=self.__class__)

        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 = []  # type: List[http.cookie.SimpleCookie]
        self._new_cookies.append(response.cookies)

        self.write(response.content)
        self.finish()
コード例 #3
0
ファイル: wsgi.py プロジェクト: AltSchool/django
    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:
                # Check that middleware is still uninitialized.
                if self._request_middleware is None:
                    self.load_middleware()

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        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)
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
コード例 #4
0
ファイル: http.py プロジェクト: pashinin/channels
 def handle(self, body):
     """
     Synchronous message processing.
     """
     # Set script prefix from message root_path, turning None into empty string
     set_script_prefix(self.scope.get("root_path", "") or "")
     signals.request_started.send(sender=self.__class__, scope=self.scope)
     # Run request through view system
     try:
         request = self.request_class(self.scope, body)
     except UnicodeDecodeError:
         logger.warning(
             "Bad Request (UnicodeDecodeError)",
             exc_info=sys.exc_info(),
             extra={
                 "status_code": 400,
             }
         )
         response = http.HttpResponseBadRequest()
     except RequestTimeout:
         # Parsing the rquest failed, so the response is a Request Timeout error
         response = HttpResponse("408 Request Timeout (upload too slow)", status=408)
     except RequestAborted:
         # Client closed connection on us mid request. Abort!
         return
     else:
         response = self.get_response(request)
         # Fix chunk size on file responses
         if isinstance(response, FileResponse):
             response.block_size = 1024 * 512
     # Transform response into messages, which we yield back to caller
     for response_message in self.encode_response(response):
         self.send(response_message)
     # Close the response now we're done with it
     response.close()
コード例 #5
0
 def process_request(self, request):
     base_path = request.path.split("/")[1]
     request.brand = "democracyclub"
     if base_path in settings.EMBED_PREFIXES:
         request.brand = base_path
         set_script_prefix("/%s" % base_path)
     if base_path in settings.WHITELABEL_PREFIXES:
         request.brand = base_path
コード例 #6
0
ファイル: models.py プロジェクト: feincms/feincms
def app_reverse(viewname, urlconf=None, args=None, kwargs=None, *vargs, **vkwargs):
    """
    Reverse URLs from application contents

    Works almost like Django's own reverse() method except that it resolves
    URLs from application contents. The second argument, ``urlconf``, has to
    correspond to the URLconf parameter passed in the ``APPLICATIONS`` list
    to ``Page.create_content_type``::

        app_reverse('mymodel-detail', 'myapp.urls', args=...)

        or

        app_reverse('mymodel-detail', 'myapp.urls', kwargs=...)

    The second argument may also be a request object if you want to reverse
    an URL belonging to the current application content.
    """

    # First parameter might be a request instead of an urlconf path, so
    # we'll try to be helpful and extract the current urlconf from it
    extra_context = getattr(urlconf, "_feincms_extra_context", {})
    appconfig = extra_context.get("app_config", {})
    urlconf = appconfig.get("urlconf_path", urlconf)

    appcontent_class = ApplicationContent._feincms_content_models[0]
    cache_key = appcontent_class.app_reverse_cache_key(urlconf)
    url_prefix = cache.get(cache_key)

    if url_prefix is None:
        content = appcontent_class.closest_match(urlconf)

        if content is not None:
            if urlconf in appcontent_class.ALL_APPS_CONFIG:
                # We have an overridden URLconf
                app_config = appcontent_class.ALL_APPS_CONFIG[urlconf]
                urlconf = app_config["config"].get("urls", urlconf)

            prefix = content.parent.get_absolute_url()
            prefix += "/" if prefix[-1] != "/" else ""

            url_prefix = (urlconf, prefix)
            cache.set(cache_key, url_prefix, timeout=APP_REVERSE_CACHE_TIMEOUT)

    if url_prefix:
        # vargs and vkwargs are used to send through additional parameters
        # which are uninteresting to us (such as current_app)
        prefix = get_script_prefix()
        try:
            set_script_prefix(url_prefix[1])
            return reverse(
                viewname, url_prefix[0], args=args, kwargs=kwargs, *vargs, **vkwargs
            )
        finally:
            set_script_prefix(prefix)

    raise NoReverseMatch("Unable to find ApplicationContent for %r" % urlconf)
コード例 #7
0
ファイル: models.py プロジェクト: wilbrone/Scheduler
def app_reverse(viewname, urlconf=None, args=None, kwargs=None, *vargs, **vkwargs):
    """
    Reverse URLs from application contents

    Works almost like Django's own reverse() method except that it resolves
    URLs from application contents. The second argument, ``urlconf``, has to
    correspond to the URLconf parameter passed in the ``APPLICATIONS`` list
    to ``Page.create_content_type``::

        app_reverse('mymodel-detail', 'myapp.urls', args=...)

        or

        app_reverse('mymodel-detail', 'myapp.urls', kwargs=...)

    The second argument may also be a request object if you want to reverse
    an URL belonging to the current application content.
    """

    # First parameter might be a request instead of an urlconf path, so
    # we'll try to be helpful and extract the current urlconf from it
    extra_context = getattr(urlconf, "_feincms_extra_context", {})
    appconfig = extra_context.get("app_config", {})
    urlconf = appconfig.get("urlconf_path", urlconf)

    appcontent_class = ApplicationContent._feincms_content_models[0]
    cache_key = appcontent_class.app_reverse_cache_key(urlconf)
    url_prefix = cache.get(cache_key)

    if url_prefix is None:
        content = appcontent_class.closest_match(urlconf)

        if content is not None:
            if urlconf in appcontent_class.ALL_APPS_CONFIG:
                # We have an overridden URLconf
                app_config = appcontent_class.ALL_APPS_CONFIG[urlconf]
                urlconf = app_config["config"].get("urls", urlconf)

            prefix = content.parent.get_absolute_url()
            prefix += "/" if prefix[-1] != "/" else ""

            url_prefix = (urlconf, prefix)
            cache.set(cache_key, url_prefix, timeout=APP_REVERSE_CACHE_TIMEOUT)

    if url_prefix:
        # vargs and vkwargs are used to send through additional parameters
        # which are uninteresting to us (such as current_app)
        prefix = get_script_prefix()
        try:
            set_script_prefix(url_prefix[1])
            return reverse(
                viewname, url_prefix[0], args=args, kwargs=kwargs, *vargs, **vkwargs
            )
        finally:
            set_script_prefix(prefix)

    raise NoReverseMatch("Unable to find ApplicationContent for %r" % urlconf)
コード例 #8
0
    def handle(
        self,
        output_file,
        overwrite,
        format,
        api_url,
        mock,
        user,
        private,
        info,
        urlconf,
        component=None,
        *args,
        **options,
    ):
        _version = getattr(settings, f"{component.upper()}_API_VERSION")

        # Setting must exist for vng-api-common, so monkeypatch it in
        settings.API_VERSION = _version

        if settings.SUBPATH:
            set_script_prefix(settings.SUBPATH)

        if not component:
            super().handle(
                output_file,
                overwrite,
                format,
                api_url,
                mock,
                user,
                private,
                info,
                urlconf,
                *args,
                **options,
            )

        # rewrite command arguments based on the component
        info = SCHEMA_MAPPING["info"].format(component)
        urlconf = SCHEMA_MAPPING["urlconf"].format(component)

        # generate schema
        super().handle(
            output_file,
            overwrite,
            format,
            api_url,
            mock,
            user,
            private,
            info,
            urlconf,
            *args,
            **options,
        )
コード例 #9
0
    def process_request(request):
        """ This middleware class sets a series of variables for templates
        and views to access inside the request object. It defines what site
        is being requested based on the domain:

        if settings.URL_CONFIG is set to 'domain':
            matches alias, journal, press  models by domain (in that order)
        if settings.URL_CONFIG is set to 'domain':
            matches the press by domain and journal by path. If no journal code
            is present it assumes a press site.

        :param request: the current request
        :return: None or an http 404 error in the event of catastrophic failure
        """

        journal, press, redirect_obj = get_site_resources(request)
        if redirect_obj is not None:
            return redirect_obj

        request.port = request.META['SERVER_PORT']
        request.press = press
        request.press_cover = press.press_cover(request)

        if journal is not None:
            logger.set_prefix(journal.code)
            request.journal = journal
            request.journal_cover = journal.override_cover(request)
            request.site_type = journal
            request.model_content_type = ContentType.objects.get_for_model(
                    journal)

            if settings.URL_CONFIG == 'path':
                prefix = "/" + journal.code
                logger.debug("Setting script prefix to %s" % prefix)
                set_script_prefix(prefix)
                request.path_info = request.path_info[len(prefix):]

        elif press is not None:
            logger.set_prefix("press")
            request.journal = None
            request.site_type = press
            request.model_content_type = ContentType.objects.get_for_model(press)
            request.press_base_url = press.site_url()
        else:
            raise Http404()

        # We check if the journal and press are set to be secure and redirect if the current request is not secure.
        if not request.is_secure():
            if (
                    request.journal
                    and request.journal.is_secure
                    and not settings.DEBUG
            ):
                return redirect("https://{0}{1}".format(request.get_host(), request.path))
            elif request.press.is_secure and not settings.DEBUG:
                return redirect("https://{0}{1}".format(request.get_host(), request.path))
コード例 #10
0
def script_prefix(new_prefix):
    """
    Override ``SCRIPT_NAME`` WSGI param, yield, then restore its original value.

    :param new_prefix: New ``SCRIPT_NAME`` value.
    """
    old_prefix = get_script_prefix()
    set_script_prefix(new_prefix)
    yield
    set_script_prefix(old_prefix)
コード例 #11
0
 def test_prefixes(self):
     prefixes = ["/gibbarish/", "/c/", "", "/X/"]
     for prefix in prefixes:
         set_script_prefix(prefix)
         out = Template(
             "{% load noprefix_url %}"
             "Chicken sandwich: "
             "{% noprefix_url 'day-view' '2015' '01' '01' %}").render(
                 Context())
         self.assertEqual(out,
                          "Chicken sandwich: /programme/view/2015/01/01")
コード例 #12
0
def setup(set_prefix=True):
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix('/' if settings.FORCE_SCRIPT_NAME is None else
                          settings.FORCE_SCRIPT_NAME)
    apps.populate(settings.INSTALLED_APPS)
コード例 #13
0
 def test_prefixes(self):
     prefixes = ["/gibbarish/", "/c/", "", "/X/"]
     for prefix in prefixes:
         set_script_prefix(prefix)
         out = Template(
             "{% load noprefix_url %}"
             "Chicken sandwich: "
             "{% noprefix_url 'day-view' '2015' '01' '01' %}"
         ).render(Context())
         self.assertEqual(
             out, "Chicken sandwich: /programme/view/2015/01/01")
コード例 #14
0
    def test_force_script_name(self):
        from django.urls import set_script_prefix, _prefixes
        try:
            url = reverse('django_js_urls')
            set_script_prefix("/force_script")
            response = self.client.get(url)
        finally:
            del _prefixes.value

        result = json.loads(response.content.decode())
        self.assertEqual(result['django_js_urls'],
                         '/force_script/djangojs/urls')
コード例 #15
0
    def test_force_script_name(self):
        from django.urls import set_script_prefix, _prefixes

        try:
            set_script_prefix("/force_script")
            self.result = self.get_result(
            )  # To take override_settings in account
        finally:
            del _prefixes.value

        self.assertEqual(self.result['django_js_urls'],
                         '/force_script/djangojs/urls')
コード例 #16
0
    def handle(self, **options):
        # The script prefix needs to be set here because the generated URLs
        # need to be aware of that and they are cached. Ideally Django should
        # take care of setting this up, but it doesn't yet (fixed in Django
        # 1.10): https://code.djangoproject.com/ticket/16734
        script_name = (u'/'
                       if settings.FORCE_SCRIPT_NAME is None
                       else force_unicode(settings.FORCE_SCRIPT_NAME))
        set_script_prefix(script_name)

        failed_queue = get_failed_queue()
        for job_id in failed_queue.get_job_ids():
            failed_queue.requeue(job_id=job_id)
コード例 #17
0
    def patch_script_prefix(self, script_name):
        """Patch up Django's and Piston's notion of the script_name prefix.

        This manipulates how Piston gets Django's version of script_name
        which it needs so that it can prefix script_name to URL paths.
        """
        # Patching up get_script_prefix doesn't seem to do the trick,
        # and patching it in the right module requires unwarranted
        # intimacy with Piston.  So just go through the proper call and
        # set the prefix.  But clean this up after the test or it will
        # break other tests!
        original_prefix = get_script_prefix()
        self.addCleanup(set_script_prefix, original_prefix)
        set_script_prefix(script_name)
コード例 #18
0
    def get(self, request):
        if not request.META['SCRIPT_NAME']:
            set_script_prefix('/profiles/')

        uhome = request.build_absolute_uri(reverse('user:home'))
        endpoint = uhome + 'redir'
        current_url = request.resolver_match.url_name

        return render(request, self.template_name, {
            'form': self.form_class,
            'usso_url': endpoint + '?' + urlencode({'logout': request.build_absolute_uri(uhome)}),
            'usso_base': settings.USSO_BASE,
            'usso_widget': settings.USSO_RU,
        })
コード例 #19
0
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix('/' if settings.FORCE_SCRIPT_NAME is None else
                          settings.FORCE_SCRIPT_NAME)
    apps.populate(settings.INSTALLED_APPS)
コード例 #20
0
ファイル: wsgi.py プロジェクト: 070519960/Nova-Pagina
    def __call__(self, environ, start_response):
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        request = self.request_class(environ)
        response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%d %s' % (response.status_code, response.reason_phrase)
        response_headers = list(response.items())
        for c in response.cookies.values():
            response_headers.append(('Set-Cookie', c.output(header='')))
        start_response(status, response_headers)
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
コード例 #21
0
ファイル: __init__.py プロジェクト: 9nix00/django
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS)
コード例 #22
0
    def __call__(self, request):
        if DEBUG:
            print("Lighttpd Middleware Incoming:")
            print("\t{}: {}".format('SCRIPT_NAME',
                                    request.environ['SCRIPT_NAME']))
            print("\t{}: {}".format('PATH_INFO', request.environ['PATH_INFO']))

        request.path = request.environ.get(
            'SCRIPT_NAME', '') + request.environ.get('PATH_INFO', '')

        if request.path == '//':
            request.path = '/'

        # By the time a WSGIRequest object is built by Django there is an unclear duplicity between
        # environ and META and for our two important values, attributes. So we try to deck all three
        # places these are stored. One of the drawbacks of doing this in middleware clearly. Alas.
        request.path_info = request.path
        request.script_name = ''
        request.environ['PATH_INFO'] = request.path_info
        request.environ['SCRIPT_NAME'] = ''
        request.META['PATH_INFO'] = request.path_info
        request.META['SCRIPT_NAME'] = ''

        # While I think fixing this in middleware is the appropriate thing to do it is not
        # quite as easy as fixing the wsgi interface because middleware is called a little later
        # in the cycle, in fact after the WSGIRequest object that is provided here as request,
        # is built, and in its construction Django squirrels away the SCRIPT_NAME already in an
        # internal buffer that it later uses to build urls. Grrrr. So we have to ask it to set
        # that internal buffered value as well.
        set_script_prefix(request.script_name)

        if DEBUG:
            print("Lighttpd Middleware Fixed:")
            print("\t{}: {} and {} and {}".format(
                'SCRIPT_NAME', request.environ['SCRIPT_NAME'],
                request.script_name, get_script_prefix()))
            print("\t{}: {} and {}".format('PATH_INFO',
                                           request.environ['PATH_INFO'],
                                           request.path_info))

        response = self.get_response(request)

        return response
コード例 #23
0
ファイル: wsgi.py プロジェクト: DavTho1983/UPress2
    def __call__(self, environ, start_response):
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        request = self.request_class(environ)
        response = self.get_response(request)

        response._handler_class = self.__class__

        status = "%d %s" % (response.status_code, response.reason_phrase)
        response_headers = [
            *response.items(),
            *(("Set-Cookie", c.output(header=""))
              for c in response.cookies.values()),
        ]
        start_response(status, response_headers)
        if getattr(response, "file_to_stream",
                   None) is not None and environ.get("wsgi.file_wrapper"):
            response = environ["wsgi.file_wrapper"](response.file_to_stream)
        return response
コード例 #24
0
ファイル: wsgi.py プロジェクト: nbsky/django
    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:
                # Check that middleware is still uninitialized.
                if self._request_middleware is None:
                    self.load_middleware()

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        try:
            #这一步完成了wsgi的environ原始的数据的封装,封装成了django定义的request对象,把各种header body打包进request
            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:
            #request进去response出来,response并不能直接返回,按照wsgi,把response拆成(http body)和(status code + header)两部分
            response = self.get_response(request)

        response._handler_class = self.__class__

        #剥离出status code
        status = '%s %s' % (response.status_code, response.reason_phrase)
        #剥离出headers
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        #header加上set-cookies,其实也是header的一部分,只是response单独放cookies属性里面
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
        #wsgi第一步:实现了包含http状态码和header两个参数的函数调用完成了wsgi的其中一步
        start_response(force_str(status), response_headers)
        # TODO是文件流要特殊处理,具体如何处理
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        #wsgi第二步:返回可迭代body
        return response
コード例 #25
0
ファイル: forms.py プロジェクト: rmoch/pootle
def update_translation_project(tp, initialize_from_templates, response_url):
    """Wraps translation project initializing to allow it to be running
    as RQ job.
    """
    script_name = (u'/' if settings.FORCE_SCRIPT_NAME is None else
                   force_unicode(settings.FORCE_SCRIPT_NAME))
    set_script_prefix(script_name)

    try:
        with useable_connection():
            if initialize_from_templates:
                tp.init_from_templates()
            else:
                tp.update_from_disk()
    except Exception as e:
        tp_init_failed_async.send(sender=tp.__class__, instance=tp)
        raise e
    tp_inited_async.send(sender=tp.__class__,
                         instance=tp,
                         response_url=response_url)
コード例 #26
0
ファイル: tasks.py プロジェクト: Phdmani/crate
def process_contact_request(contact_request_id: int) -> None:
    """
    Celery task to act on a contact request. For example, might send an e-mail
    to a clinician, or generate a letter to the researcher.

    Callers include
    - :meth:`crate_anon.crateweb.consent.models.ContactRequest.create`

    Sets ``processed = True`` and ``processed_at`` for the
    :class:`crate_anon.crateweb.consent.models.ContactRequest`.

    Args:
        contact_request_id: PK of the contact request
    """
    from crate_anon.crateweb.consent.models import ContactRequest  # delayed import  # noqa
    log.debug("process_contact_request")
    set_script_prefix(settings.FORCE_SCRIPT_NAME)  # see site_absolute_url
    contact_request = ContactRequest.objects.get(
        pk=contact_request_id)  # type: ContactRequest  # noqa
    contact_request.process_request()
コード例 #27
0
ファイル: forms.py プロジェクト: SafaAlfulaij/pootle
def update_translation_project(tp, initialize_from_templates, response_url):
    """Wraps translation project initializing to allow it to be running
    as RQ job.
    """
    script_name = (u'/'
                   if settings.FORCE_SCRIPT_NAME is None
                   else force_unicode(settings.FORCE_SCRIPT_NAME))
    set_script_prefix(script_name)

    try:
        with useable_connection():
            if initialize_from_templates:
                tp.init_from_templates()
            else:
                tp.update_from_disk()
    except Exception as e:
        tp_init_failed_async.send(sender=tp.__class__, instance=tp)
        raise e
    tp_inited_async.send(sender=tp.__class__,
                         instance=tp, response_url=response_url)
コード例 #28
0
 async def __call__(self, scope, receive, send):
     """
     Async entrypoint - parses the request and hands off to get_response.
     """
     # Serve only HTTP connections.
     # FIXME: Allow to override this.
     if scope['type'] != 'http':
         raise ValueError(
             'Django can only handle ASGI/HTTP connections, not %s.' %
             scope['type'])
     # Receive the HTTP request body as a stream object.
     try:
         body_file = await self.read_body(receive)
     except RequestAborted:
         return
     # Request is complete and can be served.
     set_script_prefix(self.get_script_prefix(scope))
     await sync_to_async(signals.request_started.send
                         )(sender=self.__class__, scope=scope)
     # Get the request and check for basic issues.
     request, error_response = self.create_request(scope, body_file)
     if request is None:
         await self.send_response(error_response, send)
         return
     # Get the response, using the async mode of BaseHandler.
     response = await self.get_response_async(request)
     response._handler_class = self.__class__
     # Increase chunk size on file responses (ASGI servers handles low-level
     # chunking).
     if isinstance(response, FileResponse):
         response.block_size = self.chunk_size
     # Send the response.
     if response.streaming:
         await run_until_first_complete((self.send_response, {
             "response": response,
             "send": send
         }), (self.listen_for_disconnect, {
             "receive": receive
         }))
     else:
         await self.send_response(response, send)
コード例 #29
0
ファイル: wsgi.py プロジェクト: 99amruthap/webBackendVibhor
    def __call__(self, environ, start_response):
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        request = self.request_class(environ)
        response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%d %s' % (response.status_code, response.reason_phrase)
        response_headers = [
            *response.items(),
            *(('Set-Cookie', c.output(header='')) for c in response.cookies.values()),
        ]
        start_response(status, response_headers)
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            # If `wsgi.file_wrapper` is used the WSGI server does not call
            # .close on the response, but on the file wrapper. Patch it to use
            # response.close instead which takes care of closing all files.
            response.file_to_stream.close = response.close
            response = environ['wsgi.file_wrapper'](response.file_to_stream, response.block_size)
        return response
コード例 #30
0
ファイル: handlers.py プロジェクト: xaoei/zulip
    def convert_tornado_request_to_django_request(self) -> HttpRequest:
        # This takes the WSGI environment that Tornado received (which
        # fully describes the HTTP request that was sent to Tornado)
        # and pass it to Django's WSGIRequest to generate a Django
        # HttpRequest object with the original Tornado request's HTTP
        # headers, parameters, etc.
        environ = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO'])

        # Django WSGIRequest setup code that should match logic from
        # Django's WSGIHandler.__call__ before the call to
        # `get_response()`.
        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        request = WSGIRequest(environ)

        # Provide a way for application code to access this handler
        # given the HttpRequest object.
        request._tornado_handler = self

        return request
コード例 #31
0
 def __call__(self, message):
     # Set script prefix from message root_path, turning None into empty string
     set_script_prefix(message.get('root_path', '') or '')
     signals.request_started.send(sender=self.__class__, message=message)
     # Run request through view system
     try:
         request = self.request_class(message)
     except UnicodeDecodeError:
         logger.warning('Bad Request (UnicodeDecodeError)',
                        exc_info=sys.exc_info(),
                        extra={
                            'status_code': 400,
                        })
         response = http.HttpResponseBadRequest()
     except RequestTimeout:
         # Parsing the rquest failed, so the response is a Request Timeout error
         response = HttpResponse("408 Request Timeout (upload too slow)",
                                 status=408)
     except RequestAborted:
         # Client closed connection on us mid request. Abort!
         return
     else:
         try:
             response = self.get_response(request)
             # Fix chunk size on file responses
             if isinstance(response, FileResponse):
                 response.block_size = 1024 * 512
         except AsgiRequest.ResponseLater:
             # The view has promised something else
             # will send a response at a later time
             return
         if response.status_code == HttpResponseLater.status_code:
             # equal to ResponseLater exception above
             return
     # Transform response into messages, which we yield back to caller
     for message in self.encode_response(response):
         # TODO: file_to_stream
         yield message
     # Close the response now we're done with it
     response.close()
コード例 #32
0
ファイル: application.py プロジェクト: mraleson/rag
    def setup(self, set_prefix=True):
        # don't allow DJANGO_SETTINGS_MODULE because it loads settings differently than settings.configure (see dj docs)
        if "DJANGO_SETTINGS_MODULE" in os.environ:
            raise RuntimeError('DJANGO_SETTINGS_MODULE environment variable is not supported.')

        # load settings
        if isinstance(self.settings, str):
            module = importlib.import_module(self.settings)
            self.settings = {k: getattr(module, k) for k in dir(module) if not k.startswith('_') and k.isupper()}

        # inject urls into settings
        self.settings['ROOT_URLCONF'] = self.urls

        # inject root asgi app setting
        if 'ASGI_APPLICATION' not in self.settings:
            self.settings['ASGI_APPLICATION'] = find_asgi_path()

        # set default migrations module
        if 'MIGRATIONS_MODULES' not in self.settings and importlib.util.find_spec('migrations'):
            self.settings['MIGRATION_MODULES'] = {self.app: 'migrations'}

        # add this application to installed apps
        self.settings['INSTALLED_APPS'] = [self.app] + self.settings.get('INSTALLED_APPS', default.INSTALLED_APPS)

        # configure settings
        settings.configure(default, **self.settings)

        # configure logging
        configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)

        # set prefix
        if set_prefix:
            set_script_prefix('/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME)

        # populate apps
        apps.populate(settings.INSTALLED_APPS)

        # setup urls
        self.urls.setup()
コード例 #33
0
 def handle(self, scope, send, body):
     """
     Synchronous message processing.
     """
     # Set script prefix from message root_path, turning None into empty string
     script_prefix = scope.get("root_path", "") or ""
     if settings.FORCE_SCRIPT_NAME:
         script_prefix = settings.FORCE_SCRIPT_NAME
     set_script_prefix(script_prefix)
     signals.request_started.send(sender=self.__class__, scope=scope)
     # Run request through view system
     try:
         request = self.request_class(scope, body)
     except UnicodeDecodeError:
         logger.warning(
             "Bad Request (UnicodeDecodeError)",
             exc_info=sys.exc_info(),
             extra={"status_code": 400},
         )
         response = http.HttpResponseBadRequest()
     except RequestTimeout:
         # Parsing the request failed, so the response is a Request Timeout error
         response = HttpResponse("408 Request Timeout (upload too slow)",
                                 status=408)
     except RequestAborted:
         # Client closed connection on us mid request. Abort!
         return
     except RequestDataTooBig:
         response = HttpResponse("413 Payload too large", status=413)
     else:
         response = self.get_response(request)
         # Fix chunk size on file responses
         if isinstance(response, FileResponse):
             response.block_size = 1024 * 512
     # Transform response into messages, which we yield back to caller
     for response_message in self.encode_response(response):
         send(response_message)
     # Close the response now we're done with it
     response.close()
コード例 #34
0
ファイル: __init__.py プロジェクト: suosuo1930/parse_django
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
        配置设置(这是访问的副作用
        配置日志并填充应用注册表。
        如果' set_prefix '为真,则设置线程本地 rlresolvers 脚本前缀
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)  # 配置 日志 设置

    if set_prefix:
        #
        # 参数为 '/'
        set_script_prefix('/' if settings.FORCE_SCRIPT_NAME is None else
                          settings.FORCE_SCRIPT_NAME)
    apps.populate(settings.INSTALLED_APPS)  # 开始 填充
コード例 #35
0
ファイル: handler.py プロジェクト: Krukov/channels
 def __call__(self, message):
     # Set script prefix from message root_path, turning None into empty string
     set_script_prefix(message.get('root_path', '') or '')
     signals.request_started.send(sender=self.__class__, message=message)
     # Run request through view system
     try:
         request = self.request_class(message)
     except UnicodeDecodeError:
         logger.warning(
             'Bad Request (UnicodeDecodeError)',
             exc_info=sys.exc_info(),
             extra={
                 'status_code': 400,
             }
         )
         response = http.HttpResponseBadRequest()
     except RequestTimeout:
         # Parsing the rquest failed, so the response is a Request Timeout error
         response = HttpResponse("408 Request Timeout (upload too slow)", status=408)
     except RequestAborted:
         # Client closed connection on us mid request. Abort!
         return
     else:
         try:
             response = self.get_response(request)
             # Fix chunk size on file responses
             if isinstance(response, FileResponse):
                 response.block_size = 1024 * 512
         except AsgiRequest.ResponseLater:
             # The view has promised something else
             # will send a response at a later time
             return
     # Transform response into messages, which we yield back to caller
     for message in self.encode_response(response):
         # TODO: file_to_stream
         yield message
     # Close the response now we're done with it
     response.close()
コード例 #36
0
 async def __call__(self, scope, receive, send):
     """
     Async entrypoint - parses the request and hands off to get_response.
     """
     # Serve only HTTP connections.
     # FIXME: Allow to override this.
     if scope['type'] != 'http':
         raise ValueError(
             'Django can only handle ASGI/HTTP connections, not %s.' %
             scope['type'])
     # Receive the HTTP request body as a stream object.
     try:
         body_file = await self.read_body(receive)
     except RequestAborted:
         return
     # Request is complete and can be served.
     set_script_prefix(self.get_script_prefix(scope))
     await sync_to_async(signals.request_started.send
                         )(sender=self.__class__, scope=scope)
     # Get the request and check for basic issues.
     request, error_response = self.create_request(scope, body_file)
     if request is None:
         await self.send_response(error_response, send)
         return
     # Get the response, using a threadpool via sync_to_async, if needed.
     if asyncio.iscoroutinefunction(self.get_response):
         response = await self.get_response(request)
     else:
         # If get_response is synchronous, run it non-blocking.
         response = await sync_to_async(self.get_response)(request)
     response._handler_class = self.__class__
     # Increase chunk size on file responses (ASGI servers handles low-level
     # chunking).
     if isinstance(response, FileResponse):
         response.block_size = self.chunk_size
     # Send the response.
     await self.send_response(response, send)
コード例 #37
0
    def __call__(self, environ, start_response):

        # Generate a compatible url from the ROOT_SUBDIRECTORY_PATH
        pre_path = django.conf.settings.ROOT_SUBDIRECTORY_PATH
        if len(pre_path):
            # Confirm that the first character is a forward slash
            if pre_path[0] != '/':
                # No, insert a forward slash
                pre_path = "/" + pre_path

            # Confirm that the last character is not a forward slash
            if pre_path[-1] == '/':
                # Remove the forward slash
                pre_path = pre_path[:-1]

        # Override the environment paths
        #environ['RAW_URI'] = "{}{}".format(pre_path, environ['RAW_URI'])
        #environ['PATH_INFO'] = "{}{}".format(pre_path, environ['PATH_INFO'])

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        request = self.request_class(environ)

        response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%d %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)
        if getattr(response, 'file_to_stream',
                   None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
コード例 #38
0
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    import threading
    ct = threading.current_thread()
    print('【django.__init__.setup】当前线程:', ct.name, ct.ident)

    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix('/' if settings.FORCE_SCRIPT_NAME is None else
                          settings.FORCE_SCRIPT_NAME)
    # 这个 apps 是 django.apps.registry.Apps 类的实例,叫做「应用收集对象」
    # 这里调用 populate 方法将项目的配置项 INSTALLED_APPS 中的应用都放到实例自身的 app_configs 属性字典中
    # key 就是 INSTALLED_APPS 列表里的字符串
    # value 是 django.apps.config.AppConfig 类的实例,此实例就是应用对象
    apps.populate(settings.INSTALLED_APPS)
コード例 #39
0
ファイル: utils.py プロジェクト: matason/django
 def __enter__(self):
     set_script_prefix(self.prefix)
コード例 #40
0
 def tearDown(self):
     urlresolvers.clean_url_prefixes()
     set_script_prefix('/')
     super(TestPrefixer, self).tearDown()
コード例 #41
0
ファイル: test_urls.py プロジェクト: FlaviaBastos/pretix
def test_site_url_subpath():
    settings.SITE_URL = 'https://example.com/presale'
    old_prefix = urls.get_script_prefix()
    urls.set_script_prefix('/presale/')
    assert build_absolute_uri('control:auth.login') == 'https://example.com/presale/control/login'
    urls.set_script_prefix(old_prefix)
コード例 #42
0
ファイル: utils.py プロジェクト: AmineYaiche/django
 def disable(self):
     set_script_prefix(self.old_prefix)
コード例 #43
0
ファイル: utils.py プロジェクト: AmineYaiche/django
 def enable(self):
     self.old_prefix = get_script_prefix()
     set_script_prefix(self.prefix)
コード例 #44
0
 def disable(self):
     set_script_prefix(self.old_prefix)
コード例 #45
0
 def enable(self):
     self.old_prefix = get_script_prefix()
     set_script_prefix(self.prefix)
コード例 #46
0
 def tearDown(self):
     set_script_prefix(self._initial_prefix)
コード例 #47
0
ファイル: utils.py プロジェクト: matason/django
 def __exit__(self, exc_type, exc_val, traceback):
     set_script_prefix(self.old_prefix)
コード例 #48
0
ファイル: utils.py プロジェクト: ierror/django-js-reverse
 def __exit__(self, type, value, traceback):
     set_script_prefix(self.oldprefix)
コード例 #49
0
ファイル: utils.py プロジェクト: ierror/django-js-reverse
 def __enter__(self):
     set_script_prefix(self.newpath)