Python django.http.response.HttpResponse() Examples

The following are 30 code examples of django.http.response.HttpResponse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.http.response , or try the search function .
Example #1
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def remove(self, request: WSGIRequest) -> HttpResponse:
        """Removes a song identified by the given key from the queue."""
        key = request.POST.get("key")
        if key is None:
            return HttpResponseBadRequest()
        ikey = int(key)
        try:
            removed = self.playback.queue.remove(ikey)
            self.playback.queue_semaphore.acquire(blocking=False)
            # if we removed a song and it was added by autoplay,
            # we want it to be the new basis for autoplay
            if not removed.manually_requested:
                self.playback.handle_autoplay(removed.external_url or removed.title)
            else:
                self.playback.handle_autoplay()
        except models.QueuedSong.DoesNotExist:
            return HttpResponseBadRequest("song does not exist")
        return HttpResponse() 
Example #2
Source File: csp.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def csp_report_view(request):
    global generic_related
    report_json = request.body.decode('utf8')
    report = json.loads(report_json)
    resp = HttpResponse()

    if ('script-sample' in report['csp-report']
            and 'var t=0,e=function(t,e){ret' in report['csp-report']['script-sample']) or \
            ('script-sample' in report['csp-report'] and report['csp-report']['script-sample'] == ';undefined'):
        # firefox browser plugin injection?
        return resp

    if generic_related is None:
        generic_related = Unit.objects.get(slug='univ')
    userid = request.user.username if request.user.is_authenticated else '_anon'
    l = LogEntry(userid=userid, description='CSP violation', comment=report_json, related_object=generic_related)
    l.save()

    if settings.DEBUG:
        print(json.dumps(report, indent=2))

    return resp 
Example #3
Source File: export_utils.py    From seqr with GNU Affero General Public License v3.0 6 votes vote down vote up
def export_multiple_files(files, zip_filename, file_format='csv', add_header_prefix=False, blank_value=''):
    if file_format not in DELIMITERS:
        raise ValueError('Invalid file_format: {}'.format(file_format))
    with NamedTemporaryFile() as temp_file:
        with zipfile.ZipFile(temp_file, 'w') as zip_file:
            for filename, header, rows in files:
                header_display = header
                if add_header_prefix:
                    header_display = ['{}-{}'.format(str(header_tuple[0]).zfill(2), header_tuple[1]) for header_tuple in enumerate(header)]
                    header_display[0] = header[0]
                content = DELIMITERS[file_format].join(header_display) + '\n'
                content += '\n'.join([
                    DELIMITERS[file_format].join([row.get(key) or blank_value for key in header]) for row in rows
                ])
                if isinstance(content, str):
                    content = content.encode('utf-8')
                content = str(content, 'ascii', errors='ignore') # Strip unicode chars in the content
                zip_file.writestr('{}.{}'.format(filename, file_format), content)
        temp_file.seek(0)
        response = HttpResponse(temp_file, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename="{}.zip"'.format(zip_filename).encode('ascii', 'ignore')
        return response 
Example #4
Source File: data_export_views.py    From intake with MIT License 6 votes vote down vote up
def csv_download(request):
    """ Creates a CSV file using all of the applications to the users
    organization.
    """
    apps = get_all_applications_for_users_org(request.user)
    data = ApplicationCSVDownloadSerializer(apps, many=True).data
    fields = []
    for datum in data:
        these_fields = list(datum.keys())
        # Finds the largest set of fields and uses it
        # There should not be a case where a smaller set of fields would have
        # a field not in a larger one.
        if len(these_fields) > len(fields):
            fields = these_fields
    response = HttpResponse(content_type='text/csv')
    csv_writer = csv.DictWriter(response, fieldnames=fields)
    csv_writer.writeheader()
    csv_writer.writerows(data)
    file = 'all_applications_to_%s_%s.csv' % (
        request.user.profile.organization.slug,
        timezone.now().strftime('%m-%d-%Y'),
    )
    response['Content-Disposition'] = 'attachment; filename="%s"' % file
    return response 
Example #5
Source File: __init__.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _patch_get_response():
    # type: () -> None
    """
    patch get_response, because at that point we have the Django request object
    """
    from django.core.handlers.base import BaseHandler

    old_get_response = BaseHandler.get_response

    def sentry_patched_get_response(self, request):
        # type: (Any, WSGIRequest) -> Union[HttpResponse, BaseException]
        _before_get_response(request)
        return old_get_response(self, request)

    BaseHandler.get_response = sentry_patched_get_response

    if hasattr(BaseHandler, "get_response_async"):
        from sentry_sdk.integrations.django.asgi import patch_get_response_async

        patch_get_response_async(BaseHandler, _before_get_response) 
Example #6
Source File: android_app.py    From heltour with MIT License 6 votes vote down vote up
def fcm_register(request):
    args = json.loads(request.body.decode('utf-8'))
    slack_token = args.get('slack_token')
    reg_id = args.get('reg_id')

    url = 'https://slack.com/api/auth.test'
    r = requests.get(url, params={'token': slack_token})
    slack_user_id = r.json().get('user_id')
    if not slack_user_id:
        logger.warning('Couldn\'t validate slack token for FCM registration')
        return HttpResponse('Could not validate slack token', status=400)

    FcmSub.objects.update_or_create(reg_id=reg_id, defaults={'slack_user_id': slack_user_id})
    logger.warning('FCM registration complete for %s %s' % (slack_user_id, reg_id))

    return HttpResponse('ok') 
Example #7
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def reorder(self, request: WSGIRequest) -> HttpResponse:
        """Reorders the queue.
        The song specified by element is inserted between prev and next."""
        prev_key = request.POST.get("prev")
        cur_key = request.POST.get("element")
        next_key = request.POST.get("next")
        if not cur_key:
            return HttpResponseBadRequest()
        if not prev_key:
            iprev_key = None
        else:
            iprev_key = int(prev_key)
        icur_key = int(cur_key)
        if not next_key:
            inext_key = None
        else:
            inext_key = int(next_key)
        try:
            self.playback.queue.reorder(iprev_key, icur_key, inext_key)
        except ValueError:
            return HttpResponseBadRequest("request on old state")
        return HttpResponse() 
Example #8
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def disabled_when_voting(func: Callable) -> Callable:
    """A decorator for controls that are disabled during voting.
    Only users with appropriate privileges are still able to perform this action."""

    def _decorator(
        self: "Controller", request: WSGIRequest, *args, **kwargs
    ) -> HttpResponse:
        if (
            self.musiq.base.settings.basic.voting_system
            and not self.musiq.base.user_manager.has_controls(request.user)
        ):
            return HttpResponseForbidden()
        func(self, request, *args, **kwargs)
        self.musiq.update_state()
        return HttpResponse()

    return wraps(func)(_decorator) 
Example #9
Source File: spotify.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def request_radio(self, request_ip: str) -> HttpResponse:
        result = self.web_client.get(
            "recommendations",
            params={
                "limit": self.musiq.base.settings.basic.max_playlist_items,
                "market": "from_token",
                "seed_tracks": self.id,
            },
        )

        for track in result["tracks"]:
            external_url = track["external_urls"]["spotify"]
            self.musiq.do_request_music(
                "",
                external_url,
                None,
                False,
                "spotify",
                archive=False,
                manually_requested=False,
            )

        return HttpResponse("queueing radio") 
Example #10
Source File: views.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def generate_toml(request):
    """Generate the TOML file."""
    toml_dict = {
        "ACCOUNTS": [
            asset.distribution_account
            for asset in Asset.objects.exclude(distribution_seed__isnull=True)
        ],
        "VERSION": "0.1.0",
        "SIGNING_KEY": settings.SIGNING_KEY,
        "NETWORK_PASSPHRASE": settings.STELLAR_NETWORK_PASSPHRASE,
    }

    if "sep-24" in django_settings.ACTIVE_SEPS:
        toml_dict["TRANSFER_SERVER"] = os.path.join(settings.HOST_URL, "sep24")
        toml_dict["TRANSFER_SERVER_SEP0024"] = toml_dict["TRANSFER_SERVER"]
    if "sep-6" in django_settings.ACTIVE_SEPS:
        toml_dict["TRANSFER_SERVER"] = os.path.join(settings.HOST_URL, "sep6")
    if "sep-10" in django_settings.ACTIVE_SEPS:
        toml_dict["WEB_AUTH_ENDPOINT"] = os.path.join(settings.HOST_URL, "auth")
    if "sep-12" in django_settings.ACTIVE_SEPS:
        toml_dict["KYC_SERVER"] = os.path.join(settings.HOST_URL, "kyc")

    toml_dict.update(registered_toml_func())

    return HttpResponse(toml.dumps(toml_dict), content_type="text/plain") 
Example #11
Source File: musiq.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def request_radio(self, request: WSGIRequest) -> HttpResponse:
        """Endpoint to request radio for the current song."""
        # only get ip on user requests
        if self.base.settings.basic.logging_enabled:
            request_ip, _ = ipware.get_client_ip(request)
            if request_ip is None:
                request_ip = ""
        else:
            request_ip = ""

        try:
            current_song = CurrentSong.objects.get()
        except CurrentSong.DoesNotExist:
            return HttpResponseBadRequest("Need a song to play the radio")
        provider = SongProvider.create(self, external_url=current_song.external_url)
        return provider.request_radio(request_ip) 
Example #12
Source File: suggestions.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def random_suggestion(cls, request: WSGIRequest) -> HttpResponse:
        """This method returns a random suggestion from the database.
        Depending on the value of :param playlist:,
        either a previously pushed playlist or song is returned."""
        suggest_playlist = request.GET["playlist"] == "true"
        if not suggest_playlist:
            if ArchivedSong.objects.count() == 0:
                return HttpResponseBadRequest("No songs to suggest from")
            index = random.randint(0, ArchivedSong.objects.count() - 1)
            song = ArchivedSong.objects.all()[index]
            return JsonResponse({"suggestion": song.displayname(), "key": song.id})

        # exclude radios from suggestions
        remaining_playlists = (
            ArchivedPlaylist.objects.all()
            .exclude(list_id__startswith="RD")
            .exclude(list_id__contains="&list=RD")
        )
        if remaining_playlists.count() == 0:
            return HttpResponseBadRequest("No playlists to suggest from")
        index = random.randint(0, remaining_playlists.count() - 1)
        playlist = remaining_playlists.all()[index]
        return JsonResponse({"suggestion": playlist.title, "key": playlist.id}) 
Example #13
Source File: test_utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_enterprise_customer_cookie_empty_cookie_domain(self):
        """
        Verify that enterprise cookie is not set if base_cookie_domain is empty
        in site configuration.
        """
        self.site.siteconfiguration.base_cookie_domain = ''
        self.site.siteconfiguration.save()

        enterprise_customer_uuid = uuid.uuid4()
        response = HttpResponse()

        result = set_enterprise_customer_cookie(self.site, response, enterprise_customer_uuid)

        self.assertNotIn(settings.ENTERPRISE_CUSTOMER_COOKIE_NAME, result.cookies) 
Example #14
Source File: views.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get(self, request, content_disposition_type="inline", *args, **kwargs):
        if USE_X_ACCEL_REDIRECT:
            response = HttpResponse('')
            if X_ACCEL_REDIRECT_PREFIX is not None:
                first_path_element = re.compile("^/([^/]*)/").search(request.path).group(1)
                request.path = request.path.replace(first_path_element, X_ACCEL_REDIRECT_PREFIX, 1)
            response['X-Accel-Redirect'] = request.path
            response['Content-Type'] = ''

        else:
            response = serve(request, request.path, settings.FILES_DIR)

        return response 
Example #15
Source File: test_decorators.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def _mock_view(*args, **kwargs):  # pylint: disable=unused-argument
        """
        Mock django view to use for testing decorator.
        """
        return HttpResponse() 
Example #16
Source File: test_utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_enterprise_customer_cookie(self):
        """
        Verify that enterprise cookies are set properly.
        """
        enterprise_customer_uuid = uuid.uuid4()
        response = HttpResponse()

        result = set_enterprise_customer_cookie(self.site, response, enterprise_customer_uuid)

        cookie = result.cookies[settings.ENTERPRISE_CUSTOMER_COOKIE_NAME]
        self.assertEqual(str(enterprise_customer_uuid), cookie.value) 
Example #17
Source File: views.py    From dash-django-example with MIT License 5 votes vote down vote up
def dash_json(request, **kwargs):
    """Handle Dash JSON API requests"""
    print(request.get_full_path())
    return HttpResponse(dispatcher(request), content_type='application/json') 
Example #18
Source File: urls.py    From boss-oidc with Apache License 2.0 5 votes vote down vote up
def protected(request):
    return HttpResponse("protected") 
Example #19
Source File: middleware.py    From django-request-token with MIT License 5 votes vote down vote up
def process_exception(
        self, request: HttpRequest, exception: Exception
    ) -> HttpResponse:
        """Handle all InvalidTokenErrors."""
        if isinstance(exception, InvalidTokenError):
            logger.exception("JWT request token error")
            response = _403(request, exception)
            if getattr(request, "token", None):
                request.token.log(request, response, error=exception)
            return response 
Example #20
Source File: views.py    From My_Dashboard with MIT License 5 votes vote down vote up
def dash(request, **kwargs):
    return HttpResponse(dispatcher(request)) 
Example #21
Source File: test_api.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_fatal_code(self):
        response_with_200 = HttpResponse(status=200)
        response_with_429 = HttpResponse(status=429)
        response_with_504 = HttpResponse(status=504)
        self.assertTrue(self.loader_class._fatal_code(HttpClientError(response=response_with_200)))  # pylint: disable=protected-access
        self.assertFalse(self.loader_class._fatal_code(HttpClientError(response=response_with_429)))  # pylint: disable=protected-access
        self.assertFalse(self.loader_class._fatal_code(HttpClientError(response=response_with_504)))  # pylint: disable=protected-access 
Example #22
Source File: views.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request):
        uuids_string = self.request.GET.get(self.QUERY_PARAM)
        if not uuids_string:
            return HttpResponse(self.HELP_STRING, status=404)
        uuids_split = uuids_string.split(',')
        try:
            uuids = {UUID(uuid_str) for uuid_str in uuids_split}
        except ValueError:
            return HttpResponse(self.HELP_STRING, status=404)
        if len(uuids) > self.MAX_REQUESTED_PROGRAMS:
            return HttpResponse(
                'Too many programs requested, only {} allowed.'.format(self.MAX_REQUESTED_PROGRAMS),
                status=422,
            )
        programs = use_read_replica_if_available(
            Program.objects.filter(uuid__in=list(uuids))
        )
        loaded_uuids = {program.uuid for program in programs}
        bad_uuids = uuids - loaded_uuids
        if bad_uuids:
            return HttpResponse(
                "Could not load programs from UUIDs: [{}]".format(
                    ",".join(str(uuid) for uuid in bad_uuids)
                ),
                status=404,
            )
        objects = load_program_fixture(programs)
        json_text = json.Serializer().serialize(objects)
        return HttpResponse(json_text, content_type='text/json') 
Example #23
Source File: feed.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def feed_export_opml(request, download: T.bool.default(False)):
    """export feeds to OPML file"""
    total, feeds, __ = UnionFeed.query_by_user(request.user.id)
    feeds = [x.to_dict() for x in feeds]
    for user_feed in feeds:
        for field in ['title', 'link', 'url', 'version']:
            user_feed[field] = xml_quote(xml_escape(user_feed[field] or ''))
    tmpl = Template(filename=OPML_TEMPLATE_PATH)
    content = tmpl.render(feeds=feeds)
    response = HttpResponse(content, content_type='text/xml')
    if download:
        response['Content-Disposition'] = 'attachment;filename="rssant.opml"'
    return response 
Example #24
Source File: decorators.py    From asap-authentication-python with MIT License 5 votes vote down vote up
def validate_asap(issuers=None, subjects=None, required=True):
    """Decorator to allow endpoint-specific ASAP authorization, assuming ASAP
    authentication has already occurred.

    :param list issuers: A list of issuers that are allowed to use the
        endpoint.
    :param list subjects: A list of subjects that are allowed to use the
        endpoint.
    :param boolean required: Whether or not to require ASAP on this endpoint.
        Note that requirements will be still be verified if claims are present.
    """
    def validate_asap_decorator(func):
        @wraps(func)
        def validate_asap_wrapper(request, *args, **kwargs):
            asap_claims = getattr(request, 'asap_claims', None)
            if required and not asap_claims:
                message = 'Unauthorized: Invalid or missing token'
                response = HttpResponse(message, status=401)
                response['WWW-Authenticate'] = 'Bearer'
                return response

            if asap_claims:
                iss = asap_claims['iss']
                if issuers and iss not in issuers:
                    message = 'Forbidden: Invalid token issuer'
                    return HttpResponse(message, status=403)

                sub = asap_claims.get('sub')
                if subjects and sub not in subjects:
                    message = 'Forbidden: Invalid token subject'
                    return HttpResponse(message, status=403)

            return func(request, *args, **kwargs)

        return validate_asap_wrapper
    return validate_asap_decorator 
Example #25
Source File: views.py    From scale with Apache License 2.0 5 votes vote down vote up
def _patch_v6(self, request, workspace_id):
        """Edits an existing workspace and returns the updated details

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param workspace_id: The ID for the workspace.
        :type workspace_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        title = rest_util.parse_string(request, 'title', required=False)
        description = rest_util.parse_string(request, 'description', required=False)
        json = rest_util.parse_dict(request, 'configuration', required=False)
        base_url = rest_util.parse_string(request, 'base_url', required=False)
        is_active = rest_util.parse_string(request, 'is_active', required=False)

        configuration = None
        if json:
            try:
                configuration = WorkspaceConfigurationV6(json, do_validate=True).get_configuration()
            except InvalidWorkspaceConfiguration as ex:
                message = 'Workspace configuration invalid'
                logger.exception(message)
                raise BadParameter('%s: %s' % (message, unicode(ex)))

        try:
            Workspace.objects.edit_workspace(workspace_id, title, description, configuration, base_url, is_active)
        except Workspace.DoesNotExist:
            raise Http404
        except InvalidWorkspaceConfiguration as ex:
            logger.exception('Unable to edit workspace: %s', workspace_id)
            raise BadParameter(unicode(ex))

        return HttpResponse(status=204) 
Example #26
Source File: test_views.py    From django-batch-requests with MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        '''
            Handles the get request.
        '''
        # Lookup for the duration to sleep.
        seconds = int(request.GET.get("seconds", "5"))

        # Make the current thread sleep for the specified duration.
        sleep(seconds)
        # Make the current thread sleep.
        return HttpResponse("Success!") 
Example #27
Source File: test_views.py    From django-batch-requests with MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        '''
            Handles the get request.
        '''
        # Lookup for the header client is requesting for.
        header = request.GET.get("header", None)

        # Get the value for the associated header.
        value = getattr(request, header, None)

        # If header is not an attribute of request, look into request.META
        if value is None:
            value = request.META.get(header, None)

        return HttpResponse(value) 
Example #28
Source File: test_views.py    From django-batch-requests with MIT License 5 votes vote down vote up
def delete(self, request):
        '''
            Handles delete requests
        '''
        return HttpResponse(status=202, content="No Content!") 
Example #29
Source File: test_views.py    From django-batch-requests with MIT License 5 votes vote down vote up
def patch(self, request):
        '''
            Handles PATCH requests
        '''
        # Imaginary current view of data.
        data = {"method": "PUT", "status": 202, "text": "Updated"}
        data.update(json.loads(request.body))
        return HttpResponse(status=202, content=json.dumps(data)) 
Example #30
Source File: test_views.py    From django-batch-requests with MIT License 5 votes vote down vote up
def put(self, request):
        '''
            Handles PUT requests
        '''
        # Imaginary current view of data.
        data = {"method": "PUT", "status": 202, "text": "Updated"}
        data.update(json.loads(request.body))
        return HttpResponse(status=202, content=json.dumps(data))