Пример #1
0
import dateutil.parser
from flask import Flask, render_template, request, flash, redirect, url_for, jsonify
from flask_moment import Moment
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.exceptions import abort

from forms import *
# ----------------------------------------------------------------------------#
# App Config.
# ----------------------------------------------------------------------------#
from helpers import get_datetime_now, convert_string_to_datetime
from models import Artist, Venue, Show, db_setup

app = Flask(__name__)
moment = Moment(app)
db = db_setup(app=app)

#
# ----------------------------------------------------------------------------#
# Filters.
# ----------------------------------------------------------------------------#


def format_datetime(value, format='medium'):
    date = dateutil.parser.parse(value)
    if format == 'full':
        format = "EEEE MMMM, d, y 'at' h:mma"
    elif format == 'medium':
        format = "EE MM, dd, y h:mma"
    return babel.dates.format_datetime(date, format)
Пример #2
0
from difflib import get_close_matches
import sys
from models import Artist, Venue, Show, db_setup

# ----------------------------------------------------------------------------#
# App Config.
# ----------------------------------------------------------------------------#

app = Flask(__name__)
moment = Moment(app)
app.config.from_object('config')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
now = datetime.utcnow()
migrate = Migrate(app, db)
db_setup(app)

# ----------------------------------------------------------------------------#
# Models.
# ----------------------------------------------------------------------------#

# ----------------------------------------------------------------------------#
# Filters.
# ----------------------------------------------------------------------------#


def format_datetime(value, format='medium'):
    date = dateutil.parser.parse(value)
    if format == 'full':
        format = "EEEE MMMM, d, y 'at' h:mma"
    elif format == 'medium':
Пример #3
0
def create_app(test_config=None):
    app = Flask(__name__)
    db_setup(app)
    #db_reset()

    CORS(app)

    def paginate_results(request, selection):
        # Same function as I used in one of the previous submissions to return only X rows per page (cf Trivia API)
        page = request.args.get('page', 1, type=int)

        start = (page - 1) * ROWS_PER_PAGE
        end = start + ROWS_PER_PAGE

        objects_formatted = [object_name.format() for object_name in selection]
        return objects_formatted[start:end]

    ########################################
    # Endpoints
    ########################################

    @app.route('/')
    def index_page():
        return jsonify({"message": "Healthy"})

    ########################################
    # Actors endpoints for GET, POST, PATCH, DELETE

    @app.route('/actors', methods=['GET'])
    @requires_auth('read:actors')
    def get_actors(payload):
        actors_raw = Actor.query.all()
        actors_paginated = paginate_results(request, actors_raw)

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

        return jsonify({"success": True, "actors": actors_paginated}), 200

    @app.route('/actors', methods=['POST'])
    @requires_auth('create:actors')
    def insert_actors(payload):
        body = request.get_json()

        if body is None:
            abort(400)

        name = body.get("name")
        age = body.get("age")
        gender = body.get("gender", "Other")

        if not name or not age:
            abort(422)

        new_actor = Actor(name=name, age=age, gender=gender)
        new_actor.insert()

        return jsonify({"success": True, "created": new_actor.id})

    @app.route('/actors/<actor_id>', methods=['PATCH'])
    @requires_auth('edit:actors')
    def edit_actors(payload, actor_id):
        body = request.get_json()
        actor = Actor.query.filter(Actor.id == actor_id).one_or_none()

        if body is None:
            abort(400)
        if actor is None:
            abort(400)

        name = body.get("name")
        age = body.get("age")
        gender = body.get("gender", "Other")

        if name:
            actor.name = name
        if age:
            actor.age = age
        if gender:
            actor.gender = gender

        actor.update()

        return jsonify({"success": True, "updated": actor.id})

    @app.route('/actors/<actor_id>', methods=['DELETE'])
    @requires_auth('delete:actors')
    def delete_actors(payload, actor_id):
        actor = Actor.query.filter(Actor.id == actor_id).one_or_none()

        if not actor:
            abort(400)

        actor.delete()

        return jsonify({"success": True, "deleted": actor_id})

    ########################################
    # Movies endpoints for GET, POST, PATCH, DELETE

    @app.route('/movies', methods=['GET'])
    @requires_auth('read:movies')
    def get_movies(payload):
        movies_raw = Movie.query.all()
        movies_paginated = paginate_results(request, movies_raw)

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

        return jsonify({"success": True, "actors": movies_paginated}), 200

    @app.route('/movies', methods=['POST'])
    @requires_auth('create:movies')
    def insert_movies(payload):
        body = request.get_json()

        if body is None:
            abort(400)

        title = body.get("title")
        release_date = body.get("release_date",
                                "Wed, 24 Jun 2020 00:00:00 GMT")

        if not title:
            abort(422)

        new_movie = Movie(title=title, release_date=release_date)
        new_movie.insert()

        return jsonify({"success": True, "created": new_movie.id})

    @app.route('/movies/<movie_id>', methods=['PATCH'])
    @requires_auth('edit:movies')
    def edit_movies(payload, movie_id):
        body = request.get_json()
        movie = Movie.query.filter(Movie.id == movie_id).one_or_none()

        if body is None:
            abort(400)
        if movie is None:
            abort(400)

        title = body.get("title")
        release_date = body.get("age")

        if title:
            movie.title = title
        if release_date:
            movie.release_date = release_date

        movie.update()

        return jsonify({"success": True, "updated": movie.id})

    @app.route('/movies/<movie_id>', methods=['DELETE'])
    @requires_auth('delete:movies')
    def delete_movies(payload, movie_id):
        movie = Movie.query.filter(Movie.id == movie_id).one_or_none()

        if not movie:
            abort(400)

        movie.delete()

        return jsonify({"success": True, "deleted": movie_id})

    ########################################
    # Error Handlers
    ########################################

    @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": "resource not found"
        }), 404

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

    return app
Пример #4
0
def create_app():
    app = Flask(__name__)
    db_setup(app)
    CORS(app)

    @app.route('/')
    def home():
        return 'Welcome to capstone'

    @app.route('/movies')
    @requires_auth('get:movies')
    def get_all_movies():

        movies = Movie.query.all()

        return jsonify({
            "success": True,
            "all_movies": [movies.format() for movies in movies]
        }), 200

    @app.route('/movies/create', methods=['POST'])
    @requires_auth('post:movies')
    def create_movie():

        data = request.get_json()

        title = data.get('title')
        release_date = data.get('release_date')

        movie = Movie(title=title, release_date=release_date)
        movie.insert()
        return jsonify({'success': True, 'movies': movie.format()})

    @app.route('/movies/<int:id>', methods=['PATCH'])
    @requires_auth('patch:movies')
    def edit_movie(id):
        data = request.get_json()

        movies = Movie.query.filter(Movie.id == id).one_or_none()

        if not movies:
            abort(404)

        movies.title = data.get('title', movies.title)
        movies.update()

        return jsonify({"success": True, "movies": movies.format()}), 200

    @app.route('/movies/<int:id>', methods=['DELETE'])
    @requires_auth('delete:movies')
    def delete_movies(id):

        movie = Movie.query.filter(Movie.id == id).one_or_none()

        if not movie:
            abort(404)

        movie.delete()

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

    @app.route('/actors')
    @requires_auth('get:actors')
    def get_all_actors():

        actors = Actor.query.all()
        return jsonify({
            "success": True,
            "all_actors": [actors.format() for actors in actors]
        }), 200

    @app.route('/actors/create', methods=['POST'])
    @requires_auth('post:actors')
    def create_actor():

        data = request.get_json()

        name = data.get('name')
        age = data.get('age')
        gender = data.get('gender')

        actor = Actor(name=name, age=age, gender=gender)
        db.session.add(actor)
        db.session.commit()

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

    @app.route('/actors/<int:id>', methods=['PATCH'])
    @requires_auth('patch:actors')
    def edit_actor(id):
        data = request.get_json()

        actor = Actor.query.filter(Actor.id == id).one_or_none()

        if not actor:
            abort(404)

        actor.name = data.get('name', actor.name)
        actor.age = data.get('age', actor.age)
        actor.gender = data.get('gender', actor.gender)
        db.session.commit()

        return jsonify({"success": True, "actors": actor.format()}), 200

    @app.route('/actors/<int:id>', methods=['DELETE'])
    @requires_auth('delete:actors')
    def delete_actors(id):

        actor = Actor.query.filter(Actor.id == id).one_or_none()

        if not actor:
            abort(404)

        # actor.delete()
        db.session.add(actor)
        db.session.commit()

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

    ## Error Handling
    '''
    Example error handling for unprocessable entity
    '''

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

    '''
    @TODO implement error handler for 404
        error handler should conform to general task above 
    '''

    @app.errorhandler(404)
    def resource_not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

    '''
    @TODO implement error handler for AuthError
        error handler should conform to general task above 
    '''

    @app.errorhandler(405)
    def permission_error(error):
        return jsonify({
            "success": False,
            "error": 405,
            "message": "Authentication error"
        }), 405

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

    return app
Пример #5
0
def create_app():
    app = Flask(__name__)
    db_setup(app)
    CORS(app)

    #----------------------------------------------------------------------------#
    # Endpoints
    #----------------------------------------------------------------------------#

    @app.route('/')
    def home():
        return 'Welcome to capstone'

    # TODO DONE implement endpoint GET /movies

    @app.route('/movies')
    @requires_auth('get:movies')
    def get_all_movies(payload):
        movies = Movie.query.all()
        return jsonify({
            "success": True,
            "all_movies": [movies.format() for movies in movies]
        }), 200

# TODO DONE implement endpoint GET /actors

    @app.route('/actors')
    @requires_auth('get:actors')
    def get_all_actors(payload):
        actors = Actor.query.order_by(Actor.name).all()

        if len(actors) != 0:
            try:
                actors = [actor.format() for actor in actors]

                return jsonify({'success': True, 'actors': actors}), 200
            except:
                abort(422)
        else:
            abort(404)

# TODO-DONE implement endpoint POST /movies

    @app.route('/movies', methods=['POST'])
    @requires_auth('post:movies')
    def create_movie(payload):
        body = request.get_json()
        title = body.get('title')
        release_date = body.get('release_date')
        movie = Movie(title=title, release_date=release_date)
        movie.insert()
        return jsonify({'success': True, 'movies': movie.format()})

# TODO-DONE implement endpoint POST /actors

    @app.route('/actors', methods=['POST'])
    @requires_auth('post:actors')
    def create_actor(payload):
        data = request.get_json()
        name = data.get('name')
        age = data.get('age')
        gender = data.get('gender')
        actor = Actor(name=name, age=age, gender=gender)
        db.session.add(actor)
        db.session.commit()
        return jsonify({'success': True, 'actors': actor.format()}), 201

# TODO DONE implement endpoint PATCH /movies/<id>

    @app.route('/movies/<int:id>', methods=['PATCH'])
    @requires_auth('patch:movies')
    def edit_movie(payload, id):
        data = request.get_json()
        movies = Movie.query.filter(Movie.id == id).one_or_none()
        if not movies:
            abort(404)
        movies.title = data.get('title', movies.title)
        movies.update()
        return jsonify({"success": True, "movies": movies.format()}), 200

# TODO DONE implement endpoint PATCH /actors/<id>

    @app.route('/actors/<int:id>', methods=['PATCH'])
    @requires_auth('patch:actors')
    def edit_actor(payload, id):
        data = request.get_json()
        actor = Actor.query.filter(Actor.id == id).one_or_none()
        if not actor:
            abort(404)
        actor.name = data.get('name', actor.name)
        actor.age = data.get('age', actor.age)
        actor.gender = data.get('gender', actor.gender)
        db.session.commit()
        return jsonify({"success": True, "actors": actor.format()}), 200

# TODO DONE implement endpoint DELETE /movies/<drink_id>

    @app.route('/movies/<int:id>', methods=['DELETE'])
    @requires_auth('delete:movies')
    def delete_movies(payload, id):
        movie = Movie.query.filter(Movie.id == id).one_or_none()
        if not movie:
            abort(404)
        movie.delete()
        return jsonify({"success": True, "delete": id}), 200

# TODO DONE implement endpoint DELETE /actors/<drink_id>

    @app.route('/actors/<int:id>', methods=['DELETE'])
    @requires_auth('delete:actors')
    def delete_actors(payload, id):
        actor = Actor.query.filter(Actor.id == id).one_or_none()
        if not actor:
            abort(404)
        actor.delete()
        return jsonify({"success": True, "delete": id}), 200


# Error Handling

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

    @app.errorhandler(404)
    def resource_not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

    @app.errorhandler(405)
    def permission_error(error):
        return jsonify({
            "success": False,
            "error": 405,
            "message": "Authentication error"
        }), 405

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

    @app.errorhandler(401)
    def custom_401(error):
        return jsonify({
            "success":
            False,
            "error":
            401,
            "message":
            "unauthorized user, please login and try again."
        }), 401

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

    return app
Пример #6
0
import babel
from flask import Flask, render_template, request, flash, redirect, url_for, jsonify
from datetime import datetime
import logging
from logging import Formatter, FileHandler
from forms import *
from models import db_setup, Venue, Show, Artist
from flask_moment import Moment

#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
moment = Moment(app)
db, migrate = db_setup(app)

#----------------------------------------------------------------------------#
# Filters.
#----------------------------------------------------------------------------#

# used for formatting user time input


def format_datetime(value, format='medium'):
    date = dateutil.parser.parse(value)
    if format == 'full':
        format = "EEEE MMMM, d, y 'at' h:mma"
    elif format == 'medium':
        format = "EE MM, dd, y h:mma"
    return babel.dates.format_datetime(date, format, locale='en')