示例#1
0
文件: api.py 项目: coyotevz/spl
def configure_api(app):
    manager = APIManager(app, flask_sqlalchemy_db=db)

    exclude = ['documents', 'orders', 'supplier_contacts']

    manager.create_api(Supplier, collection_name='suppliers',
                       exclude_columns=exclude)
 def test_creation_api_without_app_dependency(self):
     """Tests that api can be added before app will be passed to manager."""
     manager = APIManager()
     manager.create_api(self.Person)
     manager.init_app(self.flaskapp, self.session)
     response = self.app.get('/api/person')
     assert response.status_code == 200
示例#3
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
示例#4
0
class TestFlaskSqlalchemy(FlaskTestBase):
    """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()
        self.db = SQLAlchemy(self.flaskapp)
        self.session = self.db.session

        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 teardown(self):
        """Drops all tables and unregisters Flask-SQLAlchemy session signals.

        """
        self.db.drop_all()
        unregister_fsa_session_signals()

    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
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
示例#6
0
    def test_create_api_for_model_collections(self):
        """Test for read access to model foreign keys

        """
        mary = self.Person(name=u'Mary', age=19, other=19)
        pc = self.Computer(name=u'PC', vendor=u'Noname')
        pc.owner.append(mary)
        laptop = self.Computer(name=u'Lappy', vendor=u'Dell')
        laptop.owner.append(mary)
        self.session.add_all([mary, pc, laptop])
        self.session.commit()

        manager = APIManager(self.flaskapp, session=self.Session)
        manager.create_api(self.Person, methods=['GET'])
        manager.create_api(self.Computer, methods=['GET'])

        # test that collection endpoints are present
        response = self.app.get('/api/person/'+str(mary.id)+'/computers/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(loads(response.data)['objects']), 2)
        # test that not existing collection endpoint returns HTTP 404
        response = self.app.get('/api/person/'+str(mary.id)+'/parents/')
        self.assertEqual(response.status_code, 404)

        # access is setup for child relations only, master cannot be accessed this way
        response = self.app.get('/api/computer/'+str(pc.id)+'/owner/')
        self.assertEqual(response.status_code, 404)
        # also plain attributes cannot be accessed this way
        response = self.app.get('/api/person/'+str(mary.id)+'/name/')
        self.assertEqual(response.status_code, 404)
        response = self.app.get('/api/computer/'+str(pc.id)+'/owner_id/')
        self.assertEqual(response.status_code, 404)
    def test_universal_preprocessor(self):
        """Tests universal preprocessor and postprocessor applied to all
        methods created with the API manager.

        """
        class Counter(object):
            def __init__(s):
                s.count = 0

            def increment(s):
                s.count += 1

            def __eq__(s, o):
                return s.count == o.count if isinstance(o, Counter) \
                    else s.count == o
        precount = Counter()
        postcount = Counter()

        def preget(**kw):
            precount.increment()

        def postget(**kw):
            postcount.increment()

        manager = APIManager(self.flaskapp, self.session,
                             preprocessors=dict(GET_MANY=[preget]),
                             postprocessors=dict(GET_MANY=[postget]))
        manager.create_api(self.Person)
        manager.create_api(self.Computer)
        self.app.get('/api/person')
        self.app.get('/api/computer')
        self.app.get('/api/person')
        assert precount == postcount == 3
示例#8
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
示例#9
0
    def load_endpoint(self, Module):
        r"""Load a single module endpoint.

        Given a module name, locate the `endpoint.py` file, and instantiate a
        new Flask Restless compatible endpoint accorindg to the settings
        contained within the `endpoint.py` file.

        :param object self: The Application class
        :param object Module: The of module containing endpoint

        See the official Flask Restless documentation for more information
        https://flask-restless.readthedocs.org/en/latest/api.html#\
        flask.ext.restless.APIManager.create_api
        """
        manager = APIManager(self.app, flask_sqlalchemy_db=db)

        if hasattr(Module, 'endpoints'):
            if hasattr(Module, 'Model'):
                Seed_ = Module.endpoints.Seed()
                manager.create_api(Module.Model, **Seed_.__arguments__)
                logger.info('`%s` module endpoints loaded' %
                            (Module.__name__))
            else:
                logger.error('`%s` module has endpoints, but is missing '
                             'Model' % (Module.__name__))
        else:
            logger.info('`%s` module did not contain any endpoints.' %
                        (Module.__name__))
示例#10
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'
示例#11
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
示例#12
0
    def test_init_app(self):
        """Tests for initializing the Flask application after instantiating the
        :class:`flask.ext.restless.APIManager` object.

        """
        manager = APIManager()
        manager.init_app(self.flaskapp, session=self.session)
        manager.create_api(self.Person, app=self.flaskapp)
        response = self.app.get('/api/person')
        assert response.status_code == 200
示例#13
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
示例#14
0
def create_api(app):
    prefix = '/api/v0'

    api_manager = APIManager(app, flask_sqlalchemy_db=db)

    api = ((AnalysisTbl, 'analysis', {'methods': ['GET']}),
           (IrradiationPositionTbl, 'iposition', {'methods': ['GET']}),
           (IrradiationTbl, 'irradiation', {'methods': ['GET']}),
           (LevelTbl, 'level',  {'methods': ['GET']}),
           (ProductionTbl, 'production',  {'methods': ['GET']}))
    for table, cname, kw in api:
        api_manager.create_api(table, collection_name=cname, url_prefix=prefix,  **kw)
示例#15
0
文件: api.py 项目: oyang/testFalsk
def create_api(app, db):
    api_manager = APIManager(app, flask_sqlalchemy_db=db)
    allowed_methods = ['GET', 'POST', 'PUT', 'DELETE']

    for module_name in modules.__all__:
        module = getattr(modules, module_name)

        # override existing the default allowed_methods if exists
        if hasattr(module, 'allowed_methods'):
            allowed_methods = getattr(modules, 'allowed_methods')

        api_manager.create_api(module, methods=allowed_methods)
示例#16
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
示例#17
0
    def test_session_class(self):
        """Test for providing a session class instead of a sesssion instance.

        """
        manager = APIManager(self.flaskapp, session=self.Session)
        manager.create_api(self.Person, methods=["GET", "POST"])
        response = self.app.get("/api/person")
        self.assertEqual(response.status_code, 200)
        response = self.app.post("/api/person", data=dumps(dict(name="foo")))
        self.assertEqual(response.status_code, 201)
        response = self.app.get("/api/person/1")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(loads(response.data)["id"], 1)
示例#18
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')
        response = self.app.get('/bar/person')
        assert response.status_code == 200
        response = self.app.get('/foo/person')
        assert response.status_code == 404
示例#19
0
    def test_session_class(self):
        """Test for providing a session class instead of a sesssion instance.

        """
        manager = APIManager(self.flaskapp, session=self.Session)
        manager.create_api(self.Person, methods=['GET', 'POST'])
        response = self.app.get('/api/person')
        self.assertEqual(response.status_code, 200)
        response = self.app.post('/api/person', data=dumps(dict(name='foo')))
        self.assertEqual(response.status_code, 201)
        response = self.app.get('/api/person/1')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(loads(response.data)['id'], 1)
示例#20
0
 def test_url_for(self):
     manager = APIManager(self.flaskapp, session=self.session)
     manager.create_api(self.Person, collection_name='people')
     manager.create_api(self.Computer, collection_name='computers')
     with self.flaskapp.app_context():
         url = url_for(self.Computer)
         assert url.endswith('/api/computers')
         assert url_for(self.Person).endswith('/api/people')
         assert url_for(self.Person, instid=1).endswith('/api/people/1')
         url = url_for(self.Person, instid=1, relationname='computers')
         assert url.endswith('/api/people/1/computers')
         url = url_for(self.Person, instid=1, relationname='computers',
                       relationinstid=2)
         assert url.endswith('/api/people/1/computers/2')
示例#21
0
文件: restapi.py 项目: bjourne/vvm
def setup_api(app, db):
    manager = APIManager(app, flask_sqlalchemy_db=db)
    manager.create_api(
        Score,
        preprocessors={"DELETE": [score_pre_delete], "PATCH_SINGLE": [score_pre_patch], "POST": [score_pre_post]},
        postprocessors={"PATCH_SINGLE": [post_post], "POST": [post_post]},
        methods=["DELETE", "GET", "PATCH", "POST", "PUT"],
    )
    manager.create_api(
        User,
        methods=["GET"],
        postprocessors={"GET_MANY": [user_post_get_many], "GET_SINGLE": [filter_user]},
        max_results_per_page=None,
    )
示例#22
0
    def setUp(self):
        """Creates the database, the :class:`~flask.Flask` object, the
        :class:`~flask_restless.manager.APIManager` for that application, and
        creates the ReSTful API endpoints for the :class:`testapp.Person` and
        :class:`testapp.Computer` models.

        """
        # create the database
        self.db_fd, self.db_file = mkstemp()
        setup(create_engine('sqlite:///%s' % self.db_file))
        create_all()

        # create the Flask application
        app = flask.Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        self.app = app.test_client()

        # setup the URLs for the Person and Computer API
        self.manager = APIManager(app)
        self.manager.create_api(Person, methods=['GET', 'PATCH', 'POST',
                                                 'DELETE'])
        self.manager.create_api(Computer, methods=['GET', 'POST'])

        # to facilitate searching
        self.app.search = lambda url, q: self.app.get(url + '?q={}'.format(q))
示例#23
0
文件: webif.py 项目: mrowl/putio-sync
    def __init__(self, db_manager, download_manager):
        self.app = flask.Flask(__name__)
        self.db_manager = db_manager
        self.api_manager = APIManager(self.app, session=self.db_manager.get_db_session())
        self.download_manager = download_manager
        self._rate_tracker = DownloadRateTracker()

        def include_datetime(result):
            print result

        self.download_record_blueprint = self.api_manager.create_api(
            DownloadRecord,
            methods=['GET'],
            postprocessors={
                "GET_MANY": [include_datetime]
            })

        # filters
        self.app.jinja_env.filters["prettysize"] = self._pretty_size

        # urls
        self.app.add_url_rule("/", view_func=self._view_active)
        self.app.add_url_rule("/active", view_func=self._view_active)
        self.app.add_url_rule("/history", view_func=self._view_history)
        self.app.add_url_rule("/download_queue", view_func=self._view_download_queue)
        self.app.add_url_rule("/history/page/<int:page>", view_func=self._view_history)
示例#24
0
    def setUp(self):
        """Creates the Flask application, the APIManager, the database, and the
        Flask-SQLAlchemy models.

        """
        super(TestFSA, self).setUp()

        # initialize SQLAlchemy and Flask-Restless
        self.db = SQLAlchemy(self.flaskapp)
        self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)

        # for the sake of brevity...
        db = self.db

        # declare the models
        class Computer(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            name = db.Column(db.Unicode, unique=True)
            vendor = db.Column(db.Unicode)
            buy_date = db.Column(db.DateTime)
            owner_id = db.Column(db.Integer, db.ForeignKey("person.id"))
            owner = db.relationship("Person", backref=db.backref("computers", lazy="dynamic"))

        class Person(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            name = db.Column(db.Unicode, unique=True)
            age = db.Column(db.Float)
            other = db.Column(db.Float)
            birth_date = db.Column(db.Date)

        self.Person = Person
        self.Computer = Computer

        # create all the tables required for the models
        self.db.create_all()
示例#25
0
    def __init__(self, db_manager, download_manager, putio_client, synchronizer):
        self.app = flask.Flask(__name__)
        self.synchronizer = synchronizer
        self.db_manager = db_manager
        self.api_manager = APIManager(self.app, session=self.db_manager.get_db_session())
        self.download_manager = download_manager
        self.putio_client = putio_client
        self.transmission_rpc_server = TransmissionRPCServer(putio_client, self.synchronizer)
        self._rate_tracker = DownloadRateTracker()

        self.app.logger.setLevel(logging.DEBUG)

        def include_datetime(result):
            print result

        self.download_record_blueprint = self.api_manager.create_api(
            DownloadRecord,
            methods=['GET'],
            postprocessors={
                "GET_MANY": [include_datetime]
            })

        # filters
        self.app.jinja_env.filters["prettysize"] = self._pretty_size

        # urls
        self.app.add_url_rule("/", view_func=self._view_active)
        self.app.add_url_rule("/active", view_func=self._view_active)
        self.app.add_url_rule("/history", view_func=self._view_history)
        self.app.add_url_rule("/download_queue", view_func=self._view_download_queue)
        self.app.add_url_rule("/history/page/<int:page>", view_func=self._view_history)
        self.app.add_url_rule("/transmission/rpc", methods=['POST', 'GET', ],
                              view_func=self.transmission_rpc_server.handle_request)
示例#26
0
    def test_create_api_before_db_create_all(self):
        """Tests that we can create APIs before
        :meth:`flask.ext.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']
示例#27
0
class TestFlaskSqlalchemy(FlaskTestBase):
    """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)
        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 teardown(self):
        """Drops all tables and unregisters Flask-SQLAlchemy session signals.

        """
        self.db.drop_all()
        unregister_fsa_session_signals()

    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'
示例#28
0
    def test_multiple_app_delayed_init(self):
        manager = 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_json_contenttype(testclient2)

        # First create the API, then initialize the Flask applications after.
        manager.create_api(self.Person, app=flaskapp1)
        manager.create_api(self.Computer, app=flaskapp2)
        manager.init_app(flaskapp1)
        manager.init_app(flaskapp2)

        # Tests that only the first Flask application gets requests for
        # /api/person and only the second gets requests for /api/computer.
        response = testclient1.get('/api/person')
        assert response.status_code == 200
        response = testclient1.get('/api/computer')
        assert response.status_code == 404
        response = testclient2.get('/api/person')
        assert response.status_code == 404
        response = testclient2.get('/api/computer')
        assert response.status_code == 200
示例#29
0
    def test_flask_sqlalchemy(self):
        """Tests that :class:`flask.ext.restless.APIManager` correctly exposes
        models defined using Flask-SQLAlchemy.

        """
        manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)

        # create three different APIs for the same model
        manager.create_api(self.Person, methods=['GET', 'POST'])
        manager.create_api(self.Person, methods=['PATCH'], url_prefix='/api2')
        manager.create_api(self.Person, methods=['GET'],
                           url_prefix='/readonly')

        # test that specified endpoints exist
        response = self.app.post('/api/person', data=dumps(dict(name='foo')))
        assert response.status_code == 201
        assert loads(response.data)['id'] == 1
        response = self.app.get('/api/person')
        assert response.status_code == 200
        assert len(loads(response.data)['objects']) == 1
        assert loads(response.data)['objects'][0]['id'] == 1
        response = self.app.patch('/api2/person/1',
                                  data=dumps(dict(name='bar')))
        assert response.status_code == 200
        assert loads(response.data)['id'] == 1
        assert loads(response.data)['name'] == 'bar'

        # test that the model is the same as before
        response = self.app.get('/readonly/person')
        assert response.status_code == 200
        assert len(loads(response.data)['objects']) == 1
        assert loads(response.data)['objects'][0]['id'] == 1
        assert loads(response.data)['objects'][0]['name'] == 'bar'
示例#30
0
def init_webapp():
  """Initialize the web application."""

  # logging.getLogger('flask_cors').level = logging.DEBUG
  # app.wsgi_app = LoggingMiddleware(app.wsgi_app)

  # Note, this url namespace also exists for the Flask-Restless
  # extension and is where CRUD interfaces live, so be careful not to
  # collide with model names here. We could change this, but it's nice
  # to have API live in the same url namespace.
  app.register_blueprint(api, url_prefix='/api')

  # Initialize Flask configuration
  app.config['SQLALCHEMY_DATABASE_URI'] = make_conn_str()
  app.config['SECRET_KEY'] = 'abc123'
  app.config['WTF_CSRF_ENABLED'] = False
  app.config['SECURITY_TOKEN_MAX_AGE'] = 60
  app.config['SECURITY_TOKEN_AUTHENTICATION_HEADER'] = 'Auth-Token'
  # app.config['SECURITY_POST_LOGIN_VIEW'] = 'http://127.0.0.1:4200'
  # app.config['CORS_HEADERS'] = 'Content-Type'

  # Initialize Flask-CORS
  CORS(app, supports_credentials=True)
  # CORS(app, supports_credentials=True, resources={r"/*": {"origins": "*"}})

  # Initialize Flask-Bootstrap
  Bootstrap(app)

  # Initialize Flask-Security
  user_datastore = SQLAlchemyUserDatastore(db, User, Role)
  security = Security(app, user_datastore)

  # Initialize Flask-SQLAlchemy
  db.app = app
  db.init_app(app)
  db.create_all()

  # Initialize Flask-Restless
  manager = APIManager(
    app,
    flask_sqlalchemy_db=db,
    preprocessors=dict(GET_MANY=[restless_api_auth_func]),
  )
  manager.create_api(Employee, methods=['GET', 'POST', 'OPTIONS'])
  return app
示例#31
0
    """Return json for 404 error"""
    return make_response(jsonify({'error': 'Not found'}), 404)


### HELPER FUNCTION ###


def to_dict(task):
    """Turn an employee object into a dictionary."""
    return {
        'id': task.task_id,
        'title': task.task_title,
        'description': task.task_description,
        'completed': task.task_completed,
        'uri': url_for('get_task', task_id=task.task_id, _external=True)
    }


if __name__ == '__main__':
    connect_to_db(app)

    manager = APIManager(app, flask_sqlalchemy_db=db)

    # Create API endpoints, which will be available at /api/<tablename> by
    # default. Allowed HTTP methods can be specified as well.

    manager.create_api(Tasks,
                       methods=['GET', 'POST', 'DELETE', 'PUT', 'PATCH'])

    app.run(debug=True)
示例#32
0
import os, re
from subprocess import Popen as run, PIPE
from StringIO import StringIO
from contextlib import closing
from Bio import AlignIO
from Bio.Align import MultipleSeqAlignment
from itertools import chain
import random
import multiprocessing
from zlib import compress
from base64 import b64encode
from autoupdate.core import Manager
from config import config
import string

manager = APIManager(app, flask_sqlalchemy_db=scoped_db)

for cls in classes:
    manager.create_api(cls, methods=['GET'])

thread_count = multiprocessing.cpu_count() * 2
print("Working with {:} threads.".format(thread_count))
api = Api(app)
lib_path = app.config['LIB_PATH']
root_path = Manager().actual_version_path()
fetch_call = '{:s}/hmmer/easel/miniapps/esl-afetch'.format(lib_path)
muscle_call = ('{:s}/muscle/src/muscle -maxiters 1 -diags1 -quiet -sv '
               '-distance1 kbit20_3').format(lib_path)
mafft_call = ('MAFFT_BINARIES={0} {0}/mafft --retree 2 --maxiterate 0 '
              '--thread {1} --quiet').format(lib_path + '/mafft/core',
                                             thread_count)
示例#33
0
 def test_init_app_split_initialization(self):
     manager = APIManager(session=self.session)
     manager.init_app(self.flaskapp)
     manager.create_api(self.Person, app=self.flaskapp)
     response = self.app.get('/api/person')
     assert response.status_code == 200
示例#34
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
示例#35
0
 def __init__(self, hostname, port, app):
     self.hostname = hostname
     self.port = port
     self.app = app
     self.apimanager = APIManager()
示例#36
0
文件: api.py 项目: jcmcken/penumbra
from flask.ext.restless import APIManager
from penumbra import app, db
from penumbra.models import Host, Datum
from penumbra.auth import AUTH_MECHANISM, AUTH_MAP

manager = APIManager(app, flask_sqlalchemy_db=db)

host_blueprint = manager.create_api(
    Host,
    methods=['GET', 'POST', 'DELETE'],
    exclude_columns=['data'],
    preprocessors={
        'GET_SINGLE': AUTH_MAP['GET_SINGLE'],
        'GET_MANY': AUTH_MAP['GET_MANY'],
    },
)
datum_blueprint = manager.create_api(
    Datum,
    exclude_columns=['_value', 'key', 'host'],
)
示例#37
0
    def test_missing_session(self):
        """Tests that setting neither a session nor a Flask-SQLAlchemy
        object yields an error.

        """
        APIManager(app=self.flaskapp)
示例#38
0
from app.helpers.restricted_admin import RestrictedAdminIndexView
from flask import Flask
from flask.ext.admin import Admin
from flask.ext.login import LoginManager
from flask.ext.restless import APIManager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

api_manager = APIManager(app, flask_sqlalchemy_db=db)
admin_manager = Admin(app,
                      index_view=RestrictedAdminIndexView(),
                      name='Site Administration'
                     )

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

from app import commands, models, views
示例#39
0
文件: server.py 项目: 001101/ursus
    benchmark_id = db.Column(db.String)
    result_reported_at = db.Column(db.DateTime)
    instance_id = db.Column(db.String)
    instance_name = db.Column(db.String)
    vcpus = db.Column(db.Integer)
    ram = db.Column(db.Integer)
    instances = db.Column(db.Integer)
    bandwidth = db.Column(db.Integer)


class IPerfExt(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    create_request_at = db.Column(db.DateTime)
    benchmark_id = db.Column(db.String)
    result_reported_at = db.Column(db.DateTime)
    instance_id = db.Column(db.String)
    instance_name = db.Column(db.String)
    vcpus = db.Column(db.Integer)
    ram = db.Column(db.Integer)
    instances = db.Column(db.Integer)
    bandwidth = db.Column(db.Integer)


db.create_all()
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(UnixBench, methods=['GET', 'POST'])
manager.create_api(FioRead, methods=['GET', 'POST'])
manager.create_api(FioWrite, methods=['GET', 'POST'])
manager.create_api(IPerfInt, methods=['GET', 'POST'])
manager.create_api(IPerfExt, methods=['GET', 'POST'])
示例#40
0
# -*- coding: utf-8 -*-
import os
from flask import Flask, request, jsonify, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///drink.db'
db = SQLAlchemy(app)
import server.model.models as model

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(model.Drink, methods=['GET'])
示例#41
0
app = Flask(__name__, static_url_path='/static')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pin.db'
db = SQLAlchemy(app)
Triangle(app)


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


# db.create_all()

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


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


app.debug = True

if __name__ == '__main__':
    app.run(host="0.0.0.0")
示例#42
0
from datetime import date
from decimal import Decimal, ROUND_DOWN
from flask import Flask, request, render_template
from flask.ext.restless import APIManager
from sqlalchemy.orm import scoped_session
from schedule import Session
from schedule.models import Department, Course, Section, SectionInstance
from schedule.stats import most_full_filters, biggest_filters

app = Flask(__name__)

# initialize API
session = scoped_session(Session)
manager = APIManager(app, session=session)
manager.create_api(Department)
manager.create_api(Course)
manager.create_api(Section)
manager.create_api(SectionInstance)

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

@app.route('/mostfull/', methods=['GET', 'POST'])
def mostfull():
    error = None
    if request.method == 'POST':
        try:
            year = int(request.form['year'])
            month = int(request.form['month'])
            day = int(request.form['day'])
示例#43
0
# define flask extensions in separate file, to resolve import dependencies

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from flask.ext.cache import Cache
cache = Cache()

from flask.ext.assets import Environment
assets = Environment()

from flask.ext.babel import Babel
babel = Babel()

from flask.ext.mail import Mail
mail = Mail()

from flask.ext.login import LoginManager
login_manager = LoginManager()

from flask.ext.restless import APIManager
rest = APIManager()

from flask_wtf.csrf import CsrfProtect
csrf = CsrfProtect()

from flask.ext.store import Store
store = Store()
示例#44
0
            response.headers.add(
                self.header_mapping[HEADERS.REMAINING],
                str(window_stats[1])
            )
            response.headers.add(
                self.header_mapping[HEADERS.RESET],
                str(window_stats[0])
            )
        return response


cache = Cache()
compress = Compress()
limiter = JSONLimiter(headers_enabled=True, default_limits=["1000 per minute"],
                      key_func=get_remote_address)
api = APIManager()
jwt = JWT()
celery = Celery()
mail = Mail()

from croplands_api.models import db, User


def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = request.headers.get(
        'Access-Control-Request-Headers', '*')
    response.headers['Access-Control-Allow-Methods'] = request.headers.get(
        'Access-Control-Request-Method', '')
    # Do nothing for post, patch, delete etc..
    try:
示例#45
0
    content = db.Column(db.Text)
    viewed_flag = db.Column(db.Boolean)
    read_later_flag = db.Column(db.Boolean)
    add_date = db.Column(db.DateTime)
    update_date = db.Column(db.DateTime)
    rating_int = db.Column(db.Integer)
    rating_enum = db.Column(db.Text)


class Labels_v(db.Model):
    __tablename__ = 'labels_v'
    label = db.Column(db.String(255), primary_key=True)

db.create_all()

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(FeedsLabels, methods=['GET', 'POST', 'DELETE', 'PUT'])  # , max_results_per_page=-1
api_manager.create_api(Articles, methods=['GET', 'POST', 'DELETE', 'PUT'])
api_manager.create_api(Labels_v, methods=['GET'])

@app.route('/client/')
def client():
    #print(request.args.get('id'))
    #a = request.args.get('a', 0, type=int)
    #b = request.args.get('b', 0, type=int)
    return render_template('client.html')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=True)

示例#46
0
import os

from angular_flask import app

from flask.ext.restless import APIManager
from flask.ext.mongoengine import MongoEngine

app.config["MONGODB_SETTINGS"] = {
    'DB': os.environ.get('MONGODB_DB'),
    "host": os.environ.get('MONGODB_URI')
}

mongo_db = MongoEngine(app)

api_manager = APIManager(app)
示例#47
0
# Step 0: the database in this example is at './test.sqlite'.
DATABASE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        'test.sqlite')
if os.path.exists(DATABASE):
    os.unlink(DATABASE)

# Step 1: setup the Flask application.
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['TESTING'] = True
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % DATABASE

# Step 2: initialize extensions.
db = SQLAlchemy(app)
api_manager = APIManager(app, session=db.session)
login_manager = LoginManager()
login_manager.setup_app(app)


# Step 3: create the user database model.
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Unicode)
    password = db.Column(db.Unicode)


# Step 4: create the database and add a test user.
db.create_all()
user1 = User(username=u'example', password=u'example')
db.session.add(user1)
示例#48
0
class WebServer(object):

    """TODO: Add here description """

    def __init__(self, hostname, port, app):
        self.hostname = hostname
        self.port = port
        self.app = app
        self.apimanager = APIManager()

    def create_blueprints(self, session):
        # Initialize APIManager with Flask object
        self.apimanager.init_app(self.app, session=session)

        # Create API endpoints

        # SmaliClass
        self.apimanager.create_api(
            SmaliClass, app=self.app, methods=['GET', 'POST']
        )

        # SmaliProperty
        self.apimanager.create_api(
            SmaliProperty, app=self.app, methods=['GET', 'POST']
        )

        # SmaliMethod
        self.apimanager.create_api(
            SmaliMethod, app=self.app, methods=['GET', 'POST']
        )

        # SmaliConstString
        self.apimanager.create_api(
            SmaliConstString, app=self.app, methods=['GET', 'POST']
        )

        # SmaliCall
        self.apimanager.create_api(
            SmaliCall, app=self.app, methods=['GET', 'POST']
        )

    def run(self):
        """Runs the server"""
        run_simple(self.hostname, self.port, self.app)
示例#49
0
# Define static pages
#class Root(object):
#    def index(self):
#        return open(os.path.join(WEB_DIR, 'index.html'))
#    index.exposed = True

#root = Root()

# restless docs
# https://flask-restless.readthedocs.org/en/latest/quickstart.html
# https://flask-restless.readthedocs.org/en/latest/searchformat.html

# Connect flask with SQLAlchemy
app = flask.Flask(__name__)
init_db()
manager = APIManager(app, session=db_session)

# Hook up with CherryPy
#d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
#restServer = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 9876), d)

# Create the API endpoints
station_blueprint = manager.create_api(Station,
                                       methods=['GET'],
                                       max_results_per_page=-1)
trip_blueprint = manager.create_api(Trip,
                                    methods=['GET'],
                                    max_results_per_page=100)
trip_lines_blueprint = manager.create_api(TripLines,
                                          methods=['GET'],
                                          max_results_per_page=-1)
示例#50
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
示例#51
0
    def setUp(self):
        """Initializes an instance of :class:`flask.ext.restless.APIManager`.

        """
        super(ManagerTestBase, self).setUp()
        self.manager = APIManager(self.flaskapp, session=self.session)
示例#52
0
    def test_constructor(self):
        """Tests that no error occurs on instantiation without any arguments to
        the constructor.

        """
        APIManager()
示例#53
0
class FSATest(FlaskTestBase):
    """Tests which use models defined using Flask-SQLAlchemy instead of pure
    SQLAlchemy.

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

        """
        super(FSATest, self).setUp()

        # initialize SQLAlchemy and Flask-Restless
        self.db = SQLAlchemy(self.flaskapp)
        self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)

        # for the sake of brevity...
        db = self.db

        # declare the models
        class Computer(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            name = db.Column(db.Unicode, unique=True)
            vendor = db.Column(db.Unicode)
            buy_date = db.Column(db.DateTime)
            owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))

        class Person(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            name = db.Column(db.Unicode, unique=True)
            age = db.Column(db.Float)
            other = db.Column(db.Float)
            birth_date = db.Column(db.Date)
            computers = db.relationship('Computer',
                                        backref=db.backref('owner',
                                                           lazy='dynamic'))

        self.Person = Person
        self.Computer = Computer

        # create all the tables required for the models
        self.db.create_all()

    def tearDown(self):
        """Drops all tables from the temporary database."""
        self.db.drop_all()

    def test_flask_sqlalchemy(self):
        """Tests that :class:`flask.ext.restless.APIManager` correctly exposes
        models defined using Flask-SQLAlchemy.

        """
        # create three different APIs for the same model
        self.manager.create_api(self.Person, methods=['GET', 'POST'])
        self.manager.create_api(self.Person,
                                methods=['PATCH'],
                                url_prefix='/api2')
        self.manager.create_api(self.Person,
                                methods=['GET'],
                                url_prefix='/readonly')

        # test that specified endpoints exist
        response = self.app.post('/api/person', data=dumps(dict(name='foo')))
        self.assertEqual(response.status_code, 201)
        self.assertEqual(loads(response.data)['id'], 1)
        response = self.app.get('/api/person')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(loads(response.data)['objects']), 1)
        self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
        response = self.app.patch('/api2/person/1',
                                  data=dumps(dict(name='bar')))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(loads(response.data)['id'], 1)
        self.assertEqual(loads(response.data)['name'], 'bar')

        # test that the model is the same as before
        response = self.app.get('/readonly/person')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(loads(response.data)['objects']), 1)
        self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
        self.assertEqual(loads(response.data)['objects'][0]['name'], 'bar')
示例#54
0
class rpad(Flask):
    IMAGE_STORE = 'static/imagestore'

    def __init__(self, db):
        Flask.__init__(self, 'rpad')

        self.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
        self.db = db
        self.api_manager = APIManager(self, flask_sqlalchemy_db=self.db)
        # Create R subprocess.
        # A single R instance will serve all pads using Rserve.
        self.r = R()

        # Routing and URL rules:
        self.add_url_rule('/', 'index', self.handle_index)
        self.add_url_rule('/about', 'about', self.handle_about)
        self.add_url_rule('/new_pad', 'new_pad', self.handle_new_pad)
        self.add_url_rule('/pad/<int:pad_id>', 'pad', self.handle_pad)
        self.add_url_rule('/r', 'r', self.handle_r_eval)
        self.add_url_rule('/upload_image',
                          'upload_image',
                          self.handle_upload_image,
                          methods=['POST'])

        # API routing
        self.api_manager.create_api(Pad,
                                    include_columns=['id', 'name'],
                                    collection_name='pads',
                                    methods=['GET'])
        self.api_manager.create_api(Pad,
                                    methods=['GET', 'POST', 'DELETE', 'PUT'])
        self.api_manager.create_api(Block,
                                    methods=['GET, POST', 'DELETE', 'PUT'])

    def handle_index(self):
        return self.handle_about()

    def handle_about(self):
        pads = Pad.query.all()
        return render_template('about.html', pads=pads)

    def handle_new_pad(self):
        pad = Pad(name='Untitled Pad')
        block = Block(type='text', position=0, content='')
        pad.blocks.append(block)
        db.session.add(pad)
        db.session.add(block)
        db.session.commit()
        return redirect('pad/%i' % (pad.id))

    def handle_pad(self, pad_id):
        pad = Pad.query.get(pad_id)
        if pad is None:
            abort(404)
        pads = Pad.query.all()

        return render_template('pad.html', current_pad=pad, pads=pads)

    def handle_r_eval(self):
        if 'expr' not in request.args:
            abort(400)

        expr = html_parser.unescape(urllib.unquote(
            request.args['expr'])).decode('utf-8', 'ignore')
        pad = int(request.args.get('pad'))
        results = self.r.eval(expr, pad)  # (result, type) pairs
        outputs = []
        for (result, type_) in results:
            print type_, result
            outputs.append(format(result, type_))
        return json.dumps(outputs)

    def handle_upload_image(self):
        file = request.files['file']
        pad_id = request.args.get('pad_id')
        if file:
            file.save(os.path.join(self.IMAGE_STORE, file.filename))
            image = Image(filename=file.filename, pad_id=pad_id)
            db.session.add(image)
            db.session.commit()
            return '1'
        else:
            return '0'
示例#55
0
    auth = request.authorization
    if auth:
        user = User.get()
        if auth.username == user.id and auth.password == user.password:
            return user
    return None


#@login_required
def auth(**kw):
    pass


from flask.ext.restless import APIManager, ProcessingException

apimanager = APIManager(app, flask_sqlalchemy_db=db)

# Set up the organizations API.

from models import Organization
import math

apimanager.create_api(Organization,
                      methods=['DELETE', 'GET', 'POST', 'PUT'],
                      include_methods=[
                          'children_ids', 'ancestor_ids', 'descendant_ids',
                          'ancestor_tree'
                      ],
                      exclude_columns=['authors'],
                      preprocessors={
                          'DELETE_SINGLE': [auth],
示例#56
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        super(TestSupport, self).setUp()

        # initialize SQLAlchemy and Flask-Restless
        app = self.flaskapp
        engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'],
                               convert_unicode=True)
        self.Session = sessionmaker(autocommit=False, autoflush=False,
                                    bind=engine)
        self.session = scoped_session(self.Session)
        self.Base = declarative_base()
        self.Base.metadata.bind = engine
        #Base.query = self.session.query_property()
        self.manager = APIManager(app, self.session)

        # declare the models
        class Computer(self.Base):
            __tablename__ = 'computer'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode, unique=True)
            vendor = Column(Unicode)
            buy_date = Column(DateTime)
            owner_id = Column(Integer, ForeignKey('person.id'))
            owner = relationship('Person')

        class Person(self.Base):
            __tablename__ = 'person'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode, unique=True)
            age = Column(Float)
            other = Column(Float)
            birth_date = Column(Date)
            computers = relationship('Computer')

        class LazyComputer(self.Base):
            __tablename__ = 'lazycomputer'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)
            ownerid = Column(Integer, ForeignKey('lazyperson.id'))

        class LazyPerson(self.Base):
            __tablename__ = 'lazyperson'
            id = Column(Integer, primary_key=True)
            name = Column(Unicode)
            computers = relationship('LazyComputer',
                                     backref=backref('owner', lazy='dynamic'))

        class Planet(self.Base):
            __tablename__ = 'planet'
            name = Column(Unicode, primary_key=True)

        class Star(self.Base):
            __tablename__ = 'star'
            id = Column(Integer, primary_key=True)
            inception_time = Column(DateTime, nullable=True)

        self.Person = Person
        self.LazyComputer = LazyComputer
        self.LazyPerson = LazyPerson
        self.Computer = Computer
        self.Planet = Planet
        self.Star = Star

        # create all the tables required for the models
        self.Base.metadata.create_all()
示例#57
0
from public_records_portal import app, models, db, views
from views import *  # Import all the functions that render templates
from flask.ext.restless import APIManager
from flask.ext.admin import Admin, expose, BaseView, AdminIndexView
from flask.ext.admin.contrib.sqlamodel import ModelView

# Create API
manager = APIManager(app, flask_sqlalchemy_db=db)
# The endpoints created are /api/object, e.g. publicrecordsareawesome.com/api/request/
manager.create_api(models.Request,
                   methods=['GET'],
                   results_per_page=10,
                   allow_functions=True)
manager.create_api(models.Owner,
                   methods=['GET'],
                   results_per_page=10,
                   allow_functions=True)
manager.create_api(models.Note,
                   methods=['GET'],
                   results_per_page=10,
                   allow_functions=True)
manager.create_api(models.Record,
                   methods=['GET'],
                   results_per_page=10,
                   allow_functions=True)
manager.create_api(models.QA,
                   methods=['GET'],
                   results_per_page=10,
                   allow_functions=True)
manager.create_api(models.Subscriber,
                   methods=['GET'],
示例#58
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
示例#59
0

# RESTful API database model class
class Class(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    classnum = db.Column(db.Text)
    classname = db.Column(db.Text)
    professor = db.Column(db.Text)
    classtype = db.Column(db.Text)
    seats = db.Column(db.INT)
    bldgcode = db.Column(db.Text)
    roomcode = db.Column(db.Text)
    classdays = db.Column(db.Text)
    starttime = db.Column(db.Text)
    endtime = db.Column(db.Text)


# Push all structures to database
db.create_all()

# Creating APIManager from restless extension
manager = APIManager(app, flask_sqlalchemy_db=db)

# Defining valid HTML requests
class_blueprint = manager.create_api(
    Class, methods=['GET', 'POST', 'DELETE', 'PUT', 'PATCH'])

# Running Flask loop sequence
if __name__ == "__main__":
    app.run()
示例#60
0
# Step 0: the database in this example is at './test.sqlite'.
DATABASE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                        'test.sqlite')
if os.path.exists(DATABASE):
    os.unlink(DATABASE)

# Step 1: setup the Flask application.
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['TESTING'] = True
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % DATABASE

# Step 2: initialize extensions.
db = SQLAlchemy(app)
api_manager = APIManager(app, flask_sqlalchemy_db=db)
login_manager = LoginManager()
login_manager.setup_app(app)


# Step 3: create the user database model.
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Unicode)
    password = db.Column(db.Unicode)


# Step 4: create the database and add a test user.
db.create_all()
user1 = User(username=u'example', password=u'example')
db.session.add(user1)