Python django.http.JsonResponse() Examples
The following are 30
code examples of django.http.JsonResponse().
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
, or try the search function
.
Example #1
Source File: views.py From django-ajax-contacts with The Unlicense | 8 votes |
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
Source File: views.py From cloudless with Apache License 2.0 | 6 votes |
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 #3
Source File: celeryIndex.py From AnsibleUI with GNU General Public License v3.0 | 6 votes |
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 #4
Source File: json_utils.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
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 #5
Source File: api.py From heltour with MIT License | 6 votes |
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 #6
Source File: api.py From heltour with MIT License | 6 votes |
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 #7
Source File: annotations.py From readux with MIT License | 6 votes |
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 #8
Source File: annotations.py From readux with MIT License | 6 votes |
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 #9
Source File: views.py From normandy with Mozilla Public License 2.0 | 6 votes |
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 #10
Source File: views.py From django-healthchecks with MIT License | 6 votes |
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 #11
Source File: annotations.py From readux with MIT License | 6 votes |
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 #12
Source File: edit.py From django-idcops with Apache License 2.0 | 6 votes |
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 #13
Source File: library.py From raveberry with GNU Lesser General Public License v3.0 | 6 votes |
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 #14
Source File: api.py From heltour with MIT License | 6 votes |
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 #15
Source File: api.py From heltour with MIT License | 6 votes |
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 #16
Source File: urls.py From polls-api with MIT License | 6 votes |
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 #17
Source File: views.py From django-ajax-contacts with The Unlicense | 6 votes |
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 #18
Source File: markup_view.py From PoetryCorpus with Apache License 2.0 | 5 votes |
def post(self, request, *args, **kwargs): if request.user.is_authenticated(): diffs = request.POST.getlist('diffs[]') m = self.get_object() poem = m.poem markup = m.get_markup() for diff in diffs: l = int(diff.split('-')[0]) w = int(diff.split('-')[1]) s = int(diff.split('-')[2]) syllable = markup.lines[l].words[w].syllables[s] if syllable.stress != -1: syllable.stress = -1 else: for i in range(len(syllable.text)): if syllable.text[i] in VOWELS: syllable.stress = syllable.begin + i m = Markup() if Markup.objects.filter(author=request.user.email, poem=poem).exists(): m = Markup.objects.filter(author=request.user.email, poem=poem)[0] m.text = markup.to_json() m.author = request.user.email m.poem = poem m.markup_version = MarkupVersion.objects.get(name="Manual") m.save() return JsonResponse({'url': reverse('corpus:markup', kwargs={'pk': m.pk}),}, status=200) else: raise PermissionDenied
Example #19
Source File: urls.py From django-qsessions with MIT License | 5 votes |
def read_session(request): return JsonResponse(dict(request.session))
Example #20
Source File: views.py From PrivacyScore with GNU General Public License v3.0 | 5 votes |
def site_result_json(request: HttpRequest, site_id: int) -> HttpResponse: if 'at' in request.GET: # Check that the site even exists site = get_object_or_404(Site, pk=site_id) # TODO sanity check timestamp try: timestamp = datetime.strptime(request.GET['at'], "%Y-%m-%d") except: return render(request, 'frontend/site_result_json.html', {'site': site, 'highlighted_code': 'Incorrect timestamp format'}) try: scan = Scan.objects.filter(site=site).filter(end__lte=timestamp).order_by('-end').first() scan_result = ScanResult.objects.get(scan=scan).result except Exception as e: scan_result = None else: site = get_object_or_404(Site.objects.annotate_most_recent_scan_result(), pk=site_id) scan_result = site.last_scan__result if site.last_scan__result else {} if 'raw' in request.GET: return JsonResponse(scan_result) code = json.dumps(scan_result, indent=2) if scan_result is not None: highlighted_code = mark_safe(highlight(code, JsonLexer(), HtmlFormatter())) else: highlighted_code = 'No scan data found for these parameters' return render(request, 'frontend/site_result_json.html', { 'site': site, 'highlighted_code': highlighted_code })
Example #21
Source File: views.py From readux with MIT License | 5 votes |
def get(self, request, *args, **kwargs): return JsonResponse(json.loads(serialize('canvas', self.get_queryset(), is_list=True)), safe=False)
Example #22
Source File: views.py From AnsibleUI with GNU General Public License v3.0 | 5 votes |
def post(self, request, *k, **kw): return JsonResponse({"msg": "err"})
Example #23
Source File: views.py From AnsibleUI with GNU General Public License v3.0 | 5 votes |
def get(self, request, *args, **kw): user = request.META.get("HTTP_WEICHAT_USER") user = request.user myfunc = request.GET.get("function", None) playbook = request.GET.get("playbook", None) var = request.GET.get('vars') extra_vars = ast.literal_eval(var) if var else {} if myfunc and not playbook: f = Functions.objects.filter(funcName=myfunc)[0] playbook = f.playbook groupName = request.GET.get("groupName", None) if not groupName: return JsonResponse({"msg": "参数错误"}) if not playbook and not myfunc: return JsonResponse({"msg": "参数错误"}) s = AnsibleOpt.ansible_playbook( groupName=groupName, playbook=playbook, user=user, extra_vars=extra_vars, **{'label': request.META.get('REMOTE_ADDR')} ) # s = extra_vars # return redirect('/ansible/get_Ansible_Tasks/?dataKey=%s' % s.get('tid')) return redirect('/ansible/task/%s/' % s.get('id')) # 参数: groupName, (playbook | myfunc), 不支持 茉莉花 调用
Example #24
Source File: views.py From cloudless with Apache License 2.0 | 5 votes |
def getImage(request): """ An API for getting random image data """ return JsonResponse(random_img())
Example #25
Source File: views.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get(self, request, *args, **kwargs): """ Return a :class:`.django.http.JsonResponse`. Example:: { 'results': [ { 'text': "foo", 'id': 123 } ], 'more': true } """ self.widget = self.get_widget_or_404() self.term = kwargs.get('term', request.GET.get('term', '')) self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse({ 'results': [ { 'text': self.widget.label_from_instance(obj), 'id': obj.pk, } for obj in context['object_list'] ], 'more': context['page_obj'].has_next() })
Example #26
Source File: views.py From AnsibleUI with GNU General Public License v3.0 | 5 votes |
def post(self, request, *k, **kw): return JsonResponse({'data': {'k': k, 'kw': kw}})
Example #27
Source File: edit.py From django-idcops with Apache License 2.0 | 5 votes |
def form_valid(self, form): form.instance.operator = self.request.user if 'onidc' not in form.cleaned_data: form.instance.onidc = self.request.user.onidc d1 = form.initial message = json.dumps(form.changed_data) response = super(EditModelView, self).form_valid(form) d2 = model_to_dict(construct_instance(form, self.object)) diffs = diff_dict(make_dict(d1), make_dict(d2)) content = json.dumps(diffs) 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="修改", message=message, content=content ) 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 #28
Source File: views.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get(self, request, *args, **kwargs): """ Return a :class:`.django.http.JsonResponse`. Example:: { 'results': [ { 'text': "foo", 'id': 123 } ], 'more': true } """ self.widget = self.get_widget_or_404() self.term = kwargs.get('term', request.GET.get('term', '')) self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse({ 'results': [ { 'text': self.widget.label_from_instance(obj), 'id': obj.pk, } for obj in context['object_list'] ], 'more': context['page_obj'].has_next() })
Example #29
Source File: views.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get(self, request, *args, **kwargs): """ Return a :class:`.django.http.JsonResponse`. Example:: { 'results': [ { 'text': "foo", 'id': 123 } ], 'more': true } """ self.widget = self.get_widget_or_404() self.term = kwargs.get('term', request.GET.get('term', '')) self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse({ 'results': [ { 'text': self.widget.label_from_instance(obj), 'id': obj.pk, } for obj in context['object_list'] ], 'more': context['page_obj'].has_next() })
Example #30
Source File: views.py From django-idcops with Apache License 2.0 | 5 votes |
def get(self, request, *args, **kwargs): return JsonResponse({ 'status': 'false', 'message': _('Only POST method is allowed'), }, status=400)