コード例 #1
0
ファイル: test_app.py プロジェクト: drdilyor/fsnd-capstone
    def __init__(self, *args, **kwargs):  # noqa
        super().__init__(*args, **kwargs)

        if MyTestCase.app is None:
            MyTestCase.app = create_app()
        MyTestCase.client = self.app.test_client()
        if MyTestCase.db is None:
            setup_db(self.app, self.database_path)
            MyTestCase.db = db

        self.db.drop_all()
        self.db.create_all()

        self.sample_actor = dict(
            name='My actor',
            age=4,
            gender=0,
        )
        self.bad_actor = dict(
            name='',  # oops, empty name
            age=42,
            gender=0,
        )
        self.sample_movie = dict(
            title='My movie',
            release_date=date(2021, 3, 30).isoformat(),
        )
        self.bad_movie = dict(
            title='',
            release_date=date(2021, 3, 30).isoformat(),
        )
        m = Movie(**self.sample_movie)
        m.id = 499
        m.insert()
コード例 #2
0
    def setUpClass(self):
        """Excuted in the beginning of the test, the target of this test is that all tests run in order at once """
        """Define test variables and initialize src."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "casting_agency_test"
        self.database_path = "postgresql://*****:*****@{}/{}".format('localhost:5432', self.database_name)

        # binds the src to the current context
        self.new_actor = {"name": "Markos24", "age": 23, "gender": "Male"}
        self.new_movie = {"title": "the real stuff", "release_date": "08/20/2020"}
        setup_db(self.app, self.database_path)

        with self.app.app_context():
            db.init_app(self.app)
            # create all tables
            db.drop_all()
            db.create_all()
コード例 #3
0
    def setUpClass(cls):
        """Define test variables and initialize app."""

        cls.header = {
            "Authorization":
            "Bearer " +
            "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik5FRkVPRE16UVVSRE16aENPVE"
            +
            "ZEUVRkR1FUVXpOVFpGTmtKRlJUbEZNemsyT1RWQ09FRTVRUSJ9.eyJpc3MiOiJodHRwczovL2"
            +
            "d3aWxsaWcuZXUuYXV0aDAuY29tLyIsInN1YiI6Imdvb2dsZS1vYXV0aDJ8MTE1NTY1NDgyODE"
            +
            "4Mjc4OTAxNTMwIiwiYXVkIjpbImNhc3RpbmdfYWdlbmN5IiwiaHR0cHM6Ly9nd2lsbGlnLmV1"
            +
            "LmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE1ODUwNzgzMTEsImV4cCI6MTU4NTE2NDY5O"
            +
            "CwiYXpwIjoiUVltdW9ha2hiUERqQW1SRFB5ZnBnTGlsemNwV0ZBQUsiLCJzY29wZSI6Im9wZW"
            +
            "5pZCBwcm9maWxlIGVtYWlsIiwicGVybWlzc2lvbnMiOlsiZGVsZXRlOmFjdG9yIiwiZGVsZXR"
            +
            "lOm1vdmllIiwiZ2V0OmFjdG9yIiwiZ2V0OmFjdG9ycyIsImdldDptb3ZpZSIsImdldDptb3Zp"
            +
            "ZXMiLCJwYXRjaDphY3RvciIsInBhdGNoOm1vdmllIiwicG9zdDphY3RvciIsInBvc3Q6bW92a"
            +
            "WUiXX0.aufLPeJXyJ5GTHj8c4uV6THJ_k8jXOmyN3XKVf-xEdJAQWoRyt_BbYo0ZZxdIzAaVY"
            +
            "JoN4GLAbruYN6lanUzA_Ms4enP_GsUYJUDLNxhb5IwU6BSecTysM736YfGW5s3xSi75ps7UqP"
            +
            "UNgrckYopUIQSfj2PMYyq-WByPbfhz4wfXFwK-PfkX_XMVAtQLzFjHrU7m35BKCmZ9JgwmsEk"
            +
            "B-YoDv904v1qr91JY2_X3GZQJKcmK-PyOW58Z-62zpp9X550Bx4lGnwGATZDlHiUOty66DABk"
            + "WH9XNZMMy2SzcOYSJwmXm46mc3BBpK9c9vO0osMpn1pAbvHI6_T7BDt_Q"
        }

        cls.app = create_app(dbms="sql", test_config=True)
        project_dir = os.path.dirname(os.path.abspath(__file__))
        database_path = "sqlite:///{}".format(
            os.path.join(project_dir, "database_test.db"))
        cls.db = setup_db(cls.app, database_path)
        cls.client = cls.app.test_client

        dummy_actor1 = Actor(first_name="Max", family_name="Mustermann")

        dummy_movie1 = Movie(title="Movie XY")
        dummy_movie1.actors.append(dummy_actor1)

        cls.db.session.bulk_save_objects([
            Actor(first_name="Gerald", family_name="Mustermann"),
            Actor(first_name="Albert", family_name="Mustermann"),
            Actor(first_name="Max", family_name="Mustermann"),
            Movie(title="Doe goes New York"),
            Movie(title="Tim goes New York"), dummy_movie1
        ])

        cls.db.session.commit()
コード例 #4
0
def create_app():
    """Creates the application with correct endpoints and error handlers"""
    app = Flask(__name__, template_folder=TEMPLATE_FOLDER)
    db = setup_db(app)
    migrate = Migrate(app, db)
    #db.create_all()
    """Endpoints"""
    @app.route("/")
    def default_route():
        return render_template("main_page.html", data=User.query.all())

    @app.route("/users/", methods=['GET', 'POST'])
    def users():
        if request.method == 'POST':
            body = request.get_json()
            if body is None:
                pass  #abort error code
            new_username = body.get("username")
            if new_username:
                try:
                    new_user = User(username=new_username)
                except Exception:
                    pass

        elif request.method == 'GET':
            users = User.query.all()
            return " ".join([user.user_id for user in users])

    @app.route("/users/<int:user_id>")
    def retrieve_user(user_id):
        user = User.query.filter_by(user_id=user_id).one_or_none()
        if user is not None:
            return str(user_id)
        else:
            abort(404)

    """Error handlers"""

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

    return app
コード例 #5
0
def create_app(dbms="sql", test_config=None):
    # create and configure the app
    app = Flask(__name__)

    if dbms == "sql":
        if test_config:
            database_filename = "database_test.db"
        else:
            database_filename = "database.db"
        project_dir = os.path.dirname(os.path.abspath(__file__))
        database_path = "sqlite:///{}".format(
            os.path.join(project_dir, database_filename))
        db = setup_db(app, database_path)

    '1.Step: config cors'
    CORS(app)

    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/actors', methods=['GET'])
    @requires_auth('get:actors')
    def get_all_actors(payload):
        """
        Return all actors

        :return:
        """
        # Convert sqlalchemy  object into dict
        query_result = [
            convert_sqlalchemy_todict(x)
            for x in db.session.query(Actor).all()
        ]

        return jsonify({'success': True, 'actors': query_result}, 200)

    @app.route('/movies', methods=['GET'])
    @requires_auth('get:movies')
    def get_all_movies(payload):
        """
        Return all actors

        :return:
        """
        # Convert sqlalchemy  object into dict
        query_result = [
            convert_sqlalchemy_todict(x)
            for x in db.session.query(Movie).all()
        ]

        return jsonify({'success': True, 'movies': query_result}, 200)

    @app.route('/actor', methods=['GET'])
    @requires_auth('get:actor')
    def get_actor(payload):
        """
        Return all actors

        :return:
        """
        request_dict = process_request(request)
        actor_id = request_dict["id"]
        # Convert sqlalchemy  object into dict
        query_result = convert_sqlalchemy_todict(
            db.session.query(Actor).filter_by(id=actor_id).first())

        return jsonify({'success': True, 'actors': query_result}, 200)

    @app.route('/movie', methods=['GET'])
    @requires_auth('get:movie')
    def get_movie(payload):
        """
        Return all actors

        :return:
        """
        request_dict = process_request(request)
        movie_id = request_dict["id"]
        # Convert sqlalchemy  object into dict
        query_result = convert_sqlalchemy_todict(
            db.session.query(Movie).filter_by(id=movie_id).first())

        return jsonify({'success': True, 'actors': query_result}, 200)

    @app.route("/movie", methods=['Delete'])
    @requires_auth('delete:movie')
    def delete_movie(payload):

        try:
            request_dict = process_request(request)
            movie_title = request_dict["title"]
            db.session.query(Movie).filter_by(title=movie_title).delete()
            db.session.commit()
        except:
            db.session.rollback()
            db.session.close()
            abort(400)
        finally:
            db.session.close()

        return jsonify({'success': True}, 204)

    @app.route("/actor", methods=['Delete'])
    @requires_auth('delete:actor')
    def delete_actor(payload):

        request_dict = process_request(request)
        first_name = request_dict["first_name"]
        family_name = request_dict["family_name"]
        try:
            db.session.query(Actor).filter_by(
                first_name=first_name, family_name=family_name).delete()
            db.session.commit()
        except:
            db.session.rollback()
            db.session.close()
            abort(400)
        finally:
            db.session.close()

        return jsonify({'success': True}, 204)

    @app.route("/actor", methods=['Patch'])
    @requires_auth('patch:actor')
    def patch_actor(payload):
        try:
            request_dict = process_request(request)
            actor_id = request_dict["id"]
            first_name = request_dict["first_name"]
            family_name = request_dict["family_name"]
            query_result = db.session.query(Actor).filter_by(id=actor_id)
            if query_result.count() == 0:
                return jsonify({'success': False}, 404)
            else:
                query_result.first_name = first_name
                query_result.family_name = family_name
                db.session.commit()
        except:
            db.session.rollback()
            db.session.close()
            abort(404)
        finally:
            db.session.close()

        return jsonify({'success': True}, 204)

    @app.route("/actor", methods=['Post'])
    @requires_auth('post:actor')
    def post_actor(payload):
        try:
            request_dict = process_request(request)
            movie_title = request_dict["movie_title"]
            first_name = request_dict["first_name"]
            family_name = request_dict["family_name"]

            query_result = db.session.query(Movie).filter_by(
                title=movie_title).first()
            a1 = Actor(first_name=first_name, family_name=family_name)
            query_result.actors.append(a1)
            db.session.commit()
        except:
            db.session.rollback()
            db.session.close()
            abort(422)
        finally:
            db.session.close()

        return jsonify({'success': True}, 204)

    @app.route("/movie", methods=['Patch'])
    @requires_auth('patch:movie')
    def patch_movie(payload):
        try:
            request_dict = process_request(request)
            movie_id = request_dict["id"]
            title = request_dict["title"]
            query_result = db.session.query(Movie).filter_by(id=movie_id)
            if query_result.count() == 0:
                return jsonify({'success': False}, 404)
            else:
                query_result.title = title
                db.session.commit()
        except:
            db.session.rollback()
            db.session.close()
            abort(404)
        finally:
            db.session.close()

        return jsonify({'success': True}, 204)

    @app.route("/movie", methods=['Post'])
    @requires_auth('post:movie')
    def post_movie(payload):
        try:
            request_dict = process_request(request)
            m1 = Movie(title=request_dict["title"])
            db.session.add(m1)
            db.session.commit()
        except:
            db.session.rollback()
            db.session.close()
            abort(422)
        finally:
            db.session.close()

        return jsonify({'success': True}, 204)

    """
    * API:

        * Testing:  
            * One test for success behavior of each endpoint
            * One test for error behavior of each endpoint
            * At least two tests of RBAC for each role
    
    
    """

    def convert_sqlalchemy_todict(obj):
        """
        Converts a sqlalchemy oject to a dict
        :param obj:
        :return:
        """
        return {
            c.key: getattr(obj, c.key)
            for c in inspect(obj).mapper.column_attrs
        }

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify(dict(success=False, error=400,
                            message='bad request')), 400

    @app.errorhandler(404)
    def resource_not_found(error):
        return jsonify(
            dict(success=False, error=404, message='resource not found')), 404

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify(
            dict(success=False,
                 error=422,
                 message='The server understands the '
                 'content type of the request entity')), 422

    return app
コード例 #6
0
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})


@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    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


setup_db(app)


@app.route('/')
def index():
    return 'Welcome to Rss Feed.'


'''
GET request for getting feeds based on user information. 
If no user exists, meaning user is new or that user was created prior but never add any rss url 
to feed, create new user in database 
request json format:
    {
        "given_name": "Mr. Test",
        "email": "*****@*****.**",
コード例 #7
0
#!/usr/bin/env python3
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from src.app import APP
from src.models import setup_db, db

setup_db(APP)

migrate = Migrate(APP, db)
manager = Manager(APP)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
コード例 #8
0
ファイル: api.py プロジェクト: lorcents/covid-19-estimator-py
def create_app(test_config=None):
    app = Flask(__name__)
    setup_db(app)

    @app.before_request
    def start_timer():
        g.start = time.time()

    @app.after_request
    def log_request(response):
        status_code = response.status.split()[0]

        latency_ms = int((time.time() - g.start) * 1000)

        new_log_entry = Log_entry(request_method=request.method,
                                  path=request.path,
                                  status_code=status_code,
                                  latency_ms=latency_ms)

        new_log_entry.insert()

        return response

    @app.route('/api/v1/on-covid-19', methods=['POST', 'GET'])
    @app.route('/api/v1/on-covid-19/', methods=['POST', 'GET'])
    @app.route('/api/v1/on-covid-19/<data_format>', methods=['POST', 'GET'])
    def compute_estimates(data_format=None):
        """
        Returns the covid-19 impact estimate based on the input data provided.
        """

        if data_format not in ['xml', 'json', None]:
            abort(404)

        try:
            request_payload = request.get_json()

            payload_is_valid = estimation_data_schema().load(request_payload)

            response_data = impact_estimator(request_payload)

            if data_format == 'xml':
                # create an xml version of the json data
                xml_data = dicttoxml(response_data)

                return Response(xml_data, mimetype='application/xml')

            elif data_format == 'json':
                return jsonify(response_data)

            return jsonify(response_data)

        except ValidationError:
            abort(400)

        except:
            print(sys.exc_info())
            abort(500)

    @app.route('/api/v1/on-covid-19/logs')
    def get_logs():
        try:
            request_response_logs = Log_entry.query.all()

            log_data = [entry.serialize() for entry in request_response_logs]

            formatted_log_data = ""

            for item in log_data:
                formatted_log_data += item + "\n"

            formatted_log_data = f"{formatted_log_data}"

            return Response(formatted_log_data, mimetype='text/plain')

        except:
            print(sys.exc_info())
            abort(500)

        finally:
            db.session.close()

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

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

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

    @app.errorhandler(500)
    def not_found(
        error,
        message="Something went wrong on the server, and we are looking into it. Sorry for the inconvenience."
    ):
        return jsonify({
            "success": False,
            "error": 500,
            "message": message
        }), 500

    return app