Exemplo n.º 1
0
def view(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are valid\n'
        return http_bad_response

    profList = models.Teacher.objects.all()
    the_list = []
    for professor in profList:
        rateSum = 0
        avgRate = 0
        ratingList = models.Rating.objects.filter(teacher=professor.id)
        numRatings = models.Rating.objects.filter(teacher=professor.id).count()
        for profRate in ratingList:
            rateSum = rateSum + profRate.Rating
        if rateSum > 0:
            avgRate = math.trunc((rateSum / numRatings) + 0.5)
        else:
            avgRate = 0
        name = professor.profName[0] + "." + professor.profLastName
        item = {'Rating': avgRate, 'name': name}
        the_list.append(item)
    payload = {'phrase': the_list}
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    return http_response
Exemplo n.º 2
0
def list(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are valid\n'
        return http_bad_response

    module_list = models.Module.objects.all().values('module_ID', 'name',
                                                     'semester', 'year',
                                                     'teachers')
    the_list = []
    for r in module_list:
        profName = models.Teacher.objects.get(id=r['teachers'])
        string = str(profName.profID) + ", " + str(
            profName.profName)[0] + "." + str(profName.profLastName)
        item = {
            'ID': r['module_ID'],
            'name': r['name'],
            'sem': r['semester'],
            'year': r['year'],
            'tc': string
        }
        the_list.append(item)
    payload = {'phrase': the_list}
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    return http_response
Exemplo n.º 3
0
def HandleDeleteStoryRequest(request):
    # Don't accept non-POST requests
    if (request.method != 'POST'):
        http_bad_response = HttpResponseBadRequest()
        http_bad_response['Content-Type'] = 'text/plain'
        http_bad_response.content = 'Only POST requests are permitted for this resource\n'
        return http_bad_response

    # Create response object
    http_response = HttpResponse()
    http_response['Content-Type'] = 'text/plain'

    # Check if user is logged in
    if request.user.is_authenticated:
        # Decode json data
        requestData = json.loads(request.body)
        # Delete the story object
        story_id = requestData['story_key']
        s1 = Story.objects.get(id=story_id)
        s1.delete()
        http_response.status_code = 201
        http_response.reason_phrase = 'Created'
        http_response.content = 'Story deleted successfully'
        return http_response
    else:
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        http_response.content = 'User is not authenticated'

    return http_response
Exemplo n.º 4
0
def HandleLoginRequest(request):
    # Don't accept non-POST requests
    if (request.method != 'POST'):
        http_bad_response = HttpResponseBadRequest()
        http_bad_response['Content-Type'] = 'text/plain'
        http_bad_response.content = 'Only POST requests are permitted for this resource\n'
        return http_bad_response

    # Get the login details provided
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)

    # Create http response object
    http_response = HttpResponse()
    http_response['Content-Type'] = 'text/plain'

    # Respond based on whether the user has been authenticated
    if user is not None:
        login(request, user)
        request.session.modified = True
        http_response.status_code = 200
        http_response.reason_phrase = 'OK'
        http_response.content = 'Welcome to The Josh Boult News Agency'
    else:
        http_response.status_code = 401
        http_response.reason_phrase = 'Unauthorized'
        http_response.content = 'Invalid login'

    return http_response
Exemplo n.º 5
0
def HandleView(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if request.method != 'GET':
        http_bad_response.content = 'Only GET request is allowed'
        return http_bad_response

    new_list = []
    prof_list = []
    for prof_id in Professor.objects.all().values('professor_id'):
        prof_id_get = prof_id.get('professor_id')
        prof_list.append(prof_id_get)

    for professor in prof_list:
        rating_prof = Rating.objects.filter(
            which_professor__professor_id=professor).aggregate(Avg('rating'))
        raw_rating = rating_prof.get('rating__avg')
        rounded = int(
            Decimal(raw_rating).quantize(Decimal('1'), rounding=ROUND_HALF_UP))

        ratingobjects = {'code': professor, 'rating': rounded}
        new_list.append(ratingobjects)

    payload = {'rating_list': new_list}

    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'

    return http_response
Exemplo n.º 6
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
Exemplo n.º 7
0
def POST_req_checker(request):
    bad_response = HttpResponseBadRequest()
    bad_response['Content-Type'] = 'text/plain'

    if request.method != "POST":
        bad_response.content = "Only POST requests are allowed for this resource\n"
        return False, bad_response

    return True, None
Exemplo n.º 8
0
def input_detail(request, invite_id, guest_id):
    post_info = request.POST
    guest_pk = guest_id
    guest = get_object_or_404(Person, pk=guest_pk)
    # if "isVegan" in post_info and is_bool(post_info["isVegan"]):
    #     is_vegan = pars_bool(post_info["isVegan"])
    #     guest.is_vegan = is_vegan
    if "dietaryInfo" in post_info:
        guest.diet_info = post_info["dietaryInfo"]
        if post_info["dietaryInfo"] == "None":
            guest.diet_info = ''
    if "needRideLocation" in post_info:
        guest.needs_ride_location = post_info["needRideLocation"]
    if "giveRideLocation" in post_info:
        guest.has_car_room_location = post_info["giveRideLocation"]
    if "numSeats" in post_info:
        if is_int(post_info["numSeats"]):
            number_of_seats = int(post_info["numSeats"])
            guest.number_of_seats = number_of_seats
        else:
            response = HttpResponseBadRequest()
            response.content = guest.name + ":\n" + "Number of available seats must be a whole number.\n" + \
                "מספר המקומות הפנויים צריך להיות מספר שלם."
            return response
    if "email" in post_info:
        if post_info["email"]:
            if is_email(post_info["email"]):
                guest.email_app = post_info["email"]
            else:
                response = HttpResponseBadRequest()
                response.content = guest.name + ":\n" + "Invalid email address.\n" + \
                    "כתובת מייל לא תקינה."
                return response
    if "phone" in post_info:
        if post_info["phone"]:
            if is_phone_number(post_info["phone"]):
                guest.phone_app = post_info["phone"]
            else:
                response = HttpResponseBadRequest()
                response.content = guest.name + ":\n" + "Phone number must have 10 digits..\n" + \
                    "מספר טלפון צריך להיות בעל 10 ספרות."
                return response
    guest.save()
    return HttpResponse('')
Exemplo n.º 9
0
def DeleteStory(request):
    #receiving the story_key from the user
    payload = json.loads(request.body)
    story_key = payload['story_key']

    #retriving all the ids from the list
    storylist = list(NewsStories.objects.all().values_list('id'))

    #creating and empty string to parse the ids in so i can indlude them in the repsonse
    StringStory = " ".join(map(str, storylist))

    #Checking if the id exists in our database
    try:
        obj = NewsStories.objects.get(id=story_key)
    except NewsStories.DoesNotExist:
        obj = None

    #if the id does not exists send status code 503 and reasoning
    if obj == None:
        bad_response = HttpResponseBadRequest()
        bad_response['Content-Type'] = 'text/plain'
        bad_response.content = '\n This Key story does not exist try a different one : Available story_key ' + StringStory
        bad_response.status_code = 503
        return (bad_response)

    if request.method == 'POST':

        #delete object
        obj.delete()
        response = HttpResponse()
        response['Content-Type'] = 'text/plain'
        response.content = '\n Story deleted'
        response.status_code = 201
        response.reason_phrase = 'OK'
        return (response)

    #In case the user tries a different reqeust from post
    else:
        bad_response = HttpResponseBadRequest()
        bad_response['Content-Type'] = 'text/plain'
        bad_response.content = '\n Something went wrong (maybe post using get request)'
Exemplo n.º 10
0
def rate(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method == 'GET'):
        http_bad_response.content = 'Only POST requests are allowed for this resource\n'
        return http_bad_response

    profID = request.POST.get('teach_ID').upper()
    modID = request.POST.get('mod_ID').upper()
    year = request.POST.get('year')
    sem = request.POST.get('semester')
    rate = request.POST.get('rate')

    numProf = models.Teacher.objects.filter(profID=profID).count()
    numModule = models.Module.objects.filter(module_ID=modID).count()
    is_int = isinstance(rate, int)

    if numProf == 0 or numModule == 0 or is_int:
        the_list = "\n\nInvalid option\n\n"
        payload = {'phrase': the_list}
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 401
        http_response.reason_phrase = 'Invalid Details'
        return http_response
    else:
        prof = models.Teacher.objects.get(profID=profID)
        module = models.Module.objects.filter(module_ID=modID)[0]
        numModules = models.Module.objects.filter(module_ID=modID,
                                                  teachers=prof.id,
                                                  year=int(year),
                                                  semester=int(sem)).count()
        if numModules > 0:
            the_list = "\n\nRate successful\n\n"
            payload = {'phrase': the_list}
            http_response = HttpResponse(json.dumps(payload))
            http_response['Content-Type'] = 'application/json'
            http_response.status_code = 200
            http_response.reason_phrase = 'OK'
            rating = models.Rating.objects.create(module=module,
                                                  teacher=prof,
                                                  Rating=rate)
            rating.save()
        else:
            the_list = "\n\nTeacher does not take this module at specified time.\n\n"
            payload = {'phrase': the_list}
            http_response = HttpResponse(json.dumps(payload))
            http_response['Content-Type'] = 'application/json'
            http_response.status_code = 401
            http_response.reason_phrase = 'Invalid Details'
            return http_response
        return http_response
Exemplo n.º 11
0
def poststory(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if request.method == 'POST':
        if request.user.is_authenticated:
            req = simplejson.loads(request.body)
            hdl = req['headline']
            cat = req['category']
            reg = req['region']
            det = req['details']

            user = models.Author.objects.get(user=request.user)
            if cat == 'politics' or 'art' or 'technology' or 'trivial':
                if reg == 'UK' or 'European' or 'World':
                    models.Story.objects.create(headline=hdl,
                                                category=cat,
                                                region=reg,
                                                author=user,
                                                details=det)
                    http_response = HttpResponse()
                    http_response['Content-Type'] = 'text/plain'
                    http_response.status_code = 201
                    http_response.content = 'CREATED\n'
                    return http_response
                else:
                    http_bad_response.status_code = 503
                    http_bad_response.content = 'Wrong region\n'
                    return http_bad_response
            else:
                http_bad_response.status_code = 503
                http_bad_response.content = 'Wrong category\n'
                return http_bad_response
        else:
            http_bad_response.status_code = 503
            http_bad_response.content = 'Unauthenticated\n'
            return http_bad_response
    else:
        http_bad_response.content = 'Only GET requests are allowed for this resource\n'
        return http_bad_response
Exemplo n.º 12
0
def userLogout(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'
    if request.method == 'GET':
        auth.logout(request)
        if request.user.is_authenticated:
            http_bad_response.status_code = 423
            http_bad_response.content = 'logout failed'
            return http_bad_response
        else:
            http_response = HttpResponse()
            http_response['Content-Type'] = 'text/plain'
            http_response.status_code = 200
            http_response.content = 'logout successful'
            return http_response
Exemplo n.º 13
0
def bookingStatus(request):
    has_error = False
    error_message = 'Error:\n'
    json_data = {}
    booking_num = ""

    if(request.method != 'GET'):
        has_error = True
        error_message += 'Only GET requests allowed for this resource\n'

    headers = request.META
    content_type = headers['CONTENT_TYPE']
    if content_type != 'application/json':
        has_error = True
        error_message += 'Payload must be a json object\n'

    try:
        payload = request.body
        json_data = json.loads(payload)
    except ValueError:
        has_error = True
        error_message += 'invalid json object\n'

    try:
        booking_num = str(json_data['booking_num'])
    except KeyError:
        has_error = True
        error_message += 'expected json key not found in payload\n'


    #Retrieve booking
    booking = Booking.objects.get(booking_number = booking_num)
    #formulate return payload
    payload = {'booking_num':booking.booking_number, 'booking_status' : booking.status, 'flight_num':booking.flight.flight_number, 'dep_airport':booking.flight.departure_airport.name, 'dest_airport':booking.flight.destination_airport.name, 'dep_datetime': booking.flight.departure_date_time, 'arr_datetime': booking.flight.arrival_date_time, 'duration':str(booking.flight.flight_duration)}

    if (has_error):
        http_response = HttpResponseBadRequest ()
        http_response['Content-Type'] = 'text/plain'
        http_response.content = error_message
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        return http_response

    http_response = HttpResponse (json.dumps(payload, default=dateTimeConverter))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    return http_response
Exemplo n.º 14
0
def HandleLogoutRequest(request):
    # Don't accept non-POST requests
    if (request.method != 'POST'):
        http_bad_response = HttpResponseBadRequest()
        http_bad_response['Content-Type'] = 'text/plain'
        http_bad_response.content = 'Only POST requests are permitted for this resource\n'
        return http_bad_response

    # Logout
    logout(request)
    http_response = HttpResponse()
    http_response['Content-Type'] = 'text/plain'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    http_response.content = 'Goodbye, visit The Josh Boult News Agency soon!'
    return http_response
Exemplo n.º 15
0
def HandleList(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if request.method != 'GET':
        http_bad_response.content = 'Only GET request is allowed'
        return http_bad_response

    new_list = []
    for module in Module.objects.all().order_by('module_code', 'semester'):
        module_code = module.module_code
        name = module.name
        year = module.year
        semester = module.semester

        professor_id = module.taught_by.all().values(
            'professor_id')  # this gives a queryset
        professor_id2 = professor_id[0]['professor_id']

        first_name = module.taught_by.all().values('first_name')
        first_name2 = first_name[0]['first_name']

        last_name = module.taught_by.all().values('last_name')
        last_name2 = last_name[0]['last_name']

        moduleobjects = {
            'module_code': module_code,
            'name': name,
            'year': year,
            'semester': semester,
            'professor_id': professor_id2,
            'first_name': first_name2,
            'last_name': last_name2
        }

        new_list.append(moduleobjects)

    payload = {'module_list': new_list}

    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'

    # return http_response
    return JsonResponse(payload, status=200)
Exemplo n.º 16
0
def Login_view(request):
    if (request.method == 'POST'):
        #retrieving the credentials of the user
        username = request.POST.get('username')
        password = request.POST.get('password')
        #retrieving the asked username and password
        #If username or password does not exist in the Author object set them to None
        try:
            field_username = Author.objects.get(username=username).username
            field_password = Author.objects.get(password=password).password
        except Author.DoesNotExist:
            field_password = None
            field_username = None

        #checking if the credentials provided are correct
        if field_password == password and field_username == username:

            #saving the author as a global variable to re-use it for posting
            global authorname
            authorname = field_username

            response = HttpResponse()
            response['Content-Type'] = 'text/plain'
            response.content = '\n Welcome to the news agency Api ' + authorname
            response.status_code = 200
            response.reason_phrase = 'OK'
            return (response)

        #If the user provides wrong credentials
        else:
            response = HttpResponse()
            response['Content-Type'] = 'text/plain'
            response.content = '\n Incorrect Username or Password '
            response.status_code = 404
            response.reason_phrase = 'Not found'
            return (response)

    else:
        bad_response = HttpResponseBadRequest()
        bad_response['Content-Type'] = 'text/plain'
        bad_response.content = '\n Something went wrong (maybe not using post request)'

        return (bad_response)
Exemplo n.º 17
0
def userLogin(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'
    if request.method == 'POST':
        usr = request.POST.get('username')
        pwd = request.POST.get('password')
        user = auth.authenticate(username=usr, password=pwd)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                http_response = HttpResponse()
                http_response['Content-Type'] = 'text/plain'
                http_response.status_code = 200
                http_response.content = 'login successful'
                return http_response

    http_bad_response.status_code = 423
    http_bad_response.content = 'login failed'
    return http_bad_response
Exemplo n.º 18
0
def logout(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are valid\n'
        return http_bad_response

    token = ""
    payload = {
        'phrase': "\n\nYou are now logged out!!!\n\n",
        'token': token,
        'usrname': ""
    }
    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phrase = 'OK'
    return http_response
Exemplo n.º 19
0
def PostStory(request):
    if (request.method == 'POST'):

        #collecting information from the user for creating new story
        payload = json.loads(request.body)
        headline = payload['headline']
        category = payload['category']
        region = payload['region']
        details = payload['details']

        #Setting the information for the creation of the new story
        NewsStory = NewsStories(headline=headline,
                                category=category,
                                region=region,
                                details=details,
                                author=authorname)
        try:
            #if we reached this point everything is correct and
            #we should save the new story into our database
            NewsStory.save()
            response = HttpResponse()
            response['Content-Type'] = 'text/plain'
            response.status_code = 201
            response.reason_phrase = 'Created'
        except:
            response = HttpResponseBadRequest()
            response['Content-Type'] = 'text/plain'
            response.content = 'Something went wrong'
            response.status_code = 503
            response.reason_phrase = 'Error'

        return (response)

    else:
        bad_response = HttpResponseBadRequest()
        bad_response['Content-Type'] = 'text/plain'
        bad_response.content = '\n Something went wrong (maybe post using get request)'

        return (bad_response)
Exemplo n.º 20
0
def HandlePostStoryRequest(request):
    # Don't accept non-POST requests
    if (request.method != 'POST'):
        http_bad_response = HttpResponseBadRequest()
        http_bad_response['Content-Type'] = 'text/plain'
        http_bad_response.content = 'Only POST requests are permitted for this resource\n'
        return http_bad_response

    # Create response object
    http_response = HttpResponse()
    http_response['Content-Type'] = 'text/plain'

    # Check if user is logged in
    if request.user.is_authenticated:
        # Decode json data
        requestData = json.loads(request.body)
        # Create the story object and save to database
        author = Author.objects.get(user=request.user)
        headline = requestData['headline']
        category = requestData['category']
        region = requestData['region']
        details = requestData['details']
        s1 = Story(author=author,
                   headline=headline,
                   category=category,
                   region=region,
                   details=details)
        s1.save()
        http_response.status_code = 201
        http_response.reason_phrase = 'Created'
        http_response.content = 'Story added successfully'
        return http_response
    else:
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        http_response.content = 'User is not authenticated'

    return http_response
Exemplo n.º 21
0
def deletestory(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'POST'):
        http_bad_response.content = 'Only POST requests are allowed for this resource\n'
        return http_bad_response

    if request.method == 'POST':
        if request.user.is_authenticated:
            req = simplejson.loads(request.body)
            ki = req['story_key']

            # if the number of key is larger than the biggest key, we consider it correct.
            # Because the story of the key doesnt exit, which is 'deleted'. :)
            # So loop for counting the number of key is unnecessary. xD!
            models.Story.objects.filter(key=ki).delete()

            http_response = HttpResponse()
            http_response['Content-Type'] = 'text/plain'
            http_response.status_code = 201
            http_response.content = 'CREATED\n'
            return http_response
Exemplo n.º 22
0
def register(request):
    uniqueUser = True
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method == 'GET'):
        http_bad_response.content = 'Only POST requests are allowed for this resource\n'
        return http_bad_response

    username = request.POST.get('usrname')
    email = request.POST.get('email')
    password = request.POST.get('pass')

    if User.objects.filter(
            username=username).count() > 0 or User.objects.filter(
                email=email).count() > 0:
        uniqueUser = False

    if uniqueUser:
        users = User.objects.create_user(username, email, password)
        users.save()
        payload = {'phrase': "\nSuceessfully Registered!!!\n"}
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 200
        http_response.reason_phrase = 'OK'
        return http_response
    else:
        payload = {
            'phrase':
            "\nRegistration Failed!!!\nUsername or email already exists\n\n"
        }
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 401
        http_response.reason_phrase = 'Invalid Credentials'
        return http_response
Exemplo n.º 23
0
def login(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method == 'GET'):
        http_bad_response.content = 'Only POST requests are valid\n'
        return http_bad_response

    usrname = request.POST.get('usrname')
    password = request.POST.get('pass')
    user = authenticate(request, username=usrname, password=password)
    if user is not None:
        auth_login(request, user, user.backend)
        token, _ = Token.objects.get_or_create(user=user)
        payload = {
            'phrase': "\nCongrat's! You are logged in!\n",
            'token': "Token " + token.key,
            'usrname': usrname
        }
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 200
        http_response.reason_phrase = 'OK'
        return http_response
    else:
        payload = {
            'phrase':
            "\n\nError. Login Failed. Invalid credentials. Try again or register first!!!\n\n",
            'token': "",
            'usrname': ""
        }
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 401
        http_response.reason_phrase = 'Invalid credentials'
        return http_response
Exemplo n.º 24
0
def average(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are allowed for this resource\n'
        return http_bad_response

    profID = request.POST.get('teach_ID').upper()
    moduleID = request.POST.get('mod_ID').upper()

    teacher = models.Teacher.objects.filter(profID=profID).count()
    module = models.Module.objects.filter(module_ID=moduleID).count()

    if teacher == 0 or module == 0:
        the_list = "\n\nInvalid option\n\n"
        payload = {'phrase': the_list}
        http_response = HttpResponse(json.dumps(payload))
        http_response['Content-Type'] = 'application/json'
        http_response.status_code = 401
        http_response.reason_phrase = 'Invalid Details'
        return http_response
    else:
        module = models.Module.objects.filter(module_ID=moduleID)[0]
        teacher = models.Teacher.objects.get(profID=profID)
        rateSum = 0
        avgRate = 0
        rate = models.Rating.objects.filter(module=module, teacher=teacher.id)
        numModule = models.Module.objects.filter(module_ID=moduleID,
                                                 teachers=teacher.id).count()
        numRating = models.Rating.objects.filter(module=module,
                                                 teacher=teacher.id).count()
        if numModule > 0:
            for j in rate:
                rateSum = rateSum + j.Rating
            if rateSum > 0:
                avgRate = math.trunc((rateSum / numRating) + 0.5)
            else:
                avgRate = 0
            name = teacher.profName[0] + "." + teacher.profLastName
            modulename = module.name
            modid = module.module_ID
            item = {
                'Rating': avgRate,
                'name': name,
                'module_n': modulename,
                'modid': modid
            }
            payload = {'phrase': item}
            http_response = HttpResponse(json.dumps(payload))
            http_response['Content-Type'] = 'application/json'
            http_response.status_code = 200
            http_response.reason_phrase = 'OK'
            return http_response

        else:
            the_list = "\n\nTeacher does not take this module.\n\n"
            payload = {'phrase': the_list}
            http_response = HttpResponse(json.dumps(payload))
            http_response['Content-Type'] = 'application/json'
            http_response.status_code = 401
            http_response.reason_phrase = 'Invalid Details'
            return http_response
Exemplo n.º 25
0
def getstories(request):
    http_bad_response = HttpResponseBadRequest()
    http_bad_response['Content-Type'] = 'text/plain'

    if (request.method != 'GET'):
        http_bad_response.content = 'Only GET requests are allowed for this resource\n'
        return http_bad_response

    if request.method == 'GET':
        req = simplejson.loads(request.body)
        cat = req['story_cat']
        reg = req['story_region']
        dato = req['story_date']
        if cat == '*' and reg != '*' and dato != '*':
            dat = datetime.strptime(str(dato), '%d/%m/%Y')
            story_list = models.Story.objects.filter(
                region=reg, date_gt=dat.datetime_object.strftime('%Y-%m-%d'))
        if reg == '*' and cat != '*' and dato != '*':
            dat = datetime.strptime(str(dato), '%d/%m/%Y')
            story_list = models.Story.objects.filter(
                category=cat, date_gt=dat.datetime_object.strftime('%Y-%m-%d'))
        if dato == '*' and reg != '*' and cat != '*':
            story_list = models.Story.objects.filter(category=cat, region=reg)
        if dato == '*' and reg == '*' and cat != '*':
            story_list = models.Story.objects.filter(category=cat)
        if dato == '*' and reg != '*' and cat == '*':
            story_list = models.Story.objects.filter(region=reg)
        if dato != '*' and reg == '*' and cat == '*':
            dat = datetime.strptime(str(dato), '%d/%m/%Y')
            story_list = models.Story.objects.filter(date_gt=dat)
        if dato != '*' and reg != '*' and cat != '*':
            dat = datetime.strptime(str(dato), '%d/%m/%Y')
            story_list = models.Story.objects.filter(
                category=cat,
                region=reg,
                date_gt=dat.datetime_object.strftime('%Y-%m-%d'))
        if dato == '*' and reg == '*' and cat == '*':
            story_list = models.Story.objects.all().values(
                'key',
                'headline',
                'category',
                'region',
                'author',
                'date',
                'details',
            )

    the_list = []
    for record in story_list:
        item = {
            'key': record['key'],
            'headline': record['headline'],
            'story_cat': record['category'],
            'story_region': record['region'],
            'author': record['author'],
            'story_date': str(record['date']),
            'story_details': record['details']
        }
        the_list.append(item)

    payload = {'Stories': the_list}

    http_response = HttpResponse(json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 200
    http_response.reason_phtase = 'OK'
    return http_response
Exemplo n.º 26
0
def payForBooking(request):
    has_error = False
    error_message = 'Error:\n'
    json_data = {}
    invoice = {}
    returnPayload = {}

    if(request.method != 'POST'):
        has_error = True
        error_message += 'Only POST requests allowed for this resource\n'

    headers = request.META
    content_type = headers['CONTENT_TYPE']
    if content_type != 'application/json':
        has_error = True
        error_message += 'Payload must be a json object\n'

    try:
        payload = request.body
        json_data = json.loads(payload)
    except ValueError:
        has_error = True
        error_message += 'invalid json object\n'

    try:
        #log in as business into payment provider
        #retrieve payment provider & details
        provider = PaymentProvider.objects.get(provider_id = json_data['pay_provider_id'])
        base_url = provider.web_address
        payload = {'username':provider.login_username, 'password':provider.login_password}
        session = Session()
        r = session.post(base_url + "login/", data=payload)
        #GET COST OF BOOKING!
        # retrieve booking
        booking = Booking.objects.get(booking_number = json_data['booking_num'])
        # get number of passengers
        numPassengers = booking.number_of_seats
        # retrieve flight
        # get price
        price = booking.flight.seat_price
        # cost = numPassengers x price
        totalCost = numPassengers * price

        payload = {'account_num' : str(provider.account_number), 'client_ref_num' : json_data['booking_num'], 'amount':totalCost}
        response = session.post(base_url + "createinvoice/", json=payload)
        print("just created invoice at provider")
        if(response.status_code == 201):
            invoice = json.loads(response.text)
            #Store the invoice
            Invoice.objects.create(payment_service_provider_invoice_number = invoice['payprovider_ref_num'], booking_number = booking, amount = totalCost, paid = False, payment_confirmation_code = invoice['stamp_code'])
            print("Invoice has been generated")
            returnPayload = {'pay_provider_id': json_data['pay_provider_id'], 'invoice_id' : invoice['payprovider_ref_num'], 'booking_num' : json_data['booking_num'], 'url': provider.web_address, 'amount':totalCost}
        else:
            error_message = 'Could not create invoice'
    except KeyError:
        has_error = True
        error_message += 'expected json key not found in payload\n'

    if (has_error):
        http_response = HttpResponseBadRequest ()
        http_response['Content-Type'] = 'text/plain'
        http_response.content = error_message
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        return http_response

    http_response = HttpResponse (json.dumps(returnPayload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 201
    http_response.reason_phrase = 'CREATED'
    return http_response
Exemplo n.º 27
0
def handler400(request):
    response = HttpResponseBadRequest()
    context = RequestContext(request)
    response.content = render_to_string('400.html', context_instance=context)
    return response
Exemplo n.º 28
0
def bookFlight(request):
    has_error = False
    error_message = 'Error:\n'
    json_data = {}
    flightId = ""
    passengers = []

    if(request.method != 'POST'):
        has_error = True
        error_message += 'Only POST requests allowed for this resource\n'

    headers = request.META
    content_type = headers['CONTENT_TYPE']
    if content_type != 'application/json':
        has_error = True
        error_message += 'Payload must be a json object\n'

    try:
        payload = request.body
        json_data = json.loads(payload)
    except ValueError:
        has_error = True
        error_message += 'invalid json object\n'

    try:
        flightId = str(json_data['flight_id'])
        passengers = json_data['passengers']

    except KeyError:
        has_error = True
        error_message += 'expected json key not found in payload\n'


#####   CHECK SEATS AVAILABLE? - currently no mechanism to fail a request for booking
    bookingPassengers = []

    #Retrieve flight
    flight = Flight.objects.get(flight_number = flightId)
    #Create booking
    booking = Booking.objects.create(booking_number = generateRandomBookingNumber(), flight = flight, number_of_seats = len(passengers), payment_time_window = datetime.timedelta(minutes=10))
    #Add passengers & associate to booking
    for passenger in passengers:
        booking.passenger_details.create(first_name = passenger['first_name'], surname = passenger['surname'], email = passenger['email'], phone_number = passenger['phone'])

    #Return booking details in payload - number, status and total price
    #Calculate total price
    pricePerSeat = flight.seat_price
    totalPrice = pricePerSeat * len(passengers)
    payload = {'booking_num': booking.booking_number, 'booking_status' : booking.status, 'tot_price' : totalPrice}

    if (has_error):
        http_response = HttpResponseBadRequest ()
        http_response['Content-Type'] = 'text/plain'
        http_response.content = error_message
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        return http_response

    http_response = HttpResponse (json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 201
    http_response.reason_phrase = 'CREATED'
    return http_response
Exemplo n.º 29
0
def finalizeBooking(request):
    has_error = False
    error_message = 'Error:\n'
    json_data = {}
    booking_num = ""
    stamp_code = ""

    if(request.method != 'POST'):
        has_error = True
        error_message += 'Only POST requests allowed for this resource\n'

    headers = request.META
    content_type = headers['CONTENT_TYPE']
    if content_type != 'application/json':
        has_error = True
        error_message += 'Payload must be a json object\n'

    try:
        payload = request.body
        json_data = json.loads(payload)
    except ValueError:
        has_error = True
        error_message += 'invalid json object\n'

    try:
        booking_num = str(json_data['booking_num'])
        stamp_code = str(json_data['stamp'])

    except KeyError:
        has_error = True
        error_message += 'expected json key not found in payload\n'


    #Retrieve booking & invoice
    booking = Booking.objects.get(booking_number = booking_num)
    invoice = Invoice.objects.get(booking_number = booking)
    #check stamp code matches
    if(invoice.payment_confirmation_code == stamp_code):
        #change booking to confirmed status
        booking.status = "Confirmed"
        booking.save()
        #change invoice to paid
        invoice.paid = True
        invoice.save()
        payload = {'booking_num':booking_num, 'booking_status' : booking.status}
    else:
        has_error = True
        error_message += 'Verification of payment failed \n'

    if (has_error):
        http_response = HttpResponseBadRequest ()
        http_response['Content-Type'] = 'text/plain'
        http_response.content = error_message
        http_response.status_code = 503
        http_response.reason_phrase = 'Service Unavailable'
        return http_response

    http_response = HttpResponse (json.dumps(payload))
    http_response['Content-Type'] = 'application/json'
    http_response.status_code = 201
    http_response.reason_phrase = 'CREATED'
    return http_response
Exemplo n.º 30
0
def GetStory(request):
    if (request.method == 'GET'):
        #get the list of stories from the database
        #receiving the parameters from the user
        payload1 = json.loads(request.read())
        category = payload1['story_cat']
        region = payload1['story_region']
        date3 = payload1['story_date']

        stories_list = NewsStories.objects.all().values(
            'id', 'headline', 'category', 'region', 'author', 'date',
            'details')

        #collect the list items and put a new list with appropriate json names as pre requirements
        the_list = []

        for record in stories_list:
            #removing hours , minutes , seconds from the date
            date1 = str(record['date'])
            chop = len(date1.split()[-1]) + 1
            date1 = date1[:-chop]
            #Changing the format of date to dd/mm/YY
            formatDate = datetime.strptime(date1,
                                           "%Y-%m-%d").strftime("%d/%m/%Y")

            #checking if the requested fields match in the database
            if record['category'] == category and record[
                    'region'] == region and formatDate == date3:
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if category == '*' and region == '*' and date3 == '*':
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if record[
                    'category'] == category and region == '*' and date3 == '*':
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if category == '*' and record['region'] == region and date3 == '*':
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if category == '*' and region == '*' and formatDate == date3:
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if category == '*' and record[
                    'region'] == region and formatDate == date3:
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if record['category'] == category and record[
                    'region'] == region and date3 == '*':
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

            if record[
                    'category'] == category and region == '*' and formatDate == date3:
                item = {
                    'key': record['id'],
                    'headline': record['headline'],
                    'story_cat': record['category'],
                    'story_region': record['region'],
                    'author': record['author'],
                    'story_date': formatDate,
                    'story_details': record['details']
                }
                the_list.append(item)

        #if the list's length equals to 0 then it means the story does not exists
        if len(the_list) == 0:
            response = HttpResponse()
            response['Content-Type'] = 'text/plain'
            response.content = '\n This story does not exist try a different one '
            response.status_code = 404
            response.reason_phrase = 'Not found'
            return (response)

        #creating the json response payload
        payload = {'stories': the_list}

        #creating and returning a normal response
        response = HttpResponse(json.dumps(payload))
        response['Content-Type'] = 'application/json'
        response.status_code = 200

        return (response)

    #In case the user tries a different reqeust from get
    else:
        bad_response = HttpResponseBadRequest()
        bad_response['Content-Type'] = 'text/plain'
        bad_response.content = '\n Something went wrong (maybe post using post request)'