本文整理汇总了Python中flask_restful.Resource方法的典型用法代码示例。如果您正苦于以下问题:Python flask_restful.Resource方法的具体用法?Python flask_restful.Resource怎么用?Python flask_restful.Resource使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask_restful
的用法示例。
在下文中一共展示了flask_restful.Resource方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_app
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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
示例2: __init__
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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,
)
示例3: register_resources
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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)
示例4: post
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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
示例5: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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)
示例6: put
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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)
示例7: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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)
示例8: test_restful_with_blueprints
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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.]+')
示例9: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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으로 처리됨
示例10: __repr__
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
def __repr__(self):
return "<Resource {0}>".format(self.__class__.__name__)
示例11: _import_module_routes
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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})
示例12: get
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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)
示例13: listen_to_web
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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()
示例14: test_flask_restful_resource
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Resource [as 别名]
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