def shipments_with_customer_as(request, customer_id, role): if request.method == 'GET': if role == 'shipper': print('inside SHIPPER') shipments_queryset = Shipment.objects.filter(shipper=customer_id) print('queryset RETRIEVED') json_ready = list(shipments_queryset) print('json_ready READY') shipments_data = serializers.serialize('json', json_ready) print('READY TO RETURN RESPONSE') return Response(shipments_data) elif role == 'consignee': print('inside CONSIGNEE') shipments_queryset = Shipment.objects.filter(consignee=customer_id) print('queryset RETRIEVED') json_ready = list(shipments_queryset) print('json_ready READY') shipments_data = serializers.serialize('json', json_ready) print('READY TO RETURN RESPONSE') return Response(shipments_data) elif role == 'billto': print('inside BILLTO') shipments_queryset = Shipment.objects.filter(billto=customer_id) print('queryset RETRIEVED') json_ready = list(shipments_queryset) print('json_ready READY') shipments_data = serializers.serialize('json', json_ready) print('READY TO RETURN RESPONSE') return Response(shipments_data) else: return Response( 'error: customer role not shipper, consignee, or bill-to') else: return Response('error: not GET method')
def api_movie_list_view(request): if request.method == "GET": qs = Movie.objects.all() return HttpResponse(serializers.serialize("json", qs), content_type = "application/json") elif request.method == "POST": data = request.POST new_movie = Movie.objects.create(title=data['title']) return HttpResponse(serializers.serialize("json", [movie]), status=201, content_type="application/json")
def get_sport_name(self, obj): sports = obj.sport.all() # values('id','name') if sports: from django.core import serializers import ast sport_name = serializers.serialize("json", sports) sport_name = ast.literal_eval(sport_name) # new_list = [] # for i in range(len(sport_name)): # # new_list.append(sport_name[i]["fields"]["name"]) # sport_name = new_list keys = ['id', 'name'] array_length = len(sport_name) sport_list = [] for i in range(array_length): sport_dict = {} sport_dict.update({ keys[0]: (sport_name[i]["pk"]), keys[1]: (sport_name[i]["fields"]["name"]) }) dummy_dict = sport_dict sport_list.append(dummy_dict) # sport_name = x return sport_list
def mapview(request): from django.core import serializers json_data = serializers.serialize("json", Hostel_info.objects.all()) context = { 'json': json_data, } return render(request, 'CRUD/map.html', context)
def mobile_facebook_login(request): if request.method=="POST": response=HttpResponse access_token =str(request.POST['access_token']) #email=str(request.POST['email']) try: app=SocialApp.objects.get(provider="facebook") token=SocialToken(app=app,token=access_token) # Check token against facebook login = fb_complete_login(request, app, token) login.token = token login.state = SocialLogin.state_from_request(request) # Add or update the user into users table ret = complete_social_login(request, login) a=SocialToken.objects.get(token=access_token) try: account=a.account user=account.user user.backend = 'django.contrib.auth.backends.ModelBackend' profile=UserProfile.objects.get_or_create(user=user,dp=account.get_avatar_url(),fullName=user.get_full_name())[0] return HttpResponse(serializers.serialize("json",[profile])) except User.DoesNotExist: return HttpResponse("User Dosent Exist") return HttpResponse("wuhoo") except Exception as e: # If we get here we've failed return HttpResponse("ASdsa "+str(e))
def join_game(request): if request.method=="POST": id=str(request.POST['uuid']) access_token =str(request.POST['access_token']) type=str(request.POST['type']) #email=str(request.POST['email']) try: app=SocialApp.objects.get(provider="facebook") token=SocialToken(app=app,token=access_token) # Check token against facebook login = fb_complete_login(request, app, token) login.token = token login.state = SocialLogin.state_from_request(request) # Add or update the user into users table ret = complete_social_login(request, login) a=SocialToken.objects.get(token=access_token) try: account=a.account user=account.user game=Game.objects.create(id=id) game.participants.add(user) return HttpResponse(serializers.serialize("json",[game])) except User.DoesNotExist: return HttpResponse("User Dosent Exist") return HttpResponse("wuhoo") except Exception as e: # If we get here we've failed return HttpResponse("ASdsa "+str(e))
def displayAllFiles(request): files = fileController.getAllFiles() json = serializers.serialize('json', files) print(json) response = HttpResponse(files) response['Content-Type'] = 'application/json' response['Access-Control-Allow-Origin'] = '*' return response
def searchhostel(request): #in map from django.core import serializers try: search = request.GET['name'] except: return render(request, 'CRUD/clientpage.html', {'json': 'true'}) if (search != None): if (search == 'all hostel' or search == 'Hostels'): print('true') match = Hostel_info.objects.all() json_data = serializers.serialize("json", match) return render(request, 'CRUD/clientpage.html', {'json': json_data}) match = Hostel_info.objects.filter(Q(Hostel_name__icontains=search)) print(match) json_data = serializers.serialize("json", match) print(json_data) return render(request, 'CRUD/clientpage.html', {'json': json_data})
def stendent_api2(request): if request.method == "GET": datas = {} all = Stendent.objects.all() datas['infos'] = json.loads(serializers.serialize('json', all)) datas['total'] = len(all) res = {"code": 0, "msg": "success!", "data": datas} return JsonResponse(res, json_dumps_params={'ensure_ascii': False})
def voyages_using_tug(request, tug_id): if request.method == 'GET': voyages_queryset = Voyage.objects.filter(tug=tug_id) json_ready = list(voyages_queryset) voyages_data = serializers.serialize('json', json_ready) print(voyages_data) return Response(voyages_data) else: return Response('error: not GET method')
def shipments_using_equipment(request, equipment_id): if request.method == 'GET': shipments_queryset = Shipment.objects.filter(equipment=equipment_id) json_ready = list(shipments_queryset) shipments_data = serializers.serialize('json', json_ready) print(shipments_data) return Response(shipments_data) else: return Response('error: not GET method')
def ret_user(request): if request.method == "GET": #db = Stu.objects.all() #db = [i.name for i in db] user_list = Stu.objects.all() json = serializers.serialize("json", user_list) print(json) return JsonResponse({"status": 0, "data": json}) else: return JsonResponse({"status": 1, "message": "you need GET method"})
def equipment_of_type(request, customer_id): if request.method == 'GET': addresses_queryset = CustomerContact.objects.filter( customer_id=customer_id) json_ready = list(addresses_queryset) addresses_data = serializers.serialize('json', json_ready) print(addresses_data) return Response(addresses_data) else: return Response('error: not a GET method')
def nearest(request, h_long, h_lat): print(h_long, h_lat) h = Hostel_info.objects.all() shortest = {} long_lat = {} h_long = float(h_long) h_lat = float(h_long) innerlist = [] tupple = () finallist = [] def calc(h_long, h_lat, longi, lati): from math import sin, cos, sqrt, atan2, radians dlon = h_long - longi dlat = h_lat - lati a = sin(dlat / 2)**2 + cos(lati) * cos(h_lat) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) R = 6373.0 distance = R * c return distance index = {} k = 1 for each in h: innerlist.append(each.Hostel_long) innerlist.append(each.Hostel_lat) tupple = tuple(innerlist) finallist.append(tupple) innerlist.remove(each.Hostel_long) innerlist.remove(each.Hostel_lat) index.update({'hostel' + str(k): each.Hostel_name}) k = k + 1 i = 1 for each in finallist: long_lat.update({'hostel' + str(i): each}) i = i + 1 j = 1 for state in long_lat.values(): longi = float(state[0]) lati = float(state[1]) short = calc(h_long, h_lat, longi, lati) shortest.update({'hostel' + str(j): short}) j = j + 1 nearestvalue = max(shortest) nearesthostel = index.get(nearestvalue) from django.core import serializers match = Hostel_info.objects.filter(Hostel_name=nearesthostel) print(match) json_data = serializers.serialize("json", match) return render(request, 'CRUD/clientpage.html', {'json': json_data})
def recipe_rank(request, id): count_per_page = request.GET.get('count', 10) page = request.GET.get('page', 0) recipes = Recipe.objects.filter(nutrition__nutrition__id=id).order_by( 'nutrition__value')[page * count_per_page:count_per_page] data = serializers.serialize("json", recipes) response_kwargs = dict() response_kwargs['content_type'] = 'application/json' return HttpResponse(data, **response_kwargs)
def availableGemsThumbs_list(request): """ List all available Gems with url to Thumbnail """ if request.method == 'GET': qGemsAvailThumb = ThumbDisplays.objects.filter(gem__soldOut=False, gem__canPurchase=True) data = serializers.serialize( 'json', list(qGemsAvailThumb), fields=('url','gems.name','gems.description') ) return JSONResponse(data)
def ingredient_rank(request, id): count_per_page = request.GET.get('count', 10) page = request.GET.get('page', 0) ingredients = Ingredient.objects.filter(nutrition__nutrition__id=id).order_by('nutrition__value')[ page * count_per_page:count_per_page] data = serializers.serialize("json", ingredients) response_kwargs = dict() response_kwargs['content_type'] = 'application/json' return HttpResponse(data, **response_kwargs)
def view_order(request): from django.core import serializers qs = Order.objects.filter(user=request.user) id = [] for qs in qs: id.append(qs.id) queryset = OrderItem.objects.filter(order__in=id) import json serialized_obj = serializers.serialize('python', queryset) return Response(data=serialized_obj,status=HTTP_200_OK)
def signup(request): if request.method == 'POST': newUser = User( username=request.POST.get('username'), password=request.POST.get('password'), first_name=request.POST.get('first_name'), last_name=request.POST.get('last_name'), email=request.POST.get('email'), phone=request.POST.get('phone')) newUser.save() return HttpResponse(serializers.serialize("json", [newUser]))
def post(self, request): #bookstore_serializers = BookstoreSerializer(data = request.data) # data = list(Bookstore.objects.values()) # return JsonResponse(data, safe = False) bookstore_json = serializers.serialize('json', bookstore) if bookstore_serializers.is_valid(): bookstore_serializers.save() return Response(bookstore_serializers.data, status=status.HTTP_201_CREATED) return Response(bookstore_serializers.errors, status=status.HTTP_400_BAD_REQUEST)
def islogin(request): postBody = request.body result = json.loads(postBody) user = User.objects.filter(name=result['username']) if user.count() > 0: info = {"login": "******"} info2 = serializers.serialize("json", user) info["userinfo"] = json.loads(info2) return HttpResponse(json.dumps(info), content_type="application/json") else: info = {"login": "******", "userinfo": "null"} return HttpResponse(json.dumps(info), content_type="application/json")
def hall_search(request): data = [] search_form = SearchForm(request.GET) if search_form.is_valid(): encoded_search_term = urllib.parse.quote( search_form.cleaned_data['search_term']) halls = Hall.objects.filter(title__icontains=encoded_search_term) # response = requests.get(f'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q={encoded_search_term}&key={ YOUTUBE_API_KEY }') data = serializers.serialize('json', halls, fields=('title', 'id')) print(data) return JsonResponse(data, safe=False) return JsonResponse({'error': 'not able to find the videos'})
def get_rows(self, table_name): annotations = DynamicDBModelQuerySet(self)._get_custom_annotation( table_name) if annotations is None: qs = models.QuerySet(self.model).none() column_names = [k for k, v in annotations] values = DynamicDBModelQuerySet(self)._get_query_values(column_names) qs = Cell.objects.filter(primary_key__table__name=table_name).values( 'primary_key').annotate(**annotations).values(**values).order_by() return JsonResponse(serializers.serialize("json", qs))
def export(request, model): """ :param request: :return: """ from django.apps import apps from django.core import serializers model = apps.get_model(app_label=model + 's', model_name=model) data = serializers.serialize(request.GET['format'], model.objects.all().order_by('-pub_date')[:100]) return JSONResponse({'response_data':data})
def AdvanceSearchFreelancerListView(request): first_name=request.POST.get('cityName') print(request) print(first_name) queryset=freelancer.objects.filter(first_name=first_name) print(queryset) test = [] for val in queryset: print(val) fl = FreeelanceView() posts_serialized = FreeelanceView() test.append(fl) posts_serialized = serializers.serialize('json', test) return Response(posts_serialized, safe=False)
def create_provider(request): if request.method == 'POST': try: data = JSONRenderer().render(request.data) stream = BytesIO(data) provider_model = JSONParser().parse(stream) provider = CreateNewProvider(provider_model) serialized_obj = serializers.serialize('json', [ provider, ]) return Response(serialized_obj, status=status.HTTP_202_ACCEPTED) except Exception, e: return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
def list(self, request, *args, **kwargs): # queryset = self.filter_queryset(self.get_queryset()) # page = self.paginate_queryset(queryset) # if page is not None: # serializer = self.get_serializer(page, many=True) # return self.get_paginated_response(serializer.data) # serializer = self.get_serializer(queryset, many=True) data = Song.objects.filter(user_id=request.user.id) return HttpResponse( serializers.serialize("json", data), content_type="text/json-comment-filtered", )
def process_purchase(request): if request.method == 'POST': try: data = JSONRenderer().render(request.data) stream = BytesIO(data) purchase_model = JSONParser().parse(stream) purchase = HandlePurchase(purchase_model) serialized_obj = serializers.serialize('json', [ purchase, ]) #serialized_obj = serializers.serialize('json', [ provider_model, ]) return Response(serialized_obj, status=status.HTTP_202_ACCEPTED) except Exception, e: return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
def search(request): name = request.GET.get('name') nutrition = None if name: # search the name and alias at the same time nutrition = Nutrition.objects.filter(Q(name__contains=name) | Q(alias__contains=name)).order_by('name') if not nutrition: nutrition = [] data = serializers.serialize("json", nutrition) response_kwargs = dict() response_kwargs['content_type'] = 'application/json' return HttpResponse(data, **response_kwargs)
def export(request, model): """ :param request: :return: """ from django.apps import apps from django.core import serializers model = apps.get_model(app_label=model + 's', model_name=model) data = serializers.serialize( request.GET['format'], model.objects.all().order_by('-pub_date')[:100], indent=2) return HttpResponse(data, content_type=request.GET['format'])
def addresses_for_customer(request, customer_id): if request.method == 'GET': addresses_queryset = CustomerContact.objects.filter( customer_id=customer_id) json_ready = list(addresses_queryset) addresses_data = serializers.serialize('json', json_ready) print(addresses_data) return Response(addresses_data) elif request.method == 'POST': serializer = CustomerContactSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) else: return Response('error: not a GET method')
def search(request): name = request.GET.get('name') nutrition = None if name: # search the name and alias at the same time nutrition = Nutrition.objects.filter( Q(name__contains=name) | Q(alias__contains=name)).order_by('name') if not nutrition: nutrition = [] data = serializers.serialize("json", nutrition) response_kwargs = dict() response_kwargs['content_type'] = 'application/json' return HttpResponse(data, **response_kwargs)
def getNotification(request): if request.method == 'GET': username1 = request.GET['userType'] user1 = models.User.objects.filter(username=username1).values('groups') userGroup = '' if user1[0]["groups"] == 3: userGroup = 'Troop' if user1[0]["groups"] == 2: userGroup = 'HQ Operators' if user1[0]["groups"] == 1: userGroup = 'HQ General' notification = Notification.objects.filter( ToWho=userGroup).order_by("-Date_time") data = serializers.serialize('json', notification) return JsonResponse(data, safe=False)
def getPermissions(request): permissions = serializers.serialize('json', Permission.objects.all()) permissions = json.loads(permissions) return JsonResponse(dict(permissions=permissions))