How to use the cachelib.SimpleCache function in cachelib

To help you get started, we’ve selected a few cachelib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github govau / notify / api / app / notifications / validators.py View on Github external
from app.dao import services_dao, templates_dao
from app.dao.service_sms_sender_dao import dao_get_service_sms_senders_by_id
from app.models import (
    INTERNATIONAL_SMS_TYPE, SMS_TYPE, EMAIL_TYPE, LETTER_TYPE,
    KEY_TYPE_TEST, KEY_TYPE_TEAM, SCHEDULE_NOTIFICATIONS
)
from app.service.utils import service_allowed_to_send_to
from app.v2.errors import TooManyRequestsError, BadRequestError, RateLimitError
from app import redis_store
from app.notifications.process_notifications import create_content_for_notification
from app.utils import get_public_notify_type_text
from app.dao.service_email_reply_to_dao import dao_get_reply_to_by_id
from app.dao.service_letter_contact_dao import dao_get_letter_contact_by_id


daily_message_limit_cache = SimpleCache(default_timeout=15)


def check_service_over_api_rate_limit(service, api_key):
    if current_app.config['API_RATE_LIMIT_ENABLED'] and current_app.config['REDIS_ENABLED']:
        cache_key = rate_limit_cache_key(service.id, api_key.key_type)
        rate_limit = service.rate_limit
        interval = 60
        if redis_store.exceeded_rate_limit(cache_key, rate_limit, interval):
            current_app.logger.error("service {} has been rate limited for throughput".format(service.id))
            raise RateLimitError(rate_limit, interval, api_key.key_type)


def check_service_over_daily_message_limit(key_type, service):
    if key_type == KEY_TYPE_TEST:
        return
github carrier-io / carrier-io / deprecated / installer / run.py View on Github external
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from json import dumps

from deprecated.installer.libs import ProvisionDocker

from deprecated.installer.libs import str2bool
from flask import Flask, render_template, request, Response
from cachelib import SimpleCache

app = Flask(__name__)
cache = SimpleCache()


@app.route("/", methods=["GET"])
def hello():
    return render_template("index.html")


@app.route("/install", methods=["POST"])
def install():
    data = dict(dns=request.form['dns'],
                workers=int(request.form['workers']),
                perfmeter=str2bool(request.form['perfmeter']),
                perfgun=str2bool(request.form['perfgun']),
                sast=str2bool(request.form['sast']),
                dast=str2bool(request.form['dast']),
                grafana_dashboards=not str2bool(request.form['grafana_dashboards']),
github greiginsydney / Intervalometerator / Raspberry Pi / www / intvlm8r.py View on Github external
import importlib.util # Testing installed packages
import io   #Camera preview
import logging
import os
import psutil
import re    #RegEx. Used in Copy Files
from smbus2 import SMBus # For I2C
import struct
import subprocess
import sys
import time

import gphoto2 as gp

from cachelib import SimpleCache
cache = SimpleCache()

from werkzeug.security import check_password_hash

from flask import Flask, flash, render_template, request, redirect, url_for, make_response, abort
from flask_login import LoginManager, current_user, login_user, logout_user, login_required, UserMixin, login_url
app = Flask(__name__)
app.secret_key = b'### Paste the secret key here. See the Setup docs ###' #Cookie for session messages
app.jinja_env.lstrip_blocks = True
app.jinja_env.trim_blocks = True

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = ''


# ////////////////////////////////
github govau / notify / api / app / clients / sms / sap.py View on Github external
import datetime
from cachelib import SimpleCache
from app.clients.sms import PollableSMSClient
from app.clients.sms.utils import timed
from saplivelink365 import Configuration, ApiClient, AuthorizationApi, SMSV20Api

# See https://livelink.sapmobileservices.com/documentation/guides/sms-channel/delivery_statuses/#body-description
sap_response_map = {
    'SENT': 'sending',
    'DELIVERED': 'delivered',
    'RECEIVED': 'delivered',
    'ERROR': 'failed',
}

auth_cache = SimpleCache()


def get_sap_responses(status):
    return sap_response_map[status]


class SAPSMSClient(PollableSMSClient):
    def __init__(self, client_id=None, client_secret=None, *args, **kwargs):
        super(SAPSMSClient, self).__init__(*args, **kwargs)
        self._client_id = client_id
        self._client_secret = client_secret

    def init_app(self, logger, notify_host, *args, **kwargs):
        self.logger = logger
        self.notify_host = notify_host
github govau / notify / api / app / notifications / notifications_ses_callback.py View on Github external
Notification = 'Notification'
    UnsubscribeConfirmation = 'UnsubscribeConfirmation'


class InvalidMessageTypeException(Exception):
    pass


def verify_message_type(message_type: str):
    try:
        SNSMessageType(message_type)
    except ValueError:
        raise InvalidMessageTypeException(f'{message_type} is not a valid message type.')


certificate_cache = SimpleCache()


def get_certificate(url):
    res = certificate_cache.get(url)
    if res is not None:
        return res
    res = requests.get(url).content
    certificate_cache.set(url, res, timeout=60 * 60)  # 60 minutes
    return res


# 400 counts as a permanent failure so SNS will not retry.
# 500 counts as a failed delivery attempt so SNS will retry.
# See https://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html#DeliveryPolicies
@ses_callback_blueprint.route('/notifications/email/ses', methods=['POST'])
def sns_callback_handler():

cachelib

A collection of cache libraries in the same API interface.

BSD-3-Clause
Latest version published 7 months ago

Package Health Score

89 / 100
Full package analysis