<commit_before># coding: utf-8
"""
    flask_oauthlib.contrib.sqlalchemy
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    SQLAlchemy and Cache support for OAuth2 provider.

    contributed by: <NAME>
"""

from datetime import datetime, timedelta
from werkzeug.contrib.cache import (
    NullCache,
    SimpleCache,
    MemcachedCache,
    RedisCache,
    FileSystemCache
)
import logging


log = logging.getLogger('flask_oauthlib')


class Grant(object):

    def __init__(self, cache=None, client_id=None, code=None,
                 redirect_uri=None, scopes=None, user=None):
        self._cache = cache
        self.client_id = client_id
        self.code = code
        self.redirect_uri = redirect_uri
        self.scopes = scopes
        self.user = user

    def delete(self):
        log.debug("DELETE GRANT")
        log.debug("CODE: {0}".format(self.code))
        self._cache.delete(self.key)
        return None

    @property
    def key(self):
        key = '{code}{client_id}'.format(
            code=self.code,
            client_id=self.client_id
        )
        return key

    def __getitem__(self, item):
        return getattr(self, item)

    def keys(self):
        return ['client_id', 'code', 'redirect_uri', 'scopes', 'user']


class GrantCacheBinding(object):

    def __init__(self, app, provider, current_user, config=None):

        if config is None:
            config = app.config

        self.current_user = current_user

        config.setdefault('OAUTH2_CACHE_DEFAULT_TIMEOUT', 100)
        config.setdefault('OAUTH2_CACHE_THRESHOLD', 500)
        config.setdefault('OAUTH2_CACHE_KEY_PREFIX', None)
        config.setdefault('OAUTH2_CACHE_MEMCACHED_SERVERS', None)
        config.setdefault('OAUTH2_CACHE_REDIS_HOST', 'localhost')
        config.setdefault('OAUTH2_CACHE_REDIS_PORT', 6379)
        config.setdefault('OAUTH2_CACHE_REDIS_PASSWORD', None)
        config.setdefault('OAUTH2_CACHE_REDIS_DB', 0)
        config.setdefault('OAUTH2_CACHE_DIR', None)
        config.setdefault('OAUTH2_CACHE_MODE', '0600')
        config.setdefault('OAUTH2_CACHE_TYPE', 'null')

        self.config = config
        kwargs = dict(default_timeout=config['OAUTH2_CACHE_DEFAULT_TIMEOUT'])
        cache_type = '_{}'.format(config['OAUTH2_CACHE_TYPE'])

        try:
            self.cache = getattr(self, cache_type)(kwargs)
        except AttributeError:
            raise AttributeError(
                '`{}` is not a valid cache type!'.format(cache_type))

        provider.grantgetter(self.get)
        provider.grantsetter(self.set)

    def _null(self, kwargs):
        return NullCache()

    def _simple(self, kwargs):
        kwargs.update(dict(threshold=self.config['OAUTH2_CACHE_THRESHOLD']))
        return SimpleCache(**kwargs)

    def _memcache(self, kwargs):
        kwargs.update(dict(
            servers=self.config['OAUTH2_CACHE_MEMCACHED_SERVERS'],
            key_prefix=self.config['OAUTH2_CACHE_KEY_PREFIX']
        ))
        return MemcachedCache(**kwargs)

    def _redis(self, kwargs):
        kwargs.update(dict(
            host=self.config['OAUTH2_CACHE_REDIS_HOST'],
            port=self.config['OAUTH2_CACHE_REDIS_PORT'],
            password=self.config['OAUTH2_CACHE_REDIS_PASSWORD'],
            db=self.config['OAUTH2_CACHE_REDIS_DB'],
            key_prefix=self.config['OAUTH2_CACHE_KEY_PREFIX']
        ))
        return RedisCache(**kwargs)

    def _filesystem(self, kwargs):
        kwargs.update(dict(
            threshold=self.config['OAUTH2_CACHE_THRESHOLD']
        ))
        return FileSystemCache(self.config['OAUTH2_CACHE_DIR'], **kwargs)

    def set(self, client_id, code, request, *args, **kwargs):
        log.debug("SET GRANT")
        grant = Grant(
            self.cache,
            client_id=request.client.client_id,
            code=code['code'],
            redirect_uri=request.redirect_uri,
            scopes=request.scopes,
            user=self.current_user()
        )
        self.cache.set(grant.key, dict(grant))

    def get(self, client_id, code):
        log.debug("GET GRANT")
        grant = Grant(self.cache, client_id=client_id, code=code)
        kwargs = self.cache.get(grant.key)
        log.debug("KWARGS: {0}".format(kwargs))
        if kwargs:
            for k, v in kwargs.iteritems():
                setattr(grant, k, v)
            return grant
        log.debug("GET NOT FOUND")
        return None


class SQLAlchemyBinding(object):<commit_msg>Little fixes, starting working on docstrings<commit_after># coding: utf-8
"""
    flask_oauthlib.contrib.sqlalchemy
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    SQLAlchemy and Cache support for OAuth2 provider.

    contributed by: <NAME>
"""

from datetime import datetime, timedelta
from werkzeug.contrib.cache import (
    NullCache,
    SimpleCache,
    MemcachedCache,
    RedisCache,
    FileSystemCache
)
import logging


log = logging.getLogger('flask_oauthlib')


class Grant(object):
    """Grant object returned back to the provider

    :param cache: cache instance
    :param client_id:
    :param code:
    :param redirect_uri:
    :param scopes: a space delimited list of scopes
    :param user: user object returned from self.current_user
    """

    def __init__(self, cache=None, client_id=None, code=None,
                 redirect_uri=None, scopes=None, user=None):
        self._cache = cache
        self.client_id = client_id
        self.code = code
        self.redirect_uri = redirect_uri
        self.scopes = scopes
        self.user = user

    def delete(self):
        """Removes itself from the cache"""
        log.debug("Deleting grant")
        log.debug("Code: {0}".format(self.code))
        log.debug("Client id: {0}".format(self.client_id))
        self._cache.delete(self.key)
        return None

    @property
    def key(self):
        """String used as the key for the cache"""
        key = '{code}{client_id}'.format(
            code=self.code,
            client_id=self.client_id
        )
        return key

    def __getitem__(self, item):
        return getattr(self, item)

    def keys(self):
        return ['client_id', 'code', 'redirect_uri', 'scopes']


class GrantCacheBinding(object):
    """
    """

    def __init__(self, app, provider, current_user, config=None):

        if config is None:
            config = app.config

        self.current_user = current_user

        config.setdefault('OAUTH2_CACHE_DEFAULT_TIMEOUT', 100)
        config.setdefault('OAUTH2_CACHE_THRESHOLD', 500)
        config.setdefault('OAUTH2_CACHE_KEY_PREFIX', None)
        config.setdefault('OAUTH2_CACHE_MEMCACHED_SERVERS', None)
        config.setdefault('OAUTH2_CACHE_REDIS_HOST', 'localhost')
        config.setdefault('OAUTH2_CACHE_REDIS_PORT', 6379)
        config.setdefault('OAUTH2_CACHE_REDIS_PASSWORD', None)
        config.setdefault('OAUTH2_CACHE_REDIS_DB', 0)
        config.setdefault('OAUTH2_CACHE_DIR', None)
        config.setdefault('OAUTH2_CACHE_MODE', '0600')
        config.setdefault('OAUTH2_CACHE_TYPE', 'null')

        self.config = config
        kwargs = dict(default_timeout=config['OAUTH2_CACHE_DEFAULT_TIMEOUT'])
        cache_type = '_{0}'.format(config['OAUTH2_CACHE_TYPE'])

        try:
            self.cache = getattr(self, cache_type)(kwargs)
        except AttributeError:
            raise AttributeError(
                '`{0}` is not a valid cache type!'.format(cache_type))

        provider.grantgetter(self.get)
        provider.grantsetter(self.set)

    def _null(self, kwargs):
        return NullCache()

    def _simple(self, kwargs):
        kwargs.update(dict(threshold=self.config['OAUTH2_CACHE_THRESHOLD']))
        return SimpleCache(**kwargs)

    def _memcache(self, kwargs):
        kwargs.update(dict(
            servers=self.config['OAUTH2_CACHE_MEMCACHED_SERVERS'],
            key_prefix=self.config['OAUTH2_CACHE_KEY_PREFIX']
        ))
        return MemcachedCache(**kwargs)

    def _redis(self, kwargs):
        kwargs.update(dict(
            host=self.config['OAUTH2_CACHE_REDIS_HOST'],
            port=self.config['OAUTH2_CACHE_REDIS_PORT'],
            password=self.config['OAUTH2_CACHE_REDIS_PASSWORD'],
            db=self.config['OAUTH2_CACHE_REDIS_DB'],
            key_prefix=self.config['OAUTH2_CACHE_KEY_PREFIX']
        ))
        return RedisCache(**kwargs)

    def _filesystem(self, kwargs):
        kwargs.update(dict(
            threshold=self.config['OAUTH2_CACHE_THRESHOLD']
        ))
        return FileSystemCache(self.config['OAUTH2_CACHE_DIR'], **kwargs)

    def set(self, client_id, code, request, *args, **kwargs):
        log.debug("SET GRANT")
        grant = Grant(
            self.cache,
            client_id=request.client.client_id,
            code=code['code'],
            redirect_uri=request.redirect_uri,
            scopes=request.scopes,
            user=self.current_user()
        )
        self.cache.set(grant.key, dict(grant))

    def get(self, client_id, code):
        log.debug("GET GRANT")
        grant = Grant(self.cache, client_id=client_id,
                      code=code, user=self.current_user())
        kwargs = self.cache.get(grant.key)
        log.debug("KWARGS: {0}".format(kwargs))
        if kwargs:
            for k, v in kwargs.iteritems():
                setattr(grant, k, v)
            return grant
        log.debug("GET NOT FOUND")
        return None


class SQLAlchemyBinding(object):
{'fraction_non_alphanumeric': 0.11779661016949153, 'fraction_numerical': 0.009216101694915255, 'mean_word_length': 2.629757785467128, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4313170', 'n_tokens_mistral': 2961, 'n_tokens_neox': 2865, 'n_words': 523}