def create(request): if request.method == "GET": # list departments departments = Department.objects.all() return render(request, 'item/add.html', {'all_departments': departments}) else: visableres = json.loads('visable') if visableres == 'on': result = True else: result = False all_departments = Department.objects.filter( id__in=json.loads('department_id')) instance = Item.objects.create(name=json.loads('name'), description=json.loads('description'), price=json.loads('price'), visableres=True) instance.department.set(all_departments) # multiple images # image = request.FILES.getlist("file[]") # for img in image: # fs = FileSystemStorage() # file_path = fs.save(img.name, img) # # pimage = images(product_id=instance, image=file_path) # pimage.save() return redirect('item_list')
def login_faculty(request): if request.method == "POST": #Login_Form = LoginForm(request.POST) #if Login_Form.is_valid(): email = json.loads(request.body.decode("utf-8"))['email'] password = json.loads(request.body.decode("utf-8"))['password'] #hash_password = pbkdf2_sha256.encrypt(password,rounds=300000, salt_size=32) try: #print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") #hash=pbkdf2_sha256.using(rounds=8000, salt_size=10).hash(Login_Form.cleaned_data["password"]) authority_object = Authority.objects.get( aemail=email, atype='faculty', ) #print("errorerrrrrrfrom django.shortcuts import render, render_to_responserrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr") #user_login=pbkdf2_sha256.using(rounds=200000, salt_size=32).verify(Login_Form.cleaned_data["password"], authority_object.password) except Exception as e: #messages.info(request, 'Login Failed') print("Login Failed" + str(e)) dbpassword = authority_object.apassword if pbkdf2_sha256.verify(password, dbpassword): request.session["sessionid"] = authority_object.aid return JsonResponse({'url': "/faculty/"}, safe=False)
def report(request, id=None): if request.method == 'POST': placeid = id if not request.session.get('sessionid', None): return HttpResponse("Login required") sessionid = request.session['sessionid'] quesid = json.loads(request.body.decode('utf-8'))["quesid"] newreport = json.loads(request.body.decode('utf-8'))["report"] #print (str(newreport)+" "+str(quesid)) try: status_obj = People_Question_Status.objects.get(quesid=quesid, placeid=placeid, userid=sessionid) #print ("In the try section") status_obj.report = newreport status_obj.save() except Exception as e: entry_status_obj = People_Question_Status( quesid=People_Question(quesid), placeid=Place(placeid), userid=People(sessionid), report=newreport) #print ("In the exception state") entry_status_obj.save() return HttpResponse()
def answervoting(request, id=None): global newanswerstatus if request.method == 'POST': if not request.session.get('sessionid', None): return HttpResponse("Login required") sessionid = request.session['sessionid'] quesid = json.loads(request.body.decode('utf-8'))["quesid"] placeid = id answerid = json.loads(request.body.decode('utf-8'))["answerid"] try: answer_upvote_obj = People_Answer_Status.objects.get( questionid=quesid, answerid=answerid, userid=sessionid, placeid=placeid) #print("In the try state " + str(quesid) + " " + str(answerid) + " " + str(sessionid)) if answer_upvote_obj: answerstatus = answer_upvote_obj.answerstatus if answerstatus == False: answer_upvote_obj.answerstatus = True answer_upvote_obj.save() newanswerstatus = True elif answerstatus == True: answer_upvote_obj.answerstatus = False answer_upvote_obj.delete() newanswerstatus = False except Exception as e: #print ("In the exception state "+str(quesid)+" "+str(answerid)+" "+str(sessionid)) entry_answer = People_Answer_Status( answerid=People_Answer(answerid), questionid=People_Question(quesid), placeid=Place(placeid), userid=People(sessionid), answerstatus=True, answerreport='none') entry_answer.save() newanswerstatus = True #print(entry_answer.answerstatus) new_answer_status_like = People_Answer_Status.objects.filter( questionid=quesid, answerid=answerid, placeid=placeid, answerstatus=True) count_new_answer_status_like = len(new_answer_status_like) context_answer_like = {} context_answer_like['userid'] = sessionid context_answer_like['placeid'] = placeid context_answer_like['quesid'] = quesid context_answer_like['answerid'] = answerid context_answer_like['answerstatus'] = newanswerstatus context_answer_like['noofanswerlike'] = count_new_answer_status_like return JsonResponse(context_answer_like)
def answerreport(request, id=None): if request.method == 'POST': placeid = id if not request.session.get('sessionid', None): return HttpResponse("Login required") sessionid = request.session['sessionid'] quesid = json.loads(request.body.decode('utf-8'))['quesid'] answerid = json.loads(request.body.decode('utf-8'))['answerid'] newanswerreport = json.loads( request.body.decode('utf-8'))['answerreport'] try: answer_status_obj = People_Answer_Status.objects.get( answerid=answerid, questionid=quesid, placeid=placeid, userid=sessionid) #print("In the try state " + str(quesid) + " " + str(answerid) + " " + str(sessionid)) answer_status_obj.answerreport = newanswerreport answer_status_obj.save() except Exception as e: #print("In the exception state " + str(quesid) + " " + str(answerid) + " " + str(sessionid)) entry_answer_status_obj = People_Answer_Status( answerid=People_Answer(answerid), questionid=People_Question(quesid), placeid=Place(placeid), userid=People(sessionid), answerreport=newanswerreport) entry_answer_status_obj.save() return HttpResponse()
def collect(sc): print("collect data...") conn = http.client.HTTPConnection("localhost:8080") conn.request("GET", "/get/tools") r1 = conn.getresponse() response = r1.read() # what will happen if response code will be not 200 conn.close() response = response.decode("utf-8") decoded = json.loads(response) ToolsActivate.objects.all().delete() Tools.objects.all().delete() Actions.objects.all().delete() for x in decoded["ToolsActivate"]: # print(decoded[x][subsection]) dd = ToolsActivate(name=x["Name"], countUse=x["CountUse"], time = x["Time"]) dd.save() for x in decoded["ToolsUse"]: # print(decoded[x][subsection]) dd = Tools(name=x["Name"], countUse=x["CountUse"], time = x["Time"]) dd.save() #actions conn = http.client.HTTPConnection("localhost:8080") conn.request("GET", "/get/actions") r1 = conn.getresponse() response = r1.read() # what will happen if response code will be not 200 conn.close() response = response.decode("utf-8") decoded = json.loads(response) for x in decoded["Actions"]: # print(decoded[x][subsection]) dd = Actions(name=x["Name"], countUse=x["CountUse"]) dd.save() s.enter(3600, 1, collect, (sc,)) #updates every hour
def login_proctor(request): if request.method == "POST": #Login_Form = LoginForm(request.POST) #if Login_Form.is_valid(): email = json.loads(request.body.decode("utf-8"))['email'] password = json.loads(request.body.decode("utf-8"))['password'] #hash_password = pbkdf2_sha256.encrypt(password,rounds=500000, salt_size=32) #print("The hashed password is"+str(hash_password)) try: #print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") #hash=pbkdf2_sha256.using(rounds=8000, salt_size=10).hash(Login_Form.cleaned_data["password"]) authority_object = Authority.objects.get(aemail=email, atype='Proctore') #print("errorerrrrrrfrom django.shortcuts import render, render_to_responserrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr") #user_login=pbkdf2_sha256.using(rounds=200000, salt_size=32).verify(Login_Form.cleaned_data["password"], authority_object.password) except Exception as e: #messages.info(request, 'Login Failed') print("Login Failed " + str(e)) dbpassword = authority_object.apassword print("The database password is " + str(dbpassword)) if pbkdf2_sha256.verify(password, dbpassword): request.session["sessionid"] = authority_object.aid #return HttpResponseRedirect("/index/student/") #return render_to_response('student.html') #return redirect("/index/student/") return JsonResponse({'url': "/proctor/"}, safe=False)
def loadProjectPlans(request, slug): plans = ProjectPlan.objects.filter(project_id=slug) data = {} if plans: plansArr = json.loads(serializers.serialize("json", plans)) data['plans'] = json.loads(plansArr[0].get("fields").get("content")) else: data['plans'] = [] return JsonResponse(data)
def kmeans(request): if request.is_ajax(): if request.method == 'POST': print(request.POST) data = request.POST.getlist('request_data') tmp = json.loads(data[0]) for i in tmp: print(i) # print("tmp", tmp) data2 = request.POST.getlist('centeroid') tmp2 = json.loads(data2[0]) step = request.POST['step'] while True: tmpX = [[], [], []] tmpY = [[], [], []] for i in range(0, 20): tmp3 = [] for j in range(0, 3): tmp3.append([ math.sqrt((float(tmp[i]['age']) - float(tmp2[j]['x']))**2 + (float(tmp[i]['spend']) - float(tmp2[j]['y']))**2), j ]) tmp[i]['class'] = min(tmp3)[1] + 1 tmpX[min(tmp3)[1]].append(float(tmp[i]['age'])) tmpY[min(tmp3)[1]].append(float(tmp[i]['spend'])) # print(avg(tmpX[0]),avg(tmpX[1]),avg(tmpX[2])) # print(avg(tmpY[0]), avg(tmpY[1]), avg(tmpY[2])) if tmp2[0]['x'] == avg(tmpX[0]) and tmp2[1]['x'] == avg(tmpX[1]) and tmp2[1]['x'] == avg(tmpX[1]) and \ tmp2[0]['y'] == avg(tmpY[0]) and tmp2[1]['y'] == avg(tmpY[1]) and tmp2[2]['y'] == avg(tmpY[2]): step = '-1' return HttpResponse( json.dumps({ 'DATA': tmp, 'CEN': tmp2, 'STEP': step }), 'application/json') else: tmp2[0]['x'] = avg(tmpX[0]) tmp2[1]['x'] = avg(tmpX[1]) tmp2[2]['x'] = avg(tmpX[2]) tmp2[0]['y'] = avg(tmpY[0]) tmp2[1]['y'] = avg(tmpY[1]) tmp2[2]['y'] = avg(tmpY[2]) step = int(step) + 1 print(tmp) print(tmp2) # if step == -1: # return HttpResponse(json.dumps({'DATA':tmp, 'CEN': tmp2, 'STEP' : step}), 'application/json') return render(request, 'index/cluster.html')
def change_settings(request): if request.method == 'POST': if not request.session.get('sessionid', None): return HttpResponse("Login required") sessionid = request.session('sessionid', None) name = json.loads(request.body.decode('utf-8'))['name'] email = json.loads(request.body.decode('utf-8'))['email'] phone = json.loads(request.body.decode('utf-8'))['phone'] branch = json.loads(request.body.decode('utf-8'))['branch'] designation = json.loads(request.body.decode('utf-8'))['designation'] try: authority_object = Authority.objects.get(aid=sessionid) except Exception as e: print("The exception is " + str(e)) if name is not None: authority_object.aname = name if email is not None: authority_object.aemail = email if phone is not None: authority_object.aphone = phone if branch is not None: authority_object.branch = branch if designation is not None: authority_object.designation = designation authority_object.save() try: new_authority_object = Authority.objects.get(aid=sessionid) except Exception as e: print("The exception is " + str(e)) newemail = new_authority_object.aemail newname = new_authority_object.aname newphone = new_authority_object.aphone newbranch = new_authority_object.abranch newdesignation = new_authority_object.designation context_authority = {} context_authority['email'] = newemail context_authority['name'] = newname context_authority['phone'] = newphone context_authority['branch'] = newbranch context_authority['designation'] = newdesignation print("The context authority is" + str(context_authority)) return JsonResponse(context_authority, safe=False)
def post_detail(self, request, **kwargs): print "COSM UPDATE!" store_id=int(request.path.split("/")[-2]) ce = COSMSource.objects.get(id=store_id) #Uuuugh. Sorry! try: print "Trying to get post stuff" data_string = request.POST['body'] data = json.loads(data_string) except Exception as e: print "Trying raw data instead" data = json.loads(request.raw_post_data) print "Got data:",data print "Data:",data ce.receive_data(data) return {"OK":"True"}
def add_records_to_db(request): if request.method == 'POST': boundary = "" gridList = json.loads(request.POST.get('grids', None)) commentText = request.POST.get('comment', None) emotionsList = json.loads(request.POST.get('emotions', None)) if not str(commentText).strip(): commentText = "NA" for index in range(len(gridList)): boundary = boundary + gridList[index]["id"] result = rhealpix_services.addRecordAPIcall(boundary, commentText, emotionsList) return HttpResponse(result.text)
def download_all_records_csv(request): if request.method == 'GET': import requests import json import re import csv output = [] url = "http://127.0.0.1:8000/bdatasets/" mongo_response = requests.get(url) json_response = json.loads(mongo_response.text) for record in json_response: row = {} cells = record["boundary_data_set"][0]["boundary"] for cell in re.findall('[A-Z][^A-Z]*', cells): row["cell"] = cell row["emotion"] = record["boundary_data_set"][0]["data"]["emotions"] row["comment"] = record["boundary_data_set"][0]["data"]["comment"] output.append(row) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="one.csv"' writer = csv.writer(response) writer.writerow(['cell', 'emotion', 'comment']) for x in output: te = [x['cell'], x['emotion'], x['comment']] writer.writerow(te) return response
def getorderedwishlist(request): data = request.body.decode('utf-8') dataJson = json.loads(data) content1 = dataJson['userID'] content2 = dataJson['orderBy'] if(content2=="price"): print("byprice") cursor = connection.cursor() cursor.execute("SELECT db_Product.productID FROM db_Wishlist JOIN db_Product ON db_Wishlist.productID=db_Product.productID WHERE db_Wishlist.buyerID="+str(content1)+" ORDER BY db_Product.price ASC ;") solution=cursor.fetchall() else: print("bycat") cursor = connection.cursor() cursor.execute( "SELECT db_Product.productID FROM db_Wishlist JOIN db_Product ON db_Wishlist.productID=db_Product.productID WHERE db_Wishlist.buyerID="+str(content1)+" ORDER BY db_Product.catID ASC ;") solution = cursor.fetchall() list: [Wishlist] = [] for x in solution: list.append(x) print(list) list2: [int] = [] for a in list: print(a) o = a[0] list2.append(o) a = {'OrderedWishList': [list2]} return JsonResponse(a)
def profile(request): data1 = request.body.decode('utf-8') dataJson = json.loads(data1) content1 = dataJson['userID'] # create new list for getting each object out of U # U ja ork ma pen [<Order: Order object>, <Order: Order object>] tong aow data ork ma # User has to be the same with in models U = list(User.objects.filter(userID=content1)) print(U) # put data from U into another list try: for a in U: phone = str(a.phoneNumber) print(phone) uid = str(a.userID) print(uid) u = make_profile(uid, phone) profile1.append(u) print(profile1) except: print("Error: unable to fetch data") b = {'profile': makeDict(profile1)} print(b) # return HttpResponse(U) # wela ja send data to xcode return JsonResponse(b)
def product(request): data1 = request.body.decode('utf-8') dataJson = json.loads(data1) content3 = dataJson['orderID'] M = list(Order.objects.filter(orderID=content3)) print(M) product1: [Product] = [] try: for a in M: o = str(a.orderID) print(o) p = str(a.productID) print(p) # except: print("Error: unable to fetch data") L = list(Product.objects.filter(productID=p)) # # return HttpResponse(U) try: for c in L: s = str(c.sellerID) print(s) productA = make_product(s) product1.append(productA) except: print("pung") a = {'product': makeDict(product1)} print(a) # # wela ja send data to xcode return JsonResponse(a)
def particular_authority(request): if request.method == 'POST': if not request.session.get('sessionid', None): return HttpResponse("Login required") sessionid = request.session('sessionid', None) atype = json.loads(request.body.decode('utf-8'))['atype'] try: authority_object = Authority.objects.filter(atype=atype) except Exception as e: print("The exception is" + str(e)) context_authority = {} context_authority_list = [] for authority in authority_object: context_authority['name'] = authority.aname context_authority['phone'] = authority.aphone context_authority['email'] = authority.aemail context_authority['branch'] = authority.abranch context_authority['designation'] = authority.adesignation print("This is context " + str(context_authority)) context_authority_list.append(context_authority) print("The context authority list is" + str(context_authority_list)) return JsonResponse(context_authority_list, safe=False)
def put(self, request, *args, **kwargs): if request.content_type == 'text/plain;charset=UTF-8': data = json.loads(request.body.decode('utf-8')) else: data = request.data user = get_user_from_request(request) form = UserForm(data) if form.is_valid(): user.first_name = data.get('first_name') user.last_name = data.get('last_name') user.contact = data.get('vk') if data.get('image'): user_avatar = request.data.get('image') upload_path = 'avatar/{}.jpg'.format(user.id) upload_file(upload_path, user_avatar) user.avatar = MEDIA_URL + upload_path user_notification = get_object_or_404(UserSubscription, user=user) if data.get('notification') is not None: user_notification.email_notification = data.get('notification') user_notification.save() user.save() serializer = self.get_serializer(user) data = serializer.data return JsonResponse({ **{ 'notification': user_notification.email_notification }, **data }) else: return JsonResponse( {'detail': 'Ошибка создания, проверьте данные'}, status=400)
def post(self, request): data = json.loads(request.body) try: self.sendEmail(data) return JsonResponse({'response': 'OK'}) except: return JsonResponse({'response': 'FAIL'})
def getProductIDByOrder(request): data1=request.body.decode('utf-8') dataJson = json.loads(data1) content1 = dataJson['orderID'] U,=Order.objects.filter(orderID=content1) productID=U.productID return HttpResponse(str(productID))
def get_filters(self, request): _search = request.GET.get('_search') filters = None if _search == 'true': _filters = request.GET.get('filters') try: filters = _filters and json.loads(_filters) except ValueError: return None if filters is None: field = request.GET.get('searchField') op = request.GET.get('searchOper') data = request.GET.get('searchString') if all([field, op, data]): filters = { 'groupOp': 'AND', 'rules': [{ 'op': op, 'field': field, 'data': data }] } return filters
def PhoneVerificationView(request, **kwargs): if request.method == "POST": username = request.POST['username'] user = User.objects.get(username=username) form = PhoneVerificationForm(request.POST) if form.is_valid(): verification_code = request.POST['one_time_password'] response = verify_sent_code(verification_code, user) print(response.text) data = json.loads(response.text) if data['success'] == True: login(request, user) if user.phone_number_verified is False: user.phone_number_verified = True user.save() return redirect('/dashboard') else: messages.add_message(request, messages.ERROR, data['message']) return render(request, " ", {'user': user}) else: context = { 'user': user, 'form': form, } return render(request, " ", context) elif request.method == "GET": try: user = kwargs['user'] return render(request, " ", {'user': user}) except: return HttpResponse("Not Allowed")
def new_photo(request): if request.method == 'POST': data = json.loads(request.body) new_photo = droneshare.objects.create( photo=data['photo'], ) return HttpResponse(json.dumps(new_photo), content_type='application/json')
def removefrommywishlist(request): data = request.body.decode('utf-8') dataJson = json.loads(data) content1 = dataJson['productID'] content2 = dataJson['buyerID'] Wishlist.objects.filter(productID=content1,buyerID=content2).delete() return HttpResponse("success")
def put(self, request): data = json.loads(request.body.decode()) selected = data.get('selected') user = request.user #判断用户是否登录 if user.is_authenticated: #已登录 conn = get_redis_connection('carts') cart_dict = conn.hgetall('carts_%' % user.id) sku_ids = cart_dict.keys() # 2、设置全/全取消 if selected: conn.sadd('selected_%s' % user.id, *sku_ids) else: conn.srem('selected_%s' % user.id, *sku_ids) return JsonResponse({'code': 0, 'errmsg': 'ok'}) else: # 未登录 cookie_str = request.COOKIES.get('carts') cart_dict = carts_cookie_decode(cookie_str) #判断选中状态 sku_ids = cart_dict.keys() for sku_id in sku_ids: cart_dict[sku_id]['selected'] = selected #覆盖写入cookie购物车 cookie_str = carts_cookie_encode(cart_dict) response = JsonResponse({'code': 0, 'errmsg': "ok"}) response.set_cookie("carts", cookie_str) return response
def delete(self, request): data = json.loads(request.body.decode()) sku_id = data.get('sku_id') user = request.user #已登录 if user.is_authenticated: conn = get_redis_connection('carts') # 1.1 删除购物车哈希数据——carts_user_id : {sku_id : count} conn.hdel('carts_%s' % user.id, sku_id) #删除集合中的sku_id conn.srem('selected_%s' % user.id, sku_id) return JsonResponse({'code': 0, 'errmsg': 'ok'}) else: #获取cookie购物车数据 cookie_str = request.COOKIES.get('carts') cart_dict = carts_cookie_decode(cookie_str) #删除cookie购物车字典中的sku_id键值对 if sku_id in cart_dict: cart_dict.pop(sku_id) #新的数据写入cookie中 cart_str = carts_cookie_encode(cart_dict) response = JsonResponse({ 'code': 0, 'errmsg': 'ok', }) response.set_cookie('carts', cart_dict) return response
def order(request): data1 = request.body.decode('utf-8') dataJson = json.loads(data1) content1 = dataJson['userID'] # create new list for getting each object out of U # U ja ork ma pen [<Order: Order object>, <Order: Order object>] tong aow data ork ma U = list(Order.objects.filter(buyerID=content1, confirmedStatus=0)) print(U) order1: [Order] = [] # put data from U into another list try: for a in U: o = str(a.orderID) print(o) c = bool(a.confirmedStatus) print(c) orderA = make_order(o,c) order1.append(orderA) print(order1) except: print("Error: unable to fetch data") a = {'orderID': makeDict(order1)} print(a) # return HttpResponse(U) # wela ja send data to xcode return JsonResponse(a)
def register(request): data1 = request.body.decode('utf-8') dataJson = json.loads(data1) content1 = dataJson['phoneNum'] content2 = dataJson['password'] U = User.objects.create(phoneNumber=content1, password=content2) return HttpResponse("success")
def addtowishlist(request): data = request.body.decode('utf-8') dataJson = json.loads(data) content1 = dataJson['productID'] content2 = dataJson['userID'] U = Wishlist.objects.create(productID=content1,buyerID=content2) return HttpResponse("success")
def create_category(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) new_category = Category(name=body["name"]) new_category.competition = Competition.objects.get(pk=body["competitionId"]) new_category.save() return HttpResponse(json.dumps(new_category.as_json()), content_type="application/json")
def modifyBasicAccount(self, cookie, data): url = "http://www.cloudsim.ml:8090/modifyBasicAccount" iccid = data['iccid'] imsi = data['imsi'] operatorName = data['operatorName'] mcc = data['mcc'] operatorId = data['operatorId'] mainBalance = data['mainBalance'] expiresTime = data['expiresTime'] r = requests.post( url, cookies=cookie, header=modifyAccountResource.hd, data={ 'iccid': iccid, 'imsi': imsi, 'operatorName': operatorName, 'mcc': mcc, 'operatorId': operatorId, 'mainBalance': mainBalance, 'expiresTime': expiresTime, 'oldBasicStr': '{"id":null,"iccid":"8986011785112933841","imsi":"460012018633614","mcc":"460","operatorId":"46001","operatorName":"中国联通","mainBalance":1.9,"expiresTime":1522512000000,"planId":null,"lastUpdateTime":null}' }) r.text() result = json.loads(r.text) print('操作结果:', result['msg'])
def dispatch(self, request, name=None): if not name: raise Http404 # Check if the function is callable if dajaxice_functions.is_callable(name, request.method): function = dajaxice_functions.get(name) data = getattr(request, function.method).get("argv", "") # Clean the argv if data != "undefined": try: data = safe_dict(json.loads(data)) except Exception: data = {} else: data = {} # Call the function. If something goes wrong, handle the Exception try: response = function.call(request, **data) except Exception: if settings.DEBUG: raise response = dajaxice_config.DAJAXICE_EXCEPTION return HttpResponse(response, mimetype="application/x-json") else: raise FunctionNotCallableError(name)
def dehydrate(self, bundle): # detect if detail if self.get_resource_uri(bundle) == bundle.request.path: # detail detected, add graph as json try: bundle.data['graph'] = json.loads(bundle.obj.graph) except ValueError: logger.error("Failed to decode workflow graph into dictionary for workflow " + str(bundle.obj) + ".") # don't include in response if error occurs bundle.data['author'] = bundle.obj.get_owner() bundle.data['galaxy_instance_identifier'] = bundle.obj.workflow_engine.instance.api_key return bundle
def post_detail(self, request, **kwargs): store_id=int(request.path.split("/")[-2]) log.info("cosm update for datastore %d" % store_id) ce = COSMSource.objects.get(id=store_id) # Uuuugh. Sorry! data_string = request.POST.get('body') or request.raw_post_data data = json.loads(data_string) log.debug("data is %s" % data) try: ce.receive_data(data) return {"OK":"True"} except Exception as e: log.exception("cosm update failed: %s" % str(e))
def get_filters(self, request): _search = request.GET.get('_search') filters = None if _search == 'true': _filters = request.GET.get('filters') try: filters = _filters and json.loads(_filters) except ValueError: return None if filters is None: field = request.GET.get('searchField') op = request.GET.get('searchOper') data = request.GET.get('searchString') if all([field, op, data]): filters = { 'groupOp': 'AND', 'rules': [{'op': op, 'field': field, 'data': data}] } return filters
def get(self,request,*args,**kwargs): mensajes_Error = {} datosJson = {} try: data = request.GET['objetos'] timestamp = int(time.time()) broker = '192.168.1.6' port = 1883 datosJson = json.loads(data) #*********************MQTT PUBLICADOR****************** topic = 'sensor/luminico' message = datosJson['valor'] mqttclient = mqtt.Client("mqtt-panel-test", protocol=mqtt.MQTTv311) mqttclient.connect(broker, port=int(port)) mqttclient.publish(topic, message) #time.sleep(2) mensajes_Error['message'] = "Se ha publicado un mensaje en el topico SENSOR/luminico" mensajes_Error['result'] = "OK" return HttpResponse(json.dumps(mensajes_Error), content_type="application/json") except Exception as error: print("Error al guardar-->transaccion" + str(error)) mensajes_Error['message'] = "Ha ocurrod un error al publicar" mensajes_Error['result'] = "X" return HttpResponse(json.dumps(mensajes_Error), content_type="application/json")
def view_history(request, dochistorycode): docHistory = DocumentHistory.objects.get(id=int(dochistorycode)) snapshot = json.dumps(json.loads(docHistory.snapshot), indent=4) return render(request, 'doc/dochistory_detail.html', {'document': docHistory.document, 'docHistory': docHistory, 'snapshot': snapshot})
def json_deserialize(json): return json.loads(json, to_raw_data)
def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_ajax(): if form.is_valid(): in_data = json.loads(request.body)
def from_json(self, content): data = json.loads(content) return data