示例#1
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
示例#2
0
def create(request):
    # assump1: post body exists
    # assump1: post body has 'longlink' defined

    if request.method != 'POST':
        return redirect('/')

    reqBody = loads(request.body)
    longlink = reqBody['longlink']
    shortlink = ''  # temporary empty value

    try:
        shortlink = reqBody['shortlink']

        if shortlink == '':
            # ik it's wrong...sorry.
            raise KeyError('Empty shortlink')
        if linkExists(shortlink):
            res = HttpResponseBadRequest()
            res.reason_phrase = 'Shortlink already taken'
            res.status_code = 400
            return res
    except KeyError:
        shortlink = getShortRandomLink(5)

    obj = Link(shortlink=shortlink, longlink=longlink)
    obj.save()
    return HttpResponse(dumps(obj.getDict()))
示例#3
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
示例#4
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
示例#5
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
示例#6
0
文件: views.py 项目: mivashh/ApiNews
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)'
示例#7
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
示例#8
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
示例#9
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
示例#10
0
from django.shortcuts import render
from .models import Professor, Module, ProfessorModuleRating, ModuleInstance
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
import requests
from decimal import *
import json

http_bad_response = HttpResponseBadRequest()
http_bad_response.status_code = 503
http_bad_response.reason_phrase = 'Unavailable Service'
http_bad_response['Content-Type'] = 'text/plain'


# Create your views here.
@csrf_exempt
def HandleRegisterRequest(request):
    if request.user.is_authenticated:
        http_bad_response.content = "You are already logged in!"
        return http_bad_response
    else:
        if request.method != 'POST':
            http_bad_response.content = "Only POST requests are allowed for this resource"
            return http_bad_response

        if request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            email = request.POST.get('email')