def HandleGetStoriesRequest(request): # Don't accept non-GET requests if (request.method != 'GET'): http_bad_response = HttpResponseBadRequest() http_bad_response['Content-Type'] = 'text/plain' http_bad_response.content = 'Only GET requests are permitted for this resource\n' return http_bad_response # Retrieve information from the request requestData = json.loads(request.body) category = requestData['story_cat'] region = requestData['story_region'] date = requestData['story_date'] # Get the total story list to begin with stories = Story.objects.all() # Now we check if there's something other than the default values to filter by if (category != '*'): stories = stories.filter(category=category) if (region != '*'): stories = stories.filter(region=region) if (date != '*'): stories = stories.filter(date__gte=date) # Check that stories still has some data if stories is not None: jsonList = [] # Iterate through the story list as a dict for record in stories.values(): # We need to get the author name first author_id = record['author_id'] authorName = Author.objects.get(id=author_id).name # Withdraw the information and add to the JSON list item = { 'key': record['id'], 'headline': record['headline'], 'story_cat': record['category'], 'story_region': record['region'], 'author': authorName, 'story_date': record['date'], 'story_details': record['details'] } jsonList.append(item) payload = {'stories': jsonList} http_response = JsonResponse(payload) #json.dumps(payload) http_response.status_code = 200 http_response.reason_phrase = 'OK' http_response['Content-Type'] = 'application/json' return http_response else: http_response = HttpResponse() http_response.status_code = 404 http_response.reason_phrase = 'Not Found' http_response['Content-Type'] = 'text/plain' http_response.content = 'No stories match this filter' return http_response
def compressResult(result): #response = HttpResponse(result,mimetype="application/json") response = JsonResponse(result, safe=False) #response['Access-Control-Allow-Origin'] = '*' compressed_content = compress_string(response.content) if len(compressed_content) >= len(response.content): return response response.content = compressed_content response['Content-Length'] = str(len(response.content)) response['Content-Encoding'] = 'gzip' return response
def compressResult(result): #response = HttpResponse(result,mimetype="application/json") response = JsonResponse(result,safe=False) #response['Access-Control-Allow-Origin'] = '*' compressed_content = compress_string(response.content) if len(compressed_content) >= len(response.content): return response response.content = compressed_content response['Content-Length'] = str(len(response.content)) response['Content-Encoding'] = 'gzip' return response
def new(cls, *, code: int, message: str, **kwargs): """ return a new Json Response """ resp = JsonResponse({}) resp.status_code = code payload = dict({'message': message}) for (key, value) in kwargs.items(): payload[key] = value resp.content = json.dumps(payload) return resp
def Respond(cls, *, status: int, message: str, **kwargs): data = dict({ 'message': message }) for (key, value) in kwargs.items(): data[key] = value resp = JsonResponse({}) resp.status_code = status resp.content = dumps(data) return resp
def process_view(self, request, view_func, args, kwargs): # check for any app-wide blocks if request.method != 'GET': # allow any actions under /admin if ALLOWED_ALWAYS_NON_GET_URLS.search(request.path): return block_msg = check_blocks(raise_error=False, error_message='Unable to process request.') if block_msg is not False: # 1. request is ajax # 2. content type is json # 3. any api request (except /api/app/ or /api/version/ - mostly this check is for # apps.project.api.v1.ProjectViewSet.send_clusters_to_project which receives form data if request.is_ajax() or request.META['CONTENT_TYPE'] == 'application/json' or re.search(r'^/api/v\d', request.path): response = JsonResponse({'detail': block_msg}, status=403) else: response = HttpResponseForbidden() response.content = render(request, '403.html', context={'message': block_msg}) return response
def json_tags_starting_with(request, callback=None): # Callback for JSONP prefix = request.GET.get('q', '') callback = request.GET.get('callback', '') # Prefix must have at least 2 characters if len(prefix) < 2: return HttpResponse('') tags_list = [] for tag in _tags_starting_with(prefix, request.user): if not tag.name in tags_list: tags_list.append(tag.name) if request.GET.get('mozhint', ''): result = [prefix, tags_list] else: result = {"matches": tags_list} response = JsonResponse(result, safe=False) if callback: response.content = callback + "(" + response.content + ");" return response
def json_tags_starting_with(request, callback=None): # Callback for JSONP prefix = request.GET.get('q', '') callback = request.GET.get('callback', '') # Prefix must have at least 2 characters if len(prefix) < 2: return HttpResponse('') tags_list = [] for tag in _tags_starting_with(prefix, request.user): if tag.name not in tags_list: tags_list.append(tag.name) if request.GET.get('mozhint', ''): result = [prefix, tags_list] else: result = {"matches": tags_list} response = JsonResponse(result, safe=False) if callback: response.content = callback + "(" + response.content + ");" return response
def lazy_endpoint(request): data = {"tags": []} response = JsonResponse(data) if request.method == "POST" and request.body: try: payload = json.loads(request.body) except json.JSONDecodeError: return HttpResponseBadRequest() consent = payload.get("consent", None) request.path = payload.get("pathname", request.path) request.META["QUERY_STRING"] = payload.get("search", "") strategy = TagStrategy(request, consent) for cookie_name, value in strategy.cookies.items(): set_cookie(response, cookie_name, value) for tag in strategy.result: element = tag.get("element") for content in element.contents: if content.name: data["tags"].append({ "name": content.name, "attributes": getattr(content, "attrs", {}), "string": content.string, }) response.content = json.dumps(data) return response return HttpResponseBadRequest()
def data_json_response(list_of_objects): data = serializers.serialize("json", list_of_objects) response = JsonResponse(data, safe = False) response.content = ("{\"response\" : \"success\", \"data\" : ").encode('utf-8') + (str(response.content[1:-1], 'utf-8').replace("\\","")).encode('utf-8') + "}".encode('utf-8') return response