def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client setup_db(self.app, TEST_CONNECT_STRING) self.test_movie_original = { 'title': 'Monty Python', 'release date': '2020-09-05 17:07:43' } self.test_movie = { 'title': 'test6', 'release_date': '2020-09-05 17:07:43' } self.test_movie_error = {"bad": "string"} self.test_movie_update = {'title': 'test-update'} self.test_movie_update_error = {'title': 4} # 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()
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client setup_db(self.app, TEST_CONNECT_STRING) self.test_actor_original = { 'name': 'Tom Hardy', 'age': 42, 'gender': 'male' } self.test_actor = { 'name': 'Test McTesterson', 'age': 25, 'gender': 'male' } self.test_actor_error = {"bad": "string"} self.test_actor_update = {'name': 'Testina', 'gender': 'female'} self.test_actor_update_error = {'name': 4} # 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()
def setUp(self): self.app = app self.client = self.app.test_client self.database_path = 'postgres://localhost:5432/test_concierge' setup_db(self.app, self.database_path) self.new_restaurant = { 'name': 'Al Mahara', 'cuisine_id': 17, 'location_id': 9, 'age_policy_id': 2, 'category_id': 2, 'rating': 5, 'address': 'Burj Al Arab hotel', 'phone_number': '97144555555', 'prebooking_required': True } self.new_restaurant_error = { 'name': 'Amazonico', 'rating': 4, 'address': 'DIFC' } self.edit_rest = {'cuisine_id': 17} self.edit_rest_error = {'category_id': 77} self.headers = { 'Content-Type': 'application/json', 'Authorization': JWT_TOKEN }
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client setup_db(self.app, TEST_CONNECT_STRING) # 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()
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_path = os.getenv('DB_TEST_URI') setup_db(self.app, self.database_path) self.casting_assistant = os.getenv('TOKEN_CASTING_ASSISTANT') self.casting_director = os.getenv('TOKEN_CASTING_DIRECTOR') self.executive_producer = os.getenv('TOKEN_EXECUTIVE_PRODUCER') # 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()
def create_app(test_config=None): app = Flask(__name__) setup_db(app) app.config.from_object('config') # Necessary because our frontend connects with a different port CORS(app) # logging file_handler = RotatingFileHandler('logs/castify.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () # mail mail_handler = SMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), fromaddr='no-reply@' + app.config['MAIL_SERVER'], toaddrs=app.config['ADMINS'], subject='Error from castify', credentials=auth, secure=secure) mail_handler.setLevel(logging.DEBUG) app.logger.addHandler(mail_handler) app.logger.addHandler(file_handler) app.logger.info('test log') # enable logging for flask cors logging.getLogger('flask_cors').level = logging.DEBUG app.register_blueprint(api_routes) app.register_blueprint(movie_routes) app.register_blueprint(genre_routes) app.register_blueprint(actor_routes) app.register_blueprint(error_routes) app.register_blueprint(link_routes) app.register_blueprint(server_routes) return app
def create_app(test_config=None): # create and configure the Flask application. app = Flask(__name__) setup_db(app) # ----------------------------------------------------------------------------# # @TODO IS DONE 100% 😇 # Set up CORS. Allow '*' for origins. # ----------------------------------------------------------------------------# cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) # ----------------------------------------------------------------------------# # @TODO IS DONE 100% 😇 # Use the after_request decorator to set Access-Control-Allow # ----------------------------------------------------------------------------# @app.after_request def after_request(response): response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization,true") response.headers.add("Access-Control-Allow-Methods", "GET,PATCH,POST,DELETE,OPTIONS") return response # ----------------------------------------------------------------------------# # @TODO IS DONE 100% 😇 # Create an endpoint to handle GET requests for all available categories. # ----------------------------------------------------------------------------# @app.route("/categories", methods=["GET"]) def get_categories(): try: all_cat = Category.query.order_by(Category.id).all() categories = {} for category in all_cat: categories[category.id] = category.type if len(all_cat) == 0: abort(404) return jsonify({"success": True, "categories": categories}) except AttributeError: abort(422)
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client setup_db(self.app, TEST_CONNECT_STRING) self.test_movie_actor_link = {'movie_id': 1, 'actor_id': 1} self.test_movie_actor_link_404 = {'movie_id': 9999, 'actor_id': 9999} self.test_movie_actor_link_400 = {'movie_id': '9999', 'actor_id': 9999} # 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()
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client setup_db(self.app, TEST_CONNECT_STRING) self.test_genre_original = {'name': 'soul'} self.test_genre = {'name': 'punk'} self.test_genre_error = {"bad": "string"} self.test_genre_update = {'name': 'metal'} self.test_genre_update_error = {'name': 4} # 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()
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from models.models import setup_db from flaskr import create_app app = create_app() db = setup_db(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
def create_app(test_config=None, database=None): app = Flask(__name__) if (database is None): setup_db(app) else: setup_db(app, database) CORS(app) @app.route('/actors') @requires_auth('read:actors') def get_actors(payload): actors = Actor.query.all() data = {} for actor in actors: data[actor.id] = actor.format() return jsonify({"success": True, "actors": data}) @app.route('/actors', methods=['POST']) @requires_auth('create:actor') def post_actor(payload): req = request.get_json() body = {} try: actor = Actor( name=req['name'], age=req['age'], gender=req['gender'], ) Actor.insert(actor) body['name'] = req['name'] body['age'] = req['age'] body['gender'] = req['gender'] body["id"] = actor.id except Exception: db.session.close() abort(422) return jsonify({"success": True, "actors": {body["id"]: body}}) @app.route('/actors/<int:actor_id>', methods=['DELETE']) @requires_auth('delete:actor') def delete_actor(payload, actor_id): error = False try: effected_rows = Actor.query.filter_by(id=actor_id).delete() if (effected_rows < 1): abort(404) db.session.commit() except Exception: db.session.rollback() error = True finally: db.session.close() if error: abort(404) else: return jsonify({'success': True, "delete": actor_id}) @app.route('/actors/<int:actor_id>', methods=['PATCH']) @requires_auth('edit:actor') def edit_actor(payload, actor_id): old_actor = Actor.query.get(actor_id) if not old_actor: abort(404) req = request.get_json() body = {} try: if 'name' in req: old_actor.name = req['name'] if 'age' in req: old_actor.age = req['age'] if 'gender' in req: old_actor.gender = req['gender'] db.session.commit() body = old_actor.format() except Exception: db.session.close() abort(422) finally: db.session.close() return jsonify({"success": True, "actors": {body["id"]: body}}) @app.route('/movies') @requires_auth('read:movies') def get_movies(payload): movies = Movie.query.all() data = {} for movie in movies: data[movie.id] = movie.format() return jsonify({"success": True, "movies": data}) @app.route('/movies', methods=['POST']) @requires_auth('create:movie') def post_movie(payload): req = request.get_json() body = {} try: movie = Movie( title=req['title'], release_date=req['release_date'], ) Movie.insert(movie) body['title'] = req['title'] body['release_date'] = req['release_date'] body["id"] = movie.id except Exception: db.session.close() abort(422) finally: db.session.close() return jsonify({"success": True, "movies": {body["id"]: body}}) @app.route('/movies/<int:movie_id>', methods=['DELETE']) @requires_auth('delete:movie') def delete_movie(payload, movie_id): error = False try: effected_rows = Movie.query.filter_by(id=movie_id).delete() if (effected_rows < 1): abort(404) db.session.commit() except Exception: db.session.rollback() error = True finally: db.session.close() if error: abort(404) else: return jsonify({'success': True, "delete": movie_id}) @app.route('/movies/<int:movie_id>', methods=['PATCH']) @requires_auth('edit:movie') def edit_movie(payload, movie_id): old_movie = Movie.query.get(movie_id) if not old_movie: abort(404) req = request.get_json() body = {} try: if 'title' in req: old_movie.title = req['title'] if 'release_date' in req: old_movie.release_date = req['release_date'] db.session.commit() body = old_movie.format() except Exception: db.session.close() abort(422) finally: db.session.close() return jsonify({"success": True, "actors": {body["id"]: body}}) @app.errorhandler(404) def not_found_error(error): return jsonify({ "success": False, "message": "The resource could not be found", "status_code": 404 }), 404 @app.errorhandler(422) def improperlyFormatted(error): return jsonify({ "success": False, "message": "There is something wrong with the request", "status_code": 422 }), 422 @app.errorhandler(AuthError) def authentification_failed(AuthError): return jsonify({ "success": False, "error": AuthError.status_code, "message": AuthError.error }), AuthError.status_code return app
from flask import Flask, jsonify, request, abort import re from flask_migrate import Migrate from models.models import setup_db, db, Restaurant, Location, Age_policy, Category, Cuisine, Notes, drop_and_create_all from auth.auth import AuthError, requires_auth app = Flask(__name__) setup_db(app) migrate = Migrate(app, db) # pagination parameters DEFAULT_PER_PAGE = 3 @app.route('/') def index(): return 'Welcome to ATP-Concierge' # Restaurants # ------------------------------------------------------------------- # public endpoint @app.route('/restaurants-public', methods=['GET']) def get_restaurants_short_list(): page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', DEFAULT_PER_PAGE, type=int) restaurants = Restaurant.query.order_by(Restaurant.id).paginate( page=page, error_out=False, per_page=per_page)
import os import sys from flask import Flask, request, jsonify, abort from sqlalchemy import exc import json from faker import Faker import random from models.models import setup_db, Actor, Movie app = Flask(__name__) database_path = os.getenv(sys.argv[1]) setup_db(app, database_path) fak = Faker() def populate_actors(): i = 1 for i in range(101): Faker.seed(i) gender = '' if i % 2 == 0: gender = 'male' name = fak.name_male() else: gender = 'female' name = fak.name_female() age = fak.random_int(18, 80)
def create_app(test_config=None): app = Flask(__name__) setup_db(app) # Set up CORS CORS(app) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true') response.headers.add('Access-Control-Allow-Methods', 'GET,PATCH,POST,DELETE,OPTIONS') response.headers.add('Access-Control-Allow-Origin', '*') return response @app.route('/', methods=['GET']) def home_route(): return jsonify({'success': True, 'message': 'Route Working'}) ''' Movies routes ''' @app.route('/movies', methods=['GET']) @requires_auth('get:movies') def get_all_movies(payload): if request.args.get('page') is None: page = 1 else: page = int(request.args.get('page')) movies = Movie.query.order_by(Movie.id).paginate( page, MOVIES_PER_PAGE).items return jsonify({ 'success': True, 'movies': [movie.format() for movie in movies] }) @app.route('/movies/<int:movie_id>', methods=['GET']) @requires_auth('get:movies') def get_single_movie(payload, movie_id): movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) return jsonify({'success': True, 'movie': movie.format()}) @app.route('/movies', methods=['POST']) @requires_auth('post:movies') def post_movie(payload): try: body = request.get_json() if body is None: abort(400) title = body.get('title', None) release_date = body.get('release_date', None) if title is None or release_date is None: abort(400) movie = Movie(title=title, release_date=release_date) movie.insert() return jsonify({'success': True, 'created': movie.id}) except: abort(422) @app.route('/movies/<int:movie_id>', methods=['PATCH']) @requires_auth('patch:movies') def update_movie(payload, movie_id): try: movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) body = request.get_json() if body is None: abort(400) # If the user provides a non-existent ID in the list of Actors # for the movie, the request cannot be processed if body.get('actors', None) is not None: actors = Actor.query.filter(Actor.id.in_(body.get('actors'))).\ all() if len(actors) is not len(body.get('actors')): abort(400) movie.actors = actors movie.title = body.get('title', movie.title) movie.release_date = body.get('release_date', movie.release_date) movie.update() return jsonify({'success': True, 'updated': movie.id}) except: abort(422) @app.route('/movies/<int:movie_id>', methods=['DELETE']) @requires_auth('delete:movies') def delete_movie(payload, movie_id): movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) movie.delete() total_movies = Movie.query.order_by(Movie.id).count() return jsonify({'success': True, 'total_movies': total_movies}) ''' Actors routes ''' @app.route('/actors', methods=['GET']) @requires_auth('get:actors') def get_all_actors(payload): if request.args.get('page') is None: page = 1 else: page = int(request.args.get('page')) actors = Actor.query.order_by(Actor.id).paginate( page, ACTORS_PER_PAGE).items return jsonify({ 'success': True, 'actors': [actor.format() for actor in actors] }) @app.route('/actors/<int:actor_id>', methods=['GET']) @requires_auth('get:actors') def get_single_actor(payload, actor_id): actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) return jsonify({'success': True, 'actor': actor.format()}) @app.route('/actors', methods=['POST']) @requires_auth('post:actors') def post_actor(payload): try: body = request.get_json() if body is None: abort(400) name = body.get('name', None) age = body.get('age', None) gender = body.get('gender', None) if name is None or age is None or gender is None: abort(400) if gender not in GENDERS: abort(400) actor = Actor(name=name, age=age, gender=gender) actor.insert() return jsonify({'success': True, 'created': actor.id}) except: abort(422) @app.route('/actors/<int:actor_id>', methods=['PATCH']) @requires_auth('patch:actors') def update_actor(payload, actor_id): try: actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) body = request.get_json() if body is None: abort(400) # If the user provides a non-existent ID in the list of Movies # the Actor has been featured in, the request cannot be processed if body.get('movies', None) is not None: movies = Movie.query.filter(Movie.id.in_(body.get('movies'))).\ all() if len(movies) is not len(body.get('movies')): abort(400) actor.movies = movies actor.name = body.get('name', actor.name) actor.age = body.get('age', actor.age) actor.gender = body.get('gender', actor.gender) if actor.gender not in GENDERS: abort(400) actor.update() return jsonify({'success': True, 'updated': actor.id}) except: abort(422) @app.route('/actors/<int:actor_id>', methods=['DELETE']) @requires_auth('delete:actors') def delete_actor(payload, actor_id): actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) actor.delete() total_actors = Actor.query.order_by(Actor.id).count() return jsonify({'success': True, 'total_actors': total_actors}) # Error Handling ''' Example error handling for unprocessable entity ''' @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 auth_error(error): return jsonify({"message": error.error}), error.status_code return app