Пример #1
0
 def decript(self, password=None):
     if password:
         p = self.crypt_module.decrypt(to_bytes(password, self.encoding),
                                       self.secret_key)
         return to_string(p, self.encoding)
     else:
         return UNUSABLE_PASSWORD
Пример #2
0
def parse_info(response):
    info = {}
    response = to_string(response)

    def get_value(value):
        if "," not in value or "=" not in value:
            try:
                if "." in value:
                    return float(value)
                else:
                    return int(value)
            except ValueError:
                return value
        else:
            sub_dict = {}
            for item in value.split(","):
                k, v = item.rsplit("=", 1)
                sub_dict[k] = get_value(v)
            return sub_dict

    for line in response.splitlines():
        if line and not line.startswith("#"):
            key, value = line.split(":", 1)
            info[key] = get_value(value)
    return info
Пример #3
0
 def login_response(self, request, user):
     session = self.create_session(request, user)
     request.cache.session = session
     token = to_string(session.encoded)
     request.response.status_code = 201
     return Json({'success': True,
                  'token': token}).http_response(request)
Пример #4
0
 def _form_message(self, container, key, msg):
     if msg:
         msg = to_string(msg)
         if key in container:
             container[key].append(msg)
         else:
             container[key] = [msg]
Пример #5
0
def parse_info(response):
    info = {}
    response = to_string(response)

    def get_value(value):
        if ',' not in value or '=' not in value:
            try:
                if '.' in value:
                    return float(value)
                else:
                    return int(value)
            except ValueError:
                return value
        else:
            sub_dict = {}
            for item in value.split(','):
                k, v = item.rsplit('=', 1)
                sub_dict[k] = get_value(v)
            return sub_dict

    for line in response.splitlines():
        if line and not line.startswith('#'):
            key, value = line.split(':', 1)
            info[key] = get_value(value)
    return info
Пример #6
0
 def values(self, bfield):
     '''Generator of values in select'''
     for o in self.all(bfield):
         if isinstance(o, Widget):
             v = o.attr('value')
         else:
             v = to_string(o[0])
         yield v
Пример #7
0
 def _to_string(self, value):
     if isinstance(value, Mapping):
         raise BuildError('A dictionary found when coverting to string')
     elif isinstance(value, (list, tuple)):
         return ', '.join(self._to_string(v) for v in value)
     elif isinstance(value, date):
         return iso8601(value)
     else:
         return to_string(value)
Пример #8
0
    def to_string(self, stream):
        '''Once the :class:`.Future`, returned by :meth:`content`
        method, is ready, this method get called to transform the stream into
        the content string. This method can be overwritten by derived classes.

        :param stream: a collections containing ``strings/bytes`` used to
            build the final ``string/bytes``.
        :return: a string or bytes
        '''
        return to_string(''.join(stream_to_string(stream)))
Пример #9
0
 def _render_meta(self, value, context):
     if isinstance(value, Mapping):
         return dict(((k, self._render_meta(v, context))
                      for k, v in value.items()))
     elif isinstance(value, (list, tuple)):
         return [self._render_meta(v, context) for v in value]
     elif isinstance(value, date):
         return value
     elif value is not None:
         return self._engine(to_string(value), context)
Пример #10
0
    def to_string(self, streams):
        '''Called to transform the collection of
        ``streams`` into the content string.
        This method can be overwritten by derived classes.

        :param streams: a collection (list or dictionary) containing
            ``strings/bytes`` used to build the final ``string/bytes``.
        :return: a string or bytes
        '''
        return to_string(''.join(stream_to_string(streams)))
Пример #11
0
 def login(self, request, user):
     """Handle a request for a token to be used on a web browser
     """
     seconds = request.config['MAX_TOKEN_SESSION_EXPIRY']
     expiry = datetime.now() + timedelta(seconds=seconds)
     token = self.create_token(request, user, expiry=expiry)
     token = to_string(token.encoded)
     request.response.status_code = 201
     return {'success': True,
             'token': token}
Пример #12
0
 def _clean(self, value, instance):
     try:
         value = to_string(value)
     except Exception as exc:
         raise ValidationError from exc
     minlength = self.attrs.get('minlength')
     if minlength and len(value) < minlength:
         raise ValidationError('too short')
     maxlength = self.attrs.get('maxlength')
     if maxlength and len(value) > maxlength:
         raise ValidationError('too long')
     return value
Пример #13
0
 def _clean_simple(self, value, bfield):
     '''Invoked by :meth:`clean` if :attr:`model` is not defined.'''
     choices = self.choices
     if hasattr(choices, '__call__'):
         choices = choices(bfield)
     if not isinstance(choices, Mapping):
         choices = dict(choices)
     values = value if self.multiple else (value,)
     for v in values:
         v = to_string(v)
         if v not in choices:
             raise ValidationError('%s is not a valid choice' % v)
     return value
Пример #14
0
 def broadcast(self, channel, message):
     '''Broadcast ``message`` to all :attr:`clients`.'''
     remove = set()
     channel = to_string(channel)
     message = self.decode(message)
     clients = tuple(self.clients)
     for client in clients:
         try:
             client(channel, message)
         except Exception:
             LOGGER.exception('Exception while processing pub/sub client. '
                              'Removing it.')
             remove.add(client)
     self.clients.difference_update(remove)
Пример #15
0
 def dataReceived(self, data):
     sep = self.separator
     idx = data.find(sep)
     if idx >= 0:
         if self.buffer:
             msg = self.buffer + msg
             self.buffer = b''
         id, msg, data = data[:8], data[8:idx], data[idx+len(sep):]
         d = self.requests.pop(id)
         d.callback(to_string(msg))
         if data:
             self.dataReceived(data)
     else:
         self.buffer += data
Пример #16
0
 def _clean(self, value, bfield):
     try:
         value = to_string(value)
     except Exception:
         raise ValidationError
     if self.toslug:
         value = slugify(value, self.toslug)
     if self.char_transform:
         if self.char_transform == 'u':
             value = value.upper()
         else:
             value = value.lower()
     if self.required and not value:
         raise ValidationError(
             self.validation_error.format(bfield.name, value))
     return value
Пример #17
0
 def broadcast(self, response):
     '''Broadcast ``message`` to all :attr:`clients`.'''
     remove = set()
     channel = to_string(response[0])
     message = response[1]
     if self._protocol:
         message = self._protocol.decode(message)
     for client in self._clients:
         try:
             client(channel, message)
         except IOError:
             remove.add(client)
         except Exception:
             self._loop.logger.exception(
                 'Exception while processing pub/sub client. Removing it.')
             remove.add(client)
     self._clients.difference_update(remove)
Пример #18
0
 def execute(self, request):
     '''Execute a new ``request``.
     '''
     handle = None
     if request:
         request[0] = command = to_string(request[0]).lower()
         info = COMMANDS_INFO.get(command)
         if info:
             handle = getattr(self.store, info.method_name)
         #
         if self.channels or self.patterns:
             if command not in self.store.SUBSCRIBE_COMMANDS:
                 return self.reply_error(self.store.PUBSUB_ONLY)
         if self.blocked:
             return self.reply_error('Blocked client cannot request')
         if self.transaction is not None and command not in 'exec':
             self.transaction.append((handle, request))
             return self._transport.write(self.store.QUEUED)
     self._execute_command(handle, request)
Пример #19
0
 def _test_done(self, monitor, task_id=None, exc=None):
     runner = self.runner
     if task_id:
         self._tests_done.add(to_string(task_id))
     if self._tests_queued is not None:
         left = self._tests_queued.difference(self._tests_done)
         if not left:
             tests = yield self.backend.get_tasks(self._tests_done)
             self.logger.info('All tests have finished.')
             time_taken = default_timer() - self._time_start
             for task in tests:
                 runner.add(task.get('result'))
             runner.on_end()
             runner.printSummary(time_taken)
             # Shut down the arbiter
             if runner.result.errors or runner.result.failures:
                 exit_code = 2
             else:
                 exit_code = 0
             monitor._loop.call_soon(self._exit, exit_code)
Пример #20
0
 def get_model(self, manager, pk):
     key = '%s%s:%s' % (self.namespace, manager._meta.table_name,
                        to_string(pk))
     return self.execute('hgetall', key,
                         factory=partial(self.build_model, manager))
Пример #21
0
def _gen_query(query_string, encoding):
    # keep_blank_values=True
    for key, value in parse_qsl((query_string or ''), True):
        yield (to_string(key, encoding, errors='replace'),
               to_string(value, encoding, errors='replace'))
Пример #22
0
 def _clean(self, value, instance):
     try:
         return to_string(value)
     except Exception:
         raise ValidationError
Пример #23
0
 def get_model(self, manager, pk):
     key = '%s%s:%s' % (self.namespace, manager._meta.table_name,
                        to_string(pk))
     return self.execute('hgetall', key,
                         factory=partial(self.build_model, manager))
Пример #24
0
def str_lower_case(x):
    return to_string(x).lower()
Пример #25
0
 def encript(self, password):
     p = self.crypt_module.encrypt(to_bytes(password, self.encoding),
                                   self.secret_key, self.salt_size)
     return to_string(p, self.encoding)
Пример #26
0
 def __lt__(self, other):
     if isinstance(other, self.__class__):
         return to_string(self) < to_string(other)
     else:
         raise TypeError('Cannot compare {0} with {1}'.format(self, other))
Пример #27
0
 def decode(self, message):
     '''Convert message to a string.'''
     return to_string(message)
Пример #28
0
 def basekey(self, meta, *args):
     key = '%s%s' % (self.namespace, meta.table_name)
     postfix = ':'.join((to_string(p) for p in args if p is not None))
     return '%s:%s' % (key, postfix) if postfix else key
Пример #29
0
 def decode(self, message):
     return to_string(message)
Пример #30
0
 def home_page(self, request):
     data = open(os.path.join(CHAT_DIR, 'chat.html')).read()
     request.response.content_type = 'text/html'
     request.response.content = to_string(data % request.environ)
     return request.response
Пример #31
0
from pulsar.utils.pep import to_string, iteritems


__all__ = ['Query', 'CompiledQuery', 'OdmError',
           'ModelNotFound', 'QueryError']


def int_or_float(v):
    v = float(v)
    i = int(v)
    return i if v == i else v


JSPLITTER = '__'
pass_through = lambda x: x
str_lower_case = lambda x: to_string(x).lower()
range_lookups = {
    'gt': int_or_float,
    'ge': int_or_float,
    'lt': int_or_float,
    'le': int_or_float,
    'contains': pass_through,
    'startswith': pass_through,
    'endswith': pass_through,
    'icontains': str_lower_case,
    'istartswith': str_lower_case,
    'iendswith': str_lower_case}

lookup_value = namedtuple('lookup_value', 'type value')