我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.http.JsonResponse()。
def donations(request): ''' actual data from the FEC, propublica data, through the django ORM cache ''' data = {} data["representatives"] = {d["id"]: d for d in Representative.objects.all() .annotate(name=Concat('first_name', Value(" "), 'last_name')) .values("id", "name", "party")} data["committees"] = {d["id"]: d for d in SuperPAC.objects.all().values("id", "name")} data["donations"] = list(Donation.objects.all() .annotate(source=F("superpac_id"), destination=F("representative_id")) .values("source", "destination", "support") .annotate(amount=Sum("amount"))) return JsonResponse(data)
def doDelHighscore(self, request): context, teacher = self.getContextTeacher(request) delIds = request.POST.get('ids') if not delIds: return JsonResponse({'ok': False, 'msg': '????', 'code': 1}) delIds = delIds.split(","); delIds = list(map(int, filter(lambda x: x, delIds))) try: delObjs = models.Highscore.objects.filter(id__in=delIds) allIsSelf = True for p in delObjs: if p.teacher.id != teacher.id: allIsSelf = False if not allIsSelf: return JsonResponse({'ok': False, 'msg': '?????????', 'code': -1}) ret = models.Highscore.objects.filter(id__in=delIds).delete() return JsonResponse({'ok': True, 'msg': '', 'code': 0}) except Exception as err: logger.error(err) return JsonResponse({'ok': False, 'msg': '????,?????,??????!', 'code': -1})
def echoHome(request) : loginUser = request.session.get('user') usrObj = User.objects.get(user_id = loginUser) playerObj, created = echoplayer.objects.get_or_create(playerId = usrObj.user_id.split('|')[1],ref_id=usrObj) if created: playerObj.rank = echoplayer.objects.count() playerObj.save() if not os.path.exists(os.path.join(os.getcwd(), 'echo/media/')) : os.makedirs(os.path.join(os.getcwd(), 'echo/media/players/')) if not os.path.exists(os.path.join(os.getcwd(), 'echo/media/players/')) : os.makedirs(os.path.join(os.getcwd(), 'echo/media/players/')) if not os.path.exists(os.path.join(os.getcwd(), 'echo/media/players/'+playerObj.playerId+'/')) : os.makedirs(os.path.join(os.getcwd(), 'echo/media/players/'+playerObj.playerId+'/')) subprocess.Popen(['cp', '-r' , os.path.join(os.getcwd(), 'echo/skel/home/'), os.path.join(os.getcwd(), 'echo/media/players/'+playerObj.playerId+'/')]) levelObj = echolevel.objects.get(levelId=playerObj.playerLevel) status = False response = {'player' : playerObj.playerId, 'level' : playerObj.playerLevel,'question':levelObj.qnDesc, 'partCode' : playerObj.partCode, 'status' : status} return JsonResponse(response) # return render(request, 'echohome.html', response)
def donationsDemo(request): ''' actual data from the FEC, propublica data, through the django ORM cache this returns specially selected pieces of data for demo purposes ''' data = {"representatives":{},"committees":{},"donations":[]} representative_list = Representative.objects.all() special_reps = [488,200,390,119,49,445,491] for rep in representative_list: if rep.first_name+" "+rep.last_name in ['Ted Cruz','Marco Rubio','Tammy Duckworth','Rand Paul','Ruben Kihuen','Stephanie Murphy']: data["representatives"][rep.id] = rep.__json__() superpac_list = SuperPAC.objects.all() special_pacs = [3505,3498,3453,3323,276] for sup in superpac_list: if sup.name in ['MAKE DC LISTEN','COURAGEOUS CONSERVATIVES PAC','CONSERVATIVE SOLUTIONS PAC','RIGHT TO RISE USA','NEXTGEN CLIMATE ACTION COMMITTEE','AMERICA\'S LIBERTY PAC','STAND FOR TRUTH','TEXAS TEA PARTY PATRIOTS','FLORIDIANS FOR A STRONG MIDDLE CLASS','HOUSE MAJORITY PAC','PLANNED PARENTHOOD VOTES','IMMIGRANT VOTERS WIN PAC']: data["committees"][sup.id] = sup.__json__() data["donations"] = list(Donation.objects.all() .annotate(source=F("superpac_id"), destination=F("representative_id")) .values("source", "destination", "support") .annotate(amount=Sum("amount"))) return JsonResponse(data)
def votes(request): ''' Returns votes for the given bill ''' bill_id = request.GET["bill_id"] #get latest roll call vote from sunlight results = SunlightAPI().votes(bill_id) print(results) if len(results["results"]) == 0: return JsonResponse({"votes": []}) last_vote = results["results"][0] #get individual votes for the roll call vote results = CongressAPI(ProPublica_APIKEY).get_vote(last_vote["congress"], last_vote["chamber"], 2-last_vote["year"]%2, last_vote["number"]) data = {"votes": []} for vote in results["results"]["votes"]["vote"]["positions"]: rep = Representative.objects.filter(propublicaid=vote["member_id"]).first() if rep is not None: data["votes"].append({"source": rep.id, "destination": bill_id, "position": vote["vote_position"]}) return JsonResponse(data)
def like(request): """ kullan?c? be?endi?inde vya be?enmedi?inde ekrandaki skoru otomatik update eder """ id = request.GET.get("id", default=None) like = request.GET.get("like") obj = get_object_or_404(Post, id=int(id)) if like == "true": # f objesi veri tabanindaki ilgili sutunun degerini cekerek # atama yapmak yerine arttirma veya azaltma yapmamizi saglar. obj.score = F("score") + 1 obj.save(update_fields=["score"]) elif like == "false": obj.score = F("score") - 1 obj.save(update_fields=["score"]) else: return HttpResponse(status=400) obj.refresh_from_db() return JsonResponse({"like": obj.score, "id": id})
def wishlist_oglas(request, oglas_id): oglas = get_object_or_404(Oglas, pk=oglas_id) try: if oglas.na_wishlist: oglas.na_wishlist = False else: oglas.na_wishlist = True oglas.save() except (KeyError, Oglas.DoesNotExist): return JsonResponse({'success': False}) else: return JsonResponse({'success': True})
def dispatch(self, request, *args, **kwargs): search = request.GET.get('search') if not search or len(search) < 2: return JsonResponse({'count': 0, 'results': []}) queryset = Member.objects.filter( Q(name__icontains=search) | Q(profile_profile__nick__icontains=search) ) return JsonResponse({ 'count': len(queryset), 'results': [ { 'id': member.pk, 'nick': member.profile_profile.nick, 'name': member.name, } for member in queryset ], })
def get(self, request, server_id, character_id): server = self.get_server(request, server_id) if server is None: return HttpResponse('server does not exist', status=400) character = (Character.objects .filter( server_id=server.id, id=character_id) .first()) if character is None: return HttpResponse('character does not exist', status=400) histories = CharacterHistory.objects.filter(character_id=character.id) serialized = CharacterHistorySerializer(histories, many=True).data return JsonResponse({'history': serialized}, status=200)
def get(self, request, server_id, character_id): server = self.get_server(request, server_id) if server is None: return HttpResponse('server does not exist', status=400) character = (Character.objects .filter( server_id=server.id, id=character_id) .first()) if character is None: return HttpResponse('character does not exist', status=400) serialized = CharacterSerializer(character).data return JsonResponse(serialized, status=200)
def post(self, request, server_id): if 'private_secret' not in request.GET: return HttpResponse('missing required param private_secret') data = request.GET server = self.get_server(request, server_id) if server is None: return HttpResponse('server does not exist', status=404) if 'name' in data: server.name = data['name'] server.save() serialized = ServerAdminSerializer(server).data return JsonResponse(serialized, status=200)
def get(self, request, server_id, clan_id): server = self.get_server(request, server_id) if server is None: return HttpResponse('server does not exist', status=400) clan = (Clan.objects .filter( server_id=server.id, id=clan_id) .first()) if clan is None: return HttpResponse('clan does not exist', status=400) serialized = ClanSerializer(clan).data return JsonResponse(serialized, status=200)
def loci(request): chrom = request.GET.get('chrom', False) loop_list = request.GET.get('loop-list', False) # Get relative loci (loci_rel, chroms) = get_intra_chr_loops_from_looplist( path.join('data', loop_list), chrom ) loci_rel_chroms = np.column_stack( (chroms[:, 0], loci_rel[:, 0:2], chroms[:, 1], loci_rel[:, 2:4]) ) # Create results results = { 'loci': rel_loci_2_obj(loci_rel_chroms) } return JsonResponse(results)
def available_chrom_sizes(request): ''' Get the list of available chromosome size lists. Args: request: HTTP GET request object. Should contain no query features Returns: A JSON response containing the list of chromosome size lists. ''' queryset = tm.Tileset.objects.all() queryset = queryset.filter(datatype__in=["chromsizes"]) serializer = tss.UserFacingTilesetSerializer(queryset, many=True) return JsonResponse({"count": len(queryset), "results": serializer.data})
def suggest(request): ''' Suggest gene names based on the input text ''' # suggestions are taken from a gene annotations tileset tileset_uuid = request.GET['d'] text = request.GET['ac'] try: tileset = tm.Tileset.objects.get(uuid=tileset_uuid) except ObjectDoesNotExist: raise rfe.NotFound('Suggestion source file not found') result_dict = tsu.get_gene_suggestions( tut.get_datapath(tileset.datafile.url), text ) return JsonResponse(result_dict, safe=False)
def ansible_log_view(request,model,id): if request.method == "POST": if model == 'model': try: result = '' logId = Log_Ansible_Model.objects.get(id=id) for ds in Ansible_CallBack_Model_Result.objects.filter(logId=logId): result += ds.content result += '\n' except Exception,e: return JsonResponse({'msg':"????","code":500,'data':e}) elif model == 'playbook': try: result = '' logId = Log_Ansible_Playbook.objects.get(id=id) for ds in Ansible_CallBack_PlayBook_Result.objects.filter(logId=logId): result += ds.content result += '\n' except Exception,e: return JsonResponse({'msg':"????","code":500,'data':e}) return JsonResponse({'msg':"????","code":200,'data':result})
def register(request): if request.method == "POST": if request.POST.get('password') == request.POST.get('c_password'): try: user = User.objects.filter(username=request.POST.get('username')) if len(user)>0:return JsonResponse({"code":500,"data":None,"msg":"????????????"}) else: user = User() user.username = request.POST.get('username') user.email = request.POST.get('email') user.is_staff = 0 user.is_active = 0 user.is_superuser = 0 user.set_password(request.POST.get('password')) user.save() return JsonResponse({"code":200,"data":None,"msg":"??????"}) except Exception,e: return JsonResponse({"code":500,"data":None,"msg":"??????"}) else:return JsonResponse({"code":500,"data":None,"msg":"?????????????"})
def search(request): q = request.GET.get('q') if not q: return HttpResponseBadRequest("GET['q'] not set!") q = q.strip() try: document_ids = search_ids(q) except SearchError as e: return HttpResponseServerError(str(e)) documents = [get_document(id).parsed for id in document_ids] data = { 'status': 'ok', 'query': q, 'document_ids': document_ids, 'documents': documents, 'results': len(document_ids), } r = JsonResponse(data) r["Access-Control-Allow-Origin"] = '*' return r
def log_skip_grammar(request): if not request.method == 'POST': response = render(request, 'LL1_Academy/error.html', { 'title':'Oops, invalid request to log_skip_grammar.', 'text':'log_skip_grammar is not happy with how your request is formatted.' }) response.status_code = 400 return response request.session['hide_explainer'] = request.POST.get('hide_explainer') gid = request.session['gid'] grammar_obj = Grammar.objects.filter(gid=gid).first() grammar_obj.nSkip +=1 grammar_obj.save() #only does this part if user is logged in if request.user.is_authenticated: if not UserHistory.objects.filter(user=request.user, grammar=grammar_obj).exists(): newHistory = UserHistory(user=request.user,grammar=grammar_obj) newHistory.save() return JsonResponse({})
def post(self, request): jsonstr = request.GET.get('data') params = json.loads(jsonstr) create = 0 exists = 0 for key,value in params.items(): book,created = models.Book.objects.get_or_create(qs_id=key) if created: book.an_id = value create += 1 book.save() else: exists += 1 response_data = { 'create': create, 'exists': exists, 'message': 'yes', } return JsonResponse(response_data)
def api_song_meta(request): def convert_for_no_safari(meta): if meta.codec == 'alac': if settings.ALAC_CONVERTIBLE: convert_aac.delay(settings.MEDIA_ROOT + meta.filepath, meta.rawhash) meta.fileurl = meta.cacheurl return meta if request.method == 'GET': data = request.query_params try: meta = MusicLibrary.objects.get(rawhash=data['rawhash']) except MusicLibrary.DoesNotExist: return JsonResponse({}, safe=True) if not is_ua_safari(request): meta = convert_for_no_safari(meta) serializer = MusicMetaSerializer(meta) return JsonResponse(serializer.data)
def approve_withdraw(self, request, ahid): ok = False try: with transaction.atomic(): ah = models.AccountHistory.objects.get(id=ahid) if not ah.withdrawal.is_pending(): return JsonResponse({'ok': False, 'msg': '???????', 'code': -1}) ah.audit_withdrawal(True, request.user) ok = True except IntegrityError as err: logger.error(err) return JsonResponse({'ok': False, 'msg': '????, ???????????', 'code': -1}) if ok: # ?????? teacher = ah.account.user.teacher _try_send_sms(teacher.user.profile.phone, smsUtil.TPL_WITHDRAW_APPROVE, {'username':teacher.name}, 2) return JsonResponse({'ok': True, 'msg': 'OK', 'code': 0})
def view_available(self, request): tid = request.POST.get('tid') timeslot = models.TimeSlot.objects.get(id=tid) teacher = timeslot.order.teacher school = timeslot.order.school sa_dict = teacher.shortterm_available_dict(school) data = [OrderedDict([ ('weekday', one[0]), ('start', one[1]), ('end', one[2]), ('available', sa_dict[(one[0], one[1], one[2])]) ]) for one in sa_dict] now_date = timezone.now().astimezone().strftime('%Y-%m-%d') now_time = timezone.now().astimezone().strftime('%H:%M:%S') return JsonResponse({'ok': True, 'sa_dict': data, 'now_date': now_date, 'now_time': now_time})
def request_refund(self, request): order_id = request.POST.get('order_id') order = models.Order.objects.get(id=order_id) reason = request.POST.get('reason') lessons_count = request.POST.get('lessons_count', 0) try: models.Order.objects.refund(order, reason, self.request.user, lessons_count) # ?????? parent = order.parent student_name = parent.student_name or parent.user.profile.mask_phone() _try_send_sms(parent.user.profile.phone, smsUtil.TPL_STU_REFUND_REQUEST, {'studentname': student_name}, 3) # ?????? teacher = order.teacher _try_send_sms(teacher.user.profile.phone, smsUtil.TPL_REFUND_NOTICE, {'username': teacher.name}, 2) return JsonResponse({'ok': True}) except OrderStatusIncorrect as e: return JsonResponse({'ok': False, 'msg': '%s' % e}) except RefundError as e: return JsonResponse({'ok': False, 'msg': '%s' % e})
def post(self, request): region_id = request.POST.get('region') level_id = request.POST.get('level') commission_percentage = request.POST.get('commission_percentage') if not region_id or not level_id or not commission_percentage: return HttpResponse(status=400) try: new_percent = int(commission_percentage) except Exception as e: new_percent = -1 if not (0 <= new_percent <= 100): return JsonResponse({'ok': False, 'msg': '????????', 'code': 1}) region = get_object_or_404(models.Region, id=region_id) level = get_object_or_404(models.Level, id=level_id) num = models.Price.objects.filter(region=region, level=level).update(commission_percentage=new_percent) logger.info("????%s??%s??????%s, ?????%s?"%(region.name, level.name, new_percent, num)) return JsonResponse({'ok': True, 'msg': '????', 'code': 0})
def post(self, request): # ??????? school_master = self.school_master is_school_master = school_master is not None and school_master.school is not None if not is_school_master: return JsonResponse({'ok': False, 'msg': '?????, ?????', 'code': 1}) # ???? pk = request.POST.get('pk') price = request.POST.get('price') try: new_price = float(price) except Exception as e: new_price = -1 if new_price < 0: return JsonResponse({'ok': False, 'msg': '??????', 'code': 2}) cur_price = models.PriceConfig.objects.get(pk=pk) # ?????????? if cur_price.school_id != school_master.school_id: return JsonResponse({'ok': False, 'msg': '????????, ??????????', 'code': 3}) cur_price.price = int(new_price * 100) cur_price.save() return JsonResponse({'ok': True, 'msg': '????', 'code': 0})
def post(self, request): school_id = request.POST.get('school') school = get_object_or_404(models.School, id=school_id) name = request.POST.get('name') capacity = parseInt(request.POST.get('capacity'), 0) if not name: return JsonResponse({'ok': False, 'msg': '???????'}) if not capacity > 0: return JsonResponse({'ok': False, 'msg': '?????????'}) if models.ClassRoom.objects.filter(school=school).exists(): return JsonResponse({'ok': False, 'msg': '????, ???????'}) new_room = models.ClassRoom(school=school, name=name, capacity=capacity) new_room.save() return JsonResponse({'ok': True, 'msg': '????!'})
def post(self, request): var = ('username', 'password',) vard = {} for k in var: v = request.POST.get(k, '') if not v: return JsonResponse({'error': k + ' is empty'}) vard[k] = v user = auth.authenticate( username=vard['username'], password=vard['password']) if user is None: return JsonResponse({'error': 'username or password incorrect'}) if not is_lecturer(user): return JsonResponse({'error': 'you are not authorized'}) auth.login(request, user) return redirect('lecturer:index')
def post(self, request, *args, **kwargs): action = request.POST.get('action') question_group_id = request.POST.get('question_group') live_course_timeslot_id = request.POST.get('live_course_timeslot') response = JsonResponse({'ok': False, 'msg': '????', 'code': -99}) if action == 'start': response = self.set_exercise_session( live_course_timeslot_id=live_course_timeslot_id, question_group_id=question_group_id, is_active=True, ) elif action == 'stop': response = self.set_exercise_session( live_course_timeslot_id=live_course_timeslot_id, question_group_id=question_group_id, is_active=False, ) return response
def set_exercise_session(self, live_course_timeslot_id, question_group_id, is_active): question_group = get_object_or_404( models.QuestionGroup, pk=question_group_id ) live_course_timeslot = get_object_or_404( models.LiveCourseTimeSlot, pk=live_course_timeslot_id ) exercise_session, created = models.ExerciseSession.objects.get_or_create( live_course_timeslot=live_course_timeslot, question_group=question_group) exercise_session.is_active = is_active exercise_session.save() return JsonResponse({'ok': True, 'msg': 'OK', 'code': 0, 'sid': exercise_session.id})
def get(self, request): hours = int(request.GET.get('hours')) teacher = get_object_or_404( models.Teacher, pk=request.GET.get('teacher')) assert hours % 2 == 0 assert hours > 0 hours = min(hours, 200) # Only return first 100 timeslots weekly_time_slots = request.GET.get('weekly_time_slots').split() weekly_time_slots = [get_object_or_404(models.WeeklyTimeSlot, pk=x) for x in weekly_time_slots] data = models.Order.objects.concrete_timeslots( hours, weekly_time_slots, teacher) data.sort(key=lambda x: x['start']) data = [(int(x['start'].timestamp()), int(x['end'].timestamp())) for x in data] return JsonResponse({'data': data})
def doDeleteCert(self, request): context, teacher = self.getContextTeacher(request) certId = request.POST.get('certId') if not certId: return JsonResponse({'ok': False, 'msg': '????', 'code': 1}) try: cert = models.Certificate.objects.get(id=certId, teacher=teacher) if cert.type and cert.type != models.Certificate.OTHER: return JsonResponse({'ok': False, 'msg': '???????????', 'code': 4}) cert.delete() return JsonResponse({'ok': True, 'msg': '', 'code': 0}) except models.Certificate.DoesNotExist as e: logger.warning(e) return JsonResponse({'ok': False, 'msg': '?????????', 'code': 2}) except Exception as err: logger.error(err) return JsonResponse({'ok': False, 'msg': '????,?????,??????!', 'code': -1})
def handle_post(self, request, user, teacher, student_type, page_offset, student_id): title = request.POST.get('title') content = request.POST.get('content') context = { 'student_type': student_type, 'page_offset': page_offset, 'student_id': student_id } self.setSidebarContent(teacher, context) student = None try: student = models.Parent.objects.get(id=student_id) except: return JsonResponse({'ok': False, 'msg': 'student not find', 'code': -1}) canLetter, letterId = student.check_month_letter(teacher) if not canLetter: return JsonResponse({'ok': False, 'msg': 'already have letter', 'id': letterId, 'code': -2}) letter = models.Letter(teacher=teacher, parent=student, title=title, content=content) letterId = letter.save() return JsonResponse({'ok': True, 'id': letterId, 'code': 0})
def handle_post(self, request, user, teacher, *args, **kwargs): new_ids_str = request.POST.get('new_ids') removed_ids_str = request.POST.get('removed_ids') new_ids = new_ids_str and [s for s in new_ids_str.split('+') if s and s.strip() != ''] or None removed_ids = removed_ids_str and [s for s in removed_ids_str.split('+') if s and s.strip() != ''] or None if not new_ids and not removed_ids: return JsonResponse({'ok': False, 'msg': '????', 'code': 1}) if new_ids: new_ts_set = models.WeeklyTimeSlot.objects.filter(id__in=new_ids) for s in new_ts_set: teacher.weekly_time_slots.add(s) if removed_ids: removed_ts_set = models.WeeklyTimeSlot.objects.filter(id__in=removed_ids) for s in removed_ts_set: teacher.weekly_time_slots.remove(s) return JsonResponse({'ok': True, 'msg': 'ok', 'code': 0})
def schools_distance(self, request): lat = request.POST.get('lat') lng = request.POST.get('lng') tid = request.POST.get('tid') if lat is None or lat == '' or lng is None or lng == '': return JsonResponse({'ok': False}) lat = float(lat) lng = float(lng) if tid: teacher = models.Teacher.objects.get(id=tid) schools = teacher.schools.filter(opened=True) else: schools = models.School.objects.filter(opened=True) distances = [] p = {'lat': lat, 'lng': lng} for school in schools: if school.latitude is None or school.longitude is None: distances.append({'id': school.id, 'far': ''}) continue sp = {'lat': school.latitude, 'lng': school.longitude} dis = calculateDistance(p, sp) distances.append({'id': school.id, 'far': dis}) return JsonResponse({'ok': True, 'list': distances})
def submit(request): if request.method=='POST': loginUser=request.session['user'] usr=hiuser.objects.get(user_id=loginUser) form=SubmissionForm(request.POST,request.FILES) if form.is_valid(): prob = problems.objects.get(pid=request.POST['pid']) obj=Submission(user_id=usr,pid=prob,fid=request.FILES['file'],lang=request.POST['lang']) obj.save() res=run.delay(request.POST['pid'],obj.fid.name,obj.lang,loginUser) obj.tid=res.task_id obj.save() hashinclude_channel_push({'pid':request.POST['pid'],'lang':obj.lang,'tid':res.task_id,'result':'PENDING'}) #taskobj=submissionTask(user_id=usr,tid=res.task_id) #taskobj.save() return JsonResponse({'taskid':res.task_id}) else: return JsonResponse({'result':'Error'})
def handShake(request): if request.session.get('logged_in',False): user_id = request.session['user'] if not User.objects.filter(user_id=user_id).exists(): home_user = HomeUser.objects.get(user_id=user_id) User.objects.create( user_id=home_user.user_id, name=home_user.username, email = home_user.email, image_url = home_user.profile_picture, ) print("new user................") Portfolio.objects.create( user_id=user_id, net_worth=1000000.00, cash_bal=1000000.00, ) return JsonResponse({'success' : True}) else: return JsonResponse({'success' : False}) #======Dashboard======#
def companydetails(request): company = request.POST['company'] try: data_to_send = Stock_data.objects.get(symbol=company).as_dict() return JsonResponse(data_to_send) except: return JsonResponse({ 'result' : 'wrong company name!'} ) #======Buy/Short-Sell======# # buy() removed, since it is same as company info #======Submit-Buy======#
def history(request): username = request.session['user'] hist = History.objects.filter(user_id=username) hf = [] for i in hist: h = i.as_dict() h['time'] = h['time'].strftime("%a %d %b %I:%M:%S %p") h['total']= (float(i.quantity) * float(i.price)) hf.append(h) data = { 'history' : hf, } return JsonResponse(data) #======To Get Current Price======#
def currPrice(request): user_id=request.session['user'] comp = request.POST['company'] curr_price = Stock_data.objects.get(symbol=comp).current_price portfo = Portfolio.objects.get(user_id=user_id) cash_bal = portfo.cash_bal margin = portfo.margin no_trans = portfo.no_trans data_to_send = { 'curr_price' : curr_price, 'cash_bal': cash_bal, 'margin' : margin, 'no_trans' : no_trans } return JsonResponse(data_to_send)
def autocomplete(request): query = request.GET.get('query') if query: warehouses = Warehouse.objects.all() suggestions = [] for warehouse in model_search(query, warehouses, Warehouse.search_fields): if warehouse.full_name not in suggestions: suggestions.append(warehouse.full_name) suggestions = suggestions[:10] else: suggestions = [] return JsonResponse({ 'query': query, 'suggestions': suggestions })
def submit_feedback(request): if request.method != "POST": return HttpResponse(code=400) arxiv_id = request.POST['arxivId'] jpg_data_b64 = request.POST.get('jpgData') if jpg_data_b64: jpg_data = base64.b64decode(jpg_data_b64) else: jpg_data = None text = request.POST['text'] feedback = Feedback( github_access_token=settings.GITHUB_ACCESS_TOKEN, repo_name=settings.FEEDBACK_REPO_NAME, project_id=settings.FEEDBACK_PROJECT_ID, column_id=settings.FEEDBACK_COLUMN_ID ) issue_url = feedback.create_issue(arxiv_id, text, jpg_data) return JsonResponse({'issue_url': issue_url})
def demo(request): ''' example data from our api ''' return JsonResponse({ "representatives": { "1": { "id": 1, "name": "Nancy Pelosi", "party": "d" }, "2": { "id": 2, "name": "Paul Ryan", "party": "r" }, "3": { "id": 3, "name": "Rick Scott", "party": "r" } }, "committees": { "1": { "id": 1, "name": "Guns for Americans" }, "2": { "id": 2, "name": "Right to Rise" }, "3": { "id": 3, "name": "Pro Life PAC" } }, "bills": { "1": { "id": 1, "name": "Club Baby Seal Act of 2017" }, "2": { "id": 2, "name": "Dirty Water Act" }, "3": { "id": 3, "name": "No More Handouts Act" } }, "donations": [ { "from": 1, "to": 1, "amount": 100 }, { "from": 1, "to": 1, "amount": 100 }, { "from": 1, "to": 1, "amount": 100 }, { "from": 1, "to": 2, "amount": 300 }, { "from": 2, "to": 2, "amount": 700 }, { "from": 2, "to": 3, "amount": 50 }, { "from": 3, "to": 1, "amount": 200 }, { "from": 3, "to": 3, "amount": 400 } ], "votes": [ { "from": 1, "to": 1, "pass": "true" }, { "from": 1, "to": 2, "pass": "false" }, { "from": 1, "to": 3, "pass": "false" }, { "from": 2, "to": 1, "pass": "true" }, { "from": 2, "to": 2, "pass": "true" }, { "from": 2, "to": 3, "pass": "true" }, { "from": 3, "to": 1, "pass": "false" }, { "from": 3, "to": 2, "pass": "true" }, { "from": 3, "to": 3, "pass": "false" } ] })
def search(request): ''' Searches through all available sources to match the user's query ''' query = request.GET["query"] ## match the query against a zipcode regex, go a zipcode search if it matches if re.match("^\d{5}$", query): ## here we call an external api to search for the reps via zipcode results = SunlightAPI().rep_by_zip(query) ## loop through the results reps = [] for rep in results["results"]: ## try finding the rep in our database reps += (Representative.objects.all() .annotate(name=Concat('first_name', Value(" "), 'last_name')) .filter(name=rep["first_name"]+" "+rep["last_name"]) .values("id", "name", "party")) ## return the found reps return JsonResponse({"representatives": reps, "committees": []}) data = {} data["representatives"] = list(Representative.objects.all() .annotate(name=Concat('first_name', Value(" "), 'last_name')) .filter(name__icontains=query) .values("id", "name", "party")) data["committees"] = list(SuperPAC.objects.filter(name__icontains=query) .values("id", "name")) if "." in query or len(query) > 5: results = SunlightAPI().search(query) data["bills"] = results["results"] return JsonResponse(data)
def get(self, request): obj = self.get_obj() return JsonResponse({'value': obj.value})
def sales_api(request): startTime_month = timezone.now() - datetime.timedelta(days=30) qs = (Sale.objects .filter(timestamp__gt=startTime_month) .annotate(day=TruncDay('timestamp')) .values('day') .annotate(c=Count('*')) .annotate(r=Sum('price')) ) db_sales = {i["day"].date(): (i["c"], money(i["r"])) for i in qs} base = timezone.now().date() date_list = [base - datetime.timedelta(days=x) for x in range(0, 30)] sales_list = [] revenue_list = [] for date in date_list: if date in db_sales: sales, revenue = db_sales[date] sales_list.append(sales) revenue_list.append(revenue) else: sales_list.append(0) revenue_list.append(0) items = { "day": date_list, "sales": sales_list, "revenue": revenue_list, } return JsonResponse(items)
def user_like_response(request): """ ajax ile arkaplanda t?klanan cümlenin databasedeki skorunu çekiyor """ id = request.GET.get("id", None) data = { "score": Post.objects.filter(id=id)[0].score } return JsonResponse(data)
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() })
def render_to_json_response(self, context, **response_kwargs): """Return a JSON response, transforming 'context' for the payload.""" return JsonResponse( self.get_data(context), **response_kwargs )