Python flask_restful.Resource() Examples

The following are 17 code examples of flask_restful.Resource(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_restful , or try the search function .
Example #1
Source File: main.py    From syntaxnet-rest-api with GNU General Public License v3.0 6 votes vote down vote up
def post(self):
        args = self.reqparse.parse_args()
        if parse_handler==None:
            return {"result":"fail", "reason":"Please initialize the model first!"}, 400
        #parse = parser.SyntaxnetParser(segmenter_model,parser_model,folder=args['syntax_folder'])
        try:
            return parse_handler.parse_multi_string(args['strings'],tree=args['tree'])
        except Exception as e:
            return {'result': 'fail', "reason": str(e)}, 400

# class SyntaxModelQuery(Resource):
#     def __init__(self):
#         self.reqparse = reqparse.RequestParser()
#         self.reqparse.add_argument('strings', required=True, type=list, help='string is required field, you should input a list of strings', location='json')
#         self.reqparse.add_argument('syntax_folder', required=False, type=str, default=config.syntaxnetFolder,
#                                    location='json')
#         super(SyntaxModelQuery, self).__init__()
#
#     def post(self,folder):
#         args = self.reqparse.parse_args()
#         parse = parser.SyntaxnetParser(folder=args['syntax_folder'])
#         try:
#             return parse.parse_multi_string_custom(args['strings'],folder=folder)
#         except Exception, e:
#             return {'result': 'fail', "reason": e}, 400 
Example #2
Source File: resource.py    From cmdb with GNU General Public License v2.0 6 votes vote down vote up
def register_resources(resource_path, rest_api):
    for root, _, files in os.walk(os.path.join(resource_path)):
        for filename in files:
            if not filename.startswith("_") and filename.endswith("py"):
                module_path = os.path.join(API_PACKAGE, root[root.index("views"):])
                if module_path not in sys.path:
                    sys.path.insert(1, module_path)
                view = __import__(os.path.splitext(filename)[0])
                resource_list = [o[0] for o in getmembers(view) if isclass(o[1]) and issubclass(o[1], Resource)]
                resource_list = [i for i in resource_list if i != "APIView"]
                for resource_cls_name in resource_list:
                    resource_cls = getattr(view, resource_cls_name)
                    if not hasattr(resource_cls, "url_prefix"):
                        resource_cls.url_prefix = ("",)
                    if isinstance(resource_cls.url_prefix, six.string_types):
                        resource_cls.url_prefix = (resource_cls.url_prefix,)

                    rest_api.add_resource(resource_cls, *resource_cls.url_prefix) 
Example #3
Source File: api.py    From raiden-services with MIT License 6 votes vote down vote up
def __init__(
        self,
        monitoring_service: MonitoringService,
        operator: str,
        info_message: str = DEFAULT_INFO_MESSAGE,
    ) -> None:
        self.flask_app = Flask(__name__)
        self.api = ApiWithErrorHandler(self.flask_app)
        self.rest_server: Optional[WSGIServer] = None

        self.monitoring_service = monitoring_service
        self.operator = operator
        self.info_message = info_message

        resources: List[Tuple[str, Resource, str]] = [
            ("/info", cast(Resource, InfoResource), "info"),
        ]

        for endpoint_url, resource, endpoint in resources:
            self.api.add_resource(
                resource,
                API_PATH + endpoint_url,
                resource_class_kwargs={"monitoring_service": monitoring_service, "api": self},
                endpoint=endpoint,
            ) 
Example #4
Source File: flask.py    From Neuraxle with Apache License 2.0 6 votes vote down vote up
def get_app(self):
        """
        This methods returns a REST API wrapping the pipeline.

        :return: a Flask app (as given by `app = Flask(__name__)` and then configured).
        """
        from flask import Flask, request
        from flask_restful import Api, Resource

        app = Flask(__name__)
        api = Api(app)
        wrapped = self

        class RESTfulRes(Resource):
            def get(self):
                return wrapped.transform(request.get_json())

        api.add_resource(
            RESTfulRes,
            self.route
        )

        return app 
Example #5
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def put(self, project_id, entity_id):
        """
        Resource to allow the modification of assets linked to an entity.
        """
        casting = request.json
        user_service.check_manager_project_access(project_id)
        return breakdown_service.update_casting(entity_id, casting) 
Example #6
Source File: plugin_routes.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def _import_module_routes(self, plugin, plugin_type):
        module = importlib.import_module('plugins.{0}.{1}.{2}.{2}'.format(plugin_type, plugin, ROUTES_MODULE_NAME))
        if hasattr(module, 'PluginRoutes'):
            module.PluginRoutes(self._app, self._config)
        for rest_class in [
            element for element in [getattr(module, attribute) for attribute in dir(module)]
            if inspect.isclass(element) and issubclass(element, Resource) and not element == Resource
        ]:
            for endpoint, methods in rest_class.ENDPOINTS:
                self._api.add_resource(rest_class, endpoint, methods=methods, resource_class_kwargs={'config': self._config}) 
Example #7
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return "<Resource {0}>".format(self.__class__.__name__) 
Example #8
Source File: index.py    From --Awesome-Python-- with GNU General Public License v3.0 5 votes vote down vote up
def get(self):
        print(request.args['key'])
        # 요청 데이터에 접근할 때, 해당 key가 존재하지 않는다면 자동으로 '400 bad request'를 abort해 준다

        return [1, 2, 3]
        # Flask의 route 데코레이터를 통한 라우팅에서 이 구문은 TypeError를 발생시키지만
        # Flask-restful의 Resource를 상속받아 API를 구현하면 반환이 자동으로 직렬화되며 Content Type이 application/json으로 처리됨 
Example #9
Source File: test_blueprint.py    From prometheus_flask_exporter with MIT License 5 votes vote down vote up
def test_restful_with_blueprints(self):
        try:
            from flask_restful import Resource, Api
        except ImportError:
            self.skipTest('Flask-RESTful is not available')
            return

        class SampleResource(Resource):
            status = 200

            @self.metrics.summary('requests_by_status', 'Request latencies by status',
                                  labels={'status': lambda r: r.status_code})
            def get(self):
                if 'fail' in request.args:
                    return 'Not OK', 400
                else:
                    return 'OK'

        blueprint = Blueprint('v1', __name__, url_prefix='/v1')
        api = Api(blueprint)

        api.add_resource(SampleResource, '/sample', endpoint='api_sample')

        self.app.register_blueprint(blueprint)
        self.metrics.init_app(self.app)

        self.client.get('/v1/sample')
        self.client.get('/v1/sample')
        self.client.get('/v1/sample?fail=1')

        response = self.client.get('/metrics')
        self.assertEqual(response.status_code, 200)

        self.assertIn('requests_by_status_count{status="200"} 2.0', str(response.data))
        self.assertRegex(str(response.data), 'requests_by_status_sum{status="200"} [0-9.]+')

        self.assertIn('requests_by_status_count{status="400"} 1.0', str(response.data))
        self.assertRegex(str(response.data), 'requests_by_status_sum{status="400"} [0-9.]+') 
Example #10
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, asset_id):
        """
        Resource to retrieve the casting of a given asset.
        """
        asset = assets_service.get_asset(asset_id)
        user_service.check_project_access(asset["project_id"])
        user_service.check_entity_access(asset["id"])
        return breakdown_service.get_cast_in(asset_id) 
Example #11
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, asset_id):
        """
        Resource to retrieve the casting of a given asset.
        """
        asset = assets_service.get_asset(asset_id)
        user_service.check_project_access(asset["project_id"])
        user_service.check_entity_access(asset_id)
        return breakdown_service.get_casting(asset_id) 
Example #12
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, project_id, asset_type_id):
        """
        Resource to retrieve the casting of assets from given asset type.
        """
        user_service.check_project_access(project_id)
        assets_service.get_asset_type(asset_type_id)
        return breakdown_service.get_asset_type_casting(
            project_id, asset_type_id
        ) 
Example #13
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, project_id, sequence_id):
        """
        Resource to retrieve the casting of shots from given sequence.
        """
        user_service.check_project_access(project_id)
        shots_service.get_sequence(sequence_id)
        return breakdown_service.get_sequence_casting(sequence_id) 
Example #14
Source File: resources.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, project_id, entity_id):
        """
        Resource to retrieve the casting of a given entity.
        """
        user_service.check_project_access(project_id)
        return breakdown_service.get_casting(entity_id) 
Example #15
Source File: resource_streamer.py    From actinia_core with GNU General Public License v3.0 4 votes vote down vote up
def get(self, user_id, resource_id, file_name):
        """Get the file based resource as HTTP attachment

        Args:
            user_id (str): The unique user name/id
            resource_id (str): The id of the resource
            file_name (str): The name of the file to send as attachment

        Returns:
            flask.Response: A HTTP response with the
                            file as attachment in case of success or
                            JSON payload containing the error status
                            and a message

            The HTTP status 200 header::

                Content-Disposition: attachment; filename=my_accumulation.tiff
                Content-Length: 3469
                Content-Type: image/tiff
                Last-Modified: Tue, 07 Jun 2016 10:34:17 GMT
                Cache-Control: public, max-age=43200
                Expires: Tue, 07 Jun 2016 22:34:18 GMT
                ETag: "1465295657.53-3469-665590421"
                Date: Tue, 07 Jun 2016 10:34:18 GMT


            The HTTP status 400 response JSON contents::

                {
                  "Messages": "Resource does not exist",
                  "Status": "error"
                }

        """

        resource_dir = global_config.GRASS_RESOURCE_DIR
        user_export_path =os.path.join(resource_dir, user_id)
        resource_export_path = os.path.join(user_export_path, resource_id)
        resource_export_file_path = os.path.join(resource_export_path, file_name)

        if os.path.exists(resource_export_file_path) is True and \
                          os.access(resource_export_file_path, os.R_OK) is True:

            return send_from_directory(resource_export_path,
                                       file_name, as_attachment=True)
        else:
            return make_response(jsonify({"status":"error",
                                          "message":"Resource does not exist"}), 400) 
Example #16
Source File: interactive.py    From pytorch-human-performance-gec with Apache License 2.0 4 votes vote down vote up
def listen_to_web(args, max_positions, task, process_batch):
    # initialize web app
    app = Flask(__name__, static_folder='')
    api = Api(app)

    # register route for web server

    # a simple form page
    @app.route('/form')
    def form():
        input = request.args.get('input', '')
        inputs = [input]
        results, outputs = process_inputs(args, inputs, max_positions, task, process_batch)
        return render_template('form.html', input=input, outputs=outputs)

    # a dynamic web app with static resource
    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/static/<path:path>')
    def send_static(path):
        return send_from_directory('templates/static', path)

    # a JSON api
    resource_fields = {
        'iteration': fields.Integer,
        'src_str': fields.String, 'hypo_str': fields.String,
        'hypo_score': fields.Float, 'pos_scores': fields.Float, 'gleu_scores': fields.Float,
        'fluency_scores': fields.Float, 'alignments': fields.Float,
        'hypo_score_str': fields.String, 'pos_scores_str': fields.String, 'gleu_scores_str': fields.String,
        'fluency_scores_str': fields.String,  'alignments_str': fields.String
    }
    class API(Resource):
        @marshal_with(resource_fields)
        def get(self, input):
            inputs = [input]
            results, outputs = process_inputs(args, inputs, max_positions, task, process_batch)
            # return outputs # raw string outputs
            return results # json

    # register routes for API
    api.add_resource(API, '/api/<string:input>')

    # listen with web server
    print('server running at port: {}'.format(args.port))
    http_server = WSGIServer(('', args.port), app)
    http_server.serve_forever() 
Example #17
Source File: test_views.py    From flask-limiter with MIT License 4 votes vote down vote up
def test_flask_restful_resource(extension_factory):
    app, limiter = extension_factory(default_limits=["1/hour"])
    api = RestfulApi(app)

    class Va(Resource):
        decorators = [limiter.limit("2/second")]

        def get(self):
            return request.method.lower()

        def post(self):
            return request.method.lower()

    class Vb(Resource):
        decorators = [limiter.limit("1/second, 3/minute")]

        def get(self):
            return request.method.lower()

    class Vc(Resource):
        def get(self):
            return request.method.lower()

    class Vd(Resource):
        decorators = [
            limiter.limit("2/second", methods=['GET']),
            limiter.limit("1/second", methods=['POST']),

        ]

        def get(self):
            return request.method.lower()

        def post(self):
            return request.method.lower()

    api.add_resource(Va, "/a")
    api.add_resource(Vb, "/b")
    api.add_resource(Vc, "/c")
    api.add_resource(Vd, "/d")

    with hiro.Timeline().freeze() as timeline:
        with app.test_client() as cli:
            assert 200 == cli.get("/a").status_code
            assert 200 == cli.get("/a").status_code
            assert 429 == cli.get("/a").status_code
            assert 429 == cli.post("/a").status_code
            assert 200 == cli.get("/b").status_code
            assert 200 == cli.get("/d").status_code
            assert 200 == cli.get("/d").status_code
            assert 429 == cli.get("/d").status_code
            assert 200 == cli.post("/d").status_code
            assert 429 == cli.post("/d").status_code
            timeline.forward(1)
            assert 200 == cli.get("/b").status_code
            timeline.forward(1)
            assert 200 == cli.get("/b").status_code
            timeline.forward(1)
            assert 429 == cli.get("/b").status_code
            assert 200 == cli.get("/c").status_code
            assert 429 == cli.get("/c").status_code