Пример #1
0
    def __init__(self, atomspace):
        self.atomspace = atomspace

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = swagger.docs(Api(self.app), apiVersion='1.1', api_spec_url='/api/v1.1/spec')

        # Allow Cross Origin Resource Sharing (CORS) so that javascript apps
        # can use this API from other domains, ports and protocols. 
        self.cors = CORS(self.app, resources={r"/api/*": {"origins": "*"}})

        # Create and add each resource
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI
        shell_api = ShellAPI
        scheme_api = SchemeAPI.new(self.atomspace)
        ghost_api = GhostApi.new(self.atomspace)

        self.api.decorators=[cors.crossdomain(origin='*', automatic_options=False)]

        self.api.add_resource(atom_collection_api,
                              '/api/v1.1/atoms',
                              '/api/v1.1/atoms/<int:id>', endpoint='atoms')
        self.api.add_resource(atom_types_api,
                              '/api/v1.1/types',
                              endpoint='types')
        self.api.add_resource(shell_api,
                              '/api/v1.1/shell',
                              endpoint='shell')
        self.api.add_resource(scheme_api,
                              '/api/v1.1/scheme',
                              endpoint='scheme')
        self.api.add_resource(ghost_api, 
                              '/api/v1.1/ghost', 
                              endpoint='ghost')
Пример #2
0
    def __init__(self, atomspace):
        self.atomspace = atomspace

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = swagger.docs(Api(self.app), apiVersion='1.1', api_spec_url='/api/v1.1/spec')

        # Allow Cross Origin Resource Sharing (CORS) so that javascript apps
        # can use this API from other domains, ports and protocols. 
        self.cors = CORS(self.app)

        # Create and add each resource
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI
        shell_api = ShellAPI
        scheme_api = SchemeAPI.new(self.atomspace)

        self.api.add_resource(atom_collection_api,
                              '/api/v1.1/atoms',
                              '/api/v1.1/atoms/<int:id>', endpoint='atoms')
        self.api.add_resource(atom_types_api,
                              '/api/v1.1/types',
                              endpoint='types')
        self.api.add_resource(shell_api,
                              '/api/v1.1/shell',
                              endpoint='shell')
        self.api.add_resource(scheme_api,
                              '/api/v1.1/scheme',
                              endpoint='scheme')
Пример #3
0
def test_docs_simple_instantiate_add_resources(path, endpoint, make_class,
                                               register):

    my_blueprint1 = Blueprint("my_blueprint1", __name__)

    api1 = docs(Api(my_blueprint1), **docs_kwargs)

    class MockResource(Resource):
        def get(self):
            return "OK", 200, {"Access-Control-Allow-Origin": "*"}

    make_class.return_value = MockResource
    endpoint.return_value = MockResource
    path.return_value = "/some/swagger/path"

    api1.add_resource(MockResource, "/some/url")

    # Validate All Mock Calls

    assert register.call_args_list[0][0][0] == api1
    assert register.call_args_list[0][0][2:] == (
        "an api version",
        "1.2",
        "a basepath",
        "a resource path",
        ["application/json", "text/html"],
        "an api spec url",
        "an Api Description Description",
    )
    assert len(register.call_args_list[0][0]) == 9

    path.assert_called_once_with("/some/url")
    assert endpoint.call_args_list[0][0][0] == api1
    assert endpoint.call_args_list[0][0][2] == "/some/url"
    make_class.assert_called_once_with(MockResource)
Пример #4
0
def create_app(config_object='webfront_service.settings.__init__'):
    """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.

    :param config_object: The configuration object to use.
    """
    app = Flask(__name__.split('.')[0])
    app.config.from_object(config_object)

    global api
    api = swagger.docs(
        Api(app),
        apiVersion="0.1",
        basePath="http://localhost:5000",
        resourcePath="/",
        produces=["application/json", "text/html"],
        api_spec_url="/api/spec",
        description="A Basic API",
    )
    print("swagger")

    register_halo(app)
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)
    register_shellcontext(app)
    register_commands(app)
    register_urls(app)
    register_monitor(app)
    return app
Пример #5
0
def main(mongoHost, mongoPort, serverHost, serverPort):
    """
    Serve TV program episode and schedule information in REST style
    """

    # Connect to MongoDB and create a DB instance
    mongoClient = pymongo.MongoClient(host=mongoHost, port=mongoPort)
    db = ScheduleDB(mongoClient)

    # Set up Flask app with Swagger document
    app = Flask(__name__)
    api = swagger.docs(
        Api(app),
        basePath="http://{}:{}".format(serverHost, serverPort)
    )

    # Redirect / to API document
    @app.route("/")
    def index():
        return redirect("/api/spec.html")

    # Register API methods
    api.add_resource(ScheduleSearch.make(db), "/schedule/search")
    api.add_resource(ScheduleList.make(db), "/schedule/list")
    api.add_resource(CelebritiesList.make(db), "/celebrities/list")

    # Run the app
    app.run(host=serverHost, port=serverPort)
Пример #6
0
def create_production_app(config_file):
    app = Flask("RestAPI Server")
    _load_config(app, config_file)
    db.init_app(app)
    app.app_context().push()
    api = swagger.docs(Api(app), apiVersion='1.0', api_spec_url='/api/spec')
    return app, api
Пример #7
0
def initialize_api(app):
    """Initialize API and Add resoruces/routing
    """
    from resources import (
        ProjectResource, ProjectListResource,
        ProjectProgressResource, ProjectProgressListResource)

    errors = {
      'NegativeProgressError': {
          'message': 'Progress can only be positive.',
          'status': 400,
      }
    }

    api = swagger.docs(Api(app, errors=errors), apiVersion='0.1')

    api.add_resource(ProjectListResource, '/api/projects')
    api.add_resource(ProjectResource, '/api/projects/<int:project_id>')
    api.add_resource(
      ProjectProgressListResource, '/api/projects/<int:project_id>/progress')
    api.add_resource(
        ProjectProgressResource,
        '/api/projects/<int:project_id>/progress/<int:project_progress_id>')

    return api
Пример #8
0
 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 = {}
Пример #9
0
    def __init__(self):
        self.app = Flask(__name__)
        custom_errors = {
            'JsonInvalidError': {
                'status': 500,
                'message': 'JSON format not valid'
            },
            'JsonRequiredError': {
                'status': 400,
                'message': 'JSON input required'
            }
        }
        self.api = swagger.docs(Api(self.app, errors=custom_errors),
                                apiVersion=API_VERSION_NUMBER)

        self.api.add_resource(PingEndpoint, '/ping', endpoint='ping')
        self.api.add_resource(UserEndpoint, '/user', endpoint='user')
        self.api.add_resource(ChallengeEndpoint,
                              '/challenge',
                              endpoint='challenge')
        self.api.add_resource(TwilioEndpointInstance,
                              '/api/twilio/image_recognition',
                              endpoint='twilio_image_recognition')
        self.api.add_resource(IOSEndpoint,
                              '/api/ios/image_recognition',
                              endpoint='ios_image_recognition')
Пример #10
0
def setup_resources(api):
    api = swagger.docs(api,
                       apiVersion='0.1',
                       basePath='http://localhost:8100')
    api.add_resource(Blueprints,
                     '/blueprints')
    api.add_resource(BlueprintsId,
                     '/blueprints/<string:blueprint_id>')
    api.add_resource(BlueprintsIdArchive,
                     '/blueprints/<string:blueprint_id>/archive')
    api.add_resource(ExecutionsId,
                     '/executions/<string:execution_id>')
    api.add_resource(Deployments,
                     '/deployments')
    api.add_resource(DeploymentsId,
                     '/deployments/<string:deployment_id>')
    api.add_resource(DeploymentsIdExecutions,
                     '/deployments/<string:deployment_id>/executions')
    api.add_resource(Nodes,
                     '/nodes')
    api.add_resource(NodeInstances,
                     '/node-instances')
    api.add_resource(NodeInstancesId,
                     '/node-instances/<string:node_instance_id>')
    api.add_resource(Events, '/events')
    api.add_resource(Search, '/search')
    api.add_resource(Status, '/status')
    api.add_resource(ProviderContext, '/provider/context')
    api.add_resource(Version, '/version')
Пример #11
0
    def __init__(self, atomspace):
        self.atomspace = atomspace

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = swagger.docs(Api(self.app),
                                apiVersion='1.1',
                                api_spec_url='/api/v1.1/spec')

        # Create and add each resource
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI
        shell_api = ShellAPI
        scheme_api = SchemeAPI.new(self.atomspace)

        self.api.add_resource(atom_collection_api,
                              '/api/v1.1/atoms',
                              '/api/v1.1/atoms/<int:id>',
                              endpoint='atoms')
        self.api.add_resource(atom_types_api,
                              '/api/v1.1/types',
                              endpoint='types')
        self.api.add_resource(shell_api, '/api/v1.1/shell', endpoint='shell')
        self.api.add_resource(scheme_api,
                              '/api/v1.1/scheme',
                              endpoint='scheme')
Пример #12
0
def create_app():
    app = Flask('vk_publisher')
    api_bp = Blueprint('vk_api', __name__)
    ui_bp = Blueprint('vk_ui',
                      __name__,
                      static_folder='../static',
                      static_url_path='')
    ui_route = Api(ui_bp)
    api = swagger.docs(Api(api_bp), apiVersion='0.1', description='TramAPI')

    # Add api resources here
    api.add_resource(VKOAuthResource, '/verify')
    api.add_resource(VKLogOutResource, '/logout')
    api.add_resource(RulesResource, '/rules')
    api.add_resource(PostsResource, '/posts')

    # Add ui resources here
    ui_route.add_resource(VKLogInResource, '/', endpoint='base')
    ui_route.add_resource(HomePageResource, '/home', endpoint='home')

    # Smoke test resource
    api.add_resource(SmokeResource, '/smoke')

    # Register blueprints
    app.register_blueprint(api_bp, url_prefix='/vk_publisher/v1')
    app.register_blueprint(ui_bp)
    return app
Пример #13
0
    def __init__(self, atomspace):
        self.atomspace = atomspace

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = swagger.docs(Api(self.app), apiVersion='1.1', api_spec_url='/api/v1.1/spec')

        # Create and add each resource
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI
        shell_api = ShellAPI
        scheme_api = SchemeAPI.new(self.atomspace)

        self.api.add_resource(atom_collection_api,
                              '/api/v1.1/atoms',
                              '/api/v1.1/atoms/<int:id>', endpoint='atoms')
        self.api.add_resource(atom_types_api,
                              '/api/v1.1/types',
                              endpoint='types')
        self.api.add_resource(shell_api,
                              '/api/v1.1/shell',
                              endpoint='shell')
        self.api.add_resource(scheme_api,
                              '/api/v1.1/scheme',
                              endpoint='scheme')
Пример #14
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ['APP_SETTINGS'])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    api = swagger.docs(Api(app), apiVersion='0.1')
    db.init_app(app)
    set_views(api)
    return app
Пример #15
0
def create_app():
    app = Flask(__name__)

    api = swagger.docs(Api(app), apiVersion='0.1')
    app_endpoints(api)

    FlaskInjector(app=app, modules=[bind_modules])

    return app
Пример #16
0
def test_docs_simple_instantiate():

    app = Flask(__name__)
    app.config["basePath"] = "/abc/123"
    my_blueprint1 = Blueprint("my_blueprint1", __name__)

    api1 = docs(Api(my_blueprint1), **docs_kwargs)

    assert api1.add_resource.__name__ == "add_resource"
    assert isinstance(api1.add_resource, types.FunctionType)
Пример #17
0
def get_app():
    app = Flask(__name__)
    #api = Api(app)
    api = swagger.docs(Api(app), apiVersion='0.1')
    api.add_resource(JobsList, '/jobs')
    api.add_resource(Job, '/jobs/<string:job_id>',)
    api.add_resource(JobController, '/jobs/<string:job_id>/<string:action>')
    api.add_resource(JobArtifacts, '/jobs/<string:job_id>/artifacts/<string:artifact_name>')

    return app,api
Пример #18
0
def create_app(model_params, app_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    app = Flask(__name__)
    api = swagger.docs(Api(app), apiVersion='0.1')
    # build model
    disambiguator = model.build_mmdisambiguator(**model_params)
    parser = reqparse.RequestParser()
    parser.add_argument('query')

    class CategorizeMouse(Resource):
        "Find user query, determine if it is valid and tell model to make predicition. Return response with prediction"

        @swagger.operation(
            responseClass='GET',
            nickname='get',
            parameters=[{
                "name": "query",
                "description":
                "Sentence containing word mouse to perform prediction upon.",
                "required": True,
                "allowMultiple": False,
                "dataType": 'string',
                'paramType': 'query'
            }])
        def get(self):
            # use parser and find the user's query
            args = parser.parse_args()
            user_query = args['query']
            self._abort_if_invalid_query(user_query)

            prediction_results = disambiguator.predict(user_query,
                                                       format='text',
                                                       source='text')
            prediction, prediction_probability = prediction_results[:,
                                                                    0], prediction_results[:,
                                                                                           1]
            output = {'prediction': prediction[0]}

            return output

        def _abort_if_invalid_query(self, query):
            """Abort if the user query does not contain word 'mouse'"""
            if 'mouse' not in query.lower():
                abort(404,
                      message=
                      "INVALID QUERY: Query {} does not contain word 'mouse'".
                      format(query))

    # Setup the Api resource routing here
    # Route the URL to the resource
    api.add_resource(CategorizeMouse, '/predict')
    return app
Пример #19
0
def create_api():
    app = create_app()
    api = Api(app)
    api = swagger.docs(api,
                       apiVersion='1.0',
                       basePath=settings.SWAGGER_BASE_PATH,
                       resourcePath='/',
                       produces=['text/html'],
                       api_spec_url='/api/doc',
                       description='安装包系统API文档')
    return api
Пример #20
0
def create_app(config_name, config_path=None):
    app = Flask(__name__)
    # 读取配置文件
    if not config_path:
        pwd = os.getcwd()
        config_path = os.path.join(pwd, 'config/config.yaml')
    if not config_name:
        config_name = 'PRODUCTION'

    # 读取配置文件
    conf = read_yaml(config_name, config_path)
    app.config.update(conf)

    # 更新Celery配置信息
    celery_conf = "redis://{}:{}/{}".format(app.config['REDIS_HOST'], app.config['REDIS_PORT'], app.config['REDIS_DB'])
    celery_app.conf.update({"broker_url": celery_conf, "result_backend": celery_conf})

    # 注册接口
    register_api(app=app, routers=router)

    # swagger
    api = swagger.docs(Api(app), description='swagger_test', api_spec_url="/show")
    register_api(app=app, routers=[AddArticle], api=api)

    # 返回json格式转换
    app.json_encoder = JSONEncoder

    # 注册数据库连接
    db.app = app
    db.init_app(app)

    # 启动定时任务
    if app.config.get("SCHEDULER_OPEN"):
        scheduler_init(app)

    # 日志文件目录
    if not os.path.exists(app.config['LOGGING_PATH']):
        os.mkdir(app.config['LOGGING_PATH'])

    # 报表文件目录
    if not os.path.exists(app.config['REPORT_PATH']):
        os.mkdir(app.config['REPORT_PATH'])

    # 日志设置
    with open(app.config['LOGGING_CONFIG_PATH'], 'r', encoding='utf-8') as f:
        dict_conf = yaml.safe_load(f.read())
    logging.config.dictConfig(dict_conf)

    # 读取msg配置
    with open(app.config['RESPONSE_MESSAGE'], 'r', encoding='utf-8') as f:
        msg = yaml.safe_load(f.read())
        app.config.update(msg)

    return app
Пример #21
0
    def run(self):
        self.app = Flask(__name__)
        self.api = swagger.docs(
            Api(self.app, errors=errors),
            apiVersion='0.1',
            api_spec_url='/api/rogue-ng',
            description='Rogue-NG, the evilest of evil hotspots')

        self.add_resources()

        self.app.run(debug=True, use_debugger=False, host="0.0.0.0")
Пример #22
0
def create_app(config=DefaultConfig):

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(config)
    # app.config.from_pyfile(config)

    db.init_app(app)
    app.db = db  # so we can call current_app.db from any resource

    migrate.init_app(app, db)

    # api = Api(app)

    @app.cli.command()
    def populate_db():
        """ Initialize the database. """
        populate_database()
        click.echo('Successfully Populated DB')

    @app.cli.command()
    def clear_db():
        """ Clear the database. """
        clear_database()
        click.echo('Successfully Cleared DB')

    # Swagger flask restful API:
    # https://github.com/rantav/flask-restful-swagger
    api = swagger.docs(Api(app),
                       apiVersion='1.0',
                       api_spec_url='/api/api_documentation',
                       swaggerVersion='3.0',
                       description='API')

    from flask_restful import reqparse, Resource

    class StatusResource(Resource):
        def get(self):
            """ Check API Running """
            return {'status': 'OK', 'message': 'Connected to API'}, 200

    api.add_resource(StatusResource, '/api/status')

    from .resources.users import Login
    api.add_resource(Login, '/api/login')

    from .resources.users import Register
    api.add_resource(Register, '/api/register')

    from .resources.bonds import BondsResource
    api.add_resource(BondsResource, '/api/bonds')

    return app
Пример #23
0
def add_api_support(flask_app):
    api = Api(flask_app)
    api = swagger.docs(api,
                       apiVersion="0.1",
                       produces=["application/json", "text/html"],
                       api_spec_url='/api/spec',
                       description='A Sample for API list')

    add_restapi_endpoints(api)

    logging.debug("Added rest api entries")

    return flask_app
Пример #24
0
def main():
    app = Flask(__name__)
    anagramophone_blueprint = Blueprint('anagramophone', __name__)
    api = swagger.docs(Api(app), apiVersion='0.1',
                       basePath='http://localhost:9009',
                       resourcePath='/',
                       produces=["application/json", "text/html"],
                       api_spec_url='/api/spec',
                       description='Anagramophone API Description')
    app.register_blueprint(anagramophone_blueprint, url_prefix='/api')
    api.add_resource(FetchAPI, '/fetch/<string:UUID>')
    api.add_resource(HealthyAPI, '/healthy', endpoint='healthy')
    api.add_resource(LoadAPI, '/load', endpoint='load')
    api.add_resource(SolveAPI, '/solve/<string:string>')
    app.run(host=HOST_NAME, port=PORT_NUMBER, debug=True)
Пример #25
0
def create_app():
    """创建App"""
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = MySQL_URI  # 定义URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 是否开启跟踪
    db.init_app(app)
    CORS(app)  # 跨域支持
    api_bp = Blueprint('api', __name__)
    api = swagger.docs(Api(api_bp),
                       apiVersion='0.1',
                       resourcePath='/',
                       description='EMDP_API',
                       api_spec_url='/swagger')  # swagger支持
    bind_resources(api)
    app.register_blueprint(api_bp, url_prefix='/api')
    return app
Пример #26
0
    def __init__(self,db, testing=False):
        app = Flask(__name__)
        app.url_map.strict_slashes = False
        api = swagger.docs(Api(app), apiVersion='0.1')
        # app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING')
        # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        
        app.config['MONGODB_SETTINGS'] = { 
            'host': os.environ.get('DB_CONNECTION_STRING')
        }
        db.init_app(app)
        # MIGRATE = Migrate(app, db)
        # db.init_app(app)
        # CORS(app)

        self.app = app
        self.api = api
Пример #27
0
    def __init__(self):
        self.app = Flask(__name__)
        custom_errors = {
            'JsonInvalidError': {
                'status': 500,
                'message': 'JSON format not valid'
            },
            'JsonRequiredError': {
                'status': 400,
                'message': 'JSON input required'
            }
        }
        self.api = swagger.docs(Api(self.app, errors=custom_errors),
                                apiVersion=API_VERSION_NUMBER)

        self.api.add_resource(DummyEndpoint, '/dummy', endpoint='dummy')
        self.api.add_resource(HelloEndpoint, '/hello', endpoint='hello')
Пример #28
0
def main():
    app = flask.Flask(__name__)
    api = swagger.docs(restful.Api(app), apiVersion='0.2',
                       basePath='http://%s:%d' % (HOST_NAME, PORT_NUMBER),
                       resourcePath='/',
                       produces=["application/json", "text/html"],
                       api_spec_url='/api/spec',
                       description='Chorus Webservice API Description')
    api.add_resource(FlaskBuild,            '/build',           endpoint='build')
    api.add_resource(FlaskBusy,             '/busy',            endpoint='busy')
    api.add_resource(FlaskDetails,          '/details',         endpoint='details')
    api.add_resource(FlaskHealthy,          '/healthy',         endpoint='healthy')
    api.add_resource(FlaskLastContainer,    '/lastcontainer',   endpoint='lastcontainer')
    api.add_resource(FlaskLastDockerFile,   '/lastdf',          endpoint='lastdf')
    api.add_resource(FlaskStop,             '/stop',            endpoint='stop')
    api.add_resource(FlaskSuccessful,       '/success',         endpoint='success')
    api.add_resource(FlaskUptime,           '/uptime',          endpoint='uptime')
    app.run(host=HOST_NAME, port=PORT_NUMBER, debug=True)
Пример #29
0
def create_app(config_cls: str = 'ProductionConfig'):
    app = Flask(__name__)
    app.config.from_object(f'config.{config_cls}')

    app.register_error_handler(400, handle_bad_request)
    app.register_error_handler(404, handle_not_found)
    app.register_error_handler(500, handle_internal_error)

    db.init_app(app)
    migrate = Migrate()
    migrate.init_app(app, db)

    api = Api(app)
    api = swagger.docs(api, apiVersion='0.1')
    api.add_resource(ProductListResource, '/products/')
    api.add_resource(ProductResource, '/products/<int:product_id>/')

    return app
Пример #30
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'True'
    app.config['DATABASE_FILE'] = 'i2v.sqlite'
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
    app.config['SECRET_KEY'] = os.getenv(
        'ILLUSTRATION2VEC_SECRET_KEY') or os.urandom(24)
    # Create directory for file fields to use
    try:
        os.mkdir(models.file_path)
        app.logger.debug('File path created')
    except OSError:
        pass
    # app and db
    models.db.init_app(app)
    app.app_context().push()
    models.db.create_all()
    # other setup
    # api
    api = swagger.docs(Api(app), apiVersion='0.1')
    api.add_resource(resources.Checksum, '/api/checksum/<int:c_id>')
    api.add_resource(resources.ChecksumTag,
                     '/api/checksum/<int:c_id>/tag/<int:t_id>')
    api.add_resource(resources.ChecksumInvalidTag,
                     '/api/checksum/<int:c_id>/invalid_tag/<int:t_id>')
    api.add_resource(resources.ChecksumTagList, '/api/checksum/<int:c_id>/tag')

    # admin
    admin = Admin(app,
                  name='Illustration2Vec',
                  template_mode='bootstrap3',
                  index_view=views.HomeView(url='/'))
    admin.add_view(views.ImageView(models.Image, models.db.session))
    admin.add_view(views.ChecksumView(models.Checksum, models.db.session))
    admin.add_view(
        views.TagEstimationView(models.TagEstimation, models.db.session))
    app.add_url_rule('/file/<filename>',
                     'file',
                     view_func=lambda filename: send_from_directory(
                         models.file_path, filename))
    app.logger.debug('file path: {}'.format(models.file_path))
    return app
Пример #31
0
    def __init__(self, config):
        self.blueprint = Blueprint('hpcpm-api', __name__)
        api = swagger.docs(Api(self.blueprint), apiVersion='0.1', basePath=config['base_url'], api_spec_url='/help')

        api.add_resource(Status, '/status')
        api.add_resource(ComputationNode, '/nodes/computation_node/<string:name>')
        api.add_resource(PowerLimit, '/nodes/computation_node/<string:name>/<string:device_id>/power_limit')
        api.add_resource(PowerLimitConstraints,
                         '/nodes/computation_node/<string:name>/<string:device_id>/power_limit_constraints')
        api.add_resource(PowerUsage, '/nodes/computation_node/<string:name>/<string:device_id>/power_usage')
        api.add_resource(AllComputationNodes, '/nodes/computation_nodes')
        api.add_resource(StatisticsInterval,
                         '/nodes/computation_node/<string:name>/<string:device_id>/statistics_interval')
        api.add_resource(StatisticsData,
                         '/nodes/computation_node/<string:name>/<string:device_id>/statistics_data/<string:date_time>')
        api.add_resource(StatisticsDataWithInterval,
                         '/nodes/computation_node/<string:name>/<string:device_id>/statistics_data')
        api.add_resource(RuleTypes, '/rule_types')
        api.add_resource(Rule, '/nodes/computation_node/<string:name>/<string:device_id>/rule')
def create_app(app_name, resources: List[APIResource]) -> Flask:
    """ Helper routine to create a rest API out of
        a flask-resultful Resource class
    """
    app = Flask(app_name)
    CORS(app)
    # Create Swagger Wrapper
    # Note:
    #  To debug the API in swagger:
    #     docker run -d -p 1080:8080 swaggerapi/swagger-ui:v2.2.9
    #     go to: http://localhost:1080/
    #     put in: http://127.0.0.1:5000/api/spec.json
    api = swagger.docs(Api(app), apiVersion='0.1')

    for res in resources:
        api.add_resource(res.api_class,
                         res.path,
                         resource_class_kwargs={'svc': res.service_instance})

    return app
Пример #33
0
    def __init__(self):
        self.app = Flask(__name__)
        custom_errors = {
            "JsonInvalidError": {
                "status": 500,
                "message": "JSON format not valid"
            },
            "JsonRequiredError": {
                "status": 400,
                "message": "JSON input required"
            },
        }
        self.api = swagger.docs(Api(self.app, errors=custom_errors),
                                apiVersion=API_VERSION_NUMBER)

        self.api.add_resource(DummyEndpoint, "/dummy", endpoint="dummy")
        self.api.add_resource(HelloEndpoint, "/hello", endpoint="hello")
        self.api.add_resource(GetIssueEndpoint,
                              "/issue/<issue_id>",
                              endpoint="issue/<issue_id>")
Пример #34
0
def setup_resources(api):
    api = swagger.docs(api, apiVersion='0.1', basePath='http://localhost:8100')
    api.add_resource(Blueprints, '/blueprints')
    api.add_resource(BlueprintsId, '/blueprints/<string:blueprint_id>')
    api.add_resource(BlueprintsIdArchive,
                     '/blueprints/<string:blueprint_id>/archive')
    api.add_resource(Executions, '/executions')
    api.add_resource(ExecutionsId, '/executions/<string:execution_id>')
    api.add_resource(Deployments, '/deployments')
    api.add_resource(DeploymentsId, '/deployments/<string:deployment_id>')
    api.add_resource(DeploymentsIdOutputs,
                     '/deployments/<string:deployment_id>/outputs')
    api.add_resource(Nodes, '/nodes')
    api.add_resource(NodeInstances, '/node-instances')
    api.add_resource(NodeInstancesId,
                     '/node-instances/<string:node_instance_id>')
    api.add_resource(Events, '/events')
    api.add_resource(Search, '/search')
    api.add_resource(Status, '/status')
    api.add_resource(ProviderContext, '/provider/context')
    api.add_resource(Version, '/version')
Пример #35
0
def setup_resources(api):
    api = swagger.docs(api,
                       apiVersion='0.1')
    api.add_resource(blueprints.Blueprints, '/blueprints')
    api.add_resource(blueprints.BlueprintsId,
                     '/blueprints/<string:blueprint_id>')
    api.add_resource(blueprints.BlueprintArchive,
                     '/blueprints/<string:blueprint_id>/archive')
    api.add_resource(deployments.Deployments, '/deployments')
    api.add_resource(deployments.DeploymentsId,
                     '/deployments/<string:deployment_id>')
    api.add_resource(deployments.DeploymentOutputs,
                     '/deployments/<string:deployment_id>/outputs')
    api.add_resource(deployments.DeploymentsUpdates, '/deployment-updates')
    api.add_resource(executions.Executions, '/executions')
    api.add_resource(executions.ExecutionsId,
                     '/executions/<string:execution_id>')
    api.add_resource(events.Events, '/events')
    api.add_resource(status.Status, '/status')
    api.add_resource(login.Login, '/login')

    # admin part, you must have rights for do operation from this section
    # look to rights table, partial copy of manage section
    api.add_resource(endpoints.Endpoints, '/endpoints')
    api.add_resource(endpoints.EndpointsId, '/endpoints/<string:id>/')
    api.add_resource(tenants.Tenants, '/tenants')
    api.add_resource(tenants.TenantsId, '/tenants/<string:id>')
    api.add_resource(tenantlimits.Limits, '/limits')
    api.add_resource(tenantlimits.LimitsId, '/limits/<string:id>')

    # walle admin part, will check walle auth
    api.add_resource(plugins.ApprovedPlugins, '/manage/approved_plugins')
    api.add_resource(plugins.ApprovedPluginsFromFile,
                     '/manage/approved_plugins/from_file')
    api.add_resource(plugins.ApprovedPluginsId,
                     '/manage/approved_plugins/<string:name>')
    api.add_resource(service.Maintenance, '/maintenance')
    api.add_resource(nodes.Nodes, '/nodes')
    api.add_resource(nodes.NodeInstances, '/node-instances')
Пример #36
0
def create_app(for_testing=False):
    app = Flask(__name__)
    app.config.from_object(Config)
    if for_testing:
        app.config['TESTING'] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
    else:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///production.db"
    app.app_context().push()
    CORS(app)
    api = swagger.docs(Api(app), apiVersion="0.1")

    db.init_app(app)
    try:
        db.session.remove()
        db.drop_all(app=app)
    except:
        pass
    finally:
        db.create_all(app=app)
    initialize_routes(api)
    return app
Пример #37
0
def create_app():
    """创建App"""
    app = Flask(__name__)
    app.config.from_object(DevConfig)  # 初始化配置项

    jwt = JWTManager(app)

    @jwt.expired_token_loader
    def my_expired_token_callback():
        return jsonify({
            'status': 401,
            'sub_status': 42,
            'msg': 'The token has expired'
        }), 401

    @jwt.user_claims_loader
    def add_claims_to_access_token(user):
        return user.usertype

    @jwt.user_identity_loader
    def user_identity_lookup(user):
        data = [user.userid, user.username]
        return data

    db.init_app(app)  # 初始化MYSQL数据库
    mongo.init_app(app)  # 初始化MONGODB数据库
    CORS(app)  # 跨域支持
    api_bp = Blueprint('api', __name__)
    api = swagger.docs(Api(api_bp),
                       apiVersion='0.1',
                       resourcePath='/',
                       description='EMDP_API',
                       api_spec_url='/swagger')  # swagger支持
    bind_resources(api)  # restful 的逻辑
    app.register_blueprint(api_bp, url_prefix='/api')  # 蓝图注册

    bind_views(app)
    return app
Пример #38
0
    def create_app(self):
        self.app = Flask(__name__)
        CORS(self.app)

        custom_errors = {
            'SentenceInvalidError': {
                'status': 500,
                'message': 'Sentence format not valid'
            },
            'SentenceRequiredError': {
                'status': 400,
                'message': 'Sentence not provided'
            }
        }

        self.api = swagger.docs(Api(self.app, errors=custom_errors),
                                apiVersion=API_VERSION_NUMBER)

        self.api.add_resource(MorphologicalAnalyzeEndpoint,
                              '/analyze',
                              endpoint='analyze')

        return self.app
Пример #39
0
def create_app(register_blueprints=True):
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object('app.default_config')
    # app.config.from_pyfile('application.cfg.py')

    app.config['SQLALCHEMY_DATABASE_URI'] = \
        "{db_prefix}://{user}:{passwd}@{server}/{db}".format(
        db_prefix=app.config['SQLALCHEMY_DB_PREFIX'],
        user=app.config['POSTGRES_USER'],
        passwd=app.config['POSTGRES_PASSWORD'],
        server=app.config['DB_SERVER'],
        db=app.config['POSTGRES_DB'])
    db.init_app(app)

    # so we can call current_app.db from any resource
    app.db = db

    # api = Api(app)

    # Swagger flask restful API:
    # https://github.com/rantav/flask-restful-swagger
    api = swagger.docs(Api(app),
                       apiVersion='1.0',
                       api_spec_url='/api/api_documentation',
                       swaggerVersion='3.0',
                       description='Cloud API')

    from .resources.gifts import GiftsResource
    from .resources.gifts import PutRemoveGiftsResource
    api.add_resource(GiftsResource, '/api/gifts')
    api.add_resource(PutRemoveGiftsResource, '/api/gifts/<gift_id>')

    from .resources.gifts import GiftsReportResource
    api.add_resource(GiftsReportResource, '/api/gift-report')

    return app
Пример #40
0
    def __init__(self):
        self.app = Flask(__name__)

        custom_errors = {
            'JsonInvalidError': {
                'status': 500,
                'message': 'JSON format not valid'
            },
            'JsonRequiredError': {
                'status': 400,
                'message': 'JSON input required'
            },
            'PipelineError': {
                'status': 500,
                'message': 'Pipeline processing error'
            },
        }

        self.api = swagger.docs(
            Api(self.app, errors=custom_errors),
            api_spec_url='/help',
            description='Auto generated API docs for rigel-server',
            apiVersion=API_VERSION_NUMBER)

        self.api.add_resource(PredictEndpoint,
                              '/predict',
                              endpoint='predict',
                              strict_slashes=False)
        self.api.add_resource(ModelEndpoint,
                              '/model',
                              endpoint='model',
                              strict_slashes=False)
        self.api.add_resource(LicenseEndpoint,
                              '/license',
                              endpoint='license',
                              strict_slashes=False)
  PYTHONPATH=. python examples/inheritance.py

"""
from flask import Flask
from flask.ext.restful import Api, Resource
from flask_restful_swagger import swagger

app = Flask(__name__, static_folder="../static")

###################################
# This is important:
api = swagger.docs(
    Api(app),
    apiVersion="0.1",
    basePath="http://localhost:5000",
    resourcePath="/",
    produces=["application/json", "text/html"],
    api_spec_url="/api/spec",
    description="Inheritance demonstration",
)
###################################


class Base(Resource):
    def get(self):
        pass

    def post(self):
        pass

    def delete(self):
Пример #42
0
from flask_restful_swagger import swagger

app = Flask(__name__)

from .query import Query
from .register import Register, Manage
from .api import MyApi
from .config import Config
from .namespaces import NamespacesResource
from .services import ServicesResource
from .service import ServiceResource, ServiceQueryResource


api = swagger.docs(MyApi(app),
                   apiVersion='0.1',
                   basePath=Config.get('server', 'url'),
                   resourcePath='/',
                   produces=["application/json", "text/html"],
                   api_spec_url='/api/spec')

api.add_resource(NamespacesResource, '/adama')
api.add_resource(ServicesResource, '/adama/<string:namespace>/services')
api.add_resource(
    ServiceResource, '/adama/<string:namespace>/<string:service>',
    endpoint='service')
api.add_resource(
    ServiceQueryResource, '/adama/<string:namespace>/<string:service>/search',
    endpoint='search')

# api.add_resource(
#     ServiceResource, '/adama/<string:namespace>/<string:service>/search')
Пример #43
0

from flask import Flask, redirect, Blueprint
from flask.ext.restful import reqparse, abort, Api, Resource, fields,\
    marshal_with
from flask_restful_swagger import swagger

app = Flask(__name__, static_folder='../static')
my_blueprint1 = Blueprint('my_blueprint1', __name__)
my_blueprint2 = Blueprint('my_blueprint2', __name__)

###################################
# This is important:
api1 = swagger.docs(Api(my_blueprint1), apiVersion='0.1',
                   basePath='http://localhost:5000',
                   resourcePath='/',
                   produces=["application/json", "text/html"],
                   api_spec_url='/api/spec',
                   description='Blueprint1 Description')
api2 = swagger.docs(Api(my_blueprint2), apiVersion='0.1',
                   basePath='http://localhost:5000',
                   resourcePath='/',
                   produces=["application/json", "text/html"],
                   api_spec_url='/api/spec',
                   description='Blueprint2 Description')
###################################

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}
Пример #44
0
db.init_app(app)

# Configuración de migraciones de la base de datos.
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

# Manejo global de solicitudes CORS
cors = CORS(app)

# Importación del manejo de autenticación HTTP.
from .mod_shared.models import auth

# Crea la API y activa el soporte de Swagger para la misma.
api = swagger.docs(Api(app))

api.add_resource(AnalysisAnalysisFileList, '/analysis/<int:analysis_id>/files')
api.add_resource(AnalysisAnalysisCommentList, '/analysis/<int:analysis_id>/comments')
api.add_resource(AnalysisCommentView, '/analysis_comments/<int:analysis_comment_id>')
api.add_resource(AnalysisView, '/analysis/<int:analysis_id>')
api.add_resource(AnalysisList, '/analysis')
api.add_resource(AnalysisFileDownload, '/analysis_files/<int:id>/download')
api.add_resource(AnalysisFileThumbnail, '/analysis_files/<int:analysis_file_id>/thumbnail')
api.add_resource(AnalysisFileThumbnailByQuery, '/analysis_files/<int:analysis_file_id>/thumbnail_by_query')
api.add_resource(AnalysisFileView, '/analysis_files/<int:id>')
api.add_resource(AnalysisFileList, '/analysis_files')
api.add_resource(AnalysisGroupPermissionList, '/analysis/<int:analysis_id>/group_permissions')
api.add_resource(AnalysisMeasurementList, '/analysis/<int:analysis_id>/measurements')
api.add_resource(AnalysisPermissionList, '/analysis/<int:analysis_id>/permissions')
api.add_resource(GenderView, '/genders/<int:id>')
Пример #45
0
from flask import Flask, redirect
from flask.ext.restful import reqparse, abort, Api, Resource, fields,marshal_with
from flask_restful_swagger import swagger
import csv
import json
from google.cloud import datastore

app = Flask(__name__, static_folder='../static')

api = swagger.docs(Api(app), apiVersion='0.1',
                   basePath='http://localhost:5000',
                   resourcePath='/',
                   produces=["application/json", "text/html"],
                   api_spec_url='/api/spec',
                   description='Supplies summary statistics for Flaredown data')

def create_client():
    project_id = 'flaredown-149515'
    return datastore.Client(project_id)

def getCountsByCondition(client, trackable_type, condition):
    query = client.query(kind='Condition' + trackable_type)
    query.add_filter('condition','=',condition)
    for result in query.fetch(limit=1):
        return result

def getTotal(client, trackable_type, trackable_name):
    query = client.query(kind=trackable_type + 'Count')
    query.add_filter('name','=',trackable_name)
    for result in query.fetch(limit=1):
        return result['count']
Пример #46
0
#see

#https://flask-restful.readthedocs.org/en/0.3.2/quickstart.html#full-example


from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource

from cloudmesh_pbs.OpenPBS import OpenPBS

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

api = swagger.docs(Api(app), apiVersion='0.1',
                   basePath='http://localhost:5000',
                   resourcePath='/',
                   produces=["application/json", "text/html"],
                   api_spec_url='/pbs/api/spec',
                   description='The Cloudmesh PBS REST API')

class Job(restful.Resource):

   def get(self, id):
       """gets all jobs"""
       return {'name': 'job get ' + str(id)}

#
# NOTE RESPONSE MSG IS DUMMY I DID NOT WORK ON THAT YET
#
class JobList(restful.Resource):
    @swagger.operation(
        notes='Listing of PBS jobs on a host',
Пример #47
0
from flask import Flask, request
from flask.ext import restful
from datetime import timedelta
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from flask_restful_swagger import swagger
from cors import crossdomain
import sanitize, serialize

# configure the application and the database
app = Flask(__name__)
api = swagger.docs(restful.Api(app, decorators=[crossdomain('*')]), apiVersion='0.1')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)


##############################################################################
class Tag(db.Model):
##############################################################################

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(140), unique=True)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Tag %r>' % self.name


##############################################################################
Пример #48
0
'''


from flask import Flask, redirect
from flask.ext.restful import reqparse, abort, Api, Resource, fields,\
    marshal_with
from flask_restful_swagger import swagger

app = Flask(__name__, static_folder='../static')

###################################
# This is important:
api = swagger.docs(Api(app), apiVersion='0.1',
                   basePath='http://localhost:5000',
                   resourcePath='/',
                   produces=["application/json", "text/html"],
                   api_spec_url='/api/spec')
###################################

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


def abort_if_todo_doesnt_exist(todo_id):
  if todo_id not in TODOS:
    abort(404, message="Todo {} doesn't exist".format(todo_id))
Пример #49
0
from flask_restful_swagger import swagger

import config
from service.transfer import Transfer

import logging
import logging.config

logging.config.fileConfig('../conf/log.conf')
router_logger = logging.getLogger('router')

app = Flask(__name__, static_folder='./static')

api = swagger.docs(Api(app), apiVersion='0.1',
                   resourcePath='/',
                   produces=["application/json"],
                   api_spec_url='/api/monitor',
                   description='SaDev4 Linux Monitor API')


@app.route('/')
@app.route('/index.html')
def index():
    router_logger.info('visit index.html')
    return render_template('index.html')


@app.route('/host/detail', methods=['POST'])
def host_detail():
    uuid = request.form['hostUuid']
    router_logger.info('visit /host/detail with uuid ' + uuid)
Пример #50
0
from flask import Blueprint, jsonify
from flask.ext.login import current_user
from flask.ext.security import login_required
from flask.views import MethodView
from flask_oauthlib.client import OAuth
import os
from core.util import append_container, DEFAULT_SECURITY, get_context_for_scope
from flask import current_app
from core.oauth.base import state_token_required, OauthV1Base, OauthV2Base
from flask.ext.restful import Resource, Api
from flask.ext.restful import reqparse
from flask_restful_swagger import swagger

oauth_views = Blueprint('oauth_views', __name__, template_folder=os.path.join(current_app.config['REPO_PATH'], 'templates'))
oauth = OAuth(oauth_views)
api = swagger.docs(Api(oauth_views), api_spec_url=current_app.config['API_SPEC_URL'])

oauth_handlers = current_app.config['OAUTH_CONFIG'].keys()
oauth_secrets = current_app.config.get("OAUTH_SECRETS", {})

handlers = {}
login_urls = {}

for handler in oauth_handlers:
    mod = __import__("core.oauth.{0}".format(handler))
    if handler not in oauth_secrets:
        continue

    handler_settings = dict(current_app.config['OAUTH_CONFIG'][handler].items() + oauth_secrets[handler].items())
    handler_obj = oauth.remote_app(
        handler,
Пример #51
0
        response = {
            'message'   : message,
            'status'    : code,
            'timestamp' : timestamp
        }
        return self.make_response(response, code)


_CONFIG = DCConfig()

app = Flask(__name__)
# our RESTful API wrapped with Swagger documentation
api = swagger.docs(
    ExceptionHandlingApi(app),
    apiVersion=VERSION,
    description='Data Catalog - enables search, retrieval and storage of metadata '
                'describing data sets. ')

api.add_resource(DataSetSearchResource, _CONFIG.app_base_path)
api.add_resource(MetadataEntryResource, _CONFIG.app_base_path + '/<entry_id>')
api.add_resource(DataSetCountResource, _CONFIG.app_base_path + '/count')
api.add_resource(ElasticSearchAdminResource, _CONFIG.app_base_path + '/admin/elastic')

ignore_for_auth = ['/api/spec']
security = Security(ignore_for_auth)
app.before_request(security.authenticate)


def prepare_environment():
    """Prepares ElasticSearch index for work if it's not yet ready."""
Пример #52
0
#  with the License.  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing,
#  software distributed under the License is distributed on an
#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#  KIND, either express or implied.  See the License for the
#  specific language governing permissions and limitations
#  under the License.

__author__ = "Shamal Faily"

import os
from flask import Blueprint
from flask_restful_swagger import swagger
from flask_restful import Api
from cairis.core.Borg import Borg

b = Borg()
main = Blueprint(
    "main",
    __name__,
    template_folder=os.path.join(b.cairisRoot, "templates"),
    static_folder=b.staticDir,
    static_url_path="",
)
api = swagger.docs(Api(main), apiVersion="1.2.10", description="CAIRIS API", api_spec_url="/api/cairis")

from cairis.daemon.main import views, errors
Пример #53
0
from flask_restful_swagger import swagger

from cairis.core.Borg import Borg
from CairisHTTPError import CairisHTTPError, ARMHTTPError
from cairis.core.ARM import ARMException, DatabaseProxyException
from cairis.controllers import AssetController, AttackerController, CImportController, CExportController, DependencyController, \
    DimensionController, EnvironmentController, GoalController, LoginController, MisuseCaseController, PersonaController, ProjectController, \
    RequirementController, ResponseController, RiskController, RoleController, TaskController, ThreatController, \
    UploadController, VulnerabilityController

__author__ = 'Robin Quetin'
''' This module uses Flask (tested using 0.10) & Flask-Restful (tested using 0.3.3) '''


app = Flask(__name__)
api = swagger.docs(Api(app), apiVersion='0.1', description='CAIRIS API', api_spec_url='/api/cairis')
cors = CORS(app)
b = Borg()


@app.route('/')
def index():
    return app.send_static_file('index.html')


@app.route('/plugins/<path:path>')
def plugin_reroute(path):
    try:
        web_image_dir = os.path.join(b.staticDir, 'plugins')
        return send_from_directory(web_image_dir, path)
    except AttributeError:
Пример #54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask.ext.restful import reqparse, Api
from flask_restful_swagger import swagger

from server import app
from server.views.users import UserView, UserResetPasswordView, UserNewPasswordView
from server.views.sessions import SessionView
from server.views.regexps import RegexpListView, RegexpView
from server.views.datasets import DatasetListView, DatasetView, DatasetSampleView, DatasetProcessView,DatasetSizeView, DatasetPaginateView,DatasetSearchWordView
from server.views.topograms import TopogramListView, TopogramWordsView, TopogramCitationsView, TopogramsByDataset, TopogramView, TopogramTimeFramesView,TopogramFrequentWordsView, TopogramTimeSeries

# doc for flask restful with swagger
api = swagger.docs(Api(app), apiVersion='0.1', api_spec_url="/api/v1/spec", resourcePath="/api/v1/spec")

# users
api.add_resource(UserView, '/api/v1/users')
api.add_resource(UserResetPasswordView, '/api/v1/users/resetPassword')
api.add_resource(UserNewPasswordView, '/api/v1/users/newPassword')
api.add_resource(SessionView, '/api/v1/sessions')

# datasets
api.add_resource(DatasetListView, '/api/v1/datasets')
api.add_resource(DatasetView, '/api/v1/datasets/<int:id>')
api.add_resource(DatasetProcessView, '/api/v1/datasets/<int:id>/index')
api.add_resource(DatasetSampleView, '/api/v1/datasets/<int:id>/sample')
api.add_resource(DatasetSizeView, '/api/v1/datasets/<int:id>/size')
api.add_resource(DatasetPaginateView, '/api/v1/datasets/<int:id>/from/<int:start>/qty/<int:qty>')
api.add_resource(DatasetSearchWordView, '/api/v1/datasets/<int:id>/search')
Пример #55
0
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Extensions module. Each extension is initialized in the app factory located
in app.py
"""
from flask.ext.restful import Api
from flask_restful_swagger import swagger

restapi = swagger.docs(
    Api(),
    apiVersion='0.1',
    api_spec_url='/api/spec',
    description='gluu cluster API',
)
Пример #56
0

config = SafeConfigParser()
config.read('config.ini')

ansible_config = SafeConfigParser()
try:
    ansible_config.read('/etc/ansible/ansible.cfg')
    ansible_default_inventory = config.get("Defaults", "inventory")
except:
    ansible_default_inventory = '/etc/ansible/hosts'

app.config['CELERY_BROKER_URL'] = config.get("Default", "CELERY_BROKER_URL")
app.config['CELERY_RESULT_BACKEND'] = config.get("Default", "CELERY_RESULT_BACKEND")

api = swagger.docs(Api(app), apiVersion='0.1')

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

inventory_access = []

def get_inventory_access(username, inventory):
    if username == "admin":
        return True
    result = False
    with open("rbac.json") as rbac_file:
        rbac_data = json.load(rbac_file)
    user_list = rbac_data['rbac']
    for user in user_list:
        if user['user'] == username:
Пример #57
0
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
from flask_restful_swagger import swagger

app = Flask(__name__)
api = swagger.docs(Api(app), apiVersion='0.1', api_spec_url='/api/spec')

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

parser = reqparse.RequestParser()
parser.add_argument('task')


# Todo
# shows a single todo item and lets you delete a todo item
@swagger.model
class Todo(Resource):
    """Hello, this is my Todo!"""
    def __init__(self):
        pass

    @swagger.operation(
Пример #58
0
    args = parser.parse_args()
    os.environ["api_env"] = args.env

    if not os.environ.get("db_loaded", None):
        run_init_db()
        os.environ["db_loaded"] = "y"

    cfg = Helpers.load_config()
    api_cfg = cfg["api"]

    app = Flask(__name__)
    app.config['BUNDLE_ERRORS'] = True
    api = swagger.docs(Api(app),
                       apiVersion=api_cfg["version"],
                       basePath='http://127.0.0.1:%i' % api_cfg["port"],
                       resourcePath='/',
                       produces=["application/json", "text/html"],
                       api_spec_url='/api/spec',
                       description='99taxis API Project')

    import resources  # import resources after configure environment
    _resources = [
        resources.Driver, resources.DriverInArea, resources.UserCreate,
        resources.UserLogin, resources.UserLogout, resources.RequestDriver,
        resources.RequestHistory, resources.RequestAssignment, resources.FindDrivers]

    for _res in _resources:
        _res.register(api)

    app.run(debug=cfg["env"] != "prod", host=api_cfg["host"], port=api_cfg["port"])
Пример #59
0
def output_csv(data, code, headers=None):
    csv = "{},{},{},{},{},{}\n".format('Value', 'Type', 'Tags', 'First seen', 'Last seen', "Analyzed")
    for d in data:
        csv += "{},{},{},{},{},{}\n".format(d.get('value', "-"), d.get('type', "-"), ";".join(d.get('tags', [])), d.get('date_first_seen', "-"), d.get('date_last_seen', "-"), d.get('last_analysis', "-"))

    resp = make_response(csv, code)
    resp.headers.extend(headers or {})
    return resp

def output_standard(data, code, headers=None):
    resp = make_response(str(data), code)
    resp.headers.extend(headers or {})
    return resp

api = swagger.docs(MalcomApi(app), apiVersion='0.1')

api.representations['text/csv'] = output_csv
api.representations['application/json'] = output_json
api.representations['text/html'] = output_standard

class FileStorageArgument(reqparse.Argument):
    def convert(self, value, op):
        if self.type is FileStorage:
            return value


# API PUBLIC for FEEDS===========================================

class FeedsAPI(Resource):
    decorators=[login_required]