Пример #1
0
def create_app(**kwargs_config):
    """
    Create the flask app
    :param kwargs_config: overwrite any base level config
    :return: flask.Flask instance
    """

    app = factory.create_app(
        app_name=__name__.replace('.app', ''),
        **kwargs_config
    )

    # Load config and logging

    # Register extensions
    api = Api(app)
    mail = Mail(app)
    CORS(
        app,
        origins=app.config.get('CORS_DOMAINS'),
        allow_headers=app.config.get('CORS_HEADERS'),
        methods=app.config.get('CORS_METHODS'),
        supports_credentials=True,
    )

    # Add end points
    api.add_resource(SlackFeedback, '/slack')

    return app
Пример #2
0
def create_app():
    global ds
    global config
    global password_store
    global app

    if app is None:
        try:
            app = Flask(__name__, static_url_path="")
            api = Api(app)
            password_store = None

            config = init_config()

            # A stand alone route for testing
            @app.route('/')
            def index():
                # Some code here
                return jsonify({'status': 200, 'success': True})

            # Set up password store for HTTP Basic auth
            if config['auth_config']['method'] == "HTTP Basic":
                password_store = FilePasswordStore(config['auth_config']['store_file'])
                MemoryAPI.decorators = [auth.login_required]
                MemoryListAPI.decorators = [auth.login_required]

            api.add_resource(MemoryListAPI, '/mydetic/api/v1.0/memories', endpoint='memories')
            api.add_resource(MemoryAPI, '/mydetic/api/v1.0/memories/<string:date_str>', endpoint='memory')

            ds = S3DataStore(s3_config=config["s3_config"])

        except:
            traceback.print_exc(file=sys.stderr)
    return app
Пример #3
0
def configure_api(app):
    api = Api(app, prefix='/api/v1')

    for resource in movie_resources:
        if hasattr(resource, 'path') and hasattr(resource, 'endpoint'):
            api.add_resource(resource, resource.path,
                             endpoint=resource.endpoint)
Пример #4
0
def create_app(conf):
    from views.scc_view import scc
    from views.main_view import main
    from views.cxw_view import cxw
    # from views.api_view import api
    # view_list = [scc, main, api]
    view_list = [scc, main, cxw]

    app = Flask(__name__)
    # to apply config to app,must before init of SQLAlchemy and LoginManager
    app.config.from_object(conf)
    #
    from app.views.api_view import ToolsApi, ArticleApi, ApiRoute, ApiComment, CaptchaApi
    api = Api(app)
    api.add_resource(ToolsApi, '/api/tools/uuid/', endpoint='tool')
    api.add_resource(CaptchaApi, '/api/tools/captcha', endpoint='captcha')
    api.add_resource(ArticleApi,
                     '/api/article/uuid/<uuid>',
                     endpoint='article')
    api.add_resource(ApiComment, '/api/comment/id/<id>', endpoint='comment')
    api.add_resource(ApiRoute, '/api/token/', endpoint='route')

    db.init_app(app)
    # http://blog.csdn.net/yannanxiu/article/details/53426359
    # http://www.pythondoc.com/flask-sqlalchemy/api.html#flask.ext.sqlalchemy.SQLAlchemy.init_app
    # http://librelist.com/browser/flask/2010/8/30/sqlalchemy-init-app-problem/
    db.app = app
    # do not use setup_app()
    lm.session_protection = 'strong'
    lm.login_view = "main.main_login"
    lm.refresh_view = "main.main_login"
    lm.needs_refresh_message = u"To protect your account, please re-authenticate to access this page."
    lm.needs_refresh_message_category = "info"

    # lm callback
    @lm.user_loader
    def load_user(uid):
        return Login.get(uid)

    # auth callback
    @auth.verify_password
    def verify_password(username_or_token, password):
        user = Login.verify_auth_token(username_or_token)
        if not user:
            user = Login.query.filter_by(user=username_or_token).first()
            if not user or not user.verify_password(password):
                return False
        g.user_ = user  # distinguish with flask-login user
        return True

    lm.init_app(app)
    mail.init_app(app)

    for view in view_list:
        # register static fold path to blueprint
        view.static_folder = conf.static_path
        view.template_folder = conf.template_path(postfix=view.name)
        # register blueprint to app
        app.register_blueprint(view)
    return app
Пример #5
0
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """
    app = Flask(__name__)
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(
        app.config['TUGBOAT_LOGGING']
    )

    # CORS
    CORS(
        app,
        resource={
            r'/redirect': {'origins': app.config['TUGBOAT_CORS']}
        }
    )

    # Add end points
    api = Api(app)
    api.add_resource(IndexView, '/index')
    api.add_resource(BumblebeeView, '/redirect')

    return app
Пример #6
0
def configure_extensions(app):
    redis = StrictRedis.from_url(app.config['REDIS_URL'])
    # redis log
    redis_log = RedisLog(
        connection=redis,
        ttl=app.config['REDIS_LOG_TTL'],
        prefix=app.config['REDIS_LOG_PREFIX'],
    )
    app.extensions.update({
        'redis': redis,
        'redis_log': redis_log,
    })
    # rq
    for q in app.config['QUEUES']:
        queue = Queue(
            name=q, default_timeout=app.config[
                'RQ_JOB_TIMEOUT_{}'.format(q.upper())],
            connection=redis,
        )
        app.extensions['rq_{}'.format(q)] = queue

    # rq dashboard
    RQDashboard(app, url_prefix='/_rq')

    # api endpoints
    api = Api(prefix='/api')
    api.add_resource(build.Build, '/build/')
    api.add_resource(build.Logs, '/build/<build_id>/logs/')
    api.init_app(app)
Пример #7
0
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """
    app = Flask(__name__)
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(
        app.config['SMACKDOWN_LOGGING']
    )

    # Cache
    # cache.init_app(app, config=app.config['CACHE'])

    # CORS
    CORS(
        app,
        resource={
            r'/status': {'origins': app.config['CORS_ORIGINS']}
        }
    )
    # Register extensions
    api = Api(app)

    # Add end points
    api.add_resource(IndexView, '/', methods=['GET'])
    api.add_resource(SmackView, '/smackdown', methods=['POST'])

    return app
Пример #8
0
def create_app(config, debug=False, testing=False, config_overrides=None):
    """Application factory."""
    # define the WSGI application object
    flask_app = Flask(__name__)

    # configuration
    flask_app.config.from_object(config)
    flask_app.debug = debug
    flask_app.testing = testing

    if config_overrides:
        flask_app.config.update(config_overrides)

    # initialize the database
    db.init_app(flask_app)

    # blueprints
    from app.listings import listings_blueprint
    flask_app.register_blueprint(listings_blueprint)

    # flask-restful
    from app.listings import ListingsAPI

    api = Api()
    api.add_resource(ListingsAPI, '/listings', endpoint='listings')

    api.init_app(flask_app)

    cors = CORS(resources={r'/api/*': {'origins': '*'}})
    cors.init_app(flask_app)

    return flask_app
Пример #9
0
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    # Load config and logging
    Consul(app)  # load_config expects consul to be registered
    load_config(app)
    logging.config.dictConfig(
        app.config['EXPORT_SERVICE_LOGGING']
    )

    # Register extensions
    api = Api(app)
    Discoverer(app)

    api.add_resource(Aastex, '/aastex')
    api.add_resource(Bibtex, '/bibtex')
    api.add_resource(Endnote, '/endnote')

    return app
Пример #10
0
def create_app():
    """
    Create the application and return it to the user
    :return: application
    """

    app = Flask(__name__, static_folder='static')
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(
        app.config['ACE_LOGGING']
    )

    # Load corpus into the application
    corpus = Corpus()
    corpus.load(
        app.config['ACE_MODEL_PATH']
    )
    app.config['CORPUS'] = corpus

    # Register extensions
    Watchman(app, version=dict(scopes=['']))
    api = Api(app)

    # Add the end resource end points
    api.add_resource(ConceptView, '/concept', methods=['POST'])
    api.add_resource(ReportView, '/report', methods=['GET'])
    return app
    def create_app(self):
        from flask.ext.restful import Resource, Api 
        app = Flask(__name__,static_folder=None)
        
        class DefaultView(Resource):
            '''Default route docstring'''
            def put(self):
                return "put on default route"
            def post(self):
                return "post on default route"
        
        class ScopedView(Resource):
            '''Scoped route docstring'''
            scopes = ['default']
            decorators = [advertise('scopes')]
            def get(self):
                return "scoped route"
        
        self.expected_resources = {
            '/scoped': {
                'scopes':['default'],
                'description': 'Scoped route docstring',
                'methods': ['HEAD','OPTIONS','GET'],
            },
            '/default': {
                'description': 'Default route docstring',
                'methods': ['PUT','POST','OPTIONS'],
            },
        }

        api = Api(app)
        api.add_resource(DefaultView,'/default')
        api.add_resource(ScopedView,'/scoped')
        discoverer = Discoverer(app)
        return app
Пример #12
0
def create_app():
    """
    Create the application and return it to the user
    :return: application
    """

    app = Flask(__name__, static_folder='static')
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(app.config['ACE_LOGGING'])

    # Load corpus into the application
    corpus = Corpus()
    corpus.load(app.config['ACE_MODEL_PATH'])
    app.config['CORPUS'] = corpus

    # Register extensions
    Watchman(app, version=dict(scopes=['']))
    api = Api(app)

    # Add the end resource end points
    api.add_resource(ConceptView, '/concept', methods=['POST'])
    api.add_resource(ReportView, '/report', methods=['GET'])
    return app
Пример #13
0
def init_app():
    chore_app = Flask(__name__)
    CORS(chore_app)
    api = Api(chore_app)
    api.add_resource(WheelAPI, '/api/wheels/<string:id>', endpoint='wheel')
    api.add_resource(WheelListAPI, '/api/wheels', endpoint='wheels')
    return chore_app
Пример #14
0
def create_app(config, debug=False, testing=False, config_overrides=None):
  """Application factory
  """
  # define the WSGI application object
  flask_app = Flask(__name__)

  # configuration
  flask_app.config.from_object(config)
  flask_app.debug = debug
  flask_app.testing = testing

  if config_overrides:
    flask_app.config.update(config_overrides)

  # initialize the database
  db.init_app(flask_app)

  # blueprints
  from app.users import users_blueprint
  flask_app.register_blueprint(users_blueprint)

  # flask-restful
  from app.users import UserListAPI, UserAPI

  api = Api(prefix='/api/v0')
  api.add_resource(UserListAPI, '/users', endpoint='users')
  api.add_resource(UserAPI, '/users/<id>', endpoint='user')

  api.init_app(flask_app)

  cors = CORS(resources={r'/api/*': {'origins': '*'}})
  cors.init_app(flask_app)

  return flask_app
Пример #15
0
def create_app():
    """
    Create the application and return it to the user
    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    Consul(app)

    load_config(app)

    logging.config.dictConfig(
        app.config['GRAPHICS_LOGGING']
    )

    api = Api(app)
    api.add_resource(Graphics, '/<string:bibcode>')

    db.init_app(app)

    Discoverer(app)

    return app
Пример #16
0
class test_auth(BaseResourceTest):
    def setup(self):
        super(test_auth, self).setup()
        import fm

        fm.app.config['TESTING'] = False

    def test_authenticated(self):
        add_user('name1', 'pw1', 'normal')
        add_user('name2', 'pw2', 'disable')
        import fm

        self.api = Api(fm.app)
        self.api.add_resource(AuthResource, '/test/api/auth/')

        rv = self.app.get('/test/api/auth/')
        rv = json.loads(rv.data)
        assert rv['status'] == 403
        rv = self.app.post('/api/user/current/',
                           data={'name': 'name1',
                                 'password': '******'})
        rv = self.app.get('/test/api/auth/')
        rv = json.loads(rv.data)
        assert rv is True
        rv = self.app.post('/test/api/auth/')
        rv = json.loads(rv.data)
        assert rv['status'] == 403

        rv = self.app.delete('/api/user/current/')
        rv = self.app.post('/api/user/current/',
                           data={'name': 'name2',
                                 'password': '******'})
        rv = self.app.get('/test/api/auth/')
        rv = json.loads(rv.data)
        assert rv['status'] == 403
Пример #17
0
def create_app(**kwargs_config):
    app = factory.create_app(
        app_name=__name__.replace('.app', ''),
        **kwargs_config
    )

    api = Api(app)

    # Overwrite WWW-Authenticate challenge on 401
    api.unauthorized = lambda noop: noop

    CORS(
        app,
        origins=app.config.get('CORS_DOMAINS'),
        allow_headers=app.config.get('CORS_HEADERS'),
        methods=app.config.get('CORS_METHODS')
    )

    app.json_encoder = JSONEncoder
    api.add_resource(BenchmarkEndView, '/end')
    api.add_resource(BenchmarkRedirectView, '/redirect')
    api.add_resource(BenchmarkDoubleRedirectView, '/double_redirect')
    api.add_resource(BenchmarkTimeoutEndView, '/timeout_end')
    api.add_resource(BenchmarkTimeoutRedirectView, '/timeout_redirect')

    # Register custom error handlers
    if not app.config.get('DEBUG'):
        app.errorhandler(AdsWSError)(on_adsws_error)
        app.errorhandler(AdsWSFormError)(on_adsws_form_error)
    return app
Пример #18
0
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """
    app = Flask(__name__)
    app.url_map.strict_slashes = False

    # Load config and logging
    Consul(app)  # load_config expects consul to be registered
    load_config(app)
    logging.config.dictConfig(
        app.config['SYSTEMSGO_LOGGING']
    )

    # Cache
    cache.init_app(app, config=app.config['CACHE'])

    # CORS
    CORS(
        app,
        resource={
            r'/status': {'origins': app.config['CORS_ORIGINS']}
        }
    )
    # Register extensions
    api = Api(app)

    # Add end points
    api.add_resource(IndexView, '/')
    api.add_resource(HomeView, '/status')

    return app
Пример #19
0
def init_api(app):
    api = Api(app)
    api.add_resource(UserList, "/api/users")
    api.add_resource(User, "/api/users/<string:user_id>")
    api.add_resource(LocationList, "/api/locations")
    api.add_resource(Location, "/api/locations/<string:location_id>")
    api.add_resource(UserLocation, "/api/user_locations/users/<string:user_id>/locations/<string:location_id>")
Пример #20
0
def create_app(**kwargs_config):
    """
    Create the flask app
    :param kwargs_config: overwrite any base level config
    :return: flask.Flask instance
    """

    app = factory.create_app(app_name=__name__.replace('.app', ''),
                             **kwargs_config)

    # Load config and logging

    # Register extensions
    api = Api(app)
    mail = Mail(app)
    CORS(
        app,
        origins=app.config.get('CORS_DOMAINS'),
        allow_headers=app.config.get('CORS_HEADERS'),
        methods=app.config.get('CORS_METHODS'),
        supports_credentials=True,
    )

    # Add end points
    api.add_resource(SlackFeedback, '/slack')

    return app
Пример #21
0
class RestServer(multiprocessing.Process):
    def __init__(self, host, port, smoker_daemon):
        """
        :param host: host to bind the server to"
        :type host: string
        :param port: port to bind the server to"
        :type port: int
        :param smoker_daemon: instance of the smoker daemon
        :type smoker_daemon: smokerd.Smokerd
        """
        self.host = host
        self.port = port
        self.app = Flask(__name__)

        self.api = Api(self.app)
        self.api.add_resource(About, '/')
        self.api.add_resource(Plugins, '/plugins', '/plugins/')
        self.api.add_resource(Plugin, '/plugins/<string:name>',
                              '/plugins/<string:name>/')
        self.api.add_resource(Processes, '/processes', '/processes/')
        self.api.add_resource(Process, '/processes/<int:id>',
                              '/processes/<int:id>/')

        global smokerd
        smokerd = smoker_daemon

        super(RestServer, self).__init__()
        self.daemon = True

    def run(self):
        setproctitle.setproctitle('smokerd rest api server')
        self.app.run(self.host, self.port)
Пример #22
0
def init_urls(app, urls):
    api = Api(app)
    for k, v in urls.iteritems():
        if isinstance(v, list):
            _v = [i for i in v]
            api.add_resource(k, *_v)
        else:
            api.add_resource(k, v)
Пример #23
0
def run_server(ns, config={}):
    """
    Run API that reads benchmark result data from Crate cluster.
    """
    api = Api(app)
    api.add_resource(Result, "/result/<group>", endpoint="result")
    app.config.update(config)
    app.run(host=ns.http_host, port=ns.http_port, debug=ns.debug)
Пример #24
0
def build_app():
    """
    build a basic flask app containing the API
    """
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(API, '/docker_flask/<argument>')
    return app
Пример #25
0
def build_app():
    """
    build a basic flask app containing the API
    """
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(SpoolerAPI, "/docker_flask/spool_once")
    api.add_resource(ContinuousSpoolerAPI, "/docker_flask/spool_forever")
    return app
Пример #26
0
def setup_web():
    global app
    global api

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

    api.add_resource(Ipipy, '/')
    return app
def test_app_public_endpoint_resource(app, client):
    class RestResource(Resource):
        @public_endpoint
        def get(self):
            return {}

    api = Api(app)
    api.add_resource(RestResource, '/test_restresource_url')

    assert client.get(url_for('restresource')).status_code == 200
Пример #28
0
def routes_init(app):
    api = Api(app)

    api.add_resource(TodoListView, "/api/v1/todos")
    api.add_resource(AddTodoView, "/api/v1/todos/add")
    api.add_resource(ToggleTodoStateView, "/api/v1/todos/<string:id>/toggle")
    api.add_resource(ShowTodoView, "/api/v1/todos/<string:id>")
    api.add_resource(CompleteAllTodosView, "/api/v1/todos/completeall")

    return api
Пример #29
0
class ResourceModel():
	def __init__(self, service):
		self.urlservice = service
		self.service = service.replace("/", "") + "_api"
		self.bp = Blueprint(self.service, __name__)
		CORS(self.bp)
		self.api = Api(self.bp)
		self.entityservice = EntityService
		self.entityview = EntityView
		self.api.add_resource(self.entityservice, '/service/<model>')
		self.api.add_resource(self.entityview, '/get/<model>/<int:entity_id>')
Пример #30
0
class RESTAPI(object):
    """
    REST API for OpenCog

    Implemented using the Flask micro-framework and Flask-RESTful extension

    Documentation:
    http://wiki.opencog.org/w/REST_API

    Prerequisites:
    Flask, mock, flask-restful, six

    Default endpoint: http://127.0.0.1:5000/api/v1.1/
    (Replace 127.0.0.1 with the IP address of the server if necessary)

    Example request: http://127.0.0.1:5000/api/v1.1/atoms?type=ConceptNode

    See: opencog/python/web/api/exampleclient.py for detailed examples of usage, and review
    the method definitions in each resource for request/response specifications.
    """
    def __init__(self, atomspace):
        self.atomspace = atomspace

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = Api(self.app)
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI()
        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')

    def run(self, host='127.0.0.1', port=5000):
        """
        Runs the REST API

        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
                     have the server available externally as well. Defaults to
                     ``'127.0.0.1'``.
        :param port: the port of the webserver. Defaults to ``5000``
        """
        self.app.run(debug=False, host=host, port=port)

    def test(self):
        """
        Returns a test client for the REST API
        """
        return self.app.test_client()
Пример #31
0
def create_app(name='ADSDeploy'):
    """
    Create the application

    :param name: name of the application
    :return: flask.Flask application
    """

    app = Flask(name, static_folder='') # set the root of the project
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(
        app.config['DEPLOY_LOGGING']
    )

    # CORS
    CORS(
        app,
        resources={
            r'/*': {'origins': app.config['CORS_ORIGINS']},
        },
        allow_headers=app.config['CORS_HEADERS'],
        supports_credentials=True
    )

    # Register extensions
    api = Api(app)
    api.add_resource(GithubListener, '/webhooks', methods=['POST'])
    api.add_resource(CommandView, '/command', methods=['GET'])
    api.add_resource(RabbitMQ, '/rabbitmq', methods=['POST'])
    api.add_resource(StatusView, '/status', methods=['GET'])
    api.add_resource(ServerSideStorage, '/store/<string:key>', methods=['GET', 'POST'])
    @app.route('/static/<path:path>')
    def root(path):
        static_folder = app.config.get('STATIC_FOLDER', 'static')
        if not os.path.isabs(static_folder):
            static_folder = os.path.join(app.root_path, static_folder)
        return send_from_directory(static_folder, path)

    # Register any WebSockets
    socketio.init_app(app)

    # Initialise the database
    db.init_app(app)
    # add events
    db.event.listen(Deployment, 'after_insert', after_insert)
    db.event.listen(Deployment, 'after_update', after_update)

    return app
Пример #32
0
def create_app():
  api = Api(blueprint)
  api.add_resource(Resources, '/resources')
  api.add_resource(UnixTime, '/time')

  app = Flask(__name__, static_folder=None) 
  app.url_map.strict_slashes = False
  app.config.from_object('sample_application.config')
  try:
    app.config.from_object('sample_application.local_config')
  except ImportError:
    pass
  app.register_blueprint(blueprint)
  return app
Пример #33
0
def build_app():
    """
    build a basic flask app containing the API
    """
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(ConfigAPI, '/docker_flask/<element>')

    @app.before_first_request
    def on_load():
        LOGGER.info("Config loaded before_first_request")
        api.config = _load_config()

    return app
Пример #34
0
def create_app():
    app = Blueprint('backend', __name__)
    app.debug = True
    api = Api(app)

    from bingo.api.resources import (Rules, Rule)
    resources = {
        Rules: '/rules',
        Rule: '/rules/<name>',
    }

    for resource, route in resources.items():
        api.add_resource(resource, route)
    return app
Пример #35
0
def main():
    try:
        # init
        lModel = RangeManager(int(sys.argv[1]), int(sys.argv[2]))

        monkey.patch_all()
        lApp = Flask(__name__)
        lApp.debug = True
        lApi = Api(lApp)
        FetchRange.sModel = lModel
        Report.sModel = lModel
        Progress.sModel = lModel
        Reset.sModel = lModel
        PushNamespace.sModel = lModel

        # routes
        lApp.add_url_rule('/', 'poll', poll)
        lApp.add_url_rule('/socket.io/<path:path>', 'socket.io', run_socketio)
        lApi.add_resource(FetchRange, '/fetch')
        lApi.add_resource(Report, '/report')
        lApi.add_resource(Progress, '/progress')
        lApi.add_resource(Reset, '/reset')

        # go
        lApp = SharedDataMiddleware(lApp, {})
        lServer = SocketIOServer(('0.0.0.0', 5000),
                                 lApp,
                                 resource="socket.io",
                                 policy_server=False)
        lServer.serve_forever()
    except IndexError:
        print "Usage: " + sys.argv[0] + \
            " <number of ranges> <timeout per range>"
    except KeyboardInterrupt:
        lServer.stop()
Пример #36
0
def create_app(config_type='PRODUCTION'):
    """
    Create the application and return it to the user
    :param config_type: specifies which configuration file to load. Options are
    TEST, LOCAL, and PRODUCTION.

    :return: application
    """

    app = Flask(__name__, static_folder=None)

    app.url_map.strict_slashes = False

    config_dictionary = dict(
        TEST='test_config.py',
        LOCAL='local_config.py',
        PRODUCTION='config.py'
    )

    app.config.from_pyfile(config_dictionary['PRODUCTION'])

    if config_type in config_dictionary.keys():
        try:
            app.config.from_pyfile(config_dictionary[config_type])
        except IOError:
            app.logger.warning('Could not find specified config file: {0}'
                               .format(config_dictionary[config_type]))
            raise

    # Initiate the blueprint
    api = Api(app)

    # Add the end resource end points
    api.add_resource(UserView,
                     '/users/<int:user>/libraries/',
                     methods=['GET', 'POST'])

    api.add_resource(LibraryView,
                     '/users/<int:user>/libraries/<int:library>',
                     methods=['GET', 'POST', 'DELETE'])

    # Initiate the database from the SQL Alchemy model
    db.init_app(app)

    # Add logging
    handler = setup_logging_handler(level='DEBUG')
    app.logger.addHandler(handler)

    discoverer = Discoverer(app)
    return app
Пример #37
0
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    # Load config and logging
    Consul(app)  # load_config expects consul to be registered
    load_config(app)
    logging.config.dictConfig(
        app.config['SAMPLE_APPLICATION_LOGGING']
    )

    # Register extensions
    api = Api(app)
    Discoverer(app)
    db.init_app(app)

    api.add_resource(UnixTime, '/time')
    api.add_resource(PrintArg, '/print/<string:arg>')
    api.add_resource(ExampleApiUsage, '/search')
    api.add_resource(HopperService, '/hopper/<string:bibcodes>') # /print/<array:bibcodes>')

    return app
Пример #38
0
class RESTAPI(object):
    """
    REST API for OpenCog

    Implemented using the Flask micro-framework and Flask-RESTful extension

    Documentation:
    http://wiki.opencog.org/w/REST_API

    Prerequisites:
    Flask, mock, flask-restful, six

    Default endpoint: http://127.0.0.1:5000/api/v1.1/
    (Replace 127.0.0.1 with the IP address of the server if necessary)

    Example request: http://127.0.0.1:5000/api/v1.1/atoms?type=ConceptNode

    See: opencog/python/web/api/exampleclient.py for detailed examples of usage, and review
    the method definitions in each resource for request/response specifications.
    """

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

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = Api(self.app)
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI()
        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')

    def run(self, host='127.0.0.1', port=5000):
        """
        Runs the REST API

        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
                     have the server available externally as well. Defaults to
                     ``'127.0.0.1'``.
        :param port: the port of the webserver. Defaults to ``5000``
        """
        self.app.run(debug=False, host=host, port=port)

    def test(self):
        """
        Returns a test client for the REST API
        """
        return self.app.test_client()
Пример #39
0
def main():
    logging.info('Beginning main loop.')

    # Initialize the arguements
    api_parser = reqparse.RequestParser()
    #api_parser.add_argument('ASN1', type=str, help="First ASN of query. (Order doesn't matter.)", default=None)
    #api_parser.add_argument('ASN2', type=str, help="Second ASN of query.  (Order doesn't matter.)", default=None)
    #api_parser.add_argument('verizon', type=bool, help="Report on verizon existance in ASN's paths.", default=False)
    #api_parser.add_argument('source', type=str, help="An ASN representing the source of the traffic", default=False)
    #api_parser.add_argument('destination', type=str, help="An IP address or subnet destination." , default=False)

    app = Flask(__name__)
    api = Api(app)
    api.add_resource(ASNSearch, '/')
    app.run(debug=True)
    logging.info('Ending main loop.')
Пример #40
0
def create_app():
    app = Flask(__name__, static_folder=None)
    default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  'utils/config.py')
    app.config.from_pyfile(default_config)

    from elric import models

    db.init_app(app)

    from elric.endpoints import ENDPOINTS

    api = Api(app)

    for urlclass, url in ENDPOINTS:
        api.add_resource(urlclass, url)
    return app
Пример #41
0
def create_app(config_name):
    """ Create an application with the given configuration
    """
    # Configure application
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Register API blueprints
    api_blueprint = Blueprint('api', __name__)
    api = Api(api_blueprint)

    # Resources
    api.add_resource(BotAPI, '/')
    app.register_blueprint(api_blueprint)

    return app
Пример #42
0
def init_rest(app_):
    """
    Initializes Flask-Restful related objects and server resources.

    :param app_: The Flask instance.
    """

    from application.resources.app_resource import AppResource
    from application.resources.app_list_resource import AppListResource

    rest_api = Api(app_)
    rest_api.add_resource(AppListResource,
                          ActiveConfig.REST_URL_APPS_LIST,
                          ActiveConfig.REST_URL_APPS_LIST + '/')
    rest_api.add_resource(AppResource,
                          ActiveConfig.REST_URL_APPS_ITEM,
                          ActiveConfig.REST_URL_APPS,
                          ActiveConfig.REST_URL_APPS + '/')
Пример #43
0
def create_app(config_name):
    """
    Flask app factory
    """
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    api = Api()
    db.init_app(app)

    from .resources import MonsterResource, MonsterListResource

    api.add_resource(MonsterListResource, '/monsters', endpoint='monsters')
    api.add_resource(MonsterResource, '/monster/<int:id>', endpoint='monster')
    api.init_app(app)
    app.after_request(add_cors_headers)

    return app
Пример #44
0
def create_app():
    """
    Application factory
    :return configured flask.Flask application instance
    """
    app = Flask(__name__, static_folder=None)

    app.url_map.strict_slashes = False
    Consul(app)  # load_config expects consul to be registered
    load_config(app)
    logging.config.dictConfig(app.config['SOLR_SERVICE_LOGGING'])

    api = Api(app)

    @api.representation('application/json')
    def json(data, code, headers):
        """
        Since we force SOLR to always return JSON, it is faster to
        return JSON as text string directly, without parsing and serializing
        it multiple times
        """
        if not isinstance(data, basestring):
            resp = jsonify(data)
            resp.status_code = code
        else:
            resp = make_response(data, code)
        resp.headers['Content-Type'] = 'application/json'
        resp.headers['Server'] = 'Solr Microservice {v}'.format(
            v=app.config.get('SOLR_SERVICE_VERSION'))
        if code == 200:
            resp.headers['Cache-Control'] = app.config.get(
                'SOLR_CACHE_CONTROL', "public, max-age=600")
        return resp

    api.add_resource(StatusView, '/status')
    api.add_resource(Tvrh, '/tvrh')
    api.add_resource(Search, '/query')
    api.add_resource(Qtree, '/qtree')
    api.add_resource(BigQuery, '/bigquery')

    Discoverer(app)
    return app
Пример #45
0
def create_app():
    """
    Create the application and return it to the user
    :return: application
    """

    app = Flask(__name__, static_folder='static')
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(app.config['LOGGING'])

    # Register extensions
    api = Api(app)

    # Add the end resource end points
    api.add_resource(BenchmarkView, '/benchmark', methods=['POST'])
    api.add_resource(BenchmarkView2, '/benchmark2', methods=['POST'])
    return app
Пример #46
0
def create_app(blueprint_only=False):
  app = Flask(__name__, static_folder=None)

  app.url_map.strict_slashes = False
  app.config.from_pyfile('config.py')
  try:
    app.config.from_pyfile('local_config.py')
  except IOError:
    pass
  app.client = Client(app.config['CLIENT'])

  api = Api(blueprint)
  api.add_resource(Resources, '/resources')
  api.add_resource(Recommender, '/<string:bibcode>')

  if blueprint_only:
    return blueprint

  app.register_blueprint(blueprint)
  db.init_app(app)
  return app
Пример #47
0
def create_app():
    app = Blueprint('backend', __name__, url_prefix='/api')
    app.debug = True
    api = Api(app)

    from saltmonitor.api.resources import (
        Jobs,
        Job,
        SaltReturns,
        SaltReturn,
    )
    resources = {
        Jobs: '/jobs',
        Job: '/jobs/<jid>',
        SaltReturns: '/returns',
        SaltReturn: '/returns/<jid>',
    }

    for resource, route in resources.items():
        api.add_resource(resource, route)
    return app
Пример #48
0
def create_app(name="mission-control"):
    """
    Create the application

    :param name: name of the application
    :return: flask.Flask application
    """

    app = Flask(name, static_folder=None)
    app.url_map.strict_slashes = False

    # Load config and logging
    load_config(app)
    logging.config.dictConfig(app.config['MC_LOGGING'])

    # Register extensions
    api = Api(app)
    api.add_resource(GithubListener, '/webhooks')
    db.init_app(app)

    return app
Пример #49
0
def create_app(config_name):
    """Create a flask app from a config"""
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    register_extensions(app)

    # TODO - better solution
    api = Api(app)

    api_url = '/api/v1'

    from .main import resources

    # TODO - Is this needed
    from . import  auth
    api = Api(app)
    api.add_resource(resources.PopularShows, api_url + '/popular')

    return app
Пример #50
0
def create_app():
    app = Blueprint('backend', __name__, url_prefix='/api')
    api = Api(app)

    from catpics.api.resources import (
        APIToken,
        Users,
        RandomImage,
        Image,
    )
    resources = {
        APIToken: '/tokens',
        Users: '/users',
        RandomImage: '/random',
        Image: '/images/<image>',
    }

    for resource, route in resources.items():
        api.add_resource(resource, route)

    return app
Пример #51
0
def make_blueprint():
    """
    Create a v1 Flask Blueprint
    """
    api_v1_bp = Blueprint('api_v1', __name__)
    api_1 = Api(api_v1_bp)
    api_1.add_resource(DocV1, '/doc/<string:lang>/<string:smallkey>')
    api_1.add_resource(DocsV1, '/docs/<string:lang>/<string:smallkeylist>',
                       '/docs/<string:lang>/<string:smallkeylist>/<string:sortarg>')

    @api_v1_bp.route('/register/<string:smallkey>', methods=['PUT', 'DELETE'])
    def reg_obsolete(smallkey):
        return Response('{"deprecated":"Registration should be performed using the V2 API"}',
                        mimetype='application/json', status=410)

    api_1.add_resource(registration.Refresh, '/update/<string:arg>')

    @api_v1_bp.route('/simplification/<string:smallkey>', methods=['PUT'])
    def simp_obsolete(smallkey):
        return Response('{"deprecated":"Simplification is deprecated, use the v2 update endpoint to edit entries"}',
                        mimetype='application/json', status=410)

    @api_v1_bp.route('/updatefeature/<string:smallkey>', methods=['PUT', 'DELETE'])
    def uf_obsolete(smallkey):
        return Response('{"deprecated":"Update feature should be performed using the V2 API"}',
                        mimetype='application/json', status=410)

    return api_v1_bp
Пример #52
0
def create_app():
    """
    Create the application and return it to the user

    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    # Load config and logging
    Consul(app)  # load_config expects consul to be registered
    load_config(app)
    logging.config.dictConfig(
        app.config['SAMPLE_APPLICATION_LOGGING']
    )

    # Register extensions
    api = Api(app)
    Discoverer(app)
    db.init_app(app)

    api.add_resource(UnixTime, '/time')
    api.add_resource(PrintArg, '/print/<string:arg>')
    api.add_resource(ExampleApiUsage, '/search')

    return app
Пример #53
0
def create_app():
    """
    Create the application and return it to the user
    :return: flask.Flask application
    """

    app = Flask(__name__, static_folder=None)
    app.url_map.strict_slashes = False

    Consul(app)

    load_config(app)

    logging.config.dictConfig(
        app.config['OBJECTS_LOGGING']
    )

    app.cache = Cache(app) 

    api = Api(app)
    api.add_resource(ObjectSearch, '/', '/<string:objects>', '/<string:objects>/<string:source>')
    api.add_resource(PositionSearch, '/pos/<string:pstring>')
    api.add_resource(QuerySearch, '/query')

    discoverer = Discoverer(app)

    return app
Пример #54
0
def create_app(**kwargs_config):
    app = factory.create_app(app_name=__name__.replace('.app', ''),
                             **kwargs_config)

    api = Api(app)

    # Overwrite WWW-Authenticate challenge on 401
    api.unauthorized = lambda noop: noop

    CORS(app,
         origins=app.config.get('CORS_DOMAINS'),
         allow_headers=app.config.get('CORS_HEADERS'),
         methods=app.config.get('CORS_METHODS'))

    app.json_encoder = JSONEncoder
    api.add_resource(StatusView, '/status')
    api.add_resource(ProtectedView, '/protected')
    api.add_resource(UserResolver, '/user/<string:identifier>')
    discover(app)  # Incorporate local and remote applications into this one

    # Register custom error handlers
    if not app.config.get('DEBUG'):
        app.errorhandler(AdsWSError)(on_adsws_error)
        app.errorhandler(AdsWSFormError)(on_adsws_form_error)
    return app