Ejemplo n.º 1
0
    def setUp(self):
        """Creates the Flask-SQLAlchemy database and models."""
        super(FSAModelTest, self).setUp()

        db = SQLAlchemy(self.flaskapp)

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

        class Pet(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            ownerid = db.Column(db.Integer, db.ForeignKey(User.id))
            owner = db.relationship(User, backref=db.backref("pets"))

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

        class LazyPet(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            ownerid = db.Column(db.Integer, db.ForeignKey(LazyUser.id))
            owner = db.relationship(LazyUser, backref=db.backref("pets", lazy="dynamic"))

        self.User = User
        self.Pet = Pet
        self.LazyUser = LazyUser
        self.LazyPet = LazyPet

        self.db = db
        self.db.create_all()

        self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
Ejemplo n.º 2
0
    def setUp(self):
        """Creates the database, :class:`~flask.Flask` object, and the
        :class:`~flask_restless.manager.APIManager` for that application.

        """
        # set up the database
        self.db_fd, self.db_file = mkstemp()
        setup(create_engine('sqlite:///%s' % self.db_file))
        create_all()
        session.commit()
        
        # set up the application and API manager
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        self.app = app.test_client()
        self.manager = APIManager(app)
Ejemplo n.º 3
0
db = SQLAlchemy(app)


class Meas(db.Model):
    id = Column(Integer, primary_key=True)
    local_epoch = Column(DateTime, unique=False)
    h2o_temp = Column(Float, unique=False)
    air_temp = Column(Float, unique=False)
    humidity = Column(Float, unique=False)
    wind_speed = Column(Float, unique=False)
    wind_gusts = Column(Float, unique=False)
    wind_direction = Column(Integer, unique=False)
    precipitation = Column(Float, unique=False)
    humidity = Column(Integer, unique=False)
    pressure = Column(Float, unique=False)

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


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

db.create_all()
app.debug = True


if __name__ == '__main__':
    app.run()
Ejemplo n.º 4
0
class FSAModelTest(FlaskTestBase):
    """Tests for functions which operate on Flask-SQLAlchemy models."""

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

        db = SQLAlchemy(self.flaskapp)

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

        class Pet(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            ownerid = db.Column(db.Integer, db.ForeignKey(User.id))
            owner = db.relationship(User, backref=db.backref("pets"))

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

        class LazyPet(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            ownerid = db.Column(db.Integer, db.ForeignKey(LazyUser.id))
            owner = db.relationship(LazyUser, backref=db.backref("pets", lazy="dynamic"))

        self.User = User
        self.Pet = Pet
        self.LazyUser = LazyUser
        self.LazyPet = LazyPet

        self.db = db
        self.db.create_all()

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

    def tearDown(self):
        """Drops all tables."""
        self.db.drop_all()

    def test_get(self):
        """Test for the :meth:`views.API.get` method with models defined using
        Flask-SQLAlchemy with both dynamically loaded and static relationships.

        """
        # create the API endpoint
        self.manager.create_api(self.User)
        self.manager.create_api(self.LazyUser)
        self.manager.create_api(self.Pet)
        self.manager.create_api(self.LazyPet)

        response = self.app.get("/api/user")
        self.assertEqual(200, response.status_code)
        response = self.app.get("/api/lazy_user")
        self.assertEqual(200, response.status_code)
        response = self.app.get("/api/pet")
        self.assertEqual(200, response.status_code)
        response = self.app.get("/api/lazy_pet")
        self.assertEqual(200, response.status_code)

        # create a user with two pets
        owner = self.User()
        pet1 = self.Pet()
        pet2 = self.Pet()
        pet1.owner = owner
        pet2.owner = owner
        self.db.session.add_all([owner, pet1, pet2])
        self.db.session.commit()

        response = self.app.get("/api/user/%d" % owner.id)
        self.assertEqual(200, response.status_code)
        data = loads(response.data)
        self.assertEqual(2, len(data["pets"]))
        for pet in data["pets"]:
            self.assertEqual(owner.id, pet["ownerid"])

        response = self.app.get("/api/pet/1")
        self.assertEqual(200, response.status_code)
        data = loads(response.data)
        self.assertFalse(isinstance(data["owner"], list))
        self.assertEqual(owner.id, data["ownerid"])

        # create a lazy user with two lazy pets
        owner = self.LazyUser()
        pet1 = self.LazyPet()
        pet2 = self.LazyPet()
        pet1.owner = owner
        pet2.owner = owner
        self.db.session.add_all([owner, pet1, pet2])
        self.db.session.commit()

        response = self.app.get("/api/lazy_user/%d" % owner.id)
        self.assertEqual(200, response.status_code)
        data = loads(response.data)
        self.assertEqual(2, len(data["pets"]))
        for pet in data["pets"]:
            self.assertEqual(owner.id, pet["ownerid"])

        response = self.app.get("/api/lazy_pet/1")
        self.assertEqual(200, response.status_code)
        data = loads(response.data)
        self.assertFalse(isinstance(data["owner"], list))
        self.assertEqual(owner.id, data["ownerid"])
Ejemplo n.º 5
0
class APIManagerTest(unittest.TestCase):
    """Unit tests for the :class:`flask_restless.manager.APIManager` class.

    """

    def setUp(self):
        """Creates the database, :class:`~flask.Flask` object, and the
        :class:`~flask_restless.manager.APIManager` for that application.

        """
        # set up the database
        self.db_fd, self.db_file = mkstemp()
        setup(create_engine('sqlite:///%s' % self.db_file))
        create_all()
        session.commit()
        
        # set up the application and API manager
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        self.app = app.test_client()
        self.manager = APIManager(app)

    def tearDown(self):
        """Drops all tables from the temporary database and closes and unlink
        the temporary file in which it lived.

        """
        drop_all()
        session.commit()
        os.close(self.db_fd)
        os.unlink(self.db_file)

    def test_create_api(self):
        """Tests that the :meth:`flask_restless.manager.APIManager.create_api`
        method creates endpoints which are accessible by the client, only allow
        specified HTTP methods, and which provide a correct API to a database.

        """
        # create three different APIs for the same model
        # TODO note in documentation that only
        self.manager.create_api(Person, methods=['GET', 'POST'])
        self.manager.create_api(Person, methods=['PATCH'], url_prefix='/api2')
        self.manager.create_api(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)

        # test that non-specified methods are not allowed
        response = self.app.delete('/api/person/1')
        self.assertEqual(response.status_code, 405)
        response = self.app.patch('/api/person/1',
                                  data=dumps(dict(name='bar')))
        self.assertEqual(response.status_code, 405)

        # test that specified endpoints exist
        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 non-specified methods are not allowed
        response = self.app.get('/api2/person/1')
        self.assertEqual(response.status_code, 405)
        response = self.app.delete('/api2/person/1')
        self.assertEqual(response.status_code, 405)
        response = self.app.post('/api2/person',
                                 data=dumps(dict(name='baz')))
        self.assertEqual(response.status_code, 405)

        # 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')

    def test_different_collection_name(self):
        """Tests that providing a different collection name exposes the API at
        the corresponding URL.

        """
        self.manager.create_api(Person, methods=['POST', 'GET'],
                                collection_name='people')

        response = self.app.post('/api/people', data=dumps(dict(name='foo')))
        self.assertEqual(response.status_code, 201)
        self.assertEqual(loads(response.data)['id'], 1)

        response = self.app.get('/api/people')
        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.get('/api/people/1')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(loads(response.data)['id'], 1)
Ejemplo n.º 6
0
def getFile(connection_id, file_id):
    try:
        filename = getFilename(connection_id, file_id)
        return send_file(filename, as_attachment=True)
    except IndexError:
        return make_response('File not found', 404)


@app.route('/api/connections/<int:connection_id>/connect', methods=['POST'])
def connect(connection_id):
    connection = findConnection(connection_id)
    return jsonify({'href': url_for('processesapi0.processesapi', instid=connection.connect())})


@app.route('/api/connections/<int:connection_id>/disconnect', methods=['POST'])
def disconnect(connection_id):
    connection = findConnection(connection_id)
    connection.disconnect()
    return jsonify({'href': url_for('connectionsapi0.connectionsapi', instid=connection_id)})

manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Connection,
                   methods=['GET', 'POST', 'PUT'],
                   exclude_columns=['processesList', 'config'],
                   include_methods=['href', 'processes', 'files', 'workingDir', 'configuration'])
manager.create_api(Process, methods=['GET', 'DELETE'], exclude_columns=['connectionId', 'parentConnection'],
                   include_methods=['href', 'connection', 'status'])

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8888)
Ejemplo n.º 7
0
def getFile(connection_id, file_id):
    try:
        filename = getFilename(connection_id, file_id)
        return send_file(filename, as_attachment=True)
    except IndexError:
        return make_response('File not found', 404)


@app.route('/api/connections/<int:connection_id>/connect', methods=['POST'])
def connect(connection_id):
    connection = findConnection(connection_id)
    return jsonify({'href': url_for('processesapi0.processesapi', instid=connection.connect())})


@app.route('/api/connections/<int:connection_id>/disconnect', methods=['POST'])
def disconnect(connection_id):
    connection = findConnection(connection_id)
    connection.disconnect()
    return jsonify({'href': url_for('connectionsapi0.connectionsapi', instid=connection_id)})

manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Connection,
                   methods=['GET', 'POST', 'PUT'],
                   exclude_columns=['processesList', 'config'],
                   include_methods=['href', 'processes', 'files', 'workingDir', 'configuration'])
manager.create_api(Process, methods=['GET', 'DELETE'], exclude_columns=['connectionId', 'parentConnection'],
                   include_methods=['href', 'connection', 'status'])

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8888)
Ejemplo n.º 8
0
from flask.ext.restless.manager import APIManager
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, Text

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


class Pin(db.Model):
    id = Column(Integer, primary_key=True)
    title = Column(Text, unique=False)
    image = Column(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 app.send_static_file('index.html')


app.debug = True

if __name__ == '__main__':
    app.run()
Ejemplo n.º 9
0
from flask.ext.restless.manager import APIManager
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, Text

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


class Pin(db.Model):
    id = Column(Integer, primary_key=True)
    title = Column(Text, unique=False)
    image = Column(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 app.send_static_file("index.html")


app.debug = True

if __name__ == "__main__":
    app.run()