Beispiel #1
0
def user_bookings_add(username, page):

    if username not in users:
        raise NotFound("User '{}' not found.".format(username))

    if request.method == 'GET':
        result = {}
        try:
            showtimes = requests.get(
                "http://127.0.0.1:5002/showtimes/{}".format(page))
        except requests.exceptions.ConnectionError:
            raise ServiceUnavailable("The Showtimes service is unavailable.")

        showtimes = showtimes.json()

        for movieid in showtimes:
            result[movieid] = []
            try:
                movies_resp = requests.get(
                    "http://127.0.0.1:5001/movies/{}".format(movieid))
            except requests.exceptions.ConnectionError:
                raise ServiceUnavailable("The Movie service is unavailable.")
            try:
                movies_resp = movies_resp.json()
            except ValueError:
                raise ServiceUnavailable("Sorry! No movies in this day.")
            result[movieid].append({
                "title": movies_resp["title"],
                "rating": movies_resp["rating"]
            })

        return nice_json(result)

    if request.method == 'POST':
        raw = request.get_json()
        result = requests.post(
            "http://127.0.0.1:5003/bookings/{}/add".format(username),
            json={username: raw})
        result = result.json()

        user_resp = requests.get(
            "http://127.0.0.1:5000/users/{}".format(username))
        user_resp = user_resp.json()
        content = {
            "id": user_resp["id"],
            "name": user_resp["name"],
            "last_active": 0
        }
        content = {username: content}
        with open("{}/database/users.json".format(root_dir())) as ff:
            data = json.load(ff)

        data.update(content)
        with open("{}/database/users.json".format(root_dir()), "w+") as ff:
            json.dump(data, ff)
        users.update(content)
        return nice_json(result)

    raise NotImplementedError()
Beispiel #2
0
def booking_add(username):
    content = request.json

    with open("{}/database/bookings.json".format(root_dir())) as ff:
        data = json.load(ff)

    data.update(content)
    with open("{}/database/bookings.json".format(root_dir()), 'w+') as ff:
	    json.dump(data,ff)
    bookings.update(content)
	
    return nice_json(content)
Beispiel #3
0
def refresh():
    current_user = get_jwt_identity()
    ret = {
        'access_token': create_access_token(identity=current_user),
        'refresh_token': create_refresh_token(identity=current_user)
    }
    with open("{}/tokens/token.json".format(root_dir()), "w") as f:
        json.dump(ret, f)
    return nice_json(ret)
Beispiel #4
0
def user_login():
    auth = mongo.db.auth
    email = request.get_json(force=True)['email']
    password = request.get_json()['password']
    result = ""

    response = auth.find_one({'email': email})

    if response:
        if bcrypt.check_password_hash(response['password'], password):
            ret = {
                'access_token':
                create_access_token(
                    identity={
                        'first_name': response['first_name'],
                        'last_name': response['last_name'],
                        'email': response['email']
                    },
                    expires_delta=datetime.timedelta(minutes=30)),
                'refresh_token':
                create_refresh_token(
                    identity={
                        'first_name': response['first_name'],
                        'last_name': response['last_name'],
                        'email': response['email']
                    })
            }
            result = nice_json(ret)
            with open("{}/tokens/token.json".format(root_dir()), "w") as f:
                json.dump(ret, f)
        else:
            result = nice_json({"error": "Invalid username and password"})
    else:
        result = nice_json({"result": "No results found"})

    return result, 200
Beispiel #5
0
from services import root_dir, nice_json
from flask import Flask
from werkzeug.exceptions import NotFound
import json

app = Flask(__name__)

with open("../database/showtimes.json".format(root_dir()), "r") as f:
    showtimes = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "showtimes": "/showtimes",
            "showtime": "/showtimes/<date>"
        }
    })


@app.route("/showtimes", methods=['GET'])
def showtimes_list():
    return nice_json(showtimes)


@app.route("/showtimes/<date>", methods=['GET'])
def showtimes_record(date):
    if date not in showtimes:
        raise NotFound
Beispiel #6
0
from services import root_dir, nice_json
from flask import Flask
import json
from werkzeug.exceptions import NotFound

app = Flask(__name__)

with open("{}/database/bookings.json".format(root_dir()), "r") as f:
    bookings = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "bookings": "/bookings",
            "booking": "/bookings/<username>"
        }
    })


@app.route("/bookings", methods=['GET'])
def booking_list():
    return nice_json(bookings)


@app.route("/bookings/<username>", methods=['GET'])
def booking_record(username):
    if username not in bookings:
        raise NotFound
Beispiel #7
0
from services import root_dir, nice_json
from flask import Flask
from werkzeug.exceptions import NotFound
import json

app = Flask(__name__)

with open("../database/movies.json".format(root_dir()), "r") as f:
    movies = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "movies": "/movies",
            "movie": "/movies/<id>"
        }
    })


@app.route("/movies/<movieid>", methods=['GET'])
def movie_info(movieid):
    if movieid not in movies:
        raise NotFound

    result = movies[movieid]
    result["uri"] = "/movies/{}".format(movieid)

    return nice_json(result)
Beispiel #8
0
from services import root_dir, nice_json
from flask import Flask
from werkzeug.exceptions import NotFound
import json


app = Flask(__name__)

with open("{}/database/movies.json".format(root_dir()), "r") as f:
    movies = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "movies": "/movies",
            "movie": "/movies/<id>"
        }
    })

@app.route("/movies/<movieid>", methods=['GET'])
def movie_info(movieid):
    if movieid not in movies:
        raise NotFound

    result = movies[movieid]
    result["uri"] = "/movies/{}".format(movieid)

    return nice_json(result)
def get_csv_file():
    parent_root_dir = root_dir()
    csv_file = parent_root_dir + "/database/" + settings.CSVFILE
    return csv_file
from services import root_dir, nice_json
from flask import Flask
import json
import requests

app = Flask(__name__)

with open("{}/dbs/passengers".format(root_dir()), 'r') as a:
    passengers = json.load(a)


@app.route('/')
def hello():
    response_data = "Hi!\n" \
                    "What do you want to do here?\n" \
                    "* /passengers - all passengers info\n" \
                    "* /passengers/<passenger> - specific passenger info\n" \
                    "* /passengers/<passenger>/flight' - number of flight passenger is booked\n" \
                    "* /passengers/<passenger>/flight/info - passenger flight info"
    return response_data


@app.route('/passengers', methods=['GET'])
def get_all_passengers():
    return nice_json(passengers)


@app.route('/passengers/<passenger>')
def get_passenger_info(passenger):
    return nice_json(passengers[passenger])
Beispiel #11
0
from flask import Flask
from services import root_dir, nice_json
from werkzeug.exceptions import NotFound, ServiceUnavailable
import json
import requests
import os
import json
import logging
from flask import make_response

dic2 = {'a': 1, 'b': 2, 'b': '3'}
a = 0
app = Flask(__name__)

with open("{}/database/users.json".format(root_dir()), "r") as f:
    users = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "add": "/add",
            "users": "/users",
            "user": "******",
            "bookings": "/users/<username>/bookings",
            "suggested": "/users/<username>/suggested"
        }
    })
Beispiel #12
0
from services import root_dir, nice_json
from flask import Flask
from werkzeug.exceptions import NotFound, ServiceUnavailable
import json
import requests
import os


app = Flask(__name__)
pwd = os.getcwd()
print pwd
with open(pwd+"/database/users.json".format(root_dir()), "r") as f:
    users = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "users": "/users",
            "user": "******",
            "bookings": "/users/<username>/bookings",
            "suggested": "/users/<username>/suggested"
        }
    })


@app.route("/users", methods=['GET'])
def users_list():
    return nice_json(users)
from services import root_dir, nice_json
from flask import Flask
from werkzeug.exceptions import NotFound
import json


app = Flask(__name__)

with open("{}/database/showtimes.json".format(root_dir()), "r") as f:
    showtimes = json.load(f)


@app.route("/")
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "showtimes": "/showtimes",
            "showtime": "/showtimes/<date>"
        }
    })


@app.route("/showtimes")
def showtimes_list():
    return nice_json(showtimes)


@app.route("/showtimes/<date>")
def showtimes_record(date):
    if date not in showtimes:
Beispiel #14
0
import pandas as pd
from services import settings
from services import root_dir

root_dir = root_dir()
file_name = "/database/" + settings.CSVFILE
csv_file = root_dir + file_name
json_file = root_dir + "/database/" + settings.JSONFILE

print(csv_file, json_file)

with open(csv_file, "r") as f:
    csvfile = pd.read_csv(f)
csvfile.to_json(json_file)
df = pd.read_json(json_file)
print(df.head)
Beispiel #15
0
from services import root_dir, nice_json
from flask import Flask, request
from werkzeug.exceptions import NotFound
import json

app = Flask(__name__)

ROOT_MOVIES = {
    "uri": "/",
    "subresource_uris": {
        "movies": "/movies",
        "movie": "/movies/<id>"
    }
}
MOVIES_JSON = "{}/database/movies.json".format(root_dir())


def get_movies(movie_id=None):
    with open(MOVIES_JSON, "r") as f:
        movies = json.load(f)
        if movie_id is None:
            return movies
        else:
            return movies[movie_id]


get_movies()


@app.route("/", methods=['GET'])
from flask import Flask
import json

from services import root_dir, nice_json

app = Flask(__name__)

with open('{}/dbs/flights'.format(root_dir()), 'r') as f:
    flights = json.load(f)


@app.route('/')
def hello():
    response_data = "Hello!\n" \
                    "Things to do here:\n" \
                    "* /flights - all flights info\n" \
                    "* /flights/<flight> - specific flight info"

    return response_data


@app.route('/flights', methods=['GET'])
def get_all_flights():
    return nice_json(flights)


@app.route('/flights/<flight>', methods=['GET'])
def get_flight_info(flight):
    return nice_json(flights[flight])

Beispiel #17
0
from services import root_dir, json_response
from flask import Flask, request
from datetime import date, datetime, timedelta
import json
import requests

app = Flask(__name__)

with open("{}/db/customers.json".format(root_dir()), "r") as f:
    customers = json.load(f)

def howManyDays(start, end):
    return (date.fromisoformat(end) - date.fromisoformat(start)).days + 1

def getDates(startDate, endDate):
    dateArray = []
    if endDate == None:
      endDate = (date.today()).isoformat()
    if startDate == None:
      return []
    else:
      currentDate = date.fromisoformat(startDate)
      while currentDate <= date.fromisoformat(endDate):
        dateArray.append(currentDate)
        currentDate = currentDate + timedelta(days=1)
      return dateArray
    
def dropWeekends(rng):
    return [d for d in rng if not d.isoweekday() in [6,7]]
  
def getFirstPaidDay(lastFreeDay):
Beispiel #18
0
from services import root_dir, nice_json
from flask import Flask
import json
from werkzeug.exceptions import NotFound


app = Flask(__name__)

with open("{}/database/bookings.json".format(root_dir()), "r") as f:
    bookings = json.load(f)


@app.route("/", methods=['GET'])
def hello():
    return nice_json({
        "uri": "/",
        "subresource_uris": {
            "bookings": "/bookings",
            "booking": "/bookings/<username>"
        }
    })


@app.route("/bookings", methods=['GET'])
def booking_list():
    return nice_json(bookings)


@app.route("/bookings/<username>", methods=['GET'])
def booking_record(username):
    if username not in bookings:
def get_json_file():
    parent_root_dir = root_dir()
    json_file = parent_root_dir + "/database/" + settings.JSONFILE
    return json_file
Beispiel #20
0
from services import root_dir
import user
from werkzeug.utils import redirect
from flask import Flask, request, render_template, url_for, flash, session
import os, datetime
import query
app = Flask(__name__)
app.secret_key = os.urandom(24)
ROOT_MOVIES = {
    "uri": "/",
    "subresource_uris": {
        "movies": "/movies",
        "movie": "/movies/<id>"
    }
}
MOVIES_DB = "C:\\Users\HP\Desktop\db\database.db".format(root_dir())


@app.route('/')
def home():
    if not session.get('logged_in'):
        return redirect(url_for("do_login"))
    else:
        if session['name'] == "88" and session['id'] == "admin":
            return "Hello"+session.get("name") + "\n<a href='/logout'>Logout</a><br><br><a id='user' href='/getmovies'>Update_Delete_Add_list_of_movies</a>" \
            "<br><br><a href='/redirect'>Update_Delete_Add_list of users</a>"
        else:
            query.apdatelastactive(
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
                session.get('name'))
            return "Hello\n" + session['id']+"<br><br><a href='/logout'>Logout</a><br><br><br><a href='/threemax'>three max movies</a> " \
Beispiel #21
0
def user_bookings_add(username, page):

    with open("{}/tokens/token.json".format(root_dir()), "r") as ff:
        try:
            token = json.load(ff)
        except:
            raise Unauthorized()
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(token['access_token'])
    }
    auth_check = requests.get("http://127.0.0.1:5004/check", headers=headers)
    auth_check = auth_check.json()
    if auth_check['msg'] != 'OK':
        raise Unauthorized(auth_check['msg'])

    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer {}".format(token['refresh_token'])
    }
    if auth_check['msg'] == 'Token has expired':
        auth_refresh = requests.post("http://127.0.0.1:5004/refresh",
                                     headers=headers)

    if username not in users:
        raise NotFound("User '{}' not found.".format(username))

    if request.method == 'GET':
        result = {}
        try:
            showtimes = requests.get(
                "http://127.0.0.1:5002/showtimes/{}".format(page))
        except requests.exceptions.ConnectionError:
            raise ServiceUnavailable("The Showtimes service is unavailable.")

        showtimes = showtimes.json()

        for movieid in showtimes:
            result[movieid] = []
            try:
                movies_resp = requests.get(
                    "http://127.0.0.1:5001/movies/{}".format(movieid))
            except requests.exceptions.ConnectionError:
                raise ServiceUnavailable("The Movie service is unavailable.")
            try:
                movies_resp = movies_resp.json()
            except ValueError:
                raise ServiceUnavailable("Sorry! No movies in this day.")
            result[movieid].append({
                "title": movies_resp["title"],
                "rating": movies_resp["rating"]
            })

        return nice_json(result)

    if request.method == 'POST':
        raw = request.get_json()
        try:
            user_resp = requests.get(
                "http://127.0.0.1:5000/users/{}".format(username))
        except:
            raise ServiceUnavailable(
                "Sorry, service unavailable at the moment!")
        try:
            result = requests.post(
                "http://127.0.0.1:5003/bookings/{}/add".format(username),
                json={username: raw})
        except:
            raise ServiceUnavailable(
                "Sorry, service unavailable at the moment!")
        result = result.json()
        user_resp = user_resp.json()
        content = {
            "id": user_resp["id"],
            "name": user_resp["name"],
            "last_active": 0
        }
        content = {username: content}
        with open("{}/database/users.json".format(root_dir())) as ff:
            data = json.load(ff)

        data.update(content)
        with open("{}/database/users.json".format(root_dir()), "w+") as ff:
            json.dump(data, ff)
        users.update(content)
        return nice_json(result)

    raise NotImplementedError()