Example #1
0
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
Example #2
0
def create_paste_view(request, delete_key: typing.Optional[str] = None):
    r = _ensure_method(request, ['POST', 'PUT'])
    if r:
        return r
    text = request.body.decode(errors='replace')

    if delete_key is None:
        delete_key = ''.join(
            random.choices(string.ascii_letters + string.digits, k=30))

    expire_time = request.GET.get('expire_time', None)
    utc_now = datetime.datetime.now(pytz.timezone('UTC'))
    if expire_time is None:
        expire_time = utc_now + datetime.timedelta(days=60)
    else:
        try:
            expire_time = datetime.datetime.fromisoformat(expire_time)
            expire_time = expire_time.astimezone(utc_now.tzinfo)
        except ValueError as e:
            resp = JsonResponse({
                'status':
                400,
                'message':
                'Bad request, bad ISO formatted date',
            })
            resp.status_code = 400
            resp.reason_phrase = 'Bad request'
            return resp
        if expire_time <= utc_now:
            resp = JsonResponse({
                'status': 400,
                'message': 'Bad request, date is in the past',
            })
            resp.status_code = 400
            resp.reason_phrase = 'Bad request'
            return resp

    id_ = ''.join(random.choices(string.ascii_letters + string.digits, k=15))

    paste = Paste(id=id_,
                  text=text,
                  delete_key=delete_key,
                  expire_time=expire_time)
    paste.save()
    return JsonResponse({
        'status': 200,
        'message': 'Created paste',
        'key': id_,
        'delete_key': delete_key
    })
Example #3
0
def raw_paste_view(request, paste_id):
    r = _ensure_method(request)
    if r:
        return r

    try:
        return HttpResponse(Paste.get(paste_id).text,
                            content_type='text/plain')
    except Paste.DoesNotExist:
        resp = JsonResponse({'status': 404, 'message': 'Not found.'})
        resp.status_code = 404
        resp.reason_phrase = 'Not found.'
        return resp
    except ExpiredPasteError:
        resp = JsonResponse({
            'status': 410,
            'message': 'Gone, paste has expired.'
        })
        resp.status_code = 410
        resp.reason_phrase = 'Gone'
        return resp
Example #4
0
def _ensure_method(request, methods=None):
    if methods is None:
        methods = ['GET']
    if request.method not in methods:
        resp = JsonResponse({
            'status': 400,
            'message':
            f'Bad request, allowed methods: {", ".join(methods)}, but {request.method!r} was used',
            'allowed_methods': methods
        })
        resp.status_code = 400
        resp.reason_phrase = 'Bad request'
        return resp
Example #5
0
def json_paste_view(request, paste_id):
    r = _ensure_method(request)
    if r:
        return r

    try:
        return JsonResponse({
            'data': Paste.get(paste_id).text,
            'key': paste_id
        })
    except Paste.DoesNotExist:
        resp = JsonResponse({'status': 404, 'message': 'Not found.'})
        resp.status_code = 404
        resp.reason_phrase = 'Not found.'
        return resp
    except ExpiredPasteError:
        resp = JsonResponse({
            'status': 410,
            'message': 'Gone, paste has expired.'
        })
        resp.status_code = 410
        resp.reason_phrase = 'Gone'
        return resp
Example #6
0
def clean_pastes_view(request):
    r = _ensure_method(request, ['POST', 'DELETE'])
    if r:
        return r

    if not request.user.has_perm('clean_pastes'):
        resp = JsonResponse({
            'status':
            401,
            'message':
            'Unauthorized, not logged in or insufficient permissions'
        })
        resp.status_code = 401
        resp.reason_phrase = 'Unauthorized, not logged in or insufficient permissions'
        return resp

    now = datetime.datetime.now(pytz.timezone('UTC'))
    to_delete = Paste.objects.filter(expire_time__lte=now)
    num_deleted = to_delete.delete()[0]
    return JsonResponse({
        'status': 200,
        'message': f'Successfully deleted {num_deleted} pastes',
        'num_deleted': num_deleted
    })
Example #7
0
def json_error_response(code, message, data):
    response = JsonResponse({'error': message, 'data': data})
    response.status_code = code
    response.reason_phrase = message
    return response