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


Python http.JsonResponse方法代码示例

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


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

示例1: contact_detail

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def contact_detail(request, pk):
    if request.method == 'POST':
        data = (request.POST.get(key) for key in ('name', 'fone', 'email'))
        contact = Contact.objects.get(pk=pk)
        contact.name, contact.fone, contact.email = data
        contact.save()
    else:
        contact = get_object_or_404(Contact, pk=pk)

    response = dict(
        name=contact.name,
        avatar=contact.avatar(),
        email=contact.email,
        phone=contact.fone,
        url=resolve_url('contact-details', pk=contact.pk)
    )
    return JsonResponse(response) 
开发者ID:cuducos,项目名称:django-ajax-contacts,代码行数:19,代码来源:views.py

示例2: contacts_new

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def contacts_new(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(('POST',))

    data = {
        key: value for key, value in request.POST.items()
        if key in ('name', 'fone', 'email')
    }
    contact = Contact.objects.create(**data)
    response = dict(
        name=contact.name,
        avatar=contact.avatar(),
        email=contact.email,
        phone=contact.fone
    )

    return JsonResponse(response, status=201) 
开发者ID:cuducos,项目名称:django-ajax-contacts,代码行数:19,代码来源:views.py

示例3: healthcheck_view

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def healthcheck_view(request):
    content_type = 'application/health+json'
    database_accessible = True

    try:
        connections['default'].cursor()
    except ImproperlyConfigured:
        # Database is not configured (DATABASE_URL may not be set)
        database_accessible = False
    except OperationalError:
        # Database is not accessible
        database_accessible = False

    if database_accessible:
        return JsonResponse({ 'status': 'ok' }, content_type=content_type)

    return JsonResponse({ 'status': 'fail' }, status=503, content_type=content_type) 
开发者ID:apiaryio,项目名称:polls-api,代码行数:19,代码来源:urls.py

示例4: list_subdirectories

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def list_subdirectories(self, request: WSGIRequest) -> HttpResponse:
        """Returns a list of all subdirectories for the given path."""
        path = request.GET.get("path")
        if path is None:
            return HttpResponseBadRequest("path was not supplied.")
        basedir, subdirpart = os.path.split(path)
        if path == "":
            suggestions = ["/"]
        elif os.path.isdir(basedir):
            suggestions = [
                os.path.join(basedir, subdir + "/")
                for subdir in next(os.walk(basedir))[1]
                if subdir.lower().startswith(subdirpart.lower())
            ]
            suggestions.sort()
        else:
            suggestions = ["not a valid directory"]
        if not suggestions:
            suggestions = ["not a valid directory"]
        return JsonResponse(suggestions, safe=False) 
开发者ID:raveberry,项目名称:raveberry,代码行数:22,代码来源:library.py

示例5: create_result_response

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def create_result_response(self, service, result, service_path):
        for nested in service_path:
            result = result.get(nested, None)
            if result is None:
                break

        if result is None:
            raise Http404()

        if result in (True, False):
            status_code = 200 if result else _get_err_status_code()
            return HttpResponse(str(result).lower(), status=status_code)
        elif isinstance(result, six.string_types) or isinstance(result, bytes):
            return HttpResponse(result)
        else:
            # Django requires safe=False for non-dict values.
            return JsonResponse(result, safe=False) 
开发者ID:mvantellingen,项目名称:django-healthchecks,代码行数:19,代码来源:views.py

示例6: index

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def index(request):
    if request.path.startswith("/api"):
        # If you ended up here, your URL pattern didn't match anything and if your path
        # starts with anything "api" you're going to expect JSON.
        return JsonResponse({"path": request.path}, status=404)

    hostname = request.get_host()

    delivery_console_url = DELIVERY_CONSOLE_URLS["prod"]
    match = re.search(
        r"(\w+)-admin\.normandy\.(?:non)?prod\.cloudops\.mozgcp\.net", hostname, re.I
    )
    if match:
        env = match.group(1)
        if env in DELIVERY_CONSOLE_URLS:
            delivery_console_url = DELIVERY_CONSOLE_URLS[env]

    # Add any path at the end of the delivery console URL, to hopefully
    # redirect the user to the right page.
    delivery_console_url += request.get_full_path()

    return render(request, "base/index.html", {"DELIVERY_CONSOLE_URL": delivery_console_url}) 
开发者ID:mozilla,项目名称:normandy,代码行数:24,代码来源:views.py

示例7: create_json_response

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def create_json_response(obj, **kwargs):
    """Encodes the give object into json and create a django JsonResponse object with it.

    Args:
        obj (object): json response object
        **kwargs: any addition args to pass to the JsonResponse constructor
    Returns:
        JsonResponse
    """

    dumps_params = {
        'sort_keys': True,
        'indent': 4,
        'default': DjangoJSONEncoderWithSets().default
    }

    return JsonResponse(
        obj, json_dumps_params=dumps_params, encoder=DjangoJSONEncoderWithSets, **kwargs) 
开发者ID:macarthur-lab,项目名称:seqr,代码行数:20,代码来源:json_utils.py

示例8: get

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def get(self, request):
        page_size = 100
        if hasattr(settings, "ACTIVITY_STREAM_PAGE_SIZE"):
            page_size = int(setting.ACTIVITY_STREAM_PAGE_SIZE)

        totalItems = models.EditLog.objects.all().exclude(resourceclassid=settings.SYSTEM_SETTINGS_RESOURCE_MODEL_ID).count()

        uris = {
            "root": request.build_absolute_uri(reverse("as_stream_collection")),
            "first": request.build_absolute_uri(reverse("as_stream_page", kwargs={"page": 1})),
            "last": request.build_absolute_uri(reverse("as_stream_page", kwargs={"page": 1})),
        }

        if totalItems > page_size:
            uris["last"] = request.build_absolute_uri(reverse("as_stream_page", kwargs={"page": int(totalItems / page_size) + 1}))

        collection = ActivityStreamCollection(uris, totalItems, base_uri_for_arches=request.build_absolute_uri("/").rsplit("/", 1))

        return JsonResponse(collection.to_obj()) 
开发者ID:archesproject,项目名称:arches,代码行数:21,代码来源:resource.py

示例9: get_roster

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def get_roster(request):
    try:
        league_tag = request.GET.get('league', None)
        season_tag = request.GET.get('season', None)
    except ValueError:
        return HttpResponse('Bad request', status=400)

    try:
        seasons = Season.objects.order_by('-start_date', '-id')
        if league_tag is not None:
            seasons = seasons.filter(league__tag=league_tag)
        if season_tag is not None:
            seasons = seasons.filter(tag=season_tag)
        else:
            seasons = seasons.filter(is_active=True)

        season = seasons[0]
    except IndexError:
        return JsonResponse(
            {'season_tag': None, 'players': None, 'teams': None, 'error': 'no_matching_rounds'})

    if season.league.competitor_type == 'team':
        return _team_roster(season)
    else:
        return _lone_roster(season) 
开发者ID:cyanfish,项目名称:heltour,代码行数:27,代码来源:api.py

示例10: _lone_roster

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def _lone_roster(season):
    season_players = season.seasonplayer_set.select_related('player').nocache()

    player_board = {}
    current_round = season.round_set.filter(publish_pairings=True, is_completed=False).first()
    if current_round is not None:
        for p in current_round.loneplayerpairing_set.all():
            player_board[p.white] = p.pairing_order
            player_board[p.black] = p.pairing_order

    return JsonResponse({
        'league': season.league.tag,
        'season': season.tag,
        'players': [{
            'username': season_player.player.lichess_username,
            'rating': season_player.player.rating_for(season.league),
            'board': player_board.get(season_player.player, None)
        } for season_player in season_players]
    }) 
开发者ID:cyanfish,项目名称:heltour,代码行数:21,代码来源:api.py

示例11: league_document

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def league_document(request):
    try:
        league_tag = request.GET.get('league', None)
        type_ = request.GET.get('type', None)
        strip_html = request.GET.get('strip_html', None) == 'true'
    except ValueError:
        return HttpResponse('Bad request', status=400)

    if not league_tag or not type_:
        return HttpResponse('Bad request', status=400)

    league_doc = LeagueDocument.objects.filter(league__tag=league_tag, type=type_).first()
    if league_doc is None:
        return JsonResponse({'name': None, 'content': None, 'error': 'not_found'})

    document = league_doc.document
    content = document.content
    if strip_html:
        content = strip_tags(content)

    return JsonResponse({
        'name': document.name,
        'content': content
    }) 
开发者ID:cyanfish,项目名称:heltour,代码行数:26,代码来源:api.py

示例12: link_slack

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def link_slack(request):
    try:
        user_id = request.GET.get('user_id', None)
        display_name = request.GET.get('display_name', None)
    except ValueError:
        return HttpResponse('Bad request', status=400)

    if not user_id:
        return HttpResponse('Bad request', status=400)

    token = LoginToken.objects.create(slack_user_id=user_id, username_hint=display_name,
                                      expires=timezone.now() + timedelta(days=30))
    league = League.objects.filter(is_default=True).first()
    sp = SeasonPlayer.objects.filter(player__lichess_username__iexact=display_name).order_by(
        '-season__start_date').first()
    if sp:
        league = sp.season.league
    url = reverse('by_league:login_with_token', args=[league.tag, token.secret_token])
    url = request.build_absolute_uri(url)

    already_linked = [p.lichess_username for p in Player.objects.filter(slack_user_id=user_id)]

    return JsonResponse({'url': url, 'already_linked': already_linked, 'expires': token.expires}) 
开发者ID:cyanfish,项目名称:heltour,代码行数:25,代码来源:api.py

示例13: random_img

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def random_img():
    """
    Returns a dictionary of info about a random non-annotated image
    """
    imgs = Image.objects.filter(annotation__isnull=True).order_by('?')
    if not imgs:
        return JsonResponse({
            'status': 'error',
            'error': 'No images remain to annotate'
        })

    i = imgs[0]
    return {
        'status': 'ok',
        'image_id': i.id,
        'image_url': i.url()
    } 
开发者ID:BradNeuberg,项目名称:cloudless,代码行数:19,代码来源:views.py

示例14: form_valid

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def form_valid(self, form):
        form.instance.creator = self.request.user
        if 'onidc' not in form.cleaned_data:
            form.instance.onidc = self.request.user.onidc
        response = super(NewModelView, self).form_valid(form)
        log_action(
            user_id=self.request.user.pk,
            content_type_id=get_content_type_for_model(self.object, True).pk,
            object_id=self.object.pk,
            action_flag="新增"
        )
        if self.model_name == 'online':
            verify = Thread(target=device_post_save, args=(self.object.pk,))
            verify.start()
        if self.request.is_ajax():
            data = {
                'message': "Successfully submitted form data.",
                'data': form.cleaned_data
            }
            return JsonResponse(data)
        else:
            return response 
开发者ID:Wenvki,项目名称:django-idcops,代码行数:24,代码来源:edit.py

示例15: post

# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import JsonResponse [as 别名]
def post(self, request, *a,  **kw):
        data = request.POST.dict()
        if data.get('opt', '') == 'grow':
            num = int(data.get('num', '0'))
            node_name = data.get('node_name', None)
            if num and node_name:
                ret = appCelery.control.pool_grow(n=num, reply=True, destination=[node_name])
                print(ret)
                return JsonResponse({'data': ret, 'msg': '%s: %s'% (node_name, ret[0][node_name])})
        elif data.get('opt', '') == 'shrink':
            num = int(data.get('num', '0'))
            node_name = data.get('node_name', None)
            if num and node_name:
                ret = appCelery.control.pool_shrink(n=num, reply=True, destination=[node_name])
                return JsonResponse({'data': ret, 'msg': '%s: %s'% (node_name, ret[0][node_name])})
        return JsonResponse({'msg': 'ok'}) 
开发者ID:lotus-dgas,项目名称:AnsibleUI,代码行数:18,代码来源:celeryIndex.py


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