예제 #1
0
def api_decorator(cls, swagger_decorator):
    """
        Decorator for the API views:
            - add swagger documentation ( swagger_decorator )
            - add cors
            - add generic exception handling

        We couldn't use inheritance because the rest method decorator
        references the cls.SAFRSObject which isn't known
    """

    cors_domain = get_config("cors_domain")
    cls.http_methods = {
    }  # holds overridden http methods, note: cls also has the "methods" set, but it's not related to this
    for method_name in ["get", "post", "delete", "patch", "put",
                        "options"]:  # HTTP methods
        method = getattr(cls, method_name, None)
        if not method:
            continue

        decorated_method = method
        # if the SAFRSObject has a custom http method decorator, use it
        # e.g. SAFRSObject.get
        custom_method = getattr(cls.SAFRSObject, method_name, None)
        if custom_method and callable(custom_method):
            decorated_method = custom_method
            # keep the default method as parent_<method_name>, e.g. parent_get
            parent_method = getattr(cls, method_name)
            cls.http_methods[
                method_name] = lambda *args, **kwargs: parent_method(
                    *args, **kwargs)

        # Apply custom decorators, specified as class variable list
        try:
            # Add swagger documentation
            decorated_method = swagger_decorator(decorated_method)
        except RecursionError:
            # Got this error when exposing WP DB, TODO: investigate where it comes from
            # safrs.log.error("Failed to generate documentation for {} {} (Recursion Error)".format(cls, decorated_method))
            pass
        # pylint: disable=broad-except
        except Exception as exc:
            pass
            # safrs.log.exception(exc)
            # safrs.log.error("Failed to generate documentation for {}".format(decorated_method))

        # Add cors
        if cors_domain is not None:
            decorated_method = cors.crossdomain(
                origin=cors_domain)(decorated_method)
        # Add exception handling
        decorated_method = http_method_decorator(decorated_method)

        setattr(decorated_method, "SAFRSObject", cls.SAFRSObject)
        for custom_decorator in getattr(cls.SAFRSObject, "custom_decorators",
                                        []):
            decorated_method = custom_decorator(decorated_method)

        setattr(cls, method_name, decorated_method)
    return cls
예제 #2
0
    def __init__(self, host, http_port, ws_port,
                 ws_poll_interval, dring, verbose):

        self.host = host
        self.http_port = http_port
        self.ws_port = ws_port
        self.ws_poll_interval = ws_poll_interval
        self.dring = dring
        self.verbose = verbose

        # Flask Application
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 't0p_s3cr3t'
        self.app.config.update(PROPAGATE_EXCEPTIONS=True)

        # Flask Restuful API
        self.api = Api(self.app, catch_all_404s=True)

        # Cross Origin Resource Sharing is needed to define response headers
        # to allow HTTP methods from in-browser Javascript because accessing
        # a different port is considered as accessing a different domain
        self.api.decorators = [
            cors.crossdomain(
                origin='*',
                methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
                attach_to_all=True,
                automatic_options=True
            )
        ]

        self._init_api_resources()

        # Websockets
        self._init_websockets()
        self._register_callbacks()
예제 #3
0
파일: jsonapi.py 프로젝트: tate11/safrs
def api_decorator(cls, swagger_decorator):
    '''
        Decorator for the API views:
            - add swagger documentation ( swagger_decorator )
            - add cors 
            - add generic exception handling

        We couldn't use inheritance because the rest method decorator 
        references the cls.SAFRSObject which isn't known 
    '''

    cors_domain = globals().get('cors_domain', 'No_cors_domain')
    for method_name in ['get', 'post', 'delete', 'patch',
                        'put']:  # HTTP methods
        method = getattr(cls, method_name, None)
        if not method:
            continue
        # Add swagger documentation
        decorated_method = swagger_decorator(method)
        # Add cors
        decorated_method = cors.crossdomain(
            origin=cors_domain)(decorated_method)
        # Add exception handling
        decorated_method = http_method_decorator(decorated_method)
        setattr(cls, method_name, decorated_method)

    return cls
예제 #4
0
class PlateListAPI(Resource):
    #    decorators = [auth.login_required]
    #    decorators = [jsonp]
    decorators = [
        cors.crossdomain(origin='*', methods=['GET', 'PUT'], headers='*')
    ]

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        #        self.reqparse.add_argument('title', type = str, required = True, help = 'No plate title provided', location = 'json')
        #        self.reqparse.add_argument('description', type = str, default = "", location = 'json')
        super(PlateListAPI, self).__init__()

    def get(self):
        args = self.reqparse.parse_args()
        print self.reqparse.args
        return {'plates': map(lambda t: marshal(t, plate_fields), plates)}

    def put(self):
        args = self.reqparse.parse_args()
        print args

    def post(self):
        args = self.reqparse.parse_args()
        plate = {
            'id': plates[-1]['id'] + 1,
            'title': args['title'],
            'description': args['description'],
            'done': False
        }
        plates.append(plate)
        return {'plate': marshal(plate, plate_fields)}, 201
예제 #5
0
    def init_app(self, app):
        """Initialize with app."""
        self._init_client_resources(app)

        prefix = app.config['API_URL_PREFIX']
        api = Api(self.api_blueprint, prefix=prefix)
        api.decorators = [cors.crossdomain(origin='*')]
        self._init_api_resources(api)

        app.register_blueprint(self.api_blueprint)
예제 #6
0
    def __init__(self):
        self.__app = Flask(__name__)
        self.__api = Api(self.__app)
        self.__api.decorators = [
            cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])
        ]
        self.__parser = reqparse.RequestParser()
        self.__stub_to_rs_service = None

        # SSL 적용 여부에 따라 context 생성 여부를 결정한다.
        if conf.ENABLE_REST_SSL is True:
            self.__ssl_context = (conf.DEFAULT_SSL_CERT_PATH,
                                  conf.DEFAULT_SSL_KEY_PATH)
        else:
            self.__ssl_context = None
예제 #7
0
def create_app(config_name):

    app = Flask(__name__)

    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    import logging
    logging.basicConfig(
        level=logging.getLevelName(app.config.get("LOG_LEVEL")))

    logger = logging.getLogger("App")
    logger.info("Starting app!")

    register_routes(api)
    register_error_handlers(app)

    api.init_app(app)
    db.init_app(app)

    CORS(app, origins=["*"], send_wildcard=True)
    app.config['CORS_HEADERS'] = 'Content-Type'
    app.config['CORS_RESOURCES'] = {r"/*": {"origins": "*"}}

    api.decorators = [
        cors.crossdomain(
            origin='*',
            methods=['GET', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
            attach_to_all=True,
            automatic_options=False)
    ]

    from daos.http_daos import httpDAO

    @app.after_request
    def after_request(response):

        httpDAO.add_entry(path=request.path,
                          method=request.method,
                          response_code=response.status_code,
                          client_ip=request.remote_addr)

        return response

    return app
예제 #8
0
    def __init__(self):
        self.__app = Flask(__name__)
        self.__api = Api(self.__app)
        self.__api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])]
        self.__parser = reqparse.RequestParser()
        self.__stub_to_peer_service = None

        # SSL 적용 여부에 따라 context 생성 여부를 결정한다.
        if conf.ENABLE_REST_SSL == 0:
            self.__ssl_context = None
        elif conf.ENABLE_REST_SSL == 1:
            self.__ssl_context = (conf.DEFAULT_SSL_CERT_PATH, conf.DEFAULT_SSL_KEY_PATH)
        else:
            self.__ssl_context = ssl.SSLContext(_ssl.PROTOCOL_SSLv23)

            self.__ssl_context.verify_mode = ssl.CERT_REQUIRED
            self.__ssl_context.check_hostname = False

            self.__ssl_context.load_verify_locations(cafile=conf.DEFAULT_SSL_TRUST_CERT_PATH)
            self.__ssl_context.load_cert_chain(conf.DEFAULT_SSL_CERT_PATH, conf.DEFAULT_SSL_KEY_PATH)
def create_app(env='dev', services=dict()):
    # Create the flask app
    app = Flask(__name__)

    register_error_handlers(app)

    # Do everything in the app context
    with app.app_context():
        from flask import current_app, g

        g._env = env

        # Load the config
        current_app.config.from_object('app.config.config_%s.Config' % env)

        # Load all services
        for name, obj in services.iteritems():
            app.config['SERVICE'].add(name, obj)

        # Get the database connection object
        from odm import loadOdm

        loadOdm()


        # Configure the Applications API
        g._api = restful.Api(current_app)
        g._api.decorators = [
            #authenticate(node_key_allowed=current_app.config['NODE_KEY_ALLOWED'], node_key_cache_dir=current_app.config['NODE_KEY_CACHE_DIR']),
            cors.crossdomain(origin=current_app.config['CORS_ORIGIN'], methods=current_app.config['CORS_METHODS'],
                             headers=current_app.config['CORS_HEADERS'])
        ]

        # Load all further resources
        from views import loadViews
        from resources import loadResources

        loadResources()
        loadViews()

        return app
def create_app(env='dev', services=dict()):
    # Create the flask app
    app = Flask(__name__)

    register_error_handlers(app)

    # Do everything in the app context
    with app.app_context():
        from flask import current_app, g

        g._env = env

        # Load the config
        current_app.config.from_object('app.config.config_%s.Config' % env)

        # Load all services
        for name, obj in services.iteritems():
            app.config['SERVICE'].add(name, obj)

        # Get the database connection object
        from odm import loadOdm

        loadOdm()

        # Configure the Applications API
        g._api = restful.Api(current_app)
        g._api.decorators = [
            #authenticate(node_key_allowed=current_app.config['NODE_KEY_ALLOWED'], node_key_cache_dir=current_app.config['NODE_KEY_CACHE_DIR']),
            cors.crossdomain(origin=current_app.config['CORS_ORIGIN'],
                             methods=current_app.config['CORS_METHODS'],
                             headers=current_app.config['CORS_HEADERS'])
        ]

        # Load all further resources
        from views import loadViews
        from resources import loadResources

        loadResources()
        loadViews()

        return app
예제 #11
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    import logging
    logging.basicConfig(
        level=logging.getLevelName(app.config.get("LOG_LEVEL")))

    logger = logging.getLogger("App")
    logger.info("Starting app!")

    register_routes(api)
    register_error_handlers(app)

    CORS(app, origins=["*"], supports_credentials=True)
    app.config['CORS_HEADERS'] = 'Content-Type'

    api.init_app(app)
    db.init_app(app)
    ma.init_app(app)

    api.decorators = [
        cors.crossdomain(origin='*',
                         methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
                         attach_to_all=True,
                         automatic_options=False)
    ]

    if (os.environ['APP_SETTINGS'] != 'testing'):

        @app.before_request
        def client_token():
            client_token = request.headers.get('x-client-token')
            if (os.environ['AUTH_CLIENT_TOKEN'] != client_token):
                raise ClientUnauthorizedError(f"Auth client token is invalid.")

    return app
예제 #12
0
class PlateAPI(Resource):
    #    decorators = [auth.login_required]
    #    decorators = []
    decorators = [
        cors.crossdomain(origin='*', methods=['GET', 'PUT'], headers='*')
    ]

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('title', type=str, location='json')
        self.reqparse.add_argument('description', type=str, location='json')
        self.reqparse.add_argument('done', type=bool, location='json')
        super(PlateAPI, self).__init__()

    def get(self, id):
        plate = filter(lambda t: t['id'] == id, plates)
        if len(plate) == 0:
            abort(404)
        return {'plate': marshal(plate[0], plate_fields)}

    def put(self, id):
        print id
        plate = filter(lambda t: t['id'] == id, plates)
        if len(plate) == 0:
            abort(404)
        plate = plate[0]
        args = self.reqparse.parse_args()
        for k, v in args.iteritems():
            if v != None:
                plate[k] = v
        return {'plate': marshal(plate, plate_fields)}

    def delete(self, id):
        plate = filter(lambda t: t['id'] == id, plates)
        if len(plate) == 0:
            abort(404)
        plates.remove(plate[0])
        return {'result': True}
예제 #13
0
    'lat': fields.Float,
    'lon': fields.Float,
    'radius': fields.Integer
}

action_fields = {
    'task': fields.String(attribute='task_id'),
    'timestamp': fields.DateTime,
    'status': fields.String,
    'user': fields.String(attribute='user_id')
}

user_summary = {'id': fields.Integer, 'display_name': fields.String}

api = Api(app)
api.decorators = [cors.crossdomain(origin=app.config['METRICS_URL'])]

# override the default JSON representation to support the geo objects


class ApiPing(Resource):
    """a simple ping endpoint"""
    def get(self):
        return ["I am alive"]


class ApiChallenge(Resource):
    @marshal_with(challenge_summary)
    def get(self):
        """Return a single challenge"""
        c = None
예제 #14
0
파일: __init__.py 프로젝트: ynnt/quay
CROSS_DOMAIN_HEADERS = ["Authorization", "Content-Type", "X-Requested-With"]
FRESH_LOGIN_TIMEOUT = convert_to_timedelta(app.config.get("FRESH_LOGIN_TIMEOUT", "10m"))


class ApiExceptionHandlingApi(Api):
    @crossdomain(origin="*", headers=CROSS_DOMAIN_HEADERS)
    def handle_error(self, error):
        return super(ApiExceptionHandlingApi, self).handle_error(error)


api = ApiExceptionHandlingApi()
api.init_app(api_bp)
api.decorators = [
    csrf_protect(),
    crossdomain(origin="*", headers=CROSS_DOMAIN_HEADERS),
    process_oauth,
    require_xhr_from_browser,
]


def resource(*urls, **kwargs):
    def wrapper(api_resource):
        if not api_resource:
            return None

        api_resource.registered = True
        api.add_resource(api_resource, *urls, **kwargs)
        return api_resource

    return wrapper
예제 #15
0
파일: api.py 프로젝트: soltysh/blast
import os
import sys

from flask import Flask
from flask_restful import Resource, Api
from flask_restful.utils import cors

from db import Mongo

app = Flask(__name__)
api = Api(app)
api.decorators = [
    cors.crossdomain(
        origin="*",
        headers=['accept', 'Content-Type'],
        methods=['HEAD', 'OPTIONS', 'GET', 'PUT', 'POST', 'DELETE'])
]


class BlastText(Resource):
    def __init__(self):
        if 'TEXT_DB_SERVICE_HOST' in os.environ:
            self.db = Mongo(os.getenv('MONGODB_USER'), \
                os.getenv('MONGODB_PASSWORD'), \
                os.getenv('TEXT_DB_SERVICE_HOST'), \
                os.getenv('TEXT_DB_SERVICE_PORT'))
        else:
            self.db = Mongo('user', 'password', 'localhost', '27017')

    def get(self, text):
        items = []
예제 #16
0
class RestApi(Resource, RestMixin):
    headers = [
        'content-type',
    ]
    
    decorators = [crossdomain(origin="*", headers=headers)]
예제 #17
0
파일: api.py 프로젝트: bangui/JBElec
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@author: houxue
@date: 2017/5/22
"""
from flask_restful import Api
from flask_restful.utils import cors
from . import app

from api.resources.test import Hello

from api.resources.line import Line, LineHeat
from api.resources.tg import TgHeat, TgEq, TopTgHeat, TgInCircle, TgInBox
from api.resources.user import UserByType, UserInCircle, UserInBox, UserInShape, Cluster

api = Api(app)
api.decorators = [cors.crossdomain(origin='*')]

api.add_resource(Hello, '/hello')

api.add_resource(Line, '/line/query')
api.add_resource(LineHeat, '/line/heat')

api.add_resource(TgHeat, '/tg/heat')
api.add_resource(TgEq, '/tg/eq')
api.add_resource(TopTgHeat, '/tg/topTg')
api.add_resource(TgInCircle, '/tg/incircle')
api.add_resource(TgInBox, '/tg/inbox')

api.add_resource(UserByType, '/user/bytype')
api.add_resource(UserInCircle, '/user/incircle')
api.add_resource(UserInBox, '/user/inbox')
예제 #18
0
from flask_restful import Api, Resource, reqparse
from flask_restful.utils import cors
from flask_mongoengine import MongoEngine
from sentiment_scraper.models.article import Article

env = os.environ.get('NEWS_SENTIMENT_ENV', 'development')
if env == 'prod' or env == 'production':
    from server.config import ProdConfig as Config
else:
    from server.config import DevConfig as Config

app = Flask(__name__)
api = Api(app)
app.config.from_object(Config)
db = MongoEngine(app)
api.decorators = [cors.crossdomain(origin='*', headers=['Content-Type'])]


class SingleArticleRes(Resource):
    """

    """
    def get(self, id):
        response = {}
        article = Article.objects.get(id=id)
        article.load_text()
        response['result'] = article.to_json()
        return json.dumps(response), 200


class AllArticlesRes(Resource):
예제 #19
0
import json
import re
import time

from flask import Blueprint
from flask_restful import Api, Resource
from flask_restful import abort
from flask_restful import reqparse
from flask_login import current_user, login_required
from flask_restful.reqparse import Argument
from flask_restful.utils import cors


api = Blueprint('api', __name__)
# api_res = Api(api)
api_res = Api(api, decorators=[cors.crossdomain(origin='*')])

def addArg(**kwargs):
    def wrapper(cls):
        if not hasattr(cls, "argDict"):
            setattr(cls, "argDict", {})
        for k,args in kwargs.items():
            parser = reqparse.RequestParser()
            for i in args:
                parser.add_argument(i)
            cls.argDict[k] = parser
        return cls
    return wrapper

def abortValueError(name, message=""):
    abort(400, message="Arg <{0}> Error! {1}".format(name, message))
예제 #20
0
from flask_oauthlib.provider import OAuth2Provider
from flask_restful.utils import cors
from celery import Celery
from logging.handlers import RotatingFileHandler

#app
app = Flask(__name__)
app.config.from_object('config')

#database
db = MongoEngine(app)

#api
api = restful.Api(app)
api.decorators = [
    cors.crossdomain(origin='*',
                     headers="origin,content-type,accept,authorization")
]

#oauth
oauth = OAuth2Provider(app)

#logging
file_handler = logging.handlers.RotatingFileHandler(
    app.config['HABITAT_LOG_FILE'], maxBytes=1024 * 1024 * 100, backupCount=20)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(
    logging.Formatter('%(asctime)s, %(levelname)s, %(message)s'))
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(file_handler)

#tasks
예제 #21
0
#fh = logging.FileHandler('flask.log')
#fh.setLevel(logging.DEBUG)
#ch = logging.StreamHandler()
#ch.setLevel(logging.DEBUG)
#logger.addHandler(fh)
#logger.addHandler(ch)
#app.logger.addHandler(fh)
#app.logger.addHandler(ch)

#login
login_manager = LoginManager(app)
login_manager.login_view = "%s/choose-provider" % app.config['BASE_URL']

#api
api = restful.Api(app)
api.decorators=[cors.crossdomain(origin='*', headers = "origin,content-type,accept,authorization")]

@api.representation('text/html')
def output_html(data, code, headers):
    if not isinstance(data, list):
        template = '%s.html' % data.get('slug', 'registerbase')
        resp = make_response(render_template(template, data=data))
    else:
        resp = make_response(render_template('registerbase_list.html', data_list=data))
    for key, val in headers.items():
        resp.headers[key] = value
    return resp

#oauth
oauth = OAuth2Provider(app)
예제 #22
0
from api.login import Login
from api.logout import Logout
from api.search import Search
from api.milestone import Milestone
from api.set_skills import SetSkills
from api.get_skills import GetSkills
from api.create_skill import CreateSkill
from api.guideline import Guideline
from api.remove_skill import RemoveSkill
from api.remove_milestone import RemoveMilestone

api = Api(app)
api.decorators = [
    cors.crossdomain(
        origin='*',
        headers=['accept', 'Content-Type', 'Access-Control-Allow-Origin'])
]
api.add_resource(Login, "/login")
api.add_resource(Logout, "/logout")
api.add_resource(Search, "/search")
api.add_resource(Milestone, "/milestone")
api.add_resource(SetSkills, "/setSkills")
api.add_resource(GetSkills, "/getSkills")
api.add_resource(CreateSkill, "/createSkill")
api.add_resource(Guideline, "/guideline")
api.add_resource(RemoveSkill, "/deleteSkill")
api.add_resource(RemoveMilestone, "/deleteMilestone")

if __name__ == "__main__":
    app.run(host="0.0.0.0")
예제 #23
0
from flask_restful import Api

from app import app
from .infofill import UserView, RoleView, ActivateAccount, Authenticate, AttachUserRole
from flask_restful.utils import cors

app.secret_key = 'nexii'

restServerInstance = Api(app)
restServerInstance.decorators = [cors.crossdomain(origin='*')]

restServerInstance.add_resource(AttachUserRole,
                                "/api/v1.0/attach/user/role/",
                                endpoint="AttachUserRole")
restServerInstance.add_resource(UserView,
                                "/api/v1.0/user/",
                                endpoint="UserView")
restServerInstance.add_resource(RoleView,
                                "/api/v1.0/role/",
                                endpoint="RoleView")
restServerInstance.add_resource(ActivateAccount,
                                "/api/v1.0/activate/",
                                endpoint="activate_account")
restServerInstance.add_resource(Authenticate,
                                "/api/v1.0/auth/signin/",
                                endpoint="Authenticate")
예제 #24
0
from flask_restful import Api, Resource, reqparse
from flask_restful.utils import cors
from flask_mongoengine import MongoEngine
from sentiment_scraper.models.article import Article

env = os.environ.get('NEWS_SENTIMENT_ENV', 'development')
if env == 'prod' or env == 'production':
    from server.config import ProdConfig as Config
else:
    from server.config import DevConfig as Config

app = Flask(__name__)
api = Api(app)
app.config.from_object(Config)
db = MongoEngine(app)
api.decorators = [cors.crossdomain(origin='*', headers=['Content-Type'])]


class SingleArticleRes(Resource):
    """

    """
    def get(self, id):
        response = {}
        article = Article.objects.get(id=id)
        article.load_text()
        response['result'] = article.to_json()
        return json.dumps(response), 200


class AllArticlesRes(Resource):
예제 #25
0
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 18:47:34 2020

@author: Demo
"""
from flask import Flask, request, jsonify, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource
from flask_restful.utils import cors
from flask_ormapi_factory import ModelFactory, ResourceFactory, create_token, login_required
app = Flask(__name__)
app.secret_key = '123'

api = Api(app)
api.decorators = [cors.crossdomain(origin='*',\
    headers=['accept', 'Content-Type','Authorization'],methods={"HEAD","POST","GET",'OPTIONS','PUT','DELETE'})] ## 支持跨域

# 配置SQLALCHEMY
app.config[
    'SQLALCHEMY_DATABASE_URI'] = "postgresql://*****:*****@127.0.0.1/test"
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
model_factory = ModelFactory(app)
resource_factory = ResourceFactory(app)


class BaseResource(Resource):
    def options(self):
        return 'ok'
예제 #26
0
파일: api.py 프로젝트: stevebirk/eventlog
        if code == 405:
            headers['Allow'] = e.valid_methods

        enhanced_data = copy.deepcopy(envelope)
        enhanced_data.update(copy.deepcopy(error_meta))
        enhanced_data["meta"]["error_type"] = e.__class__.__name__
        enhanced_data["meta"]["code"] = code
        enhanced_data["meta"]["error_message"] = data['message']

        resp = self.make_response(enhanced_data, code, headers)

        if code == 401:  # pragma: no cover
            resp = self.unauthorized(resp)

        return resp


class Argument(_Argument):
    def convert(self, value, op):
        try:
            return super().convert(value, op)
        except Exception as e:
            message = "Invalid value for '%s': %s" % (self.name, str(e))
            raise type(e)(message)

    def handle_validation_error(self, error, bundle_errors):
        abort(400, message=str(error))


api = Api(catch_all_404s=True, decorators=[cors.crossdomain(origin='*')])
예제 #27
0
from flask import Blueprint
from flask_restful import Api, Resource, url_for
from flask_restful.utils import cors

api_bp = Blueprint('api', __name__)
api = Api(api_bp)
api.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type','Authorization'])]

from . import routes
예제 #28
0
파일: app.py 프로젝트: dbertouille/lolable2
from flask import Flask
from flask_restful import Api
from flask_restful.utils import cors
from extensions import *

app = Flask('lolws')
app.config.from_pyfile('lolws.cfg')
api = Api(app, decorators=[cors.crossdomain(origin='*')])
init_extensions(app)

from resources import *

api.add_resource(Authenticate, '/authenticate')

api.add_resource(ArchiveList, '/archive')

api.add_resource(BlogList, '/blogs')
api.add_resource(Blog, '/blogs/<int:blog_id>', '/comics/<int:comic_id>/blog')

api.add_resource(ComicList, '/comics')
api.add_resource(Comic, '/comics/<string:id>', '/comics/<int:id>')

api.add_resource(ConfigurationList, '/configuration')

if __name__ == '__main__':
    app.run(threaded=True)
from flask_restful import Api
from flask_restful.utils import cors
from flask_pymongo import PyMongo

api_decorators = [cors.crossdomain('*')]
api = Api(decorators=api_decorators)
api.decorators
mongo = PyMongo()
예제 #30
0
def load_api(app):
    apis = Api(app)
    apis.decorators = [cors.crossdomain(origin='*')]
    apis.add_resource(Login, '/login')
    apis.add_resource(Reg, '/register')
예제 #31
0
from flask import Flask, request, current_app
from flask_restful import Resource, Api
from flask_restful.utils import cors

from src.power_data import PowerData
from src.zone_data import ZoneData
from src.simulation_data import SimulationData

app = Flask(__name__, static_folder='static', static_url_path='')
api = Api(app, decorators=[cors.crossdomain(origin='*')])


class Root(Resource):
    def get(self):
        return current_app.send_static_file('index.html')


#api.add_resource(ZoneDataByDate, '/api/ZoneData/<string:date>')
api.add_resource(ZoneData, '/api/ZoneData/<int:resource_id>')
api.add_resource(PowerData, '/api/PowerData')
api.add_resource(SimulationData, '/api/SimulationData')
api.add_resource(Root, '/')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8000)
예제 #32
0
from flask_restful.utils import cors
from resources.nfl.player import NFL_Player_2015, All_NFL_Players_2015
from resources.nfl.team import NFL_Teams_2015, NFL_Team_2015
import resources.nfl.totals as t
import resources.nfl.games as g
import resources.nfl.trending as trend



from models.nfl_qb_game_2015 import NFL_QB_Game_2015_M
from models.nfl_rb_game_2015 import NFL_RB_Game_2015_M
from models.nfl_wr_game_2015 import NFL_WR_Game_2015_M
from models.nfl_te_game_2015 import NFL_TE_Game_2015_M


api = Api(app)
api.decorators = [cors.crossdomain(origin='*')]

# Public APIS

api.add_resource(NFL_Teams_2015, '/api/nfl/teams')
api.add_resource(NFL_Player_2015, '/api/nfl/player/<int:player_id>', endpoint='player_id')
api.add_resource(NFL_Team_2015, '/api/nfl/team/<int:team_id>', endpoint='team_id')

# Private APIS

api.add_resource(All_NFL_Players_2015, '/api/nfl/players')
api.add_resource(t.Pos_Totals_2015, '/api/nfl/totals/<string:pos>')
api.add_resource(g.Pos_Games_2015, '/api/nfl/games/<string:pos>')
api.add_resource(trend.Trending_Players, '/api/nfl/trending')
예제 #33
0
def api_decorator(cls, swagger_decorator):
    """ Decorator for the API views:
            - add swagger documentation ( swagger_decorator )
            - add cors
            - add generic exception handling

        We couldn't use inheritance because the rest method decorator
        references the cls.SAFRSObject which isn't known

        :param cls: The class that will be decorated (e.g. SAFRSRestAPI, SAFRSRestRelationshipAPI)
        :param swagger_decorator: function that will generate the swagger
        :return: decorated class
    """

    cors_domain = get_config("cors_domain")
    cls.http_methods = {
    }  # holds overridden http methods, note: cls also has "methods" set, but it's not related to this
    for method_name in [
            "patch",
            "post",
            "delete",
            "get",
            "put",
            "options",
    ]:  # HTTP methods, "put isn't used by us but may be used by a hacky developer"
        method = getattr(cls, method_name, None)
        if not method:
            continue

        decorated_method = method
        # if the SAFRSObject has a custom http method decorator, use it
        # e.g. SAFRSObject.get
        custom_method = getattr(cls.SAFRSObject, method_name, None)
        if custom_method and callable(custom_method):
            decorated_method = custom_method
            # keep the default method as parent_<method_name>, e.g. parent_get
            parent_method = getattr(cls, method_name)
            cls.http_methods[method_name] = parent_method

        # Add cors
        if cors_domain is not None:
            decorated_method = cors.crossdomain(
                origin=cors_domain)(decorated_method)
        # Add exception handling
        decorated_method = http_method_decorator(decorated_method)

        setattr(decorated_method, "SAFRSObject", cls.SAFRSObject)

        try:
            # Add swagger documentation
            decorated_method = swagger_decorator(decorated_method)
        except RecursionError:
            # Got this error when exposing WP DB, TODO: investigate where it comes from
            safrs.log.error(
                "Failed to generate documentation for {} {} (Recursion Error)".
                format(cls, decorated_method))
        # pylint: disable=broad-except
        except Exception as exc:
            safrs.log.exception(exc)
            safrs.log.error("Failed to generate documentation for {}".format(
                decorated_method))

        # The user can add custom decorators
        # Apply the custom decorators, specified as class variable list
        for custom_decorator in getattr(cls.SAFRSObject,
                                        "custom_decorators", []) + getattr(
                                            cls.SAFRSObject, "decorators", []):
            # update_wrapper(custom_decorator, decorated_method)
            swagger_operation_object = getattr(decorated_method,
                                               "__swagger_operation_object",
                                               {})
            decorated_method = custom_decorator(decorated_method)
            decorated_method.__swagger_operation_object = swagger_operation_object

        setattr(cls, method_name, decorated_method)
    return cls
예제 #34
0
from flask import Flask
from flask_restful import Api
from flask_restful.utils import cors
from api.name import NameAPI

app = Flask(__name__)
api = Api(app)
api.decorators = [
    cors.crossdomain(origin='*',
                     headers='my-header, accept, content-type, token')
]

api.add_resource(NameAPI, '/name')

if __name__ == '__main__':
    app.run(debug=True)
예제 #35
0
from flask_restful.utils import cors
from flask_paginate import Pagination
import random
from bson.son import SON
import os
import datetime
import calendar
from dateutil.parser import *

MONGOLAB_URL = os.environ['MONGOLAB_URL']
DEFAULT_HARVEST_DATE = datetime.datetime(2016, 1, 1, 0, 0, 0)

app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(
    origin='*',
    methods=['GET'],
)]

REASONS = {
    '33(1)(a)': {
        'definition':
        'contains information or matter the disclosure of which under this Act could reasonably be expected to cause damage to the security, defence or international relations of the Commonwealth',
        'source': 'act'
    },
    '33(1)(b)': {
        'definition':
        'contains information or matter: (i) that was communicated in confidence by, or on behalf of, a foreign government, an authority of a foreign government or an international organisation (the foreign entity) to the Government of the Commonwealth, to an authority of the Commonwealth or to a person who received the communication on behalf of the Commonwealth or an authority of the Commonwealth (the Commonwealth entity); and (ii) which the foreign entity advises the Commonwealth entity is still confidential; and (iii) the confidentiality of which it would be reasonable to maintain',
        'source': 'act'
    },
    '33(1)(c)': {
        'definition':
예제 #36
0
from flask import Flask
from flask_restful import Api
from flask_restful.utils import cors

import server.resources as Resources

APP = Flask(__name__)
API = Api(APP)

API.decorators = [cors.crossdomain(origin='*', headers=['accept', 'Content-Type'])] 


API.add_resource(Resources.Services, '/')
API.add_resource(Resources.ConvexHull, '/convexHull')

if __name__ == '__main__':
    APP.run(debug=True)
예제 #37
0
}

action_fields = {
    'task': fields.String(attribute='task_id'),
    'timestamp': fields.DateTime,
    'status': fields.String,
    'user': fields.String(attribute='user_id')
}

user_summary = {
    'id': fields.Integer,
    'display_name': fields.String
}

api = Api(app)
api.decorators = [cors.crossdomain(origin=app.config['METRICS_URL'])]

# override the default JSON representation to support the geo objects


class ApiPing(Resource):

    """a simple ping endpoint"""

    def get(self):
        return ["I am alive"]


class ApiChallenge(Resource):

    @marshal_with(challenge_summary)
예제 #38
0
app = Flask(__name__)
# app.wsgi_app = WhiteNoise(app.wsgi_app)
# app.wsgi_app.add_files('static/')
app.config['FLASKS3_BUCKET_NAME'] = 'yupikmodulesweb'
# app.config['FLASKS3_REGION'] = 'DEFAULT'
app.config['FLASKS3_DEBUG'] = True
app.config['FLASKS3_HEADERS'] = {
    'Cache-Control': 'max-age=86400',
}
app.config['FLASKS3_ONLY_MODIFIED'] = True
app.config['FLASKS3_GZIP'] = True
Compress(app)
s3 = FlaskS3(app)
api = Api(app)

api.decorators = [cors.crossdomain(origin='*', automatic_options=False)]
api.methods = ['GET', 'OPTIONS', 'POST', 'PUT']

# Define parser and request args
parser_api = reqparse.RequestParser()
parser_api.add_argument('root', type=str)
parser_api.add_argument('postbase', type=str, action='append')

# FIXME obsolete
# Takes a list of dict/json objects and add id field
# def index(l):
#     new_l = []
#     for i in range(len(l)):
#         new_x = l[i]
#         new_x['id'] = i
#         new_l.append(new_x)