Exemple #1
0
import binascii
import datetime
import functools
import os
from typing import Any, Callable, Dict, List

from cachelib.simple import SimpleCache
from flask import make_response, request

from decksite import get_season_id
from magic import rotation
from shared_web import localization

CACHE = SimpleCache() # type: ignore

def cached() -> Callable:
    return cached_impl(cacheable=True, must_revalidate=True, client_only=False, client_timeout=1 * 60 * 60, server_timeout=5 * 60)

# pylint: disable=too-many-arguments
def cached_impl(cacheable: bool = False,
                must_revalidate: bool = True,
                client_only: bool = True,
                client_timeout: int = 0,
                server_timeout: int = 5 * 60,
                key: str = 'view{id}{locale}') -> Callable:
    """
    @see https://jakearchibald.com/2016/caching-best-practices/
         https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching
    """
    def decorator(f: Callable) -> Callable:
        @functools.wraps(f)
Exemple #2
0
import re
import uuid
from functools import wraps
from typing import Any, Callable

from cachelib.simple import SimpleCache
from flask import abort, current_app, redirect, request
from flask_app.authorization import Authorization
from flask_app.calendar_data import CalendarData
from flask_app.constants import SESSION_ID
from flask_app.gregorian_calendar import GregorianCalendar

cache = SimpleCache()

# see `app_utils` tests for details, but TL;DR is that urls must start with `http://` or `https://` to match
URLS_REGEX_PATTERN = r"(https?\:\/\/[\w/\-?=%.]+\.[\w/\+\-?=%.~&\[\]\#]+)"
DECORATED_URL_FORMAT = '<a href="{}" target="_blank">{}</a>'


def authenticated(decorated_function: Callable) -> Any:
    @wraps(decorated_function)
    def wrapper(*args: Any, **kwargs: Any) -> Any:
        session_id = request.cookies.get(SESSION_ID)
        if session_id is None or not is_session_valid(str(session_id)):
            if request.headers.get("Content-Type", "") == "application/json":
                abort(401)
            return redirect("/login")
        return decorated_function(*args, **kwargs)

    return wrapper
Exemple #3
0
from app import app
from flask import render_template, request, jsonify, make_response, redirect, url_for, session
import pickle
from uuid import uuid4
from logic.chess_board import Board
from logic.chess_pieces import *
from cachelib.simple import SimpleCache

c = SimpleCache()


@app.route('/', methods=["GET", "POST"])
@app.route('/chess', methods=["GET", "POST"])
def chess():
    b = load_board()

    flipped = b.flipped
    img_dict = b.board_html()

    save_board(b)

    return render_template('base.html', img_dict=img_dict, flipped=flipped)


@app.route('/flip')
def flip():
    b = load_board()

    b.flipped = not b.flipped

    save_board(b)
Exemple #4
0
from resources.dining import Dining, DiningInformation, DiningSearch, DiningToday
#from resources.weather import Weather
from resources.wifi import Wifi, WifiNearMe
from resources.laundry import Laundry
from resources.main import Main
from resources.free_food import FreeFood
from resources.ews_status import EWSStatus
from resources.athletic_schedule import AthleticSchedule
from resources.buildings import Buildings
from resources.directory import FacultyDirectory
from resources.daily_illini import News, SubCategoryNews, SportsNews, RecentNews
from resources.calendar import Calendar

app = Flask(__name__)
api = Api(app)
cache = SimpleCache(app)

# Define routes
api.add_resource(Main, '/')
'''Dining'''
api.add_resource(DiningToday, '/dining/<string:hall>')
api.add_resource(Dining,
                 '/dining/<string:hall>/<string:dateFrom>/<string:dateTo>')
api.add_resource(DiningSearch, '/dining/search/<string:query>')
api.add_resource(DiningInformation, '/dining/information')
'''Wifi'''
api.add_resource(Wifi, '/wifi')
#api.add_resource(WifiNearMe, '/wifi/<string:latitude>/<string:longitude>')

#api.add_resource(Weather, '/weather')
Exemple #5
0
 def __init__(self, app=None):
     """Initialize the cache."""
     super(ImageSimpleCache, self).__init__(app=app)
     self.cache = SimpleCache()
Exemple #6
0
class ImageSimpleCache(ImageCache):
    """Simple image cache."""
    def __init__(self, app=None):
        """Initialize the cache."""
        super(ImageSimpleCache, self).__init__(app=app)
        self.cache = SimpleCache()

    def get(self, key):
        """Return the key value.

        :param key: the object's key
        :return: the stored object
        :rtype: `BytesIO` object
        """
        return self.cache.get(key)

    def set(self, key, value, timeout=None):
        """Cache the object.

        :param key: the object's key
        :param value: the stored object
        :type value: `BytesIO` object
        :param timeout: the cache timeout in seconds
        """
        timeout = timeout or self.timeout
        self.cache.set(key, value, timeout)
        self.set_last_modification(key, timeout=timeout)

    def get_last_modification(self, key):
        """Get last modification of cached file.

        :param key: the file object's key
        """
        return self.get(self._last_modification_key_name(key))

    def set_last_modification(self, key, last_modification=None, timeout=None):
        """Set last modification of cached file.

        :param key: the file object's key
        :param last_modification: Last modification date of
            file represented by the key
        :type last_modification: datetime.datetime
        :param timeout: the cache timeout in seconds
        """
        if not last_modification:
            last_modification = datetime.utcnow().replace(microsecond=0)
        timeout = timeout or self.timeout
        self.cache.set(self._last_modification_key_name(key),
                       last_modification, timeout)

    def delete(self, key):
        """Delete the specific key."""
        self.cache.delete(key)
        self.cache.delete(self._last_modification_key_name(key))

    def flush(self):
        """Flush the cache."""
        self.cache.clear()