Ejemplo n.º 1
0
def create_oauth(app):
    spf = SanicPluginsFramework(app)
    try:
        oauth = spf.register_plugin(oauthclient)
    except ValueError as v:
        _, oauth = v
    return oauth
Ejemplo n.º 2
0
 def api(self, app):
     blueprint = Blueprint('api', __name__)
     spf = SanicPluginsFramework(blueprint)
     plugin, reg = spf.register_plugin(restplus)
     api = Api(reg)
     app.register_blueprint(blueprint)
     yield api
Ejemplo n.º 3
0
def sqlalchemy_provider(app):
    spf = SanicPluginsFramework(app)
    oauth = spf.register_plugin(oauth2provider)
    bind_sqlalchemy(oauth, db.session, user=User, token=Token,
                    client=Client, grant=Grant, current_user=current_user)

    return oauth
Ejemplo n.º 4
0
def add_oauth_plugin(app):
    spf = SanicPluginsFramework(app)
    try:
        oauth = spf.register_plugin(oauthclient)
    except ValueError as v:
        _, oauth = v.args
    return oauth
Ejemplo n.º 5
0
def test_middleware_response():
    app = Sanic('test_middleware_response')
    spf = SanicPluginsFramework(app)
    plugin = TestPlugin()
    results = []

    @plugin.middleware('request')
    async def process_response(request):
        results.append(request)

    @plugin.middleware('response')
    async def process_response(request, response):
        results.append(request)
        results.append(response)

    @plugin.route('/')
    async def handler(request):
        return text('OK')

    spf.register_plugin(plugin)
    request, response = app.test_client.get('/')

    assert response.text == 'OK'
    assert type(results[0]) is Request
    assert type(results[1]) is Request
    assert isinstance(results[2], HTTPResponse)
Ejemplo n.º 6
0
 def test_lazy_load(self):
     twitter = oauthclient.remote_app(
         'twitter',
         base_url='https://api.twitter.com/1/',
         app_key='twitter'
     )
     assert twitter.base_url == 'https://api.twitter.com/1/'
     app = Sanic(__name__)
     app.config.update({
         'twitter': dict(
             request_token_params={'realms': 'email'},
             consumer_key='twitter key',
             consumer_secret='twitter secret',
             request_token_url='request url',
             access_token_url='token url',
             authorize_url='auth url',
         )
     })
     spf = SanicPluginsFramework(app)
     spf.register_plugin(oauthclient)
     assert twitter.consumer_key == 'twitter key'
     assert twitter.consumer_secret == 'twitter secret'
     assert twitter.request_token_url == 'request url'
     assert twitter.access_token_url == 'token url'
     assert twitter.authorize_url == 'auth url'
     assert twitter.content_type is None
     assert 'realms' in twitter.request_token_params
def test_plugin_urlfor_1():
    app = Sanic('test_plugin_urlfor_1')
    spf = SanicPluginsFramework(app)
    spf.register_plugin(test_plugin)
    client = app.test_client
    resp = client.get('/t2')
    assert resp[1].text == 't1'
Ejemplo n.º 8
0
def test_raise_app():
    with raises(AttributeError):
        app = Sanic(__name__)
        spf = SanicPluginsFramework(app)
        oauth = spf.register_plugin(oauthclient)
        plugin = app.extensions['oauthlib.client']
        client = spf.get_plugin_assoc(plugin)
        assert client.demo.name == 'dev'
Ejemplo n.º 9
0
def cache_provider(app):
    spf = SanicPluginsFramework(app)
    oauth = spf.register_plugin(oauth2provider)
    bind_sqlalchemy(oauth, db.session, user=User,
                    token=Token, client=Client, current_user=current_user)

    app.config.update({'OAUTH2_CACHE_TYPE': 'simple'})
    bind_cache_grant(app, oauth, current_user)
    return oauth
def create_app():
    LOG_CONFIG = copy(LOGGING_CONFIG_DEFAULTS)
    LOG_CONFIG['loggers']['sanic.error'][
        'level'] = "WARNING"  # Default is INFO
    LOG_CONFIG['loggers']['sanic.access'][
        'level'] = "WARNING"  # Default is INFO
    app = Sanic(__name__, log_config=LOG_CONFIG, configure_logging=True)
    spf = SanicPluginsFramework(app)
    app.config['LOGO'] = r"""
     _     ___   ____ ___   ___ _   _ _____ _____ ____ ____     _  _____ ___  ____       _    ____ ___
    | |   / _ \ / ___|_ _| |_ _| \ | |_   _| ____/ ___|  _ \   / \|_   _/ _ \|  _ \     / \  |  _ |_ _|
    | |  | | | | |    | |   | ||  \| | | | |  _|| |  _| |_) | / _ \ | || | | | |_) |   / _ \ | |_) | |
    | |__| |_| | |___ | |   | || |\  | | | | |__| |_| |  _ < / ___ \| || |_| |  _ <   / ___ \|  __/| |
    |_____\___/ \____|___| |___|_| \_| |_| |_____\____|_| \_/_/   \_|_| \___/|_| \_\ /_/   \_|_|  |___|
    git commit: {}
    """.format(gitlabel)
    app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
    app.config.RESPONSE_TIMEOUT = 4800
    # Register/Activate Sanic-CORS plugin with allow all origins
    _ = spf.register_plugin(cors, origins=r".*", automatic_options=True)

    # Register/Activate Sanic-Restplus plugin
    restplus_associated = spf.register_plugin(restplus, _url_prefix="api")

    # Remove any previous apps from the api instance.
    # (this is needed during testing, the test runner does calls create_app many times)
    api_v1.spf_reg = None

    # Register our LOCI Api on the restplus plugin
    restplus_associated.api(api_v1)

    # Make the static directory available to be served via the /static/ route if needed
    # Note, it is preferred that something like apache or nginx does static file serving in production
    dir_loc = os.path.abspath(os.path.join(HERE_DIR, "static"))
    app.static(uri="/static/",
               file_or_directory=dir_loc,
               name="material_swagger")

    @app.route("/")
    def index(request):
        """
        Route function for the index route.
        Only exists to point a wayward user to the api swagger doc page.
        :param request:
        :type request: Request
        :return:
        :rtype: HTTPResponse
        """
        html = "<h1>LOCI Integration API</h1>\
        <a href=\"api/v1/doc\">Click here to go to the swaggerui doc page.</a>\
        <pre>Git commit: <a href=\"{prefix}{commit}\">{commit}</a></pre>".format(
            prefix=
            "https://github.com/CSIRO-enviro-informatics/loci-integration-api/commit/",
            commit=str(gitlabel))
        return HTTPResponse(html, status=200, content_type="text/html")

    return app
Ejemplo n.º 11
0
def default_provider(app):
    spf = SanicPluginsFramework(app)
    oauth = spf.register_plugin(oauth2provider)
    @oauth.clientgetter
    def get_client(client_id):
        return db.session.query(Client).filter_by(client_id=client_id).first()

    @oauth.grantgetter
    def get_grant(client_id, code):
        return db.session.query(Grant).filter_by(client_id=client_id, code=code).first()

    @oauth.tokengetter
    def get_token(access_token=None, refresh_token=None):
        if access_token:
            return db.session.query(Token).filter_by(access_token=access_token).first()
        if refresh_token:
            return db.session.query(Token).filter_by(refresh_token=refresh_token).first()
        return None

    @oauth.grantsetter
    def set_grant(client_id, code, request, *args, **kwargs):
        expires = datetime.utcnow() + timedelta(seconds=100)
        grant = Grant(
            client_id=client_id,
            code=code['code'],
            redirect_uri=request.redirect_uri,
            scope=' '.join(request.scopes),
            user_id=g.user.id,
            expires=expires,
        )
        db.session.add(grant)
        db.session.commit()

    @oauth.tokensetter
    def set_token(token, request, *args, **kwargs):
        # In real project, a token is unique bound to user and client.
        # Which means, you don't need to create a token every time.
        tok = Token(**token)
        if request.response_type == 'token':
            tok.user_id = g.user.id
        else:
            tok.user_id = request.user.id
        tok.client_id = request.client.client_id
        db.session.add(tok)
        db.session.commit()

    @oauth.usergetter
    def get_user(username, password, *args, **kwargs):
        # This is optional, if you don't need password credential
        # there is no need to implement this method
        user = db.session.query(User).filter_by(username=username).first()
        if user and user.check_password(password):
            return user
        return None

    return oauth
Ejemplo n.º 12
0
def test_plugin_log1():
    app = Sanic('test_plugin_log1')
    spf = SanicPluginsFramework(app)
    plugin = spf.register_plugin(test_plugin)
    client = app.test_client
    exceptions = None
    try:
        resp = client.get('/t1')
    except Exception as e:
        exceptions = e
    assert exceptions is None
Ejemplo n.º 13
0
def test_spf_singleton_2():
    """
    Registering the framework twice, but with different apps should return
    two different spfs
    :return:
    """
    app1 = Sanic('test_spf_singleton_2_1')
    spf1 = SanicPluginsFramework(app1)
    app2 = Sanic('test_spf_singleton_2_1')
    spf1.register_plugin(instance)
    spf2 = SanicPluginsFramework(app2)
    assert spf1 != spf2
Ejemplo n.º 14
0
 def wrapped_decorator(f):
     spf = SanicPluginsFramework(app)  # get the singleton from the app
     try:
         plugin = spf.register_plugin(cors, skip_reg=True)
     except ValueError as e:
         # this is normal, if this plugin has been registered previously
         assert e.args and len(e.args) > 1
         plugin = e.args[1]
     context = cors.get_context_from_spf(spf)
     log = context.log
     log(logging.DEBUG, "Enabled {:s} for cross_origin using options: {}".format(str(f), str(_options)))
     return _real_decorator(f)
Ejemplo n.º 15
0
def test_spf_singleton_1():
    """
    Registering the framework twice on the same app should return
    an indentical instance of the spf
    :return:
    """
    app = Sanic('test_spf_singleton_1')
    spf = SanicPluginsFramework(app)
    spf.register_plugin(instance)

    spf2 = SanicPluginsFramework(app)
    assert spf == spf2
Ejemplo n.º 16
0
    def create_client(self, app):
        spf = SanicPluginsFramework(app)
        oauth = spf.register_plugin(oauthclient)

        remote = oauth.remote_app(
            'dev',
            consumer_key='noclient',
            consumer_secret='dev',
            request_token_params={'realm': 'email'},
            base_url='http://localhost/api/',
            request_token_url='http://localhost/oauth/request_token',
            access_token_method='GET',
            access_token_url='http://localhost/oauth/access_token',
            authorize_url='http://localhost/oauth/authorize')
        return create_client(app, remote)
Ejemplo n.º 17
0
def create_app():
    app = Sanic(__name__)
    spf = SanicPluginsFramework(app)
    app.config['LOGO'] = r"""
     _     ___   ____ ___   ___ _   _ _____ _____ ____ ____     _  _____ ___  ____       _    ____ ___ 
    | |   / _ \ / ___|_ _| |_ _| \ | |_   _| ____/ ___|  _ \   / \|_   _/ _ \|  _ \     / \  |  _ |_ _|
    | |  | | | | |    | |   | ||  \| | | | |  _|| |  _| |_) | / _ \ | || | | | |_) |   / _ \ | |_) | | 
    | |__| |_| | |___ | |   | || |\  | | | | |__| |_| |  _ < / ___ \| || |_| |  _ <   / ___ \|  __/| | 
    |_____\___/ \____|___| |___|_| \_| |_| |_____\____|_| \_/_/   \_|_| \___/|_| \_\ /_/   \_|_|  |___|prod
    """
    app.config.SWAGGER_UI_DOC_EXPANSION = 'list'

    # Register/Activate Sanic-CORS plugin with allow all origins
    _ = spf.register_plugin(cors, origins=r".*", automatic_options=True)

    # Register/Activate Sanic-Restplus plugin
    restplus_associated = spf.register_plugin(restplus)

    # Remove any previous apps from the api instance.
    api_v1.spf_reg = None

    # Register our LOCI Api on the restplus plugin
    restplus_associated.api(api_v1)

    # Make the static directory available to be served via the /static/ route if needed
    # Note, it is preferred that something like apache or nginx does static file serving in production
    dir_loc = os.path.abspath(os.path.join(HERE_DIR, "static"))
    app.static(uri="/static/",
               file_or_directory=dir_loc,
               name="material_swagger")

    @app.route("/")
    def index(request):
        """
        Route function for the index route.
        Only exists to point a wayward user to the api swagger doc page.
        :param request:
        :type request: Request
        :return:
        :rtype: HTTPResponse
        """
        html = "<h1>LOCI Integration API</h1>\
        <a href=\"api/v1/doc\">Click here to go to the swaggerui doc page.</a>"

        return HTTPResponse(html, status=200, content_type="text/html")

    return app
Ejemplo n.º 18
0
def test_app(request):
    app = Sanic(request.node.name)
    spf = SanicPluginsFramework(app)
    oauth = spf.register_plugin(oauthclient)
    remote = oauth.remote_app(
        'dev',
        consumer_key='dev',
        consumer_secret='dev',
        request_token_params={'scope': 'email'},
        base_url='http://127.0.0.1:5000/api/',
        request_token_url=None,
        access_token_method='POST',
        access_token_url='http://127.0.0.1:5000/oauth/token',
        authorize_url='http://127.0.0.1:5000/oauth/authorize')
    plugin = app.extensions['oauthlib.client']
    client = spf.get_plugin_assoc(plugin)
    assert client.dev.name == 'dev'
Ejemplo n.º 19
0
def test_middleware_override_request():
    app = Sanic('test_middleware_override_request')
    spf = SanicPluginsFramework(app)
    plugin = TestPlugin()

    @plugin.middleware
    async def halt_request(request):
        return text('OK')

    @plugin.route('/')
    async def handler(request):
        return text('FAIL')

    spf.register_plugin(plugin)
    response = app.test_client.get('/', gather_request=False)

    assert response.status == 200
    assert response.text == 'OK'
Ejemplo n.º 20
0
    def test_lazy_load_with_plain_text_config(self):
        twitter = oauthclient.remote_app('twitter', app_key='TWITTER')

        app = Sanic(__name__)
        app.config['TWITTER_CONSUMER_KEY'] = 'twitter key'
        app.config['TWITTER_CONSUMER_SECRET'] = 'twitter secret'
        app.config['TWITTER_REQUEST_TOKEN_URL'] = 'request url'
        app.config['TWITTER_ACCESS_TOKEN_URL'] = 'token url'
        app.config['TWITTER_AUTHORIZE_URL'] = 'auth url'

        spf = SanicPluginsFramework(app)
        spf.register_plugin(oauthclient)

        assert twitter.consumer_key == 'twitter key'
        assert twitter.consumer_secret == 'twitter secret'
        assert twitter.request_token_url == 'request url'
        assert twitter.access_token_url == 'token url'
        assert twitter.authorize_url == 'auth url'
Ejemplo n.º 21
0
def test_plugin_url_attributes(path, query, expected_url):
    app = Sanic('test_plugin_url_attrs')
    spf = SanicPluginsFramework(app)
    test_plugin = TestPlugin()

    async def handler(request):
        return text('OK')

    test_plugin.route(path)(handler)

    spf.register_plugin(test_plugin)
    request, response = app.test_client.get(path + '?{}'.format(query))
    assert request.url == expected_url.format(HOST, PORT)

    parsed = urlparse(request.url)

    assert parsed.scheme == request.scheme
    assert parsed.path == request.path
    assert parsed.query == request.query_string
    assert parsed.netloc == request.host
def test_plugin_ws_url_attributes(path, query, expected_url):
    """Note, this doesn't _really_ test websocket functionality very well."""
    app = Sanic('test_plugin_ws_url_attrs')
    spf = SanicPluginsFramework(app)
    test_plugin = TestPlugin()

    async def handler(request):
        return text('OK')

    test_plugin.websocket(path)(handler)

    spf.register_plugin(test_plugin)
    request, response = app.test_client.get(path + '?{}'.format(query))
    assert request.url == expected_url.format(HOST, PORT)

    parsed = urlparse(request.url)

    assert parsed.scheme == request.scheme
    assert parsed.path == request.path
    assert parsed.query == request.query_string
    assert parsed.netloc == request.host
Ejemplo n.º 23
0
def test_middleware_order():
    app = Sanic('test_middleware_order')
    spf = SanicPluginsFramework(app)
    plugin = TestPlugin()
    order = []

    @plugin.middleware('request')
    async def request1(request):
        order.append(1)

    @plugin.middleware('request')
    async def request2(request):
        order.append(2)

    @plugin.middleware('request')
    async def request3(request):
        order.append(3)

    @plugin.middleware('response')
    async def response1(request, response):
        order.append(6)

    @plugin.middleware('response')
    async def response2(request, response):
        order.append(5)

    @plugin.middleware('response')
    async def response3(request, response):
        order.append(4)

    @plugin.route('/')
    async def handler(request):
        return text('OK')

    spf.register_plugin(plugin)
    request, response = app.test_client.get('/')

    assert response.status == 200
    assert order == [1, 2, 3, 4, 5, 6]
Ejemplo n.º 24
0
def test_middleware_response_exception():
    app = Sanic('test_middleware_response_exception')
    spf = SanicPluginsFramework(app)
    plugin = TestPlugin()

    result = {'status_code': None}

    @plugin.middleware('response')
    async def process_response(reqest, response):
        result['status_code'] = response.status
        return response

    @plugin.exception(NotFound)
    async def error_handler(request, exception):
        return text('OK', exception.status_code)

    @plugin.route('/')
    async def handler(request):
        return text('FAIL')

    spf.register_plugin(plugin)
    request, response = app.test_client.get('/page_not_found')
    assert response.text == 'OK'
    assert result['status_code'] == 404
Ejemplo n.º 25
0
    def api(self, reg, *args, api_class=None, **kwargs):
        from .api import Api
        if isinstance(reg, PluginAssociated):
            (pl, reg) = reg
            (spf, _, _) = reg
        elif isinstance(reg, PluginRegistration):
            (spf, _, _) = reg
        elif isinstance(reg, SanicPluginsFramework):
            spf = reg
            reg = self.find_plugin_registration(spf)
        elif isinstance(reg, Sanic):
            app = reg
            spf = SanicPluginsFramework(app)
            reg = self.find_plugin_registration(spf)
        else:
            raise RuntimeError(
                "the 'reg' argument must be a SPF, an Association, Registration, or an App!"
            )
        context = self.get_context_from_spf(reg)
        app = context.app
        assert isinstance(app, (Sanic, Blueprint))
        if api_class is None:
            if args and len(args) > 0 and isinstance(args[0], Api):
                args = list(args)
                api_class = args.pop(0)
            else:
                api_class = Api
        if isinstance(api_class, type):
            if app in args:
                # don't want app in here!
                args = list(args)
                args.remove(app)
            assert issubclass(api_class, Api)
            api = api_class(*args, **kwargs)
            kwargs = dict()
        else:
            api = api_class
        assert isinstance(api, Api)

        api.init_api(reg, **kwargs)
        context.apis.add(api)
        return api
from sanic import Sanic
from sanic.response import text
from sanic.exceptions import InvalidUsage, ServerError, NotFound
from sanic.handlers import ErrorHandler
from spf import SanicPlugin, SanicPluginsFramework


class TestPlugin(SanicPlugin):
    pass


# The following tests are taken directly from Sanic source @ v0.6.0
# and modified to test the SanicPlugin, rather than Sanic

exception_handler_app = Sanic('test_exception_handler')
spf = SanicPluginsFramework(exception_handler_app)
test_plugin = TestPlugin()


@test_plugin.route('/1')
def handler_1(request):
    raise InvalidUsage("OK")


@test_plugin.route('/2')
def handler_2(request):
    raise ServerError("OK")


@test_plugin.route('/3')
def handler_3(request):
Ejemplo n.º 27
0
def spf(request):
    a = app_with_name(request.node.name)
    return SanicPluginsFramework(a)
Ejemplo n.º 28
0
    def __init__(self,
                 spf_reg=None,
                 version='1.0',
                 title=None,
                 description=None,
                 terms_url=None,
                 license=None,
                 license_url=None,
                 contact=None,
                 contact_url=None,
                 contact_email=None,
                 authorizations=None,
                 security=None,
                 doc='/',
                 default_id=default_id,
                 default='default',
                 default_label='Default namespace',
                 validate=None,
                 tags=None,
                 prefix='',
                 ordered=False,
                 default_mediatype='application/json',
                 decorators=None,
                 catch_all_404s=False,
                 serve_challenge_on_401=False,
                 format_checker=None,
                 additional_css=None,
                 **kwargs):
        self.version = version
        self.title = title or 'API'
        self.description = description
        self.terms_url = terms_url
        self.contact = contact
        self.contact_email = contact_email
        self.contact_url = contact_url
        self.license = license
        self.license_url = license_url
        self.authorizations = authorizations
        self.security = security
        self.default_id = default_id
        self.ordered = ordered
        self._validate = validate
        self._doc = doc
        self._doc_view = None
        self._default_error_handler = None
        self.tags = tags or []

        self.error_handlers = {
            ParseError: mask_parse_error_handler,
            MaskError: mask_error_handler,
        }
        self._schema = None
        self.models = {}
        self._refresolver = None
        self.format_checker = format_checker
        self.namespaces = []
        self.default_namespace = self.namespace(
            default,
            default_label,
            endpoint='{0}-declaration'.format(default),
            validate=validate,
            api=self,
            path='/',
        )
        self.ns_paths = dict()
        if py_36 > cur_py_version:  #py3.5 or below
            self.representations = OrderedDict(DEFAULT_REPRESENTATIONS)
        else:
            self.representations = dict(DEFAULT_REPRESENTATIONS)
        self.urls = {}
        self.prefix = prefix
        self.default_mediatype = default_mediatype
        self.decorators = decorators if decorators else []
        self.catch_all_404s = catch_all_404s
        self.serve_challenge_on_401 = serve_challenge_on_401
        self.blueprint_setup = None
        self.endpoints = set()
        self.resources = []
        self.spf_reg = None
        self.blueprint = None
        self.additional_css = additional_css
        Api.uid_counter += 1
        self._uid = Api.uid_counter

        if spf_reg is not None:
            if isinstance(spf_reg, Sanic):
                # use legacy init method
                spf = SanicPluginsFramework(spf_reg)
                try:
                    spf_reg = restplus.find_plugin_registration(spf)
                except LookupError:
                    raise RuntimeError(
                        "Cannot create Api before sanic_restplus is registered on the SPF."
                    )
            self.init_api(reg=spf_reg, **kwargs)
Ejemplo n.º 29
0
 def create_app(self):
     client_app = Sanic(__name__)
     server_app = Sanic(__name__)
     spf1 = SanicPluginsFramework(client_app)
     spf2 = SanicPluginsFramework(server_app)
     return server_app, client_app
Ejemplo n.º 30
0
from sanic import Sanic
from sanic.response import text
from spf import SanicPluginsFramework
#from examples.my_plugin import my_plugin
from examples import my_plugin
from examples.my_plugin import MyPlugin
from logging import DEBUG

app = Sanic(__name__)
# mp = MyPlugin(app)  //Legacy registration example
spf = SanicPluginsFramework(app)
my_plugin = spf.register_plugin(my_plugin)


@app.route('/')
def index(request):
    return text("hello world")


if __name__ == "__main__":
    app.run("127.0.0.1", port=8098, debug=True)