Example #1
0
class Session(object):
    """
    セッション管理をするクラス
    cachelibの機能を使ってファイルによってセッションを管理する
    セッション自体は1つの辞書っぽいもので,一番上のキーが各セッションのIDになるえ
    Flask Sessionの実装を参考に作成した
    https://github.com/fengsp/flask-session/blob/a88f07e7260ae582b0744de42e77c4625e6884ea/flask_session/sessions.py

    TODO: セッション情報を削除する機能を追加
    """
    def __init__(self, config: Config):
        self.cache = FileSystemCache(config.session_cache_dir)
        self.session_lifetime = config.session_lifetime

    def get(self, session_id: str) -> Dict[str, Hashable]:
        """
        与えられたセッションIDのセッション情報を取得する
        :param session_id: セッションID
        :return:
        """
        if not session_id:
            return {}
        return self._load_session_from_file(session_id)

    def set(self, key: str, value: Hashable, session_id: str = None) -> str:
        """
        セッションを追加する
        :param session_id: セッションId
        :param key: 追加するセッション情報のキー
        :param value: 追加するセッション情報の値
        """
        if not session_id:
            # セッションを新規作成
            session_id = self._generate_session_id()
        session_obj = self._load_session_from_file(session_id) or {}
        session_obj.update({key: value})
        self._save_session(session_id, session_obj)
        return session_id

    def destroy(self, session_id):
        """
        セッションを削除する
        :param session_id: 削除するセッションのID
        :return: None
        """
        self.cache.delete(session_id)

    def _load_session_from_file(self, session_id) -> Dict[str, Hashable]:
        """
        与えられたセッションIDの情報を取得する
        :param session_id: セッションID
        :return dict: セッション情報
        """
        return self.cache.get(session_id)

    def _save_session(self, session_id: str, obj: Hashable) -> None:
        self.cache.set(session_id, obj, timeout=self.session_lifetime)

    def _generate_session_id(self) -> str:
        return uuid4().hex
Example #2
0
 def __init__(self,
              cache_dir,
              threshold,
              mode,
              key_prefix,
              use_signer=False,
              permanent=True):
     from cachelib.file import FileSystemCache
     self.cache = FileSystemCache(cache_dir, threshold=threshold, mode=mode)
     self.key_prefix = key_prefix
     self.use_signer = use_signer
     self.permanent = permanent
Example #3
0
 def __init__(self,
              cache_dir,
              threshold,
              mode,
              key_prefix,
              use_signer=False,
              permanent=True):
     from cachelib.file import FileSystemCache
     self.cache = FileSystemCache(cache_dir, threshold=threshold, mode=mode)
     self.key_prefix = key_prefix
     self.use_signer = use_signer
     self.permanent = permanent
     self.has_same_site_capability = hasattr(self, "get_cookie_samesite")
Example #4
0
def _get_cache():
    _cache = g.get('_oauth_cache')
    if _cache:
        return _cache
    _cache = FileSystemCache(current_app.config['OAUTH_CACHE_DIR'])
    g._oauth_cache = _cache
    return _cache
Example #5
0
class FileSystemSessionInterface(SessionInterface):
    """Uses the :class:`werkzeug.contrib.cache.FileSystemCache` as a session
    backend.

    .. versionadded:: 0.2
        The `use_signer` parameter was added.

    :param cache_dir: the directory where session files are stored.
    :param threshold: the maximum number of items the session stores before it
                      starts deleting some.
    :param mode: the file mode wanted for the session files, default 0600
    :param key_prefix: A prefix that is added to FileSystemCache store keys.
    :param use_signer: Whether to sign the session id cookie or not.
    :param permanent: Whether to use permanent session or not.
    """

    session_class = FileSystemSession

    def __init__(self,
                 cache_dir,
                 threshold,
                 mode,
                 key_prefix,
                 use_signer=False,
                 permanent=True):
        from cachelib.file import FileSystemCache
        self.cache = FileSystemCache(cache_dir, threshold=threshold, mode=mode)
        self.key_prefix = key_prefix
        self.use_signer = use_signer
        self.permanent = permanent

    def open_session(self, app, request):
        sid = request.cookies.get(app.session_cookie_name)
        if not sid:
            sid = self._generate_sid()
            return self.session_class(sid=sid, permanent=self.permanent)
        if self.use_signer:
            signer = self._get_signer(app)
            if signer is None:
                return None
            try:
                sid_as_bytes = signer.unsign(sid)
                sid = sid_as_bytes.decode()
            except BadSignature:
                sid = self._generate_sid()
                return self.session_class(sid=sid, permanent=self.permanent)

        data = self.cache.get(self.key_prefix + sid)
        if data is not None:
            return self.session_class(data, sid=sid)
        return self.session_class(sid=sid, permanent=self.permanent)

    def save_session(self, app, session, response):
        domain = self.get_cookie_domain(app)
        path = self.get_cookie_path(app)
        if not session:
            if session.modified:
                self.cache.delete(self.key_prefix + session.sid)
                response.delete_cookie(app.session_cookie_name,
                                       domain=domain,
                                       path=path)
            return

        httponly = self.get_cookie_httponly(app)
        secure = self.get_cookie_secure(app)
        expires = self.get_expiration_time(app, session)
        data = dict(session)
        self.cache.set(self.key_prefix + session.sid, data,
                       total_seconds(app.permanent_session_lifetime))
        if self.use_signer:
            session_id = self._get_signer(app).sign(want_bytes(session.sid))
        else:
            session_id = session.sid
        response.set_cookie(app.session_cookie_name,
                            session_id,
                            expires=expires,
                            httponly=httponly,
                            domain=domain,
                            path=path,
                            secure=secure,
                            samesite='None')
Example #6
0
# The SQLAlchemy connection string.
SQLALCHEMY_DATABASE_URI = "%s://%s:%s@%s:%s/%s" % (
    DATABASE_DIALECT,
    DATABASE_USER,
    DATABASE_PASSWORD,
    DATABASE_HOST,
    DATABASE_PORT,
    DATABASE_DB,
)

REDIS_HOST = get_env_variable("REDIS_HOST")
REDIS_PORT = get_env_variable("REDIS_PORT")
REDIS_CELERY_DB = get_env_variable("REDIS_CELERY_DB", 0)
REDIS_RESULTS_DB = get_env_variable("REDIS_CELERY_DB", 1)

RESULTS_BACKEND = FileSystemCache("/app/superset_home/sqllab")


class CeleryConfig(object):
    BROKER_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_CELERY_DB}"
    CELERY_RESULT_BACKEND = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_RESULTS_DB}"
    CELERY_TASK_PROTOCOL = 1
    CELERY_IMPORTS = (
        'superset.sql_lab',
        'superset.tasks',
    )
    CELERYD_LOG_LEVEL = 'DEBUG'
    CELERYD_PREFETCH_MULTIPLIER = 10
    CELERY_ACKS_LATE = True
    CELERY_ANNOTATIONS = {
        "tasks.add": {
Example #7
0
from functools import wraps
from cachelib.file import FileSystemCache
from mongoengine.base import BaseField
from mongoengine.errors import SaveConditionError
import logging
import itertools
import json

from scout.libs.redislib import RedisLib
from scout.libs.aspire import Aspire

db = MongoEngine()
assets = Environment()
limiter = Limiter(key_func=get_ipaddr)
redis = RedisLib()
cache = FileSystemCache('./.cache/')
logger = logging.getLogger('scout')
formatter = logging.Formatter(
    "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
aspire = Aspire()


def UTC():
    return datetime.now(timezone.utc)


def ignored_default(default_val, *exceptions):
    def dec(function):
        def _dec(*args, **kwargs):
            try:
                return function(*args, **kwargs)
Example #8
0
def set_cache(key, value, timeout=15, cache_dir=None):
    global cache
    if cache is None:
        cache = FileSystemCache(cache_dir or get_cache_dir())
    cache.set(str(key), value, timeout=timeout)
Example #9
0
def get_cache(key, cache_dir=None):
    global cache
    if cache is None:
        cache = FileSystemCache(cache_dir or get_cache_dir())
    return cache.get(str(key))
Example #10
0
 def __init__(self, config: Config):
     self.cache = FileSystemCache(config.session_cache_dir)
     self.session_lifetime = config.session_lifetime
Example #11
0
    Server: Werkzeug/0.9.4 Python/2.7.5+
    X-Cache: miss

    1000
"""
from __future__ import division, unicode_literals
from six.moves.http_client import BAD_REQUEST, OK
from time import sleep

from cachelib.file import FileSystemCache

from flask import Flask, render_template, request
from flask.ext.webcache import easy_setup, modifiers

app = Flask(__name__)
werkzeug_cache = FileSystemCache('/tmp/.sleepycalc')
easy_setup(app, werkzeug_cache)

PLAINTEXT = (('Content-Type', 'text/plain'), )


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


@app.route("/addition")
@modifiers.cache_for(seconds=30)
def addition():
    try:
        term1, term2 = int(request.args['term1']), int(request.args['term2'])