Python django.http.JsonResponse() Examples

The following are 30 code examples for showing how to use django.http.JsonResponse(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 7 votes vote down vote up
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) 
Example 2
Project: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 6 votes vote down vote up
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) 
Example 3
Project: polls-api   Author: apiaryio   File: urls.py    License: MIT License 6 votes vote down vote up
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) 
Example 4
Project: raveberry   Author: raveberry   File: library.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example 5
Project: django-healthchecks   Author: mvantellingen   File: views.py    License: MIT License 6 votes vote down vote up
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) 
Example 6
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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}) 
Example 7
Project: seqr   Author: macarthur-lab   File: json_utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 8
Project: arches   Author: archesproject   File: resource.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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()) 
Example 9
Project: heltour   Author: cyanfish   File: api.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: heltour   Author: cyanfish   File: api.py    License: MIT License 6 votes vote down vote up
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]
    }) 
Example 11
Project: heltour   Author: cyanfish   File: api.py    License: MIT License 6 votes vote down vote up
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
    }) 
Example 12
Project: heltour   Author: cyanfish   File: api.py    License: MIT License 6 votes vote down vote up
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}) 
Example 13
Project: cloudless   Author: BradNeuberg   File: views.py    License: Apache License 2.0 6 votes vote down vote up
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()
    } 
Example 14
Project: django-idcops   Author: Wenvki   File: edit.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 15
Project: AnsibleUI   Author: lotus-dgas   File: celeryIndex.py    License: GNU General Public License v3.0 6 votes vote down vote up
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'}) 
Example 16
Project: readux   Author: ecds   File: views.py    License: MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        # TODO Does this view need owners?
        # owners = [request.user.id]
        return JsonResponse(
            json.loads(
                serialize(
                    'annotation',
                    self.get_queryset(),
                    # version=kwargs['version'],
                    # owners=owners,
                    is_list = True
                )
            ),
            safe=False
        )


# class AnnotationDetail(generics.RetrieveUpdateDestroyAPIView):
#     """
#     Endpoint to update and delete annotation.
#     """
#     serializer_class = AnnotationSerialize

#     def get_queryset(self):
#         return Annotation.objects.all() 
Example 17
Project: readux   Author: ecds   File: annotations.py    License: MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        username = kwargs['username']
        try:
            owner = User.objects.get(username=username)
            if self.request.user == owner: 
                return JsonResponse(
                    json.loads(
                        serialize(
                            'user_annotation_list',
                            self.get_queryset(),
                            owners=[owner]
                        )
                    ),
                    safe=False
                )
            else:
                return JsonResponse(status=401, data={"Permission to see annotations not allowed for logged in user.": username})

        except ObjectDoesNotExist:
            # attempt to get annotations for non-existent user
            return JsonResponse(status=404, data={"User not found.": username})
        return JsonResponse(status=200, data={}) 
Example 18
Project: readux   Author: ecds   File: annotations.py    License: MIT License 6 votes vote down vote up
def post(self, request):
        oa_annotation = json.loads(self.payload['oa_annotation'])
        annotation = UserAnnotation()
        annotation.oa_annotation = oa_annotation
        annotation.owner = request.user
        annotation.motivation = 'oa:commenting'
        annotation.save()
        # TODO: should we respond with the saved annotation?
        return JsonResponse(
            json.loads(
                serialize(
                    'annotation',
                    [annotation]
                )
            ),
            safe=False,
            status=201
        ) 
Example 19
Project: readux   Author: ecds   File: annotations.py    License: MIT License 6 votes vote down vote up
def put(self, request):
        # if hasattr(request, 'user') is False or request.user.is_authenticated is False:
        #     return self.__unauthorized()

        # self.payload = json.loads(request.body.decode('utf-8'))
        annotation = self.get_queryset()

        if annotation is None:
            return self.__not_found()

        elif hasattr(request, 'user') and annotation.owner == request.user:
            annotation.oa_annotation = self.payload['oa_annotation']
            annotation.save()
            return JsonResponse(
                json.loads(
                    serialize(
                        'annotation',
                        [annotation]
                    )
                ),
                safe=False,
                status=201
            )
        else:
            return self.__unauthorized() 
Example 20
Project: wechatpy   Author: wechatpy   File: views.py    License: MIT License 5 votes vote down vote up
def jsapi_signature(request):
    noncestr = "123456"
    timestamp = int(time.time())
    url = request.POST["url"]

    client = WeChatClient(settings.WECHAT_APPID, settings.WECHAT_SECRET)
    ticket_response = client.jsapi.get_ticket()
    signature = client.jsapi.get_jsapi_signature(noncestr, ticket_response["ticket"], timestamp, url)
    ret_dict = {
        "noncestr": noncestr,
        "timestamp": timestamp,
        "url": url,
        "signature": signature,
    }
    return JsonResponse(ret_dict) 
Example 21
Project: wechatpy   Author: wechatpy   File: views.py    License: MIT License 5 votes vote down vote up
def log(request):
    print("Hello World!")
    return JsonResponse({"status": "ok",}) 
Example 22
Project: django-notifs   Author: danidee10   File: views.py    License: MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """Generate the notification."""
        data = loads(request.body)
        message = data['message']

        # Create/retrieve the user
        User = get_user_model()

        try:
            user = User.objects.get(username='demouser')
        except ObjectDoesNotExist:
            user = User.objects.create_user(
                username='demouser', email='example@gmail.com',
                password='mypassword'
            )

        # notification
        args = {
            'source': user, 'source_display_name': user.get_full_name(),
            'recipient': user, 'category': 'Quote', 'action': 'Sent',
            'obj': user.id,
            'short_description': 'You a message: {}'.format(message),
            'url': 'http://example.com', 'channels': ('websocket',)
        }
        notify.send(sender=self.__class__, **args)

        response = JsonResponse({'message': 'Notification generated'})

        self.add_access_control_headers(response)

        return response 
Example 23
Project: django-ajax-contacts   Author: cuducos   File: views.py    License: The Unlicense 5 votes vote down vote up
def contacts(request):
    contacts = [_contact_summary(contact) for contact in Contact.objects.all()]
    return JsonResponse(dict(contacts=contacts)) 
Example 24
Project: TwitterFriends   Author: mgmacias95   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def netjson(request):
    global whole_net
    net = generate_net_json(whole_net)
    return JsonResponse(net) 
Example 25
Project: raveberry   Author: raveberry   File: state_handler.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_state(self, _request) -> JsonResponse:
        """Returns the state of this class as a json dictionary for clients to use."""
        state = self.state_dict()
        return JsonResponse(state) 
Example 26
Project: raveberry   Author: raveberry   File: wifi.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def available_ssids(self, _request: WSGIRequest) -> JsonResponse:
        """List all ssids that can currently be seen."""
        output = subprocess.check_output(
            ["sudo", "/usr/local/sbin/raveberry/list_available_ssids"]
        ).decode()
        ssids = output.split("\n")
        return JsonResponse(ssids[:-1], safe=False) 
Example 27
Project: raveberry   Author: raveberry   File: wifi.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def stored_ssids(self, _request: WSGIRequest) -> JsonResponse:
        """Return the list of ssids that this Raspberry Pi was connected to in the past."""
        output = subprocess.check_output(
            ["sudo", "/usr/local/sbin/raveberry/list_stored_ssids"]
        ).decode()
        ssids = output.split("\n")
        return JsonResponse(ssids[:-1], safe=False) 
Example 28
Project: raveberry   Author: raveberry   File: sound.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def output_devices(self, _request: WSGIRequest) -> JsonResponse:
        """Returns a list of all sound output devices currently available."""
        output = subprocess.check_output(
            "pactl list short sinks".split(),
            env={"PULSE_SERVER": "127.0.0.1"},
            universal_newlines=True,
        )
        tokenized_lines = [line.split() for line in output.splitlines()]
        sinks = [sink[1] for sink in tokenized_lines if len(sink) >= 2]
        return JsonResponse(sinks, safe=False) 
Example 29
Project: django-ads   Author: razisayyed   File: mixins.py    License: Apache License 2.0 5 votes vote down vote up
def render_to_json_response(self, context, **response_kwargs):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        return JsonResponse(
            self.get_data(context),
            **response_kwargs
        ) 
Example 30
Project: django-healthchecks   Author: mvantellingen   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        try:
            report, is_healthy = create_report(request=request)
        except PermissionDenied:
            response = HttpResponse(status=401)
            response['WWW-Authenticate'] = 'Basic realm="Healthchecks"'
            return response
        status_code = 200 if is_healthy else _get_err_status_code()
        return JsonResponse(report, status=status_code)