Esempio n. 1
0
def send_sms(text, to):
    assert len(text) <= 160, text
    if config.has_option('authentication_sms', 'function'):
        func = resolve(config.get('authentication_sms', 'function'))
        if func:
            from_ = config.get('authentication_sms', 'from', default=None)
            return func(text, to, from_)
    logger.error('Could not send SMS to %s: "%s"', to, text)
Esempio n. 2
0
    def _get_handling_class():
        if (ErrorHandler._ErrorHandlingClass is not None or
                not error_handler_configuration):
            return ErrorHandler._ErrorHandlingClass

        HandlingClass = resolve(
            config.get('admin', 'error_handling_class'))
        if not issubclass(HandlingClass, ErrorHandler):
            raise ValueError(
                'Invalid error handling class in configuration')
        ErrorHandler._ErrorHandlingClass = HandlingClass
        return HandlingClass
Esempio n. 3
0
                    cursor.execute(
                        *table.update([table.timestamp], [CurrentTimestamp()],
                                      where=table.name == name))
                else:
                    cursor.execute(*table.insert([table.timestamp, table.name],
                                                 [[CurrentTimestamp(), name]]))
            resets.clear()

    @classmethod
    def drop(cls, dbname):
        for inst in cls._cache_instance:
            inst._cache.pop(dbname, None)


if config.get('cache', 'class'):
    Cache = resolve(config.get('cache', 'class'))
else:
    Cache = MemoryCache


class LRUDict(OrderedDict):
    """
    Dictionary with a size limit.
    If size limit is reached, it will remove the first added items.
    """
    __slots__ = ('size_limit', )

    def __init__(self, size_limit, *args, **kwargs):
        assert size_limit > 0
        self.size_limit = size_limit
        super(LRUDict, self).__init__(*args, **kwargs)
Esempio n. 4
0
            return None, None
        return loader


app = TrytondWSGI()
if config.get('web', 'root'):
    static_files = {
        '/': config.get('web', 'root'),
        }
    app.wsgi_app = SharedDataMiddlewareIndex(
        app.wsgi_app, static_files,
        cache_timeout=config.getint('web', 'cache_timeout'))
num_proxies = config.getint('web', 'num_proxies')
if num_proxies:
    app.wsgi_app = NumProxyFix(app.wsgi_app, num_proxies)

if config.has_section('wsgi middleware'):
    for middleware in config.options('wsgi middleware'):
        Middleware = resolve(config.get('wsgi middleware', middleware))
        args, kwargs = (), {}
        section = 'wsgi %s' % middleware
        if config.has_section(section):
            if config.has_option(section, 'args'):
                args = eval(config.get(section, 'args'))
            if config.has_option(section, 'kwargs'):
                kwargs = eval(config.get(section, 'kwargs'))
        app.wsgi_app = Middleware(app.wsgi_app, *args, **kwargs)

import trytond.protocols.dispatcher  # noqa: E402,F401
import trytond.bus  # noqa: E402,F401
Esempio n. 5
0
            basename = os.path.basename(filename)
            if os.path.exists(filename):
                if data != self.get(basename, prefix):
                    collision += 1
                    filename = self._filename('%s-%s' % (id, collision),
                                              prefix)
                    continue
            else:
                with open(filename, 'wb') as fp:
                    fp.write(data)
            return basename

    def setmany(self, data, prefix=''):
        return [self.set(d, prefix) for d in data]

    def _filename(self, id, prefix):
        path = os.path.normpath(config.get('database', 'path'))
        filename = os.path.join(path, prefix, id[0:2], id[2:4], id)
        filename = os.path.normpath(filename)
        if not filename.startswith(path):
            raise ValueError('Bad prefix')
        return filename

    def _id(self, data):
        return hashlib.md5(data).hexdigest()


if config.get('database', 'class'):
    FileStore = resolve(config.get('database', 'class'))  # noqa: F811
filestore = FileStore()
Esempio n. 6
0
            logger.debug('Database backend do not support channels')
            return

        cursor = transaction.connection.cursor()
        message['message_id'] = str(uuid.uuid4())
        payload = json.dumps({
            'channel': channel,
            'message': message,
        },
                             cls=JSONEncoder,
                             separators=(',', ':'))
        cursor.execute('NOTIFY "%s", %%s' % cls._channel, (payload, ))


if config.get('bus', 'class'):
    Bus = resolve(config.get('bus', 'class'))
else:
    Bus = LongPollingBus


@app.route('/<string:database_name>/bus', methods=['POST'])
@app.auth_required
def subscribe(request, database_name):
    if not _allow_subscribe:
        raise NotImplemented
    if _url_host and _url_host != request.host_url:
        response = redirect(urljoin(_url_host, request.path),
                            HTTPStatus.PERMANENT_REDIRECT)
        # Allow to change the redirection after some time
        response.headers['Cache-Control'] = ('private, max-age=%s' %
                                             _web_cache_timeout)