Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
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)
Exemplo n.º 5
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)
Exemplo n.º 6
0
Arquivo: app.py Projeto: adsabs/adsws
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
Exemplo n.º 7
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
Exemplo n.º 8
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
Exemplo n.º 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

    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
Exemplo n.º 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
Exemplo n.º 11
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
Exemplo n.º 12
0
    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
Exemplo n.º 13
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
Exemplo n.º 14
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)
Exemplo n.º 15
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
Exemplo n.º 16
0
def setup_web():
    global app
    global api

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

    api.add_resource(Ipipy, '/')
    return app
Exemplo n.º 17
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
Exemplo n.º 18
0
def create_api(app):
    from flask.ext.restful import Api
    from api import add_resources

    api = Api(catch_all_404s=True)
    api = add_resources(api)
    api.init_app(app)

    return api
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
Exemplo n.º 20
0
def new_restful_api(blueprint):
    """
    Flask-Restful asks for authentication on 401 error through http basic-auth. Since
    we're not using http basic-auth, we have to disable this default handler.
    :param blueprint:
    :return:
    """
    api = Api(blueprint)
    api.unauthorized = _unauthorized_override
    return api
Exemplo n.º 21
0
def create_app(config_filemane):
  """Application factory
  """
  # define the WSGI application object
  flask_app = Flask(__name__)

  # configuration
  flask_app.config.from_object(config_filemane)

  # initialize the database
  db.init_app(flask_app)

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

  # flask-restful
  from app.users import UserListAPI, UserAPI
  from app.trips import TripListAPI, TripAPI
  api = Api(prefix='/api/v0')
  api.add_resource(UserListAPI, '/users', endpoint='users')
  api.add_resource(UserAPI, '/users/<id>', endpoint='user')
  api.add_resource(TripListAPI, '/trips', endpoint='trips')
  api.add_resource(TripAPI, '/trips/<int:id>', endpoint='trip')
  api.init_app(flask_app)

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

  return flask_app
Exemplo n.º 22
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
Exemplo n.º 23
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>')
Exemplo n.º 24
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
Exemplo n.º 25
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
Exemplo n.º 26
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
Exemplo n.º 27
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
Exemplo n.º 28
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()
Exemplo n.º 29
0
    def init_app(self, app, prefix='/api'):
        if hasattr(app, 'teardown_appcontext'):
            app.teardown_appcontext(self.teardown)
        else:
            app.teardown_request(self.teardown)

        self.api = Api(app, prefix=prefix)
Exemplo n.º 30
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 = Api(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')
Exemplo n.º 31
0
        order = {}
        order_id = generate_id()
        order['products'] = 'request/' + order_id
        order = data['products']
        return make_response(render_order_list_as_html(order), 201)


# Define a resource for getting a JSON representation of a EventList.
class OrderListAsJSON(Resource):
    def get(self):
        return data


# Assign URL paths to our resources.
app = Flask(__name__)
api = Api(app)
api.add_resource(HelpRequestList, '/requests')
api.add_resource(HelpRequestListAsJSON, '/requests.json')
api.add_resource(HelpRequest, '/request/<string:farm_id>')
api.add_resource(HelpRequestAsJSON, '/request/<string:farm_id>.json')
api.add_resource(Order, '/order_requests')
api.add_resource(OrderAsJSON, '/order_requests.json')
api.add_resource(OrderList, '/order_requests/<string:farm_id>')
api.add_resource(OrderListAsJSON, '/order_requests/<string:farm_id>.json')


# Redirect from the index to the list of help requests.
@app.route('/')
def index():
    return redirect(api.url_for(HelpRequestList), code=303)
Exemplo n.º 32
0
# coding:UTF-8
import os
from flask.ext.restful import Api
from flask import Flask
from config import config

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config.from_object(config[os.getenv('FLASK_CONFIG') or 'default'])
api = Api(app)

from resources import UserResource, UserListResource, HabitListResource, HabitResource, CategoryResource
api.add_resource(UserListResource, '/users', endpoint='users')
api.add_resource(UserResource, '/users/<uid>', endpoint='user')
api.add_resource(HabitListResource, '/habits', endpoint='habits')
api.add_resource(HabitResource, '/habits/<id>', endpoint='habit')
api.add_resource(CategoryResource, '/categories', endpoint='categories')

if __name__ == '__main__':
    app.run()
Exemplo n.º 33
0
import pymongo
from flask import Flask
from flask.ext.restful import Api


db = pymongo.MongoClient()['stretch-agent']
app = Flask(__name__)
api = Api(app, catch_all_404s=True)
container_dir = '/usr/share/stretch'
agent_dir = '/var/lib/stretch/agent'


class TaskException(Exception):
    pass
Exemplo n.º 34
0
import os
import sys
from petrarch2 import petrarch2
from tornado.ioloop import IOLoop
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from flask import Flask, jsonify, make_response
from flask.ext.restful import Api, Resource, reqparse

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

cwd = os.path.abspath(os.path.dirname(__file__))


@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify({'error': 'Bad request'}), 400)


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


class CodeAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('events', type=dict)
        super(CodeAPI, self).__init__()
Exemplo n.º 35
0
from flask import Flask
from flask.ext.restful import Api, Resource
from peewee import SqliteDatabase

database = SqliteDatabase('/tmp/fangorn.db', threadlocals=True)

from models import User, Token, Folder, File

database.create_tables([User, Token, Folder, File], True)

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

from users import RegistrationResource, AuthenticationResource, AuthenticatedResource
from folders import FolderResource, FolderInstance

api.add_resource(RegistrationResource, '/users/')
api.add_resource(AuthenticationResource, '/authenticate/')
api.add_resource(FolderResource, '/folders/')
api.add_resource(FolderInstance, '/folders/<int:id>/')
Exemplo n.º 36
0
from flask.ext.restful import Api
from . import views
from ptero_workflow.urls import ENDPOINT_INFO

__all__ = ['api']

api = Api(default_mediatype='application/json')

RESOURCES = {
    'workflow-list': views.WorkflowListView,
    'workflow-detail': views.WorkflowDetailView,
    'execution-detail': views.ExecutionDetailView,
    'task-callback': views.TaskCallback,
    'method-callback': views.MethodCallback,
    'report': views.ReportDetailView,
    'server-info': views.ServerInfo,
}

for endpoint_name, resource in RESOURCES.items():
    info = ENDPOINT_INFO[endpoint_name]
    api.add_resource(resource, info['url'], endpoint=endpoint_name)
Exemplo n.º 37
0
from RESTfulApi.resources.account import Accounts, Account

from RESTfulApi.resources.book import Books, Book

from RESTfulApi.resources.vip import Vips, Vip

from RESTfulApi.resources.book_type import BookTypes, BookType

from RESTfulApi.resources.sales_record import SalesRecords

from RESTfulApi.resources.reference import ReferenceBook2Type, ReferenceSaleRecord2Account
from RESTfulApi.resources.reference import ReferenceSaleRecord2Book, ReferenceSale2Vip

api_bp = Blueprint('api', __name__)
api = Api(api_bp)

api.add_resource(Session, '/session')

api.add_resource(Accounts, '/accounts')
api.add_resource(Account, '/accounts/<account_id>')

api.add_resource(Books, '/books')
api.add_resource(Book, '/books/<book_id>')

api.add_resource(Vips, '/vips')
api.add_resource(Vip, '/vips/<vip_id>')

api.add_resource(BookTypes, '/types')
api.add_resource(BookType, '/types/<book_type_id>')
Exemplo n.º 38
0
from lemur.auth.service import AuthenticatedResource
from lemur.auth.permissions import ViewKeyPermission
from lemur.auth.permissions import AuthorityPermission
from lemur.auth.permissions import UpdateCertificatePermission
from lemur.auth.permissions import SensitiveDomainPermission

from lemur.certificates import service
from lemur.authorities.models import Authority
from lemur.roles import service as role_service
from lemur.domains import service as domain_service
from lemur.common.utils import marshal_items, paginated_parser
from lemur.notifications.views import notification_list

mod = Blueprint('certificates', __name__)
api = Api(mod)

FIELDS = {
    'name': fields.String,
    'id': fields.Integer,
    'bits': fields.Integer,
    'deleted': fields.String,
    'issuer': fields.String,
    'serial': fields.String,
    'owner': fields.String,
    'chain': fields.String,
    'san': fields.String,
    'active': fields.Boolean,
    'description': fields.String,
    'notBefore': fields.DateTime(dt_format='iso8601', attribute='not_before'),
    'notAfter': fields.DateTime(dt_format='iso8601', attribute='not_after'),
Exemplo n.º 39
0
            help='No password provided',
            location=['form', 'json']
        )
        self.reqparse.add_argument(
            'verify_password',
            required=True,
            help='No password verification provided',
            location=['form', 'json']
        )
        super().__init__()

    def post(self):
        args = self.reqparse.parse_args()
        if args['password'] == args['verify_password']:
            user = models.User.create_user(**args)
            return marshal(user, user_fields), 201
        return make_response(
            json.dumps({
                'error': 'Password and password verification do not match'
            }), 400)



users_api = Blueprint('resources.users', __name__)
api = Api(users_api)
api.add_resource(
    UserList,
    '/users',
    endpoint='users'
)
Exemplo n.º 40
0
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource, fields, marshal_with
import sys

sys.path.append('..')
from log import Logger

Log = Logger.getLogger(__name__)

import json

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

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

resource_fields = {
    'code': fields.Integer(default=500),
    'message': fields.String,
    'data': fields.Url('todolist')
}
Exemplo n.º 41
0
# -*- coding: utf-8 -*-
# Flask-Diamond (c) Ian Dennis Miller

from flask.ext.restful import Api

rest_api = Api()


def init_rest(self, api_map=None):
    """
    Initialize REST API.

    :returns: None

    By default, this function does nothing.  Your application needs to
    overload this function in order to implement your REST API.
    More information about REST can be found in the
    `documentation <http://flask-restful.readthedocs.org/en/latest/>`_.

    api_map is an optional function that can be responsible
    for setting up the API.  This is usually accomplished with a series of
    add_resource() invocations.  api_map must take one parameter, which is
    the Flask-Restful object managed by Flask-Diamond.

    You will end up writing something like this in your application:

    def api_map(rest):
        rest_api.add_resource(Blah)
    """

    if api_map:
Exemplo n.º 42
0
"""
Defines the blueprint for the users
"""
from flask import Blueprint
from flask.ext.restful import Api

from resources import DeviceResource

DEVICE_BLUEPRINT = Blueprint('device', __name__)
Api(DEVICE_BLUEPRINT).add_resource(DeviceResource, '/device/<string:_id>')
# -*- coding: utf-8 -*-

import sys
import time
import json

import pandas as pd
from flask import Flask
from flask.ext.restful import Api, Resource
from flask import Flask, request, send_file, Response, render_template



app = Flask(__name__, static_folder='./static', template_folder='./templates')
app.secret_key = 'ok, do u l0ve me ~^_ '
api = Api(app)


class Main(Resource):
    def get(self): 
        return Response(render_template('display.html'))


api.add_resource(Main, '/')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
Exemplo n.º 44
0
# -*- coding:utf-8 -*-
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

# restful
from flask.ext.restful import Api
api = Api()


Exemplo n.º 45
0
    :license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <*****@*****.**>
"""
from flask import g, Blueprint
from flask.ext.restful import reqparse, Api, fields

from lemur.users import service
from lemur.certificates import service as certificate_service
from lemur.roles import service as role_service
from lemur.auth.service import AuthenticatedResource
from lemur.auth.permissions import admin_permission
from lemur.common.utils import marshal_items, paginated_parser


mod = Blueprint('users', __name__)
api = Api(mod)


FIELDS = {
    'username': fields.String,
    'active': fields.Boolean,
    'email': fields.String,
    'profileImage': fields.String(attribute='profile_picture'),
    'id': fields.Integer,
}


def roles(values):
    """
    Validate that the passed in roles exist.
Exemplo n.º 46
0
item_each_page = ITEM_EACH_PAGE


def init_parse():
    parser = reqparse.RequestParser()
    parser.add_argument('mark', type=bool)
    parser.add_argument('item_each_page', type=int)
    parser.add_argument('key', type=str)
    parser.add_argument('regex', type=str)
    parser.add_argument('code', type=int)
    return parser


result_bp = Blueprint('result', __name__)
parser = init_parse()
result_api = Api(result_bp)
result_db = client.centaur


class UpdateResult(Resource):
    method_decorators = [login_required]

    def post(self):
        celery_stored = result_db.celery_taskmeta.find()
        for item in celery_stored:
            result = json.loads(item["result"])
            if result:
                result_dict = {
                    "url": result[0],
                    "poc": result[1],
                    "code": result[2][0],
Exemplo n.º 47
0
import ssl
from flask import Flask, send_file, send_from_directory, redirect, request, make_response
from flask.ext.restful import Resource, Api
from flask.ext.restful.reqparse import RequestParser
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from provisor import Provisor
from provisor.provisor import UNKNOWN_HOST
from provisor.utils import validate_pubkey as pubkey
from provisor.utils import validate_username as username

app = Flask(__name__)
app.config['RESTFUL_JSON'] = {"indent": 4}

api = Api(app)

p = Provisor(
    uri="ldap://ldap.hashbang.sh",
    user="******",
    password=os.environ['LDAP_PASSWORD'],
    user_base="ou=People,dc=hashbang,dc=sh",
    group_base="ou=Group,dc=hashbang,dc=sh",
    servers_base="ou=Servers,dc=hashbang,dc=sh",
)

certfile = os.path.join(os.getcwd(), "certs/server.crt")
keyfile = os.path.join(os.getcwd(), "certs/server.key")
https_port = 4443
http_port = 8080
Exemplo n.º 48
0
class ArticlesChallenge(PyAggAbstractResource):
    controller_cls = ArticleController
    attrs = {'ids': {'type': list, 'default': []}}

    @api_permission.require(http_exception=403)
    def get(self):
        parsed_args = self.reqparse_args(right='read')
        # collecting all attrs for casting purpose
        attrs = self.controller_cls._get_attrs_desc('admin')
        for id_dict in parsed_args['ids']:
            keys_to_ignore = []
            for key in id_dict:
                if key not in attrs:
                    keys_to_ignore.append(key)
                if issubclass(attrs[key]['type'], datetime):
                    id_dict[key] = dateutil.parser.parse(id_dict[key])
            for key in keys_to_ignore:
                del id_dict[key]

        result = list(self.controller.challenge(parsed_args['ids']))
        return result or None, 200 if result else 204

api = Api(current_app, prefix=conf.API_ROOT)

api.add_resource(ArticleNewAPI, '/article', endpoint='article_new.json')
api.add_resource(ArticleAPI, '/article/<int:obj_id>', endpoint='article.json')
api.add_resource(ArticlesAPI, '/articles', endpoint='articles.json')
api.add_resource(ArticlesChallenge, '/articles/challenge',
                 endpoint='articles_challenge.json')
Exemplo n.º 49
0
# -*- coding: utf-8 -*-
__author__ = '__apple'
__time__ = '2018/1/17 15:47'

from flask import Flask
from flask.ext.restful import Api

from api.commodity.search import SearchAPI, AssociateApi

app = Flask(__name__)
api_fast = Api(app)

api_fast.add_resource(SearchAPI, '/search/api/')
api_fast.add_resource(AssociateApi, '/associate/api/')

if __name__ == '__main__':
    app.run(debug=True)
Exemplo n.º 50
0
from flask import request, render_template, flash, redirect, url_for
import os
import json
from flask import jsonify
import bson
from bson.objectid import ObjectId
import pymongo
import unicodedata
from flask.ext.restful import Api
from bson.json_util import dumps
from database import db
from database import init_db

app = Flask(__name__)
app.debug = True
api = Api(app)

from resources import PostClass, Search

baseURL = '/api'

api.add_resource(PostClass, baseURL + '/post')
api.add_resource(Search, baseURL + '/get')
'''
@app.route('/api/post', methods=['POST'])
def index():

#	if request.args.get('entity') is None:
#		return json.dumps([])

    jsondata = request.form['jsondata']
Exemplo n.º 51
0
            print e
            return


class ModelWordSet(Resource):
    def get(self):
        try:
            res = base64.b64encode(cPickle.dumps(set(model.index2word)))
            return res
        except Exception, e:
            print e
            return


app = Flask(__name__)
api = Api(app)
#csrf = CsrfProtect(app)
#csrf = CSRFProtect(app)


@app.errorhandler(404)
def pageNotFound(error):
    return "page not found"


@app.errorhandler(500)
def raiseError(error):
    return error


@app.errorhandler(400)
Exemplo n.º 52
0
def create_api(app, api_version='0.0', specpath=''):
    # app.config['CORS_HEADERS'] = 'Content-Type,Auth-Token'

    Config.ES_TISSUE_MAP = load_tissue_map()
    'custom errors for flask-restful'
    # errors = {'SignatureExpired': {
    #     'message': "Authentication expired.",
    #     'status': 419},
    # }
    errors = {}
    api = Api(app, errors=errors)
    '''define api'''

    from app.resources.target import TargetInfo, TargetInfoSingle
    from app.resources import evidence
    from app.resources.efo import EfoLabelFromCode
    from app.resources.evidenceontology import EcoLabelFromCode
    from app.resources.freetextsearch import FreeTextSearch, BestHitSearch, AutoComplete, QuickSearch
    from app.resources import association
    from app.resources.auth import RequestToken, ValidateToken
    from app.resources.expression import Expression
    from app.resources.proxy import ProxyEnsembl, ProxyGXA, ProxyPDB, ProxyGeneric
    from app.resources.cache import ClearCache
    from app.resources.utils import Ping, Version
    from app.resources.relation import RelationTargetSingle, RelationDiseaseSingle
    from app.resources.stats import Stats

    # api.add_resource(AvailableGenes,
    #                  basepath+'/available-genes')
    api.add_resource(
        evidence.Evidence,
        '/public/evidence',
    )
    api.add_resource(evidence.FilterBy,
                     '/public/evidence/filter',
                     endpoint="evidence-filter")
    api.add_resource(
        association.Association,
        '/public/association',
    )
    api.add_resource(association.FilterBy,
                     '/public/association/filter',
                     endpoint="association-filter")
    api.add_resource(EfoLabelFromCode, '/private/disease/<string:disease_id>')
    api.add_resource(EfoLabelFromCode,
                     '/private/disease',
                     endpoint="disease-facets")
    api.add_resource(EcoLabelFromCode, '/private/eco/<string:code>')
    api.add_resource(TargetInfoSingle, '/private/target/<string:target_id>')
    api.add_resource(TargetInfo, '/private/target')
    api.add_resource(Expression, '/private/target/expression')
    api.add_resource(BestHitSearch, '/private/besthitsearch')
    api.add_resource(FreeTextSearch, '/public/search')
    api.add_resource(QuickSearch, '/private/quicksearch')
    api.add_resource(AutoComplete, '/private/autocomplete')
    api.add_resource(RequestToken, '/public/auth/request_token')
    api.add_resource(ValidateToken, '/public/auth/validate_token')
    api.add_resource(ClearCache, '/private/cache/clear')
    api.add_resource(Ping, '/public/utils/ping')
    api.add_resource(Version, '/public/utils/version')
    api.add_resource(Stats, '/public/utils/stats')
    api.add_resource(LogEvent, '/private/utils/logevent')
    api.add_resource(RelationTargetSingle,
                     '/private/relation/target/<string:target_id>')
    api.add_resource(Relations, '/private/relation')
    api.add_resource(RelationDiseaseSingle,
                     '/private/relation/disease/<string:disease_id>')
    api.add_resource(EnrichmentTargets, '/private/enrichment/targets')
    #
    # api.add_resource(ProxyEnsembl,
    #                  '/proxy/ensembl/<path:url>')
    # api.add_resource(ProxyGXA,
    #                  '/proxy/gxa/<path:url>')
    # api.add_resource(ProxyPDB,
    #                  '/proxy/pdbe/<path:url>')
    # api.add_resource(ProxyEPMC,
    #                  '/proxy/epmc/<path:url>')
    # api.add_resource(ProxyGeneric,
    #                  '/proxy/generic/<path:url>')
    return api
Exemplo n.º 53
0
from flask import Flask
from flask.ext.restful import Api

from .db import db

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    app.config.from_object('igor_rest_api.config')
    return app


app = create_app()

from .api import routes
igor_api = Api(app)
routes.setup(igor_api)

Exemplo n.º 54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Blueprint
from flask.ext.restful import Api

Ranks = Blueprint('Ranks', __name__)
ranks_api = Api(Ranks)

from .views import *
ranks_api.add_resource(countRank, '/v1/rank')
ranks_api.add_resource(get_bonus, '/v1/bouns')
ranks_api.add_resource(Rank, '/v1/get/rank')
ranks_api.add_resource(pageRank, '/v1/new/rank')
Exemplo n.º 55
0
from redash import settings, utils, mail, __version__, statsd_client
from redash.models import db
from redash.metrics.request import provision_app
from redash.admin import init_admin

app = Flask(__name__,
            template_folder=settings.STATIC_ASSETS_PATH,
            static_folder=settings.STATIC_ASSETS_PATH,
            static_path='/static')

# Make sure we get the right referral address even behind proxies like nginx.
app.wsgi_app = ProxyFix(app.wsgi_app)
provision_app(app)

api = Api(app)
init_admin(app)

if settings.SENTRY_DSN:
    from raven.contrib.flask import Sentry
    sentry = Sentry(app, dsn=settings.SENTRY_DSN)
    sentry.client.release = __version__

# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
app.config.update(settings.all_settings())
db.init_app(app)
mail.init_app(app)

from redash.authentication import setup_authentication
Exemplo n.º 56
0
import urllib.parse
from pymongo import MongoClient
from flask import Flask, jsonify, make_response
from flask.ext.restful import reqparse, abort, Api, Resource
from bson import json_util, ObjectId
import json

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

username = '******'
password = '******'
username = urllib.parse.quote_plus(username)
password = urllib.parse.quote_plus(password)

client = MongoClient('mongodb://' + username + ':' + password +
                     '@123.56.116.122:27017/')
db = client.schooldata
collection = db.highschool


def abort_if_school_doesnt_exist(school_name):
    if school_name == None or collection.find({
            'school_name': school_name
    }).count() == 0:
        abort(404, message='School {} doesn\'t exist!'.format(school_name))


def abort_if_school_exist(school_name):
    if collection.find({'school_name': school_name}).count() > 0:
        abort(422, message='School {} already exists!'.format(school_name))
Exemplo n.º 57
0
import logging
from flask import Flask
from flask.ext.restful import Api, Resource, reqparse
from flask.ext.restful.representations.json import output_json
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

output_json.func_globals['settings'] = {
    'ensure_ascii': False,
    'encoding': 'utf8'
}

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

logging.basicConfig(
    format='%(levelname)s %(asctime)s %(filename)s %(lineno)d: %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# NOTE: If you need to access data files, the path should be '/src/file.dat'


class StubAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        # Takes a single argument, content, and coerces its type to a list
        self.reqparse.add_argument('content', type=list, location='json')
        super(StubAPI, self).__init__()
Exemplo n.º 58
0
from flask import request
from flask.ext.restful import (Resource,
                               Api)

from colour import (SpectralPowerDistribution,
                    spectral_to_XYZ,
                    CMFS)

from app import app
from sts import (STS_INTERFACE,
                 SocketClient,
                 send_sts_command)

api = Api(app)


class AcquireSpectrum(Resource):
    """
    API endpoint to read spectrum from sts
    """
    def post(self):
        values = send_sts_command(SocketClient(),
                                  STS_INTERFACE.get('get_spectrum'))
        response = [float(i) for i in values[6:-1].split()]
        return response


class AcquireWavelengths(Resource):
    """
    API endpoint to read wavelengths from STS
    """
Exemplo n.º 59
0
from flask import Blueprint, request
from flask.ext.restful import Api, Resource, fields, marshal_with
from werkzeug.datastructures import ImmutableDict
from models import Todo, db

api = Api(prefix='/api')
api_bp = Blueprint('api_bp', __name__)
api.init_app(api_bp)

todo_fields = {
    'id': fields.Integer,
    'task': fields.String,
    'date': fields.DateTime,
    'done': fields.Boolean
}


class TodoListResource(Resource):
    @marshal_with(todo_fields)
    def get(self):
        return Todo.query.all()

    @marshal_with(todo_fields)
    def post(self):
        new = Todo(request.json['task'], False)
        db.session.add(new)
        db.session.commit()
        return new, 201

    def put(self):
        tasks = Todo.query.all()
Exemplo n.º 60
0
try:
    from onelogin.saml2.auth import OneLogin_Saml2_Auth
    from onelogin.saml2.utils import OneLogin_Saml2_Utils
    onelogin_import_success = True
except ImportError:
    onelogin_import_success = False

from .service import fetch_token_header_payload, get_rsa_public_key

from security_monkey.datastore import User
from security_monkey import db, rbac

from urlparse import urlparse

mod = Blueprint('sso', __name__)
api = Api(mod)

from flask_security.utils import validate_redirect_url


class Ping(Resource):
    """
    This class serves as an example of how one might implement an SSO provider for use with Security Monkey. In
    this example we use a OpenIDConnect authentication flow, that is essentially OAuth2 underneath.
    """
    decorators = [rbac.allow(["anonymous"], ["GET", "POST"])]

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        super(Ping, self).__init__()