コード例 #1
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client

        setup_db(self.app)

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
コード例 #2
0
    def setUp(self):
    """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "postgres"
        self.database_path = "postgresql://{}@{}/{}".format('postgres:Liszt762!','localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)

    # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
        
        self.new_actor_in_test = {"name" = "Testing", "age" = "Testing", "gender" = "Testing"}
コード例 #3
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = APP
        self.client = self.app.test_client
        self.hotel_manager = os.getenv("HOTEL_MANAGER")
        self.receptionist = os.getenv("RECEPTION")
        self.restaurant = os.getenv("RESTAURANT_MANAGER")
        self.expired_token = os.getenv("EXPIRED_TOKEN")
        self.database_path = os.getenv('DATABASE_URL')
        setup_db(self.app, self.database_path)

        # add sample data to be used in the tests
        self.new_booking = {
            'room_id': 2,
            'guest_uuid': 'c5ef43fe-5567-11ea-84a8-acde48001122',
            'date_in': '2020-06-05',
            'date_out': '2020-06-08',
            'breakfast': True,
            'paid': False,
            'reason_for_stay': 'business'
        }
        self.failed_new_booking = {
            'guest_uuid': 'c5ef43fe-5567-11ea-84a8-acde48001122',
            'date_in': '2020-06-05',
            'date_out': '2020-06-08',
            'breakfast': True,
            'paid': False,
            'reason_for_stay': 'business'
        }
        self.new_guest = {
            "name": 'Vito',
            "mobile": '08674782029',
            "email": '*****@*****.**'
        }
        self.failed_new_guest = {
            "mobile": '08674782029',
            "email": '*****@*****.**'
        }
        self.edit_booking = {'reason_for_stay': 'pleasure'}
        self.edit_guest = {'name': "Rosie"}

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
コード例 #4
0
ファイル: test_api.py プロジェクト: manimanis/ND_CoffeeShop
    def setUp(self):
        """Define test variables and initialize app."""
        database_filename = "src/test_database.db"
        project_dir = os.path.dirname(os.path.abspath(__file__))
        database_path = "sqlite:///{}" \
            .format(os.path.join(project_dir, database_filename))

        self.app = create_app()
        self.client = self.app.test_client
        setup_db(self.app, database_path)

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()

        db_drop_and_create_all()
コード例 #5
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "casting_test"
        self.database_path = "postgres://{}:{}@{}/{}".format(
            'vijay', 'password', 'localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)
        self.code_success = 200
        self.code_not_found = 404
        self.code_unprocessable = 422
        self.code_unauthorised = 401

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
コード例 #6
0
    def setUp(self):
        """Define test variables and initialize app."""
        project_dir = os.path.dirname(os.path.abspath(__file__))
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "drinks_test"
        self.database_path = "sqlite:///{}".format(
            os.path.join(project_dir, self.database_name))
        setup_db(self.app, self.database_path)

        # Manager and Barista tokens
        self.barista_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlJFSTJNVFF3UXpoR1JEQTRRMFJETVVGRE5VTkJRVVUwUmtVNU9FUXhNMEUzTmtOQ016RkRSQSJ9.eyJpc3MiOiJodHRwczovL2ZzbmQtYmlsbHkuYXV0aDAuY29tLyIsInN1YiI6ImF1dGgwfDVkODYyYmY1NWJiZTgyMGRmN2EwNDQ5NyIsImF1ZCI6ImRyaW5rcyIsImlhdCI6MTU2OTI3NDUwNCwiZXhwIjoxNTY5MzYwOTA0LCJhenAiOiJybFVOaUR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ekMndweWYxeE5YON-L_0SIYg0RVpZ1WInaEuArh40n-bD84E3fDleczuxslGUSc873rQ6k_2kfI-IxUj-57iezSDmoGEXgUdexi_1sO2eyZ6F3En4Jj0Aka5p5rfps09Bro9uGYIitCFsTh_k7nuHi-KQE80ReZjIONtUNT-G-68tQ2yMyNqtM5Dmorvtb1f5Yw'

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
コード例 #7
0
ファイル: test_app.py プロジェクト: faisal3397/blog-api
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = app
        self.client = self.app.test_client
        self.database_name = "blog_test"
        self.database_path = "postgres://{}/{}".format('localhost:5432',
                                                       self.database_name)
        setup_db(self.app, self.database_path)

        self.new_post = {
            "title": "My New Post 3",
            "date": "Tue, 08 Dec 2020 15:53:58 GMT",
            "content": "Lorem ipsum dolor sit amet,"
        }

        self.bad_request_post = {"content": "Lorem ipsum dolor sit amet,"}

        self.updated_post = {
            "title": "Modified title 123",
            "date": "Tue, 08 Dec 2020 16:53:58 GMT",
            "content": "Modified content 1232341242"
        }

        self.comment = {
            "content": "Hi your post #3 is great",
            "date": "Tue, 08 Dec 2020 16:02:48 GMT"
        }

        self.bad_request_comment = {"date": "Tue, 08 Dec 2020 16:02:48 GMT"}

        self.blog_owner_token = os.environ["BLOG_OWNER_TOKEN"]
        self.auth_user_token = os.environ["AUTH_USER_TOKEN"]

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
コード例 #8
0
import os
from flask import Flask, request, jsonify, abort
from sqlalchemy import exc
import json
from flask_cors import CORS

from src.database.models import db_drop_and_create_all, setup_db, Drink
from src.auth.auth import AuthError, requires_auth

app = Flask(__name__)
setup_db(app)
CORS(app)
'''
@TODO uncomment the following line to initialize the datbase
!! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH
!! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN
'''
# db_drop_and_create_all()

## ROUTES
'''
@TODO implement endpoint
    GET /drinks
        it should be a public endpoint
        it should contain only the drink.short() data representation
    returns status code 200 and json {"success": True, "drinks": drinks} where drinks is the list of drinks
        or appropriate status code indicating reason for failure
'''


@app.route('/drinks', methods=['GET'])
コード例 #9
0
ファイル: manage.py プロジェクト: vijaybaliah/casting-agency
from flask_script import Manager
from flask_migrate import MigrateCommand
from dotenv import load_dotenv

from src.app import create_app
from src.database.models import setup_db

database_path = "postgres://{}:{}@{}/{}".format('postgres', 'password',
                                                'localhost:5432', 'casting')

load_dotenv()
app = create_app()
setup_db(app, database_path)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
コード例 #10
0
    def setUp(self):
        self.app = api.app
        setup_db(self.app)

        self.client = self.app.test_client
コード例 #11
0
def create_app():
    app = Flask(__name__)
    setup_db(app)
    CORS(app)

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Headers',
                             'Content-Type, Authorization')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET, POST, PATCH, DELETE, OPTIONS')
        return response

    @app.route('/')
    def index():
        return jsonify({"message": "Welcome to Blog API"})

    @app.route('/posts')
    def get_posts():
        posts = Post.query.all()
        formatted_posts = [post.format() for post in posts]

        page = request.args.get('page', 1, type=int)
        start = (page - 1) * POSTS_PER_PAGE
        end = start + POSTS_PER_PAGE

        resulted_posts = formatted_posts[start:end]
        if len(resulted_posts) == 0:
            abort(404)

        return jsonify({
            'success': True,
            'posts': resulted_posts,
            'total_posts': len(formatted_posts)
        })

    @app.route('/posts/<int:post_id>/comments')
    def get_post_comments(post_id):
        comments = Comment.query.filter(Comment.post_id == post_id).all()

        if len(comments) == 0:
            abort(404)

        formatted_comments = [comment.format() for comment in comments]

        return jsonify({'success': True, 'comments': formatted_comments})

    @app.route('/posts', methods=['POST'])
    @requires_auth('post:posts')
    def create_post(jwt):
        body = request.get_json()
        title = body.get('title')
        date = body.get('date')
        content = body.get('content')

        if title is None or date is None or content is None:
            abort(400)

        try:
            post = Post(title=title, date=date, content=content)
            post.insert()

            return jsonify({'success': True, 'post': post.format()}), 201

        except ():
            abort(400)

    @app.route('/posts/<int:post_id>', methods=['PATCH'])
    @requires_auth('patch:posts')
    def update_post(jwt, post_id):
        body = request.get_json()
        title = body.get('title')
        date = body.get('date')
        content = body.get('content')

        try:
            post = Post.query.filter(Post.id == post_id).one_or_none()

            if post is None:
                abort(404)

            post.title = title
            post.date = date
            post.content = content
            post.update()

            return jsonify({'success': True, 'post': post.format()})

        except ():
            abort(422)

    @app.route('/posts/<int:post_id>', methods=['DELETE'])
    @requires_auth('delete:posts')
    def delete_post(jwt, post_id):

        try:
            post = Post.query.filter(Post.id == post_id).one_or_none()

            if post is None:
                abort(404)

            post.delete()

            return jsonify({"success": True, "delete": post.id})

        except ():
            abort(422)

    @app.route('/posts/<int:post_id>/comments', methods=['POST'])
    @requires_auth('post:comments')
    def create_comment(jwt, post_id):
        body = request.get_json()
        date = body.get('date')
        content = body.get('content')

        if date is None or content is None:
            abort(400)

        try:
            post = Post.query.filter(Post.id == post_id).one_or_none()

            if post is None:
                abort(404)

            comment = Comment(date=date, content=content, post_id=post_id)
            comment.insert()

            return jsonify({'success': True, 'comment': comment.format()}), 201

        except ():
            abort(400)

    # Error Handling

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": "unprocessable"
        }), 422

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            "success": False,
            "error": 400,
            "message": "Bad Request"
        }), 400

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "Not Found"
        }), 404

    @app.errorhandler(AuthError)
    def auth_error(error):
        return jsonify({
            "success": False,
            "error": error.status_code,
            "message": error.error
        }), error.status_code

    return app
コード例 #12
0
ファイル: app.py プロジェクト: jacobtavener/FSND_Capstone
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    setup_db(app)
    CORS(app, resources={r"/capstone/*": {"origins": "*"}})

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Headers',
                             'Content-Type, Authorization')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET, POST, PATCH, DELETE, OPTIONS')
        return response

# GET REQUEST METHODS

    @app.route('/bookings')
    @requires_auth('get:bookings')
    def get_bookings(payload):
        try:
            bookings = Booking.query.all()
            booking = {
                str(b.uuid): {
                    **b.booking(),
                    **b.guest.booking(),
                    **b.room.booking(),
                    **b.room.roomtype.booking()
                }
                for b in bookings
            }
            return jsonify({"success": True, "bookings": booking})
        except Exception:
            abort(500)

    @app.route('/roomtypes')
    @requires_auth('get:roomtypes')
    def get_room_types(payload):
        try:
            roomtypes = {
                "roomtype_id_" + str(r.id): r.long()
                for r in RoomType.query.all()
            }

            return jsonify({"success": True, "Room Types": roomtypes})
        except Exception:
            abort(500)

    @app.route('/guests')
    @requires_auth('get:guests')
    def get_guests(payload):
        try:
            booked_guests = [str(b.guest_uuid) for b in Booking.query.all()]
            guest_bookings = {
                id: {
                    b.id: {
                        **b.guest_view(),
                        **b.room.booking()
                    }
                    for b in Booking.query.filter_by(guest_uuid=id).all()
                }
                for id in booked_guests
            }
            guests = {str(g.uuid): g.long() for g in Guest.query.all()}
            for id in guests.keys():
                if id in booked_guests:
                    guests[id]["bookings"] = guest_bookings[id]
                else:
                    guests[id]["bookings"] = {}
            return jsonify({"success": True, "guests": guests})
        except Exception:
            abort(500)

    @app.route('/guests/<string:guest_uuid>')
    @requires_auth('get:guests_by_uuid')
    def get_guests_by_uuid(payload, guest_uuid):
        guest = Guest.query.filter_by(uuid=guest_uuid).one_or_none()
        if guest is None:
            abort(422, 'guest uuid not found')
        try:
            guest = guest.long()
            bookings = Booking.query.filter_by(guest_uuid=guest_uuid).all()
            if len(bookings) == 0:
                guest['bookings'] = {}
            else:
                guest['bookings'] = {
                    str(b.uuid): {
                        **b.guest_view(),
                        **b.room.booking()
                    }
                    for b in bookings
                }
            return jsonify({"success": True, "guest": guest})
        except Exception:
            abort(500)

    @app.route('/rooms')
    @requires_auth('get:rooms')
    def get_rooms(payload):
        try:
            rooms = {
                r.id: {
                    **r.booking(),
                    **r.roomtype.long_no_id(), "dates_booked": booked_dates(r)
                }
                for r in Room.query.all()
            }

            return jsonify({"success": True, "rooms": rooms})
        except Exception:
            abort(500)

    @app.route('/rooms/<int:room_id>')
    @requires_auth('get:room_by_id')
    def get_room_by_id(payload, room_id):
        try:
            r = Room.query.filter_by(id=room_id).one_or_none()
            room = {
                **r.booking(),
                **r.roomtype.long_no_id(), "dates_booked": booked_dates(r)
            }
            return jsonify({"success": True, "room": room})
        except Exception:
            abort(422, "room not found")

# POST REQUEST METHODS

    @app.route('/bookings', methods=["POST"])
    @requires_auth('post:booking')
    def create_booking(payload):

        data = request.get_json()
        if set(data.keys()) != set(Booking.params()):
            abort(400, "input parameter missing")

        try:
            params = {
                'uuid': uuid.uuid4(),
                'room_id': data.get('room_id'),
                'guest_uuid': data.get('guest_uuid'),
                'date_in': data.get('date_in'),
                'date_out': data.get('date_out'),
                'breakfast': data.get('breakfast'),
                'paid': data.get('paid'),
                'reason_for_stay': data.get('reason_for_stay')
            }

            new_booking = Booking(**params)
            Booking.insert(new_booking)

            booking = new_booking.long()

            return jsonify({"success": True, "booking": booking})
        except Exception:
            abort(500)

    @app.route('/guests', methods=["POST"])
    @requires_auth('post:guests')
    def add_new_guest(payload):
        data = request.get_json()
        if set(data.keys()) != set(Guest.params()):
            abort(400, "input parameters missing")
        try:
            params = {
                "uuid": uuid.uuid4(),
                "name": data.get('name'),
                "mobile": data.get('mobile'),
                "email": data.get('email')
            }
            new_guest = Guest(**params)
            Guest.insert(new_guest)
            guest = new_guest.long()
            return jsonify({"success": True, "guest": guest})
        except Exception:
            abort(500)

# PATCH REQUEST METHODS

    @app.route('/bookings/<string:booking_uuid>', methods=["PATCH"])
    @requires_auth('patch:booking')
    def edit_bookings(payload, booking_uuid):
        data = request.get_json()
        booking = Booking.query.filter_by(uuid=booking_uuid).one_or_none()
        if booking is None:
            abort(422, "booking not found")
        try:
            if "room_id" in data:
                booking.room_id = data.get("room_id")
            if "guest_uuid" in data:
                booking.guest_uuid = data.get("guest_uuid")
            if "date_in" in data:
                booking.date_in = data.get("date_in")
            if "date_out" in data:
                booking.date_out = data.get("date_out")
            if "breakfast" in data:
                booking.breakfast = data.get("breakfast")
            if "paid" in data:
                booking.paid = data.get("paid")
            if "reason_for_stay" in data:
                booking.reason_for_stay = data.get("reason_for_stay")
            Booking.update(booking)
            return jsonify({"success": True, "booking": booking.long()})
        except Exception:
            abort(500)

    @app.route('/guests/<string:guest_uuid>', methods=["PATCH"])
    @requires_auth('patch:guest')
    def edit_guest(payload, guest_uuid):
        data = request.get_json()
        guest = Guest.query.filter_by(uuid=guest_uuid).one_or_none()
        if guest is None:
            abort(422, "guest not found")
        try:
            if "name" in data:
                guest.name = data.get("name")
            if "mobile" in data:
                guest.mobile = data.get("mobile")
            if "email" in data:
                guest.email = data.get("email")
            Guest.update(guest)
            return jsonify({"success": True, "guest": guest.long()})
        except Exception:
            abort(500)

# DELETE REQUEST METHODS

    @app.route('/bookings/<string:booking_uuid>', methods=["DELETE"])
    @requires_auth('delete:booking')
    def remove_booking(payload, booking_uuid):
        booking = Booking.query.filter_by(uuid=booking_uuid).one_or_none()
        if booking is None:
            abort(422, "booking not found")
        try:
            Booking.delete(booking)
            return jsonify({"success": True, "booking_uuid": booking_uuid})
        except Exception:
            abort(500)

    @app.route('/guests/<string:guest_uuid>', methods=["DELETE"])
    @requires_auth('delete:guest')
    def remove_guests(payload, guest_uuid):
        guest = Guest.query.filter_by(uuid=guest_uuid).one_or_none()
        if guest is None:
            abort(422, "guest not found")
        try:
            name = guest.name
            for booking in Booking.query.filter_by(
                    guest_uuid=guest_uuid).all():
                Booking.delete(booking)
            Guest.delete(guest)

            return jsonify({
                "success": True,
                "guest_uuid": guest_uuid,
                "removed": name
            })
        except Exception:
            abort(500)


# ERROR HANDLING

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": error.description
        }), 422

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            "success": False,
            "error": 400,
            "message": error.description
        }), 400

    @app.errorhandler(500)
    def internal_server_error(error):
        return jsonify({
            "success": False,
            "error": 500,
            "message": error.description
        }), 500

    @app.errorhandler(AuthError)
    def authentication_error(e):
        return jsonify(e.error), e.status_code

    return app