Exemplo n.º 1
0
def technical_500_response(request, exc_type, exc_value, tb, status_code=500):
    """
    Create a technical server error response. The last three arguments are
    the values returned from sys.exc_info() and friends.
    """
    reporter = ExceptionReporter(request, exc_type, exc_value, tb)
    if request.is_ajax():
        text = reporter.get_traceback_text()
        return HttpResponse(text,
                            status=status_code,
                            content_type='text/plain; charset=utf-8')
    else:
        html = reporter.get_traceback_html()
        return HttpResponse(html, status=status_code, content_type='text/html')
Exemplo n.º 2
0
def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    server.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)
Exemplo n.º 3
0
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={
            'i18n': 'server.templatetags.i18n'
        }).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
        c = Context()
    else:
        c = {}
    files = []
    for f in fullpath.iterdir():
        if not f.name.startswith('.'):
            url = str(f.relative_to(fullpath))
            if f.is_dir():
                url += '/'
            files.append(url)
    c.update({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c))
Exemplo n.º 4
0
def render_to_kmz(*args, **kwargs):
    """
    Compress the KML content and return as KMZ (using the correct
    MIME type).
    """
    return HttpResponse(
        compress_kml(loader.render_to_string(*args, **kwargs)),
        content_type='application/vnd.google-earth.kmz',
    )
Exemplo n.º 5
0
def default_urlconf(request):
    """Create an empty URLconf 404 error response."""
    with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
        t = DEBUG_ENGINE.from_string(fh.read())
    c = Context({
        'version': get_docs_version(),
    })

    return HttpResponse(t.render(c), content_type='text/html')
Exemplo n.º 6
0
def _precondition_failed(request):
    response = HttpResponse(status=412)
    log_response(
        'Precondition Failed: %s',
        request.path,
        response=response,
        request=request,
    )
    return response
Exemplo n.º 7
0
def respond(requests):
    '''
    Get HTTP message from socket in requests queue.
    Send response, close connection, repeat.
    '''

    connectionSocket, clientAddress = requests.get()
    message = connectionSocket.recv(4096).decode('utf-8')
    connectionSocket.send(str(HttpResponse(message)).encode('utf-8'))
    connectionSocket.close()
Exemplo n.º 8
0
def render_to_response(template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    server.template.loader.render_to_string() with the passed arguments.
    """
    warnings.warn(
        'render_to_response() is deprecated in favor of render(). It has the '
        'same signature except that it also requires a request.',
        RemovedInServer30Warning, stacklevel=2,
    )
    content = loader.render_to_string(template_name, context, using=using)
    return HttpResponse(content, content_type, status)
Exemplo n.º 9
0
    def render_to_response(self, context, **response_kwargs):
        def indent(s):
            return s.replace('\n', '\n  ')

        template = Engine().from_string(js_catalog_template)
        context['catalog_str'] = indent(
            json.dumps(context['catalog'], sort_keys=True,
                       indent=2)) if context['catalog'] else None
        context['formats_str'] = indent(
            json.dumps(context['formats'], sort_keys=True, indent=2))

        return HttpResponse(template.render(Context(context)),
                            'text/javascript; charset="utf-8"')
Exemplo n.º 10
0
 def __call__(self, request, *args, **kwargs):
     try:
         obj = self.get_object(request, *args, **kwargs)
     except ObjectDoesNotExist:
         raise Http404('Feed object does not exist.')
     feedgen = self.get_feed(obj, request)
     response = HttpResponse(content_type=feedgen.content_type)
     if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
         # if item_pubdate or item_updateddate is defined for the feed, set
         # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
         response['Last-Modified'] = http_date(
             timegm(feedgen.latest_post_date().utctimetuple()))
     feedgen.write(response, 'utf-8')
     return response
Exemplo n.º 11
0
def render_javascript_catalog(catalog=None, plural=None):
    template = Engine().from_string(js_catalog_template)

    def indent(s):
        return s.replace('\n', '\n  ')

    context = Context({
        'catalog_str':
        indent(json.dumps(catalog, sort_keys=True, indent=2))
        if catalog else None,
        'formats_str':
        indent(json.dumps(get_formats(), sort_keys=True, indent=2)),
        'plural':
        plural,
    })

    return HttpResponse(template.render(context), 'text/javascript')
Exemplo n.º 12
0
def set_language(request):
    """
    Redirect to a given URL while setting the chosen language in the session
    (if enabled) and in a cookie. The URL and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax())
            and not is_safe_url(url=next,
                                allowed_hosts={request.get_host()},
                                require_https=request.is_secure())):
        next = request.META.get('HTTP_REFERER')
        next = next and unquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next,
                           allowed_hosts={request.get_host()},
                           require_https=request.is_secure()):
            next = '/'
    response = HttpResponseRedirect(next) if next else HttpResponse(status=204)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            if next:
                next_trans = translate_url(next, lang_code)
                if next_trans != next:
                    response = HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            response.set_cookie(
                settings.LANGUAGE_COOKIE_NAME,
                lang_code,
                max_age=settings.LANGUAGE_COOKIE_AGE,
                path=settings.LANGUAGE_COOKIE_PATH,
                domain=settings.LANGUAGE_COOKIE_DOMAIN,
            )
    return response
Exemplo n.º 13
0
def render_to_kml(*args, **kwargs):
    "Render the response as KML (using the correct MIME type)."
    return HttpResponse(
        loader.render_to_string(*args, **kwargs),
        content_type='application/vnd.google-earth.kml+xml',
    )
Exemplo n.º 14
0
 def options(self, request, *args, **kwargs):
     """Handle responding to requests for the OPTIONS HTTP verb."""
     response = HttpResponse()
     response['Allow'] = ', '.join(self._allowed_methods())
     response['Content-Length'] = '0'
     return response