我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.deprecation.RemovedInDjango20Warning()。
def adapt_datetime_warn_on_aware_datetime(value, conv): # Remove this function and rely on the default adapter in Django 2.0. if settings.USE_TZ and timezone.is_aware(value): warnings.warn( "The MySQL database adapter received an aware datetime (%s), " "probably from cursor.execute(). Update your code to pass a " "naive datetime in the database connection's time zone (UTC by " "default).", RemovedInDjango20Warning) # This doesn't account for the database connection's timezone, # which isn't known. (That's why this adapter is deprecated.) value = value.astimezone(timezone.utc).replace(tzinfo=None) return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv) # MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like # timedelta in terms of actual behavior as they are signed and include days -- # and Django expects time, so we still need to override that. We also need to # add special handling for SafeText and SafeBytes as MySQLdb's type # checking is too tight to catch those (see Django ticket #6052).
def load_template(self, template_name, template_dirs=None): warnings.warn( 'The load_template() method is deprecated. Use get_template() ' 'instead.', RemovedInDjango20Warning, ) key = self.cache_key(template_name, template_dirs) template_tuple = self.template_cache.get(key) # A cached previous failure: if template_tuple is TemplateDoesNotExist: raise TemplateDoesNotExist(template_name) elif template_tuple is None: template, origin = self.find_template(template_name, template_dirs) if not hasattr(template, 'render'): try: template = Template(template, origin, template_name, self.engine) except TemplateDoesNotExist: # If compiling the template we found raises TemplateDoesNotExist, # back off to returning the source and display name for the template # we were asked to load. This allows for correct identification (later) # of the actual template that does not exist. self.template_cache[key] = (template, origin) self.template_cache[key] = (template, None) return self.template_cache[key]
def load_template_source(self, template_name, template_dirs=None): """ Loads templates from Python eggs via pkg_resource.resource_string. For every installed app, it tries to get the resource (app, template_name). """ warnings.warn( 'The load_template_sources() method is deprecated. Use ' 'get_template() or get_contents() instead.', RemovedInDjango20Warning, ) for origin in self.get_template_sources(template_name): try: return self.get_contents(origin), origin.name except TemplateDoesNotExist: pass raise TemplateDoesNotExist(template_name)
def load_template(self, template_name, template_dirs=None): warnings.warn( 'The load_template() method is deprecated. Use get_template() ' 'instead.', RemovedInDjango20Warning, ) source, display_name = self.load_template_source( template_name, template_dirs, ) origin = Origin( name=display_name, template_name=template_name, loader=self, ) try: template = Template(source, origin, template_name, self.engine) except TemplateDoesNotExist: # If compiling the template we found raises TemplateDoesNotExist, # back off to returning the source and display name for the # template we were asked to load. This allows for correct # identification of the actual template that does not exist. return source, display_name else: return template, None
def mark_for_escaping(s): """ Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once). """ warnings.warn('mark_for_escaping() is deprecated.', RemovedInDjango20Warning) if hasattr(s, '__html__') or isinstance(s, EscapeData): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return EscapeBytes(s) if isinstance(s, (six.text_type, Promise)): return EscapeText(s) return EscapeString(str(s))
def javascript_catalog(request, domain='djangojs', packages=None): """ Returns the selected language catalog as a javascript library. Receives the list of packages to check for translations in the packages parameter either from an infodict or as a +-delimited string from the request. Default is 'django.conf'. Additionally you can override the gettext domain for this view, but usually you don't want to do that, as JavaScript messages go to the djangojs domain. But this might be needed if you deliver your JavaScript source from Django templates. """ warnings.warn( "The javascript_catalog() view is deprecated in favor of the " "JavaScriptCatalog view.", RemovedInDjango20Warning, stacklevel=2 ) locale = _get_locale(request) packages = _parse_packages(packages) catalog, plural = get_javascript_catalog(locale, domain, packages) return render_javascript_catalog(catalog, plural)
def adapt_datetime_warn_on_aware_datetime(value, conv): # Remove this function and rely on the default adapter in Django 2.0. if settings.USE_TZ and timezone.is_aware(value): warnings.warn( "The MySQL database adapter received an aware datetime (%s), " "probably from cursor.execute(). Update your code to pass a " "naive datetime in the database connection's time zone (UTC by " "default).", RemovedInDjango20Warning) # This doesn't account for the database connection's timezone, # which isn't known. (That's why this adapter is deprecated.) value = value.astimezone(timezone.utc).replace(tzinfo=None) return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv) # MySQLdb returns TIME columns as timedelta -- they are more like timedelta in # terms of actual behavior as they are signed and include days -- and Django # expects time, so we still need to override that. We also need to add special # handling for SafeText and SafeBytes as MySQLdb's type checking is too tight # to catch those (see Django ticket #6052).
def get_template(self, template_name, dirs=_dirs_undefined): """ Returns a compiled Template object for the given template name, handling template inheritance recursively. """ if dirs is _dirs_undefined: dirs = None else: warnings.warn( "The dirs argument of get_template is deprecated.", RemovedInDjango20Warning, stacklevel=2) template, origin = self.find_template(template_name, dirs) if not hasattr(template, 'render'): # template needs to be compiled template = Template(template, origin, template_name, engine=self) return template # This method was originally a function defined in django.template.loader. # It was moved here in Django 1.8 when encapsulating the Django template # engine in this Engine class. It's still called by deprecated code but it # will be removed in Django 2.0. It's superseded by a new render_to_string # function in django.template.loader.
def select_template(self, template_name_list, dirs=_dirs_undefined): """ Given a list of template names, returns the first that can be loaded. """ if dirs is _dirs_undefined: # Do not set dirs to None here to avoid triggering the deprecation # warning in get_template. pass else: warnings.warn( "The dirs argument of select_template is deprecated.", RemovedInDjango20Warning, stacklevel=2) if not template_name_list: raise TemplateDoesNotExist("No template names provided") not_found = [] for template_name in template_name_list: try: return self.get_template(template_name, dirs) except TemplateDoesNotExist as exc: if exc.args[0] not in not_found: not_found.append(exc.args[0]) continue # If we get here, none of the templates could be loaded raise TemplateDoesNotExist(', '.join(not_found))
def __init__(self, dict_=None, autoescape=True, current_app=_current_app_undefined, use_l10n=None, use_tz=None): if current_app is not _current_app_undefined: warnings.warn( "The current_app argument of Context is deprecated. Use " "RequestContext and set the current_app attribute of its " "request instead.", RemovedInDjango20Warning, stacklevel=2) self.autoescape = autoescape self._current_app = current_app self.use_l10n = use_l10n self.use_tz = use_tz self.render_context = RenderContext() # Set to the original template -- as opposed to extended or included # templates -- during rendering, see bind_template. self.template = None super(Context, self).__init__(dict_)
def adapt_datetime_warn_on_aware_datetime(value): # Remove this function and rely on the default adapter in Django 2.0. if settings.USE_TZ and timezone.is_aware(value): warnings.warn( "The SQLite database adapter received an aware datetime (%s), " "probably from cursor.execute(). Update your code to pass a " "naive datetime in the database connection's time zone (UTC by " "default).", RemovedInDjango20Warning) # This doesn't account for the database connection's timezone, # which isn't known. (That's why this adapter is deprecated.) value = value.astimezone(timezone.utc).replace(tzinfo=None) return value.isoformat(str(" "))
def __init__(self, engine, loaders): self.template_cache = {} self.find_template_cache = {} # RemovedInDjango20Warning self.get_template_cache = {} self.loaders = engine.get_template_loaders(loaders) super(Loader, self).__init__(engine)
def get_template_sources(self, template_name, template_dirs=None): for loader in self.loaders: args = [template_name] # RemovedInDjango20Warning: Add template_dirs for compatibility # with old loaders if func_supports_parameter(loader.get_template_sources, 'template_dirs'): args.append(template_dirs) for origin in loader.get_template_sources(*args): yield origin
def find_template(self, name, dirs=None): """ RemovedInDjango20Warning: An internal method to lookup the template name in all the configured loaders. """ key = self.cache_key(name, dirs) try: result = self.find_template_cache[key] except KeyError: result = None for loader in self.loaders: try: template, display_name = loader(name, dirs) except TemplateDoesNotExist: pass else: origin = Origin( name=display_name, template_name=name, loader=loader, ) result = template, origin break self.find_template_cache[key] = result if result: return result else: self.template_cache[key] = TemplateDoesNotExist raise TemplateDoesNotExist(name)
def reset(self): "Empty the template cache." self.template_cache.clear() self.find_template_cache.clear() # RemovedInDjango20Warning self.get_template_cache.clear()
def __call__(self, template_name, template_dirs=None): # RemovedInDjango20Warning: Allow loaders to be called like functions. return self.load_template(template_name, template_dirs)
def load_template_source(self, template_name, template_dirs=None): """ RemovedInDjango20Warning: Returns a tuple containing the source and origin for the given template name. """ raise NotImplementedError( 'subclasses of Loader must provide a load_template_source() method' )
def supports_recursion(self): """ RemovedInDjango20Warning: This is an internal property used by the ExtendsNode during the deprecation of non-recursive loaders. """ return hasattr(self, 'get_contents')
def disconnect(self, receiver=None, sender=None, weak=None, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be remove from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid is specified. sender The registered sender to disconnect dispatch_uid the unique identifier of the receiver to disconnect """ if weak is not None: warnings.warn("Passing `weak` to disconnect has no effect.", RemovedInDjango20Warning, stacklevel=2) if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender_receivers_cache.clear() return disconnected
def disconnect(self, receiver=None, sender=None, weak=None, dispatch_uid=None, apps=None): if weak is not None: warnings.warn("Passing `weak` to disconnect has no effect.", RemovedInDjango20Warning, stacklevel=2) return self._lazy_method( super(ModelSignal, self).disconnect, apps, receiver, sender, dispatch_uid=dispatch_uid )
def supports_recursion(self): """ RemovedInDjango20Warning: This is an internal property used by the ExtendsNode during the deprecation of non-recursive loaders. """ return all(hasattr(loader, 'get_contents') for loader in self.loaders)
def get_template(self, template_name, template_dirs=None, skip=None): """ Calls self.get_template_sources() and returns a Template object for the first template matching template_name. If skip is provided, template origins in skip are ignored. This is used to avoid recursion during template extending. """ tried = [] args = [template_name] # RemovedInDjango20Warning: Add template_dirs for compatibility with # old loaders if func_supports_parameter(self.get_template_sources, 'template_dirs'): args.append(template_dirs) for origin in self.get_template_sources(*args): if skip is not None and origin in skip: tried.append((origin, 'Skipped')) continue try: contents = self.get_contents(origin) except TemplateDoesNotExist: tried.append((origin, 'Source does not exist')) continue else: return Template( contents, origin, origin.template_name, self.engine, ) raise TemplateDoesNotExist(template_name, tried=tried)
def escape_filter(value): """ Marks the value as a string that should be auto-escaped. """ with warnings.catch_warnings(): # Ignore mark_for_escaping deprecation -- this will use # conditional_escape() in Django 2.0. warnings.simplefilter('ignore', category=RemovedInDjango20Warning) return mark_for_escaping(value)
def json_catalog(request, domain='djangojs', packages=None): """ Return the selected language catalog as a JSON object. Receives the same parameters as javascript_catalog(), but returns a response with a JSON object of the following format: { "catalog": { # Translations catalog }, "formats": { # Language formats for date, time, etc. }, "plural": '...' # Expression for plural forms, or null. } """ warnings.warn( "The json_catalog() view is deprecated in favor of the " "JSONCatalog view.", RemovedInDjango20Warning, stacklevel=2 ) locale = _get_locale(request) packages = _parse_packages(packages) catalog, plural = get_javascript_catalog(locale, domain, packages) data = { 'catalog': catalog, 'formats': get_formats(), 'plural': plural, } return http.JsonResponse(data)
def __init__(self, param, cursor, strings_only=False): # With raw SQL queries, datetimes can reach this function # without being converted by DateTimeField.get_db_prep_value. if settings.USE_TZ and (isinstance(param, datetime.datetime) and not isinstance(param, Oracle_datetime)): if timezone.is_aware(param): warnings.warn( "The Oracle database adapter received an aware datetime (%s), " "probably from cursor.execute(). Update your code to pass a " "naive datetime in the database connection's time zone (UTC by " "default).", RemovedInDjango20Warning) param = param.astimezone(timezone.utc).replace(tzinfo=None) param = Oracle_datetime.from_datetime(param) string_size = 0 # Oracle doesn't recognize True and False correctly in Python 3. # The conversion done below works both in 2 and 3. if param is True: param = 1 elif param is False: param = 0 if hasattr(param, 'bind_parameter'): self.force_bytes = param.bind_parameter(cursor) elif isinstance(param, (Database.Binary, datetime.timedelta)): self.force_bytes = param else: # To transmit to the database, we need Unicode if supported # To get size right, we must consider bytes. self.force_bytes = force_text(param, cursor.charset, strings_only) if isinstance(self.force_bytes, six.string_types): # We could optimize by only converting up to 4000 bytes here string_size = len(force_bytes(param, cursor.charset, strings_only)) if hasattr(param, 'input_size'): # If parameter has `input_size` attribute, use that. self.input_size = param.input_size elif string_size > 4000: # Mark any string param greater than 4000 characters as a CLOB. self.input_size = Database.CLOB else: self.input_size = None