django.utils.encoding.smart_str

Here are the examples of the python api django.utils.encoding.smart_str taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pinax-stripe
Source File: views.py
View license
    def form_valid(self, form):
        try:
            self.update_subscription(form.cleaned_data["plan"])
            return redirect("pinax_stripe_subscription_list")
        except stripe.StripeError as e:
            return self.render_to_response(self.get_context_data(form=form, errors=smart_str(e)))

Example 2

Project: django-bcrypt
Source File: models.py
View license
def check_password(raw_password, enc_password):
    if enc_password[0] == '$':
        algo = enc_password[1:].split('$', 1)[0]
        assert algo in ('2a', '2', 'bcrypt')

        return constant_time_compare(
            enc_password,
            bcrypt.hashpw(smart_str(raw_password), enc_password),
        )

    return django_check_password(raw_password, enc_password)

Example 3

Project: tddspry
Source File: test_cases.py
View license
    def test_datadiff_assert_equal(self):
        if not datadiff:
            self.assert_false(hasattr(self, 'datadiff_assert_equal'))
        else:
            self.datadiff_assert_equal(TEST_BAR, TEST_BAR)

            try:
                self.datadiff_assert_equal(TEST_BAR, TEST_FOO)
            except AssertionError, e:
                diff = datadiff.diff(TEST_BAR, TEST_FOO)
                self.assert_unicode(e, '\n' + smart_str(diff))

Example 4

Project: reviewboard
Source File: mimetypes.py
View license
    def _generate_preview_html(self, data_string):
        """Return html of the ReST file as produced by docutils."""
        # Use safe filtering against injection attacks
        docutils_settings = {
            'file_insertion_enabled': False,
            'raw_enabled': False,
            '_disable_config': True
        }

        parts = docutils.core.publish_parts(
            source=smart_str(data_string),
            writer_name='html4css1',
            settings_overrides=docutils_settings)

        return parts['html_body']

Example 5

Project: django-importer
Source File: xml_importer.py
View license
    def get_value(self, item, source_name):
        """
        This method receives an item from the source and a source name,
        and returns the text content for the `source_name` node.
        """
        return force_text(smart_str(item.findtext(source_name))).strip()

Example 6

Project: django-easy-maps
Source File: geocode.py
View license
def google_v3(address):
    """
    Given an address, return ``(computed_address, (latitude, longitude))``
    tuple using Google Geocoding API v3.

    """
    try:
        g = geocoders.GoogleV3()

        results = g.geocode(smart_str(address), exactly_one=False)
        if results is not None:
            return results[0]

        raise Error("No results found for '%s'" % address)
    except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
        raise Error(e)

Example 7

Project: django-el-pagination
Source File: views.py
View license
    def get_context_object_name(self, object_list):
        """Get the name of the item to be used in the context.

        See original in ``django.views.generic.list.MultipleObjectMixin``.
        """
        if self.context_object_name:
            return self.context_object_name
        elif hasattr(object_list, 'model'):
            object_name = object_list.model._meta.object_name.lower()
            return smart_str('{0}_list'.format(object_name))
        else:
            return None

Example 8

Project: aino-convert
Source File: helpers.py
View license
def execute(cmd, args):
    """
    Just a simple wrapper for executing commands. args is expected to be a
    sequence or a basestring, a basestring will be executed with shell=True.
    """
    if isinstance(args, basestring):
        args = smart_str(args)
        args = shlex.split(args)
    else:
        args = map(smart_str, args)
    cmd = smart_str(cmd)
    args.insert(0, cmd)
    p = Popen(args, stderr=PIPE, stdout=PIPE)
    retcode = p.wait()
    if retcode != 0:
        raise ExecuteException(p.stderr.read().decode(DEFAULT_LOCALE_ENCODING))
    return p.stdout.read().decode(DEFAULT_LOCALE_ENCODING)

Example 9

Project: django-primate
Source File: mixins.py
View license
    def set_password(self, raw_password):
        import bcrypt
        if raw_password is None:
            self.set_unusable_password()
        else:
            raw_password = smart_str(raw_password)
            salt = bcrypt.gensalt(self.rounds)
            self.password = 'bcrypt%s' % bcrypt.hashpw(raw_password, salt)

Example 10

Project: django-formwizard
Source File: base.py
View license
    def get_step_files(self, step):
        wizard_files = self.data[self.step_files_key].get(step, {})

        if wizard_files and not self.file_storage:
            raise NoFileStorageConfigured

        files = {}
        for field, field_dict in wizard_files.iteritems():
            field_dict = dict((smart_str(k), v)
                              for k, v in field_dict.iteritems())
            tmp_name = field_dict.pop('tmp_name')
            files[field] = UploadedFile(
                file=self.file_storage.open(tmp_name), **field_dict)
        return files or None

Example 11

Project: django-couchdb-utils
Source File: couch.py
View license
    def get(self, key, default=None):
        val = CacheRow.get_row(smart_str(key))
        if not val:
            return default
        if val.expires > datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'):
            if isinstance(val, basestring):
                return smart_unicode(val)
            else:
                return val

Example 12

Project: django-reversetag
Source File: reversetag.py
View license
    def resolve(self, context):
        self.resolved_view = self.view.resolve(context)
        self.resolved_args = [arg.resolve(context) 
                              for arg in self.args]
        self.resolved_kwargs = dict(
            [(smart_str(k,'ascii'), v.resolve(context))
             for k, v in self.kwargs.items()])

Example 13

Project: django-uuslug
Source File: uuslug.py
View license
def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0,
            word_boundary=False, separator='-', save_order=False, stopwords=()):
    """
    Make a slug from a given text.
    """

    return smart_str(pyslugify(text, entities, decimal, hexadecimal, max_length,
        word_boundary, separator, save_order, stopwords))

Example 14

Project: Roll-Your-Own
Source File: formatting.py
View license
def get_format(format_type, locale=None):
    """
    For a specific format type, returns the format for the current
    language (locale), defaults to the format in the settings.
    format_type is the name of the format, e.g. 'DATE_FORMAT'
    """

    format_type = smart_str(format_type)
    if settings.USE_L10N:
        for module in get_format_modules(locale=locale):
            try:
                return getattr(module, format_type)
            except AttributeError:
                pass
    return getattr(settings, format_type)

Example 15

Project: django-rocket-engine
Source File: views.py
View license
def file_serve(request, filename):

    blobinfo = blobstore.BlobInfo.all().filter('filename =', filename)
    blobstore_key = blobinfo[0].key()._BlobKey__blob_key

    blob_info = blobstore.BlobInfo.get(blobstore_key)

    filename = getattr(blob_info, 'filename', blobstore_key)
    content_type = getattr(blob_info, 'content_type', 'application/octet-stream')

    response = HttpResponse(content_type=content_type)
    response[BLOB_KEY_HEADER] = blobstore_key

    response['Content-Disposition'] = smart_str(
        u'attachment; filename=%s' % filename.split('/')[-1]
    )

    return response

Example 16

View license
def get_lookup_params(request, remove=[]):
    """ get lookup params from a http request query param1=value1&param2__lt=value2&... """
    lookup_params = dict(request.REQUEST.items()).copy() # a dictionary of the query string
    excluded_params = [ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR]
    excluded_params.extend(remove)
    for i in excluded_params:
        if i in lookup_params:
            del lookup_params[i]
    for key, value in lookup_params.items():
        if not isinstance(key, str):
            del lookup_params[key]
            lookup_params[smart_str(key)] = value
    return lookup_params

Example 17

Project: django-castor
Source File: storage.py
View license
    def path(self, hexdigest):
        shards = self.shard(hexdigest)

        try:
            path = safe_join(self.location, *shards)
        except ValueError:
            raise SuspiciousOperation("Attempted access to '%s' denied." %
                                      ('/'.join(shards),))

        return smart_str(os.path.normpath(path))

Example 18

Project: OIPA
Source File: fields.py
View license
    def to_representation(self, value):
        """
        Transform POINT object to json.
        """
        if value is None:
            return value

        if isinstance(value, GEOSGeometry):
            value = {
                "latitude": smart_str(value.y),
                "longitude": smart_str(value.x)
            }
        return value

Example 19

Project: django-cookie-consent
Source File: middleware.py
View license
    def process_response(self, request, response):
        if not is_cookie_consent_enabled(request):
            return response
        cookie_dic = get_cookie_dict_from_request(request)
        for cookie_group in all_cookie_groups().values():
            if not cookie_group.is_deletable:
                continue
            group_version = cookie_dic.get(cookie_group.varname, None)
            for cookie in cookie_group.cookie_set.all():
                if cookie.name not in request.COOKIES:
                    continue
                if group_version == settings.COOKIE_CONSENT_DECLINE:
                    response.delete_cookie(smart_str(cookie.name),
                                           cookie.path, cookie.domain)
                if group_version < cookie.get_version():
                    if not settings.COOKIE_CONSENT_OPT_OUT:
                        response.delete_cookie(smart_str(cookie.name),
                                               cookie.path, cookie.domain)
        return response

Example 20

Project: django-timezones
Source File: fields.py
View license
    def __init__(self, verbose_name=None, name=None, timezone=None, **kwargs):
        if isinstance(timezone, basestring):
            timezone = smart_str(timezone)
        if timezone in pytz.all_timezones_set:
            self.timezone = pytz.timezone(timezone)
        else:
            self.timezone = timezone
        super(LocalizedDateTimeField, self).__init__(verbose_name, name, **kwargs)

Example 21

Project: django-sellmo
Source File: query.py
View license
    def __repr__(self):
        params = []
        for key, values in self:
            for value in values:
                value = smart_str(value)
                params.append((key, value))
        return urlencode(params)

Example 22

Project: django-calendartools
Source File: list.py
View license
    def get_context_object_name(self, object_list):
        """
        Get the name of the item to be used in the context.
        """
        if self.context_object_name:
            return self.context_object_name
        elif hasattr(object_list, 'model'):
            return smart_str(object_list.model._meta.verbose_name_plural)
        else:
            return None

Example 23

Project: django-phased
Source File: utils.py
View license
def backup_csrf_token(context, storage=None):
    """
    Get the CSRF token and convert it to a string (since it's lazy)
    """
    if storage is None:
        storage = Context()
    storage['csrf_token'] = smart_str(context.get('csrf_token', 'NOTPROVIDED'))
    return storage

Example 24

Project: django-user-streams
Source File: __init__.py
View license
def add_header(content):
    """
    We need to add a unique header to each message, as duplicate items
    will otherwise be overwritten
    """
    return uuid4().hex + smart_str(content)

Example 25

Project: django-riv
Source File: xml_serializer.py
View license
    def serialize_reverse_fields(self, obj):
        super(Serializer, self).serialize_reverse_fields(obj)
        for fieldname in self.reverse_fields:
            related = getattr(obj, fieldname)
            if isinstance(self._current[fieldname], list):
                self._current[fieldname].insert(0, smart_str(related.model._meta.verbose_name))

Example 26

Project: blue-channel
Source File: svn_app_version.py
View license
def get_all_versions(fail_silently=bool(not settings.DEBUG)):
    # this cannot be done on load as there would be circular and parital imports
    try:
        allnames = ['', 'django'] + settings.INSTALLED_APPS
        res = [ (app, smart_str(svn_app_version(app, fail_silently)))
                    for app in allnames ]
    except:
        if fail_silently: return []
        raise
    return res

Example 27

Project: django-cms
Source File: admin.py
View license
def jsonify_request(response):
    """ Turn any response in a 200 response to let jQuery code handle it nicely.
        Response contains a json object with the following attributes:
         * status: original response status code
         * content: original response content
    """
    content = {'status': response.status_code, 'content': smart_str(response.content, response.charset)}
    return HttpResponse(json.dumps(content), content_type="application/json")

Example 28

Project: zinnia-theme-html5
Source File: middleware.py
View license
    def process_response(self, request, response):
        if (not response.status_code == 200 or
                not '<html' in response.content):
            return response

        self.update_content = False
        soup = BeautifulSoup(smart_str(response.content), "html5lib")

        self.remove_pubdate(soup)
        self.remove_a_rel(soup)
        self.change_link_archives(soup)
        self.change_a_rel_tag_category(soup)

        if self.update_content:
            response.content = str(soup)

        return response

Example 29

Project: django-cache-machine
Source File: ext.py
View license
    def _cache_support(self, name, obj, timeout, extra, caller):
        """Cache helper callback."""
        if settings.TEMPLATE_DEBUG:
            return caller()
        extra = ':'.join(map(encoding.smart_str, extra))
        key = 'fragment:%s:%s' % (name, extra)
        return caching.base.cached_with(obj, caller, key, timeout)

Example 30

Project: linguist
Source File: django-models-base.py
View license
    def __repr__(self):
        try:
            u = unicode(self)
        except (UnicodeEncodeError, UnicodeDecodeError):
            u = '[Bad Unicode data]'
        return smart_str('<%s: %s>' % (self.__class__.__name__, u))

Example 31

Project: ella
Source File: managers.py
View license
def get_listings_key(self, category=None, children=ListingHandler.NONE, count=10, offset=0, content_types=[], date_range=(), exclude=None, **kwargs):
    c = category and  category.id or ''

    return 'core.get_listing:%s:%d:%d:%d:%d:%s:%s:%s' % (
            c, count, offset, children, exclude.id if exclude else 0,
            ','.join(map(lambda ct: str(ct.pk), content_types)),
            ','.join(map(lambda d: d.strftime('%Y%m%d'), date_range)),
            ','.join(':'.join((k, smart_str(v))) for k, v in kwargs.items()),
    )

Example 32

Project: peer
Source File: utils.py
View license
def generate_validation_key(domain_name, domain_owner=None):
    """ Generates a unique validation key """
    m = hashlib.sha256()
    m.update(smart_str(domain_name))

    # add also current datetime and owner for more security
    m.update(datetime.datetime.now().isoformat())
    if domain_owner:
        m.update(domain_owner)

    return m.hexdigest()

Example 33

Project: aemanager
Source File: views.py
View license
@login_required
@commit_on_success
def logo_overview(request):
    file = request.user.get_profile().logo_file
    if not file:
        return HttpResponseNotFound()

    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment;filename="%s"'\
                                    % smart_str(file.name)
    response["X-Sendfile"] = settings.FILE_UPLOAD_DIR + file.name
    response['Content-length'] = file.size
    return response

Example 34

Project: muspy
Source File: tools.py
View license
def check_password(user, password):
    # Legacy users have their passwords hashed with SHA512.
    # TODO: Remove when Django supports SHA512 (1.4?)
    if user.password.startswith('sha512$'):
        import hashlib
        from django.utils.crypto import constant_time_compare
        from django.utils.encoding import smart_str
        algo, salt, hsh = user.password.split('$')
        password, salt = smart_str(password), smart_str(salt)
        hash = hashlib.new('sha512')
        hash.update(password)
        hash.update(salt)
        hexdigest = hash.hexdigest()
        return constant_time_compare(hsh, hexdigest)
    return user.check_password(password)

Example 35

View license
    def assertNotContains(self, response, text, status_code=200):  # overrides Django's assertion, because all diagnostics should be stated positively!!!
        """
        Asserts that a response indicates that a page was retrieved
        successfully, (i.e., the HTTP status code was as expected), and that
        ``text`` doesn't occurs in the content of the response.
        """
        self.assertEqual(response.status_code, status_code,
            "Retrieving page: Response code was %d (expected %d)'" %
                (response.status_code, status_code))
        text = smart_str(text, response._charset)
        self.assertEqual(response.content.count(text),
             0, "Response should not contain '%s'" % text)

Example 36

Project: django-lingua
Source File: collectmessages.py
View license
    def handle(self, *args, **options):
        db_values = []
        """ Taken from django.core.management.commands.syncdb"""
        for app in models.get_apps():
            model_list = models.get_models(app, include_auto_created=True)

            """Performance is not so important, we do it once... """
            for m in model_list:
                if hasattr(m, '_translation_fields'):
                    for x in m._translation_fields:
                        for y in m.objects.all():
                            db_values.append( getattr(y, x) )

        #print db_values
        f = file('db_translation.html', "w")
        """ blocktrans and we dont have to worry about to escape the string etc."""   
        for v in db_values:            
            f.write('{%% blocktrans %%}%s{%% endblocktrans %%}\n' % smart_str(v))
        f.close()

Example 37

Project: django-markwhat
Source File: markup.py
View license
@register.filter(is_safe=True)
def textile(value):
    """
    :type value: str

    :rtype: str
    """
    import textile

    return mark_safe(force_text(
        textile.textile(smart_str(value), encoding='utf-8', output='utf-8'))
    )

Example 38

Project: django-mobile
Source File: __init__.py
View license
    def save(self, request, response):
        if hasattr(request, '_flavour_cookie'):
            response.set_cookie(
                smart_str(settings.FLAVOURS_COOKIE_KEY),
                smart_str(request._flavour_cookie),
                httponly=settings.FLAVOURS_COOKIE_HTTPONLY)

Example 39

Project: dre
Source File: indexer.py
View license
    def resolve(self, value):
        bits = self.path.split(".")

        for bit in bits:
            if is_iterable(value):
                value = ', '.join(
                    map(lambda v: smart_str(self.resolve_one(v, bit)), value)
                )
            else:
                value = self.resolve_one(value, bit)

        if isinstance(value, self.raw_types):
            return value
        if is_iterable(value):
            return ', '.join(map(smart_str, value))

        return value and smart_str(value) or None

Example 40

Project: khufu
Source File: text.py
View license
@register.filter
def removetext(text):
    text=smart_str(text,"utf8")
    text=text.replace("-育儿早教-中国早教网","")
    text=text.replace("-怀孕胎教-中国早教网","")
    text=text.replace("-新闻资讯-中国早教网","")
    text=text.replace("-专家指导-中国早教网","")
    text=text.replace("中国早教网","")
    return text

Example 41

Project: django-js-reverse
Source File: unit_tests.py
View license
    def test_tpl_tag_with_request_in_context(self):
        context_instance = RequestContext(self.client.request)
        tpl = Template('{% load js_reverse %}{% js_reverse_inline %}')
        js_from_tag = tpl.render(context_instance)
        js_from_view = smart_str(self.client.post('/jsreverse/').content)
        self.assertEqual(js_from_tag, js_from_view)

Example 42

Project: django-better-cache
Source File: utils.py
View license
def set_header_dict(response, header, header_dict):
    """Formats and sets a header dict in a response, inververs of get_header_dict."""
    def dictvalue(t):
        if t[1] is True:
            return t[0]
        return t[0] + '=' + smart_str(t[1])

    response[header] = ', '.join([dictvalue(el) for el in header_dict.items()])

Example 43

Project: django-spurl
Source File: spurl.py
View license
    def handle_argument(self, argument, value):
        argument = smart_str(argument, 'ascii')
        handler_name = 'handle_%s' % argument
        handler = getattr(self, handler_name, None)

        if handler is not None:
            value = value.resolve(self.context)
            handler(value)

Example 44

View license
    def parse_options(self, bits):
        options = {}
        for bit in bits:
            parsed_bit = self.re_option.match(bit)
            key = smart_str(parsed_bit.group('key'))
            value = self.parser.compile_filter(parsed_bit.group('value'))
            options[key] = value
        return options

Example 45

Project: jeeves
Source File: logging_middleware.py
View license
    def process_response(self, request, response):
        logger.info("%s \"%s\" (%s)" % (request.method, smart_str(request.path_info), response.status_code))

        indentation = 2
        if len(connection.queries) > 0:
            total_time = 0.0
            for query in connection.queries:
                nice_sql = query['sql'].replace('"', '').replace(',',', ')
                sql = "[%s] %s" % (query['time'], nice_sql)
                total_time = total_time + float(query['time'])
                logger.info("%s%s\n" % (" "*indentation, sql))
            replace_tuple = (" "*indentation, str(total_time))
            logger.info("%s[TOTAL QUERIES: %d]" % (" "*indentation, len(connection.queries)))
            logger.info("%s[TOTAL TIME: %s seconds]" % replace_tuple)
        return response

Example 46

Project: django-vcstorage
Source File: storage.py
View license
    def delete(self, name, message=None):
        """
        Deletes the specified file from the storage system.
        """
        self.populate()
        if message is None:
            message = "Automated commit: removing %s" % name
        full_paths = [smart_str(self.path(name))]
        try:
            self.wd.remove(paths=full_paths)
            self.wd.commit(message=message, paths=full_paths)
        except OSError:
            pass

Example 47

Project: ANALYSE
Source File: memcache.py
View license
def cleaned_string(val):
    """
    Converts `val` to unicode and URL-encodes special characters
    (including quotes and spaces)
    """
    return urllib.quote_plus(smart_str(val))

Example 48

Project: commonware
Source File: middleware.py
View license
    def process_request(self, request):
        _local.remote_addr = request.META.get('REMOTE_ADDR', '')
        name = '<anon>'
        if hasattr(request, 'user') and request.user.is_authenticated():
            field = getattr(request.user, 'USERNAME_FIELD', 'username')
            name = encoding.smart_str(getattr(request.user, field, ''))
        _local.username = name

Example 49

Project: intranet
Source File: adminfilters_utils.py
View license
def get_lookup_params(request, remove=[]):
    """ get lookup params from a http request query param1=value1&param2__lt=value2&... """
    lookup_params = dict(request.REQUEST.items()).copy() # a dictionary of the query string
    excluded_params = [ALL_VAR, ORDER_VAR, ORDER_TYPE_VAR, SEARCH_VAR]
    excluded_params.extend(remove)
    for i in excluded_params:
        if i in lookup_params:
            del lookup_params[i]
    for key, value in lookup_params.items():
        if not isinstance(key, str):
            del lookup_params[key]
            lookup_params[smart_str(key)] = value
    return lookup_params

Example 50

Project: dj-stripe
Source File: views.py
View license
    def post(self, request, *args, **kwargs):
        body = smart_str(request.body)
        data = json.loads(body)
        if Event.stripe_objects.exists_by_json(data):
            EventProcessingException.objects.create(
                data=data,
                message="Duplicate event record",
                traceback=""
            )
        else:
            event = Event.create_from_stripe_object(data)
            event.validate()
            event.process()
        return HttpResponse()