コード例 #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 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
コード例 #4
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
コード例 #5
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
コード例 #6
0
ファイル: views.py プロジェクト: champbriggs/web_cwk1
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')