本文整理汇总了Python中flask_restful.Api方法的典型用法代码示例。如果您正苦于以下问题:Python flask_restful.Api方法的具体用法?Python flask_restful.Api怎么用?Python flask_restful.Api使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask_restful
的用法示例。
在下文中一共展示了flask_restful.Api方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def __init__(self, gateway, config, connector_type):
super().__init__()
self.__log = log
self._default_converters = {
"uplink": "JsonRESTUplinkConverter",
"downlink": "JsonRESTDownlinkConverter"
}
self.__config = config
self._connector_type = connector_type
self.statistics = {'MessagesReceived': 0,
'MessagesSent': 0}
self.__gateway = gateway
self.__USER_DATA = {}
self.setName(config.get("name", 'REST Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))
self._connected = False
self.__stopped = False
self.daemon = True
self._app = Flask(self.get_name())
self._api = Api(self._app)
self.__rpc_requests = []
self.__attribute_updates = []
self.__fill_requests_from_TB()
self.endpoints = self.load_endpoints()
self.load_handlers()
示例2: route
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def route(flask_app: Flask):
from app.views.sample.api import SampleAPI
handle_exception_func = flask_app.handle_exception
handle_user_exception_func = flask_app.handle_user_exception
# register_blueprint 시 defer되었던 함수들이 호출되며, flask-restful.Api._init_app()이 호출되는데
# 해당 메소드가 app 객체의 에러 핸들러를 오버라이딩해서, 별도로 적용한 handler의 HTTPException 관련 로직이 동작하지 않음
# 따라서 두 함수를 임시 저장해 두고, register_blueprint 이후 함수를 재할당하도록 함
# - blueprint, api object initialize
api_blueprint = Blueprint("api", __name__)
api = Api(api_blueprint)
# - route
api.add_resource(SampleAPI, "/sample")
# - register blueprint
flask_app.register_blueprint(api_blueprint)
flask_app.handle_exception = handle_exception_func
flask_app.handle_user_exception = handle_user_exception_func
示例3: create_app
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def create_app(environment=None, support=None, load_defaults=None, raise_non_defined_vars=True, verbose=None):
app = Flask(__name__)
config = app_config.AppConfig(environment, support, load_defaults, raise_non_defined_vars, verbose=verbose)
cellphone_config = config.get_cellphone_core_config()
cellphonedb_app.init_app(cellphone_config)
flask_config = config.flask_config()
app.config.from_mapping(flask_config)
app.url_map.strict_slashes = False
api = Api(app, prefix=flask_config['API_PREFIX'])
routes.add(api, '/v1')
return app
示例4: create_app
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def create_app(env):
app = Flask(__name__)
app.config.from_object(config[env])
# Start api/v1 Blueprint
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
api.add_resource(auth.AuthLogin, '/auth/login')
api.add_resource(auth.AuthRegister, '/auth/register')
api.add_resource(files.CreateList, '/users/<user_id>/files')
api.add_resource(files.ViewEditDelete, '/users/<user_id>/files/<file_id>')
app.register_blueprint(api_bp, url_prefix="/api/v1")
# End api/v1 Blueprint
return app
示例5: configure_api_from_blueprint
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def configure_api_from_blueprint(blueprint, route_tuples):
"""
Creates a Flask Restful api object based on information from given
blueprint. API is configured to return JSON objects.
Each blueprint is describe by a list of tuple. Each tuple is composed of a
route and the related resource (controller).
"""
api = Api(blueprint, catch_all_404s=True)
api.representations = {
"application/json; charset=utf-8": output_json,
"application/json": output_json,
}
for route_tuple in route_tuples:
(path, resource) = route_tuple
api.add_resource(resource, path)
return api
示例6: init_routes
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def init_routes(app):
""" Initialize all API routes """
api = Api(app)
# import apis
from ml_enabler.api.ml import StatusCheckAPI, MLModelAPI, GetAllModels, \
PredictionAPI, PredictionTileAPI, MLModelTilesAPI, \
MLModelTilesGeojsonAPI, GetAllPredictions
from ml_enabler.api.swagger import SwaggerDocsAPI
api.add_resource(StatusCheckAPI, '/')
api.add_resource(SwaggerDocsAPI, '/v1/docs')
api.add_resource(GetAllModels, '/v1/model/all', methods=['GET'])
api.add_resource(MLModelAPI, '/v1/model', endpoint="post", methods=['POST'])
api.add_resource(MLModelAPI, '/v1/model/<int:model_id>', methods=['DELETE', 'GET', 'PUT'])
api.add_resource(PredictionAPI, '/v1/model/<int:model_id>/prediction', methods=['POST', 'GET'])
api.add_resource(GetAllPredictions, '/v1/model/<int:model_id>/prediction/all', methods=['GET'])
api.add_resource(PredictionTileAPI, '/v1/model/prediction/<int:prediction_id>/tiles', methods=['POST'])
api.add_resource(MLModelTilesAPI, '/v1/model/<int:model_id>/tiles', methods=['GET'])
api.add_resource(MLModelTilesGeojsonAPI, '/v1/model/<int:model_id>/tiles/geojson', methods=['POST'])
示例7: register_blueprints
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def register_blueprints(app):
"""Register Flask blueprints."""
api = Api(app)
api.add_resource(BaseAPI.Base, '/', endpoint='root')
api.add_resource(GeneralAPI.GeneralAPI, '/api/general/<string:action>', endpoint='general')
api.add_resource(SpaceAPI.SpaceAPI, '/api/space/', '/api/space/<int:space_id>', '/api/space/<int:space_id>/<string:action>', endpoint='space')
api.add_resource(DeployAPI.DeployAPI, '/api/deploy/', '/api/deploy/<int:task_id>', endpoint='deploy')
api.add_resource(AccessAPI.AccessAPI, '/api/access/', '/api/access/<int:access_id>', endpoint='access')
api.add_resource(RoleAPI.RoleAPI, '/api/role/', endpoint='role')
api.add_resource(GroupAPI.GroupAPI, '/api/group/', '/api/group/<int:group_id>', endpoint='group')
api.add_resource(PassportAPI.PassportAPI, '/api/passport/', '/api/passport/<string:action>', endpoint='passport')
api.add_resource(UserAPI.UserAPI, '/api/user/', '/api/user/<int:user_id>/<string:action>', '/api/user/<string:action>', '/api/user/<int:user_id>', endpoint='user')
api.add_resource(ServerAPI.ServerAPI, '/api/server/', '/api/server/<int:id>', endpoint='server')
api.add_resource(ProjectAPI.ProjectAPI, '/api/project/', '/api/project/<int:project_id>', '/api/project/<int:project_id>/<string:action>', endpoint='project')
api.add_resource(RepoApi.RepoAPI, '/api/repo/<string:action>/', endpoint='repo')
api.add_resource(TaskAPI.TaskAPI, '/api/task/', '/api/task/<int:task_id>', '/api/task/<int:task_id>/<string:action>', endpoint='task')
api.add_resource(EnvironmentAPI.EnvironmentAPI, '/api/environment/', '/api/environment/<int:env_id>', endpoint='environment')
return None
示例8: getApp
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def getApp(name):
## init flask
app = Flask(name, template_folder = '{}/app/templates'.format(workpath), static_folder = '{}/app/static'.format(workpath))
app.secret_key = os.urandom(24)
api = Api(app)
## init db config
app.config['SQLALCHEMY_DATABASE_URI'] ='mysql+pymysql://{}:{}@{}:{}/{}'.format(MARIADB_USER, MARIADB_PASSWORD,
MARIADB_HOST, MARIADB_PORT, MARIADB_DATABASE)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db.init_app(app)
## set up login manager
login_manager.session_protection = 'strong'
login_manager.login_view = 'signinpage'
login_manager.login_message = 'Unauthorized User'
login_manager.login_message_category = 'info'
login_manager.init_app(app)
## set up csrf
csrf.init_app(app)
return(app, api)
示例9: get_app
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [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
示例10: setup_app
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def setup_app():
root_app = flask.Flask('cloudkitty')
root_api = flask_restful.Api(root_app)
root_api.add_resource(api_root.CloudkittyAPIRoot, '/')
dispatch_dict = {
'/v1': get_v1_app(),
'/v2': get_v2_app(),
}
# Disabling v2 api in case v1 storage is used
if CONF.storage.version < 2:
LOG.warning('v1 storage is used, disabling v2 API')
dispatch_dict.pop('/v2')
app = dispatcher.DispatcherMiddleware(root_app, dispatch_dict)
return app
示例11: do_init
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def do_init(app, blueprint_name, resources):
"""Registers a new Blueprint containing one or several resources to app.
:param app: Flask app in which the Blueprint should be registered
:type app: flask.Flask
:param blueprint_name: Name of the blueprint to create
:type blueprint_name: str
:param resources: Resources to add to the Blueprint's Api
:type resources: list of dicts matching
``cloudkitty.api.v2.RESOURCE_SCHEMA``
"""
blueprint, api = _get_blueprint_and_api(blueprint_name)
schema = voluptuous.Schema([v2_api.RESOURCE_SCHEMA])
for resource_info in schema(resources):
resource = _load_resource(resource_info['module'],
resource_info['resource_class'])
if resource_info['url'] and not resource_info['url'].startswith('/'):
resource_info['url'] = '/' + resource_info['url']
api.add_resource(resource, resource_info['url'])
if not blueprint_name.startswith('/'):
blueprint_name = '/' + blueprint_name
app.register_blueprint(blueprint, url_prefix=blueprint_name)
示例12: __init__
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def __init__(self, trade_handler: TradeHandler):
self.th = trade_handler
self.app = app
self.app.config['JWT_SECRET_KEY'] = 'mHZ!?9@DzdLrn@H!gy2FD46W--M*Fap!' # TODO: Change this!
self.app.config['SECRET_KEY'] = 'VS?cWpbD^CGa-M@h6+@pV#qCQRU3c4dn' # TODO: Change this!
self.app.config['JWT_EXPIRES'] = timedelta(weeks=48)
self.jwt = JWTManager(app)
self.api = Api(self.app)
CORS(self.app)
self.api.add_resource(TradeListEndpoint, APIServer.API_PREFIX + '/trades',
resource_class_kwargs={'trade_handler': self.th})
self.api.add_resource(TradeEndpoint, APIServer.API_PREFIX + '/trade/<id>',
resource_class_kwargs={'trade_handler': self.th})
self.api.add_resource(APIExchangeInfoEndpoint, APIServer.API_PREFIX + '/info',
resource_class_kwargs={'trade_handler': self.th})
self.api.add_resource(JWTEndpoint, APIServer.API_PREFIX + '/auth',
resource_class_kwargs={'trade_handler': self.th})
示例13: main
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def main(argv):
global MAKEMEAHANZI_PATH, CEDICT_PATH;
opts, args = getopt.getopt(argv, '', ['makemeahanzi=', 'cedict=']);
for opt, arg in opts:
if opt == '--makemeahanzi':
MAKEMEAHANZI_PATH = arg;
elif opt == '--cedict':
CEDICT_PATH = arg;
if MAKEMEAHANZI_PATH == '' or CEDICT_PATH == '':
usage();
exit(1);
app = Flask(__name__);
cors = CORS(app);
app.config['CORS_HEADERS'] = 'Content-Type';
api = Api(app);
api.add_resource(GenerateInfos, '/generate_infos');
api.add_resource(GenerateSheet, '/generate_sheet');
api.add_resource(RetrieveSheet, '/retrieve_sheet');
api.add_resource(RetrieveCount, '/retrieve_count');
app.run(port='5002', threaded=True);
示例14: app_factory
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def app_factory(api_name: str = "api") -> Flask:
"""Create an app object."""
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key'
CORS(app)
app.url_map.strict_slashes = False
api = Api(app)
api.add_resource(Index, "/{}/".format(api_name), endpoint="api")
api.add_resource(Vocab, "/{}/vocab".format(api_name), endpoint="vocab")
api.add_resource(
Contexts,
"/{}/contexts/<string:category>.jsonld".format(api_name),
endpoint="contexts")
api.add_resource(
Entrypoint,
"/{}/contexts/EntryPoint.jsonld".format(api_name),
endpoint="main_entrypoint")
api.add_resource(
ItemCollection,
"/{}/<string:path>".format(api_name),
endpoint="item_collection")
api.add_resource(
Item,
"/{}/<string:path>/<uuid:id_>".format(api_name),
endpoint="item")
api.add_resource(
Items,
"/{}/<string:path>/add/<int_list>".format(api_name),
"/{}/<string:path>/add".format(api_name),
"/{}/<string:path>/delete/<int_list>".format(api_name))
return app
示例15: _start_monitoring_api_thread
# 需要导入模块: import flask_restful [as 别名]
# 或者: from flask_restful import Api [as 别名]
def _start_monitoring_api_thread(self, host, port, warn_on_update):
"""
Threaded method that servces the monitoring api
:param host: IP or hostname to use
:type host: str
:param port: Port to use
:type port: int
:param warn_on_update: Should the monitoring system report available updates?
:type warn_on_update: bool
"""
logging.info("Starting monitoring API service ...")
app = Flask(__name__)
@app.route('/')
@app.route('/status/')
def redirect_to_wiki():
logging.debug("Visit https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/UNICORN-"
"Monitoring-API-Service for further information!")
return redirect("https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/"
"UNICORN-Monitoring-API-Service", code=302)
api = Api(app)
api.add_resource(BinanceWebSocketApiRestServer,
"/status/<string:statusformat>/",
"/status/<string:statusformat>/<string:checkcommandversion>",
resource_class_kwargs={'handler_binance_websocket_api_manager': self,
'warn_on_update': warn_on_update})
try:
dispatcher = wsgi.PathInfoDispatcher({'/': app})
self.monitoring_api_server = wsgi.WSGIServer((host, port), dispatcher)
self.monitoring_api_server.start()
except RuntimeError as error_msg:
logging.critical("Monitoring API service is going down! - Info: " + str(error_msg))
except OSError as error_msg:
logging.critical("Monitoring API service is going down! - Info: " + str(error_msg))
开发者ID:oliver-zehentleitner,项目名称:unicorn-binance-websocket-api,代码行数:37,代码来源:unicorn_binance_websocket_api_manager.py