コード例 #1
0
 def test_init_app(self):
     self.db.create_all()
     manager = APIManager(flask_sqlalchemy_db=self.db)
     manager.create_api(self.Person)
     manager.init_app(self.flaskapp)
     response = self.app.get('/api/person')
     assert response.status_code == 200
コード例 #2
0
    def test_multiple_managers_init_multiple_apps(self):
        """Tests for calling :meth:`~APIManager.init_app` on multiple
        :class:`~flask.Flask` applications after calling
        :meth:`~APIManager.create_api` on multiple instances of
        :class:`APIManager`.

        """
        manager1 = APIManager(session=self.session)
        manager2 = APIManager(session=self.session)

        # Create the Flask applications and the test clients.
        flaskapp1 = self.flaskapp
        flaskapp2 = Flask(__name__)
        testclient1 = self.app
        testclient2 = flaskapp2.test_client()
        force_content_type_jsonapi(testclient2)

        # First create the API, then initialize the Flask applications after.
        manager1.create_api(self.Person)
        manager2.create_api(self.Article)
        manager1.init_app(flaskapp1)
        manager2.init_app(flaskapp2)

        # Tests that only the first Flask application gets requests for
        # /api/person and only the second gets requests for /api/article.
        response = testclient1.get('/api/person')
        assert response.status_code == 200
        response = testclient1.get('/api/article')
        assert response.status_code == 404
        response = testclient2.get('/api/person')
        assert response.status_code == 404
        response = testclient2.get('/api/article')
        assert response.status_code == 200
コード例 #3
0
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
    """Tests for creating resources defined as Flask-SQLAlchemy models instead
    of pure SQLAlchemy models.

    """

    def setUp(self):
        """Creates the Flask-SQLAlchemy database and models."""
        super(TestFlaskSQLAlchemy, self).setUp()

        class Person(self.db.Model):
            id = self.db.Column(self.db.Integer, primary_key=True)

        self.Person = Person
        self.db.create_all()
        self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
        self.manager.create_api(self.Person, methods=['POST'])

    def test_create(self):
        """Tests for creating a resource."""
        data = dict(data=dict(type='person'))
        response = self.app.post('/api/person', data=dumps(data))
        assert response.status_code == 201
        document = loads(response.data)
        person = document['data']
        # TODO To make this test more robust, should query for person objects.
        assert person['id'] == '1'
        assert person['type'] == 'person'
コード例 #4
0
ファイル: test_deleting.py プロジェクト: rezun/flask-restless
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
    """Tests for deleting resources defined as Flask-SQLAlchemy models instead
    of pure SQLAlchemy models.

    """

    def setUp(self):
        """Creates the Flask-SQLAlchemy database and models."""
        super(TestFlaskSQLAlchemy, self).setUp()

        class Person(self.db.Model):
            id = self.db.Column(self.db.Integer, primary_key=True)

        self.Person = Person
        self.db.create_all()
        self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
        self.manager.create_api(self.Person, methods=['DELETE'])

    def test_delete(self):
        """Tests for deleting a resource."""
        person = self.Person(id=1)
        self.session.add(person)
        self.session.commit()
        response = self.app.delete('/api/person/1')
        assert response.status_code == 204
        assert self.Person.query.count() == 0
コード例 #5
0
    def test_constructor_app(self):
        """Tests for providing a :class:`~flask.Flask` application in
        the constructor.

        """
        manager = APIManager(app=self.flaskapp, session=self.session)
        manager.create_api(self.Person)
        response = self.app.get('/api/person')
        assert response.status_code == 200
コード例 #6
0
 def test_schema_app_in_constructor(self):
     manager = APIManager(self.flaskapp, session=self.session)
     manager.create_api(self.Article)
     manager.create_api(self.Person)
     response = self.app.get('/api')
     self.assertEqual(response.status_code, 200)
     document = loads(response.data)
     info = document['meta']['modelinfo']
     self.assertEqual(sorted(info), ['article', 'person'])
     self.assertTrue(info['article']['url'].endswith('/api/article'))
     self.assertTrue(info['person']['url'].endswith('/api/person'))
コード例 #7
0
    def test_single_manager_init_single_app(self):
        """Tests for calling :meth:`~APIManager.init_app` with a single
        :class:`~flask.Flask` application after calling
        :meth:`~APIManager.create_api`.

        """
        manager = APIManager(session=self.session)
        manager.create_api(self.Person)
        manager.init_app(self.flaskapp)
        response = self.app.get('/api/person')
        assert response.status_code == 200
コード例 #8
0
    def test_empty_url_prefix(self):
        """Tests for specifying an empty string as URL prefix at the manager
        level but not when creating an API.

        """
        manager = APIManager(self.flaskapp, session=self.session,
                             url_prefix='')
        manager.create_api(self.Person)
        response = self.app.get('/person')
        assert response.status_code == 200
        response = self.app.get('/api/person')
        assert response.status_code == 404
コード例 #9
0
ファイル: api_manager.py プロジェクト: derek-miller/inspinia
def init_app(app):
    manager = APIManager(app, flask_sqlalchemy_db=db, url_prefix='/models')
    manager.create_api(User,
                       preprocessors=admin_only_preprocessors,
                       url_prefix='',
                       methods=all_methods,
                       max_page_size=100,
                       exclude=('password',))
    manager.create_api(Role,
                       preprocessors=admin_only_preprocessors,
                       url_prefix='',
                       methods=all_methods,
                       max_page_size=100)
    app.logger.addFilter(ProcessingExceptionFilter())
コード例 #10
0
    def test_create_api_before_db_create_all(self):
        """Tests that we can create APIs before
        :meth:`flask_sqlalchemy.SQLAlchemy.create_all` is called.

        """
        manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
        manager.create_api(self.Person)
        self.db.create_all()
        person = self.Person(id=1)
        self.db.session.add(person)
        self.db.session.commit()
        response = self.app.get('/api/person/1')
        assert response.status_code == 200
        document = loads(response.data)
        person = document['data']
        assert '1' == person['id']
コード例 #11
0
    def test_override_url_prefix(self):
        """Tests that a call to :meth:`APIManager.create_api` can
        override the URL prefix provided in the constructor to the
        manager class, if the new URL starts with a slash.

        """
        manager = APIManager(self.flaskapp, session=self.session,
                             url_prefix='/foo')
        manager.create_api(self.Person, url_prefix='/bar')
        manager.create_api(self.Article, url_prefix='')
        response = self.app.get('/bar/person')
        assert response.status_code == 200
        response = self.app.get('/article')
        assert response.status_code == 200
        response = self.app.get('/foo/person')
        assert response.status_code == 404
        response = self.app.get('/foo/article')
        assert response.status_code == 404
コード例 #12
0
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
    """Tests for updating resources defined as Flask-SQLAlchemy models instead
    of pure SQLAlchemy models.

    """

    def setUp(self):
        """Creates the Flask-SQLAlchemy database and models."""
        super(TestFlaskSQLAlchemy, self).setUp()
        # HACK During testing, we don't want the session to expire, so that we
        # can access attributes of model instances *after* a request has been
        # made (that is, after Flask-Restless does its work and commits the
        # session).
        session_options = dict(expire_on_commit=False)
        # Overwrite the `db` and `session` attributes from the superclass.
        self.db = SQLAlchemy(self.flaskapp, session_options=session_options)
        self.session = self.db.session

        class Person(self.db.Model):
            id = self.db.Column(self.db.Integer, primary_key=True)
            name = self.db.Column(self.db.Unicode)

        self.Person = Person
        self.db.create_all()
        self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
        self.manager.create_api(self.Person, methods=['PATCH'])

    def test_create(self):
        """Tests for creating a resource."""
        person = self.Person(id=1, name=u'foo')
        self.session.add(person)
        self.session.commit()
        data = {
            'data': {
                'id': '1',
                'type': 'person',
                'attributes': {
                    'name': u'bar'
                }
            }
        }
        response = self.app.patch('/api/person/1', data=dumps(data))
        assert response.status_code == 204
        assert person.name == 'bar'
コード例 #13
0
    def test_single_manager_init_multiple_apps(self):
        """Tests for calling :meth:`~APIManager.init_app` on multiple
        :class:`~flask.Flask` applications after calling
        :meth:`~APIManager.create_api`.

        """
        manager = APIManager(session=self.session)
        flaskapp1 = self.flaskapp
        flaskapp2 = Flask(__name__)
        testclient1 = self.app
        testclient2 = flaskapp2.test_client()
        force_content_type_jsonapi(testclient2)
        manager.create_api(self.Person)
        manager.init_app(flaskapp1)
        manager.init_app(flaskapp2)
        response = testclient1.get('/api/person')
        assert response.status_code == 200
        response = testclient2.get('/api/person')
        assert response.status_code == 200
コード例 #14
0
    def test_multiple_managers_init_single_app(self):
        """Tests for calling :meth:`~APIManager.init_app` on a single
        :class:`~flask.Flask` application after calling
        :meth:`~APIManager.create_api` on multiple instances of
        :class:`APIManager`.

        """
        manager1 = APIManager(session=self.session)
        manager2 = APIManager(session=self.session)

        # First create the API, then initialize the Flask applications after.
        manager1.create_api(self.Person)
        manager2.create_api(self.Article)
        manager1.init_app(self.flaskapp)
        manager2.init_app(self.flaskapp)

        # Tests that both endpoints are accessible on the Flask application.
        response = self.app.get('/api/person')
        assert response.status_code == 200
        response = self.app.get('/api/article')
        assert response.status_code == 200
コード例 #15
0
    def test_multiple_managers_init_single_app(self):
        """Tests for calling :meth:`~APIManager.init_app` on a single
        :class:`~flask.Flask` application after calling
        :meth:`~APIManager.create_api` on multiple instances of
        :class:`APIManager`.

        """
        manager1 = APIManager(session=self.session)
        manager2 = APIManager(session=self.session)

        # First create the API, then initialize the Flask applications after.
        manager1.create_api(self.Person)
        manager2.create_api(self.Article)
        manager1.init_app(self.flaskapp)
        manager2.init_app(self.flaskapp)

        # Tests that both endpoints are accessible on the Flask application.
        response = self.app.get('/api/person')
        assert response.status_code == 200
        response = self.app.get('/api/article')
        assert response.status_code == 200
コード例 #16
0
def setup_app(config_name, app, database):
    """
    Creates a JSON:API compliant REST application.

    :param config_name str: String name of the config.
    :param app: The application.
    :param database: SQLAlchemy database.
    """

    # 0) Import models. SQLAlchemy requires this during app initialization.
    import models

    # 1) Set up appropriate app configs.
    app.config.from_object(config[config_name])

    # 2) Set up CORS.
    CORS(app)

    # 3) Get JSON:API compliant endpoints, based on models.
    apimanager = APIManager(app,
                            flask_sqlalchemy_db=database,
                            preprocessors=dict(GET_MANY=[auth_func],
                                               GET_SINGLE=[auth_func],
                                               POST=[auth_func],
                                               DELETE=[auth_func]))

    apimanager.create_api(models.Item, methods=['GET', 'POST', 'DELETE'])
    apimanager.create_api(models.Group, methods=['GET', 'POST', 'DELETE'])
    apimanager.create_api(models.ItemImage, methods=['GET', 'POST', 'DELETE'])

    return apimanager
コード例 #17
0
    def setUp(self):
        app = Flask(__name__)
        self.engine = create_engine('sqlite://', echo=False)
        session = scoped_session(
            sessionmaker(autocommit=False, autoflush=False,
                         bind=self.engine))()

        Base.metadata.create_all(bind=self.engine)
        session.bulk_save_objects(
            [Person(id=i, name=f'Person {i}') for i in range(1, 10001)])
        session.bulk_save_objects([
            Article(id=i, title=f'Title {i}', author_id=i % 3)
            for i in range(1, 101)
        ])
        session.bulk_save_objects(
            [Comment(id=i, author_id=i, article_id=i) for i in range(1, 11)])

        self.test_client = app.test_client()

        api_manager = APIManager(app=app,
                                 session=session,
                                 url_prefix='/api',
                                 include_links=False)
        api_manager.create_api(Person, collection_name='people', page_size=0)
        api_manager.create_api(Article,
                               collection_name='articles',
                               page_size=0)
        api_manager.create_api(Comment,
                               collection_name='comments',
                               page_size=0)
        self.profile = cProfile.Profile()
コード例 #18
0
class TestFlaskSQLAlchemy(FlaskSQLAlchemyTestBase):
    """Tests for fetching resources defined as Flask-SQLAlchemy models
    instead of pure SQLAlchemy models.

    """
    def setUp(self):
        """Creates the Flask-SQLAlchemy database and models."""
        super(TestFlaskSQLAlchemy, self).setUp()

        class Person(self.db.Model):
            id = self.db.Column(self.db.Integer, primary_key=True)

        self.Person = Person
        self.db.create_all()
        self.manager = APIManager(self.flaskapp, session=self.db.session)
        self.manager.create_api(self.Person)

    def test_fetch_resource(self):
        """Test for fetching a resource."""
        person = self.Person(id=1)
        self.session.add(person)
        self.session.commit()
        response = self.app.get('/api/person/1')
        document = response.json
        person = document['data']
        assert person['id'] == '1'
        assert person['type'] == 'person'

    def test_fetch_collection(self):
        """Test for fetching a collection of resource."""
        person1 = self.Person(id=1)
        person2 = self.Person(id=2)
        self.session.add_all([person1, person2])
        self.session.commit()
        response = self.app.get('/api/person')
        document = response.json
        people = document['data']
        assert ['1', '2'] == sorted(person['id'] for person in people)
コード例 #19
0
    def test_universal_preprocessor(self):
        """Tests universal preprocessor and postprocessor applied to all
        methods created with the API manager.

        """
        class Counter:
            """An object that increments a counter on each invocation."""

            def __init__(self):
                self._counter = 0

            def __call__(self, *args, **kw):
                self._counter += 1

            def __eq__(self, other):
                if isinstance(other, Counter):
                    return self._counter == other._counter
                if isinstance(other, int):
                    return self._counter == other
                return False

        increment1 = Counter()
        increment2 = Counter()

        preprocessors = dict(GET_COLLECTION=[increment1])
        postprocessors = dict(GET_COLLECTION=[increment2])
        manager = APIManager(self.flaskapp, session=self.session,
                             preprocessors=preprocessors,
                             postprocessors=postprocessors)
        manager.create_api(self.Person)
        manager.create_api(self.Article)
        # After each request, regardless of API endpoint, both counters should
        # be incremented.
        self.app.get('/api/person')
        self.app.get('/api/article')
        self.app.get('/api/person')
        assert increment1 == increment2 == 3
コード例 #20
0
    def test_universal_preprocessor(self):
        """Tests universal preprocessor and postprocessor applied to all
        methods created with the API manager.

        """
        class Counter:
            """An object that increments a counter on each invocation."""
            def __init__(self):
                self._counter = 0

            def __call__(self, *args, **kw):
                self._counter += 1

            def __eq__(self, other):
                if isinstance(other, Counter):
                    return self._counter == other._counter
                if isinstance(other, int):
                    return self._counter == other
                return False

        increment1 = Counter()
        increment2 = Counter()

        preprocessors = dict(GET_COLLECTION=[increment1])
        postprocessors = dict(GET_COLLECTION=[increment2])
        manager = APIManager(self.flaskapp,
                             session=self.session,
                             preprocessors=preprocessors,
                             postprocessors=postprocessors)
        manager.create_api(self.Person)
        manager.create_api(self.Article)
        # After each request, regardless of API endpoint, both counters should
        # be incremented.
        self.app.get('/api/person')
        self.app.get('/api/article')
        self.app.get('/api/person')
        assert increment1 == increment2 == 3
コード例 #21
0
    def setup(self):
        manager = APIManager(self.app, session=self.session)
        manager.create_api(Article)
        manager.create_api(Person)
        manager.create_api(Comment)
        self.manager = manager

        Base.metadata.create_all(bind=self.engine)
        yield
        Base.metadata.drop_all(bind=self.engine)
コード例 #22
0
 def setup(self):
     manager = APIManager(self.app,
                          session=self.session,
                          include_links=True)
     manager.create_api(Article)
     manager.create_api(Person, methods=['GET', 'POST'])
     manager.create_api(Comment)
     Base.metadata.create_all(bind=self.engine)
     yield
     Base.metadata.drop_all(bind=self.engine)
コード例 #23
0
def setup_api(app):
    # Setup CORS
    CORS(app.flask_app)

    # Initialize the login manager
    login_manager = LoginManager()
    login_manager.init_app(app.flask_app)

    # Setup the user and request loading
    @login_manager.user_loader
    def user_loader(user_id):
        return User.find_one(id=user_id)

    @login_manager.request_loader
    def request_loader(request):
        session_token = request.headers.get('X-Session-Token')
        return User.from_token(session_token)

    # Add the auth endpoint
    app.api.add_resource(AuthResource, '/api/auth')

    # Add the answer endpoint
    app.api.add_resource(AnswerResource,
                         '/api/question/<int:question_id>/answer')

    # Add the object endpoints
    manager = APIManager(app.flask_app, flask_sqlalchemy_db=app.db)
    manager.create_api(
        Question,
        methods=['GET', 'POST', 'PUT', 'DELETE'],
        preprocessors={
            'POST': [authenticate],
            'PUT_SINGLE': [authenticate],
            'PUT_MANY': [authenticate],
            'DELETE_SINGLE': [authenticate],
            'DELETE_MANY': [authenticate],
        },
        postprocessors={'POST': [weight_postprocessor(Question)]})
    manager.create_api(
        Category,
        methods=['GET', 'POST', 'PUT', 'DELETE'],
        preprocessors={
            'POST': [authenticate],
            'PUT_SINGLE': [authenticate],
            'PUT_MANY': [authenticate],
            'DELETE_SINGLE': [authenticate],
            'DELETE_MANY': [authenticate],
        },
        postprocessors={'POST': [weight_postprocessor(Category)]})
    manager.create_api(
        QuestionWeight,
        methods=['PUT'],
        preprocessors={'PUT': [authenticate]},
    )
コード例 #24
0
 def setup(self):
     manager = APIManager(self.app, session=self.session)
     manager.create_api(Article, methods=['PATCH'])
     manager.create_api(Person, methods=['PATCH'])
     manager.create_api(Person,
                        methods=['PATCH'],
                        url_prefix='/api2',
                        allow_to_many_replacement=True,
                        allow_delete_from_to_many_relationships=True)
     Base.metadata.create_all(bind=self.engine)
     yield
     Base.metadata.drop_all(bind=self.engine)
コード例 #25
0
class TestProcessors(BaseTestClass):
    """Tests for pre- and post-processors."""

    @pytest.fixture(autouse=True)
    def setup(self):
        self.manager = APIManager(self.app, session=self.session)
        Base.metadata.create_all(bind=self.engine)
        yield
        Base.metadata.drop_all(bind=self.engine)

    def test_preprocessor(self):
        """Tests :http:method:`post` requests with a preprocessor function."""

        def set_name(data=None, **__):
            """Sets the name attribute of the incoming data object, regardless
            of the value requested by the client.

            """
            if data is not None:
                data['data']['attributes']['name'] = u'bar'

        preprocessors = dict(POST_RESOURCE=[set_name])
        self.manager.create_api(Person, methods=['POST'], preprocessors=preprocessors)
        post_data = dict(data=dict(type='person', attributes=dict(name=u'foo')))
        document = self.post_and_validate('/api/person', json=post_data)
        assert document['data']['attributes']['name'] == 'bar'

    def test_postprocessor(self):
        """Tests that a postprocessor is invoked when creating a resource."""

        def modify_result(result=None, **__):
            result['foo'] = 'bar'

        postprocessors = dict(POST_RESOURCE=[modify_result])
        self.manager.create_api(Person, methods=['POST'], postprocessors=postprocessors)
        data = dict(data=dict(type='person'))
        response = self.client.post('/api/person', json=data)
        assert response.status_code == 201
        document = response.json
        assert document['foo'] == 'bar'

    def test_postprocessor_can_rollback_transaction(self):
        """Tests that a postprocessor can rollback the transaction."""

        def rollback_transaction(**__):
            self.session.rollback()

        postprocessors = dict(POST_RESOURCE=[rollback_transaction])
        self.manager.create_api(Person, methods=['POST'], postprocessors=postprocessors)
        data = dict(data=dict(type='person'))
        self.post_and_validate('/api/person', json=data)
        assert self.session.query(Person).count() == 0
コード例 #26
0
def initialize_resources(app):
    from server.api.health_check import HealthCheckAPI
    from server.api.race_resource import RaceAPI, race_deserializer, race_serializer
    from server.models.race import Race, RaceFollow
    from server.models.user import User
    from server.models.route import Route
    api = Api(app, default_mediatype='application/json', prefix='/api/v1')
    api_manager = APIManager(app, flask_sqlalchemy_db=db)
    api_manager.create_api(
        Race,
        methods=['GET', 'PUT'],
        url_prefix='/api/v2',
        exclude_columns=['race_follows', 'routes', 'user_id'],
        serializer=race_serializer,
        deserializer=race_deserializer)
    api_manager.create_api(User, methods=['GET'])
    api_manager.create_api(Route, methods=['GET'])
    api_manager.create_api(RaceFollow, methods=['GET'])
    api.add_resource(HealthCheckAPI, '/health-check/')
    api.add_resource(RaceAPI, '/races/')
コード例 #27
0
ファイル: __init__.py プロジェクト: stevendiaz/idb
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
        if app.config['ELASTICSEARCH_URL'] else None

    api_manager = APIManager(app, flask_sqlalchemy_db=db)
    api_manager.create_api(models.Item,
                           methods=['GET'],
                           url_prefix='',
                           results_per_page=-1)
    api_manager.create_api(models.Skill,
                           methods=['GET'],
                           url_prefix='',
                           results_per_page=-1)
    api_manager.create_api(models.Video,
                           methods=['GET'],
                           url_prefix='',
                           results_per_page=-1)
    api_manager.create_api(models.Reddit,
                           methods=['GET'],
                           url_prefix='',
                           results_per_page=-1)

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.api import bp as main_bp
    app.register_blueprint(main_bp)

    CORS(app)

    return app
コード例 #28
0
ファイル: serializers.py プロジェクト: 425776024/Learn
import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restless import APIManager

app = Flask(__name__)
db = SQLAlchemy(app)
restless = APIManager(app, flask_sqlalchemy_db=db)


class User(db.Model):
    """
    user
    """
    id = db.Column(db.Integer, primary_key=True)
    nick = db.Column(db.String(255), unique=True, nullable=False)
    password = db.Column(db.Integer, nullable=False)
    create_time = db.Column(db.DateTime,
                            nullable=False,
                            default=datetime.datetime.utcnow)


restless.create_api(User,
                    methods=['GET', 'POST', 'DELETE', 'PATCH', 'PUT'],
                    results_per_page=100)

db.create_all()

if __name__ == '__main__':
    app.run(port=25000)
コード例 #29
0
class SwagAPIManager(object):
    swagger = {
        'swagger': '2.0',
        'info': {},
        'schemes': ['http', 'https'],
        'basePath': '/',
        'consumes': ['application/json'],
        'produces': ['application/json'],
        'paths': {},
        'definitions': {}
    }

    def __init__(self, app=None, **kwargs):
        self.app = None
        self.manager = None

        if app is not None:
            self.init_app(app, **kwargs)

    def to_json(self, **kwargs):
        return json.dumps(self.swagger, **kwargs)

    def to_yaml(self, **kwargs):
        return yaml.dump(self.swagger, **kwargs)

    def __str__(self):
        return self.to_json(indent=4)

    @property
    def version(self):
        if 'version' in self.swagger['info']:
            return self.swagger['info']['version']
        return None

    @version.setter
    def version(self, value):
        self.swagger['info']['version'] = value

    @property
    def title(self):
        if 'title' in self.swagger['info']:
            return self.swagger['info']['title']
        return None

    @title.setter
    def title(self, value):
        self.swagger['info']['title'] = value

    @property
    def description(self):
        if 'description' in self.swagger['info']:
            return self.swagger['info']['description']
        return None

    @description.setter
    def description(self, value):
        self.swagger['info']['description'] = value

    def add_path(self, model, **kwargs):
        name = model.__tablename__
        schema = model.__name__
        path = kwargs.get('url_prefix', "") + '/' + name
        id_path = "{0}/{{{1}Id}}".format(path, schema.lower())
        self.swagger['paths'][path] = {}

        for method in [m.lower() for m in kwargs.get('methods', ['GET'])]:
            if method == 'get':
                self.swagger['paths'][path][method] = {
                    'parameters': [{
                        'name': 'q',
                        'in': 'query',
                        'description': 'searchjson',
                        'type': 'string'
                    }],
                    'responses': {
                        200: {
                            'description': 'List ' + name,
                            'schema': {
                                'title': name,
                                'type': 'array',
                                'items': {'$ref': '#/definitions/' + name}
                            }
                        }

                    }
                }

                if model.__doc__:
                    self.swagger['paths'][path]['description'] = model.__doc__
                if id_path not in self.swagger['paths']:
                    self.swagger['paths'][id_path] = {}
                self.swagger['paths'][id_path][method] = {
                    'parameters': [{
                        'name': schema.lower() + 'Id',
                        'in': 'path',
                        'description': 'ID of ' + schema,
                        'required': True,
                        'type': 'integer'
                    }],
                    'responses': {
                        200: {
                            'description': 'Success ' + name,
                            'schema': {
                                'title': name,
                                '$ref': '#/definitions/' + name
                            }
                        }

                    }
                }
                if model.__doc__:
                    self.swagger['paths'][id_path]['description'] = model.__doc__
            elif method == 'delete':
                if id_path not in self.swagger['paths']:
                    self.swagger['paths'][id_path] = {}
                self.swagger['paths']["{0}/{{{1}Id}}".format(path, schema.lower())][method] = {
                    'parameters': [{
                        'name': schema.lower() + 'Id',
                        'in': 'path',
                        'description': 'ID of ' + schema,
                        'required': True,
                        'type': 'integer'
                    }],
                    'responses': {
                        200: {
                            'description': 'Success'
                        }

                    }
                }
                if model.__doc__:
                    self.swagger['paths'][id_path]['description'] = model.__doc__
            else:
                self.swagger['paths'][path][method] = {
                    'parameters': [{
                        'name': name,
                        'in': 'body',
                        'description': schema,
                        'type': "#/definitions/" + schema
                    }],
                    'responses': {
                        200: {
                            'description': 'Success'
                        }

                    }
                }
                if model.__doc__:
                    self.swagger['paths'][path]['description'] = model.__doc__

    def add_defn(self, model, **kwargs):
        name = model.__name__
        self.swagger['definitions'][name] = {
            'type': 'object',
            'properties': {}
        }
        columns = get_columns(model).keys()
        for column_name, column in get_columns(model).items():
            if column_name in kwargs.get('exclude_columns', []):
                continue
            try:
                column_type = str(column.type)
                if '(' in column_type:
                    column_type = column_type.split('(')[0]
                column_defn = sqlalchemy_swagger_type[column_type]
            except AttributeError:
                schema = get_related_model(model, column_name)
                if column_name + '_id' in columns:
                    column_defn = {'schema': {
                        '$ref': schema.__name__
                    }}
                else:
                    column_defn = {'schema': {
                        'type': 'array',
                        'items': {
                            '$ref': schema.__name__
                        }
                    }}

            if column.__doc__:
                column_defn['description'] = column.__doc__
            self.swagger['definitions'][name]['properties'][column_name] = column_defn

    def init_app(self, app, **kwargs):
        self.app = app
        self.manager = APIManager(self.app, **kwargs)

        swagger = Blueprint('swagger', __name__, static_folder='static',
                            static_url_path=self.app.static_url_path + '/swagger', )

        @swagger.route('/swagger')
        def swagger_ui():
            return redirect('/static/swagger/swagger-ui/index.html')

        @swagger.route('/swagger.json')
        def swagger_json():
            # I can only get this from a request context
            self.swagger['host'] = urlparse.urlparse(request.url_root).netloc
            return jsonify(self.swagger)

        app.register_blueprint(swagger)

    def create_api(self, model, **kwargs):
        self.manager.create_api(model, **kwargs)
        self.add_defn(model, **kwargs)
        self.add_path(model, **kwargs)

    def swagger_blueprint(self):

        return swagger
コード例 #30
0
def auth_func(*args, **kwargs):
    auth_token = request.headers.get('auth-token')
    print(auth_token)
    user_id = Admin.decode_auth_token(auth_token)
    print(user_id)
    user = Admin.query.filter_by(id=user_id).first()
    if not user:
        raise ProcessingException(description='Not authenticated!', code=401)
    return True


manager = APIManager(app, flask_sqlalchemy_db=db, preprocessors=dict(GET_MANY=[auth_func], POST_MANY=[auth_func],
                                                                     GET=[auth_func], DELETE=[auth_func],
                                                                     DELETE_MANY=[auth_func], POST=[auth_func]))
# manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(User, methods=['GET'], results_per_page=0)
manager.create_api(Branch, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Department, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(SubDepartment, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Designation, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Grade, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Mode, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Status, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Type, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(Employee, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(PunchRecord, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(BranchDepartment, methods=['GET', 'POST', 'DELETE', 'PATCH'])
manager.create_api(DepartmentSubDepartment, methods=['GET', 'POST', 'DELETE', 'PATCH'])

@app.route('/api/alluser', methods=['GET'])
def alluser():
コード例 #31
0
        secondaryjoin=(users_to_follow.c.user_being_followed_id == id),
        backref=db.backref('users_to_follow', lazy='dynamic'),
        lazy='dynamic')

    def __repr__(self):
        return '<Person {}>'.format(self.username)

    def follow_user(self, person):
        if not self.is_following_user(person):
            self.followed_user.append(person)

    def unfollow_user(self, person):
        if self.is_following_user(person):
            self.followed_user.remove(person)

    def is_following_user(self, person):
        return self.followed_user.filter(
            users_to_follow.c.user_being_followed_id == person.id).count() > 0


@login_manager.user_loader
def user_loader(id):
    return Person.query.get(int(id))


api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Person, methods=['GET', 'POST', 'DELETE', 'PUT'])
api_manager.create_api(Blogpost, methods=['GET', 'POST', 'DELETE', 'PUT'])
api_manager.create_api(Comment, methods=['GET', 'POST', 'DELETE', 'PUT'])
db.create_all()
コード例 #32
0
# coding=utf-8

from flask_restless import APIManager


api_manager = APIManager()

# User
from app.models import User

api_manager.create_api(
    User, methods=['GET', 'POST', 'DELETE', "PUT"],
    url_prefix="/api/model"
)


from app.models import Role
api_manager.create_api(
    Role, methods=['GET', 'POST', 'DELETE'],
    url_prefix="/api/model"
)
コード例 #33
0
ファイル: server.py プロジェクト: reniwiner/CourseProject
    return redirect('/api/simple/results?q={"filters":[{"name":"school","op":"has","val":{"name":"area","op":"ilike","val":"%район%"}}]}')


if __name__ == '__main__':

    mr_manager = APIManager(app, flask_sqlalchemy_db=db)

    simple_methods = ['abs_scores', 'scores', 'school.location', 'school.extra']
    simple_columns = ['year', 'subject', 'students', 'school', 'school.name', 'school.type', 'school_id']

    mr_manager.create_api(Result, url_prefix='/api/all',
                          collection_name='results', methods=['GET'],
                          # include_methods=simple_methods,
                          # include_columns=simple_columns,
                          #exclude_columns=['school'],
                          results_per_page=10000,
                          max_results_per_page=10000,
                          # exclude_columns=['id', 'school.id', 'school_id'],
                          # preprocessors={'GET_MANY':[]},
                          # postprocessors={'GET_MANY':[]}
                          )

    mr_manager.create_api(Result, url_prefix='/api/v2',
                          collection_name='results', methods=['GET'],
                          include_methods=simple_methods,
                          # include_columns=simple_columns,
                          results_per_page = 20,
                          # max_results_per_page = 100,
                          # allow_functions = True,
                          exclude_columns=['id', 'school.id', 'school_id', 'school.area', 'school.region',
                                            'school.has_extra_data', 'school.has_comp_class','school.comp_classes',
コード例 #34
0
ファイル: app.py プロジェクト: echo0282/train-booking
from flask_admin.contrib.sqla import ModelView
from flask_restless import APIManager

from database import db
from models import Train


app = Flask(__name__)
app.config.from_object("config.DevelopmentConfig")
db.init_app(app) #this changes the app

with app.app_context():
    api_manager = APIManager(app, flask_sqlalchemy_db=db)
   # api_manager.init_app(app) #this cannot work
    #api_manager.create_api(Train, methods=["GET", 'POST', 'DELETE'])
    api_manager.create_api(Train, include_columns =["id", "fromCity", "toCity"], methods=["GET", 'POST', 'PUT', 'DELETE'])

#def get_trains():

def create_admin():
    admin = Admin(app, name="TrainsBooking")
    admin.add_view(ModelView(Train, db.session))


def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if "logged_in" in session:
            return f(*args, **kwargs)
        else:
            flash("you need to log in first")
コード例 #35
0
 def test_init_app(self):
     manager = APIManager(flask_sqlalchemy_db=self.db)
     manager.create_api(self.Person)
     manager.init_app(self.flaskapp)
     response = self.app.get('/api/person')
     assert response.status_code == 200
コード例 #36
0
ファイル: __init__.py プロジェクト: Daemon-guo/ubackup
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers = "Referer,Accept,Origin,User-Agent"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        return rst

    return wrapper_fun



manager = APIManager(app, flask_sqlalchemy_db=db)

from myapp.views import front, alert, login
from myapp.models import Cluster, Node, BackupType, Business, BackupInstance, User

crud = ['GET', 'POST', 'DELETE', 'PUT', 'PATCH']

manager.create_api(Node, methods=crud, results_per_page=None,
                   max_results_per_page=999999999999999)
manager.create_api(Cluster, methods=crud, results_per_page=None,
                   max_results_per_page=999999999999999)

manager.create_api(BackupType, methods=crud, include_columns=['id', 'name'], results_per_page=None,
                   max_results_per_page=999999999999999)

manager.create_api(Business, methods=crud, include_columns=['id', 'business_id', 'name'], results_per_page=None,
                   max_results_per_page=999999999999999)

manager.create_api(BackupInstance, methods=crud, max_results_per_page=999999999999999,allow_delete_many=True)

コード例 #37
0
ファイル: __init__.py プロジェクト: ITPNYU/tap
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = 'strong' # or 'basic'

@login_manager.user_loader
def load_user(user_id):
    return db_session.query(User).get(int(user_id))

# Flask-Restless API endpoints
manager = APIManager(app, session=db_session,
                     preprocessors=dict(DELETE=[authn_func],
                                        GET_SINGLE=[authn_func], GET_MANY=[authn_func],
                                        PATCH=[authn_func]))
opportunity_blueprint = manager.create_api(Opportunity,
                                           methods=['GET', 'DELETE', 'PATCH', 'POST'],
                                           collection_name='opportunity',
                                           url_prefix='/v1',
                                           max_results_per_page=300,
                                           preprocessors=dict(POST=[authn_func]))
provider_blueprint = manager.create_api(Provider,
                                        methods=['GET', 'DELETE', 'PATCH', 'POST'],
                                        collection_name='provider',
                                        url_prefix='/v1',
                                        max_results_per_page=300,
                                        preprocessors=dict(POST=[authn_func]))
session_blueprint = manager.create_api(Session, methods=['POST'],
                                       collection_name='session',
                                       url_prefix='/v1',
                                       preprocessors=dict(POST=[create_session]),
                                       postprocessors=dict(POST=[perform_login]))
user_blueprint = manager.create_api(User,
                                    methods=['GET', 'PATCH', 'POST'],
コード例 #38
0
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from flask import g, make_response, redirect
from flask_restless import APIManager
from werkzeug.wrappers import Response

from veripeditus.server.app import APP, DB
from veripeditus.server.model import *
from veripeditus.server.util import guess_mime_type

_INCLUDE = ['id', 'uuid', 'created', 'updated']

MANAGER = APIManager(APP, flask_sqlalchemy_db=DB)

MANAGER.create_api(User,
                   include_columns=_INCLUDE+['username', 'email', 'players',
                                             'players.name', 'players.longitude',
                                             'players.latitude', 'players.avatar', 'current_player'])


MANAGER.create_api(Game, include_columns=_INCLUDE+['package', 'name', 'version',
                                                   'description', 'author',
                                                   'license'])
# FIXME make this API method less special
@APP.route("/api/game/<int:id_>/world_create")
def _world_create(id_):
    return Game.query.get(id_).world_create()

MANAGER.create_api(World, include_columns=_INCLUDE+['name', 'game', 'enabled'])
# FIXME make this API method less special
@APP.route("/api/world/<int:id_>/player_join")
def _world_join(id_):
コード例 #39
0
ファイル: web_dev.py プロジェクト: sotdjin/PicFood
    password = Column(Text, unique=False)
    user_preference = Column(Text, unique=False)

    def __init__(self, username, password, user_preference):
        self.username = username
        self.password = password
        self.user_preference = user_preference

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()


api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(User, methods=['GET', 'POST', 'DELETE', 'PUT'])


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


@app.route('/signup', methods=['GET', 'POST'])
def signup():
    error = None
    if request.method == 'POST':
        _username = request.form['username']
        _password = request.form['password']
        if db.session.query(User).filter(User.username == _username).scalar() is None:
            new_user = User(_username, _password, " ")
コード例 #40
0

class PersonSerializer(MarshmallowSerializer):
    schema_class = PersonSchema


class PersonDeserializer(MarshmallowDeserializer):
    schema_class = PersonSchema


class ArticleSerializer(MarshmallowSerializer):
    schema_class = ArticleSchema


class ArticleDeserializer(MarshmallowDeserializer):
    schema_class = ArticleSchema


if __name__ == '__main__':
    db.create_all()
    manager = APIManager(app, flask_sqlalchemy_db=db)

    manager.create_api(Person, methods=['GET', 'POST'],
                       serializer_class=PersonSerializer,
                       deserializer_class=PersonDeserializer)
    manager.create_api(Article, methods=['GET', 'POST'],
                       serializer_class=ArticleSerializer,
                       deserializer_class=ArticleDeserializer)

    app.run()
コード例 #41
0
ファイル: myrestless.py プロジェクト: gloria22/introduction
# -*- coding: utf8 -*-
from flask_restless import APIManager, ProcessingException
from .. import app, db
from ..models.Computermodel import Computer
from flask import request


def req_check(*args, **kwargs):
    if request.path.split("/")[-1].encode('utf-8').isdigit():
        raise ProcessingException(description="get single", code=400)
    else:
        pass


manager = APIManager(app=app,
                     flask_sqlalchemy_db=db,
                     preprocessors=dict(GET_SINGLE=[req_check],
                                        GET_MANY=[req_check]))
manager.create_api(Computer, methods=['GET', 'POST', 'DELETE', 'PUT'])
コード例 #42
0
    user = user_datastore.find_user(id=payload['identity'])
    return user


jwt = JWT(app, authenticate, load_user)

# Flask-Restless API  =========================================================
@jwt_required()
def auth_func(**kw):
    pass


apimanager = APIManager(app, flask_sqlalchemy_db=db)
apimanager.create_api(SomeStuff,
    methods=['GET', 'POST', 'DELETE', 'PUT'],
    url_prefix='/api/v1',
    collection_name='free_stuff',
    include_columns=['id', 'data1', 'data2', 'user_id'])
apimanager.create_api(SomeStuff,
    methods=['GET', 'POST', 'DELETE', 'PUT'],
    url_prefix='/api/v1',
    preprocessors=dict(GET_SINGLE=[auth_func], GET_MANY=[auth_func]),
    collection_name='protected_stuff',
    include_columns=['id', 'data1', 'data2', 'user_id'])


# Setup Admin  ================================================================
init_admin()


# Bootstrap  ==================================================================
コード例 #43
0
ファイル: __init__.py プロジェクト: cjh5414/jihungram
def initRestlessApi(app):
    manager = APIManager(app, flask_sqlalchemy_db=DBManager.db)
    manager.create_api(User, methods=['GET', 'POST', 'DELETE'])
    manager.create_api(Article, methods=['GET', 'POST', 'DELETE'])
コード例 #44
0
api_manager = APIManager(app, flask_sqlalchemy_db=db)


# Step 3: create the database model.
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode)


# Step 4: create the database and add some test people.
db.create_all()
for i in range(1, 10):
    name = u'person{0}'.format(i)
    person = Person(name=name)
    db.session.add(person)
db.session.commit()
print(Person.query.all())


# Step 5: create endpoints for the application.
@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')


# Step 6: create the API endpoints.
api_manager.create_api(Person, methods=['GET', 'POST'])

# Step 7: run the application.
app.run()
コード例 #45
0
class SwagAPIManager(object):
    swagger = {
        'swagger': '2.0',
        'info': {},
        'schemes': ['http', 'https'],
        'basePath': '/api',
        'consumes': ['application/json'],
        'produces': ['application/json'],
        'paths': {},
        'definitions': {},
        'tags': []
    }

    def __init__(self, app=None, **kwargs):
        self.app = None
        self.manager = None

        if app is not None:
            self.init_app(app, **kwargs)

    def to_json(self, **kwargs):
        return json.dumps(self.swagger, **kwargs)

    def to_yaml(self, **kwargs):
        return yaml.dump(self.swagger, **kwargs)

    def __str__(self):
        return self.to_json(indent=4)

    @property
    def version(self):
        if 'version' in self.swagger['info']:
            return self.swagger['info']['version']
        return None

    @version.setter
    def version(self, value):
        self.swagger['info']['version'] = value

    @property
    def title(self):
        if 'title' in self.swagger['info']:
            return self.swagger['info']['title']
        return None

    @title.setter
    def title(self, value):
        self.swagger['info']['title'] = value

    @property
    def description(self):
        if 'description' in self.swagger['info']:
            return self.swagger['info']['description']
        return None

    @description.setter
    def description(self, value):
        self.swagger['info']['description'] = value

    def add_path(self, model, **kwargs):
        name = model.__tablename__
        schema = model.__name__
        path = kwargs.get('url_prefix', "") + '/' + name
        id_path = "{0}/{{{1}Id}}".format(path, schema.lower())
        self.swagger['paths'][path] = {}
        self.swagger['tags'].append({'name': schema})
        for method in [m.lower() for m in kwargs.get('methods', ['GET'])]:
            if method == 'get':
                self.swagger['paths'][path][method] = {
                    'tags': [schema],
                    'parameters': [{
                        'name': 'q',
                        'in': 'query',
                        'description': 'searchjson',
                        'type': 'string'
                    }],
                    'operationId':
                    '{0}{1}-{2}'.format(method, name.capitalize(),
                                        uuid.uuid4()),
                    'responses': {
                        200: {
                            'description': 'List ' + name,
                            'schema': {
                                'title': name,
                                'type': 'array',
                                'items': {
                                    '$ref': '#/definitions/' + schema
                                }
                            }
                        }
                    }
                }

                #if model.__doc__:
                #    self.swagger['paths'][path]['description'] = model.__doc__
                if id_path not in self.swagger['paths']:
                    self.swagger['paths'][id_path] = {}
                self.swagger['paths'][id_path][method] = {
                    'tags': [schema],
                    'parameters': [{
                        'name': schema.lower() + 'Id',
                        'in': 'path',
                        'description': 'ID of ' + schema,
                        'required': True,
                        'type': 'integer'
                    }],
                    'operationId':
                    '{0}{1}-{2}'.format(method, name.capitalize(),
                                        uuid.uuid4()),
                    'responses': {
                        200: {
                            'description': 'Success ' + name,
                            'schema': {
                                'title': name,
                                '$ref': '#/definitions/' + schema
                            }
                        }
                    }
                }
                #if model.__doc__:
                #    self.swagger['paths'][id_path]['description'] = model.__doc__
            elif method == 'delete':
                if id_path not in self.swagger['paths']:
                    self.swagger['paths'][id_path] = {}
                self.swagger['paths']["{0}/{{{1}Id}}".format(
                    path, schema.lower())][method] = {
                        'tags': [schema],
                        'parameters': [{
                            'name': schema.lower() + 'Id',
                            'in': 'path',
                            'description': 'ID of ' + schema,
                            'required': True,
                            'type': 'integer'
                        }],
                        'operationId':
                        '{0}{1}-{2}'.format(method, name.capitalize(),
                                            uuid.uuid4()),
                        'responses': {
                            200: {
                                'description': 'Success'
                            }
                        }
                    }
                #if model.__doc__:
                #    self.swagger['paths'][id_path]['description'] = model.__doc__
            else:
                self.swagger['paths'][path][method] = {
                    'tags': [schema],
                    'parameters': [{
                        'name': name,
                        'in': 'body',
                        'description': schema,
                        'required': True,
                        'schema': {
                            "$ref": "#/definitions/" + schema
                        }
                    }],
                    'operationId':
                    '{0}{1}-{2}'.format(method, name.capitalize(),
                                        uuid.uuid4()),
                    'responses': {
                        200: {
                            'description': 'Success'
                        }
                    }
                }
                #if model.__doc__:
                #    self.swagger['paths'][path]['description'] = model.__doc__

    def add_defn(self, model, **kwargs):
        name = model.__name__
        self.swagger['definitions'][name] = {
            'type': 'object',
            'properties': {}
        }
        columns = get_columns(model).keys()
        for column_name, column in get_columns(model).items():
            if column_name in kwargs.get('exclude_columns', []):
                continue
            try:
                column_type = str(column.type)
                if '(' in column_type:
                    column_type = column_type.split('(')[0]
                column_defn = sqlalchemy_swagger_mapping[column_type]
            except AttributeError:
                schema = get_related_model(model, column_name)
                if column_name + '_id' in columns:
                    column_defn = {'schema': {'$ref': schema.__name__}}
                else:
                    column_defn = {
                        'schema': {
                            'type': 'array',
                            'items': {
                                '$ref': schema.__name__
                            }
                        }
                    }

            # if column.__doc__:
            #     column_defn['description'] = column.__doc__
            self.swagger['definitions'][name]['properties'][
                column_name] = column_defn

    def init_app(self, app, **kwargs):
        self.app = app
        self.manager = APIManager(self.app, **kwargs)

        swagger = Blueprint(
            'swagger',
            __name__,
            static_folder='static',
            static_url_path=self.app.static_url_path + '/swagger',
        )

        @swagger.route('/swagger')
        def swagger_ui():
            return redirect('/static/swagger/swagger-ui/index.html')

        @swagger.route('/swagger.json')
        def swagger_json():
            # I can only get this from a request context
            if not self.swagger['host']:
                self.swagger['host'] = urlparse.urlparse(
                    request.url_root).netloc
            return jsonify(self.swagger)

        @swagger.route('/swagger.yaml')
        def swagger_yaml():
            # I can only get this from a request context
            if not self.swagger['host']:
                self.swagger['host'] = urlparse.urlparse(
                    request.url_root).netloc
            return self.to_yaml()

        app.register_blueprint(swagger)

    def create_api(self, model, **kwargs):
        self.manager.create_api(model, **kwargs)
        self.add_defn(model, **kwargs)
        self.add_path(model, **kwargs)

    def swagger_blueprint(self):
        return swagger
コード例 #46
0
ファイル: server.py プロジェクト: ldp940622/netease-crawler
app = Flask(__name__)
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:root@localhost:3306/test1'
db = SQLAlchemy(app)
restless = APIManager(app, flask_sqlalchemy_db=db)


class User(db.Model):

    """
    user
    """

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(255), unique=True, nullable=False)
    password = db.Column(db.String(255), nullable=False)
    content = db.Column(db.String(255), nullable=False)


restless.create_api(
    User, methods=['GET', 'POST', 'DELETE',
                   'PATCH', 'PUT'], results_per_page=100)

db.create_all()

if __name__ == '__main__':
    # session = db.session()
    # session.add(User(id=1, username='******', password='******'))
    # session.commit()
    app.run(port=20000)
コード例 #47
0
ファイル: BbAdminApp.py プロジェクト: elmiguel/bbadmin-python
login_manager.init_app(app)

cors = CORS(app, allow_headers=[Authorization])

loopback = FlaskLoopback(app)

from views import *
from models import *

api_manager = APIManager(
    app,
    flask_sqlalchemy_db=db,
    preprocessors=dict(
        # GET=[auth_func], GET_SINGLE=[auth_func], GET_MANY=[auth_func],
        POST=[auth_func],
        POST_SINGLE=[auth_func],
        POST_MANY=[auth_func],
        PATCH=[auth_func],
        PATCH_SINGLE=[auth_func],
        PATCH_MANY=[auth_func],
        DELETE=[auth_func],
        DELETE_SINGLE=[auth_func],
        DELETE_MANY=[auth_func]))

api_manager.create_api(User,
                       methods=['GET', 'POST', 'PATCH', 'DELETE'],
                       exclude_columns=['password'],
                       postprocessors=dict(GET=[get_postprocessor],
                                           GET_SINGLE=[get_postprocessor],
                                           GET_MANY=[get_postprocessor]))
コード例 #48
0
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, Text

app = Flask(__name__, static_url_path='')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bookmarks.db'
db = SQLAlchemy(app)


class Bookmark(db.Model):
    id = Column(Integer, primary_key=True)
    title = Column(Text, unique=False)
    content = Column(Text, unique=False)


db.create_all()

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Bookmark, methods=['GET', 'POST', 'DELETE', 'PUT'])


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


# app.debug = True

if __name__ == '__main__':
    app.run()
コード例 #49
0
ファイル: api.py プロジェクト: jihwanyoon/bible-in-the-cloud
from models import *
from flask_restless import APIManager
from app import *

manager = APIManager(app, flask_sqlalchemy_db=db)

manager.create_api(Language)
manager.create_api(Book)
manager.create_api(DisplayName)
manager.create_api(Verses)
manager.create_api(Version)

if __name__ == "__main__":
    app.run(debug=True)
コード例 #50
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_restless import APIManager

app = Flask(__name__)

if os.path.exists(os.path.join(os.getcwd(), "config.py")):
    app.config.from_pyfile(os.path.join(os.getcwd(), "config.py"))
else:
    app.config.from_pyfile(os.path.join(os.getcwd(), "config.env.py"))

# Create the database session and import models.
db = SQLAlchemy(app)
from packet.models import *

migrate = Migrate(app, db)

# Initialize the Restless API manager
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Freshman, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Packet,
                   methods=['GET', 'POST', 'PUT', 'DELETE'],
                   include_methods=['signatures_req', 'signatures_total'])


@app.route('/')
def hello_world():
    return 'Hello, World!'
コード例 #51
0
ファイル: __init__.py プロジェクト: e-henry/scripto
    status = db.Column(db.Boolean)
    server = db.Column(db.String())
    last_exec = db.Column(db.DateTime)
    periodicity = db.Column(db.String())

    def __init__(self, name, status, server, last_exec, periodicity):
        self.name = name
        self.status = status
        self.server = server
        self.last_exec = last_exec
        self.periodicity = periodicity

    def __repr__(self):
        return "<Script %r>" % self.name


@app.route("/")
def root():
    scripts = Script.query.order_by("status").order_by("last_exec").all()
    return render_template("index.html", scripts=scripts)


# Rest api for script table
manager.create_api(Script,
                   url_prefix="/api/v1",
                   methods=["GET", "POST", "PUT", "DELETE", "PATCH"])

if __name__ == "__main__":
    db.create_all()  # make our sqlalchemy tabless
    app.run(port=5000, debug=True)
コード例 #52
0
ファイル: server.py プロジェクト: TaioSolve/licengine
    user = user_datastore.find_user(id=payload['identity'])
    return user


jwt = JWT(app, authenticate, load_user)


@jwt_required()
def auth_func(**kw):
    pass


apimanager = APIManager(app, flask_sqlalchemy_db=db)
apimanager.create_api(SomeStuff,
                      methods=['GET', 'POST', 'DELETE', 'PUT'],
                      url_prefix='/api/v1',
                      collection_name='free_stuff',
                      include_columns=['id', 'data1', 'data2', 'user_id'])
apimanager.create_api(SomeStuff,
                      methods=['GET', 'POST', 'DELETE', 'PUT'],
                      url_prefix='/api/v1',
                      preprocessors=dict(GET_SINGLE=[auth_func],
                                         GET_MANY=[auth_func]),
                      collection_name='protected_stuff',
                      include_columns=['id', 'data1', 'data2', 'user_id'])

init_admin()

if __name__ == '__main__':
    db.init_app(app)
    with app.context():
コード例 #53
0
from flask_restless import APIManager

# App configuration
app = Flask(__name__, instance_relative_config=True)
dburl = "{DBMS}://{DB_USER}:{DB_PASSWORD}@db/{DB_NAME}".format(**os.environ)
app.config['SQLALCHEMY_DATABASE_URI'] = dburl
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


# Model
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, unique=True)

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


# Test data
if os.environ['TEST_MODE'] == 'true':
    db.create_all()
    db.session.add(Person("Clement"))
    db.session.commit()

# REST service
location = '/api'
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Person,
                   url_prefix=location,
                   methods=['GET', 'POST', 'DELETE'])
コード例 #54
0
ファイル: __init__.py プロジェクト: SteaI/EverMeal_Web
def initRestlessApi(app):
    manager = APIManager(app, flask_sqlalchemy_db=DBManager.db)
    manager.create_api(User, methods=['POST'])
    manager.create_api(User, methods=['GET'], include_columns=['sid', 'username', 'email'])

    # manager.create_api(Gcm, methods=['POST'])

    manager.create_api(Allergy, methods=['GET', 'POST', 'DELETE'])
    manager.create_api(Provider, methods=['GET', 'POST', 'DELETE'])

    manager.create_api(ProviderInfo, methods=['GET'])
    manager.create_api(Neis, methods=['GET'])

    manager.create_api(Article, methods=['GET'])
    manager.create_api(Rate, methods=['POST'])
コード例 #55
0
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    name = db.Column(db.Unicode, nullable=False)
    description = db.Column(db.Unicode, nullable=False)


class Action_groups(SearchableMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    name = db.Column(db.Unicode, nullable=False)
    url = db.Column(db.Unicode, nullable=False)
    type = db.Column(db.Unicode, nullable=False)
    desc = db.Column(db.Unicode, nullable=False)


manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Politicians,
                   methods=['GET'],
                   preprocessors={'GET_MANY': [Politicians.get_pre_handler()]},
                   results_per_page=12)
manager.create_api(Laws,
                   methods=['GET'],
                   preprocessors={'GET_MANY': [Laws.get_pre_handler()]},
                   results_per_page=12)
manager.create_api(Affected_groups, methods=['GET'], results_per_page=12)
manager.create_api(
    Action_groups,
    methods=['GET'],
    preprocessors={'GET_MANY': [Action_groups.get_pre_handler()]},
    results_per_page=12)

app.run(host='0.0.0.0', debug=True)
コード例 #56
0
db = SQLAlchemy(app)
api_manager = APIManager(app, flask_sqlalchemy_db=db)


# Step 3: create the database model.
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode)


# Step 4: create the database and add some test people.
db.create_all()
for i in range(1, 10):
    name = u'person{0}'.format(i)
    person = Person(name=name)
    db.session.add(person)
db.session.commit()
print(Person.query.all())


# Step 5: create endpoints for the application.
@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

# Step 6: create the API endpoints.
api_manager.create_api(Person, methods=['GET', 'POST'])

# Step 7: run the application.
app.run()
コード例 #57
0
    whooshalchemy.whoosh_index(app, model)

# Create the Flask-Restless API manager.
manager = APIManager(app, flask_sqlalchemy_db=db)

# Flask-Restless config
kwargs = {
    'methods': frozenset(['GET', 'POST', 'PATCH']),
    'allow_functions': True,
    'results_per_page': 6
}

# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
for model in models_list:
    manager.create_api(model, **kwargs)


# Search endpoint template, fill in model to create response for that model
def make_search_response(model):
    search_query = request.args.get('query')
    q = model.query.whoosh_search(search_query)
    # Use Flask-restless' mechanism for generating responses from SQLAlchemy models
    api = API(db.session, model)
    deep = dict((r, {}) for r in get_relations(model))
    return jsonify(api._paginated(q, deep))


@app.route('/api/search/actor')
def search_actor():
    return make_search_response(Actor)
コード例 #58
0
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, Text

app = Flask(__name__, static_url_path='')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pin.db'
db = SQLAlchemy(app)


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


class Pin(db.Model):
    id = Column(Integer, primary_key=True)
    title = Column(Text, unique=False)
    image = Column(Text, unique=False)


db.create_all()

app.debug = True

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Pin, methods=['GET', 'POST', 'DELETE', 'PUT'])

if __name__ == '__main__':
    app.run()
コード例 #59
0
        username, password = form.username.data, form.password.data
        matches = User.query.filter_by(username=username,
                                       password=password).all()
        if len(matches) > 0:
            login_user(matches[0])
            return redirect(url_for('index'))
        flash('Username and password pair not found')
    return render_template('login.html', form=form)


# Step 8: create the API for User with the authentication guard.
def auth_func(**kw):
    if not current_user.is_authenticated():
        raise ProcessingException(description='Not Authorized', code=401)


api_manager.create_api(User, preprocessors=dict(GET_SINGLE=[auth_func],
                                                GET_MANY=[auth_func]))

# Step 9: configure and run the application
app.run()

# Step 10: visit http://localhost:5000/api/user in a Web browser. You will
# receive a "Not Authorized" response.
#
# Step 11: visit http://localhost:5000/login and enter username "example" and
# password "example". You will then be logged in.
#
# Step 12: visit http://localhost:5000/api/user again. This time you will get a
# response showing the objects in the User table of the database.
コード例 #60
0
ファイル: __init__.py プロジェクト: rpazyaquian/apptrack
__author__ = 'rebecca'

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_restless import APIManager
from models import db, User


app = Flask(__name__)
Bootstrap(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db.init_app(app)

with app.test_request_context():
    db.create_all()

manager = APIManager(app, flask_sqlalchemy_db=db)

user_blueprint = manager.create_api(User, methods=['GET', 'POST'])

login_manager = LoginManager()
login_manager.init_app(app)


import apptrack.views