我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用flask_restful.Api()。
def build_app(configure_logging=True, with_keystone=True): app = flask.Flask(__name__) app.url_map.converters.update(converters.ALL) api.init_app(app) # init_app spoils Api object if app is a blueprint app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # silence warning # TUNINGBOX_SETTINGS is the path to the file with tuning_box configuration app.config.from_envvar('TUNINGBOX_SETTINGS', silent=True) # These handlers work if PROPAGATE_EXCEPTIONS is on (Nailgun case) app.register_error_handler(sa_exc.IntegrityError, handle_integrity_error) app.register_error_handler(errors.TuningboxIntegrityError, handle_integrity_error) app.register_error_handler(errors.TuningboxNotFound, handle_object_not_found) app.register_error_handler(errors.RequestValidationError, handle_request_validation_error) app.register_error_handler(errors.KeysOperationError, handle_keys_operation_error) db.db.init_app(app) if configure_logging: log_level = app.config.get('LOG_LEVEL', 'DEBUG') logger.init_logger(app, log_level) if with_keystone: app.wsgi_app = keystone.KeystoneMiddleware(app) return app
def deferred(self): """Runs the API, listens to external requests.""" app = Flask('argosd') api = flask_restful.Api(app) api.add_resource(ShowsResource, '/shows') api.add_resource(ShowResource, '/shows/<int:show_id>') api.add_resource(EpisodesResource, '/episodes') logfile = '{}/api.log'.format(settings.LOG_PATH) logformat = '%(message)s' logging.basicConfig(format=logformat, level=logging.INFO, filename=logfile, filemode='a') app.run(host='0.0.0.0', port=27467)
def __init__(self, debug, core, host, port, app_root): self.core = core self.flask = Flask("PyPush.web", static_folder=os.path.join(const.PUSH_WEB_DIR, "static"), template_folder=os.path.join(const.PUSH_WEB_DIR, "templates"), ) self.bower = Bower(self.flask) self.restful = Api(self.flask) self._applyDefaultConfig() self.host = host self.port = port self.debug = debug self.flask.config.update( APPLICATION_ROOT=app_root, )
def register_blueprints(app): api_bp = Blueprint('api', __name__) api = Api(api_bp) api.add_resource(UserView, '/users', '/users/<int:id>') api.add_resource(OrderView, '/orders', '/orders/<int:id>') api.add_resource(ProductView, '/products', '/products/<int:id>') api.add_resource(LoginView, '/login') api.add_resource(LogoutView, '/logout') app.register_blueprint(api_bp, subdomain='api') app.register_blueprint(admin_security, subdomain='admin') app.register_blueprint( admin_static, subdomain='admin', url_prefix='/static') app.register_blueprint(admin_user, subdomain='admin', url_prefix='/users') app.register_blueprint( admin_order, subdomain='admin', url_prefix='/orders') app.register_blueprint( admin_product, subdomain='admin', url_prefix='/products') app.register_blueprint( admin_category, subdomain='admin', url_prefix='/categories')
def __init__(self): self.__app = Flask(__name__) self.__api = Api(self.__app) self.__parser = reqparse.RequestParser() self.__stub_to_peer_service = None # SSL ?? ??? ?? context ?? ??? ????. if conf.ENABLE_REST_SSL == 0: self.__ssl_context = None elif conf.ENABLE_REST_SSL == 1: self.__ssl_context = (conf.DEFAULT_SSL_CERT_PATH, conf.DEFAULT_SSL_KEY_PATH) else: self.__ssl_context = ssl.SSLContext(_ssl.PROTOCOL_SSLv23) self.__ssl_context.verify_mode = ssl.CERT_REQUIRED self.__ssl_context.check_hostname = False self.__ssl_context.load_verify_locations(cafile=conf.DEFAULT_SSL_TRUST_CERT_PATH) self.__ssl_context.load_cert_chain(conf.DEFAULT_SSL_CERT_PATH, conf.DEFAULT_SSL_KEY_PATH)
def ApiApp(trustlines): app = Flask(__name__) api_bp = Blueprint('api', __name__, url_prefix='/api/v1') api = Api(api_bp) api.add_resource(NetworkList, '/networks', resource_class_args=[trustlines]) api.add_resource(Network, '/networks/<address:address>', resource_class_args=[trustlines]) api.add_resource(UserList, '/networks/<address:address>/users', resource_class_args=[trustlines]) api.add_resource(User, '/networks/<address:network_address>/users/<address:user_address>', resource_class_args=[trustlines]) api.add_resource(ContactList, '/networks/<address:network_address>/users/<address:user_address>/contacts', resource_class_args=[trustlines]) api.add_resource(TrustlineList, '/networks/<address:network_address>/users/<address:user_address>/trustlines', resource_class_args=[trustlines]) api.add_resource(Trustline, '/networks/<address:network_address>/users/<address:a_address>/trustlines/<address:b_address>', resource_class_args=[trustlines]) api.add_resource(Spendable, '/networks/<address:network_address>/users/<address:a_address>/spendables', resource_class_args=[trustlines]) api.add_resource(SpendableTo, '/networks/<address:network_address>/users/<address:a_address>/spendables/<address:b_address>', resource_class_args=[trustlines]) api.add_resource(TransactionInfos, '/txinfos/<address:address>', resource_class_args=[trustlines]) api.add_resource(Block, '/blocknumber', resource_class_args=[trustlines]) api.add_resource(Relay, '/relay', resource_class_args=[trustlines]) api.add_resource(Balance, '/balance/<address:address>', resource_class_args=[trustlines]) app.url_map.converters['address'] = AddressConverter app.register_blueprint(api_bp) return app
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
def post(self): args = imovel_parser.parse_args() if args['caracteristicas'] == [None]: args['caracteristicas'] = None imovel_id = len(IMOVEIS) + 1 imovel_id = str(imovel_id) IMOVEIS[imovel_id] = { 'proprietario': args['proprietario'], 'caracteristicas': args['caracteristicas'], 'endereco': args['endereco'], 'valor': args['valor'], 'esta_ocupado': args['esta_ocupado'], } return IMOVEIS[imovel_id], 201 ## ## Actually setup the Api resource routing here ##
def app_factory(API_NAME="api"): """Create an app object.""" app = Flask(__name__) CORS(app) app.url_map.strict_slashes = False api = Api(app) api.add_resource(Index, "/"+API_NAME+"/", endpoint="api") api.add_resource(Vocab, "/"+API_NAME+"/vocab", endpoint="vocab") api.add_resource(Contexts, "/"+API_NAME+"/contexts/<string:category>.jsonld", endpoint="contexts") api.add_resource(Entrypoint, "/"+API_NAME+"/contexts/EntryPoint.jsonld", endpoint="main_entrypoint") api.add_resource(ItemCollection, "/"+API_NAME+"/<string:type_>", endpoint="item_collection") api.add_resource(Item, "/"+API_NAME+"/<string:type_>/<int:id_>", endpoint="item") return app
def __init__(self, host, port): self.logger = Logger.Logger('executor') self.loadConfigs() self.host = host self.port = port self.service = Flask('Executor') self.service.config['BUNDLE_ERRORS'] = True CORS(self.service) got_request_exception.connect(logException, self.service) self.api = Api(self.service) self.api.add_resource(Leaves.LeafIndex, '/leaves/') self.api.add_resource(Leaves.LeafRegister, '/leaves/register') self.api.add_resource(Leaves.LeafResource, '/leaves/<int:leafId>') self.api.add_resource(Projects.ProjectIndex, '/projects/') self.api.add_resource(Projects.ProjectResource, '/projects/<int:projectId>') self.api.add_resource(Builds.BuildIndex, '/builds/') self.api.add_resource(Builds.BuildRecentIndex, '/builds/recent/') self.api.add_resource(Builds.BuildResource, '/builds/<int:buildId>') self.api.add_resource(CI.CI, '/ci/<int:projectId>')
def __init__(self, configRoot='.'): self.__configDir = configRoot+'/.leafd/' self.__configFname = self.__configDir+'config.yaml' self.logger = Logger.Logger('LeafService') if not os.path.exists(self.__configDir): os.makedirs(self.__configDir) self.__configure() self.service = Flask('Leaf') self.api = Api(self.service) got_request_exception.connect(logException, self.service) self.api.add_resource(Info.Config, '/config') self.api.add_resource(Info.Status, '/status') self.api.add_resource(Jobs.JobIndex, '/jobs/') self.api.add_resource(Jobs.JobResource, '/jobs/<int:jobId>') t = threading.Thread(name='Leaf service', target=appThread, args=(self.service,Info.configStorage['port'])) t.start() time.sleep(1) self.__register() t.join()
def __init__(self, config): self.config = config self.clouds = [] self.app = Flask(__name__) self.api = swagger.docs(Api(self.app), apiVersion='0.2.0') self.resources = {}
def api_add_resource(): """ The resource has multiple URLs and you can pass multiple URLs to the add_resource() method on the Api object. Each one will be routed to your Resource """ for url_pattern in URLPATTERNS: try: API.add_resource( get_resource(url_pattern.target), url_pattern.url, endpoint=get_endpoint(url_pattern.url)) except StopIteration: LOGGER.error('url resource not found: %s', url_pattern.url)
def post(self): args = parser.parse_args() todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1 todo_id = 'todo%i' % todo_id TODOS[todo_id] = {'task': args['task']} return TODOS[todo_id], 201 ## ## Actually setup the Api resource routing here ##
def m_flask_restful(mocker): return mocker.MagicMock(spec=FlaskRestful)
def _create_app(volume_manager, testing=False): """Factory method to create the Flask app and register all dependencies. Args: volume_manager (VolumeManager): The volume manager to be used withing the API controller testing (bool): Whether or not to set the `TESTING` flag on the newly generated Flask application Returns: Flask: The application with all the needed dependencies bootstrapped """ unhandled_exception_errors = { 'EtcdConnectionFailed': { 'message': "The ETCD cluster is not responding.", 'status': 503, } } config = { 'RESTFUL_JSON': { 'separators': (', ', ': '), 'indent': 2, 'sort_keys': False }, 'TESTING': testing } app = Flask(__name__) app.config.update(**config) api = RestApi(app, errors=unhandled_exception_errors, catch_all_404s=True) Api._register_resources(api) app.volume_manager = volume_manager app.api = api return app
def make_api(app, url_prefix='/'): api = Api(app) api.representation('application/json')(json_representation) api.add_resource(HoudiniNodeshapeConverter, url_prefix) return api
def get(self): rdic = {} for item in tmodel.get_todo_list(): rdic[item[0]] = { "id": item[0], "Name": item[1], "Content": item[2] } return jsonify(rdic) ## ## Actually setup the Api resource routing here ##
def start(host, port, debug): logger.info('Start {host}:{port}'.format(host=host, port=port)) api = Api(app) api.add_resource(AddJob, '/api/add') api.add_resource(JobStatus, '/api/status') api.add_resource(FileUpload, '/api/upload') api.add_resource(ResultData, '/api/list') api.add_resource(ResultDetail, '/api/detail') api.add_resource(Search, '/api/search') # 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')
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.api.add_resource(Shutdown, "/shutdown") @self.app.after_request def add_access_control_header(response): response.headers['Access-Control-Allow-Origin'] = '*' return response
def __init__(self, listenip, port): self.ip = listenip self.port = port self.compute = None self.manage = 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)
def __init__(self): self.__app = Flask(__name__) self.__api = Api(self.__app) self.__parser = reqparse.RequestParser() self.__stub_to_rs_service = None # SSL ?? ??? ?? context ?? ??? ????. if conf.ENABLE_REST_SSL is True: self.__ssl_context = (conf.DEFAULT_SSL_CERT_PATH, conf.DEFAULT_SSL_KEY_PATH) else: self.__ssl_context = None
def create_app(self): """This method creates the flask app. This is required to be implemented by flask_restful. :returns: Flask application instance. """ app = Flask('test') app.config['TESTING'] = True api = flask_restful.Api(app) for url, handler in self.get_routes(): api.add_resource(handler, url) return api.app
def create_app(object_name): """ An flask application factory object_name: the python path of the config object, e.g. oniongate.settings.ProdConfig """ app = Flask(__name__, instance_relative_config=True) app.config.from_object(object_name) try: app.config.from_pyfile("config.py") except FileNotFoundError: pass # Create zone file directory if it doesn't exist zone_directory = app.config.get('zone_dir') or os.path.join(app.instance_path, 'zones') if not os.path.isdir(zone_directory): os.makedirs(zone_directory) app.config["zone_dir"] = zone_directory api_bp = Blueprint('api', __name__) api = Api(api_bp) CORS(app, resources={r"/api/*": {"origins": "*"}}) db.init_app(app) # register our blueprints app.register_blueprint(main_bp) app.register_blueprint(api_bp, url_prefix='/api/v1') api.add_resource(Domains, '/domains', '/domains/<domain_name>') api.add_resource(Records, '/records/<domain_name>', '/records/<domain_name>/<record_id>') api.add_resource(Proxies, '/proxies', '/proxies/<ip_address>') app.jinja_env.filters['naturaltime'] = humanize.naturaltime return app
def create_app(is_hd=True): state.set_model(is_hd) app = Flask(__name__) app.register_blueprint(index) app.config['ERROR_404_HELP'] = False api = Api(app) api.add_resource(SetProgram, '/api/program/<string:program>') api.add_resource(StopProgram, '/api/program') atexit.register(state.stop_program) return app
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 = get_application_config(config) for key, value in app_config: app.config[key.upper()] = int(value) if key.upper() in INT_OPTIONS else value app.config['SENTRY_INCLUDE_PATHS'] = [ 'postgraas_server', ] app.config['SENTRY_RELEASE'] = postgraas_server.__version__ sentry.init_app(app) from raven.handlers.logging import SentryHandler app.logger.addHandler(SentryHandler(client=sentry.client, level=logging.WARN)) 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
def parse_api(): parser = reqparse.RequestParser() parser.add_argument('name', required=True, type=str, help="Api needs name!", location="json") parser.add_argument('file_content', required=True, type=str, help="must not be empty api!", location="json") return parser.parse_args()
def __init__(self): loginfo("Creating RestApi instance.") self.app = Flask("aide", static_url_path="") self.api = Api(self.app, catch_all_404s=True) CORS(self.app) build_resources(self.api)
def create_app(): """Creates the Flask app object.""" app = Flask(__name__) app.config.from_object(AppConfig) api = Api(app) configure_resources(api) configure_extensions(app) return app
def configure(self, payload): if self.level == 'app' or self.level == 'api': self.server = Flask(__name__) if self.level == 'app': for api in self.app.get_apis(): setattr(api, 'server', Blueprint(api.name, __name__)) resource = Api(api.server) for route in api.config.routes: handler = api.get_handler(api, route.handler) resource.add_resource(handler, api.config.main.prefix + route.path) self.server.register_blueprint(api.server)
def add_routes(app): """Add the routes to an app""" for (prefix, routes) in API_SECTIONS: api = Api(app, prefix=prefix) for ((pattern, resource, *args), kwargs) in routes: kwargs.setdefault('strict_slashes', False) api.add_resource(resource, pattern, *args, **kwargs)
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)
def create_app(): _app = Flask(__name__) # used for encrypting cookies for handling sessions _app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b' message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.QUEUE, default=None) if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)): raise RuntimeError('no message queue type specified') message_queue = 'redis://%s' % environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.CACHE_SERVICE, default='') message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test') logger.info('message_queue: %s' % message_queue) _api = Api(_app) _socketio = SocketIO( _app, logger=logger, engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1', async_mode='eventlet', message_queue=message_queue, channel=message_channel) # preferably "emit" should be set during env creation, but the socketio object is not created until after env is environ.env.out_of_scope_emit = _socketio.emit _app.wsgi_app = ProxyFix(_app.wsgi_app) return _app, _api, _socketio
def __init__(self, app, name=None, version=None, media_type=None, **kwargs): super().__init__(app=app, default_mediatype=media_type or self.MEDIA_TYPE, **kwargs) @app.route('/') def main(): return jsonify({ 'name': name or 'Peach Rest Api', 'version': version or '0.0.0', })
def init_app(self, app): api = Api(app)
def create_api(app): api = Api(app, catch_all_404s=True, errors=errors) api.representations['application/xml'] = output_xml got_request_exception.connect(log_exception, app) api.add_resource(Recipes, '/recipes', endpoint='recipes') api.add_resource(Recipes, '/recipes/<int:recipe_id>', endpoint='recipe')
def setup_api(): api = Api(app) api.add_resource(ReadViaImage, ROOT_PATH + '/image') api.add_resource(ReadViaUrl, ROOT_PATH + '/url')
def __init__(self, app): QtCore.QThread.__init__(self) self.app = app self.flask_app = Flask(app.name, template_folder=sibling_path(__file__, 'templates'), ) self.flask_app.route('/')(self.index) self.rest_api = Api(self.flask_app) self.flask_app.config['RESTFUL_JSON'] = dict(indent=4) self.rest_api.add_resource(MicroscopeRestResource, '/api/app', resource_class_kwargs={ 'microscope_app': self.app }) self.rest_api.add_resource(HardwareSettingsListRestResource, '/api/hardware/<string:hw_name>/settings', resource_class_kwargs={ 'microscope_app': self.app }) self.rest_api.add_resource(HardwareSettingsLQRestResource, '/api/hardware/<string:hw_name>/settings/<string:lq_name>', resource_class_kwargs={ 'microscope_app': self.app }) self.rest_api.add_resource(MeasurementSettingsListRestResource, '/api/measurements/<string:measure_name>/settings', resource_class_kwargs={ 'microscope_app': self.app }) self.rest_api.add_resource(MeasurementSettingsLQRestResource, '/api/measurements/<string:measure_name>/settings/<string:lq_name>', resource_class_kwargs={ 'microscope_app': self.app }) for HW in self.app.hardware.values(): #print(HW.web_ui()) self.flask_app.route('/hw/{}'.format(HW.name))(HW.web_ui) for M in self.app.measurements.values(): self.flask_app.route('/measure/{}'.format(M.name))(M.web_ui)
def main(): app = Flask(__name__) api = Api(app) # localhost:5000/ APIRoot.register_root(api) # localhost:5000/api/ #APIRoot.register_root(api, root='/api') app.run()
def __init__(self, app): self.__api = Api(app) # enable basic auth if a password is set password = AppSettings.get_setting(AppSettings.KEY_PASSWORD) if password is not None: app.config['BASIC_AUTH_USERNAME'] = 'opserv' app.config['BASIC_AUTH_PASSWORD'] = password self.__basic_auth = BasicAuth(app)
def __init__(self, host, http_port, ws_port, ws_poll_interval, dring, verbose): self.host = host self.http_port = http_port self.ws_port = ws_port self.ws_poll_interval = ws_poll_interval self.dring = dring self.verbose = verbose # Flask Application self.app = Flask(__name__) self.app.config['SECRET_KEY'] = 't0p_s3cr3t' self.app.config.update(PROPAGATE_EXCEPTIONS=True) # Flask Restuful API self.api = Api( app=self.api_blueprint, prefix=self.API_URL_PREFIX, catch_all_404s=True ) # Cross Origin Resource Sharing is needed to define response headers # to allow HTTP methods from in-browser Javascript because accessing # a different port is considered as accessing a different domain self.api.decorators = [ cors.crossdomain( origin='*', methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], attach_to_all=True, automatic_options=True ) ] self._init_api_resources() self.app.register_blueprint(self.api_blueprint) # Websockets self._init_websockets() self._register_callbacks()
def __init__(self): self.logger = Logger.Logger('DevicePool') self.__detectDevices() self.service = Flask('DevicePool') self.api = Api(self.service) got_request_exception.connect(logException, self.service) self.api.add_resource(Devices.DeviceIndex, '/devices/') self.api.add_resource(Deploy.DeployIndex, '/deploy') self.service.run(host='0.0.0.0', port=7890)
def __init__(self, rest_api, cors_domain_list=None, web_ui=False, eth_rpc_endpoint=None): if rest_api.version != 1: raise ValueError( 'Invalid api version: {}'.format(rest_api.version) ) flask_app = Flask(__name__) if cors_domain_list: CORS(flask_app, origins=cors_domain_list) if eth_rpc_endpoint: if not eth_rpc_endpoint.startswith('http'): eth_rpc_endpoint = 'http://{}'.format(eth_rpc_endpoint) flask_app.config['WEB3_ENDPOINT'] = eth_rpc_endpoint blueprint = create_blueprint() flask_api_context = Api(blueprint, prefix=self._api_prefix) restapi_setup_type_converters( flask_app, {'hexaddress': HexAddressConverter}, ) restapi_setup_urls( flask_api_context, rest_api, URLS_V1, ) self.rest_api = rest_api self.flask_app = flask_app self.blueprint = blueprint self.flask_api_context = flask_api_context self.wsgiserver = None self.flask_app.register_blueprint(self.blueprint) self.flask_app.config['WEBUI_PATH'] = '../ui/web/dist/' if is_frozen(): # Inside frozen pyinstaller image self.flask_app.config['WEBUI_PATH'] = '{}/raiden/ui/web/dist/'.format(sys.prefix) if web_ui: for route in ('/ui/<path:file>', '/ui', '/ui/', '/index.html', '/'): self.flask_app.add_url_rule( route, route, view_func=self._serve_webui, methods=('GET', ), )
def __init__(self, listenip, port, DCnetwork=None): self.ip = listenip self.port = port # connect this DC network to the rest api endpoint (needed for the networking and monitoring api) self.connectDCNetwork(DCnetwork) # setup Flask # find directory of dashboard files dashboard_file = pkg_resources.resource_filename('emuvim.dashboard', "index.html") dashboard_dir = path.dirname(dashboard_file) logging.info("Started emu dashboard: {0}".format(dashboard_dir)) self.app = Flask(__name__, static_folder=dashboard_dir, static_url_path='/dashboard') self.api = Api(self.app) # setup endpoints # compute related actions (start/stop VNFs, get info) self.api.add_resource(Compute, "/restapi/compute/<dc_label>/<compute_name>") self.api.add_resource(ComputeList, "/restapi/compute", "/restapi/compute/<dc_label>") self.api.add_resource(ComputeResources, "/restapi/compute/resources/<dc_label>/<compute_name>") self.api.add_resource(DatacenterStatus, "/restapi/datacenter/<dc_label>") self.api.add_resource(DatacenterList, "/restapi/datacenter") # network related actions (setup chaining between VNFs) self.api.add_resource(NetworkAction, "/restapi/network") self.api.add_resource(NetworkLAN, "/restapi/networkLAN") self.api.add_resource(DrawD3jsgraph, "/restapi/network/d3jsgraph") # monitoring related actions # export a network interface traffic rate counter self.api.add_resource(MonitorInterfaceAction, "/restapi/monitor/interface") # export flow traffic counter, of a manually pre-installed flow entry, specified by its cookie self.api.add_resource(MonitorFlowAction, "/restapi/monitor/flow") # install monitoring of a specific flow on a pre-existing link in the service. # the traffic counters of the newly installed monitor flow are exported self.api.add_resource(MonitorLinkAction, "/restapi/monitor/link") # install skewness monitor of resource usage disribution # the skewness metric is exported self.api.add_resource(MonitorSkewAction, "/restapi/monitor/skewness") # start a terminal window for the specified vnfs self.api.add_resource(MonitorTerminal, "/restapi/monitor/term") logging.debug("Created API endpoint %s(%s:%d)" % (self.__class__.__name__, self.ip, self.port))
def create_app(taskflow_instance, connection_string=None, secret_key=None): app = flask.Flask(__name__) app.config['DEBUG'] = os.getenv('DEBUG', False) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = connection_string or os.getenv('SQL_ALCHEMY_CONNECTION') app.config['SESSION_COOKIE_NAME'] = 'taskflowsession' app.config['SESSION_COOKIE_HTTPONLY'] = True app.config['PERMANENT_SESSION_LIFETIME'] = 43200 app.config['SECRET_KEY'] = secret_key or os.getenv('FLASK_SESSION_SECRET_KEY') db = SQLAlchemy(metadata=metadata, model_class=BaseModel) db.init_app(app) api = Api(app) CORS(app, supports_credentials=True) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): return db.session.query(User).filter(User.id == user_id).first() def apply_attrs(class_def, attrs): for key, value in attrs.items(): setattr(class_def, key, value) return class_def attrs = { 'session': db.session, 'taskflow': taskflow_instance } with app.app_context(): api.add_resource(apply_attrs(resources.LocalSessionResource, attrs), '/v1/session') api.add_resource(apply_attrs(resources.WorkflowListResource, attrs), '/v1/workflows') api.add_resource(apply_attrs(resources.WorkflowResource, attrs), '/v1/workflows/<workflow_name>') api.add_resource(apply_attrs(resources.TaskListResource, attrs), '/v1/tasks') api.add_resource(apply_attrs(resources.TaskResource, attrs), '/v1/tasks/<task_name>') api.add_resource(apply_attrs(resources.WorkflowInstanceListResource, attrs), '/v1/workflow-instances') api.add_resource(apply_attrs(resources.WorkflowInstanceResource, attrs), '/v1/workflow-instances/<int:instance_id>') api.add_resource(apply_attrs(resources.RecurringWorkflowLastestResource, attrs), '/v1/workflow-instances/recurring-latest') api.add_resource(apply_attrs(resources.TaskInstanceListResource, attrs), '/v1/task-instances') api.add_resource(apply_attrs(resources.TaskInstanceResource, attrs), '/v1/task-instances/<int:instance_id>') api.add_resource(apply_attrs(resources.RecurringTaskLastestResource, attrs), '/v1/task-instances/recurring-latest') return app
def get(self): stock_date_range_parser.add_argument('params') args = stock_date_range_parser.parse_args() calcs = json.loads(args['params']) x = get_series(args['symbol'], args['start'], args['end']) #x.run_calculations() cc = [] for calc in calcs: t = calc['type'] p = calc['param'] if t == 'mavg': cc.append(x.calculate_mavg(p['window'])) elif t == 'rsi': cc.append(x.calculate_rsi(p['window'])) elif t == 'macd': cc.append('signal_' + str(p['signal'])) cc.append(x.calculate_macd(**p)) elif t == '': pass #TODO #x.calculate_mom() #x.calculate_rocr() #x.calculate_atr() #x.calculate_mfi() #x.calculate_obv() #x.calculate_cci() #x.calculate_trix() #x.calculate_adx() x.df = x.df.where((pd.notnull(x.df)), None) # cast Nan to Null jret = { 'ohlc' : list(zip(x.df.epoch, x.df['Open'], x.df['High'], x.df['Low'], x.df['Adj_Close'])), 'volume': list(zip(x.df.epoch, x.df['Volume'])), 'columns': cc, 'backtesting': get_backtesting(args['start'], args['end'], x) } for c in cc: jret[c] = list(zip(x.df.epoch, x.df[c])) return jret # # Actually setup the Api resource routing here #
def create_app(): app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) from db import db db.init_app(app) # TODO: upload image api = Api(app) jwt = JWT(app, authenticate, identity) # endpoint '/auth' # users api.add_resource(UserRegister, '/v1/register') api.add_resource(User, '/v1/users/<string:username>') api.add_resource(UserId, '/v1/users/<int:user_id>') # badges api.add_resource(BadgeList, '/v1/users/<int:student_id>/badges') api.add_resource(Badge, '/v1/users/<int:student_id>/badges/<int:badge_id>') # categories api.add_resource(CategoryList, '/v1/categories') api.add_resource(Category, '/v1/categories/<int:category_id>') # courses api.add_resource(CourseList, '/v1/courses') api.add_resource(Course, '/v1/courses/<int:course_id>') api.add_resource(CourseRegister, '/v1/courses/<int:course_id>/users/<int:student_id>/register') # chapters api.add_resource(ChapterList, '/v1/courses/<int:course_id>/chapters') api.add_resource(Chapter, '/v1/courses/<int:course_id>/chapters/<int:chapter_id>') # quizzes api.add_resource(QuizList, '/v1/courses/<int:course_id>/quizzes') api.add_resource(Quiz, '/v1/courses/<int:course_id>/quizzes/<int:quiz_id>') # comments api.add_resource(CommentList, '/v1/courses/<int:course_id>/comments') api.add_resource(Comment, '/v1/courses/<int:course_id>/comments/<int:comment_id>') # ratings api.add_resource(RatingList, '/v1/courses/<int:course_id>/ratings') api.add_resource(Rating, '/v1/courses/<int:course_id>/ratings/<int:rating_id>') # questions api.add_resource(QuestionList, '/v1/quizzes/<int:quiz_id>/questions') api.add_resource(Question, '/v1/quizzes/<int:quiz_id>/questions/<int:question_id>') # answers api.add_resource(AnswerList, '/v1/questions/<int:question_id>/answers') api.add_resource(Answer, '/v1/questions/<int:question_id>/answers/<int:answer_id>') # scores api.add_resource(ScoreList, '/v1/quizzes/<int:quiz_id>/scores') api.add_resource(Score, '/v1/quizzes/<int:quiz_id>/scores/<int:score_id>') # steps api.add_resource(Step, '/v1/users/<int:student_id>/courses/<int:course_id>/steps/<int:step_id>') return app