当前位置: 首页>>代码示例>>Python>>正文


Python response.HttpResponse方法代码示例

本文整理汇总了Python中django.http.response.HttpResponse方法的典型用法代码示例。如果您正苦于以下问题:Python response.HttpResponse方法的具体用法?Python response.HttpResponse怎么用?Python response.HttpResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.http.response的用法示例。


在下文中一共展示了response.HttpResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: random_suggestion

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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}) 
开发者ID:raveberry,项目名称:raveberry,代码行数:25,代码来源:suggestions.py

示例2: request_radio

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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) 
开发者ID:raveberry,项目名称:raveberry,代码行数:18,代码来源:musiq.py

示例3: request_radio

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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") 
开发者ID:raveberry,项目名称:raveberry,代码行数:25,代码来源:spotify.py

示例4: disabled_when_voting

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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) 
开发者ID:raveberry,项目名称:raveberry,代码行数:19,代码来源:controller.py

示例5: remove

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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() 
开发者ID:raveberry,项目名称:raveberry,代码行数:20,代码来源:controller.py

示例6: reorder

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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() 
开发者ID:raveberry,项目名称:raveberry,代码行数:24,代码来源:controller.py

示例7: export_multiple_files

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:24,代码来源:export_utils.py

示例8: csp_report_view

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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 
开发者ID:sfu-fas,项目名称:coursys,代码行数:24,代码来源:csp.py

示例9: fcm_register

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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') 
开发者ID:cyanfish,项目名称:heltour,代码行数:18,代码来源:android_app.py

示例10: _patch_get_response

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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) 
开发者ID:getsentry,项目名称:sentry-python,代码行数:22,代码来源:__init__.py

示例11: generate_toml

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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") 
开发者ID:stellar,项目名称:django-polaris,代码行数:27,代码来源:views.py

示例12: csv_download

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
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 
开发者ID:codeforamerica,项目名称:intake,代码行数:26,代码来源:data_export_views.py

示例13: request_radio

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
def request_radio(self, request_ip: str) -> HttpResponse:
        if not self.id:
            raise ValueError()
        radio_id = "RD" + self.id

        provider = YoutubePlaylistProvider(self.musiq, "", None)
        provider.id = radio_id
        provider.request("", archive=False, manually_requested=False)
        return HttpResponse("queueing radio (might take some time)") 
开发者ID:raveberry,项目名称:raveberry,代码行数:11,代码来源:youtube.py

示例14: request_radio

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
def request_radio(self, request_ip: str) -> HttpResponse:
        playlist = self._get_corresponding_playlist()
        self.musiq.do_request_music(
            request_ip,
            playlist.title,
            playlist.id,
            True,
            "local",
            archive=False,
            manually_requested=False,
        )
        return HttpResponse("queueing radio") 
开发者ID:raveberry,项目名称:raveberry,代码行数:14,代码来源:localdrive.py

示例15: request_music

# 需要导入模块: from django.http import response [as 别名]
# 或者: from django.http.response import HttpResponse [as 别名]
def request_music(self, request: WSGIRequest) -> HttpResponse:
        """Endpoint to request music. Calls internal function."""
        key = request.POST.get("key")
        query = request.POST.get("query")
        playlist = request.POST.get("playlist") == "true"
        platform = request.POST.get("platform")

        if query is None or not platform:
            return HttpResponseBadRequest(
                "query, playlist and platform have to be specified."
            )
        ikey = None
        if key:
            ikey = int(key)

        # 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 = ""

        successful, message, queue_key = self.do_request_music(
            request_ip, query, ikey, playlist, platform
        )
        if not successful:
            return HttpResponseBadRequest(message)
        return JsonResponse({"message": message, "key": queue_key}) 
开发者ID:raveberry,项目名称:raveberry,代码行数:31,代码来源:musiq.py


注:本文中的django.http.response.HttpResponse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。