我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.six.string_types()。
def formfield(self, **kwargs): db = kwargs.pop('using', None) if isinstance(self.remote_field.model, six.string_types): raise ValueError("Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.remote_field.model)) defaults = { 'form_class': forms.ModelChoiceField, 'queryset': self.remote_field.model._default_manager.using(db), 'to_field_name': self.remote_field.field_name, } defaults.update(kwargs) return super(ForeignKey, self).formfield(**defaults)
def test_chart_view_get(self): ChartViewSubClass = type('ChartViewSubClass', (ChartView, ), { 'chart_instance': LineChart() }) chart_view = ChartViewSubClass() request_factory = RequestFactory() request = request_factory.get('/test-url') response = chart_view.get(request) self.assertEquals(response.status_code, 200) charset = getattr(response, 'charset', 'utf-8') content = response.content.decode(charset) data = json.loads(content) self.assertIn('data', data) self.assertIn('options', data) self.assertIn('type', data) self.assertTrue(isinstance(data['data'], dict)) self.assertTrue(isinstance(data['options'], dict)) self.assertTrue(isinstance(data['type'], (six.string_types, six.text_type))) self.assertIn(data['type'], ['bar', 'line', 'radar', 'polarArea', 'pie', 'bubble']) self.assertIn('title', data['options'])
def prepare_value(self, value): """Converts value to string for widget usage""" if not isinstance(value, six.string_types): value = value or () value = self.collection_type( self.item_type(item) for item in value ) if isinstance(value, set) or not self.unique_items: collection = value else: collection = [] # Remove the duplicates while keeping order: [ collection.append(item) for item in value if item not in collection ] if self.sort: collection = sorted(collection) value = self.format_separator().join( six.text_type(item) for item in collection ) return value
def get_model_label(model): """ Take a model class or model label and return its model label. >>> get_model_label(MyModel) "myapp.MyModel" >>> get_model_label("myapp.MyModel") "myapp.MyModel" """ if isinstance(model, six.string_types): return model else: return "%s.%s" % ( model._meta.app_label, model.__name__ )
def load_object(import_path): """ Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the likes. Import paths should be: "mypackage.mymodule.MyObject". It then imports the module up until the last dot and tries to get the attribute after that dot from the imported module. If the import path does not contain any dots, a TypeError is raised. If the module cannot be imported, an ImportError is raised. If the attribute does not exist in the module, a AttributeError is raised. """ if not isinstance(import_path, six.string_types): return import_path if '.' not in import_path: raise TypeError( "'import_path' argument to 'django_load.core.load_object' must " "contain at least one dot.") module_name, object_name = import_path.rsplit('.', 1) module = import_module(module_name) return getattr(module, object_name)
def make_models(self, model_def, app_name): if not isinstance(model_def, string_types): model = self.make_model(model_def, app_name) return [model] if model else [] match = self.MULTIPLE_MODELS_RE.match(model_def) if not match: model = self.make_model(model_def, app_name) return [model] if model else [] prefix = match.group(1) prefix = self.get_model_name(app_name,prefix) return [ m for m in [ self.convert_native_model(native_model,app_name) for native_model in self.all_models if self.get_native_model_name(native_model).startswith(prefix) ] if m ]
def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of JSON data. """ if not isinstance(stream_or_string, (bytes, six.string_types)): stream_or_string = stream_or_string.read() if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') try: objects = json.loads(stream_or_string) for obj in PythonDeserializer(objects, **options): yield obj except GeneratorExit: raise except Exception as e: # Map to deserializer error six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of YAML data. """ if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') if isinstance(stream_or_string, six.string_types): stream = StringIO(stream_or_string) else: stream = stream_or_string try: for obj in PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options): yield obj except GeneratorExit: raise except Exception as e: # Map to deserializer error six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
def regex(self): """ Returns a compiled regular expression, depending upon the activated language-code. """ language_code = get_language() if language_code not in self._regex_dict: if isinstance(self._regex, six.string_types): regex = self._regex else: regex = force_text(self._regex) try: compiled_regex = re.compile(regex, re.UNICODE) except re.error as e: raise ImproperlyConfigured( '"%s" is not a valid regular expression: %s' % (regex, six.text_type(e))) self._regex_dict[language_code] = compiled_regex return self._regex_dict[language_code]
def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ def check_perms(user): if isinstance(perm, six.string_types): perms = (perm, ) else: perms = perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url)
def _check_query(self, query, country=False, city=False, city_or_country=False): "Helper routine for checking the query and database availability." # Making sure a string was passed in for the query. if not isinstance(query, six.string_types): raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__) # Extra checks for the existence of country and city databases. if city_or_country and not (self._country or self._city): raise GeoIPException('Invalid GeoIP country and city data files.') elif country and not self._country: raise GeoIPException('Invalid GeoIP country data file: %s' % self._country_file) elif city and not self._city: raise GeoIPException('Invalid GeoIP city data file: %s' % self._city_file) # Return the query string back to the caller. GeoIP only takes bytestrings. return force_bytes(query)
def check_srs(self, source_srs): "Checks the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance(source_srs, (int, six.string_types)): sr = SpatialReference(source_srs) else: # Otherwise just pulling the SpatialReference from the layer sr = self.layer.srs if not sr: raise LayerMapError('No source reference system defined.') else: return sr
def __init__(self, type_input): "Figures out the correct OGR Type based upon the input." if isinstance(type_input, OGRGeomType): num = type_input.num elif isinstance(type_input, six.string_types): type_input = type_input.lower() if type_input == 'geometry': type_input = 'unknown' num = self._str_types.get(type_input) if num is None: raise GDALException('Invalid OGR String Type "%s"' % type_input) elif isinstance(type_input, int): if type_input not in self._types: raise GDALException('Invalid OGR Integer Type: %d' % type_input) num = type_input else: raise TypeError('Invalid OGR input type given.') # Setting the OGR geometry type number. self.num = num
def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.model_name) from_field = from_model._meta.get_field(self.name) to_field = to_model._meta.get_field(self.name) # If the field is a relatedfield with an unresolved rel.to, just # set it equal to the other field side. Bandaid fix for AlterField # migrations that are part of a RenameModel change. if from_field.remote_field and from_field.remote_field.model: if isinstance(from_field.remote_field.model, six.string_types): from_field.remote_field.model = to_field.remote_field.model elif to_field.remote_field and isinstance(to_field.remote_field.model, six.string_types): to_field.remote_field.model = from_field.remote_field.model if not self.preserve_default: to_field.default = self.field.default schema_editor.alter_field(from_model, from_field, to_field) if not self.preserve_default: to_field.default = NOT_PROVIDED
def references_model(self, name, app_label=None): strings_to_check = [self.name] # Check we didn't inherit from the model for base in self.bases: if isinstance(base, six.string_types): strings_to_check.append(base.split(".")[-1]) # Check we have no FKs/M2Ms with it for fname, field in self.fields: if field.remote_field: if isinstance(field.remote_field.model, six.string_types): strings_to_check.append(field.remote_field.model.split(".")[-1]) # Now go over all the strings and compare them for string in strings_to_check: if string.lower() == name.lower(): return True return False
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): if isinstance(sender, six.string_types): try: app_label, model_name = sender.split('.') except ValueError: raise ValueError( "Specified sender must either be a model or a " "model name of the 'app_label.ModelName' form." ) try: sender = apps.get_registered_model(app_label, model_name) except LookupError: ref = (app_label, model_name) refs = self.unresolved_references.setdefault(ref, []) refs.append((receiver, weak, dispatch_uid)) return super(ModelSignal, self).connect( receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid )
def _check_referencing_to_swapped_model(self): if (self.remote_field.model not in self.opts.apps.get_models() and not isinstance(self.remote_field.model, six.string_types) and self.remote_field.model._meta.swapped): model = "%s.%s" % ( self.remote_field.model._meta.app_label, self.remote_field.model._meta.object_name ) return [ checks.Error( ("Field defines a relation with the model '%s', " "which has been swapped out.") % model, hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable, obj=self, id='fields.E301', ) ] return []
def find_template_loader(self, loader): if isinstance(loader, (tuple, list)): args = list(loader[1:]) loader = loader[0] else: args = [] if isinstance(loader, six.string_types): loader_class = import_string(loader) if getattr(loader_class, '_accepts_engine_in_init', False): args.insert(0, self) else: warnings.warn( "%s inherits from django.template.loader.BaseLoader " "instead of django.template.loaders.base.Loader. " % loader, RemovedInDjango110Warning, stacklevel=2) return loader_class(*args) else: raise ImproperlyConfigured( "Invalid value in template loaders configuration: %r" % loader)
def assertJSONEqual(self, raw, expected_data, msg=None): """ Asserts that the JSON fragments raw and expected_data are equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except ValueError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, six.string_types): try: expected_data = json.loads(expected_data) except ValueError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertEqual(data, expected_data, msg=msg)
def assertJSONNotEqual(self, raw, expected_data, msg=None): """ Asserts that the JSON fragments raw and expected_data are not equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except ValueError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, six.string_types): try: expected_data = json.loads(expected_data) except ValueError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertNotEqual(data, expected_data, msg=msg)
def enable(self): self.options = {} for name, operations in self.operations: try: # When called from SimpleTestCase.setUpClass, values may be # overridden several times; cumulate changes. value = self.options[name] except KeyError: value = list(getattr(settings, name, [])) for action, items in operations.items(): # items my be a single value or an iterable. if isinstance(items, six.string_types): items = [items] if action == 'append': value = value + [item for item in items if item not in value] elif action == 'prepend': value = [item for item in items if item not in value] + value elif action == 'remove': value = [item for item in value if item not in items] else: raise ValueError("Unsupported action: %s" % action) self.options[name] = value super(modify_settings, self).enable()
def append(self, element): if isinstance(element, six.string_types): element = force_text(element) element = normalize_whitespace(element) if self.children: if isinstance(self.children[-1], six.string_types): self.children[-1] += element self.children[-1] = normalize_whitespace(self.children[-1]) return elif self.children: # removing last children if it is only whitespace # this can result in incorrect dom representations since # whitespace between inline tags like <span> is significant if isinstance(self.children[-1], six.string_types): if self.children[-1].isspace(): self.children.pop() if element: self.children.append(element)
def finalize(self): def rstrip_last_element(children): if children: if isinstance(children[-1], six.string_types): children[-1] = children[-1].rstrip() if not children[-1]: children.pop() children = rstrip_last_element(children) return children rstrip_last_element(self.children) for i, child in enumerate(self.children): if isinstance(child, six.string_types): self.children[i] = child.strip() elif hasattr(child, 'finalize'): child.finalize()
def _count(self, element, count=True): if not isinstance(element, six.string_types): if self == element: return 1 i = 0 for child in self.children: # child is text content and element is also text content, then # make a simple "text" in "text" if isinstance(child, six.string_types): if isinstance(element, six.string_types): if count: i += child.count(element) elif element in child: return 1 else: i += child._count(element, count=count) if not count and i: return i return i
def parse_html(html): """ Takes a string that contains *valid* HTML and turns it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.feed(html) parser.close() document = parser.root document.finalize() # Removing ROOT element if it's not necessary if len(document.children) == 1: if not isinstance(document.children[0], six.string_types): document = document.children[0] return document
def sanitize_separators(value): """ Sanitizes a value according to the current decimal and thousand separator setting. Used with form field input. """ if settings.USE_L10N and isinstance(value, six.string_types): parts = [] decimal_separator = get_format('DECIMAL_SEPARATOR') if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format('THOUSAND_SEPARATOR') if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3: # Special case where we suspect a dot meant decimal separator (see #22171) pass else: for replacement in { thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}: value = value.replace(replacement, '') parts.append(value) value = '.'.join(reversed(parts)) return value
def _archive_cls(file): cls = None if isinstance(file, six.string_types): filename = file else: try: filename = file.name except AttributeError: raise UnrecognizedArchiveFormat( "File object not a recognized archive format.") base, tail_ext = os.path.splitext(filename.lower()) cls = extension_map.get(tail_ext) if not cls: base, ext = os.path.splitext(base) cls = extension_map.get(ext) if not cls: raise UnrecognizedArchiveFormat( "Path not a recognized archive format: %s" % filename) return cls
def get_formats(): """ Returns all formats strings required for i18n to work """ FORMAT_SETTINGS = ( 'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT', 'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS' ) result = {} for module in [settings] + get_format_modules(reverse=True): for attr in FORMAT_SETTINGS: result[attr] = get_format(attr) formats = {} for k, v in result.items(): if isinstance(v, (six.string_types, int)): formats[k] = smart_text(v) elif isinstance(v, (tuple, list)): formats[k] = [smart_text(value) for value in v] return formats
def i18n_patterns(prefix, *args): """ Adds the language code prefix to every URL pattern within this function. This may only be used in the root URLconf, not in an included URLconf. """ if isinstance(prefix, six.string_types): warnings.warn( "Calling i18n_patterns() with the `prefix` argument and with tuples " "instead of django.conf.urls.url() instances is deprecated and " "will no longer work in Django 1.10. Use a list of " "django.conf.urls.url() instances instead.", RemovedInDjango110Warning, stacklevel=2 ) pattern_list = patterns(prefix, *args) else: pattern_list = [prefix] + list(args) if not settings.USE_I18N: return pattern_list return [LocaleRegexURLResolver(pattern_list)]
def url(regex, view, kwargs=None, name=None, prefix=''): if isinstance(view, (list, tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) else: if isinstance(view, six.string_types): warnings.warn( 'Support for string view arguments to url() is deprecated and ' 'will be removed in Django 1.10 (got %s). Pass the callable ' 'instead.' % view, RemovedInDjango110Warning, stacklevel=2 ) if not view: raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex) if prefix: view = prefix + '.' + view return RegexURLPattern(regex, view, kwargs, name)
def find_command(cmd, path=None, pathext=None): if path is None: path = os.environ.get('PATH', '').split(os.pathsep) if isinstance(path, six.string_types): path = [path] # check if there are funny path extensions for executables, e.g. Windows if pathext is None: pathext = os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep) # don't use extensions if the command ends with one of them for ext in pathext: if cmd.endswith(ext): pathext = [''] break # check if we find the command on PATH for p in path: f = os.path.join(p, cmd) if os.path.isfile(f): return f for ext in pathext: fext = f + ext if os.path.isfile(fext): return fext return None
def _set_srs(self, srs): "Sets the SpatialReference for this geometry." # Do not have to clone the `SpatialReference` object pointer because # when it is assigned to this `OGRGeometry` it's internal OGR # reference count is incremented, and will likewise be released # (decremented) when this geometry's destructor is called. if isinstance(srs, SpatialReference): srs_ptr = srs.ptr elif isinstance(srs, six.integer_types + six.string_types): sr = SpatialReference(srs) srs_ptr = sr.ptr elif srs is None: srs_ptr = None else: raise TypeError('Cannot assign spatial reference with object of type: %s' % type(srs)) capi.assign_srs(self.ptr, srs_ptr)
def fromfile(file_h): """ Given a string file name, returns a GEOSGeometry. The file may contain WKB, WKT, or HEX. """ # If given a file name, get a real handle. if isinstance(file_h, six.string_types): with open(file_h, 'rb') as file_h: buf = file_h.read() else: buf = file_h.read() # If we get WKB need to wrap in memoryview(), so run through regexes. if isinstance(buf, bytes): try: decoded = buf.decode() if wkt_regex.match(decoded) or hex_regex.match(decoded): return GEOSGeometry(decoded) except UnicodeDecodeError: pass else: return GEOSGeometry(buf) return GEOSGeometry(six.memoryview(buf))
def _check_query(self, query, country=False, city=False, city_or_country=False): "Helper routine for checking the query and database availability." # Making sure a string was passed in for the query. if not isinstance(query, six.string_types): raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__) # Extra checks for the existence of country and city databases. if city_or_country and not (self._country or self._city): raise GeoIP2Exception('Invalid GeoIP country and city data files.') elif country and not self._country: raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file) elif city and not self._city: raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file) # Return the query string back to the caller. GeoIP2 only takes IP addresses. if not (ipv4_re.match(query) or is_valid_ipv6_address(query)): query = socket.gethostbyname(query) return query
def get_available_languages_setting(): ''' list of available languages for modeltrans translations. defaults to the list of language codes extracted from django setting LANGUAGES ''' languages = tuple(set(getattr( settings, 'MODELTRANS_AVAILABLE_LANGUAGES', (code for code, _ in getattr(settings, 'LANGUAGES')) ))) if not all(isinstance(x, six.string_types) for x in languages): raise ImproperlyConfigured('MODELTRANS_AVAILABLE_LANGUAGES should be an iterable of strings') # make sure LANGUAGE_CODE is not in available languages return (lang for lang in languages if lang != get_default_language())
def is_descendant_of(self, other, include_self=False): if self.value is None: return False if isinstance(other, Path): other = other.value if other is None: return False if not isinstance(other, string_types): raise TypeError('`other` must be a `Path` instance or a string.') if not include_self and self.value == other: return False return self.value.startswith(other) # Tells psycopg2 how to prepare a Path object for the database, # in case it doesn't go through the ORM.
def format_value(self, value): """ Return a dict containing the year, month, and day of the current value. Use dict instead of a datetime to allow invalid dates such as February 31 to display correctly. """ year, month, day = None, None, None if isinstance(value, (datetime.date, datetime.datetime)): year, month, day = value.year, value.month, value.day elif isinstance(value, six.string_types): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] d = datetime.datetime.strptime(force_str(value), input_format) year, month, day = d.year, d.month, d.day except ValueError: pass match = self.date_re.match(value) if match: year, month, day = [int(val) for val in match.groups()] return {'year': year, 'month': month, 'day': day}
def get_warning_for_invalid_pattern(pattern): """ Return a list containing a warning that the pattern is invalid. describe_pattern() cannot be used here, because we cannot rely on the urlpattern having regex or name attributes. """ if isinstance(pattern, six.string_types): hint = ( "Try removing the string '{}'. The list of urlpatterns should not " "have a prefix string as the first element.".format(pattern) ) elif isinstance(pattern, tuple): hint = "Try using url() instead of a tuple." else: hint = None return [Error( "Your URL pattern {!r} is invalid. Ensure that urlpatterns is a list " "of url() instances.".format(pattern), hint=hint, id="urls.E004", )]
def test_runner_keeps_default_classes_in_inheritance_chain( settings, runner_cls_name, test_runner_cls, test_suite_cls): settings.TEST_RUNNER = runner_cls_name django_runner_cls = get_runner(settings) def assert_is_djpt_mixin(cls, base_cls, mixin_base_name): fullname = 'django_performance_testing.test_runner.{}'.format( mixin_base_name) mixin_cls_name = '{}Mixin'.format(mixin_base_name) mixin_cls = getattr(djpt_test_runner_module, mixin_cls_name) assert fullname == to_dotted_name(cls) assert issubclass(cls, mixin_cls) assert cls.__mro__[1] == mixin_cls if any(isinstance(base_cls, str_tp) for str_tp in six.string_types): assert base_cls == to_dotted_name(cls.__mro__[2]) elif isinstance(base_cls, type): assert issubclass(cls, base_cls) assert cls.__mro__[2] == base_cls else: raise NotImplementedError( 'Cannot handle type {}'.format(type(base_cls))) assert_is_djpt_mixin( cls=django_runner_cls, base_cls=runner_cls_name, mixin_base_name='DjptDjangoTestRunner') assert_is_djpt_mixin( cls=django_runner_cls.test_runner, base_cls=test_runner_cls, mixin_base_name='DjptTestRunner') assert django_runner_cls.test_suite == test_suite_cls
def from_db_value(self, value, expression, connection, context): """ Convert our YAML string to a Python object after we load it from the DB. """ if value == "": return None try: if isinstance(value, six.string_types): return yaml.load(value) except ValueError: pass return value
def __init__(self, filter_expression, group, asvar=None, default=None, message_context=None): self.noop = True self.asvar = asvar self.default = default self.group = group self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, six.string_types): self.filter_expression.var = Variable("'%s'" % self.filter_expression.var)