Ejemplo n.º 1
0
    def test_marshal_with_honour_custom_field_mask(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        with self.settings(RESTPLUS_MASK_HEADER='X-Mask'):
            data = self.get_json('/test/', headers={
                'X-Mask': '{name,age}'
            })

        self.assertEqual(data, {
            'name': 'John Doe',
            'age': 42,
        })
 def test_models(self):
     app = Flask(__name__)
     api = Api(app)
     todo_fields = api.model("Todo", {"task": fields.String(required=True, description="The task details")})
     parser = reqparse.RequestParser()
     parser.add_argument("todo", type=todo_fields)
     self.assertEqual(parser_to_params(parser), {"todo": {"type": "Todo", "in": "body"}})
Ejemplo n.º 3
0
    def test_marshal_with_disabling_mask_header(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        with self.settings(RESTPLUS_MASK_SWAGGER=False):
            specs = self.get_specs()

        op = specs['paths']['/test/']['get']

        self.assertNotIn('parameters', op)
Ejemplo n.º 4
0
    def test_marshal_with_honour_field_mask_list(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return [{
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }, {
                    'name': 'Jane Doe',
                    'age': 33,
                    'boolean': False
                }]

        data = self.get_json('/test/', headers={
            'X-Fields': '{name,age}'
        })
        self.assertEqual(data, [{
            'name': 'John Doe',
            'age': 42,
        }, {
            'name': 'Jane Doe',
            'age': 33,
        }])
Ejemplo n.º 5
0
    def test_list_fields_with_nested_inherited(self):
        api = Api(self.app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer
        })
        child = api.inherit('Child', person, {
            'attr': fields.String
        })

        family = api.model('Family', {
            'children': fields.List(fields.Nested(child))
        })

        result = mask.apply(family.resolved, 'children{name,attr}')

        data = {'children': [
            {'name': 'John', 'age': 5, 'attr': 'value-john'},
            {'name': 'Jane', 'age': 42, 'attr': 'value-jane'},
        ]}
        expected = {'children': [
            {'name': 'John', 'attr': 'value-john'},
            {'name': 'Jane', 'attr': 'value-jane'},
        ]}

        self.assertDataEqual(marshal(data, result), expected)
        # Should leave th original mask untouched
        self.assertDataEqual(marshal(data, family), data)
Ejemplo n.º 6
0
    def test_will_prettyprint_json_in_debug_mode(self):
        self.app.config["DEBUG"] = True
        api = Api(self.app)

        class Foo1(Resource):
            def get(self):
                return {"foo": "bar", "baz": "asdf"}

        api.add_resource(Foo1, "/foo", endpoint="bar")

        with self.app.test_client() as client:
            foo = client.get("/foo")

            # Python's dictionaries have random order (as of "new" Pythons,
            # anyway), so we can't verify the actual output here.  We just
            # assert that they're properly prettyprinted.
            lines = foo.data.splitlines()
            lines = [line.decode() for line in lines]
            self.assertEquals("{", lines[0])
            self.assertTrue(lines[1].startswith("    "))
            self.assertTrue(lines[2].startswith("    "))
            self.assertEquals("}", lines[3])

            # Assert our trailing newline.
            self.assertTrue(foo.data.endswith(b"\n"))
    def test_marshal_with_expose_custom_mask_header(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        app.config['RESTPLUS_MASK_HEADER'] = 'X-Mask'
        specs = client.get_specs()

        op = specs['paths']['/test/']['get']
        assert 'parameters' in op
        assert len(op['parameters']) == 1

        param = op['parameters'][0]
        assert param['name'] == 'X-Mask'
Ejemplo n.º 8
0
    def test_marshal_handle_inheritance(self):
        api = Api(self.app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = api.inherit('Child', person, {
            'extra': fields.String,
        })

        data = {
            'name': 'John Doe',
            'age': 42,
            'extra': 'extra'
        }

        values = (
            ('name', {'name': 'John Doe'}),
            ('name,extra', {'name': 'John Doe', 'extra': 'extra'}),
            ('extra', {'extra': 'extra'}),
        )

        for mask, expected in values:
            result = marshal(data, child, mask=mask)
            self.assertEqual(result, expected)
Ejemplo n.º 9
0
    def test_marshal_does_not_hit_unrequired_attributes(self):
        api = Api(self.app)

        model = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        class Person(object):
            def __init__(self, name, age):
                self.name = name
                self.age = age

            @property
            def boolean(self):
                raise Exception()

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return Person('John Doe', 42)

        data = self.get_json('/test/', headers={
            'X-Fields': '{name,age}'
        })
        self.assertEqual(data, {
            'name': 'John Doe',
            'age': 42,
        })
Ejemplo n.º 10
0
    def test_marshal_with_expose_custom_mask_header(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        with self.settings(RESTPLUS_MASK_HEADER='X-Mask'):
            specs = self.get_specs()

        op = specs['paths']['/test/']['get']
        self.assertIn('parameters', op)
        self.assertEqual(len(op['parameters']), 1)

        param = op['parameters'][0]
        self.assertEqual(param['name'], 'X-Mask')
Ejemplo n.º 11
0
    def test_marshal_with_expose_mask_header(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        specs = self.get_specs()
        op = specs['paths']['/test/']['get']

        self.assertIn('parameters', op)
        self.assertEqual(len(op['parameters']), 1)

        param = op['parameters'][0]

        self.assertEqual(param['name'], 'X-Fields')
        self.assertEqual(param['type'], 'string')
        self.assertEqual(param['format'], 'mask')
        self.assertEqual(param['in'], 'header')
        self.assertNotIn('required', param)
        self.assertNotIn('default', param)
Ejemplo n.º 12
0
    def test_marshal_with_expose_mask_header(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        specs = client.get_specs()
        op = specs['paths']['/test/']['get']

        assert 'parameters' in op
        assert len(op['parameters']) == 1

        param = op['parameters'][0]

        assert param['name'] == 'X-Fields'
        assert param['type'] == 'string'
        assert param['format'] == 'mask'
        assert param['in'] == 'header'
        assert 'required' not in param
        assert 'default' not in param
Ejemplo n.º 13
0
    def test_marshal_with_disabling_mask_header(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        app.config['RESTPLUS_MASK_SWAGGER'] = False
        specs = client.get_specs()

        op = specs['paths']['/test/']['get']

        assert 'parameters' not in op
Ejemplo n.º 14
0
    def test_marshal_with_honour_header_field_mask_with_default_mask_and_default_model_mask(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        }, mask='{name,boolean}')

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model, mask='{name,age}')
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        data = self.get_json('/test/', headers={
            'X-Fields': '{name}'
        })
        self.assertEqual(data, {
            'name': 'John Doe',
        })
Ejemplo n.º 15
0
 def test_with_readonly(self, app):
     api = Api(app)
     nested_fields = api.model('NestedModel', {'name': fields.String})
     field = fields.Nested(nested_fields, readonly=True)
     assert field.__schema__ == {
         'readOnly': True,
         'allOf': [{'$ref': '#/definitions/NestedModel'}]
     }
Ejemplo n.º 16
0
    def test_marshal_with_handle_polymorph(self, app, client):
        api = Api(app)

        parent = api.model('Person', {
            'name': fields.String,
        })

        child1 = api.inherit('Child1', parent, {
            'extra1': fields.String,
        })

        child2 = api.inherit('Child2', parent, {
            'extra2': fields.String,
        })

        class Child1(object):
            name = 'child1'
            extra1 = 'extra1'

        class Child2(object):
            name = 'child2'
            extra2 = 'extra2'

        mapping = {
            Child1: child1,
            Child2: child2
        }

        thing = api.model('Thing', {
            'owner': fields.Polymorph(mapping),
        })

        @api.route('/thing-1/')
        class Thing1Resource(Resource):
            @api.marshal_with(thing)
            def get(self):
                return {'owner': Child1()}

        @api.route('/thing-2/')
        class Thing2Resource(Resource):
            @api.marshal_with(thing)
            def get(self):
                return {'owner': Child2()}

        data = client.get_json('/thing-1/', headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child1'}}

        data = client.get_json('/thing-1/', headers={'X-Fields': 'owner{extra1}'})
        assert data == {'owner': {'extra1': 'extra1'}}

        data = client.get_json('/thing-2/', headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child2'}}
Ejemplo n.º 17
0
    def test_no_crossdomain(self, app, client):
        class Foo(Resource):
            def get(self):
                return "data"

        api = Api(app)
        api.add_resource(Foo, '/test/')

        res = client.get('/test/')
        assert res.status_code == 200
        assert 'Access-Control-Allow-Origin' not in res.headers
        assert 'Access-Control-Allow-Methods' not in res.headers
        assert 'Access-Control-Max-Age' not in res.headers
Ejemplo n.º 18
0
    def test_no_crossdomain(self):
        class Foo(Resource):
            def get(self):
                return "data"

        api = Api(self.app)
        api.add_resource(Foo, '/test/')

        res = self.get('/test/')
        self.assertEqual(res.status_code, 200)
        self.assertNotIn('Access-Control-Allow-Origin', res.headers)
        self.assertNotIn('Access-Control-Allow-Methods', res.headers)
        self.assertNotIn('Access-Control-Max-Age', res.headers)
Ejemplo n.º 19
0
    def test_access_control_expose_headers(self):
        class Foo(Resource):
            @cors.crossdomain(origin='*',
                              expose_headers=['X-My-Header', 'X-Another-Header'])
            def get(self):
                return "data"

        api = Api(self.app)
        api.add_resource(Foo, '/test/')

        res = self.get('/test/')
        self.assertEqual(res.status_code, 200)
        self.assertIn('X-MY-HEADER', res.headers['Access-Control-Expose-Headers'])
        self.assertIn('X-ANOTHER-HEADER', res.headers['Access-Control-Expose-Headers'])
Ejemplo n.º 20
0
 def test_models(self):
     app = Flask(__name__)
     api = Api(app)
     todo_fields = api.model('Todo', {
         'task': fields.String(required=True, description='The task details')
     })
     parser = reqparse.RequestParser()
     parser.add_argument('todo', type=todo_fields)
     self.assertEqual(parser_to_params(parser), {
         'todo': {
             'type': 'Todo',
             'in': 'body',
         },
     })
Ejemplo n.º 21
0
    def test_json_float_marshalled(self, app, client):
        api = Api(app)

        class FooResource(Resource):
            fields = {'foo': fields.Float}

            def get(self):
                return marshal({"foo": 3.0}, self.fields)

        api.add_resource(FooResource, '/api')

        resp = client.get('/api')
        assert resp.status_code == 200
        assert resp.data.decode('utf-8') == '{"foo": 3.0}\n'
Ejemplo n.º 22
0
    def test_access_control_expose_headers(self, app, client):
        class Foo(Resource):
            @cors.crossdomain(origin='*',
                              expose_headers=['X-My-Header', 'X-Another-Header'])
            def get(self):
                return "data"

        api = Api(app)
        api.add_resource(Foo, '/test/')

        res = client.get('/test/')
        assert res.status_code == 200
        assert 'X-MY-HEADER' in res.headers['Access-Control-Expose-Headers']
        assert 'X-ANOTHER-HEADER' in res.headers['Access-Control-Expose-Headers']
Ejemplo n.º 23
0
    def test_json_float_marshalled(self):
        api = Api(self.app)

        class FooResource(Resource):
            fields = {"foo": fields.Float}

            def get(self):
                return marshal({"foo": 3.0}, self.fields)

        api.add_resource(FooResource, "/api")

        app = self.app.test_client()
        resp = app.get("/api")
        self.assertEquals(resp.status_code, 200)
        self.assertEquals(resp.data.decode("utf-8"), '{"foo": 3.0}\n')
Ejemplo n.º 24
0
    def test_crossdomain(self, app, client):
        class Foo(Resource):
            @cors.crossdomain(origin='*')
            def get(self):
                return "data"

        api = Api(app)
        api.add_resource(Foo, '/test/')

        res = client.get('/test/')
        assert res.status_code == 200
        assert res.headers['Access-Control-Allow-Origin'] == '*'
        assert res.headers['Access-Control-Max-Age'] == '21600'
        assert 'HEAD' in res.headers['Access-Control-Allow-Methods']
        assert 'OPTIONS' in res.headers['Access-Control-Allow-Methods']
        assert 'GET' in res.headers['Access-Control-Allow-Methods']
Ejemplo n.º 25
0
    def test_crossdomain(self):
        class Foo(Resource):
            @cors.crossdomain(origin='*')
            def get(self):
                return "data"

        api = Api(self.app)
        api.add_resource(Foo, '/test/')

        res = self.get('/test/')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.headers['Access-Control-Allow-Origin'], '*')
        self.assertEqual(res.headers['Access-Control-Max-Age'], '21600')
        self.assertIn('HEAD', res.headers['Access-Control-Allow-Methods'])
        self.assertIn('OPTIONS', res.headers['Access-Control-Allow-Methods'])
        self.assertIn('GET', res.headers['Access-Control-Allow-Methods'])
Ejemplo n.º 26
0
    def test_marshal_with_honour_complex_field_mask_header(self):
        api = Api(self.app)

        person = api.model('Person', person_fields)
        child = api.inherit('Child', person, {
            'attr': fields.String
        })

        family = api.model('Family', {
            'father': fields.Nested(person),
            'mother': fields.Nested(person),
            'children': fields.List(fields.Nested(child)),
            'free': fields.List(fields.Raw),
        })

        house = api.model('House', {
            'family': fields.Nested(family, attribute='people')
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(house)
            def get(self):
                return {'people': {
                    'father': {'name': 'John', 'age': 42},
                    'mother': {'name': 'Jane', 'age': 42},
                    'children': [
                        {'name': 'Jack', 'age': 5, 'attr': 'value-1'},
                        {'name': 'Julie', 'age': 7, 'attr': 'value-2'},
                    ],
                    'free': [
                        {'key-1': '1-1', 'key-2': '1-2'},
                        {'key-1': '2-1', 'key-2': '2-2'},
                    ]
                }}

        data = self.get_json('/test/', headers={
            'X-Fields': 'family{father{name},mother{age},children{name,attr},free{key-2}}'
        })
        expected = {'family': {
            'father': {'name': 'John'},
            'mother': {'age': 42},
            'children': [{'name': 'Jack', 'attr': 'value-1'}, {'name': 'Julie', 'attr': 'value-2'}],
            'free': [{'key-2': '1-2'}, {'key-2': '2-2'}]
        }}
        self.assertEqual(data, expected)
Ejemplo n.º 27
0
    def test_raise_400_on_invalid_mask(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                pass

        response = client.get('/test/', headers={'X-Fields': 'name{,missing}'})
        assert response.status_code == 400
        assert response.content_type == 'application/json'
Ejemplo n.º 28
0
    def test_raise_400_on_invalid_mask(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                pass

        with self.app.test_client() as client:
            response = client.get('/test/', headers={'X-Fields': 'name{,missing}'})
            self.assertEqual(response.status_code, 400)
            self.assertEquals(response.content_type, 'application/json; charset=utf-8')
Ejemplo n.º 29
0
    def test_marshal_with_expose_default_model_mask_header(self):
        api = Api(self.app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        }, mask='{name,age}')

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                pass

        specs = self.get_specs()
        definition = specs['definitions']['Test']
        self.assertIn('x-mask', definition)
        self.assertEqual(definition['x-mask'], '{name,age}')
Ejemplo n.º 30
0
    def test_marshal_with_skip_missing_fields(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                }

        data = client.get_json('/test/', headers={'X-Fields': '{name,missing}'})
        assert data == {'name': 'John Doe'}
Ejemplo n.º 31
0
import werkzeug

werkzeug.cached_property = werkzeug.utils.cached_property

from flask import Flask
from flask import request, jsonify
from flask_restplus import Api, Resource
import json
from bson.json_util import dumps
import os

app = Flask(__name__)
api = Api(
    app,
    version='1.0',
    title=
    'pokerPlam: Tool for the use of the Poker technique of planning by teams that work remotely.',
    description='pokerPlam apiRest',
)
Ejemplo n.º 32
0
# Web-server
from flask import Flask
from flask_restplus import Api, Resource
from http import HTTPStatus
# Database
from pymongo import MongoClient
# Models
from src.models.movie import MOVIE

MONGO = MongoClient()

# Initialization Params
app = Flask(__name__)
api = Api(app)

# Registers models
MOVIE = api.model("Movie", MOVIE)


@api.route("/movies")
class AllMovies(Resource):
    records = MONGO.movies.records

    @api.marshal_with(MOVIE)
    def get(self):
        return list(movie for movie in self.records.find())


@api.route("/movies/<int:year>")
class MoviesByYear(Resource):
    records = MONGO.movies.records
Ejemplo n.º 33
0
from flask_restplus import Api

from .openmp import api as openmp_namespace
from .openacc import api as openacc_namespace
from .compiler import api as compiler_namespace


api = Api(
    title='Pragcc Api',
    version='1.0',
    description="""Provides an interface to annotate C99 sequential code with
    OpenMP and OpenACC compiler directives."""
)

api.add_namespace(openmp_namespace)
api.add_namespace(openacc_namespace)
api.add_namespace(compiler_namespace)
Ejemplo n.º 34
0
   * Licence: MIT, see LICENSE
'''

import logging
import traceback

from flask_restplus import Api
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import ProgrammingError

import settings

log = logging.getLogger(__name__)

# API Docs Header
api = Api(version='1.0', title='Fitcrack API', description='')

# ERROR HANDLERS


@api.errorhandler
def default_error_handler(e):
    message = 'An unhandled exception occurred.'
    log.exception(message)

    #if not settings.FLASK_DEBUG:
    return {'message': message}, 500


@api.errorhandler(NoResultFound)
def database_not_found_error_handler(e):
Ejemplo n.º 35
0
counter_until = int(os.getenv('COUNTER'))

tz = os.getenv('TZ')
localtime = timezone(tz)


# TASK
@celery.task(bind=True, name='app.count')
def count(self, counter_value):
    return counter(counter_value)


# REST API
app.wsgi_app = ProxyFix(app.wsgi_app)
api = Api(app,
          version='1.0',
          title='Tasks API',
          description='Simple tasks management REST API, using Flask + Celery')
api.namespaces.clear()
ns = api.namespace('api',
                   description='Allows to submit, schedule, and list tasks')


@ns.route('/task')
class Task(Resource):
    def get(self):
        '''Lists all processed tasks'''
        tasks = []
        for key in redis_db.scan_iter("celery-task-meta-*"):
            content = json.loads(redis_db.get(key))
            tasks.append({
                'id': content['task_id'],
Ejemplo n.º 36
0
from flask_restplus import Api

api = Api(version='0.1',
          title='Accountmanagement Battle of AI API',
          description='Login, Registration etc all done here.')
Ejemplo n.º 37
0
from flask import Flask
from flask_restplus import Resource, Api
from flask_cors import CORS
from pymongo import MongoClient

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

# set up mongodb
MONGODB_URI = "mongodb://*****:*****@ds121603.mlab.com:21603/9321_asg3"
client = MongoClient(MONGODB_URI, connectTimeoutMS=30000)
db = client.get_database("9321_asg3")

# parse query
parser = reqparse.RequestParser()
parser.add_argument('order',
                    choices=list(column for column in student_model.keys()))
parser.add_argument('ascending', type=inputs.boolean)


@api.route('/predictPrice')
class Price(Resource):
    def get(self):

        # retrieve the query parameters
        args = parser.parse_args()
        order_by = args.get('order')
        ascending = args.get('ascending', True)

        init_doc = db['init']
Ejemplo n.º 38
0
from flask import Flask, request
from flask_restplus import Api, Resource


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

a_language = api.model('Language', {'language': fields.String('The Language.')})

languages = []
python = {'language':'Python'}
language.append(python)

@app.route('/language')
Class Language(Resource):
    def get(self):
        #return {'hey':'there'}
	    return languages

    @api.expect(a_language)
    def post(self):
	    languages.append(api.payload)
		return {'result' : 'Language added'}, 201
		
if __name__ == '__main__':
    app.run(debug=True)
Ejemplo n.º 39
0
from flask_cors import CORS
from flask_restplus import Api, fields, Resource
from services.analyzerservice import AnalyzerService
from services.areaservice import AreaService
from services.cameraservice import CameraService
from services.eventservice import EventService

event_service = EventService()
area_service = AreaService(event_service)
camera_service = CameraService(area_service)
analyzer_service = AnalyzerService(event_service, camera_service, area_service)

flask_app = Flask(__name__)
CORS(flask_app)
app = Api(app=flask_app,
          title="Camera Api",
          default="Camera Api",
          default_label="Camera Api")

configuration_name_space = app.namespace('configuration')
device_name_space = app.namespace('devices')
events_name_space = app.namespace('events')
area_name_space = app.namespace('areas')

camera_request = app.model(
    'Camera configuration params', {
        'name':
        fields.String(required=True, description='Id of the camera'),
        'ip':
        fields.String(required=True, description='Camera ip address'),
        'user':
        fields.String(required=True, description='Camera user'),
Ejemplo n.º 40
0
from flask import Flask
from flask_restplus import Api
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
app.api = Api(app, title='Simple Weather API')


def get_app():
    global app
    return app
Ejemplo n.º 41
0
logger_3.addHandler(swagger_file_handler)
# logging.basicConfig(filename="./flask.log", level=logging.INFO)
time.sleep(1)
# todo : Cache FlushAll !!!
cache = connect_redis()
cache.flushall()
log("Starting Context Aware System", "No Message", _st)
time.sleep(1)
context_awareness_setting()
app = Flask(__name__, template_folder='templates', static_folder='static')
api = Api(
    app,
    version='0.10',
    title='상황인지 시스템',
    description=
    '<h2 style="background-color: #fde3c9e0">에브리봇 물걸레 청소기 기반 서비스 시나리오.</h1>'
    '<div style="background-color: #eefdc9e0">case1 : 마지막 주기보고 시각을 기록한 뒤, 일정 시각 경과 후 작동하고 '
    '내부 batch daemon이 분단위로 체크, 3분 경과시 와이파이 연결 상태 체크 관련 문구 notification 발생.\n'
    'case2 : RSSI 값을 매회 체크하여 일정 수치 이하로 감소시 작동. 일시적인 하락으로 인한 오탐 방지 로직 검토 진행.\n</div>',
    validate=True,
    default=None)
redis_swagger = api.namespace(
    "Redis",
    description=
    '<div style="background-color: #dc17171a; text-align: right">저장된 Redis 확인용 APIs 입니다.</div>'
)
todo = api.model('Todo',
                 {'index': fields.Integer(readonly=True, description='HHHHH')})
app.static_folder = 'static'
# cat_name_space = api.namespace("cats", description='<div style="background-color: #caddff; text-align: right">테스트 API 카테고리 01 입니다.</div>')
# dog_name_space = api.namespace("dogs", description='<div style="background-color: #e0fff9; text-align: right">테스트 API 카테고리 02 입니다.</div>')
Ejemplo n.º 42
0
werkzeug.cached_property = werkzeug.utils.cached_property

# Import FLASK
from flask import Flask, request, jsonify

# Import RESTPLUS libraries
from flask_restplus import Api, Resource, fields

# Import DS libraries
import numpy as np
import pickle

# Define app and api object
application = Flask(__name__)
api = Api(application,
          version='1.0',
          title='Logistic Regression',
          description='Logistic Regression')
ns = api.namespace('DS2_3_docker_and_aws', description='Methods')

# Define arguments for our API, in this case, it is going to be just a comma separated string
single_parser = api.parser()
single_parser.add_argument('input', type=str, required=True, help='input CSV')

# Load objects from pickle files
labelEncoder1 = pickle.load(open('pickle_files/labelEncoder1.pickle', 'rb'))
labelEncoder2 = pickle.load(open('pickle_files/labelEncoder2.pickle', 'rb'))
standardScaler = pickle.load(open('pickle_files/standardScaler.pickle', 'rb'))
model = pickle.load(open('pickle_files/log_reg_model.pickle', 'rb'))


@ns.route('/prediction')
Ejemplo n.º 43
0
from flask import Flask
from flask_restplus import Api, Resource, fields

app = Flask(__name__)
api = Api(app,
          version='1.0',
          title='TodoMVC API',
          description='A simple TodoMVC API')

ns = api.namespace('todos', description='TODO operations')

todo = api.model(
    'Todo', {
        'id':
        fields.Integer(readOnly=True,
                       description='The task unique identifier'),
        'task':
        fields.String(required=True, description='The task details')
    })


class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "Todo {} doesn't exist".format(id))
Ejemplo n.º 44
0
from flask import Flask
from flask_restplus import Api, Resource
from classifier import Classifier

server = Flask(__name__)
app = Api(app=server)

name_space = app.namespace('analyzer',
                           description='Social Sentiment Analyzer APIs')

cl = Classifier()


@name_space.route("/predict/<string:social_text>")
class MainClass(Resource):
    def get(self, social_text):
        cleaned = cl.clean_text(social_text)
        vectorized = cl.vectorize_text(cleaned)
        prediction = cl.predict_text(vectorized)
        return {"prediction": prediction}


if __name__ == '__main__':
    server.run(debug=True)
Ejemplo n.º 45
0
from flask import Flask, send_from_directory
from flask_restplus import Api
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import os
from config import Configuration

# Flask 
app = Flask(__name__)
api = Api(app, version="0.0.1", title='TauCeti',
description="TauCeti Notes Sharing App's Backend Server, pre-Alpha")

# Configuring
app.config.from_object(Configuration)

# SQLALchemy
db = SQLAlchemy(app)

# Flask-restplus
from namespaces.notes import api as notes
from namespaces.courses import api as courses
from namespaces.users import api as users
from namespaces.auth import api as auth
from namespaces.messages import api as messages
from namespaces.report import api as report

api.add_namespace(notes, path='/notes')
api.add_namespace(courses, path='/courses')
api.add_namespace(users, path='/users')
api.add_namespace(auth, path='/auth')
api.add_namespace(messages, path='/messages')
Ejemplo n.º 46
0
from src import Mongo, System
from flask import Flask, request, g
from flask_restplus import Resource, Api, fields
from elasticapm.contrib.flask import ElasticAPM
from elasticapm.handlers.logging import LoggingHandler
import time, datetime

mdb = Mongo.Mongo("twitter", "twitter")
l = System.Log()

app = Flask(__name__)
api = Api(
    app,
    version='1.0',
    title='Get Tweets API',
    description='An API to get tweets',
)

apm = ElasticAPM(app,
                 server_url='http://apm-server-apm-server:8200',
                 service_name='get-tweets-api',
                 logging=True)


@api.doc(params={
    'topic': 'An hashtag (without #)',
    "number": "size of response (default 5)"
},
         responses={200: 'List the most followed users per topic'})
class MostFolowed(Resource):
    def get(self, topic={}, number=5):
Ejemplo n.º 47
0
import logging

from flask_restplus import Api

log = logging.getLogger(__name__)

api = Api(version="2.0",
          title="Hello World v2.0",
          description="Hello World v2.0")
Ejemplo n.º 48
0
from werkzeug.contrib.fixers import ProxyFix

from app.data_analyze.regression_analyze import regBase
from app.data_analyze.classify_analyze import clfBase
from app.data_analyze.cluster_analyze import cluBase
from app.model.dto import passergerInfo

from app.utils.redis import Redis

# 公共api对象

# 回归接口
api = Api(app,
          version='1.0',
          title='Titanic survive predict API',
          description=
          'API for titanic passenger survive predict with machine learning',
          default='Regression',
          default_label='')
app.wsgi_app = ProxyFix(app.wsgi_app)

# 分类接口
clf_ns = api.namespace('Classifier')

# 聚类接口
clu_ns = api.namespace('Cluster')

passengerInfo = api.model('passengerInfo', passergerInfo)


# ----- Regression -------
Ejemplo n.º 49
0
from .parser import setup_parser
from .database import DataBase
from .utils import is_date

JSON_HEADER = {'Content-Type': 'application/json'}
HTML_HEADER = {'Content-Type': 'text/html'}

# App settings
app = Flask(__name__)
app.config['UPLOAD_EXTENSIONS'] = ['.xlsx', '.csv']
app.secret_key = 'YOUR SECRET KEY'

api = Api(app=app,
          version="1.0",
          title="XLSX/CSV files processing service",
          description="This service process XLSX/CSV files "
          "and store it to the PostgreSQL database.")
upload_ns = api.namespace('upload', description='Upload name space.')
upload_parser = setup_parser(upload_ns.parser())


@upload_ns.route('/')
class UploadDemo(Resource):
    """Class that provides GET and POST methods to process input files."""
    @upload_ns.produces(['text/html'])
    @upload_ns.response(200, 'Success')
    def get(self):
        """GET method that renders home page."""
        response = make_response(render_template('home_page.html'), 200,
                                 HTML_HEADER)
Ejemplo n.º 50
0
from nlp.evaluation_model import WebPageTypeModelEvaluation
from nlp.modeler import WebPageTypeModeler
from nlp.predict_data import PredictWebPageType
from nlp.tokenizer import GeneralTokenizer
from parser.content_getter import ContentGetter
from parser.crawler import PageCrawlerWithStorage, PageCrawler
from parser.extractor import DragnetPageExtractor, ReadabilityPageExtractor, GoosePageExtractor, \
    GooseDragnetPageExtractor
from util.database import get_mg_client, get_redis_conn
from util.utils import get_logger

logger = get_logger(__name__)

app = Flask(__name__)
api = Api(app,
          doc='/doc/',
          version='1.0',
          title='Web pages type classification')

model_loc_dir = path.dirname(path.realpath(__file__)) + '/../model'
default_model_name = '6k_ecommerce_news_blog_urls_dragnet_extractor.model'
default_model_file_path = path.join(model_loc_dir, default_model_name)
crawler = PageCrawler()
extractor = DragnetPageExtractor()
content_getter = ContentGetter(crawler=crawler, extractor=extractor)
classifier = PredictWebPageType(model_loc_dir, default_model_name,
                                content_getter)

# set cur model to redis
kv_storage = get_redis_conn()
kv_storage.set(classifier.model_name_key, default_model_name)
Ejemplo n.º 51
0
from .images import api as ns_images
from .models import api as ns_models
from .users import api as ns_users
from .admin import api as ns_admin
from .tasks import api as ns_tasks
from .undo import api as ns_undo
from .info import api as ns_info
from .labelme import api as ns_labelme
from config import Config

# Create /api/ space
blueprint = Blueprint('api', __name__, url_prefix='/api')

api = Api(
    blueprint,
    title=Config.NAME,
    version=Config.VERSION,
)

# Remove default namespace
api.namespaces.pop(0)

# Setup API namespaces
api.add_namespace(ns_info)
api.add_namespace(ns_users)
api.add_namespace(ns_images)
api.add_namespace(ns_annotations)
api.add_namespace(ns_categories)
api.add_namespace(ns_datasets)
api.add_namespace(ns_exports)
api.add_namespace(ns_tasks)
Ejemplo n.º 52
0
from flask_restplus import Resource, Api
import os
import ast
from .classifier import cld2_prediction, ft_prediction
import traceback


api = Api(
    title='Mention Language Classification API',
    description='Mention Language Classification API',
    prefix=os.getenv('API_PREFIX', ''),
    doc=os.getenv('API_PREFIX', '/'))

ns = api.namespace('langindentification', description='Language analyzer')
parser = api.parser()

parser.add_argument(
    'texts',
    required=True,
    help="""{
        "texts": [
            "之前推荐过BUCC自己的糖果",
            "nə baxırsan siçan?",
            "Эксклюзивная, Современная игра на бумаге сделал сам  Своими руками(HD)"
        ]
    }
    """,
    location='json'
    )

Ejemplo n.º 53
0
from flask import Blueprint
from flask_restplus import Api
from forest_monitor.monitor.controller import api as monitor_ns
from forest_monitor.stac_compose.controller import api as stac_compose_ns

blueprint = Blueprint('forest_monitor', __name__, url_prefix='/api')

api = Api(blueprint, doc=False)

api.add_namespace(monitor_ns)
api.add_namespace(stac_compose_ns)
Ejemplo n.º 54
0
from flask_restplus import Api

api = Api(version='1.0', title='Dummy API', description='An example API')
Ejemplo n.º 55
0
from flask import Flask
from config import Config
from flask_mongoengine import MongoEngine
from flask_restplus import Api

api = Api()

app = Flask(__name__)
app.config.from_object(Config)

db = MongoEngine()
db.init_app(app)
api.init_app(app)

from application import routes
Ejemplo n.º 56
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Arne Neumann <*****@*****.**>
"""This module contains a REST API for a mock RST parser.
"""

import io
import tempfile
from pathlib import Path

from flask import Flask, request, send_file
from flask_restplus import Resource, Api
import werkzeug

app = Flask(__name__)  # create a Flask app
api = Api(app)  # create a Flask-RESTPlus API

RS3_OUTPUT_TEMPLATE = """
<rst>
  <header>
    <relations>
      <rel name="elaboration" type="rst" />
    </relations>
  </header>
  <body>
    <segment id="1">{begin}</segment>
    <segment id="2" parent="1" relname="elaboration">... {end}</segment>
  </body>
</rst>
"""
Ejemplo n.º 57
0
from flask_restplus import Api
from flask import Blueprint

from .main.controller.user_controller import api as user_ns
from .main.controller.auth_controller import api as auth_ns

blueprint = Blueprint('api', __name__)

api = Api(
    blueprint,
    title='Pip-Monitoring',
    version='1.0',
    description=
    'A simple curl based monitoring tool that check http_status_code for monitoring'
)

api.add_namespace(user_ns, path='/user')
api.add_namespace(auth_ns)
Ejemplo n.º 58
0
    """ USAGE: python-verifier will send a request with the body:
               {consumer: 'Consumer name', states: ['a thing exists']}
               to this enpoint. One state at the time is allowed.
    """
    data = request.get_json()
    prepare_state(data["states"][0])
    return jsonify({
        "productName": "Laptops",
        "locationName": "Bangalore",
        "quantity": 1000
    })


api = Api(app,
          version='1.0.0',
          title='python-producer',
          description='A sample python producer app for testing pact',
          doc='/apidocs',
          serve_challenge_on_401=True)

ns = api.namespace('api')


@ns.route("/inventory")
class PipelineState(Resource):
    """
    Class that exposes APIs to get and set the inventory.
    """
    def get(self):
        try:
            response = producerService.get_inventory()
            return jsonify(response)
Ejemplo n.º 59
0
from flask_restplus import Api
import config
from sqlalchemy.orm.exc import NoResultFound

log = logging.getLogger(__name__)

authorizations = {
    'apikey': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'X-API-KEY'
    }
}

api = Api(version=config.API_VERSION, title=config.API_TITLE, description=config.API_DESCRIPTION,authorizations=authorizations, security='apikey')


@api.errorhandler
def default_error_handler(e):
    message = 'An unhandled exception occurred.'
    log.exception(message)

    if not config.FLASK_DEBUG:
        return {'message': message}, 500


@api.errorhandler(NoResultFound)
def database_not_found_error_handler(e):
    log.warning(traceback.format_exc())
    return {'message': 'A database result was required but none was found.'}, 404
Ejemplo n.º 60
0
class FlaskApplication(ApplicationInterface):
    def __init__(
        self: object,
        host: str,
        port: int,
        character_domain: CharacterManagementInterface,
        dataset_domain: DatasetManagementInterface,
        garment_domain: GarmentManagementInterface,
        debug: bool = False,
    ) -> object:
        logging.debug("FlaskApplication.__init__")
        self.app = Flask(__name__)
        self.api = Api(self.app)
        self.host = host
        self.port = port
        self.debug = debug
        self.character_domain = character_domain
        self.dataset_domain = dataset_domain
        self.garment_domain = garment_domain

        # Character namespace
        character_namespace = Namespace("character")
        character_namespace.add_resource(
            CharacterHandler,
            "",
            resource_class_kwargs={"domain": character_domain})
        self.api.add_namespace(character_namespace,
                               path="/characters/<uuid:character_id>")
        # Characters namespace
        characters_namespace = Namespace("characters")
        characters_namespace.add_resource(
            CharactersHandler,
            "",
            resource_class_kwargs={"domain": character_domain})
        self.api.add_namespace(characters_namespace, path="/characters")
        # Datasets namespace
        datasets_namespace = Namespace("datasets")
        datasets_namespace.add_resource(
            DatasetsHandler,
            "",
            resource_class_kwargs={"domain": dataset_domain})
        self.api.add_namespace(datasets_namespace, path="/datasets")
        # Garment namespace
        garment_namespace = Namespace("garment")
        garment_namespace.add_resource(
            GarmentHandler,
            "",
            resource_class_kwargs={"domain": garment_domain})
        self.api.add_namespace(garment_namespace,
                               path="/clothes/<uuid:garment_id>")
        # Clothes namespace
        clothes_namespace = Namespace("clothes")
        clothes_namespace.add_resource(
            ClothesHandler,
            "",
            resource_class_kwargs={"domain": garment_domain})
        self.api.add_namespace(clothes_namespace, path="/clothes")

    def run(self) -> None:
        logging.debug("FlaskApplication.run")
        self.app.run(host=self.host, port=self.port, debug=self.debug)