Python flask_restful.Api() Examples
The following are 30
code examples of flask_restful.Api().
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: __init__.py From papers with MIT License | 7 votes |
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
Example #2
Source File: api.py From zou with GNU Affero General Public License v3.0 | 7 votes |
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
Example #3
Source File: utils.py From cloudkitty with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: __init__.py From ml-enabler with BSD 2-Clause "Simplified" License | 6 votes |
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'])
Example #5
Source File: app.py From walle-web with Apache License 2.0 | 6 votes |
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
Example #6
Source File: __init__.py From AIOPS_PLATFORM with MIT License | 6 votes |
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)
Example #7
Source File: flask.py From Neuraxle with Apache License 2.0 | 6 votes |
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 #8
Source File: APIServer.py From crypto-bot with Apache License 2.0 | 6 votes |
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})
Example #9
Source File: app.py From cloudkitty with Apache License 2.0 | 6 votes |
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
Example #10
Source File: server.py From cwg with GNU General Public License v3.0 | 6 votes |
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);
Example #11
Source File: flask_app.py From cellphonedb with MIT License | 6 votes |
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
Example #12
Source File: __init__.py From Flask-Large-Application-Example with MIT License | 6 votes |
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
Example #13
Source File: rest_connector.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
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()
Example #14
Source File: unicorn_binance_websocket_api_manager.py From unicorn-binance-websocket-api with MIT License | 6 votes |
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))
Example #15
Source File: dummy_cuckoo_api.py From PeekabooAV with GNU General Public License v3.0 | 5 votes |
def run(): """ Run the API """ app = flask.Flask(__name__) app.debug = True api = flask_restful.Api(app) queue = Queue() api.add_resource(Status, '/cuckoo/status', resource_class_args=[queue]) api.add_resource(View, '/tasks/view/<job_id>', resource_class_args=[queue]) api.add_resource(Report, '/tasks/report/<job_id>', resource_class_args=[queue]) api.add_resource(Create, '/tasks/create/file', resource_class_args=[queue]) app.run(port='5002')
Example #16
Source File: chain_api.py From son-emu with Apache License 2.0 | 5 votes |
def __init__(self, inc_ip, inc_port, manage): # setup Flask self.app = Flask(__name__) self.api = Api(self.app) self.ip = inc_ip self.port = inc_port self.manage = manage self.playbook_file = '/tmp/son-emu-requests.log' self.api.add_resource(ChainVersionsList, "/", resource_class_kwargs={'api': self}) self.api.add_resource(ChainList, "/v1/chain/list", resource_class_kwargs={'api': self}) self.api.add_resource(ChainVnfInterfaces, "/v1/chain/<src_vnf>/<src_intfs>/<dst_vnf>/<dst_intfs>", resource_class_kwargs={'api': self}) self.api.add_resource(ChainVnfDcStackInterfaces, "/v1/chain/<src_dc>/<src_stack>/<src_vnf>/<src_intfs>/<dst_dc>/<dst_stack>/<dst_vnf>/<dst_intfs>", resource_class_kwargs={'api': self}) self.api.add_resource(BalanceHostList, "/v1/lb/list", resource_class_kwargs={'api': self}) self.api.add_resource(BalanceHost, "/v1/lb/<vnf_src_name>/<vnf_src_interface>", resource_class_kwargs={'api': self}) self.api.add_resource(BalanceHostDcStack, "/v1/lb/<src_dc>/<src_stack>/<vnf_src_name>/<vnf_src_interface>", resource_class_kwargs={'api': self}) self.api.add_resource(QueryTopology, "/v1/topo", resource_class_kwargs={'api': self}) @self.app.after_request def add_access_control_header(response): response.headers['Access-Control-Allow-Origin'] = '*' return response
Example #17
Source File: base_openstack_dummy.py From son-emu with Apache License 2.0 | 5 votes |
def __init__(self, listenip, port): self.ip = listenip self.port = port self.compute = None self.manage = None self.http_server = None self.server_thread = None self.playbook_file = '/tmp/son-emu-requests.log' with open(self.playbook_file, 'w'): pass # setup Flask self.app = Flask(__name__) self.api = Api(self.app)
Example #18
Source File: api.py From cobra with MIT License | 5 votes |
def start(host, port, debug): logger.info('Start {host}:{port}'.format(host=host, port=port)) api = Blueprint("api", __name__) resource = Api(api) resource.add_resource(AddJob, '/api/add') resource.add_resource(JobStatus, '/api/status') resource.add_resource(FileUpload, '/api/upload') resource.add_resource(ResultData, '/api/list') resource.add_resource(ResultDetail, '/api/detail') resource.add_resource(Search, '/api/search') resource.add_resource(GetMemeber, '/api/members') app.register_blueprint(api) # consumer threads = [] for i in range(5): threads.append(threading.Thread(target=consumer, args=())) for i in threads: i.setDaemon(daemonic=True) i.start() try: global running_port, running_host running_host = host if host != '0.0.0.0' else '127.0.0.1' running_port = port app.run(debug=debug, host=host, port=int(port), threaded=True, processes=1) except socket.error as v: if v.errno == errno.EACCES: logger.critical('[{err}] must root permission for start API Server!'.format(err=v.strerror)) exit() else: logger.critical('{msg}'.format(msg=v.strerror)) logger.info('API Server start success')
Example #19
Source File: utils.py From crmint with Apache License 2.0 | 5 votes |
def create_app(self): api_blueprint = Api() app = ibackend_create_app(api_blueprint, config_object=self) app.config['TESTING'] = True app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False return app
Example #20
Source File: server.py From captcha22 with MIT License | 5 votes |
def __init__(self, host="0.0.0.0", port="5000", is_debug=False, file_drop="./Unsorted/", max_tokens=5, server_location="./", user_file="users.txt", work_folder="./Busy", model_folder="./Model"): # Create the app self.app = Flask(__name__, static_url_path="") self.api = Api(self.app) self.host = host self.port = port self.debug = is_debug self.source = data_source(file_drop, max_tokens, server_location, user_file, work_folder, model_folder) self.systemAuth = AuthSystem(self.source) self.api.add_resource(CaptchaListAPI, '/captcha22/api/v1.0/captchas', endpoint='captchas', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(CaptchaAPI, '/captcha22/api/v1.0/captchas/<int:id>', endpoint='captcha', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(ExportAPI, '/captcha22/api/v1.0/export_model/<string:dataToken>', endpoint='export_model', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(GetProgressAPI, '/captcha22/api/v1.0/training_update/<string:dataToken>', endpoint='training_update', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(GetResultsAPI, '/captcha22/api/v1.0/results/<string:dataToken>', endpoint='results', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(ToggleModelAPI, '/captcha22/api/v1.0/activate_model', endpoint='activate_model', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(SolveCaptchaAPI, '/captcha22/api/v1.0/solve_captcha', endpoint='solve_captcha', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth}) self.api.add_resource(GenerateTokenAPI, '/captcha22/api/v1.0/generate_token', endpoint='generate_token', resource_class_kwargs={'source': self.source, 'auth': self.systemAuth})
Example #21
Source File: utils.py From crmint with Apache License 2.0 | 5 votes |
def create_app(self): api_blueprint = Api() app = jbackend_create_app(api_blueprint, config_object=self) app.config['TESTING'] = True app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False return app
Example #22
Source File: create_app.py From postgraas_server with Apache License 2.0 | 5 votes |
def create_app(config): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = get_meta_db_config_path(config) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['BUNDLE_ERRORS'] = True app_config = get_application_config(config) for key in app_config: app.config[key.upper()] = int(app_config[key]) if key.upper() in INT_OPTIONS else app_config[key] app.config['SENTRY_INCLUDE_PATHS'] = [ 'postgraas_server', ] app.config['SENTRY_RELEASE'] = postgraas_server.__version__ sentry.init_app(app) restful_api = Api(app) restful_api.add_resource(DBInstanceResource, "/api/v2/postgraas_instances/<int:id>") restful_api.add_resource(DBInstanceCollectionResource, "/api/v2/postgraas_instances") db.init_app(app) app.postgraas_backend = get_backend(config) @app.route('/health') def health(): return "ok" return app
Example #23
Source File: app.py From image_text_reader with MIT License | 5 votes |
def setup_api(): api = Api(app) api.add_resource(ReadViaImage, ROOT_PATH + '/image') api.add_resource(ReadViaUrl, ROOT_PATH + '/url')
Example #24
Source File: rest_base.py From FACT_core with GNU General Public License v3.0 | 5 votes |
def __init__(self, app=None, config=None): self.api = Api(app) self.api.add_resource(RestBinary, '/rest/binary/<uid>', methods=['GET'], resource_class_kwargs={'config': config}) self.api.add_resource(RestBinarySearch, '/rest/binary_search', '/rest/binary_search/<search_id>', methods=['GET', 'POST'], resource_class_kwargs={'config': config}) self.api.add_resource(RestCompare, '/rest/compare', '/rest/compare/<compare_id>', methods=['GET', 'PUT'], resource_class_kwargs={'config': config}) self.api.add_resource(RestFileObject, '/rest/file_object', '/rest/file_object/<uid>', methods=['GET'], resource_class_kwargs={'config': config}) self.api.add_resource(RestFirmware, '/rest/firmware', '/rest/firmware/<uid>', methods=['GET', 'PUT'], resource_class_kwargs={'config': config}) self.api.add_resource(RestMissingAnalyses, RestMissingAnalyses.URL, methods=['GET'], resource_class_kwargs={'config': config}) self.api.add_resource(RestStatus, '/rest/status', methods=['GET'], resource_class_kwargs={'config': config}) self._wrap_response(self.api)
Example #25
Source File: test_plugin_routes.py From FACT_core with GNU General Public License v3.0 | 5 votes |
def setUp(self): self.app = Flask(__name__) self.app.config.from_object(__name__) self.api = Api(self.app) self.config = get_config_for_testing()
Example #26
Source File: test_routes.py From FACT_core with GNU General Public License v3.0 | 5 votes |
def setUp(self): routes.FrontEndDbInterface = DbInterfaceMock app = Flask(__name__) app.config.from_object(__name__) app.config['TESTING'] = True config = get_config_for_testing() api = Api(app) endpoint, methods = routes.QemuExecRoutesRest.ENDPOINTS[0] api.add_resource( routes.QemuExecRoutesRest, endpoint, methods=methods, resource_class_kwargs={'config': config} ) self.test_client = app.test_client()
Example #27
Source File: test_file_system_metadata_routes.py From FACT_core with GNU General Public License v3.0 | 5 votes |
def setUp(self): routes.FrontEndDbInterface = DbInterfaceMock app = Flask(__name__) app.config.from_object(__name__) app.config['TESTING'] = True config = get_config_for_testing() api = Api(app) endpoint, methods = routes.FSMetadataRoutesRest.ENDPOINTS[0] api.add_resource( routes.FSMetadataRoutesRest, endpoint, methods=methods, resource_class_kwargs={'config': config} ) self.test_client = app.test_client()
Example #28
Source File: restapi.py From floranet with MIT License | 5 votes |
def __init__(self, app, server): # NetServer self.server = server # Set the version self.version = 1.0 # Initialise the API self.api = Api(app, prefix='/api/v' + str(self.version)) # Setup routing self.resources = { # System endpoint '/system': RestSystem, # Device endpoints '/device/<int:deveui>': RestDevice, '/devices': RestDevices, # Application endpoints '/app/<int:appeui>': RestApplication, '/apps': RestApplications, # Gateway endpoints '/gateway/<host>': RestGateway, '/gateways': RestGateways, # Application interface endpoints '/interface/<appinterface_id>': RestAppInterface, '/interfaces': RestAppInterfaces, # Application property endpoints '/property/<int:appeui>': RestAppProperty, '/propertys': RestAppPropertys } kwargs = {'restapi': self, 'server': self.server} for path,klass in self.resources.iteritems(): self.api.add_resource(klass, path, resource_class_kwargs=kwargs)
Example #29
Source File: server.py From captcha22 with MIT License | 5 votes |
def __init__(self, source): self.auth = HTTPBasicAuth() self.source = source @self.auth.verify_password def verify_password(username, password): for user in self.source.users: if user.username == username: return check_password_hash(user.password, password) return False @self.auth.error_handler def unauthorized(): # return 403 instead of 401 to prevent browsers from displaying the default # auth dialog return make_response(jsonify({'message': 'Unauthorized access'}), 403) self.second_auth = HTTPTokenAuth() @self.second_auth.verify_token def verify_token(token): self.clean_tokens() headers = request.headers token = headers.get("X-Api-Key") for user in self.source.users: for current_token in user.tokens: if user.tokens[current_token][0] == token: return True return False @self.second_auth.error_handler def unauthorized(): # return 403 instead of 401 to prevent browsers from displaying the default # auth dialog return make_response(jsonify({'message': 'Unauthorized access'}), 403)
Example #30
Source File: server.py From captcha22 with MIT License | 5 votes |
def get_username(self): headers = request.headers token = headers.get("X-Api-Key") for user in self.source.users: for current_token in user.tokens: if user.tokens[current_token][0] == token: return user.username return ""