Exemplo n.º 1
0
    def test_marshal_does_not_hit_unrequired_attributes(self):
        api = Api(self.app)

        model = api.model(
            'Test', {
                '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,
        })
Exemplo n.º 2
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'))
Exemplo n.º 3
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,
        }])
Exemplo n.º 4
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')
Exemplo n.º 5
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)
Exemplo n.º 6
0
    def test_marshal_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):
            def get(self):
                return api.marshal(
                    {
                        'name': 'John Doe',
                        'age': 42,
                        'boolean': True
                    }, model)

        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_with_readonly(self):
     api = Api(self.app)
     nested_fields = api.model('NestedModel', {'name': fields.String})
     field = fields.Nested(nested_fields, readonly=True)
     self.assertEqual(field.__schema__, {
         '$ref': '#/definitions/NestedModel',
         'readOnly': True
     })
Exemplo n.º 8
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')
Exemplo n.º 9
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')
Exemplo n.º 10
0
    def test_marshal_with_skip_missing_fields(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):
                return {
                    'name': 'John Doe',
                    'age': 42,
                }

        data = self.get_json('/test/', headers={'X-Fields': '{name,missing}'})
        self.assertEqual(data, {
            'name': 'John Doe',
        })
Exemplo n.º 11
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)
Exemplo n.º 12
0
    def test_is_only_exposed_on_marshal_with(self):
        api = Api(self.app)

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

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

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

        self.assertNotIn('parameters', op)
Exemplo n.º 13
0
import settings
from settings import GENERAL_DEBUG

from flask import Flask, request
from flask.ext.restplus import Api, apidoc, Resource, reqparse, fields
from werkzeug.datastructures import FileStorage

from models import Responses
from tools import initializator

from controllers import Installator, Check, Deploy, ControllerError

app = Flask(__name__)
api = Api(
    app,
    version='1',
    title='comcloud-node-agent',
    description='An unified API to all Docker operations.',
)

## Response models
generalResponseModel = api.model('General', Responses.error)
statusResponseModel = api.model('Status', Responses.error)
errorResponseModel = api.model('Error', Responses.error)

# Common


def not_implemented():
    result = {
        'error': 'not_implemented',
        'description': 'Feature not implemented yet'
Exemplo n.º 14
0
from flask import Flask
from flask.ext.restplus import Api
from flask.ext.restplus import fields
from sklearn.externals import joblib

app = Flask(__name__)

api = Api(
   app, 
   version='1.0', 
   title='Credit API',
   description='A simple Prediction API')

ns = api.namespace('approve_credit', 
   description='Approve Credit Operations')
from .attendees import api as attendees_api
from .tickets import api as tickets_apt
from helpers.error_docs import api as error_models
from helpers.errors import (
    NotFoundError,
    NotAuthorizedError,
    PermissionDeniedError,
    ValidationError,
    InvalidServiceError,
    ServerError,
)

api_v2 = Blueprint('api', __name__, url_prefix='/api/v2')

api = Api(api_v2,
          version='2.0',
          title='Organizer Server APIs',
          description='Open Event Organizer APIs')

api.add_namespace(event_api)
api.add_namespace(session_api)
api.add_namespace(track_api)
api.add_namespace(speaker_api)
api.add_namespace(sponsor_api)
api.add_namespace(microlocation_api)
api.add_namespace(login_api)
api.add_namespace(exports_api)
api.add_namespace(imports_api)
api.add_namespace(users_api)
api.add_namespace(extras_api)
api.add_namespace(notifications_api)
api.add_namespace(error_models)
Exemplo n.º 16
0
import hysds_commons.container_utils
import hysds_commons.hysds_io_utils
import hysds_commons.job_spec_utils
import hysds_commons.job_utils

from hysds.log_utils import log_custom_event

from mozart import app

#Library backend imports
import mozart.lib.job_utils
import mozart.lib.queue_utils


services = Blueprint('api_v0-2', __name__, url_prefix='/api/v0.2')
api = Api(services, ui=False, version="0.2", title="Mozart API",
          description="API for HySDS job submission and query.")


#Namespace declarations
QUEUE_NS = "queue"
queue_ns = api.namespace(QUEUE_NS, description="Mozart queue operations") 

JOBSPEC_NS = "job_spec"
job_spec_ns = api.namespace(JOBSPEC_NS, description="Mozart job-specification operations") 

JOB_NS = "job"
job_ns = api.namespace(JOB_NS, description="Mozart job operations")

CONTAINER_NS = "container"
container_ns = api.namespace(CONTAINER_NS, description="Mozart container operations")
Exemplo n.º 17
0
from flask.ext.restplus import Api, Resource, fields

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR

from tasks import BaseTask, recorder, example

import atexit

app = Flask(__name__)
app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint,
          version='1.0',
          title="APScheduler API",
          description="A simple API to access APScheduler.")
app.register_blueprint(blueprint)

ns = api.namespace('jobs', description='Job operations')

# Fields that are expected and need to be exposed from a Job
fields = api.model(
    'Job', {
        'id':
        fields.String(),
        'name':
        fields.String(),
        'task_class':
        fields.String(attribute=lambda x: x.func_ref.replace(':', '.').replace(
            '.execute', '')),
Exemplo n.º 18
0
# -*- coding: utf-8 -*-

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restplus import Api

db = SQLAlchemy()
api = Api(version='1.0',
          title='Gastos Abertos',
          description='API para acesso a dados orçamentários',
          default='/api/v1')
Exemplo n.º 19
0
Logger = logging.getLogger(__name__)

service = Blueprint(
    'api',
    __name__)


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


api = Api(service,
          title='INSEE/IRIS Geolocalizer',
          ui=False,
          version='0.1',
          description="Retrieve some data related to the IRIS codes. Look for an IRIS from an address.")

iris_code_parser = api.parser()
iris_code_parser.add_argument("limit", required=False, default=10, dest='limit',
                              location='args', help='Limit')

address_parser = api.parser()
address_parser.add_argument("q", required=True, dest='q', location='args',
                            help='Query')

IRIS_MODEL = OrderedDict([('iris', fields.String),
                          ('city', fields.String),
                          ('citycode', fields.String),
                          ('name', fields.String),
Exemplo n.º 20
0
from flask import Flask, request
from flask.ext.restplus import Api, apidoc, Resource, reqparse, fields, marshal_with
from schemas import builderSchemas, clusterSchemas, composerSchemas, generalSchemas
from werkzeug.datastructures import FileStorage

from controllers.builder import builderOps
from controllers.cluster import clusterOps
from controllers.composer import composeOps
from controllers.management import managementOps
from datastore import dataStore
from datastore.dataStore import DataStore

app = Flask(__name__)
api = Api(
    app,
    version='0.5',
    title='Docker commander API',
    description='An unified API to all Docker operations.',
)
datastore = DataStore(app)

# Common

errorResponseModel = api.model('Error', generalSchemas.basic_error_response)


def not_implemented():
    result = {
        'error': 'not_implemented',
        'description': 'Feature not implemented yet'
    }
    return result, 500
Exemplo n.º 21
0
from flask import Flask
from flask.ext.restplus import Api, Resource, fields

app = Flask(__name__)
api = Api(
    app,
    version='1.0',
    title='Todo API',
    description=
    'A simple TODO API extracted from the original flask-restful example',
)

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

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

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

listed_todo = api.model(
Exemplo n.º 22
0
from flask import Flask, Blueprint
from flask.ext.restplus import Api, Resource, fields

api_v1 = Blueprint('api', __name__, url_prefix='/api/1')

api = Api(
    api_v1,
    version='1.0',
    title='Todo API',
    description='A simple TODO API',
)

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

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

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

listed_todo = api.model(
Exemplo n.º 23
0
from flask import Flask
from flask.ext.restplus import Api

app = Flask("dmon-logstash")
app.config['RESTPLUS_VALIDATE'] = True
api = Api(
    app,
    version='0.0.2',
    title='DICE Monitoring Logstash API',
    description=
    "RESTful API for the DICE Monitoring Platform  Logstash agent (dmon-logstash)",
)

# changes the descriptor on the Swagger WUI and appends to api /dmon and then /v1
agent = api.namespace('agent', description='dmon logstash operations')
Exemplo n.º 24
0
def setup_logging(app):
    log_file_path = app.config.get('LOG_FILE')
    log_level = app.config.get('LOG_LEVEL', logging.WARN)

    if log_file_path: # pragma: no cover
        file_handler = RotatingFileHandler(log_file_path)
        file_handler.setFormatter(Formatter(
            '%(name)s:%(levelname)s:[%(asctime)s] %(message)s '
            '[in %(pathname)s:%(lineno)d]'
            ))
        file_handler.setLevel(log_level)
        app.logger.addHandler(file_handler)
        logger = logging.getLogger('sun4allmobile')
        logger.setLevel(log_level)
        logger.addHandler(file_handler)

def setup_db(app):
    app.db = SQLAlchemy(app)

app=create_app()    
api=Api(
    app, version='1.0', 
    title='Todo API',
    description='A simple TODO API extracted from the original flask-restful example',
    default='api_socientize',
    default_label='Socientize Swagger',
    contact='*****@*****.**'
    )
db=app.db

Exemplo n.º 25
0
 def setUp(self):
     super(SwaggerFieldsTestCase, self).setUp()
     blueprint = Blueprint('api', __name__)
     self.api = Api(blueprint)
     self.app.register_blueprint(blueprint)
Exemplo n.º 26
0
#!/usr/bin/env python

from flask import Flask, Blueprint
from flask.ext.restplus import Api

app = Flask(__name__)

app.config[
    'RESTPLUS_MASK_SWAGGER'] = False  #Disables fields masks, http://flask-restplus.readthedocs.org/en/stable/mask.html
app.config[
    'SWAGGER_UI_DOC_EXPANSION'] = 'list'  #Intitial documentation expansion state (none, list or full), http://flask-restplus.readthedocs.org/en/stable/swaggerui.html

blueprint = Blueprint('api', __name__, url_prefix='/api')
#Disable documentation UI with "doc=False"
api = Api(blueprint,
          version='1.0',
          title='Vekarus API',
          description='',
          doc='/')
app.register_blueprint(blueprint)

import status
Exemplo n.º 27
0
import os, sys, json, requests, traceback
from datetime import datetime

from flask import Blueprint, request, redirect, url_for, Response, current_app
from flask.ext.restplus import Api, apidoc, Resource, fields
from flask.ext.login import login_user, logout_user, login_required

from fv_prov_es import cache
from fv_prov_es.lib.utils import get_prov_es_json, get_ttl
from fv_prov_es.lib.import_utils import get_es_conn, import_prov

NAMESPACE = "prov_es"

services = Blueprint('api_v0-2', __name__, url_prefix='/api/v0.2')
api = Api(
    services,
    ui=False,
    version="0.2",
    title="PROV-ES API",
    description="API for ingest, query, and visualization of PROV-ES documents"
)
ns = api.namespace(NAMESPACE, description="PROV-ES operations")


@services.route('/doc/', endpoint='doc')
def swagger_ui():
    return apidoc.ui_for(api)
Exemplo n.º 28
0
from app import app

from flask import Flask
from flask.ext.restplus import Api, Resource, fields

api = Api(app, version='1.0', title='TrueCar API',
    description='A simple TrueCar API borrowed from flask-restful example!',
)

ns = api.namespace('vsnLookup', description='TrueCar API')

#todo: not now probably continue later
Exemplo n.º 29
0
        'message': "This field can't be empty.",
        'status': 401,
    },
    'ValidationError': {
        'message': "This field can't be empty.",
        'status': 402,
    },
    'RestException': {
        'message': "This field can't be empty.",
        'status': 400,
    }
}

api = Api(app,
          version='1.0',
          title='API',
          description='Api para el tp de arquitectura',
          errors=errors)

#@api.errorhandler(Exception)
#def handle_custom_exception(error):
#    return {'message': 'What you want'}, 400

ed = EventDocument(api)

EventDC = ed.event
ErrorDC = ed.error
PaginateEventsDC = ed.paginateEvents

EventsDC = ed.events
Exemplo n.º 30
0
from flask import Flask
from flask.ext.restplus import Api, Resource, fields
from werkzeug.contrib.fixers import ProxyFix

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
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):