code
stringlengths
1
1.72M
language
stringclasses
1 value
from cx_Oracle import CLOB from django.contrib.gis.db.backends.adapter import WKTAdapter class OracleSpatialAdapter(WKTAdapter): input_size = CLOB
Python
""" The GeometryColumns and SpatialRefSys models for the Oracle spatial backend. It should be noted that Oracle Spatial does not have database tables named according to the OGC standard, so the closest analogs are used. For example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns model and the `SDO_COORD_REF_SYS` is used for the SpatialRefSys model. """ from django.contrib.gis.db import models from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.backends.base import SpatialRefSysMixin class GeometryColumns(models.Model): "Maps to the Oracle USER_SDO_GEOM_METADATA table." table_name = models.CharField(max_length=32) column_name = models.CharField(max_length=1024) srid = models.IntegerField(primary_key=True) # TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY). class Meta: db_table = 'USER_SDO_GEOM_METADATA' managed = False @classmethod def table_name_col(cls): """ Returns the name of the metadata column used to store the the feature table name. """ return 'table_name' @classmethod def geom_col_name(cls): """ Returns the name of the metadata column used to store the the feature geometry column. """ return 'column_name' def __unicode__(self): return '%s - %s (SRID: %s)' % (self.table_name, self.column_name, self.srid) class SpatialRefSys(models.Model, SpatialRefSysMixin): "Maps to the Oracle MDSYS.CS_SRS table." cs_name = models.CharField(max_length=68) srid = models.IntegerField(primary_key=True) auth_srid = models.IntegerField() auth_name = models.CharField(max_length=256) wktext = models.CharField(max_length=2046) # Optional geometry representing the bounds of this coordinate # system. By default, all are NULL in the table. cs_bounds = models.PolygonField(null=True) objects = models.GeoManager() class Meta: db_table = 'CS_SRS' managed = False @property def wkt(self): return self.wktext @classmethod def wkt_col(cls): return 'wktext'
Python
""" This module contains the spatial lookup types, and the `get_geo_where_clause` routine for Oracle Spatial. Please note that WKT support is broken on the XE version, and thus this backend will not work on such platforms. Specifically, XE lacks support for an internal JVM, and Java libraries are required to use the WKT constructors. """ import re from decimal import Decimal from django.db.backends.oracle.base import DatabaseOperations from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter from django.contrib.gis.db.backends.util import SpatialFunction from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance class SDOOperation(SpatialFunction): "Base class for SDO* Oracle operations." sql_template = "%(function)s(%(geo_col)s, %(geometry)s) %(operator)s '%(result)s'" def __init__(self, func, **kwargs): kwargs.setdefault('operator', '=') kwargs.setdefault('result', 'TRUE') super(SDOOperation, self).__init__(func, **kwargs) class SDODistance(SpatialFunction): "Class for Distance queries." sql_template = ('%(function)s(%(geo_col)s, %(geometry)s, %(tolerance)s) ' '%(operator)s %(result)s') dist_func = 'SDO_GEOM.SDO_DISTANCE' def __init__(self, op, tolerance=0.05): super(SDODistance, self).__init__(self.dist_func, tolerance=tolerance, operator=op, result='%s') class SDODWithin(SpatialFunction): dwithin_func = 'SDO_WITHIN_DISTANCE' sql_template = "%(function)s(%(geo_col)s, %(geometry)s, %%s) = 'TRUE'" def __init__(self): super(SDODWithin, self).__init__(self.dwithin_func) class SDOGeomRelate(SpatialFunction): "Class for using SDO_GEOM.RELATE." relate_func = 'SDO_GEOM.RELATE' sql_template = ("%(function)s(%(geo_col)s, '%(mask)s', %(geometry)s, " "%(tolerance)s) %(operator)s '%(mask)s'") def __init__(self, mask, tolerance=0.05): # SDO_GEOM.RELATE(...) has a peculiar argument order: column, mask, geom, tolerance. # Moreover, the runction result is the mask (e.g., 'DISJOINT' instead of 'TRUE'). super(SDOGeomRelate, self).__init__(self.relate_func, operator='=', mask=mask, tolerance=tolerance) class SDORelate(SpatialFunction): "Class for using SDO_RELATE." masks = 'TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|CONTAINS|COVERS|ANYINTERACT|ON' mask_regex = re.compile(r'^(%s)(\+(%s))*$' % (masks, masks), re.I) sql_template = "%(function)s(%(geo_col)s, %(geometry)s, 'mask=%(mask)s') = 'TRUE'" relate_func = 'SDO_RELATE' def __init__(self, mask): if not self.mask_regex.match(mask): raise ValueError('Invalid %s mask: "%s"' % (self.relate_func, mask)) super(SDORelate, self).__init__(self.relate_func, mask=mask) # Valid distance types and substitutions dtypes = (Decimal, Distance, float, int, long) class OracleOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = "django.contrib.gis.db.backends.oracle.compiler" name = 'oracle' oracle = True valid_aggregates = dict([(a, None) for a in ('Union', 'Extent')]) Adapter = OracleSpatialAdapter Adaptor = Adapter # Backwards-compatibility alias. area = 'SDO_GEOM.SDO_AREA' gml= 'SDO_UTIL.TO_GMLGEOMETRY' centroid = 'SDO_GEOM.SDO_CENTROID' difference = 'SDO_GEOM.SDO_DIFFERENCE' distance = 'SDO_GEOM.SDO_DISTANCE' extent= 'SDO_AGGR_MBR' intersection= 'SDO_GEOM.SDO_INTERSECTION' length = 'SDO_GEOM.SDO_LENGTH' num_geom = 'SDO_UTIL.GETNUMELEM' num_points = 'SDO_UTIL.GETNUMVERTICES' perimeter = length point_on_surface = 'SDO_GEOM.SDO_POINTONSURFACE' reverse = 'SDO_UTIL.REVERSE_LINESTRING' sym_difference = 'SDO_GEOM.SDO_XOR' transform = 'SDO_CS.TRANSFORM' union = 'SDO_GEOM.SDO_UNION' unionagg = 'SDO_AGGR_UNION' # We want to get SDO Geometries as WKT because it is much easier to # instantiate GEOS proxies from WKT than SDO_GEOMETRY(...) strings. # However, this adversely affects performance (i.e., Java is called # to convert to WKT on every query). If someone wishes to write a # SDO_GEOMETRY(...) parser in Python, let me know =) select = 'SDO_UTIL.TO_WKTGEOMETRY(%s)' distance_functions = { 'distance_gt' : (SDODistance('>'), dtypes), 'distance_gte' : (SDODistance('>='), dtypes), 'distance_lt' : (SDODistance('<'), dtypes), 'distance_lte' : (SDODistance('<='), dtypes), 'dwithin' : (SDODWithin(), dtypes), } geometry_functions = { 'contains' : SDOOperation('SDO_CONTAINS'), 'coveredby' : SDOOperation('SDO_COVEREDBY'), 'covers' : SDOOperation('SDO_COVERS'), 'disjoint' : SDOGeomRelate('DISJOINT'), 'intersects' : SDOOperation('SDO_OVERLAPBDYINTERSECT'), # TODO: Is this really the same as ST_Intersects()? 'equals' : SDOOperation('SDO_EQUAL'), 'exact' : SDOOperation('SDO_EQUAL'), 'overlaps' : SDOOperation('SDO_OVERLAPS'), 'same_as' : SDOOperation('SDO_EQUAL'), 'relate' : (SDORelate, basestring), # Oracle uses a different syntax, e.g., 'mask=inside+touch' 'touches' : SDOOperation('SDO_TOUCH'), 'within' : SDOOperation('SDO_INSIDE'), } geometry_functions.update(distance_functions) gis_terms = ['isnull'] gis_terms += geometry_functions.keys() gis_terms = dict([(term, None) for term in gis_terms]) truncate_params = {'relate' : None} def __init__(self, connection): super(OracleOperations, self).__init__() self.connection = connection def convert_extent(self, clob): if clob: # Generally, Oracle returns a polygon for the extent -- however, # it can return a single point if there's only one Point in the # table. ext_geom = Geometry(clob.read()) gtype = str(ext_geom.geom_type) if gtype == 'Polygon': # Construct the 4-tuple from the coordinates in the polygon. shell = ext_geom.shell ll, ur = shell[0][:2], shell[2][:2] elif gtype == 'Point': ll = ext_geom.coords[:2] ur = ll else: raise Exception('Unexpected geometry type returned for extent: %s' % gtype) xmin, ymin = ll xmax, ymax = ur return (xmin, ymin, xmax, ymax) else: return None def convert_geom(self, clob, geo_field): if clob: return Geometry(clob.read(), geo_field.srid) else: return None def geo_db_type(self, f): """ Returns the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it's the same for all geometry types. """ return 'MDSYS.SDO_GEOMETRY' def get_distance(self, f, value, lookup_type): """ Returns the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value # dwithin lookups on oracle require a special string parameter # that starts with "distance=". if lookup_type == 'dwithin': dist_param = 'distance=%s' % dist_param return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the SDO_CS.TRANSFORM() function call. """ if value is None: return 'NULL' def transform_value(val, srid): return val.srid != srid if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = '%s(%%s, %s)' % (self.transform, f.srid) else: placeholder = '%s' # No geometry value used for F expression, substitue in # the column name instead. return placeholder % '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression])) else: if transform_value(value, f.srid): return '%s(SDO_GEOMETRY(%%s, %s), %s)' % (self.transform, value.srid, f.srid) else: return 'SDO_GEOMETRY(%%s, %s)' % f.srid def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): "Returns the SQL WHERE clause for use in Oracle spatial SQL construction." alias, col, db_type = lvalue # Getting the quoted table name as `geo_col`. geo_col = '%s.%s' % (qn(alias), qn(col)) # See if a Oracle Geometry function matches the lookup type next lookup_info = self.geometry_functions.get(lookup_type, False) if lookup_info: # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # 'dwithin' lookup types. if isinstance(lookup_info, tuple): # First element of tuple is lookup type, second element is the type # of the expected argument (e.g., str, float) sdo_op, arg_type = lookup_info geom = value[0] # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, tuple): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) if len(value) != 2: raise ValueError('2-element tuple required for %s lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) if lookup_type == 'relate': # The SDORelate class handles construction for these queries, # and verifies the mask argument. return sdo_op(value[1]).as_sql(geo_col, self.get_geom_placeholder(field, geom)) else: # Otherwise, just call the `as_sql` method on the SDOOperation instance. return sdo_op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) else: # Lookup info is a SDOOperation instance, whose `as_sql` method returns # the SQL necessary for the geometry function call. For example: # SDO_CONTAINS("geoapp_country"."poly", SDO_GEOMTRY('POINT(5 23)', 4326)) = 'TRUE' return lookup_info.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or '')) raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__.lower() if agg_name == 'union' : agg_name += 'agg' if agg.is_extent: sql_template = '%(function)s(%(field)s)' else: sql_template = '%(function)s(SDOAGGRTYPE(%(field)s,%(tolerance)s))' sql_function = getattr(self, agg_name) return self.select % sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.oracle.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.oracle.models import SpatialRefSys return SpatialRefSys
Python
from django.db.backends.oracle.creation import DatabaseCreation from django.db.backends.util import truncate_name class OracleCreation(DatabaseCreation): def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(OracleCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table output.append(style.SQL_KEYWORD('INSERT INTO ') + style.SQL_TABLE('USER_SDO_GEOM_METADATA') + ' (%s, %s, %s, %s)\n ' % tuple(map(qn, ['TABLE_NAME', 'COLUMN_NAME', 'DIMINFO', 'SRID'])) + style.SQL_KEYWORD(' VALUES ') + '(\n ' + style.SQL_TABLE(gqn(db_table)) + ',\n ' + style.SQL_FIELD(gqn(f.column)) + ',\n ' + style.SQL_KEYWORD("MDSYS.SDO_DIM_ARRAY") + '(\n ' + style.SQL_KEYWORD("MDSYS.SDO_DIM_ELEMENT") + ("('LONG', %s, %s, %s),\n " % (f._extent[0], f._extent[2], f._tolerance)) + style.SQL_KEYWORD("MDSYS.SDO_DIM_ELEMENT") + ("('LAT', %s, %s, %s)\n ),\n" % (f._extent[1], f._extent[3], f._tolerance)) + ' %s\n );' % f.srid) if f.spatial_index: # Getting the index name, Oracle doesn't allow object # names > 30 characters. idx_name = truncate_name('%s_%s_id' % (db_table, f.column), 30) output.append(style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn(idx_name)) + style.SQL_KEYWORD(' ON ') + style.SQL_TABLE(qn(db_table)) + '(' + style.SQL_FIELD(qn(f.column)) + ') ' + style.SQL_KEYWORD('INDEXTYPE IS ') + style.SQL_TABLE('MDSYS.SPATIAL_INDEX') + ';') return output
Python
from django.db.backends.oracle.base import * from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper from django.contrib.gis.db.backends.oracle.creation import OracleCreation from django.contrib.gis.db.backends.oracle.introspection import OracleIntrospection from django.contrib.gis.db.backends.oracle.operations import OracleOperations class DatabaseWrapper(OracleDatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.ops = OracleOperations(self) self.creation = OracleCreation(self) self.introspection = OracleIntrospection(self)
Python
# Quick tests for the markup templatetags (django.contrib.markup) import re from django.template import Template, Context, add_to_builtins from django.utils import unittest from django.utils.html import escape add_to_builtins('django.contrib.markup.templatetags.markup') try: import textile except ImportError: textile = None try: import markdown except ImportError: markdown = None try: import docutils except ImportError: docutils = None class Templates(unittest.TestCase): textile_content = """Paragraph 1 Paragraph 2 with "quotes" and @code@""" markdown_content = """Paragraph 1 ## An h2""" rest_content = """Paragraph 1 Paragraph 2 with a link_ .. _link: http://www.example.com/""" @unittest.skipUnless(textile, 'texttile not installed') def test_textile(self): t = Template("{{ textile_content|textile }}") rendered = t.render(Context({'textile_content':self.textile_content})).strip() self.assertEqual(rendered.replace('\t', ''), """<p>Paragraph 1</p> <p>Paragraph 2 with &#8220;quotes&#8221; and <code>code</code></p>""") @unittest.skipIf(textile, 'texttile is installed') def test_no_textile(self): t = Template("{{ textile_content|textile }}") rendered = t.render(Context({'textile_content':self.textile_content})).strip() self.assertEqual(rendered, escape(self.textile_content)) @unittest.skipUnless(markdown, 'markdown not installed') def test_markdown(self): t = Template("{{ markdown_content|markdown }}") rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() pattern = re.compile("""<p>Paragraph 1\s*</p>\s*<h2>\s*An h2</h2>""") self.assertTrue(pattern.match(rendered)) @unittest.skipIf(markdown, 'markdown is installed') def test_no_markdown(self): t = Template("{{ markdown_content|markdown }}") rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() self.assertEqual(rendered, self.markdown_content) @unittest.skipUnless(docutils, 'docutils not installed') def test_docutils(self): t = Template("{{ rest_content|restructuredtext }}") rendered = t.render(Context({'rest_content':self.rest_content})).strip() # Different versions of docutils return slightly different HTML try: # Docutils v0.4 and earlier self.assertEqual(rendered, """<p>Paragraph 1</p> <p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""") except AssertionError, e: # Docutils from SVN (which will become 0.5) self.assertEqual(rendered, """<p>Paragraph 1</p> <p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""") @unittest.skipIf(docutils, 'docutils is installed') def test_no_docutils(self): t = Template("{{ rest_content|restructuredtext }}") rendered = t.render(Context({'rest_content':self.rest_content})).strip() self.assertEqual(rendered, self.rest_content) if __name__ == '__main__': unittest.main()
Python
""" Set of "markup" template filters for Django. These filters transform plain text markup syntaxes to HTML; currently there is support for: * Textile, which requires the PyTextile library available at http://loopcore.com/python-textile/ * Markdown, which requires the Python-markdown library from http://www.freewisdom.org/projects/python-markdown * reStructuredText, which requires docutils from http://docutils.sf.net/ """ from django import template from django.conf import settings from django.utils.encoding import smart_str, force_unicode from django.utils.safestring import mark_safe register = template.Library() def textile(value): try: import textile except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.") return force_unicode(value) else: return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8'))) textile.is_safe = True def markdown(value, arg=''): """ Runs Markdown over a given value, optionally using various extensions python-markdown supports. Syntax:: {{ value|markdown:"extension1_name,extension2_name..." }} To enable safe mode, which strips raw HTML and only returns HTML generated by actual Markdown syntax, pass "safe" as the first extension in the list. If the version of Markdown in use does not support extensions, they will be silently ignored. """ try: import markdown except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.") return force_unicode(value) else: # markdown.version was first added in 1.6b. The only version of markdown # to fully support extensions before 1.6b was the shortlived 1.6a. if hasattr(markdown, 'version'): extensions = [e for e in arg.split(",") if e] if len(extensions) > 0 and extensions[0] == "safe": extensions = extensions[1:] safe_mode = True else: safe_mode = False # Unicode support only in markdown v1.7 or above. Version_info # exist only in markdown v1.6.2rc-2 or above. if getattr(markdown, "version_info", None) < (1,7): return mark_safe(force_unicode(markdown.markdown(smart_str(value), extensions, safe_mode=safe_mode))) else: return mark_safe(markdown.markdown(force_unicode(value), extensions, safe_mode=safe_mode)) else: return mark_safe(force_unicode(markdown.markdown(smart_str(value)))) markdown.is_safe = True def restructuredtext(value): try: from docutils.core import publish_parts except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% restructuredtext %} filter: The Python docutils library isn't installed.") return force_unicode(value) else: docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {}) parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides=docutils_settings) return mark_safe(force_unicode(parts["fragment"])) restructuredtext.is_safe = True register.filter(textile) register.filter(markdown) register.filter(restructuredtext)
Python
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the given session dictionary pickled and encoded as a string. """ return SessionStore().encode(session_dict) def save(self, session_key, session_dict, expire_date): s = self.model(session_key, self.encode(session_dict), expire_date) if session_dict: s.save() else: s.delete() # Clear sessions with no data. return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID -- not the data itself. The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. For complete documentation on using Sessions in your code, consult the sessions documentation that is shipped with Django (also available on the Django Web site). """ session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date'), db_index=True) objects = SessionManager() class Meta: db_table = 'django_session' verbose_name = _('session') verbose_name_plural = _('sessions') def get_decoded(self): return SessionStore().decode(self.session_data) # At bottom to avoid circular import from django.contrib.sessions.backends.db import SessionStore
Python
import base64 from datetime import datetime, timedelta import pickle import shutil import tempfile from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession from django.contrib.sessions.backends.file import SessionStore as FileSession from django.contrib.sessions.models import Session from django.contrib.sessions.middleware import SessionMiddleware from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.http import HttpResponse from django.test import TestCase, RequestFactory from django.utils import unittest from django.utils.hashcompat import md5_constructor class SessionTestsMixin(object): # This does not inherit from TestCase to avoid any tests being run with this # class, which wouldn't work, and to allow different TestCase subclasses to # be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() def tearDown(self): # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots # of runs (think buildbots) self.session.delete() def test_new_session(self): self.assertFalse(self.session.modified) self.assertFalse(self.session.accessed) def test_get_empty(self): self.assertEqual(self.session.get('cat'), None) def test_store(self): self.session['cat'] = "dog" self.assertTrue(self.session.modified) self.assertEqual(self.session.pop('cat'), 'dog') def test_pop(self): self.session['some key'] = 'exists' # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop('some key'), 'exists') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get('some key'), None) def test_pop_default(self): self.assertEqual(self.session.pop('some key', 'does not exist'), 'does not exist') self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_setdefault(self): self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar') self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_update(self): self.session.update({'update key': 1}) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get('update key', None), 1) def test_has_key(self): self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertTrue(self.session.has_key('some key')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_values(self): self.assertEqual(self.session.values(), []) self.assertTrue(self.session.accessed) self.session['some key'] = 1 self.assertEqual(self.session.values(), [1]) def test_iterkeys(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = self.session.iterkeys() self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), ['x']) def test_itervalues(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = self.session.itervalues() self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), [1]) def test_iteritems(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = self.session.iteritems() self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), [('x',1)]) def test_clear(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(self.session.items(), [('x',1)]) self.session.clear() self.assertEqual(self.session.items(), []) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_save(self): self.session.save() self.assertTrue(self.session.exists(self.session.session_key)) def test_delete(self): self.session.delete(self.session.session_key) self.assertFalse(self.session.exists(self.session.session_key)) def test_flush(self): self.session['foo'] = 'bar' self.session.save() prev_key = self.session.session_key self.session.flush() self.assertFalse(self.session.exists(prev_key)) self.assertNotEqual(self.session.session_key, prev_key) self.assertTrue(self.session.modified) self.assertTrue(self.session.accessed) def test_cycle(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_key = self.session.session_key prev_data = self.session.items() self.session.cycle_key() self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(self.session.items(), prev_data) def test_invalid_key(self): # Submitting an invalid session key (either by guessing, or if the db has # removed the key) results in a new key being generated. try: session = self.backend('1') session.save() self.assertNotEqual(session.session_key, '1') self.assertEqual(session.get('cat'), None) session.delete() finally: # Some backends leave a stale cache entry for the invalid # session key; make sure that entry is manually deleted session.delete('1') # Custom session expiry def test_default_expiry(self): # A normal session has a max age equal to settings self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_custom_expiry_seconds(self): # Using seconds self.session.set_expiry(10) delta = self.session.get_expiry_date() - datetime.now() self.assertTrue(delta.seconds in (9, 10)) age = self.session.get_expiry_age() self.assertTrue(age in (9, 10)) def test_custom_expiry_timedelta(self): # Using timedelta self.session.set_expiry(timedelta(seconds=10)) delta = self.session.get_expiry_date() - datetime.now() self.assertTrue(delta.seconds in (9, 10)) age = self.session.get_expiry_age() self.assertTrue(age in (9, 10)) def test_custom_expiry_datetime(self): # Using fixed datetime self.session.set_expiry(datetime.now() + timedelta(seconds=10)) delta = self.session.get_expiry_date() - datetime.now() self.assertTrue(delta.seconds in (9, 10)) age = self.session.get_expiry_age() self.assertTrue(age in (9, 10)) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and different # set_expiry calls try: try: original_expire_at_browser_close = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertFalse(self.session.get_expire_at_browser_close()) settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertTrue(self.session.get_expire_at_browser_close()) except: raise finally: settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_expire_at_browser_close def test_decode(self): # Ensure we can decode what we encode data = {'a test key': 'a test value'} encoded = self.session.encode(data) self.assertEqual(self.session.decode(encoded), data) def test_decode_django12(self): # Ensure we can decode values encoded using Django 1.2 # Hard code the Django 1.2 method here: def encode(session_dict): pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) data = {'a test key': 'a test value'} encoded = encode(data) self.assertEqual(self.session.decode(encoded), data) class DatabaseSessionTests(SessionTestsMixin, TestCase): backend = DatabaseSession def test_session_get_decoded(self): """ Test we can use Session.get_decoded to retrieve data stored in normal way """ self.session['x'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {'x': 1}) def test_sessionmanager_save(self): """ Test SessionManager.save method """ # Create a session self.session['y'] = 1 self.session.save() s = Session.objects.get(session_key=self.session.session_key) # Change it Session.objects.save(s.session_key, {'y':2}, s.expire_date) # Clear cache, so that it will be retrieved from DB del self.session._session_cache self.assertEqual(self.session['y'], 2) class CacheDBSessionTests(SessionTestsMixin, TestCase): backend = CacheDBSession # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class FileSessionTests(SessionTestsMixin, unittest.TestCase): backend = FileSession def setUp(self): super(FileSessionTests, self).setUp() # Do file session tests in an isolated directory, and kill it after we're done. self.original_session_file_path = settings.SESSION_FILE_PATH self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp() def tearDown(self): settings.SESSION_FILE_PATH = self.original_session_file_path shutil.rmtree(self.temp_session_store) super(FileSessionTests, self).tearDown() def test_configuration_check(self): # Make sure the file backend checks for a good storage dir settings.SESSION_FILE_PATH = "/if/this/directory/exists/you/have/a/weird/computer" self.assertRaises(ImproperlyConfigured, self.backend) def test_invalid_key_backslash(self): # Ensure we don't allow directory-traversal self.assertRaises(SuspiciousOperation, self.backend("a\\b\\c").load) def test_invalid_key_forwardslash(self): # Ensure we don't allow directory-traversal self.assertRaises(SuspiciousOperation, self.backend("a/b/c").load) class CacheSessionTests(SessionTestsMixin, unittest.TestCase): backend = CacheSession class SessionMiddlewareTests(unittest.TestCase): def setUp(self): self.old_SESSION_COOKIE_SECURE = settings.SESSION_COOKIE_SECURE self.old_SESSION_COOKIE_HTTPONLY = settings.SESSION_COOKIE_HTTPONLY def tearDown(self): settings.SESSION_COOKIE_SECURE = self.old_SESSION_COOKIE_SECURE settings.SESSION_COOKIE_HTTPONLY = self.old_SESSION_COOKIE_HTTPONLY def test_secure_session_cookie(self): settings.SESSION_COOKIE_SECURE = True request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertTrue(response.cookies[settings.SESSION_COOKIE_NAME]['secure']) def test_httponly_session_cookie(self): settings.SESSION_COOKIE_HTTPONLY = True request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertTrue(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])
Python
import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date from django.utils.importlib import import_module class SessionMiddleware(object): def process_request(self, request): engine = import_module(settings.SESSION_ENGINE) session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) request.session = engine.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save the session data and refresh the client cookie. request.session.save() response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None) return response
Python
import errno import os import tempfile from django.conf import settings from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured class SessionStore(SessionBase): """ Implements a file based session store. """ def __init__(self, session_key=None): self.storage_path = getattr(settings, "SESSION_FILE_PATH", None) if not self.storage_path: self.storage_path = tempfile.gettempdir() # Make sure the storage path is valid. if not os.path.isdir(self.storage_path): raise ImproperlyConfigured( "The session storage path %r doesn't exist. Please set your" " SESSION_FILE_PATH setting to an existing directory in which" " Django can store session data." % self.storage_path) self.file_prefix = settings.SESSION_COOKIE_NAME super(SessionStore, self).__init__(session_key) VALID_KEY_CHARS = set("abcdef0123456789") def _key_to_file(self, session_key=None): """ Get the file associated with this session key. """ if session_key is None: session_key = self.session_key # Make sure we're not vulnerable to directory traversal. Session keys # should always be md5s, so they should never contain directory # components. if not set(session_key).issubset(self.VALID_KEY_CHARS): raise SuspiciousOperation( "Invalid characters in session key") return os.path.join(self.storage_path, self.file_prefix + session_key) def load(self): session_data = {} try: session_file = open(self._key_to_file(), "rb") try: file_data = session_file.read() # Don't fail if there is no data in the session file. # We may have opened the empty placeholder file. if file_data: try: session_data = self.decode(file_data) except (EOFError, SuspiciousOperation): self.create() finally: session_file.close() except IOError: self.create() return session_data def create(self): while True: self._session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True self._session_cache = {} return def save(self, must_create=False): # Get the session data now, before we start messing # with the file it is stored within. session_data = self._get_session(no_load=must_create) session_file_name = self._key_to_file() try: # Make sure the file exists. If it does not already exist, an # empty placeholder file is created. flags = os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) if must_create: flags |= os.O_EXCL fd = os.open(session_file_name, flags) os.close(fd) except OSError, e: if must_create and e.errno == errno.EEXIST: raise CreateError raise # Write the session file without interfering with other threads # or processes. By writing to an atomically generated temporary # file and then using the atomic os.rename() to make the complete # file visible, we avoid having to lock the session file, while # still maintaining its integrity. # # Note: Locking the session file was explored, but rejected in part # because in order to be atomic and cross-platform, it required a # long-lived lock file for each session, doubling the number of # files in the session storage directory at any given time. This # rename solution is cleaner and avoids any additional overhead # when reading the session data, which is the more common case # unless SESSION_SAVE_EVERY_REQUEST = True. # # See ticket #8616. dir, prefix = os.path.split(session_file_name) try: output_file_fd, output_file_name = tempfile.mkstemp(dir=dir, prefix=prefix + '_out_') renamed = False try: try: os.write(output_file_fd, self.encode(session_data)) finally: os.close(output_file_fd) os.rename(output_file_name, session_file_name) renamed = True finally: if not renamed: os.unlink(output_file_name) except (OSError, IOError, EOFError): pass def exists(self, session_key): if os.path.exists(self._key_to_file(session_key)): return True return False def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key try: os.unlink(self._key_to_file(session_key)) except OSError: pass def clean(self): pass
Python
import datetime from django.conf import settings from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation from django.db import IntegrityError, transaction, router from django.utils.encoding import force_unicode class SessionStore(SessionBase): """ Implements database session store. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): try: s = Session.objects.get( session_key = self.session_key, expire_date__gt=datetime.datetime.now() ) return self.decode(force_unicode(s.session_data)) except (Session.DoesNotExist, SuspiciousOperation): self.create() return {} def exists(self, session_key): try: Session.objects.get(session_key=session_key) except Session.DoesNotExist: return False return True def create(self): while True: self.session_key = self._get_new_session_key() try: # Save immediately to ensure we have a unique entry in the # database. self.save(must_create=True) except CreateError: # Key wasn't unique. Try again. continue self.modified = True self._session_cache = {} return def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session( session_key = self.session_key, session_data = self.encode(self._get_session(no_load=must_create)), expire_date = self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: transaction.savepoint_rollback(sid, using=using) raise CreateError raise def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key try: Session.objects.get(session_key=session_key).delete() except Session.DoesNotExist: pass # At bottom to avoid circular import from django.contrib.sessions.models import Session
Python
import base64 import os import random import sys import time from datetime import datetime, timedelta try: import cPickle as pickle except ImportError: import pickle from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.utils.hashcompat import md5_constructor from django.utils.crypto import constant_time_compare, salted_hmac # Use the system (hardware-based) random number generator if it exists. if hasattr(random, 'SystemRandom'): randrange = random.SystemRandom().randrange else: randrange = random.randrange MAX_SESSION_KEY = 18446744073709551616L # 2 << 63 class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class SessionBase(object): """ Base class for all Session classes. """ TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def keys(self): return self._session.keys() def items(self): return self._session.items() def get(self, key, default=None): return self._session.get(key, default) def pop(self, key, *args): self.modified = self.modified or key in self._session return self._session.pop(key, *args) def setdefault(self, key, value): if key in self._session: return self._session[key] else: self.modified = True self._session[key] = value return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE def delete_test_cookie(self): del self[self.TEST_COOKIE_NAME] def _hash(self, value): key_salt = "django.contrib.sessions" + self.__class__.__name__ return salted_hmac(key_salt, value).hexdigest() def encode(self, session_dict): "Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) hash = self._hash(pickled) return base64.encodestring(hash + ":" + pickled) def decode(self, session_data): encoded_data = base64.decodestring(session_data) try: # could produce ValueError if there is no ':' hash, pickled = encoded_data.split(':', 1) expected_hash = self._hash(pickled) if not constant_time_compare(hash, expected_hash): raise SuspiciousOperation("Session data corrupted") else: return pickle.loads(pickled) except Exception: # ValueError, SuspiciousOperation, unpickling exceptions # Fall back to Django 1.2 method # PendingDeprecationWarning <- here to remind us to # remove this fallback in Django 1.5 try: return self._decode_old(session_data) except Exception: # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). return {} def _decode_old(self, session_data): encoded_data = base64.decodestring(session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if not constant_time_compare(md5_constructor(pickled + settings.SECRET_KEY).hexdigest(), tamper_check): raise SuspiciousOperation("User tampered with session cookie.") return pickle.loads(pickled) def update(self, dict_): self._session.update(dict_) self.modified = True def has_key(self, key): return self._session.has_key(key) def values(self): return self._session.values() def iterkeys(self): return self._session.iterkeys() def itervalues(self): return self._session.itervalues() def iteritems(self): return self._session.iteritems() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True def _get_new_session_key(self): "Returns session key that isn't being used." # The random module is seeded when this Apache child is created. # Use settings.SECRET_KEY as added salt. try: pid = os.getpid() except AttributeError: # No getpid() in Jython, for example pid = 1 while 1: session_key = md5_constructor("%s%s%s%s" % (randrange(0, MAX_SESSION_KEY), pid, time.time(), settings.SECRET_KEY)).hexdigest() if not self.exists(session_key): break return session_key def _get_session_key(self): if self._session_key: return self._session_key else: self._session_key = self._get_new_session_key() return self._session_key def _set_session_key(self, session_key): self._session_key = session_key session_key = property(_get_session_key, _set_session_key) def _get_session(self, no_load=False): """ Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeError: if self._session_key is None or no_load: self._session_cache = {} else: self._session_cache = self.load() return self._session_cache _session = property(_get_session) def get_expiry_age(self): """Get the number of seconds until the session expires.""" expiry = self.get('_session_expiry') if not expiry: # Checks both None and 0 cases return settings.SESSION_COOKIE_AGE if not isinstance(expiry, datetime): return expiry delta = expiry - datetime.now() return delta.days * 86400 + delta.seconds def get_expiry_date(self): """Get session the expiry date (as a datetime object).""" expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if not expiry: # Checks both None and 0 cases expiry = settings.SESSION_COOKIE_AGE return datetime.now() + timedelta(seconds=expiry) def set_expiry(self, value): """ Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or ``timedelta`` object, the session will expire at that specific future time. If ``value`` is ``None``, the session uses the global session expiry policy. """ if value is None: # Remove any custom expiration for this session. try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = datetime.now() + value self['_session_expiry'] = value def get_expire_at_browser_close(self): """ Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ if self.get('_session_expiry') is None: return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return self.get('_session_expiry') == 0 def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete() self.create() def cycle_key(self): """ Creates a new session key, whilst retaining the current session data. """ data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key) # Methods that child classes must implement. def exists(self, session_key): """ Returns True if the given session_key already exists. """ raise NotImplementedError def create(self): """ Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError def save(self, must_create=False): """ Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key. """ raise NotImplementedError def delete(self, session_key=None): """ Deletes the session data under this key. If the key is None, the current session key value is used. """ raise NotImplementedError def load(self): """ Loads the session data and returns a dictionary. """ raise NotImplementedError
Python
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implements cached, database backed sessions. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): data = cache.get(KEY_PREFIX + self.session_key, None) if data is None: data = super(SessionStore, self).load() cache.set(KEY_PREFIX + self.session_key, data, settings.SESSION_COOKIE_AGE) return data def exists(self, session_key): return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(KEY_PREFIX + self.session_key, self._session, settings.SESSION_COOKIE_AGE) def delete(self, session_key=None): super(SessionStore, self).delete(session_key) cache.delete(KEY_PREFIX + (session_key or self.session_key)) def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete(self.session_key) self.create()
Python
from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cache" class SessionStore(SessionBase): """ A cache-based session store. """ def __init__(self, session_key=None): self._cache = cache super(SessionStore, self).__init__(session_key) def load(self): session_data = self._cache.get(KEY_PREFIX + self.session_key) if session_data is not None: return session_data self.create() return {} def create(self): # Because a cache can fail silently (e.g. memcache), we don't know if # we are failing to create a new session because of a key collision or # because the cache is missing. So we try for a (large) number of times # and then raise an exception. That's the risk you shoulder if using # cache backing. for i in xrange(10000): self.session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True return raise RuntimeError("Unable to create a new session key.") def save(self, must_create=False): if must_create: func = self._cache.add else: func = self._cache.set result = func(KEY_PREFIX + self.session_key, self._get_session(no_load=must_create), self.get_expiry_age()) if must_create and not result: raise CreateError def exists(self, session_key): if self._cache.has_key(KEY_PREFIX + session_key): return True return False def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key self._cache.delete(KEY_PREFIX + session_key)
Python
from django.utils.translation import ungettext, ugettext as _ from django.utils.encoding import force_unicode from django import template from django.template import defaultfilters from datetime import date import re register = template.Library() def ordinal(value): """ Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer. """ try: value = int(value) except (TypeError, ValueError): return value t = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th')) if value % 100 in (11, 12, 13): # special case return u"%d%s" % (value, t[0]) return u'%d%s' % (value, t[value % 10]) ordinal.is_safe = True register.filter(ordinal) def intcomma(value): """ Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ orig = force_unicode(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) if orig == new: return new else: return intcomma(new) intcomma.is_safe = True register.filter(intcomma) def intword(value): """ Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ try: value = int(value) except (TypeError, ValueError): return value if value < 1000000: return value if value < 1000000000: new_value = value / 1000000.0 return ungettext('%(value).1f million', '%(value).1f million', new_value) % {'value': new_value} if value < 1000000000000: new_value = value / 1000000000.0 return ungettext('%(value).1f billion', '%(value).1f billion', new_value) % {'value': new_value} if value < 1000000000000000: new_value = value / 1000000000000.0 return ungettext('%(value).1f trillion', '%(value).1f trillion', new_value) % {'value': new_value} return value intword.is_safe = False register.filter(intword) def apnumber(value): """ For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. """ try: value = int(value) except (TypeError, ValueError): return value if not 0 < value < 10: return value return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'), _('seven'), _('eight'), _('nine'))[value-1] apnumber.is_safe = True register.filter(apnumber) def naturalday(value, arg=None): """ For date values that are tomorrow, today or yesterday compared to present day returns representing string. Otherwise, returns a string formatted according to settings.DATE_FORMAT. """ try: value = date(value.year, value.month, value.day) except AttributeError: # Passed value wasn't a date object return value except ValueError: # Date arguments out of range return value delta = value - date.today() if delta.days == 0: return _(u'today') elif delta.days == 1: return _(u'tomorrow') elif delta.days == -1: return _(u'yesterday') return defaultfilters.date(value, arg) register.filter(naturalday)
Python
from django.conf.urls.defaults import * from django.contrib.databrowse import views # Note: The views in this URLconf all require a 'models' argument, # which is a list of model classes (*not* instances). urlpatterns = patterns('', #(r'^$', views.homepage), #(r'^([^/]+)/([^/]+)/$', views.model_detail), (r'^([^/]+)/([^/]+)/fields/(\w+)/$', views.choice_list), (r'^([^/]+)/([^/]+)/fields/(\w+)/(.*)/$', views.choice_detail), #(r'^([^/]+)/([^/]+)/calendars/(\w+)/$', views.calendar_main), #(r'^([^/]+)/([^/]+)/calendars/(\w+)/(\d{4})/$', views.calendar_year), #(r'^([^/]+)/([^/]+)/calendars/(\w+)/(\d{4})/(\w{3})/$', views.calendar_month), #(r'^([^/]+)/([^/]+)/calendars/(\w+)/(\d{4})/(\w{3})/(\d{1,2})/$', views.calendar_day), #(r'^([^/]+)/([^/]+)/objects/(.*)/$', views.object_detail), )
Python
from django import http from django.db import models from django.contrib.databrowse.datastructures import EasyModel from django.contrib.databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response from django.utils.text import capfirst from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe from django.views.generic import date_based from django.utils import datetime_safe class CalendarPlugin(DatabrowsePlugin): def __init__(self, field_names=None): self.field_names = field_names def field_dict(self, model): """ Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes take that into account when building the dictionary. """ if self.field_names is None: return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)]) else: return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField) and f.name in self.field_names]) def model_index_html(self, request, model, site): fields = self.field_dict(model) if not fields: return u'' return mark_safe(u'<p class="filter"><strong>View calendar by:</strong> %s</p>' % \ u', '.join(['<a href="calendars/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()])) def urls(self, plugin_name, easy_instance_field): if isinstance(easy_instance_field.field, models.DateField): d = easy_instance_field.raw_value return [mark_safe(u'%s%s/%s/%s/%s/%s/' % ( easy_instance_field.model.url(), plugin_name, easy_instance_field.field.name, str(d.year), datetime_safe.new_date(d).strftime('%b').lower(), d.day))] def model_view(self, request, model_databrowse, url): self.model, self.site = model_databrowse.model, model_databrowse.site self.fields = self.field_dict(self.model) # If the model has no DateFields, there's no point in going further. if not self.fields: raise http.Http404('The requested model has no calendars.') if url is None: return self.homepage_view(request) url_bits = url.split('/') if self.fields.has_key(url_bits[0]): return self.calendar_view(request, self.fields[url_bits[0]], *url_bits[1:]) raise http.Http404('The requested page does not exist.') def homepage_view(self, request): easy_model = EasyModel(self.site, self.model) field_list = self.fields.values() field_list.sort(key=lambda k:k.verbose_name) return render_to_response('databrowse/calendar_homepage.html', {'root_url': self.site.root_url, 'model': easy_model, 'field_list': field_list}) def calendar_view(self, request, field, year=None, month=None, day=None): easy_model = EasyModel(self.site, self.model) queryset = easy_model.get_query_set() extra_context = {'root_url': self.site.root_url, 'model': easy_model, 'field': field} if day is not None: return date_based.archive_day(request, year, month, day, queryset, field.name, template_name='databrowse/calendar_day.html', allow_empty=False, allow_future=True, extra_context=extra_context) elif month is not None: return date_based.archive_month(request, year, month, queryset, field.name, template_name='databrowse/calendar_month.html', allow_empty=False, allow_future=True, extra_context=extra_context) elif year is not None: return date_based.archive_year(request, year, queryset, field.name, template_name='databrowse/calendar_year.html', allow_empty=False, allow_future=True, extra_context=extra_context) else: return date_based.archive_index(request, queryset, field.name, template_name='databrowse/calendar_main.html', allow_empty=True, allow_future=True, extra_context=extra_context) assert False, ('%s, %s, %s, %s' % (field, year, month, day))
Python
from django import http from django.db import models from django.contrib.databrowse.datastructures import EasyModel from django.contrib.databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response from django.utils.text import capfirst from django.utils.encoding import smart_str, force_unicode from django.utils.safestring import mark_safe import urllib class FieldChoicePlugin(DatabrowsePlugin): def __init__(self, field_filter=None): # If field_filter is given, it should be a callable that takes a # Django database Field instance and returns True if that field should # be included. If field_filter is None, that all fields will be used. self.field_filter = field_filter def field_dict(self, model): """ Helper function that returns a dictionary of all fields in the given model. If self.field_filter is set, it only includes the fields that match the filter. """ if self.field_filter: return dict([(f.name, f) for f in model._meta.fields if self.field_filter(f)]) else: return dict([(f.name, f) for f in model._meta.fields if not f.rel and not f.primary_key and not f.unique and not isinstance(f, (models.AutoField, models.TextField))]) def model_index_html(self, request, model, site): fields = self.field_dict(model) if not fields: return u'' return mark_safe(u'<p class="filter"><strong>View by:</strong> %s</p>' % \ u', '.join(['<a href="fields/%s/">%s</a>' % (f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()])) def urls(self, plugin_name, easy_instance_field): if easy_instance_field.field in self.field_dict(easy_instance_field.model.model).values(): field_value = smart_str(easy_instance_field.raw_value) return [mark_safe(u'%s%s/%s/%s/' % ( easy_instance_field.model.url(), plugin_name, easy_instance_field.field.name, urllib.quote(field_value, safe='')))] def model_view(self, request, model_databrowse, url): self.model, self.site = model_databrowse.model, model_databrowse.site self.fields = self.field_dict(self.model) # If the model has no fields with choices, there's no point in going # further. if not self.fields: raise http.Http404('The requested model has no fields.') if url is None: return self.homepage_view(request) url_bits = url.split('/', 1) if self.fields.has_key(url_bits[0]): return self.field_view(request, self.fields[url_bits[0]], *url_bits[1:]) raise http.Http404('The requested page does not exist.') def homepage_view(self, request): easy_model = EasyModel(self.site, self.model) field_list = self.fields.values() field_list.sort(key=lambda k: k.verbose_name) return render_to_response('databrowse/fieldchoice_homepage.html', {'root_url': self.site.root_url, 'model': easy_model, 'field_list': field_list}) def field_view(self, request, field, value=None): easy_model = EasyModel(self.site, self.model) easy_field = easy_model.field(field.name) if value is not None: obj_list = easy_model.objects(**{field.name: value}) return render_to_response('databrowse/fieldchoice_detail.html', {'root_url': self.site.root_url, 'model': easy_model, 'field': easy_field, 'value': value, 'object_list': obj_list}) obj_list = [v[field.name] for v in self.model._default_manager.distinct().order_by(field.name).values(field.name)] return render_to_response('databrowse/fieldchoice_list.html', {'root_url': self.site.root_url, 'model': easy_model, 'field': easy_field, 'object_list': obj_list})
Python
from django import http from django.contrib.databrowse.datastructures import EasyModel from django.contrib.databrowse.sites import DatabrowsePlugin from django.shortcuts import render_to_response import urlparse class ObjectDetailPlugin(DatabrowsePlugin): def model_view(self, request, model_databrowse, url): # If the object ID wasn't provided, redirect to the model page, which is one level up. if url is None: return http.HttpResponseRedirect(urlparse.urljoin(request.path, '../')) easy_model = EasyModel(model_databrowse.site, model_databrowse.model) obj = easy_model.object_by_pk(url) return render_to_response('databrowse/object_detail.html', {'object': obj, 'root_url': model_databrowse.site.root_url})
Python
from django import http from django.db import models from django.contrib.databrowse.datastructures import EasyModel from django.shortcuts import render_to_response from django.utils.safestring import mark_safe class AlreadyRegistered(Exception): pass class NotRegistered(Exception): pass class DatabrowsePlugin(object): def urls(self, plugin_name, easy_instance_field): """ Given an EasyInstanceField object, returns a list of URLs for this plugin's views of this object. These URLs should be absolute. Returns None if the EasyInstanceField object doesn't get a list of plugin-specific URLs. """ return None def model_index_html(self, request, model, site): """ Returns a snippet of HTML to include on the model index page. """ return '' def model_view(self, request, model_databrowse, url): """ Handles main URL routing for a plugin's model-specific pages. """ raise NotImplementedError class ModelDatabrowse(object): plugins = {} def __init__(self, model, site): self.model = model self.site = site def root(self, request, url): """ Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'objects/3'. """ # Delegate to the appropriate method, based on the URL. if url is None: return self.main_view(request) try: plugin_name, rest_of_url = url.split('/', 1) except ValueError: # need more than 1 value to unpack plugin_name, rest_of_url = url, None try: plugin = self.plugins[plugin_name] except KeyError: raise http.Http404('A plugin with the requested name does not exist.') return plugin.model_view(request, self, rest_of_url) def main_view(self, request): easy_model = EasyModel(self.site, self.model) html_snippets = mark_safe(u'\n'.join([p.model_index_html(request, self.model, self.site) for p in self.plugins.values()])) return render_to_response('databrowse/model_detail.html', { 'model': easy_model, 'root_url': self.site.root_url, 'plugin_html': html_snippets, }) class DatabrowseSite(object): def __init__(self): self.registry = {} # model_class -> databrowse_class self.root_url = None def register(self, model_or_iterable, databrowse_class=None, **options): """ Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn't given, it will use DefaultModelDatabrowse (the default databrowse options). If a model is already registered, this will raise AlreadyRegistered. """ databrowse_class = databrowse_class or DefaultModelDatabrowse if issubclass(model_or_iterable, models.Model): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model in self.registry: raise AlreadyRegistered('The model %s is already registered' % model.__name__) self.registry[model] = databrowse_class def unregister(self, model_or_iterable): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ if issubclass(model_or_iterable, models.Model): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self.registry: raise NotRegistered('The model %s is not registered' % model.__name__) del self.registry[model] def root(self, request, url): """ Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'comments/comment/'. """ self.root_url = request.path[:len(request.path) - len(url)] url = url.rstrip('/') # Trim trailing slash, if it exists. if url == '': return self.index(request) elif '/' in url: return self.model_page(request, *url.split('/', 2)) raise http.Http404('The requested databrowse page does not exist.') def index(self, request): m_list = [EasyModel(self, m) for m in self.registry.keys()] return render_to_response('databrowse/homepage.html', {'model_list': m_list, 'root_url': self.root_url}) def model_page(self, request, app_label, model_name, rest_of_url=None): """ Handles the model-specific functionality of the databrowse site, delegating to the appropriate ModelDatabrowse class. """ model = models.get_model(app_label, model_name) if model is None: raise http.Http404("App %r, model %r, not found." % (app_label, model_name)) try: databrowse_class = self.registry[model] except KeyError: raise http.Http404("This model exists but has not been registered with databrowse.") return databrowse_class(model, self).root(request, rest_of_url) site = DatabrowseSite() from django.contrib.databrowse.plugins.calendars import CalendarPlugin from django.contrib.databrowse.plugins.objects import ObjectDetailPlugin from django.contrib.databrowse.plugins.fieldchoices import FieldChoicePlugin class DefaultModelDatabrowse(ModelDatabrowse): plugins = {'objects': ObjectDetailPlugin(), 'calendars': CalendarPlugin(), 'fields': FieldChoicePlugin()}
Python
from django.http import Http404 from django.shortcuts import render_to_response ########### # CHOICES # ########### def choice_list(request, app_label, module_name, field_name, models): m, f = lookup_field(app_label, module_name, field_name, models) return render_to_response('databrowse/choice_list.html', {'model': m, 'field': f}) def choice_detail(request, app_label, module_name, field_name, field_val, models): m, f = lookup_field(app_label, module_name, field_name, models) try: label = dict(f.field.choices)[field_val] except KeyError: raise Http404('Invalid choice value given') obj_list = m.objects(**{f.field.name: field_val}) return render_to_response('databrowse/choice_detail.html', {'model': m, 'field': f, 'value': label, 'object_list': obj_list})
Python
from django.contrib.databrowse.sites import DatabrowsePlugin, ModelDatabrowse, DatabrowseSite, site
Python
""" These classes are light wrappers around Django's database API that provide convenience functionality and permalink functions for the databrowse app. """ from django.db import models from django.utils import formats from django.utils.text import capfirst from django.utils.encoding import smart_unicode, smart_str, iri_to_uri from django.utils.safestring import mark_safe from django.db.models.query import QuerySet EMPTY_VALUE = '(None)' DISPLAY_SIZE = 100 class EasyModel(object): def __init__(self, site, model): self.site = site self.model = model self.model_list = site.registry.keys() self.verbose_name = model._meta.verbose_name self.verbose_name_plural = model._meta.verbose_name_plural def __repr__(self): return '<EasyModel for %s>' % smart_str(self.model._meta.object_name) def model_databrowse(self): "Returns the ModelDatabrowse class for this model." return self.site.registry[self.model] def url(self): return mark_safe('%s%s/%s/' % (self.site.root_url, self.model._meta.app_label, self.model._meta.module_name)) def objects(self, **kwargs): return self.get_query_set().filter(**kwargs) def get_query_set(self): easy_qs = self.model._default_manager.get_query_set()._clone(klass=EasyQuerySet) easy_qs._easymodel = self return easy_qs def object_by_pk(self, pk): return EasyInstance(self, self.model._default_manager.get(pk=pk)) def sample_objects(self): for obj in self.model._default_manager.all()[:3]: yield EasyInstance(self, obj) def field(self, name): try: f = self.model._meta.get_field(name) except models.FieldDoesNotExist: return None return EasyField(self, f) def fields(self): return [EasyField(self, f) for f in (self.model._meta.fields + self.model._meta.many_to_many)] class EasyField(object): def __init__(self, easy_model, field): self.model, self.field = easy_model, field def __repr__(self): return smart_str(u'<EasyField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def choices(self): for value, label in self.field.choices: yield EasyChoice(self.model, self, value, label) def url(self): if self.field.choices: return mark_safe('%s%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name)) elif self.field.rel: return mark_safe('%s%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name)) class EasyChoice(object): def __init__(self, easy_model, field, value, label): self.model, self.field = easy_model, field self.value, self.label = value, label def __repr__(self): return smart_str(u'<EasyChoice for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def url(self): return mark_safe('%s%s/%s/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.field.name, iri_to_uri(self.value))) class EasyInstance(object): def __init__(self, easy_model, instance): self.model, self.instance = easy_model, instance def __repr__(self): return smart_str(u'<EasyInstance for %s (%s)>' % (self.model.model._meta.object_name, self.instance._get_pk_val())) def __unicode__(self): val = smart_unicode(self.instance) if len(val) > DISPLAY_SIZE: return val[:DISPLAY_SIZE] + u'...' return val def __str__(self): return self.__unicode__().encode('utf-8') def pk(self): return self.instance._get_pk_val() def url(self): return mark_safe('%s%s/%s/objects/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, iri_to_uri(self.pk()))) def fields(self): """ Generator that yields EasyInstanceFields for each field in this EasyInstance's model. """ for f in self.model.model._meta.fields + self.model.model._meta.many_to_many: yield EasyInstanceField(self.model, self, f) def related_objects(self): """ Generator that yields dictionaries of all models that have this EasyInstance's model as a ForeignKey or ManyToManyField, along with lists of related objects. """ for rel_object in self.model.model._meta.get_all_related_objects() + self.model.model._meta.get_all_related_many_to_many_objects(): if rel_object.model not in self.model.model_list: continue # Skip models that aren't in the model_list em = EasyModel(self.model.site, rel_object.model) yield { 'model': em, 'related_field': rel_object.field.verbose_name, 'object_list': [EasyInstance(em, i) for i in getattr(self.instance, rel_object.get_accessor_name()).all()], } class EasyInstanceField(object): def __init__(self, easy_model, instance, field): self.model, self.field, self.instance = easy_model, field, instance self.raw_value = getattr(instance.instance, field.name) def __repr__(self): return smart_str(u'<EasyInstanceField for %s.%s>' % (self.model.model._meta.object_name, self.field.name)) def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """ # This import is deliberately inside the function because it causes # some settings to be imported, and we don't want to do that at the # module level. if self.field.rel: if isinstance(self.field.rel, models.ManyToOneRel): objs = getattr(self.instance.instance, self.field.name) elif isinstance(self.field.rel, models.ManyToManyRel): # ManyToManyRel return list(getattr(self.instance.instance, self.field.name).all()) elif self.field.choices: objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE) elif isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField): if self.raw_value: if isinstance(self.field, models.DateTimeField): objs = capfirst(formats.date_format(self.raw_value, 'DATETIME_FORMAT')) elif isinstance(self.field, models.TimeField): objs = capfirst(formats.time_format(self.raw_value, 'TIME_FORMAT')) else: objs = capfirst(formats.date_format(self.raw_value, 'DATE_FORMAT')) else: objs = EMPTY_VALUE elif isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField): objs = {True: 'Yes', False: 'No', None: 'Unknown'}[self.raw_value] else: objs = self.raw_value return [objs] def urls(self): "Returns a list of (value, URL) tuples." # First, check the urls() method for each plugin. plugin_urls = [] for plugin_name, plugin in self.model.model_databrowse().plugins.items(): urls = plugin.urls(plugin_name, self) if urls is not None: #plugin_urls.append(urls) values = self.values() return zip(self.values(), urls) if self.field.rel: m = EasyModel(self.model.site, self.field.rel.to) if self.field.rel.to in self.model.model_list: lst = [] for value in self.values(): url = mark_safe('%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val()))) lst.append((smart_unicode(value), url)) else: lst = [(value, None) for value in self.values()] elif self.field.choices: lst = [] for value in self.values(): url = mark_safe('%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value))) lst.append((value, url)) elif isinstance(self.field, models.URLField): val = self.values()[0] lst = [(val, iri_to_uri(val))] else: lst = [(self.values()[0], None)] return lst class EasyQuerySet(QuerySet): """ When creating (or cloning to) an `EasyQuerySet`, make sure to set the `_easymodel` variable to the related `EasyModel`. """ def iterator(self, *args, **kwargs): for obj in super(EasyQuerySet, self).iterator(*args, **kwargs): yield EasyInstance(self._easymodel, obj) def _clone(self, *args, **kwargs): c = super(EasyQuerySet, self)._clone(*args, **kwargs) c._easymodel = self._easymodel return c
Python
# -*- coding: utf-8 -*- import unittest from django.contrib.webdesign.lorem_ipsum import * from django.template import loader, Context class WebdesignTest(unittest.TestCase): def test_words(self): self.assertEqual(words(7), u'lorem ipsum dolor sit amet consectetur adipisicing') def test_paragraphs(self): self.assertEqual(paragraphs(1), ['Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.']) def test_lorem_tag(self): t = loader.get_template_from_string("{% load webdesign %}{% lorem 3 w %}") self.assertEqual(t.render(Context({})), u'lorem ipsum dolor')
Python
""" Utility functions for generating "lorem ipsum" Latin text. """ import random COMMON_P = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' WORDS = ('exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet', 'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi', 'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi', 'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos', 'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum', 'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus', 'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus', 'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum', 'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem', 'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus', 'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente', 'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet', 'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta', 'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima', 'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim', 'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores', 'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias', 'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea', 'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt', 'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate', 'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius', 'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos', 'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore', 'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo', 'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi', 'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam', 'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique', 'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere', 'maxime', 'corrupti') COMMON_WORDS = ('lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua') def sentence(): """ Returns a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random. """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [u' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))] s = u', '.join(sections) # Convert to sentence case and add end punctuation. return u'%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) def paragraph(): """ Returns a randomly generated paragraph of lorem ipsum text. The paragraph consists of between 1 and 4 sentences, inclusive. """ return u' '.join([sentence() for i in range(random.randint(1, 4))]) def paragraphs(count, common=True): """ Returns a list of paragraphs as returned by paragraph(). If `common` is True, then the first paragraph will be the standard 'lorem ipsum' paragraph. Otherwise, the first paragraph will be random Latin text. Either way, subsequent paragraphs will be random Latin text. """ paras = [] for i in range(count): if common and i == 0: paras.append(COMMON_P) else: paras.append(paragraph()) return paras def words(count, common=True): """ Returns a string of `count` lorem ipsum words separated by a single space. If `common` is True, then the first 19 words will be the standard 'lorem ipsum' words. Otherwise, all words will be selected randomly. """ if common: word_list = list(COMMON_WORDS) else: word_list = [] c = len(word_list) if count > c: count -= c while count > 0: c = min(count, len(WORDS)) count -= c word_list += random.sample(WORDS, c) else: word_list = word_list[:count] return u' '.join(word_list)
Python
from django.contrib.webdesign.lorem_ipsum import words, paragraphs from django import template register = template.Library() class LoremNode(template.Node): def __init__(self, count, method, common): self.count, self.method, self.common = count, method, common def render(self, context): try: count = int(self.count.resolve(context)) except (ValueError, TypeError): count = 1 if self.method == 'w': return words(count, common=self.common) else: paras = paragraphs(count, common=self.common) if self.method == 'p': paras = ['<p>%s</p>' % p for p in paras] return u'\n\n'.join(paras) #@register.tag def lorem(parser, token): """ Creates random Latin text useful for providing test data in templates. Usage format:: {% lorem [count] [method] [random] %} ``count`` is a number (or variable) containing the number of paragraphs or words to generate (default is 1). ``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for plain-text paragraph blocks (default is ``b``). ``random`` is the word ``random``, which if given, does not use the common paragraph (starting "Lorem ipsum dolor sit amet, consectetuer..."). Examples: * ``{% lorem %}`` will output the common "lorem ipsum" paragraph * ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph and two random paragraphs each wrapped in HTML ``<p>`` tags * ``{% lorem 2 w random %}`` will output two random latin words """ bits = list(token.split_contents()) tagname = bits[0] # Random bit common = bits[-1] != 'random' if not common: bits.pop() # Method bit if bits[-1] in ('w', 'p', 'b'): method = bits.pop() else: method = 'b' # Count bit if len(bits) > 1: count = bits.pop() else: count = '1' count = parser.compile_filter(count) if len(bits) != 1: raise template.TemplateSyntaxError("Incorrect format for %r tag" % tagname) return LoremNode(count, method, common) lorem = register.tag(lorem)
Python
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode class ContentTypeManager(models.Manager): # Cache to avoid re-looking up ContentType objects all over the place. # This cache is shared by all the get_for_* methods. _cache = {} def get_by_natural_key(self, app_label, model): try: ct = self.__class__._cache[self.db][(app_label, model)] except KeyError: ct = self.get(app_label=app_label, model=model) return ct def get_for_model(self, model): """ Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don't hit the database. """ opts = model._meta while opts.proxy: model = opts.proxy_for_model opts = model._meta key = (opts.app_label, opts.object_name.lower()) try: ct = self.__class__._cache[self.db][key] except KeyError: # Load or create the ContentType entry. The smart_unicode() is # needed around opts.verbose_name_raw because name_raw might be a # django.utils.functional.__proxy__ object. ct, created = self.get_or_create( app_label = opts.app_label, model = opts.object_name.lower(), defaults = {'name': smart_unicode(opts.verbose_name_raw)}, ) self._add_to_cache(self.db, ct) return ct def get_for_id(self, id): """ Lookup a ContentType by ID. Uses the same shared cache as get_for_model (though ContentTypes are obviously not created on-the-fly by get_by_id). """ try: ct = self.__class__._cache[self.db][id] except KeyError: # This could raise a DoesNotExist; that's correct behavior and will # make sure that only correct ctypes get stored in the cache dict. ct = self.get(pk=id) self._add_to_cache(self.db, ct) return ct def clear_cache(self): """ Clear out the content-type cache. This needs to happen during database flushes to prevent caching of "stale" content type IDs (see django.contrib.contenttypes.management.update_contenttypes for where this gets called). """ self.__class__._cache.clear() def _add_to_cache(self, using, ct): """Insert a ContentType into the cache.""" model = ct.model_class() key = (model._meta.app_label, model._meta.object_name.lower()) self.__class__._cache.setdefault(using, {})[key] = ct self.__class__._cache.setdefault(using, {})[ct.id] = ct class ContentType(models.Model): name = models.CharField(max_length=100) app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _('content type') verbose_name_plural = _('content types') db_table = 'django_content_type' ordering = ('name',) unique_together = (('app_label', 'model'),) def __unicode__(self): return self.name def model_class(self): "Returns the Python model class for this type of content." from django.db import models return models.get_model(self.app_label, self.model) def get_object_for_this_type(self, **kwargs): """ Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type's get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it. """ return self.model_class()._default_manager.using(self._state.db).get(**kwargs) def natural_key(self): return (self.app_label, self.model)
Python
from django import db from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.contrib.contenttypes.views import shortcut from django.core.exceptions import ObjectDoesNotExist from django.http import HttpRequest from django.test import TestCase class ContentTypesTests(TestCase): def setUp(self): # First, let's make sure we're dealing with a blank slate (and that # DEBUG is on so that queries get logged) self.old_DEBUG = settings.DEBUG self.old_Site_meta_installed = Site._meta.installed settings.DEBUG = True ContentType.objects.clear_cache() db.reset_queries() def tearDown(self): settings.DEBUG = self.old_DEBUG Site._meta.installed = self.old_Site_meta_installed ContentType.objects.clear_cache() def test_lookup_cache(self): """ Make sure that the content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model or by ID -- should hit the database only on the first lookup. """ # At this point, a lookup for a ContentType should hit the DB ContentType.objects.get_for_model(ContentType) self.assertEqual(1, len(db.connection.queries)) # A second hit, though, won't hit the DB, nor will a lookup by ID ct = ContentType.objects.get_for_model(ContentType) self.assertEqual(1, len(db.connection.queries)) ContentType.objects.get_for_id(ct.id) self.assertEqual(1, len(db.connection.queries)) # Once we clear the cache, another lookup will again hit the DB ContentType.objects.clear_cache() ContentType.objects.get_for_model(ContentType) len(db.connection.queries) self.assertEqual(2, len(db.connection.queries)) def test_shortcut_view(self): """ Check that the shortcut view (used for the admin "view on site" functionality) returns a complete URL regardless of whether the sites framework is installed """ request = HttpRequest() request.META = { "SERVER_NAME": "Example.com", "SERVER_PORT": "80", } from django.contrib.auth.models import User user_ct = ContentType.objects.get_for_model(User) obj = User.objects.create(username="john") if Site._meta.installed: current_site = Site.objects.get_current() response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://%s/users/john/" % current_site.domain, response._headers.get("location")[1]) Site._meta.installed = False response = shortcut(request, user_ct.id, obj.id) self.assertEqual("http://Example.com/users/john/", response._headers.get("location")[1])
Python
""" Classes allowing "generic" relations through ContentType and object-id fields. """ from django.core.exceptions import ObjectDoesNotExist from django.db import connection from django.db.models import signals from django.db import models, router, DEFAULT_DB_ALIAS from django.db.models.fields.related import RelatedField, Field, ManyToManyRel from django.db.models.loading import get_model from django.forms import ModelForm from django.forms.models import BaseModelFormSet, modelformset_factory, save_instance from django.contrib.admin.options import InlineModelAdmin, flatten_fieldsets from django.utils.encoding import smart_unicode from django.utils.functional import curry from django.contrib.contenttypes.models import ContentType class GenericForeignKey(object): """ Provides a generic relation to any object through content-type/object-id fields. """ def __init__(self, ct_field="content_type", fk_field="object_id"): self.ct_field = ct_field self.fk_field = fk_field def contribute_to_class(self, cls, name): self.name = name self.model = cls self.cache_attr = "_%s_cache" % name cls._meta.add_virtual_field(self) # For some reason I don't totally understand, using weakrefs here doesn't work. signals.pre_init.connect(self.instance_pre_init, sender=cls, weak=False) # Connect myself as the descriptor for this field setattr(cls, name, self) def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs): """ Handles initializing an object with the generic FK instaed of content-type/object-id fields. """ if self.name in kwargs: value = kwargs.pop(self.name) kwargs[self.ct_field] = self.get_content_type(obj=value) kwargs[self.fk_field] = value._get_pk_val() def get_content_type(self, obj=None, id=None, using=None): # Convenience function using get_model avoids a circular import when # using this model ContentType = get_model("contenttypes", "contenttype") if obj: return ContentType.objects.db_manager(obj._state.db).get_for_model(obj) elif id: return ContentType.objects.db_manager(using).get_for_id(id) else: # This should never happen. I love comments like this, don't you? raise Exception("Impossible arguments to GFK.get_content_type!") def __get__(self, instance, instance_type=None): if instance is None: return self try: return getattr(instance, self.cache_attr) except AttributeError: rel_obj = None # Make sure to use ContentType.objects.get_for_id() to ensure that # lookups are cached (see ticket #5570). This takes more code than # the naive ``getattr(instance, self.ct_field)``, but has better # performance when dealing with GFKs in loops and such. f = self.model._meta.get_field(self.ct_field) ct_id = getattr(instance, f.get_attname(), None) if ct_id: ct = self.get_content_type(id=ct_id, using=instance._state.db) try: rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field)) except ObjectDoesNotExist: pass setattr(instance, self.cache_attr, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError(u"%s must be accessed via instance" % self.related.opts.object_name) ct = None fk = None if value is not None: ct = self.get_content_type(obj=value) fk = value._get_pk_val() setattr(instance, self.ct_field, ct) setattr(instance, self.fk_field, fk) setattr(instance, self.cache_attr, value) class GenericRelation(RelatedField, Field): """Provides an accessor to generic related objects (e.g. comments)""" def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = GenericRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True)) # Override content-type/object-id field names on the related class self.object_id_field_name = kwargs.pop("object_id_field", "object_id") self.content_type_field_name = kwargs.pop("content_type_field", "content_type") kwargs['blank'] = True kwargs['editable'] = False kwargs['serialize'] = False Field.__init__(self, **kwargs) def get_choices_default(self): return Field.get_choices(self, include_blank=False) def value_to_string(self, obj): qs = getattr(obj, self.name).all() return smart_unicode([instance._get_pk_val() for instance in qs]) def m2m_db_table(self): return self.rel.to._meta.db_table def m2m_column_name(self): return self.object_id_field_name def m2m_reverse_name(self): return self.rel.to._meta.pk.column def m2m_target_field_name(self): return self.model._meta.pk.name def m2m_reverse_target_field_name(self): return self.rel.to._meta.pk.name def contribute_to_class(self, cls, name): super(GenericRelation, self).contribute_to_class(cls, name) # Save a reference to which model this class is on for future use self.model = cls # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseGenericRelatedObjectsDescriptor(self)) def contribute_to_related_class(self, cls, related): pass def set_attributes_from_rel(self): pass def get_internal_type(self): return "ManyToManyField" def db_type(self, connection): # Since we're simulating a ManyToManyField, in effect, best return the # same db_type as well. return None def extra_filters(self, pieces, pos, negate): """ Return an extra filter to the queryset so that the results are filtered on the appropriate content type. """ if negate: return [] ContentType = get_model("contenttypes", "contenttype") content_type = ContentType.objects.get_for_model(self.model) prefix = "__".join(pieces[:pos + 1]) return [("%s__%s" % (prefix, self.content_type_field_name), content_type)] def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): """ Return all objects related to ``objs`` via this ``GenericRelation``. """ return self.rel.to._base_manager.db_manager(using).filter(**{ "%s__pk" % self.content_type_field_name: ContentType.objects.db_manager(using).get_for_model(self.model).pk, "%s__in" % self.object_id_field_name: [obj.pk for obj in objs] }) class ReverseGenericRelatedObjectsDescriptor(object): """ This class provides the functionality that makes the related-object managers available as attributes on a model class, for fields that have multiple "remote" values and have a GenericRelation defined in their model (rather than having another model pointed *at* them). In the example "article.publications", the publications attribute is a ReverseGenericRelatedObjectsDescriptor instance. """ def __init__(self, field): self.field = field def __get__(self, instance, instance_type=None): if instance is None: return self # This import is done here to avoid circular import importing this module from django.contrib.contenttypes.models import ContentType # Dynamically create a class that subclasses the related model's # default manager. rel_model = self.field.rel.to superclass = rel_model._default_manager.__class__ RelatedManager = create_generic_related_manager(superclass) qn = connection.ops.quote_name manager = RelatedManager( model = rel_model, instance = instance, symmetrical = (self.field.rel.symmetrical and instance.__class__ == rel_model), join_table = qn(self.field.m2m_db_table()), source_col_name = qn(self.field.m2m_column_name()), target_col_name = qn(self.field.m2m_reverse_name()), content_type = ContentType.objects.db_manager(instance._state.db).get_for_model(instance), content_type_field_name = self.field.content_type_field_name, object_id_field_name = self.field.object_id_field_name ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") manager = self.__get__(instance) manager.clear() for obj in value: manager.add(obj) def create_generic_related_manager(superclass): """ Factory function for a manager that subclasses 'superclass' (which is a Manager) and adds behavior for generic related objects. """ class GenericRelatedObjectManager(superclass): def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None, join_table=None, source_col_name=None, target_col_name=None, content_type=None, content_type_field_name=None, object_id_field_name=None): super(GenericRelatedObjectManager, self).__init__() self.core_filters = core_filters or {} self.model = model self.content_type = content_type self.symmetrical = symmetrical self.instance = instance self.join_table = join_table self.join_table = model._meta.db_table self.source_col_name = source_col_name self.target_col_name = target_col_name self.content_type_field_name = content_type_field_name self.object_id_field_name = object_id_field_name self.pk_val = self.instance._get_pk_val() def get_query_set(self): db = self._db or router.db_for_read(self.model, instance=self.instance) query = { '%s__pk' % self.content_type_field_name : self.content_type.id, '%s__exact' % self.object_id_field_name : self.pk_val, } return superclass.get_query_set(self).using(db).filter(**query) def add(self, *objs): for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) setattr(obj, self.content_type_field_name, self.content_type) setattr(obj, self.object_id_field_name, self.pk_val) obj.save() add.alters_data = True def remove(self, *objs): db = router.db_for_write(self.model, instance=self.instance) for obj in objs: obj.delete(using=db) remove.alters_data = True def clear(self): db = router.db_for_write(self.model, instance=self.instance) for obj in self.all(): obj.delete(using=db) clear.alters_data = True def create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val db = router.db_for_write(self.model, instance=self.instance) return super(GenericRelatedObjectManager, self).using(db).create(**kwargs) create.alters_data = True return GenericRelatedObjectManager class GenericRel(ManyToManyRel): def __init__(self, to, related_name=None, limit_choices_to=None, symmetrical=True): self.to = to self.related_name = related_name self.limit_choices_to = limit_choices_to or {} self.symmetrical = symmetrical self.multiple = True self.through = None class BaseGenericInlineFormSet(BaseModelFormSet): """ A formset for generic inline objects to a parent. """ def __init__(self, data=None, files=None, instance=None, save_as_new=None, prefix=None, queryset=None): # Avoid a circular import. from django.contrib.contenttypes.models import ContentType opts = self.model._meta self.instance = instance self.rel_name = '-'.join(( opts.app_label, opts.object_name.lower(), self.ct_field.name, self.ct_fk_field.name, )) if self.instance is None or self.instance.pk is None: qs = self.model._default_manager.none() else: if queryset is None: queryset = self.model._default_manager qs = queryset.filter(**{ self.ct_field.name: ContentType.objects.get_for_model(self.instance), self.ct_fk_field.name: self.instance.pk, }) super(BaseGenericInlineFormSet, self).__init__( queryset=qs, data=data, files=files, prefix=prefix ) #@classmethod def get_default_prefix(cls): opts = cls.model._meta return '-'.join((opts.app_label, opts.object_name.lower(), cls.ct_field.name, cls.ct_fk_field.name, )) get_default_prefix = classmethod(get_default_prefix) def save_new(self, form, commit=True): # Avoid a circular import. from django.contrib.contenttypes.models import ContentType kwargs = { self.ct_field.get_attname(): ContentType.objects.get_for_model(self.instance).pk, self.ct_fk_field.get_attname(): self.instance.pk, } new_obj = self.model(**kwargs) return save_instance(form, new_obj, commit=commit) def generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=lambda f: f.formfield()): """ Returns an ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``object_id`` if they different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # Avoid a circular import. from django.contrib.contenttypes.models import ContentType # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate if exclude is not None: exclude = list(exclude) exclude.extend([ct_field.name, fk_field.name]) else: exclude = [ct_field.name, fk_field.name] FormSet = modelformset_factory(model, form=form, formfield_callback=formfield_callback, formset=formset, extra=extra, can_delete=can_delete, can_order=can_order, fields=fields, exclude=exclude, max_num=max_num) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field return FormSet class GenericInlineModelAdmin(InlineModelAdmin): ct_field = "content_type" ct_fk_field = "object_id" formset = BaseGenericInlineFormSet def get_formset(self, request, obj=None): if self.declared_fieldsets: fields = flatten_fieldsets(self.declared_fieldsets) else: fields = None if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) exclude = exclude or None defaults = { "ct_field": self.ct_field, "fk_field": self.ct_fk_field, "form": self.form, "formfield_callback": curry(self.formfield_for_dbfield, request=request), "formset": self.formset, "extra": self.extra, "can_delete": self.can_delete, "can_order": False, "fields": fields, "max_num": self.max_num, "exclude": exclude } return generic_inlineformset_factory(self.model, **defaults) class GenericStackedInline(GenericInlineModelAdmin): template = 'admin/edit_inline/stacked.html' class GenericTabularInline(GenericInlineModelAdmin): template = 'admin/edit_inline/tabular.html'
Python
from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site, get_current_site from django.core.exceptions import ObjectDoesNotExist def shortcut(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) if not content_type.model_class(): raise http.Http404("Content type %s object has no associated model" % content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, ValueError): raise http.Http404("Content type %s object %s doesn't exist" % (content_type_id, object_id)) try: absurl = obj.get_absolute_url() except AttributeError: raise http.Http404("%s objects don't have get_absolute_url() methods" % content_type.name) # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith('http://') or absurl.startswith('https://'): return http.HttpResponseRedirect(absurl) # Otherwise, we need to introspect the object's relationships for a # relation to the Site object object_domain = None if Site._meta.installed: opts = obj._meta # First, look for an many-to-many relationship to Site. for field in opts.many_to_many: if field.rel.to is Site: try: # Caveat: In the case of multiple related Sites, this just # selects the *first* one, which is arbitrary. object_domain = getattr(obj, field.name).all()[0].domain except IndexError: pass if object_domain is not None: break # Next, look for a many-to-one relationship to Site. if object_domain is None: for field in obj._meta.fields: if field.rel and field.rel.to is Site: try: object_domain = getattr(obj, field.name).domain except Site.DoesNotExist: pass if object_domain is not None: break # Fall back to the current site (if possible). if object_domain is None: try: object_domain = get_current_site(request).domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_url() returned. if object_domain is not None: protocol = request.is_secure() and 'https' or 'http' return http.HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl)) else: return http.HttpResponseRedirect(absurl)
Python
from django.contrib.contenttypes.models import ContentType from django.db.models import get_apps, get_models, signals from django.utils.encoding import smart_unicode def update_contenttypes(app, created_models, verbosity=2, **kwargs): """ Creates content types for models in the given app, removing any model entries that no longer have a matching model class. """ ContentType.objects.clear_cache() content_types = list(ContentType.objects.filter(app_label=app.__name__.split('.')[-2])) app_models = get_models(app) if not app_models: return for klass in app_models: opts = klass._meta try: ct = ContentType.objects.get(app_label=opts.app_label, model=opts.object_name.lower()) content_types.remove(ct) except ContentType.DoesNotExist: ct = ContentType(name=smart_unicode(opts.verbose_name_raw), app_label=opts.app_label, model=opts.object_name.lower()) ct.save() if verbosity >= 2: print "Adding content type '%s | %s'" % (ct.app_label, ct.model) # The presence of any remaining content types means the supplied app has an # undefined model. Confirm that the content type is stale before deletion. if content_types: if kwargs.get('interactive', False): content_type_display = '\n'.join([' %s | %s' % (ct.app_label, ct.model) for ct in content_types]) ok_to_delete = raw_input("""The following content types are stale and need to be deleted: %s Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? If you're unsure, answer 'no'. Type 'yes' to continue, or 'no' to cancel: """ % content_type_display) else: ok_to_delete = False if ok_to_delete == 'yes': for ct in content_types: if verbosity >= 2: print "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model) ct.delete() else: if verbosity >= 2: print "Stale content types remain." def update_all_contenttypes(verbosity=2, **kwargs): for app in get_apps(): update_contenttypes(app, None, verbosity, **kwargs) signals.post_syncdb.connect(update_contenttypes) if __name__ == "__main__": update_all_contenttypes()
Python
""" models.py (even empty) currently required by the runtests.py to enable unit tests """
Python
""" This is a URLconf to be loaded by tests.py. Add any URLs needed for tests only. """ from django.conf.urls.defaults import * from django.contrib.formtools.tests import * urlpatterns = patterns('', (r'^test1/', TestFormPreview(TestForm)), (r'^test2/', UserSecuredFormPreview(TestForm)), (r'^wizard/$', WizardClass([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm])), (r'^wizard2/$', UserSecuredWizardClass([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm])) )
Python
import os from django import forms, http from django.conf import settings from django.contrib.formtools import preview, wizard, utils from django.test import TestCase from django.utils import unittest success_string = "Done was called!" class TestFormPreview(preview.FormPreview): def get_context(self, request, form): context = super(TestFormPreview, self).get_context(request, form) context.update({'custom_context': True}) return context def get_initial(self, request): return {'field1': 'Works!'} def done(self, request, cleaned_data): return http.HttpResponse(success_string) class TestForm(forms.Form): field1 = forms.CharField() field1_ = forms.CharField() bool1 = forms.BooleanField(required=False) class UserSecuredFormPreview(TestFormPreview): """ FormPreview with a custum security_hash method """ def security_hash(self, request, form): return "123" class PreviewTests(TestCase): urls = 'django.contrib.formtools.tests.urls' def setUp(self): # Create a FormPreview instance to share between tests self.preview = preview.FormPreview(TestForm) input_template = '<input type="hidden" name="%s" value="%s" />' self.input = input_template % (self.preview.unused_name('stage'), "%d") self.test_data = {'field1':u'foo', 'field1_':u'asdf'} def test_unused_name(self): """ Verifies name mangling to get uniue field name. """ self.assertEqual(self.preview.unused_name('field1'), 'field1__') def test_form_get(self): """ Test contrib.formtools.preview form retrieval. Use the client library to see if we can sucessfully retrieve the form (mostly testing the setup ROOT_URLCONF process). Verify that an additional hidden input field is created to manage the stage. """ response = self.client.get('/test1/') stage = self.input % 1 self.assertContains(response, stage, 1) self.assertEqual(response.context['custom_context'], True) self.assertEqual(response.context['form'].initial, {'field1': 'Works!'}) def test_form_preview(self): """ Test contrib.formtools.preview form preview rendering. Use the client library to POST to the form to see if a preview is returned. If we do get a form back check that the hidden value is correctly managing the state of the form. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 1}) response = self.client.post('/test1/', self.test_data) # Check to confirm stage is set to 2 in output form. stage = self.input % 2 self.assertContains(response, stage, 1) def test_form_submit(self): """ Test contrib.formtools.preview form submittal. Use the client library to POST to the form with stage set to 3 to see if our forms done() method is called. Check first without the security hash, verify failure, retry with security hash and verify sucess. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage':2}) response = self.client.post('/test1/', self.test_data) self.assertNotEqual(response.content, success_string) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/test1/', self.test_data) self.assertEqual(response.content, success_string) def test_bool_submit(self): """ Test contrib.formtools.preview form submittal when form contains: BooleanField(required=False) Ticket: #6209 - When an unchecked BooleanField is previewed, the preview form's hash would be computed with no value for ``bool1``. However, when the preview form is rendered, the unchecked hidden BooleanField would be rendered with the string value 'False'. So when the preview form is resubmitted, the hash would be computed with the value 'False' for ``bool1``. We need to make sure the hashes are the same in both cases. """ self.test_data.update({'stage':2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash':hash, 'bool1':u'False'}) response = self.client.post('/test1/', self.test_data) self.assertEqual(response.content, success_string) def test_form_submit_django12_hash(self): """ Test contrib.formtools.preview form submittal, using the hash function used in Django 1.2 """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage':2}) response = self.client.post('/test1/', self.test_data) self.assertNotEqual(response.content, success_string) hash = utils.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/test1/', self.test_data) self.assertEqual(response.content, success_string) def test_form_submit_django12_hash_custom_hash(self): """ Test contrib.formtools.preview form submittal, using the hash function used in Django 1.2 and a custom security_hash method. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage':2}) response = self.client.post('/test2/', self.test_data) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, success_string) hash = utils.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/test2/', self.test_data) self.assertNotEqual(response.content, success_string) class SecurityHashTests(unittest.TestCase): def test_textfield_hash(self): """ Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas). """ f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2) def test_empty_permitted(self): """ Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed. """ f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.security_hash(None, f1) hash2 = utils.security_hash(None, f2) self.assertEqual(hash1, hash2) class FormHmacTests(unittest.TestCase): """ Same as SecurityHashTests, but with form_hmac """ def test_textfield_hash(self): """ Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas). """ f1 = HashTestForm({'name': 'joe', 'bio': 'Nothing notable.'}) f2 = HashTestForm({'name': ' joe', 'bio': 'Nothing notable. '}) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2) def test_empty_permitted(self): """ Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed. """ f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.form_hmac(f1) hash2 = utils.form_hmac(f2) self.assertEqual(hash1, hash2) class HashTestForm(forms.Form): name = forms.CharField() bio = forms.CharField() class HashTestBlankForm(forms.Form): name = forms.CharField(required=False) bio = forms.CharField(required=False) # # FormWizard tests # class WizardPageOneForm(forms.Form): field = forms.CharField() class WizardPageTwoForm(forms.Form): field = forms.CharField() class WizardPageTwoAlternativeForm(forms.Form): field = forms.CharField() class WizardPageThreeForm(forms.Form): field = forms.CharField() class WizardClass(wizard.FormWizard): def get_template(self, step): return 'formwizard/wizard.html' def done(self, request, cleaned_data): return http.HttpResponse(success_string) class UserSecuredWizardClass(WizardClass): """ Wizard with a custum security_hash method """ def security_hash(self, request, form): return "123" class DummyRequest(http.HttpRequest): def __init__(self, POST=None): super(DummyRequest, self).__init__() self.method = POST and "POST" or "GET" if POST is not None: self.POST.update(POST) self._dont_enforce_csrf_checks = True class WizardTests(TestCase): urls = 'django.contrib.formtools.tests.urls' def setUp(self): self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS settings.TEMPLATE_DIRS = ( os.path.join( os.path.dirname(__file__), 'templates' ), ) # Use a known SECRET_KEY to make security_hash tests deterministic self.old_SECRET_KEY = settings.SECRET_KEY settings.SECRET_KEY = "123" def tearDown(self): settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS settings.SECRET_KEY = self.old_SECRET_KEY def test_step_starts_at_zero(self): """ step should be zero for the first form """ response = self.client.get('/wizard/') self.assertEqual(0, response.context['step0']) def test_step_increments(self): """ step should be incremented when we go to the next page """ response = self.client.post('/wizard/', {"0-field":"test", "wizard_step":"0"}) self.assertEqual(1, response.context['step0']) def test_bad_hash(self): """ Form should not advance if the hash is missing or bad """ response = self.client.post('/wizard/', {"0-field":"test", "1-field":"test2", "wizard_step": "1"}) self.assertEqual(0, response.context['step0']) def test_good_hash_django12(self): """ Form should advance if the hash is present and good, as calculated using django 1.2 method. """ # We are hard-coding a hash value here, but that is OK, since we want to # ensure that we don't accidentally change the algorithm. data = {"0-field": "test", "1-field": "test2", "hash_0": "2fdbefd4c0cad51509478fbacddf8b13", "wizard_step": "1"} response = self.client.post('/wizard/', data) self.assertEqual(2, response.context['step0']) def test_good_hash_django12_subclass(self): """ The Django 1.2 method of calulating hashes should *not* be used as a fallback if the FormWizard subclass has provided their own method of calculating a hash. """ # We are hard-coding a hash value here, but that is OK, since we want to # ensure that we don't accidentally change the algorithm. data = {"0-field": "test", "1-field": "test2", "hash_0": "2fdbefd4c0cad51509478fbacddf8b13", "wizard_step": "1"} response = self.client.post('/wizard2/', data) self.assertEqual(0, response.context['step0']) def test_good_hash_current(self): """ Form should advance if the hash is present and good, as calculated using current method. """ data = {"0-field": "test", "1-field": "test2", "hash_0": "7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c", "wizard_step": "1"} response = self.client.post('/wizard/', data) self.assertEqual(2, response.context['step0']) def test_14498(self): """ Regression test for ticket #14498. All previous steps' forms should be validated. """ reached = [False] that = self class WizardWithProcessStep(WizardClass): def process_step(self, request, form, step): that.assertTrue(hasattr(form, 'cleaned_data')) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": "7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c", "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) def test_14576(self): """ Regression test for ticket #14576. The form of the last step is not passed to the done method. """ reached = [False] that = self class Wizard(WizardClass): def done(self, request, form_list): reached[0] = True that.assertTrue(len(form_list) == 2) wizard = Wizard([WizardPageOneForm, WizardPageTwoForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": "7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c", "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0]) def test_15075(self): """ Regression test for ticket #15075. Allow modifying wizard's form_list in process_step. """ reached = [False] that = self class WizardWithProcessStep(WizardClass): def process_step(self, request, form, step): if step == 0: self.form_list[1] = WizardPageTwoAlternativeForm if step == 1: that.assertTrue(isinstance(form, WizardPageTwoAlternativeForm)) reached[0] = True wizard = WizardWithProcessStep([WizardPageOneForm, WizardPageTwoForm, WizardPageThreeForm]) data = {"0-field": "test", "1-field": "test2", "hash_0": "7e9cea465f6a10a6fb47fcea65cb9a76350c9a5c", "wizard_step": "1"} wizard(DummyRequest(POST=data)) self.assertTrue(reached[0])
Python
""" Formtools Preview application. """ import cPickle as pickle from django.conf import settings from django.http import Http404 from django.shortcuts import render_to_response from django.template.context import RequestContext from django.utils.hashcompat import md5_constructor from django.utils.crypto import constant_time_compare from django.contrib.formtools.utils import security_hash AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter. class FormPreview(object): preview_template = 'formtools/preview.html' form_template = 'formtools/form.html' # METHODS SUBCLASSES SHOULDN'T OVERRIDE ################################### def __init__(self, form): # form should be a Form class, not an instance. self.form, self.state = form, {} def __call__(self, request, *args, **kwargs): stage = {'1': 'preview', '2': 'post'}.get(request.POST.get(self.unused_name('stage')), 'preview') self.parse_params(*args, **kwargs) try: method = getattr(self, stage + '_' + request.method.lower()) except AttributeError: raise Http404 return method(request) def unused_name(self, name): """ Given a first-choice name, adds an underscore to the name until it reaches a name that isn't claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form. """ while 1: try: f = self.form.base_fields[name] except KeyError: break # This field name isn't being used by the form. name += '_' return name def preview_get(self, request): "Displays the form" f = self.form(auto_id=self.get_auto_id(), initial=self.get_initial(request)) return render_to_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request)) def preview_post(self, request): "Validates the POST data. If valid, displays the preview page. Else, redisplays form." f = self.form(request.POST, auto_id=self.get_auto_id()) context = self.get_context(request, f) if f.is_valid(): self.process_preview(request, f, context) context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(request, f) return render_to_response(self.preview_template, context, context_instance=RequestContext(request)) else: return render_to_response(self.form_template, context, context_instance=RequestContext(request)) def _check_security_hash(self, token, request, form): expected = self.security_hash(request, form) if constant_time_compare(token, expected): return True else: # Fall back to Django 1.2 method, for compatibility with forms that # are in the middle of being used when the upgrade occurs. However, # we don't want to do this fallback if a subclass has provided their # own security_hash method - because they might have implemented a # more secure method, and this would punch a hole in that. # PendingDeprecationWarning <- left here to remind us that this # compatibility fallback should be removed in Django 1.5 FormPreview_expected = FormPreview.security_hash(self, request, form) if expected == FormPreview_expected: # They didn't override security_hash, do the fallback: old_expected = security_hash(request, form) return constant_time_compare(token, old_expected) else: return False def post_post(self, request): "Validates the POST data. If valid, calls done(). Else, redisplays form." f = self.form(request.POST, auto_id=self.get_auto_id()) if f.is_valid(): if not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''), request, f): return self.failed_hash(request) # Security hash failed. return self.done(request, f.cleaned_data) else: return render_to_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request)) # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ######################## def get_auto_id(self): """ Hook to override the ``auto_id`` kwarg for the form. Needed when rendering two form previews in the same template. """ return AUTO_ID def get_initial(self, request): """ Takes a request argument and returns a dictionary to pass to the form's ``initial`` kwarg when the form is being created from an HTTP get. """ return {} def get_context(self, request, form): "Context for template rendering." return {'form': form, 'stage_field': self.unused_name('stage'), 'state': self.state} def parse_params(self, *args, **kwargs): """ Given captured args and kwargs from the URLconf, saves something in self.state and/or raises Http404 if necessary. For example, this URLconf captures a user_id variable: (r'^contact/(?P<user_id>\d{1,6})/$', MyFormPreview(MyForm)), In this case, the kwargs variable in parse_params would be {'user_id': 32} for a request to '/contact/32/'. You can use that user_id to make sure it's a valid user and/or save it for later, for use in done(). """ pass def process_preview(self, request, form, context): """ Given a validated form, performs any extra processing before displaying the preview page, and saves any extra data in context. """ pass def security_hash(self, request, form): """ Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address. """ return security_hash(request, form) def failed_hash(self, request): "Returns an HttpResponse in the case of an invalid security hash." return self.preview_post(request) # METHODS SUBCLASSES MUST OVERRIDE ######################################## def done(self, request, cleaned_data): """ Does something with the cleaned_data and returns an HttpResponseRedirect. """ raise NotImplementedError('You must define a done() method on your %s subclass.' % self.__class__.__name__)
Python
try: import cPickle as pickle except ImportError: import pickle from django.conf import settings from django.forms import BooleanField from django.utils.crypto import salted_hmac from django.utils.hashcompat import md5_constructor def security_hash(request, form, *args): """ Calculates a security hash for the given Form instance. This creates a list of the form field names/values in a deterministic order, pickles the result with the SECRET_KEY setting, then takes an md5 hash of that. """ import warnings warnings.warn("security_hash is deprecated; use form_hmac instead", PendingDeprecationWarning) data = [] for bf in form: # Get the value from the form data. If the form allows empty or hasn't # changed then don't call clean() to avoid trigger validation errors. if form.empty_permitted and not form.has_changed(): value = bf.data or '' else: value = bf.field.clean(bf.data) or '' if isinstance(value, basestring): value = value.strip() data.append((bf.name, value)) data.extend(args) data.append(settings.SECRET_KEY) # Use HIGHEST_PROTOCOL because it's the most efficient. It requires # Python 2.3, but Django requires 2.4 anyway, so that's OK. pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL) return md5_constructor(pickled).hexdigest() def form_hmac(form): """ Calculates a security hash for the given Form instance. """ data = [] for bf in form: # Get the value from the form data. If the form allows empty or hasn't # changed then don't call clean() to avoid trigger validation errors. if form.empty_permitted and not form.has_changed(): value = bf.data or '' else: value = bf.field.clean(bf.data) or '' if isinstance(value, basestring): value = value.strip() data.append((bf.name, value)) pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL) key_salt = 'django.contrib.formtools' return salted_hmac(key_salt, pickled).hexdigest()
Python
""" FormWizard class -- implements a multi-page form, validating between each step and storing the form's state as HTML hidden fields so that no state is stored on the server side. """ import cPickle as pickle from django import forms from django.conf import settings from django.contrib.formtools.utils import security_hash, form_hmac from django.http import Http404 from django.shortcuts import render_to_response from django.template.context import RequestContext from django.utils.crypto import constant_time_compare from django.utils.hashcompat import md5_constructor from django.utils.translation import ugettext_lazy as _ from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect class FormWizard(object): # The HTML (and POST data) field name for the "step" variable. step_field_name="wizard_step" # METHODS SUBCLASSES SHOULDN'T OVERRIDE ################################### def __init__(self, form_list, initial=None): """ Start a new wizard with a list of forms. form_list should be a list of Form classes (not instances). """ self.form_list = form_list[:] self.initial = initial or {} # Dictionary of extra template context variables. self.extra_context = {} # A zero-based counter keeping track of which step we're in. self.step = 0 def __repr__(self): return "step: %d\nform_list: %s\ninitial_data: %s" % (self.step, self.form_list, self.initial) def get_form(self, step, data=None): "Helper method that returns the Form instance for the given step." return self.form_list[step](data, prefix=self.prefix_for_step(step), initial=self.initial.get(step, None)) def num_steps(self): "Helper method that returns the number of steps." # You might think we should just set "self.num_steps = len(form_list)" # in __init__(), but this calculation needs to be dynamic, because some # hook methods might alter self.form_list. return len(self.form_list) def _check_security_hash(self, token, request, form): expected = self.security_hash(request, form) if constant_time_compare(token, expected): return True else: # Fall back to Django 1.2 method, for compatibility with forms that # are in the middle of being used when the upgrade occurs. However, # we don't want to do this fallback if a subclass has provided their # own security_hash method - because they might have implemented a # more secure method, and this would punch a hole in that. # PendingDeprecationWarning <- left here to remind us that this # compatibility fallback should be removed in Django 1.5 FormWizard_expected = FormWizard.security_hash(self, request, form) if expected == FormWizard_expected: # They didn't override security_hash, do the fallback: old_expected = security_hash(request, form) return constant_time_compare(token, old_expected) else: return False @method_decorator(csrf_protect) def __call__(self, request, *args, **kwargs): """ Main method that does all the hard work, conforming to the Django view interface. """ if 'extra_context' in kwargs: self.extra_context.update(kwargs['extra_context']) current_step = self.determine_step(request, *args, **kwargs) self.parse_params(request, *args, **kwargs) # Sanity check. if current_step >= self.num_steps(): raise Http404('Step %s does not exist' % current_step) # Validate and process all the previous forms before instantiating the # current step's form in case self.process_step makes changes to # self.form_list. # If any of them fails validation, that must mean the validator relied # on some other input, such as an external Web site. # It is also possible that alidation might fail under certain attack # situations: an attacker might be able to bypass previous stages, and # generate correct security hashes for all the skipped stages by virtue # of: # 1) having filled out an identical form which doesn't have the # validation (and does something different at the end), # 2) or having filled out a previous version of the same form which # had some validation missing, # 3) or previously having filled out the form when they had more # privileges than they do now. # # Since the hashes only take into account values, and not other other # validation the form might do, we must re-do validation now for # security reasons. previous_form_list = [] for i in range(current_step): f = self.get_form(i, request.POST) if not self._check_security_hash(request.POST.get("hash_%d" % i, ''), request, f): return self.render_hash_failure(request, i) if not f.is_valid(): return self.render_revalidation_failure(request, i, f) else: self.process_step(request, f, i) previous_form_list.append(f) # Process the current step. If it's valid, go to the next step or call # done(), depending on whether any steps remain. if request.method == 'POST': form = self.get_form(current_step, request.POST) else: form = self.get_form(current_step) if form.is_valid(): self.process_step(request, form, current_step) next_step = current_step + 1 if next_step == self.num_steps(): return self.done(request, previous_form_list + [form]) else: form = self.get_form(next_step) self.step = current_step = next_step return self.render(form, request, current_step) def render(self, form, request, step, context=None): "Renders the given Form object, returning an HttpResponse." old_data = request.POST prev_fields = [] if old_data: hidden = forms.HiddenInput() # Collect all data from previous steps and render it as HTML hidden fields. for i in range(step): old_form = self.get_form(i, old_data) hash_name = 'hash_%s' % i prev_fields.extend([bf.as_hidden() for bf in old_form]) prev_fields.append(hidden.render(hash_name, old_data.get(hash_name, self.security_hash(request, old_form)))) return self.render_template(request, form, ''.join(prev_fields), step, context) # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ######################## def prefix_for_step(self, step): "Given the step, returns a Form prefix to use." return str(step) def render_hash_failure(self, request, step): """ Hook for rendering a template if a hash check failed. step is the step that failed. Any previous step is guaranteed to be valid. This default implementation simply renders the form for the given step, but subclasses may want to display an error message, etc. """ return self.render(self.get_form(step), request, step, context={'wizard_error': _('We apologize, but your form has expired. Please continue filling out the form from this page.')}) def render_revalidation_failure(self, request, step, form): """ Hook for rendering a template if final revalidation failed. It is highly unlikely that this point would ever be reached, but See the comment in __call__() for an explanation. """ return self.render(form, request, step) def security_hash(self, request, form): """ Calculates the security hash for the given HttpRequest and Form instances. Subclasses may want to take into account request-specific information, such as the IP address. """ return form_hmac(form) def determine_step(self, request, *args, **kwargs): """ Given the request object and whatever *args and **kwargs were passed to __call__(), returns the current step (which is zero-based). Note that the result should not be trusted. It may even be a completely invalid number. It's not the job of this method to validate it. """ if not request.POST: return 0 try: step = int(request.POST.get(self.step_field_name, 0)) except ValueError: return 0 return step def parse_params(self, request, *args, **kwargs): """ Hook for setting some state, given the request object and whatever *args and **kwargs were passed to __call__(), sets some state. This is called at the beginning of __call__(). """ pass def get_template(self, step): """ Hook for specifying the name of the template to use for a given step. Note that this can return a tuple of template names if you'd like to use the template system's select_template() hook. """ return 'forms/wizard.html' def render_template(self, request, form, previous_fields, step, context=None): """ Renders the template for the given step, returning an HttpResponse object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use get_template() instead. The template will be rendered with the following context: step_field -- The name of the hidden field containing the step. step0 -- The current step (zero-based). step -- The current step (one-based). step_count -- The total number of steps. form -- The Form instance for the current step (either empty or with errors). previous_fields -- A string representing every previous data field, plus hashes for completed forms, all in the form of hidden fields. Note that you'll need to run this through the "safe" template filter, to prevent auto-escaping, because it's raw HTML. """ context = context or {} context.update(self.extra_context) return render_to_response(self.get_template(step), dict(context, step_field=self.step_field_name, step0=step, step=step + 1, step_count=self.num_steps(), form=form, previous_fields=previous_fields ), context_instance=RequestContext(request)) def process_step(self, request, form, step): """ Hook for modifying the FormWizard's internal state, given a fully validated Form object. The Form is guaranteed to have clean, valid data. This method should *not* modify any of that data. Rather, it might want to set self.extra_context or dynamically alter self.form_list, based on previously submitted forms. Note that this method is called every time a page is rendered for *all* submitted steps. """ pass # METHODS SUBCLASSES MUST OVERRIDE ######################################## def done(self, request, form_list): """ Hook for doing something with the validated data. This is responsible for the final processing. form_list is a list of Form instances, each containing clean, valid data. """ raise NotImplementedError("Your %s class has not defined a done() method, which is required." % self.__class__.__name__)
Python
from django.core.exceptions import MiddlewareNotUsed from django.utils.http import http_date, parse_http_date_safe class ConditionalGetMiddleware(object): """ Handles conditional GET operations. If the response has a ETag or Last-Modified header, and the request has If-None-Match or If-Modified-Since, the response is replaced by an HttpNotModified. Also sets the Date and Content-Length response-headers. """ def process_response(self, request, response): response['Date'] = http_date() if not response.has_header('Content-Length'): response['Content-Length'] = str(len(response.content)) if response.has_header('ETag'): if_none_match = request.META.get('HTTP_IF_NONE_MATCH') if if_none_match == response['ETag']: # Setting the status is enough here. The response handling path # automatically removes content for this status code (in # http.conditional_content_removal()). response.status_code = 304 if response.has_header('Last-Modified'): if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if if_modified_since is not None: if_modified_since = parse_http_date_safe(if_modified_since) if if_modified_since is not None: last_modified = parse_http_date_safe(response['Last-Modified']) if last_modified is not None and last_modified <= if_modified_since: # Setting the status code is enough here (same reasons as # above). response.status_code = 304 return response
Python
"this is the locale selecting middleware that will look at accept headers" from django.utils.cache import patch_vary_headers from django.utils import translation class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course). """ def process_request(self, request): language = translation.get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = translation.get_language() translation.deactivate() return response
Python
import re from django.utils.text import compress_string from django.utils.cache import patch_vary_headers re_accepts_gzip = re.compile(r'\bgzip\b') class GZipMiddleware(object): """ This middleware compresses content if the browser allows gzip compression. It sets the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header. """ def process_response(self, request, response): # It's not worth compressing non-OK or really short responses. if response.status_code != 200 or len(response.content) < 200: return response patch_vary_headers(response, ('Accept-Encoding',)) # Avoid gzipping if we've already got a content-encoding. if response.has_header('Content-Encoding'): return response # MSIE have issues with gzipped respones of various content types. if "msie" in request.META.get('HTTP_USER_AGENT', '').lower(): ctype = response.get('Content-Type', '').lower() if not ctype.startswith("text/") or "javascript" in ctype: return response ae = request.META.get('HTTP_ACCEPT_ENCODING', '') if not re_accepts_gzip.search(ae): return response response.content = compress_string(response.content) response['Content-Encoding'] = 'gzip' response['Content-Length'] = str(len(response.content)) return response
Python
from django.conf import settings from django import http class XViewMiddleware(object): """ Adds an X-View header to internal HEAD requests -- used by the documentation system. """ def process_view(self, request, view_func, view_args, view_kwargs): """ If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, quickly return with an x-header indicating the view function. This is used by the documentation module to lookup the view function for an arbitrary page. """ if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or (request.user.is_active and request.user.is_staff)): response = http.HttpResponse() response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__) return response
Python
""" Cross Site Request Forgery Middleware. This module provides a middleware that implements protection against request forgeries from other sites. """ import itertools import re import random from django.conf import settings from django.core.urlresolvers import get_callable from django.utils.cache import patch_vary_headers from django.utils.hashcompat import md5_constructor from django.utils.http import same_origin from django.utils.log import getLogger from django.utils.safestring import mark_safe from django.utils.crypto import constant_time_compare _POST_FORM_RE = \ re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) _HTML_TYPES = ('text/html', 'application/xhtml+xml') logger = getLogger('django.request') # Use the system (hardware-based) random number generator if it exists. if hasattr(random, 'SystemRandom'): randrange = random.SystemRandom().randrange else: randrange = random.randrange _MAX_CSRF_KEY = 18446744073709551616L # 2 << 63 REASON_NO_REFERER = "Referer checking failed - no Referer." REASON_BAD_REFERER = "Referer checking failed - %s does not match %s." REASON_NO_COOKIE = "No CSRF or session cookie." REASON_NO_CSRF_COOKIE = "CSRF cookie not set." REASON_BAD_TOKEN = "CSRF token missing or incorrect." def _get_failure_view(): """ Returns the view to be used for CSRF rejections """ return get_callable(settings.CSRF_FAILURE_VIEW) def _get_new_csrf_key(): return md5_constructor("%s%s" % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest() def _make_legacy_session_token(session_id): return md5_constructor(settings.SECRET_KEY + session_id).hexdigest() def get_token(request): """ Returns the the CSRF token required for a POST form. The token is an alphanumeric value. A side effect of calling this function is to make the the csrf_protect decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie' header to the outgoing response. For this reason, you may need to use this function lazily, as is done by the csrf context processor. """ request.META["CSRF_COOKIE_USED"] = True return request.META.get("CSRF_COOKIE", None) def _sanitize_token(token): # Allow only alphanum, and ensure we return a 'str' for the sake of the post # processing middleware. token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore'))) if token == "": # In case the cookie has been truncated to nothing at some point. return _get_new_csrf_key() else: return token class CsrfViewMiddleware(object): """ Middleware that requires a present and correct csrfmiddlewaretoken for POST requests that have a CSRF cookie, and sets an outgoing CSRF cookie. This middleware should be used in conjunction with the csrf_token template tag. """ # The _accept and _reject methods currently only exist for the sake of the # requires_csrf_token decorator. def _accept(self, request): # Avoid checking the request twice by adding a custom attribute to # request. This will be relevant when both decorator and middleware # are used. request.csrf_processing_done = True return None def _reject(self, request, reason): return _get_failure_view()(request, reason=reason) def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(request, 'csrf_processing_done', False): return None # If the user doesn't have a CSRF cookie, generate one and store it in the # request, so it's available to the view. We'll store it in a cookie when # we reach the response. try: # In case of cookies from untrusted sources, we strip anything # dangerous at this point, so that the cookie + token will have the # same, sanitized value. request.META["CSRF_COOKIE"] = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME]) cookie_is_new = False except KeyError: # No cookie, so create one. This will be sent with the next # response. request.META["CSRF_COOKIE"] = _get_new_csrf_key() # Set a flag to allow us to fall back and allow the session id in # place of a CSRF cookie for this request only. cookie_is_new = True # Wait until request.META["CSRF_COOKIE"] has been manipulated before # bailing out, so that get_token still works if getattr(callback, 'csrf_exempt', False): return None if request.method == 'POST': if getattr(request, '_dont_enforce_csrf_checks', False): # Mechanism to turn off CSRF checks for test suite. It comes after # the creation of CSRF cookies, so that everything else continues to # work exactly the same (e.g. cookies are sent etc), but before the # any branches that call reject() return self._accept(request) if request.is_secure(): # Suppose user visits http://example.com/ # An active network attacker,(man-in-the-middle, MITM) sends a # POST form which targets https://example.com/detonate-bomb/ and # submits it via javascript. # # The attacker will need to provide a CSRF cookie and token, but # that is no problem for a MITM and the session independent # nonce we are using. So the MITM can circumvent the CSRF # protection. This is true for any HTTP connection, but anyone # using HTTPS expects better! For this reason, for # https://example.com/ we need additional protection that treats # http://example.com/ as completely untrusted. Under HTTPS, # Barth et al. found that the Referer header is missing for # same-domain requests in only about 0.2% of cases or less, so # we can use strict Referer checking. referer = request.META.get('HTTP_REFERER') if referer is None: logger.warning('Forbidden (%s): %s' % (REASON_NO_REFERER, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_NO_REFERER) # Note that request.get_host() includes the port good_referer = 'https://%s/' % request.get_host() if not same_origin(referer, good_referer): reason = REASON_BAD_REFERER % (referer, good_referer) logger.warning('Forbidden (%s): %s' % (reason, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, reason) # If the user didn't already have a CSRF cookie, then fall back to # the Django 1.1 method (hash of session ID), so a request is not # rejected if the form was sent to the user before upgrading to the # Django 1.2 method (session independent nonce) if cookie_is_new: try: session_id = request.COOKIES[settings.SESSION_COOKIE_NAME] csrf_token = _make_legacy_session_token(session_id) except KeyError: # No CSRF cookie and no session cookie. For POST requests, # we insist on a CSRF cookie, and in this way we can avoid # all CSRF attacks, including login CSRF. logger.warning('Forbidden (%s): %s' % (REASON_NO_COOKIE, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_NO_COOKIE) else: csrf_token = request.META["CSRF_COOKIE"] # check incoming token request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') if request_csrf_token == "": # Fall back to X-CSRFToken, to make things easier for AJAX request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') if not constant_time_compare(request_csrf_token, csrf_token): if cookie_is_new: # probably a problem setting the CSRF cookie logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_NO_CSRF_COOKIE) else: logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_BAD_TOKEN) return self._accept(request) def process_response(self, request, response): if getattr(response, 'csrf_processing_done', False): return response # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was # never called, probaby because a request middleware returned a response # (for example, contrib.auth redirecting to a login page). if request.META.get("CSRF_COOKIE") is None: return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew the expiry timer. response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52, domain=settings.CSRF_COOKIE_DOMAIN) # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) response.csrf_processing_done = True return response class CsrfResponseMiddleware(object): """ DEPRECATED Middleware that post-processes a response to add a csrfmiddlewaretoken. This exists for backwards compatibility and as an interim measure until applications are converted to using use the csrf_token template tag instead. It will be removed in Django 1.4. """ def __init__(self): import warnings warnings.warn( "CsrfResponseMiddleware and CsrfMiddleware are deprecated; use CsrfViewMiddleware and the template tag instead (see CSRF documentation).", DeprecationWarning ) def process_response(self, request, response): if getattr(response, 'csrf_exempt', False): return response if response['Content-Type'].split(';')[0] in _HTML_TYPES: csrf_token = get_token(request) # If csrf_token is None, we have no token for this request, which probably # means that this is a response from a request middleware. if csrf_token is None: return response # ensure we don't add the 'id' attribute twice (HTML validity) idattributes = itertools.chain(("id='csrfmiddlewaretoken'",), itertools.repeat('')) def add_csrf_field(match): """Returns the matched <form> tag plus the added <input> element""" return mark_safe(match.group() + "<div style='display:none;'>" + \ "<input type='hidden' " + idattributes.next() + \ " name='csrfmiddlewaretoken' value='" + csrf_token + \ "' /></div>") # Modify any POST forms response.content, n = _POST_FORM_RE.subn(add_csrf_field, response.content) if n > 0: # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) # Since the content has been modified, any Etag will now be # incorrect. We could recalculate, but only if we assume that # the Etag was set by CommonMiddleware. The safest thing is just # to delete. See bug #9163 del response['ETag'] return response class CsrfMiddleware(object): """ Django middleware that adds protection against Cross Site Request Forgeries by adding hidden form fields to POST forms and checking requests for the correct value. CsrfMiddleware uses two middleware, CsrfViewMiddleware and CsrfResponseMiddleware, which can be used independently. It is recommended to use only CsrfViewMiddleware and use the csrf_token template tag in templates for inserting the token. """ # We can't just inherit from CsrfViewMiddleware and CsrfResponseMiddleware # because both have process_response methods. def __init__(self): self.response_middleware = CsrfResponseMiddleware() self.view_middleware = CsrfViewMiddleware() def process_response(self, request, resp): # We must do the response post-processing first, because that calls # get_token(), which triggers a flag saying that the CSRF cookie needs # to be sent (done in CsrfViewMiddleware.process_response) resp2 = self.response_middleware.process_response(request, resp) return self.view_middleware.process_response(request, resp2) def process_view(self, request, callback, callback_args, callback_kwargs): return self.view_middleware.process_view(request, callback, callback_args, callback_kwargs)
Python
import re from django.conf import settings from django import http from django.core.mail import mail_managers from django.utils.http import urlquote from django.core import urlresolvers from django.utils.hashcompat import md5_constructor from django.utils.log import getLogger logger = getLogger('django.request') class CommonMiddleware(object): """ "Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, a new URL is formed by appending a slash at the end. If this new URL is found in urlpatterns, then an HTTP-redirect is returned to this new URL; otherwise the initial URL is processed as usual. - ETags: If the USE_ETAGS setting is set, ETags will be calculated from the entire page content and Not Modified responses will be returned appropriately. """ def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents if 'HTTP_USER_AGENT' in request.META: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): logger.warning('Forbidden (User agent): %s' % request.path, extra={ 'status_code': 403, 'request': request } ) return http.HttpResponseForbidden('<h1>Forbidden</h1>') # Check for a redirect based on settings.APPEND_SLASH # and settings.PREPEND_WWW host = request.get_host() old_url = [host, request.path] new_url = old_url[:] if (settings.PREPEND_WWW and old_url[0] and not old_url[0].startswith('www.')): new_url[0] = 'www.' + old_url[0] # Append a slash if APPEND_SLASH is set and the URL doesn't have a # trailing slash and there is no pattern for the current path if settings.APPEND_SLASH and (not old_url[1].endswith('/')): urlconf = getattr(request, 'urlconf', None) if (not _is_valid_path(request.path_info, urlconf) and _is_valid_path("%s/" % request.path_info, urlconf)): new_url[1] = new_url[1] + '/' if settings.DEBUG and request.method == 'POST': raise RuntimeError, ("" "You called this URL via POST, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining POST data. " "Change your form to point to %s%s (note the trailing " "slash), or set APPEND_SLASH=False in your Django " "settings.") % (new_url[0], new_url[1]) if new_url == old_url: # No redirects required. return if new_url[0]: newurl = "%s://%s%s" % ( request.is_secure() and 'https' or 'http', new_url[0], urlquote(new_url[1])) else: newurl = urlquote(new_url[1]) if request.GET: newurl += '?' + request.META['QUERY_STRING'] return http.HttpResponsePermanentRedirect(newurl) def process_response(self, request, response): "Send broken link emails and calculate the Etag, if needed." if response.status_code == 404: if settings.SEND_BROKEN_LINK_EMAILS and not settings.DEBUG: # If the referrer was from an internal link or a non-search-engine site, # send a note to the managers. domain = request.get_host() referer = request.META.get('HTTP_REFERER', None) is_internal = _is_internal_request(domain, referer) path = request.get_full_path() if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') ip = request.META.get('REMOTE_ADDR', '<none>') mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain), "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \ % (referer, request.get_full_path(), ua, ip), fail_silently=True) return response # Use ETags, if requested. if settings.USE_ETAGS: if response.has_header('ETag'): etag = response['ETag'] else: etag = '"%s"' % md5_constructor(response.content).hexdigest() if response.status_code >= 200 and response.status_code < 300 and request.META.get('HTTP_IF_NONE_MATCH') == etag: cookies = response.cookies response = http.HttpResponseNotModified() response.cookies = cookies else: response['ETag'] = etag return response def _is_ignorable_404(uri): """ Returns True if a 404 at the given URL *shouldn't* notify the site managers. """ for start in settings.IGNORABLE_404_STARTS: if uri.startswith(start): return True for end in settings.IGNORABLE_404_ENDS: if uri.endswith(end): return True return False def _is_internal_request(domain, referer): """ Returns true if the referring URL is the same domain as the current request. """ # Different subdomains are treated as different domains. return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer) def _is_valid_path(path, urlconf=None): """ Returns True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: urlresolvers.resolve(path, urlconf) return True except urlresolvers.Resolver404: return False
Python
from django.db import transaction class TransactionMiddleware(object): """ Transaction middleware. If this is enabled, each view function will be run with commit_on_response activated - that way a save() doesn't do a direct commit, the commit is done when a successful response is created. If an exception happens, the database is rolled back. """ def process_request(self, request): """Enters transaction management""" transaction.enter_transaction_management() transaction.managed(True) def process_exception(self, request, exception): """Rolls back the database and leaves transaction management""" if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() def process_response(self, request, response): """Commits and leaves transaction management.""" if transaction.is_managed(): if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() return response
Python
""" Cache middleware. If enabled, each Django-powered page will be cached based on URL. The canonical way to enable cache middleware is to set ``UpdateCacheMiddleware`` as your first piece of middleware, and ``FetchFromCacheMiddleware`` as the last:: MIDDLEWARE_CLASSES = [ 'django.middleware.cache.UpdateCacheMiddleware', ... 'django.middleware.cache.FetchFromCacheMiddleware' ] This is counter-intuitive, but correct: ``UpdateCacheMiddleware`` needs to run last during the response phase, which processes middleware bottom-up; ``FetchFromCacheMiddleware`` needs to run last during the request phase, which processes middleware top-down. The single-class ``CacheMiddleware`` can be used for some simple sites. However, if any other piece of middleware needs to affect the cache key, you'll need to use the two-part ``UpdateCacheMiddleware`` and ``FetchFromCacheMiddleware``. This'll most often happen when you're using Django's ``LocaleMiddleware``. More details about how the caching works: * Only GET or HEAD-requests with status code 200 are cached. * The number of seconds each page is stored for is set by the "max-age" section of the response's "Cache-Control" header, falling back to the CACHE_MIDDLEWARE_SECONDS setting if the section was not found. * If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests (i.e., those not made by a logged-in user) will be cached. This is a simple and effective way of avoiding the caching of the Django admin (and any other user-specific content). * This middleware expects that a HEAD request is answered with the same response headers exactly like the corresponding GET request. * When a hit occurs, a shallow copy of the original response object is returned from process_request. * Pages will be cached based on the contents of the request headers listed in the response's "Vary" header. * This middleware also sets ETag, Last-Modified, Expires and Cache-Control headers on the response object. """ from django.conf import settings from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS from django.utils.cache import get_cache_key, learn_cache_key, patch_response_headers, get_max_age class UpdateCacheMiddleware(object): """ Response-phase cache middleware that updates the cache if the response is cacheable. Must be used as part of the two-part update/fetch cache middleware. UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE_CLASSES so that it'll get called last during the response phase. """ def __init__(self): self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS self.cache = get_cache(self.cache_alias) def _session_accessed(self, request): try: return request.session.accessed except AttributeError: return False def _should_update_cache(self, request, response): if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache: return False # If the session has not been accessed otherwise, we don't want to # cause it to be accessed here. If it hasn't been accessed, then the # user's logged-in status has not affected the response anyway. if self.cache_anonymous_only and self._session_accessed(request): assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if request.user.is_authenticated(): # Don't cache user-variable requests from authenticated users. return False return True def process_response(self, request, response): """Sets the cache, if needed.""" if not self._should_update_cache(request, response): # We don't need to update the cache, just return. return response if not response.status_code == 200: return response # Try to get the timeout from the "max-age" section of the "Cache- # Control" header before reverting to using the default cache_timeout # length. timeout = get_max_age(response) if timeout == None: timeout = self.cache_timeout elif timeout == 0: # max-age was set to 0, don't bother caching. return response patch_response_headers(response, timeout) if timeout: cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache) if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback( lambda r: self.cache.set(cache_key, r, timeout) ) else: self.cache.set(cache_key, response, timeout) return response class FetchFromCacheMiddleware(object): """ Request-phase cache middleware that fetches a page from the cache. Must be used as part of the two-part update/fetch cache middleware. FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE_CLASSES so that it'll get called last during the request phase. """ def __init__(self): self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS self.cache = get_cache(self.cache_alias) def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if not request.method in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware): """ Cache middleware that provides basic behavior for many simple sites. Also used as the hook point for the cache decorator, which is generated using the decorator-from-middleware utility. """ def __init__(self, cache_timeout=None, cache_anonymous_only=None, **kwargs): # We need to differentiate between "provided, but using default value", # and "not provided". If the value is provided using a default, then # we fall back to system defaults. If it is not provided at all, # we need to use middleware defaults. cache_kwargs = {} try: self.key_prefix = kwargs['key_prefix'] if self.key_prefix is not None: cache_kwargs['KEY_PREFIX'] = self.key_prefix else: self.key_prefix = '' except KeyError: self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_kwargs['KEY_PREFIX'] = self.key_prefix try: self.cache_alias = kwargs['cache_alias'] if self.cache_alias is None: self.cache_alias = DEFAULT_CACHE_ALIAS if cache_timeout is not None: cache_kwargs['TIMEOUT'] = cache_timeout except KeyError: self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS if cache_timeout is None: cache_kwargs['TIMEOUT'] = settings.CACHE_MIDDLEWARE_SECONDS else: cache_kwargs['TIMEOUT'] = cache_timeout if cache_anonymous_only is None: self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) else: self.cache_anonymous_only = cache_anonymous_only self.cache = get_cache(self.cache_alias, **cache_kwargs) self.cache_timeout = self.cache.default_timeout
Python
from django.conf import settings from django.template import Library, Node, Template, TemplateSyntaxError from django.template.defaulttags import kwarg_re, include_is_allowed, SsiNode, URLNode from django.utils.encoding import smart_str register = Library() @register.tag def ssi(parser, token): """ Outputs the contents of a given file into the page. Like a simple "include" tag, the ``ssi`` tag includes the contents of another file -- which must be specified using an absolute path -- in the current page:: {% ssi "/home/html/ljworld.com/includes/right_generic.html" %} If the optional "parsed" parameter is given, the contents of the included file are evaluated as template code, with the current context:: {% ssi "/home/html/ljworld.com/includes/right_generic.html" parsed %} """ bits = token.contents.split() parsed = False if len(bits) not in (2, 3): raise TemplateSyntaxError("'ssi' tag takes one argument: the path to" " the file to be included") if len(bits) == 3: if bits[2] == 'parsed': parsed = True else: raise TemplateSyntaxError("Second (optional) argument to %s tag" " must be 'parsed'" % bits[0]) filepath = parser.compile_filter(bits[1]) return SsiNode(filepath, parsed, legacy_filepath=False) @register.tag def url(parser, token): """ Returns an absolute URL matching given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url "path.to.some_view" arg1 arg2 %} or {% url "path.to.some_view" name1=value1 name2=value2 %} The first argument is a path to a view. It can be an absolute python path or just ``app_name.view_name`` without the project name if the view is located inside the project. Other arguments are comma-separated values that will be filled in place of positional and keyword arguments in the URL. All arguments for the URL should be present. For example if you have a view ``app_name.client`` taking client's id and the corresponding line in a URLconf looks like this:: ('^client/(\d+)/$', 'app_name.client') and this app's URLconf is included into the project's URLconf under some path:: ('^clients/', include('project_name.app_name.urls')) then in a template you can create a link for a certain client like this:: {% url "app_name.client" client.id %} The URL will look like ``/clients/client/123/``. """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % bits[0]) viewname = parser.compile_filter(bits[1]) args = [] kwargs = {} asvar = None bits = bits[2:] if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] if len(bits): for bit in bits: match = kwarg_re.match(bit) if not match: raise TemplateSyntaxError("Malformed arguments to url tag") name, value = match.groups() if name: kwargs[name] = parser.compile_filter(value) else: args.append(parser.compile_filter(value)) return URLNode(viewname, args, kwargs, asvar, legacy_view_name=False)
Python
from django.conf import settings from django.template import Node from django.template import TemplateSyntaxError, Library from django.utils import formats from django.utils.encoding import force_unicode register = Library() def localize(value): """ Forces a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``. """ return force_unicode(formats.localize(value, use_l10n=True)) localize.is_safe = False def unlocalize(value): """ Forces a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``. """ return force_unicode(value) unlocalize.is_safe = False class LocalizeNode(Node): def __init__(self, nodelist, use_l10n): self.nodelist = nodelist self.use_l10n = use_l10n def __repr__(self): return "<LocalizeNode>" def render(self, context): old_setting = context.use_l10n context.use_l10n = self.use_l10n output = self.nodelist.render(context) context.use_l10n = old_setting return output @register.tag('localize') def localize_tag(parser, token): """ Forces or prevents localization of values, regardless of the value of `settings.USE_L10N`. Sample usage:: {% localize off %} var pi = {{ 3.1415 }}; {% endlocalize %} """ use_l10n = None bits = list(token.split_contents()) if len(bits) == 1: use_l10n = True elif len(bits) > 2 or bits[1] not in ('on', 'off'): raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0]) else: use_l10n = bits[1] == 'on' nodelist = parser.parse(('endlocalize',)) parser.delete_first_token() return LocalizeNode(nodelist, use_l10n) register.filter(localize) register.filter(unlocalize)
Python
from django import template from django.utils.encoding import iri_to_uri register = template.Library() class PrefixNode(template.Node): def __repr__(self): return "<PrefixNode for %r>" % self.name def __init__(self, varname=None, name=None): if name is None: raise template.TemplateSyntaxError( "Prefix nodes must be given a name to return.") self.varname = varname self.name = name @classmethod def handle_token(cls, parser, token, name): """ Class method to parse prefix node and return a Node. """ tokens = token.contents.split() if len(tokens) > 1 and tokens[1] != 'as': raise template.TemplateSyntaxError( "First argument in '%s' must be 'as'" % tokens[0]) if len(tokens) > 1: varname = tokens[2] else: varname = None return cls(varname, name) @classmethod def handle_simple(cls, name): try: from django.conf import settings except ImportError: prefix = '' else: prefix = iri_to_uri(getattr(settings, name, '')) return prefix def render(self, context): prefix = self.handle_simple(self.name) if self.varname is None: return prefix context[self.varname] = prefix return '' @register.tag def get_static_prefix(parser, token): """ Populates a template variable with the static prefix, ``settings.STATIC_URL``. Usage:: {% get_static_prefix [as varname] %} Examples:: {% get_static_prefix %} {% get_static_prefix as static_prefix %} """ return PrefixNode.handle_token(parser, token, "STATIC_URL") @register.tag def get_media_prefix(parser, token): """ Populates a template variable with the static prefix, ``settings.MEDIA_URL``. Usage:: {% get_media_prefix [as varname] %} Examples:: {% get_media_prefix %} {% get_media_prefix as media_prefix %} """ return PrefixNode.handle_token(parser, token, "MEDIA_URL")
Python
import re from django.template import Node, Variable, VariableNode from django.template import TemplateSyntaxError, TokenParser, Library from django.template import TOKEN_TEXT, TOKEN_VAR from django.template.base import _render_value_in_context from django.utils import translation from django.utils.encoding import force_unicode from django.template.defaulttags import token_kwargs register = Library() class GetAvailableLanguagesNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): from django.conf import settings context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES] return '' class GetLanguageInfoNode(Node): def __init__(self, lang_code, variable): self.lang_code = Variable(lang_code) self.variable = variable def render(self, context): lang_code = self.lang_code.resolve(context) context[self.variable] = translation.get_language_info(lang_code) return '' class GetLanguageInfoListNode(Node): def __init__(self, languages, variable): self.languages = Variable(languages) self.variable = variable def get_language_info(self, language): # ``language`` is either a language code string or a sequence # with the language code as its first item if len(language[0]) > 1: return translation.get_language_info(language[0]) else: return translation.get_language_info(str(language)) def render(self, context): langs = self.languages.resolve(context) context[self.variable] = [self.get_language_info(lang) for lang in langs] return '' class GetCurrentLanguageNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language() return '' class GetCurrentLanguageBidiNode(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return '' class TranslateNode(Node): def __init__(self, filter_expression, noop): self.noop = noop self.filter_expression = filter_expression if isinstance(self.filter_expression.var, basestring): self.filter_expression.var = Variable(u"'%s'" % self.filter_expression.var) def render(self, context): self.filter_expression.var.translate = not self.noop output = self.filter_expression.resolve(context) return _render_value_in_context(output, context) class BlockTranslateNode(Node): def __init__(self, extra_context, singular, plural=None, countervar=None, counter=None): self.extra_context = extra_context self.singular = singular self.plural = plural self.countervar = countervar self.counter = counter def render_token_list(self, tokens): result = [] vars = [] for token in tokens: if token.token_type == TOKEN_TEXT: result.append(token.contents) elif token.token_type == TOKEN_VAR: result.append(u'%%(%s)s' % token.contents) vars.append(token.contents) return ''.join(result), vars def render(self, context): tmp_context = {} for var, val in self.extra_context.items(): tmp_context[var] = val.resolve(context) # Update() works like a push(), so corresponding context.pop() is at # the end of function context.update(tmp_context) singular, vars = self.render_token_list(self.singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) result = translation.ungettext(singular, plural, count) vars.extend(plural_vars) else: result = translation.ugettext(singular) # Escape all isolated '%' before substituting in the context. result = re.sub(u'%(?!\()', u'%%', result) data = dict([(v, _render_value_in_context(context.get(v, ''), context)) for v in vars]) context.pop() return result % data def do_get_available_languages(parser, token): """ This will store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This will just pull the LANGUAGES setting from your setting file (or the default settings) and put it into the named variable. """ args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args) return GetAvailableLanguagesNode(args[2]) def do_get_language_info(parser, token): """ This will store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} """ args = token.contents.split() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoNode(args[2], args[4]) def do_get_language_info_list(parser, token): """ This will store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style tuple (or any sequence of sequences whose first items are language codes). Usage:: {% get_language_info_list for LANGUAGES as langs %} {% for l in langs %} {{ l.code }} {{ l.name }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-directional" }} {% endfor %} """ args = token.contents.split() if len(args) != 5 or args[1] != 'for' or args[3] != 'as': raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])) return GetLanguageInfoListNode(args[2], args[4]) def language_name(lang_code): return translation.get_language_info(lang_code)['name'] def language_name_local(lang_code): return translation.get_language_info(lang_code)['name_local'] def language_bidi(lang_code): return translation.get_language_info(lang_code)['bidi'] def do_get_current_language(parser, token): """ This will store the current language in the context. Usage:: {% get_current_language as language %} This will fetch the currently active language and put it's value into the ``language`` context variable. """ args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args) return GetCurrentLanguageNode(args[2]) def do_get_current_language_bidi(parser, token): """ This will store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This will fetch the currently active language's layout and put it's value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right """ args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args) return GetCurrentLanguageBidiNode(args[2]) def do_translate(parser, token): """ This will mark a string for translation and will translate the string for the current language. Usage:: {% trans "this is a test" %} This will mark the string for translation so it will be pulled out by mark-messages.py into the .po files and will run the string through the translation engine. There is a second form:: {% trans "this is a test" noop %} This will only mark for translation, but will return the string unchanged. Use it when you need to store values into forms that should be translated later on. You can use variables instead of constant strings to translate stuff you marked somewhere else:: {% trans variable %} This will just try to translate the contents of the variable ``variable``. Make sure that the string in there is something that is in the .po file. """ class TranslateParser(TokenParser): def top(self): value = self.value() # Backwards Compatiblity fix: # FilterExpression does not support single-quoted strings, # so we make a cheap localized fix in order to maintain # backwards compatibility with existing uses of ``trans`` # where single quote use is supported. if value[0] == "'": pos = None m = re.match("^'([^']+)'(\|.*$)",value) if m: value = '"%s"%s' % (m.group(1).replace('"','\\"'),m.group(2)) elif value[-1] == "'": value = '"%s"' % value[1:-1].replace('"','\\"') if self.more(): if self.tag() == 'noop': noop = True else: raise TemplateSyntaxError("only option for 'trans' is 'noop'") else: noop = False return (value, noop) value, noop = TranslateParser(token.contents).top() return TranslateNode(parser.compile_filter(value), noop) def do_block_translate(parser, token): """ This will translate a block of text with parameters. Usage:: {% blocktrans with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktrans %} Additionally, this supports pluralization:: {% blocktrans count count=var|length %} There is {{ count }} object. {% plural %} There are {{ count }} objects. {% endblocktrans %} This is much like ngettext, only in template syntax. The "var as value" legacy format is still supported:: {% blocktrans with foo|filter as bar and baz|filter as boo %} {% blocktrans count var|length as count %} """ bits = token.split_contents() options = {} remaining_bits = bits[1:] while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError('The %r option was specified more ' 'than once.' % option) if option == 'with': value = token_kwargs(remaining_bits, parser, support_legacy=True) if not value: raise TemplateSyntaxError('"with" in %r tag needs at least ' 'one keyword argument.' % bits[0]) elif option == 'count': value = token_kwargs(remaining_bits, parser, support_legacy=True) if len(value) != 1: raise TemplateSyntaxError('"count" in %r tag expected exactly ' 'one keyword argument.' % bits[0]) else: raise TemplateSyntaxError('Unknown argument for %r tag: %r.' % (bits[0], option)) options[option] = value if 'count' in options: countervar, counter = options['count'].items()[0] else: countervar, counter = None, None extra_context = options.get('with', {}) singular = [] plural = [] while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): singular.append(token) else: break if countervar and counter: if token.contents.strip() != 'plural': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it") while parser.tokens: token = parser.next_token() if token.token_type in (TOKEN_VAR, TOKEN_TEXT): plural.append(token) else: break if token.contents.strip() != 'endblocktrans': raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents) return BlockTranslateNode(extra_context, singular, plural, countervar, counter) register.tag('get_available_languages', do_get_available_languages) register.tag('get_language_info', do_get_language_info) register.tag('get_language_info_list', do_get_language_info_list) register.tag('get_current_language', do_get_current_language) register.tag('get_current_language_bidi', do_get_current_language_bidi) register.tag('trans', do_translate) register.tag('blocktrans', do_block_translate) register.filter(language_name) register.filter(language_name_local) register.filter(language_bidi)
Python
from django.template import Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist from django.template import resolve_variable from django.core.cache import cache from django.utils.encoding import force_unicode from django.utils.http import urlquote from django.utils.hashcompat import md5_constructor register = Library() class CacheNode(Node): def __init__(self, nodelist, expire_time_var, fragment_name, vary_on): self.nodelist = nodelist self.expire_time_var = Variable(expire_time_var) self.fragment_name = fragment_name self.vary_on = vary_on def render(self, context): try: expire_time = self.expire_time_var.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var) try: expire_time = int(expire_time) except (ValueError, TypeError): raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time) # Build a unicode key for this fragment and all vary-on's. args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])) cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest()) value = cache.get(cache_key) if value is None: value = self.nodelist.render(context) cache.set(cache_key, value, expire_time) return value def do_cache(parser, token): """ This will cache the contents of a template fragment for a given amount of time. Usage:: {% load cache %} {% cache [expire_time] [fragment_name] %} .. some expensive processing .. {% endcache %} This tag also supports varying by a list of arguments:: {% load cache %} {% cache [expire_time] [fragment_name] [var1] [var2] .. %} .. some expensive processing .. {% endcache %} Each unique set of arguments will result in a unique cache entry. """ nodelist = parser.parse(('endcache',)) parser.delete_first_token() tokens = token.contents.split() if len(tokens) < 3: raise TemplateSyntaxError(u"'%r' tag requires at least 2 arguments." % tokens[0]) return CacheNode(nodelist, tokens[1], tokens[2], tokens[3:]) register.tag('cache', do_cache)
Python
# This module is DEPRECATED! # # You should no longer be using django.template_loader. # # Use django.template.loader instead. from django.template.loader import *
Python
""" YAML serializer. Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__. """ from StringIO import StringIO import decimal import yaml from django.db import models from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.python import Deserializer as PythonDeserializer class DjangoSafeDumper(yaml.SafeDumper): def represent_decimal(self, data): return self.represent_scalar('tag:yaml.org,2002:str', str(data)) DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal) class Serializer(PythonSerializer): """ Convert a queryset to YAML. """ internal_use_only = False def handle_field(self, obj, field): # A nasty special case: base YAML doesn't support serialization of time # types (as opposed to dates or datetimes, which it does support). Since # we want to use the "safe" serializer for better interoperability, we # need to do something with those pesky times. Converting 'em to strings # isn't perfect, but it's better than a "!!python/time" type which would # halt deserialization under any other language. if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None: self._current[field.name] = str(getattr(obj, field.name)) else: super(Serializer, self).handle_field(obj, field) def end_serialization(self): yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options) def getvalue(self): return self.stream.getvalue() def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of YAML data. """ if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string for obj in PythonDeserializer(yaml.load(stream), **options): yield obj
Python
""" Serialize data to/from JSON """ import datetime import decimal from StringIO import StringIO from django.core.serializers.python import Serializer as PythonSerializer from django.core.serializers.python import Deserializer as PythonDeserializer from django.utils import datetime_safe from django.utils import simplejson class Serializer(PythonSerializer): """ Convert a queryset to JSON. """ internal_use_only = False def end_serialization(self): simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options) def getvalue(self): if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of JSON data. """ if isinstance(stream_or_string, basestring): stream = StringIO(stream_or_string) else: stream = stream_or_string for obj in PythonDeserializer(simplejson.load(stream), **options): yield obj class DjangoJSONEncoder(simplejson.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time and decimal types. """ DATE_FORMAT = "%Y-%m-%d" TIME_FORMAT = "%H:%M:%S" def default(self, o): if isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) elif isinstance(o, datetime.date): d = datetime_safe.new_date(o) return d.strftime(self.DATE_FORMAT) elif isinstance(o, datetime.time): return o.strftime(self.TIME_FORMAT) elif isinstance(o, decimal.Decimal): return str(o) else: return super(DjangoJSONEncoder, self).default(o) # Older, deprecated class name (for backwards compatibility purposes). DateTimeAwareJSONEncoder = DjangoJSONEncoder
Python
""" XML serializer. """ from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode from xml.dom import pulldom class Serializer(base.Serializer): """ Serializes a QuerySet to XML. """ def indent(self, level): if self.options.get('indent', None) is not None: self.xml.ignorableWhitespace('\n' + ' ' * self.options.get('indent', None) * level) def start_serialization(self): """ Start serialization -- open the XML document and the root element. """ self.xml = SimplerXMLGenerator(self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET)) self.xml.startDocument() self.xml.startElement("django-objects", {"version" : "1.0"}) def end_serialization(self): """ End serialization -- end the document. """ self.indent(0) self.xml.endElement("django-objects") self.xml.endDocument() def start_object(self, obj): """ Called as each object is handled. """ if not hasattr(obj, "_meta"): raise base.SerializationError("Non-model object (%s) encountered during serialization" % type(obj)) self.indent(1) obj_pk = obj._get_pk_val() if obj_pk is None: attrs = {"model": smart_unicode(obj._meta),} else: attrs = { "pk": smart_unicode(obj._get_pk_val()), "model": smart_unicode(obj._meta), } self.xml.startElement("object", attrs) def end_object(self, obj): """ Called after handling all fields for an object. """ self.indent(1) self.xml.endElement("object") def handle_field(self, obj, field): """ Called to handle each field on an object (except for ForeignKeys and ManyToManyFields) """ self.indent(2) self.xml.startElement("field", { "name" : field.name, "type" : field.get_internal_type() }) # Get a "string version" of the object's data. if getattr(obj, field.name) is not None: self.xml.characters(field.value_to_string(obj)) else: self.xml.addQuickElement("None") self.xml.endElement("field") def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey (we need to treat them slightly differently from regular fields). """ self._start_relational_field(field) related = getattr(obj, field.name) if related is not None: if self.use_natural_keys and hasattr(related, 'natural_key'): # If related object has a natural key, use it related = related.natural_key() # Iterable natural keys are rolled out as subelements for key_value in related: self.xml.startElement("natural", {}) self.xml.characters(smart_unicode(key_value)) self.xml.endElement("natural") else: if field.rel.field_name == related._meta.pk.name: # Related to remote object via primary key related = related._get_pk_val() else: # Related to remote object via other field related = getattr(related, field.rel.field_name) self.xml.characters(smart_unicode(related)) else: self.xml.addQuickElement("None") self.xml.endElement("field") def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. Related objects are only serialized as references to the object's PK (i.e. the related *data* is not dumped, just the relation). """ if field.rel.through._meta.auto_created: self._start_relational_field(field) if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'): # If the objects in the m2m have a natural key, use it def handle_m2m(value): natural = value.natural_key() # Iterable natural keys are rolled out as subelements self.xml.startElement("object", {}) for key_value in natural: self.xml.startElement("natural", {}) self.xml.characters(smart_unicode(key_value)) self.xml.endElement("natural") self.xml.endElement("object") else: def handle_m2m(value): self.xml.addQuickElement("object", attrs={ 'pk' : smart_unicode(value._get_pk_val()) }) for relobj in getattr(obj, field.name).iterator(): handle_m2m(relobj) self.xml.endElement("field") def _start_relational_field(self, field): """ Helper to output the <field> element for relational fields """ self.indent(2) self.xml.startElement("field", { "name" : field.name, "rel" : field.rel.__class__.__name__, "to" : smart_unicode(field.rel.to._meta), }) class Deserializer(base.Deserializer): """ Deserialize XML. """ def __init__(self, stream_or_string, **options): super(Deserializer, self).__init__(stream_or_string, **options) self.event_stream = pulldom.parse(self.stream) self.db = options.pop('using', DEFAULT_DB_ALIAS) def next(self): for event, node in self.event_stream: if event == "START_ELEMENT" and node.nodeName == "object": self.event_stream.expandNode(node) return self._handle_object(node) raise StopIteration def _handle_object(self, node): """ Convert an <object> node to a DeserializedObject. """ # Look up the model using the model loading mechanism. If this fails, # bail. Model = self._get_model_from_node(node, "model") # Start building a data dictionary from the object. # If the node is missing the pk set it to None if node.hasAttribute("pk"): pk = node.getAttribute("pk") else: pk = None data = {Model._meta.pk.attname : Model._meta.pk.to_python(pk)} # Also start building a dict of m2m data (this is saved as # {m2m_accessor_attribute : [list_of_related_objects]}) m2m_data = {} # Deseralize each field. for field_node in node.getElementsByTagName("field"): # If the field is missing the name attribute, bail (are you # sensing a pattern here?) field_name = field_node.getAttribute("name") if not field_name: raise base.DeserializationError("<field> node is missing the 'name' attribute") # Get the field from the Model. This will raise a # FieldDoesNotExist if, well, the field doesn't exist, which will # be propagated correctly. field = Model._meta.get_field(field_name) # As is usually the case, relation fields get the special treatment. if field.rel and isinstance(field.rel, models.ManyToManyRel): m2m_data[field.name] = self._handle_m2m_field_node(field_node, field) elif field.rel and isinstance(field.rel, models.ManyToOneRel): data[field.attname] = self._handle_fk_field_node(field_node, field) else: if field_node.getElementsByTagName('None'): value = None else: value = field.to_python(getInnerText(field_node).strip()) data[field.name] = value # Return a DeserializedObject so that the m2m data has a place to live. return base.DeserializedObject(Model(**data), m2m_data) def _handle_fk_field_node(self, node, field): """ Handle a <field> node for a ForeignKey """ # Check if there is a child node named 'None', returning None if so. if node.getElementsByTagName('None'): return None else: if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): keys = node.getElementsByTagName('natural') if keys: # If there are 'natural' subelements, it must be a natural key field_value = [getInnerText(k).strip() for k in keys] obj = field.rel.to._default_manager.db_manager(self.db).get_by_natural_key(*field_value) obj_pk = getattr(obj, field.rel.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.rel.to._meta.pk.rel: obj_pk = obj_pk.pk else: # Otherwise, treat like a normal PK field_value = getInnerText(node).strip() obj_pk = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) return obj_pk else: field_value = getInnerText(node).strip() return field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) def _handle_m2m_field_node(self, node, field): """ Handle a <field> node for a ManyToManyField. """ if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): def m2m_convert(n): keys = n.getElementsByTagName('natural') if keys: # If there are 'natural' subelements, it must be a natural key field_value = [getInnerText(k).strip() for k in keys] obj_pk = field.rel.to._default_manager.db_manager(self.db).get_by_natural_key(*field_value).pk else: # Otherwise, treat like a normal PK value. obj_pk = field.rel.to._meta.pk.to_python(n.getAttribute('pk')) return obj_pk else: m2m_convert = lambda n: field.rel.to._meta.pk.to_python(n.getAttribute('pk')) return [m2m_convert(c) for c in node.getElementsByTagName("object")] def _get_model_from_node(self, node, attr): """ Helper to look up a model from a <object model=...> or a <field rel=... to=...> node. """ model_identifier = node.getAttribute(attr) if not model_identifier: raise base.DeserializationError( "<%s> node is missing the required '%s' attribute" \ % (node.nodeName, attr)) try: Model = models.get_model(*model_identifier.split(".")) except TypeError: Model = None if Model is None: raise base.DeserializationError( "<%s> node has invalid model identifier: '%s'" % \ (node.nodeName, model_identifier)) return Model def getInnerText(node): """ Get all the inner text of a DOM node (recursively). """ # inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html inner_text = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NODE: inner_text.append(child.data) elif child.nodeType == child.ELEMENT_NODE: inner_text.extend(getInnerText(child)) else: pass return u"".join(inner_text)
Python
""" A Python "serializer". Doesn't do much serializing per se -- just converts to and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for other serializers. """ from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS from django.utils.encoding import smart_unicode, is_protected_type class Serializer(base.Serializer): """ Serializes a QuerySet to basic Python objects. """ internal_use_only = True def start_serialization(self): self._current = None self.objects = [] def end_serialization(self): pass def start_object(self, obj): self._current = {} def end_object(self, obj): self.objects.append({ "model" : smart_unicode(obj._meta), "pk" : smart_unicode(obj._get_pk_val(), strings_only=True), "fields" : self._current }) self._current = None def handle_field(self, obj, field): value = field._get_val_from_obj(obj) # Protected types (i.e., primitives like None, numbers, dates, # and Decimals) are passed through as is. All other values are # converted to string first. if is_protected_type(value): self._current[field.name] = value else: self._current[field.name] = field.value_to_string(obj) def handle_fk_field(self, obj, field): related = getattr(obj, field.name) if related is not None: if self.use_natural_keys and hasattr(related, 'natural_key'): related = related.natural_key() else: if field.rel.field_name == related._meta.pk.name: # Related to remote object via primary key related = related._get_pk_val() else: # Related to remote object via other field related = smart_unicode(getattr(related, field.rel.field_name), strings_only=True) self._current[field.name] = related def handle_m2m_field(self, obj, field): if field.rel.through._meta.auto_created: if self.use_natural_keys and hasattr(field.rel.to, 'natural_key'): m2m_value = lambda value: value.natural_key() self._current[field.name] = [m2m_value(related) for related in getattr(obj, field.name).iterator()] elif field.rel.get_related_field().primary_key: m2m_value = lambda value: smart_unicode( getattr(value, related_query.target_field_name + '_id'), strings_only=True) related_query = getattr(obj, field.name) filters = {related_query.source_field_name: obj._get_pk_val()} query = field.rel.through.objects.filter(**filters) self._current[field.name] = sorted((m2m_value(m2m_entity) for m2m_entity in query), reverse=True) else: m2m_value = lambda value: smart_unicode(value._get_pk_val(), strings_only=True) self._current[field.name] = [m2m_value(related) for related in getattr(obj, field.name).iterator()] def getvalue(self): return self.objects def Deserializer(object_list, **options): """ Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor """ db = options.pop('using', DEFAULT_DB_ALIAS) models.get_apps() for d in object_list: # Look up the model and starting build a dict of data for it. Model = _get_model(d["model"]) data = {Model._meta.pk.attname : Model._meta.pk.to_python(d["pk"])} m2m_data = {} # Handle each field for (field_name, field_value) in d["fields"].iteritems(): if isinstance(field_value, str): field_value = smart_unicode(field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True) field = Model._meta.get_field(field_name) # Handle M2M relations if field.rel and isinstance(field.rel, models.ManyToManyRel): if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): def m2m_convert(value): if hasattr(value, '__iter__'): return field.rel.to._default_manager.db_manager(db).get_by_natural_key(*value).pk else: return smart_unicode(field.rel.to._meta.pk.to_python(value)) else: m2m_convert = lambda v: smart_unicode(field.rel.to._meta.pk.to_python(v)) m2m_data[field.name] = [m2m_convert(pk) for pk in field_value] # Handle FK fields elif field.rel and isinstance(field.rel, models.ManyToOneRel): if field_value is not None: if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): if hasattr(field_value, '__iter__'): obj = field.rel.to._default_manager.db_manager(db).get_by_natural_key(*field_value) value = getattr(obj, field.rel.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.rel.to._meta.pk.rel: value = value.pk else: value = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) data[field.attname] = value else: data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value) else: data[field.attname] = None # Handle all other fields else: data[field.name] = field.to_python(field_value) yield base.DeserializedObject(Model(**data), m2m_data) def _get_model(model_identifier): """ Helper to look up a model from an "app_label.module_name" string. """ try: Model = models.get_model(*model_identifier.split(".")) except TypeError: Model = None if Model is None: raise base.DeserializationError(u"Invalid model identifier: '%s'" % model_identifier) return Model
Python
""" Module for abstract serializer/unserializer base classes. """ from StringIO import StringIO from django.db import models from django.utils.encoding import smart_str, smart_unicode from django.utils import datetime_safe class SerializationError(Exception): """Something bad happened during serialization.""" pass class DeserializationError(Exception): """Something bad happened during deserialization.""" pass class Serializer(object): """ Abstract serializer base class. """ # Indicates if the implemented serializer is only available for # internal Django use. internal_use_only = False def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) self.start_serialization() for obj in queryset: self.start_object(obj) for field in obj._meta.local_fields: if field.serialize: if field.rel is None: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_field(obj, field) else: if self.selected_fields is None or field.attname[:-3] in self.selected_fields: self.handle_fk_field(obj, field) for field in obj._meta.many_to_many: if field.serialize: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_m2m_field(obj, field) self.end_object(obj) self.end_serialization() return self.getvalue() def get_string_value(self, obj, field): """ Convert a field's value to a string. """ return smart_unicode(field.value_to_string(obj)) def start_serialization(self): """ Called when serializing of the queryset starts. """ raise NotImplementedError def end_serialization(self): """ Called when serializing of the queryset ends. """ pass def start_object(self, obj): """ Called when serializing of an object starts. """ raise NotImplementedError def end_object(self, obj): """ Called when serializing of an object ends. """ pass def handle_field(self, obj, field): """ Called to handle each individual (non-relational) field on an object. """ raise NotImplementedError def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey field. """ raise NotImplementedError def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. """ raise NotImplementedError def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue() class Deserializer(object): """ Abstract base deserializer class. """ def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, basestring): self.stream = StringIO(stream_or_string) else: self.stream = stream_or_string # hack to make sure that the models have all been loaded before # deserialization starts (otherwise subclass calls to get_model() # and friends might fail...) models.get_apps() def __iter__(self): return self def next(self): """Iteration iterface -- return the next item in the stream""" raise NotImplementedError class DeserializedObject(object): """ A deserialized model. Basically a container for holding the pre-saved deserialized data along with the many-to-many data saved with the object. Call ``save()`` to save the object (with the many-to-many data) to the database; call ``save(save_m2m=False)`` to save just the object fields (and not touch the many-to-many stuff.) """ def __init__(self, obj, m2m_data=None): self.object = obj self.m2m_data = m2m_data def __repr__(self): return "<DeserializedObject: %s.%s(pk=%s)>" % ( self.object._meta.app_label, self.object._meta.object_name, self.object.pk) def save(self, save_m2m=True, using=None): # Call save on the Model baseclass directly. This bypasses any # model-defined save. The save is also forced to be raw. # This ensures that the data that is deserialized is literally # what came from the file, not post-processed by pre_save/save # methods. models.Model.save_base(self.object, using=using, raw=True) if self.m2m_data and save_m2m: for accessor_name, object_list in self.m2m_data.items(): setattr(self.object, accessor_name, object_list) # prevent a second (possibly accidental) call to save() from saving # the m2m data twice. self.m2m_data = None
Python
""" Interfaces for serializing Django objects. Usage:: from django.core import serializers json = serializers.serialize("json", some_query_set) objects = list(serializers.deserialize("json", json)) To add your own serializers, use the SERIALIZATION_MODULES setting:: SERIALIZATION_MODULES = { "csv" : "path.to.csv.serializer", "txt" : "path.to.txt.serializer", } """ from django.conf import settings from django.utils import importlib # Built-in serializers BUILTIN_SERIALIZERS = { "xml" : "django.core.serializers.xml_serializer", "python" : "django.core.serializers.python", "json" : "django.core.serializers.json", } # Check for PyYaml and register the serializer if it's available. try: import yaml BUILTIN_SERIALIZERS["yaml"] = "django.core.serializers.pyyaml" except ImportError: pass _serializers = {} def register_serializer(format, serializer_module, serializers=None): """Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global register of serializers. Adding serializers directly is not a thread-safe operation. """ if serializers is None and not _serializers: _load_serializers() module = importlib.import_module(serializer_module) if serializers is None: _serializers[format] = module else: serializers[format] = module def unregister_serializer(format): "Unregister a given serializer. This is not a thread-safe operation." if not _serializers: _load_serializers() del _serializers[format] def get_serializer(format): if not _serializers: _load_serializers() return _serializers[format].Serializer def get_serializer_formats(): if not _serializers: _load_serializers() return _serializers.keys() def get_public_serializer_formats(): if not _serializers: _load_serializers() return [k for k, v in _serializers.iteritems() if not v.Serializer.internal_use_only] def get_deserializer(format): if not _serializers: _load_serializers() return _serializers[format].Deserializer def serialize(format, queryset, **options): """ Serialize a queryset (or any iterator that returns database objects) using a certain serializer. """ s = get_serializer(format)() s.serialize(queryset, **options) return s.getvalue() def deserialize(format, stream_or_string, **options): """ Deserialize a stream or a string. Returns an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is a instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``. """ d = get_deserializer(format) return d(stream_or_string, **options) def _load_serializers(): """ Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order. """ global _serializers serializers = {} for format in BUILTIN_SERIALIZERS: register_serializer(format, BUILTIN_SERIALIZERS[format], serializers) if hasattr(settings, "SERIALIZATION_MODULES"): for format in settings.SERIALIZATION_MODULES: register_serializer(format, settings.SERIALIZATION_MODULES[format], serializers) _serializers = serializers
Python
""" A set of request processors that return dictionaries to be merged into a template context. Each function takes the request object as its only parameter and returns a dictionary to add to the context. These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used by RequestContext. """ from django.conf import settings from django.middleware.csrf import get_token from django.utils.functional import lazy def auth(request): """ DEPRECATED. This context processor is the old location, and has been moved to `django.contrib.auth.context_processors`. This function still exists for backwards-compatibility; it will be removed in Django 1.4. """ import warnings warnings.warn( "The context processor at `django.core.context_processors.auth` is " \ "deprecated; use the path `django.contrib.auth.context_processors.auth` " \ "instead.", DeprecationWarning ) from django.contrib.auth.context_processors import auth as auth_context_processor return auth_context_processor(request) def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return 'NOTPROVIDED' else: return token _get_val = lazy(_get_val, str) return {'csrf_token': _get_val() } def debug(request): "Returns context variables helpful for debugging." context_extras = {} if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: context_extras['debug'] = True from django.db import connection context_extras['sql_queries'] = connection.queries return context_extras def i18n(request): from django.utils import translation context_extras = {} context_extras['LANGUAGES'] = settings.LANGUAGES context_extras['LANGUAGE_CODE'] = translation.get_language() context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi() return context_extras def static(request): """ Adds static-related context variables to the context. """ return {'STATIC_URL': settings.STATIC_URL} def media(request): """ Adds media-related context variables to the context. """ return {'MEDIA_URL': settings.MEDIA_URL} def request(request): return {'request': request} # PermWrapper and PermLookupDict proxy the permissions system into objects that # the template system can understand. They once lived here -- they have # been moved to django.contrib.auth.context_processors. from django.contrib.auth.context_processors import PermLookupDict as RealPermLookupDict from django.contrib.auth.context_processors import PermWrapper as RealPermWrapper class PermLookupDict(RealPermLookupDict): def __init__(self, *args, **kwargs): import warnings warnings.warn( "`django.core.context_processors.PermLookupDict` is " \ "deprecated; use `django.contrib.auth.context_processors.PermLookupDict` " \ "instead.", PendingDeprecationWarning ) super(PermLookupDict, self).__init__(*args, **kwargs) class PermWrapper(RealPermWrapper): def __init__(self, *args, **kwargs): import warnings warnings.warn( "`django.core.context_processors.PermWrapper` is " \ "deprecated; use `django.contrib.auth.context_processors.PermWrapper` " \ "instead.", PendingDeprecationWarning ) super(PermWrapper, self).__init__(*args, **kwargs)
Python
import mimetypes import os import random import time from email import Charset, Encoders try: from email.generator import Generator except ImportError: from email.Generator import Generator # TODO: Remove when remove Python 2.4 support from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.Header import Header from email.Utils import formatdate, getaddresses, formataddr, parseaddr from django.conf import settings from django.core.mail.utils import DNS_NAME from django.utils.encoding import smart_str, force_unicode try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from # some spam filters. Charset.add_charset('utf-8', Charset.SHORTEST, Charset.QP, 'utf-8') # Default MIME type to use on attachments (if it is not explicitly given # and cannot be guessed). DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream' class BadHeaderError(ValueError): pass # Copied from Python standard library, with the following modifications: # * Used cached hostname for performance. # * Added try/except to support lack of getpid() in Jython (#5496). def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) try: pid = os.getpid() except AttributeError: # No getpid() in Jython, for example. pid = 1 randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = DNS_NAME msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost) return msgid # Header names that contain structured address data (RFC #5322) ADDRESS_HEADERS = set([ 'from', 'sender', 'reply-to', 'to', 'cc', 'bcc', 'resent-from', 'resent-sender', 'resent-to', 'resent-cc', 'resent-bcc', ]) def forbid_multi_line_headers(name, val, encoding): """Forbids multi-line headers, to prevent header injection.""" encoding = encoding or settings.DEFAULT_CHARSET val = force_unicode(val) if '\n' in val or '\r' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name)) try: val = val.encode('ascii') except UnicodeEncodeError: if name.lower() in ADDRESS_HEADERS: val = ', '.join(sanitize_address(addr, encoding) for addr in getaddresses((val,))) else: val = str(Header(val, encoding)) else: if name.lower() == 'subject': val = Header(val) return name, val def sanitize_address(addr, encoding): if isinstance(addr, basestring): addr = parseaddr(force_unicode(addr)) nm, addr = addr nm = str(Header(nm, encoding)) try: addr = addr.encode('ascii') except UnicodeEncodeError: # IDN if u'@' in addr: localpart, domain = addr.split(u'@', 1) localpart = str(Header(localpart, encoding)) domain = domain.encode('idna') addr = '@'.join([localpart, domain]) else: addr = str(Header(addr, encoding)) return formataddr((nm, addr)) class SafeMIMEText(MIMEText): def __init__(self, text, subtype, charset): self.encoding = charset MIMEText.__init__(self, text, subtype, charset) def __setitem__(self, name, val): name, val = forbid_multi_line_headers(name, val, self.encoding) MIMEText.__setitem__(self, name, val) def as_string(self, unixfrom=False): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = StringIO() g = Generator(fp, mangle_from_ = False) g.flatten(self, unixfrom=unixfrom) return fp.getvalue() class SafeMIMEMultipart(MIMEMultipart): def __init__(self, _subtype='mixed', boundary=None, _subparts=None, encoding=None, **_params): self.encoding = encoding MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params) def __setitem__(self, name, val): name, val = forbid_multi_line_headers(name, val, self.encoding) MIMEMultipart.__setitem__(self, name, val) def as_string(self, unixfrom=False): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = StringIO() g = Generator(fp, mangle_from_ = False) g.flatten(self, unixfrom=unixfrom) return fp.getvalue() class EmailMessage(object): """ A container for email information. """ content_subtype = 'plain' mixed_subtype = 'mixed' encoding = None # None => use settings default def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None): """ Initialize a single email message (which can be sent to multiple recipients). All strings used to create the message can be unicode strings (or UTF-8 bytestrings). The SafeMIMEText class will handle any necessary encoding conversions. """ if to: assert not isinstance(to, basestring), '"to" argument must be a list or tuple' self.to = list(to) else: self.to = [] if cc: assert not isinstance(cc, basestring), '"cc" argument must be a list or tuple' self.cc = list(cc) else: self.cc = [] if bcc: assert not isinstance(bcc, basestring), '"bcc" argument must be a list or tuple' self.bcc = list(bcc) else: self.bcc = [] self.from_email = from_email or settings.DEFAULT_FROM_EMAIL self.subject = subject self.body = body self.attachments = attachments or [] self.extra_headers = headers or {} self.connection = connection def get_connection(self, fail_silently=False): from django.core.mail import get_connection if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection def message(self): encoding = self.encoding or settings.DEFAULT_CHARSET msg = SafeMIMEText(smart_str(self.body, encoding), self.content_subtype, encoding) msg = self._create_message(msg) msg['Subject'] = self.subject msg['From'] = self.extra_headers.get('From', self.from_email) msg['To'] = ', '.join(self.to) if self.cc: msg['Cc'] = ', '.join(self.cc) # Email header names are case-insensitive (RFC 2045), so we have to # accommodate that when doing comparisons. header_names = [key.lower() for key in self.extra_headers] if 'date' not in header_names: msg['Date'] = formatdate() if 'message-id' not in header_names: msg['Message-ID'] = make_msgid() for name, value in self.extra_headers.items(): if name.lower() == 'from': # From is already handled continue msg[name] = value return msg def recipients(self): """ Returns a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return self.to + self.cc + self.bcc def send(self, fail_silently=False): """Sends the email message.""" if not self.recipients(): # Don't bother creating the network connection if there's nobody to # send to. return 0 return self.get_connection(fail_silently).send_messages([self]) def attach(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments. """ if isinstance(filename, MIMEBase): assert content == mimetype == None self.attachments.append(filename) else: assert content is not None self.attachments.append((filename, content, mimetype)) def attach_file(self, path, mimetype=None): """Attaches a file from the filesystem.""" filename = os.path.basename(path) content = open(path, 'rb').read() self.attach(filename, content, mimetype) def _create_message(self, msg): return self._create_attachments(msg) def _create_attachments(self, msg): if self.attachments: encoding = self.encoding or settings.DEFAULT_CHARSET body_msg = msg msg = SafeMIMEMultipart(_subtype=self.mixed_subtype, encoding=encoding) if self.body: msg.attach(body_msg) for attachment in self.attachments: if isinstance(attachment, MIMEBase): msg.attach(attachment) else: msg.attach(self._create_attachment(*attachment)) return msg def _create_mime_attachment(self, content, mimetype): """ Converts the content, mimetype pair into a MIME attachment object. """ basetype, subtype = mimetype.split('/', 1) if basetype == 'text': encoding = self.encoding or settings.DEFAULT_CHARSET attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding) else: # Encode non-text attachments with base64. attachment = MIMEBase(basetype, subtype) attachment.set_payload(content) Encoders.encode_base64(attachment) return attachment def _create_attachment(self, filename, content, mimetype=None): """ Converts the filename, content, mimetype triple into a MIME attachment object. """ if mimetype is None: mimetype, _ = mimetypes.guess_type(filename) if mimetype is None: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE attachment = self._create_mime_attachment(content, mimetype) if filename: attachment.add_header('Content-Disposition', 'attachment', filename=filename) return attachment class EmailMultiAlternatives(EmailMessage): """ A version of EmailMessage that makes it easy to send multipart/alternative messages. For example, including text and HTML versions of the text is made easier. """ alternative_subtype = 'alternative' def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None): """ Initialize a single email message (which can be sent to multiple recipients). All strings used to create the message can be unicode strings (or UTF-8 bytestrings). The SafeMIMEText class will handle any necessary encoding conversions. """ super(EmailMultiAlternatives, self).__init__(subject, body, from_email, to, bcc, connection, attachments, headers, cc) self.alternatives = alternatives or [] def attach_alternative(self, content, mimetype): """Attach an alternative content representation.""" assert content is not None assert mimetype is not None self.alternatives.append((content, mimetype)) def _create_message(self, msg): return self._create_attachments(self._create_alternatives(msg)) def _create_alternatives(self, msg): encoding = self.encoding or settings.DEFAULT_CHARSET if self.alternatives: body_msg = msg msg = SafeMIMEMultipart(_subtype=self.alternative_subtype, encoding=encoding) if self.body: msg.attach(body_msg) for alternative in self.alternatives: msg.attach(self._create_mime_attachment(*alternative)) return msg
Python
""" Email message and email sending related helper functions. """ import socket # Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of # seconds, which slows down the restart of the server. class CachedDnsName(object): def __str__(self): return self.get_fqdn() def get_fqdn(self): if not hasattr(self, '_fqdn'): self._fqdn = socket.getfqdn() return self._fqdn DNS_NAME = CachedDnsName()
Python
""" Dummy email backend that does nothing. """ from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def send_messages(self, email_messages): return len(email_messages)
Python
""" Email backend that writes messages to console instead of sending them. """ import sys import threading from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): self.stream = kwargs.pop('stream', sys.stdout) self._lock = threading.RLock() super(EmailBackend, self).__init__(*args, **kwargs) def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return self._lock.acquire() try: # The try-except is nested to allow for # Python 2.4 support (Refs #12147) try: stream_created = self.open() for message in email_messages: self.stream.write('%s\n' % message.message().as_string()) self.stream.write('-'*79) self.stream.write('\n') self.stream.flush() # flush after each message if stream_created: self.close() except: if not self.fail_silently: raise finally: self._lock.release() return len(email_messages)
Python
"""SMTP email backend class.""" import smtplib import socket import threading from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.utils import DNS_NAME from django.core.mail.message import sanitize_address class EmailBackend(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__(self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, **kwargs): super(EmailBackend, self).__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT self.username = username or settings.EMAIL_HOST_USER self.password = password or settings.EMAIL_HOST_PASSWORD if use_tls is None: self.use_tls = settings.EMAIL_USE_TLS else: self.use_tls = use_tls self.connection = None self._lock = threading.RLock() def open(self): """ Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False try: # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. self.connection = smtplib.SMTP(self.host, self.port, local_hostname=DNS_NAME.get_fqdn()) if self.use_tls: self.connection.ehlo() self.connection.starttls() self.connection.ehlo() if self.username and self.password: self.connection.login(self.username, self.password) return True except: if not self.fail_silently: raise def close(self): """Closes the connection to the email server.""" try: try: self.connection.quit() except socket.sslerror: # This happens when calling quit() on a TLS connection # sometimes. self.connection.close() except: if self.fail_silently: return raise finally: self.connection = None def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not email_messages: return self._lock.acquire() try: new_conn_created = self.open() if not self.connection: # We failed silently on open(). # Trying to send would be pointless. return num_sent = 0 for message in email_messages: sent = self._send(message) if sent: num_sent += 1 if new_conn_created: self.close() finally: self._lock.release() return num_sent def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] try: self.connection.sendmail(from_email, recipients, email_message.message().as_string()) except: if not self.fail_silently: raise return False return True
Python
"""Base email backend class.""" class BaseEmailBackend(object): """ Base class for email backend implementations. Subclasses must at least overwrite send_messages(). """ def __init__(self, fail_silently=False, **kwargs): self.fail_silently = fail_silently def open(self): """Open a network connection. This method can be overwritten by backend implementations to open a network connection. It's up to the backend implementation to track the status of a network connection if it's needed by the backend. This method can be called by applications to force a single network connection to be used when sending mails. See the send_messages() method of the SMTP backend for a reference implementation. The default implementation does nothing. """ pass def close(self): """Close a network connection.""" pass def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. """ raise NotImplementedError
Python
# Mail backends shipped with Django.
Python
""" Backend for test environment. """ from django.core import mail from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): """A email backend for use during test sessions. The test connection stores email messages in a dummy outbox, rather than sending them out on the wire. The dummy outbox is accessible through the outbox instance attribute. """ def __init__(self, *args, **kwargs): super(EmailBackend, self).__init__(*args, **kwargs) if not hasattr(mail, 'outbox'): mail.outbox = [] def send_messages(self, messages): """Redirect messages to the dummy outbox""" mail.outbox.extend(messages) return len(messages)
Python
"""Email backend that writes messages to a file.""" import datetime import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend class EmailBackend(ConsoleEmailBackend): def __init__(self, *args, **kwargs): self._fname = None if 'file_path' in kwargs: self.file_path = kwargs.pop('file_path') else: self.file_path = getattr(settings, 'EMAIL_FILE_PATH',None) # Make sure self.file_path is a string. if not isinstance(self.file_path, basestring): raise ImproperlyConfigured('Path for saving emails is invalid: %r' % self.file_path) self.file_path = os.path.abspath(self.file_path) # Make sure that self.file_path is an directory if it exists. if os.path.exists(self.file_path) and not os.path.isdir(self.file_path): raise ImproperlyConfigured('Path for saving email messages exists, but is not a directory: %s' % self.file_path) # Try to create it, if it not exists. elif not os.path.exists(self.file_path): try: os.makedirs(self.file_path) except OSError, err: raise ImproperlyConfigured('Could not create directory for saving email messages: %s (%s)' % (self.file_path, err)) # Make sure that self.file_path is writable. if not os.access(self.file_path, os.W_OK): raise ImproperlyConfigured('Could not write to directory: %s' % self.file_path) # Finally, call super(). # Since we're using the console-based backend as a base, # force the stream to be None, so we don't default to stdout kwargs['stream'] = None super(EmailBackend, self).__init__(*args, **kwargs) def _get_filename(self): """Return a unique file name.""" if self._fname is None: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") fname = "%s-%s.log" % (timestamp, abs(id(self))) self._fname = os.path.join(self.file_path, fname) return self._fname def open(self): if self.stream is None: self.stream = open(self._get_filename(), 'a') return True return False def close(self): try: if self.stream is not None: self.stream.close() finally: self.stream = None
Python
""" Tools for sending email. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module # Imported for backwards compatibility, and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the introduction of email # backends and the subsequent reorganization (See #10355) from django.core.mail.utils import CachedDnsName, DNS_NAME from django.core.mail.message import \ EmailMessage, EmailMultiAlternatives, \ SafeMIMEText, SafeMIMEMultipart, \ DEFAULT_ATTACHMENT_MIME_TYPE, make_msgid, \ BadHeaderError, forbid_multi_line_headers from django.core.mail.backends.smtp import EmailBackend as _SMTPConnection def get_connection(backend=None, fail_silently=False, **kwds): """Load an e-mail backend and return an instance of it. If backend is None (default) settings.EMAIL_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. """ path = backend or settings.EMAIL_BACKEND try: mod_name, klass_name = path.rsplit('.', 1) mod = import_module(mod_name) except ImportError, e: raise ImproperlyConfigured(('Error importing email backend module %s: "%s"' % (mod_name, e))) try: klass = getattr(mod, klass_name) except AttributeError: raise ImproperlyConfigured(('Module "%s" does not define a ' '"%s" class' % (mod_name, klass_name))) return klass(fail_silently=fail_silently, **kwds) def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. """ connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) return EmailMessage(subject, message, from_email, recipient_list, connection=connection).send() def send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): """ Given a datatuple of (subject, message, from_email, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. """ connection = connection or get_connection(username=auth_user, password=auth_password, fail_silently=fail_silently) messages = [EmailMessage(subject, message, sender, recipient) for subject, message, sender, recipient in datatuple] return connection.send_messages(messages) def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None): """Sends a message to the admins, as defined by the ADMINS setting.""" if not settings.ADMINS: return mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently) def mail_managers(subject, message, fail_silently=False, connection=None, html_message=None): """Sends a message to the managers, as defined by the MANAGERS setting.""" if not settings.MANAGERS: return mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently) class SMTPConnection(_SMTPConnection): def __init__(self, *args, **kwds): import warnings warnings.warn( 'mail.SMTPConnection is deprecated; use mail.get_connection() instead.', DeprecationWarning ) super(SMTPConnection, self).__init__(*args, **kwds)
Python
import os from pprint import pformat import sys from warnings import warn from django import http from django.core import signals from django.core.handlers.base import BaseHandler from django.core.urlresolvers import set_script_prefix from django.utils import datastructures from django.utils.encoding import force_unicode, smart_str, iri_to_uri from django.utils.log import getLogger logger = getLogger('django.request') # NOTE: do *not* import settings (or any module which eventually imports # settings) until after ModPythonHandler has been called; otherwise os.environ # won't be set up correctly (with respect to settings). class ModPythonRequest(http.HttpRequest): def __init__(self, req): self._req = req # FIXME: This isn't ideal. The request URI may be encoded (it's # non-normalized) slightly differently to the "real" SCRIPT_NAME # and PATH_INFO values. This causes problems when we compute path_info, # below. For now, don't use script names that will be subject to # encoding/decoding. self.path = force_unicode(req.uri) root = req.get_options().get('django.root', '') self.django_root = root # req.path_info isn't necessarily computed correctly in all # circumstances (it's out of mod_python's control a bit), so we use # req.uri and some string manipulations to get the right value. if root and req.uri.startswith(root): self.path_info = force_unicode(req.uri[len(root):]) else: self.path_info = self.path if not self.path_info: # Django prefers empty paths to be '/', rather than '', to give us # a common start character for URL patterns. So this is a little # naughty, but also pretty harmless. self.path_info = u'/' self._post_parse_error = False self._stream = self._req self._read_started = False def __repr__(self): # Since this is called as part of error handling, we need to be very # robust against potentially malformed input. try: get = pformat(self.GET) except: get = '<could not parse>' if self._post_parse_error: post = '<could not parse>' else: try: post = pformat(self.POST) except: post = '<could not parse>' try: cookies = pformat(self.COOKIES) except: cookies = '<could not parse>' try: meta = pformat(self.META) except: meta = '<could not parse>' return smart_str(u'<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % (self.path, unicode(get), unicode(post), unicode(cookies), unicode(meta))) def get_full_path(self): # RFC 3986 requires self._req.args to be in the ASCII range, but this # doesn't always happen, so rather than crash, we defensively encode it. return '%s%s' % (self.path, self._req.args and ('?' + iri_to_uri(self._req.args)) or '') def is_secure(self): try: return self._req.is_https() except AttributeError: # mod_python < 3.2.10 doesn't have req.is_https(). return self._req.subprocess_env.get('HTTPS', '').lower() in ('on', '1') def _get_request(self): if not hasattr(self, '_request'): self._request = datastructures.MergeDict(self.POST, self.GET) return self._request def _get_get(self): if not hasattr(self, '_get'): self._get = http.QueryDict(self._req.args, encoding=self._encoding) return self._get def _set_get(self, get): self._get = get def _get_post(self): if not hasattr(self, '_post'): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_cookies(self): if not hasattr(self, '_cookies'): self._cookies = http.parse_cookie(self._req.headers_in.get('cookie', '')) return self._cookies def _set_cookies(self, cookies): self._cookies = cookies def _get_files(self): if not hasattr(self, '_files'): self._load_post_and_files() return self._files def _get_meta(self): "Lazy loader that returns self.META dictionary" if not hasattr(self, '_meta'): self._meta = { 'AUTH_TYPE': self._req.ap_auth_type, 'CONTENT_LENGTH': self._req.headers_in.get('content-length', 0), 'CONTENT_TYPE': self._req.headers_in.get('content-type'), 'GATEWAY_INTERFACE': 'CGI/1.1', 'PATH_INFO': self.path_info, 'PATH_TRANSLATED': None, # Not supported 'QUERY_STRING': self._req.args, 'REMOTE_ADDR': self._req.connection.remote_ip, 'REMOTE_HOST': None, # DNS lookups not supported 'REMOTE_IDENT': self._req.connection.remote_logname, 'REMOTE_USER': self._req.user, 'REQUEST_METHOD': self._req.method, 'SCRIPT_NAME': self.django_root, 'SERVER_NAME': self._req.server.server_hostname, 'SERVER_PORT': self._req.connection.local_addr[1], 'SERVER_PROTOCOL': self._req.protocol, 'SERVER_SOFTWARE': 'mod_python' } for key, value in self._req.headers_in.items(): key = 'HTTP_' + key.upper().replace('-', '_') self._meta[key] = value return self._meta def _get_method(self): return self.META['REQUEST_METHOD'].upper() GET = property(_get_get, _set_get) POST = property(_get_post, _set_post) COOKIES = property(_get_cookies, _set_cookies) FILES = property(_get_files) META = property(_get_meta) REQUEST = property(_get_request) method = property(_get_method) class ModPythonHandler(BaseHandler): request_class = ModPythonRequest def __call__(self, req): warn(('The mod_python handler is deprecated; use a WSGI or FastCGI server instead.'), PendingDeprecationWarning) # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that os.environ.update(req.subprocess_env) # now that the environ works we can see the correct settings, so imports # that use settings now can work from django.conf import settings # if we need to set up middleware, now that settings works we can do it now. if self._request_middleware is None: self.load_middleware() set_script_prefix(req.get_options().get('django.root', '')) signals.request_started.send(sender=self.__class__) try: try: request = self.request_class(req) except UnicodeDecodeError: logger.warning('Bad Request (UnicodeDecodeError)', exc_info=sys.exc_info(), extra={ 'status_code': 400, } ) response = http.HttpResponseBadRequest() else: response = self.get_response(request) finally: signals.request_finished.send(sender=self.__class__) # Convert our custom HttpResponse object back into the mod_python req. req.content_type = response['Content-Type'] for key, value in response.items(): if key != 'content-type': req.headers_out[str(key)] = str(value) for c in response.cookies.values(): req.headers_out.add('Set-Cookie', c.output(header='')) req.status = response.status_code try: for chunk in response: req.write(chunk) finally: response.close() return 0 # mod_python.apache.OK def handler(req): # mod_python hooks into this function. return ModPythonHandler()(req)
Python
import hotshot, time, os from django.core.handlers.modpython import ModPythonHandler PROFILE_DATA_DIR = "/var/log/cmsprofile" def handler(req): ''' Handler that uses hotshot to store profile data. Stores profile data in PROFILE_DATA_DIR. Since hotshot has no way (that I know of) to append profile data to a single file, each request gets its own profile. The file names are in the format <url>.<n>.prof where <url> is the request path with "/" replaced by ".", and <n> is a timestamp with microseconds to prevent overwriting files. Use the gather_profile_stats.py script to gather these individual request profiles into aggregated profiles by request path. ''' profname = "%s.%.3f.prof" % (req.uri.strip("/").replace('/', '.'), time.time()) profname = os.path.join(PROFILE_DATA_DIR, profname) prof = hotshot.Profile(profname) return prof.runcall(ModPythonHandler(), req)
Python
import sys from django import http from django.core import signals from django.utils.encoding import force_unicode from django.utils.importlib import import_module from django.utils.log import getLogger logger = getLogger('django.request') class BaseHandler(object): # Changes that are always applied to a response (in this order). response_fixes = [ http.fix_location_header, http.conditional_content_removal, http.fix_IE_for_attach, http.fix_IE_for_vary, ] def __init__(self): self._request_middleware = self._view_middleware = self._response_middleware = self._exception_middleware = None def load_middleware(self): """ Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__). """ from django.conf import settings from django.core import exceptions self._view_middleware = [] self._template_response_middleware = [] self._response_middleware = [] self._exception_middleware = [] request_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: try: mw_module, mw_classname = middleware_path.rsplit('.', 1) except ValueError: raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) try: mod = import_module(mw_module) except ImportError, e: raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) try: mw_class = getattr(mod, mw_classname) except AttributeError: raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)) try: mw_instance = mw_class() except exceptions.MiddlewareNotUsed: continue if hasattr(mw_instance, 'process_request'): request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_template_response'): self._template_response_middleware.insert(0, mw_instance.process_template_response) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) # We only assign to this when initialization is complete as it is used # as a flag for initialization being complete. self._request_middleware = request_middleware def get_response(self, request): "Returns an HttpResponse object for the given HttpRequest" from django.core import exceptions, urlresolvers from django.conf import settings try: # Setup default url resolver for this thread, this code is outside # the try/except so we don't get a spurious "unbound local # variable" exception in the event an exception is raised before # resolver is set urlconf = settings.ROOT_URLCONF urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) try: response = None # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if response: break if response is None: if hasattr(request, "urlconf"): # Reset url resolver with a custom urlconf. urlconf = request.urlconf urlresolvers.set_urlconf(urlconf) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) callback, callback_args, callback_kwargs = resolver.resolve( request.path_info) # Apply view middleware for middleware_method in self._view_middleware: response = middleware_method(request, callback, callback_args, callback_kwargs) if response: break if response is None: try: response = callback(request, *callback_args, **callback_kwargs) except Exception, e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. for middleware_method in self._exception_middleware: response = middleware_method(request, e) if response: break if response is None: raise # Complain if the view returned None (a common error). if response is None: try: view_name = callback.func_name # If it's a function except AttributeError: view_name = callback.__class__.__name__ + '.__call__' # If it's a class raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)) # If the response supports deferred rendering, apply template # response middleware and the render the response if hasattr(response, 'render') and callable(response.render): for middleware_method in self._template_response_middleware: response = middleware_method(request, response) response = response.render() except http.Http404, e: logger.warning('Not Found: %s' % request.path, extra={ 'status_code': 404, 'request': request }) if settings.DEBUG: from django.views import debug response = debug.technical_404_response(request, e) else: try: callback, param_dict = resolver.resolve404() response = callback(request, **param_dict) except: try: response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) finally: receivers = signals.got_request_exception.send(sender=self.__class__, request=request) except exceptions.PermissionDenied: logger.warning('Forbidden (Permission denied): %s' % request.path, extra={ 'status_code': 403, 'request': request }) response = http.HttpResponseForbidden('<h1>Permission denied</h1>') except SystemExit: # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise except: # Handle everything else, including SuspiciousOperation, etc. # Get the exception info now, in case another exception is thrown later. receivers = signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) finally: # Reset URLconf for this thread on the way out for complete # isolation of request.urlconf urlresolvers.set_urlconf(None) try: # Apply response middleware, regardless of the response for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) except: # Any exception should be gathered and handled receivers = signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) return response def handle_uncaught_exception(self, request, resolver, exc_info): """ Processing for any otherwise uncaught exceptions (those that will generate HTTP 500 responses). Can be overridden by subclasses who want customised 500 handling. Be *very* careful when overriding this because the error could be caused by anything, so assuming something like the database is always available would be an error. """ from django.conf import settings if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise if settings.DEBUG: from django.views import debug return debug.technical_500_response(request, *exc_info) logger.error('Internal Server Error: %s' % request.path, exc_info=exc_info, extra={ 'status_code': 500, 'request':request } ) # If Http500 handler is not installed, re-raise last exception if resolver.urlconf_module is None: raise exc_info[1], None, exc_info[2] # Return an HttpResponse that displays a friendly error message. callback, param_dict = resolver.resolve500() return callback(request, **param_dict) def apply_response_fixes(self, request, response): """ Applies each of the functions in self.response_fixes to the request and response, modifying the response in the process. Returns the new response. """ for func in self.response_fixes: response = func(request, response) return response def get_script_name(environ): """ Returns the equivalent of the HTTP request's SCRIPT_NAME environment variable. If Apache mod_rewrite has been used, returns what would have been the script name prior to any rewriting (so it's the script name as seen from the client's perspective), unless DJANGO_USE_POST_REWRITE is set (to anything). """ from django.conf import settings if settings.FORCE_SCRIPT_NAME is not None: return force_unicode(settings.FORCE_SCRIPT_NAME) # If Apache's mod_rewrite had a whack at the URL, Apache set either # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any # rewrites. Unfortunately not every Web server (lighttpd!) passes this # information through all the time, so FORCE_SCRIPT_NAME, above, is still # needed. script_url = environ.get('SCRIPT_URL', u'') if not script_url: script_url = environ.get('REDIRECT_URL', u'') if script_url: return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))]) return force_unicode(environ.get('SCRIPT_NAME', u''))
Python
from pprint import pformat import sys from threading import Lock try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import socket from django import http from django.core import signals from django.core.handlers import base from django.core.urlresolvers import set_script_prefix from django.utils import datastructures from django.utils.encoding import force_unicode, iri_to_uri from django.utils.log import getLogger logger = getLogger('django.request') # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html STATUS_CODE_TEXT = { 100: 'CONTINUE', 101: 'SWITCHING PROTOCOLS', 200: 'OK', 201: 'CREATED', 202: 'ACCEPTED', 203: 'NON-AUTHORITATIVE INFORMATION', 204: 'NO CONTENT', 205: 'RESET CONTENT', 206: 'PARTIAL CONTENT', 300: 'MULTIPLE CHOICES', 301: 'MOVED PERMANENTLY', 302: 'FOUND', 303: 'SEE OTHER', 304: 'NOT MODIFIED', 305: 'USE PROXY', 306: 'RESERVED', 307: 'TEMPORARY REDIRECT', 400: 'BAD REQUEST', 401: 'UNAUTHORIZED', 402: 'PAYMENT REQUIRED', 403: 'FORBIDDEN', 404: 'NOT FOUND', 405: 'METHOD NOT ALLOWED', 406: 'NOT ACCEPTABLE', 407: 'PROXY AUTHENTICATION REQUIRED', 408: 'REQUEST TIMEOUT', 409: 'CONFLICT', 410: 'GONE', 411: 'LENGTH REQUIRED', 412: 'PRECONDITION FAILED', 413: 'REQUEST ENTITY TOO LARGE', 414: 'REQUEST-URI TOO LONG', 415: 'UNSUPPORTED MEDIA TYPE', 416: 'REQUESTED RANGE NOT SATISFIABLE', 417: 'EXPECTATION FAILED', 500: 'INTERNAL SERVER ERROR', 501: 'NOT IMPLEMENTED', 502: 'BAD GATEWAY', 503: 'SERVICE UNAVAILABLE', 504: 'GATEWAY TIMEOUT', 505: 'HTTP VERSION NOT SUPPORTED', } class LimitedStream(object): ''' LimitedStream wraps another stream in order to not allow reading from it past specified amount of bytes. ''' def __init__(self, stream, limit, buf_size=64 * 1024 * 1024): self.stream = stream self.remaining = limit self.buffer = '' self.buf_size = buf_size def _read_limited(self, size=None): if size is None or size > self.remaining: size = self.remaining if size == 0: return '' result = self.stream.read(size) self.remaining -= len(result) return result def read(self, size=None): if size is None: result = self.buffer + self._read_limited() self.buffer = '' elif size < len(self.buffer): result = self.buffer[:size] self.buffer = self.buffer[size:] else: # size >= len(self.buffer) result = self.buffer + self._read_limited(size - len(self.buffer)) self.buffer = '' return result def readline(self, size=None): while '\n' not in self.buffer and \ (size is None or len(self.buffer) < size): if size: # since size is not None here, len(self.buffer) < size chunk = self._read_limited(size - len(self.buffer)) else: chunk = self._read_limited() if not chunk: break self.buffer += chunk sio = StringIO(self.buffer) if size: line = sio.readline(size) else: line = sio.readline() self.buffer = sio.read() return line class WSGIRequest(http.HttpRequest): def __init__(self, environ): script_name = base.get_script_name(environ) path_info = force_unicode(environ.get('PATH_INFO', u'/')) if not path_info or path_info == script_name: # Sometimes PATH_INFO exists, but is empty (e.g. accessing # the SCRIPT_NAME URL without a trailing slash). We really need to # operate as if they'd requested '/'. Not amazingly nice to force # the path like this, but should be harmless. # # (The comparison of path_info to script_name is to work around an # apparent bug in flup 1.0.1. Se Django ticket #8490). path_info = u'/' self.environ = environ self.path_info = path_info self.path = '%s%s' % (script_name, path_info) self.META = environ self.META['PATH_INFO'] = path_info self.META['SCRIPT_NAME'] = script_name self.method = environ['REQUEST_METHOD'].upper() self._post_parse_error = False if type(socket._fileobject) is type and isinstance(self.environ['wsgi.input'], socket._fileobject): # Under development server 'wsgi.input' is an instance of # socket._fileobject which hangs indefinitely on reading bytes past # available count. To prevent this it's wrapped in LimitedStream # that doesn't read past Content-Length bytes. # # This is not done for other kinds of inputs (like flup's FastCGI # streams) beacuse they don't suffer from this problem and we can # avoid using another wrapper with its own .read and .readline # implementation. # # The type check is done because for some reason, AppEngine # implements _fileobject as a function, not a class. try: content_length = int(self.environ.get('CONTENT_LENGTH', 0)) except (ValueError, TypeError): content_length = 0 self._stream = LimitedStream(self.environ['wsgi.input'], content_length) else: self._stream = self.environ['wsgi.input'] self._read_started = False def __repr__(self): # Since this is called as part of error handling, we need to be very # robust against potentially malformed input. try: get = pformat(self.GET) except: get = '<could not parse>' if self._post_parse_error: post = '<could not parse>' else: try: post = pformat(self.POST) except: post = '<could not parse>' try: cookies = pformat(self.COOKIES) except: cookies = '<could not parse>' try: meta = pformat(self.META) except: meta = '<could not parse>' return '<WSGIRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \ (get, post, cookies, meta) def get_full_path(self): # RFC 3986 requires query string arguments to be in the ASCII range. # Rather than crash if this doesn't happen, we encode defensively. return '%s%s' % (self.path, self.environ.get('QUERY_STRING', '') and ('?' + iri_to_uri(self.environ.get('QUERY_STRING', ''))) or '') def is_secure(self): return 'wsgi.url_scheme' in self.environ \ and self.environ['wsgi.url_scheme'] == 'https' def _get_request(self): if not hasattr(self, '_request'): self._request = datastructures.MergeDict(self.POST, self.GET) return self._request def _get_get(self): if not hasattr(self, '_get'): # The WSGI spec says 'QUERY_STRING' may be absent. self._get = http.QueryDict(self.environ.get('QUERY_STRING', ''), encoding=self._encoding) return self._get def _set_get(self, get): self._get = get def _get_post(self): if not hasattr(self, '_post'): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_cookies(self): if not hasattr(self, '_cookies'): self._cookies = http.parse_cookie(self.environ.get('HTTP_COOKIE', '')) return self._cookies def _set_cookies(self, cookies): self._cookies = cookies def _get_files(self): if not hasattr(self, '_files'): self._load_post_and_files() return self._files GET = property(_get_get, _set_get) POST = property(_get_post, _set_post) COOKIES = property(_get_cookies, _set_cookies) FILES = property(_get_files) REQUEST = property(_get_request) class WSGIHandler(base.BaseHandler): initLock = Lock() request_class = WSGIRequest def __call__(self, environ, start_response): from django.conf import settings # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._request_middleware is None: self.initLock.acquire() try: try: # Check that middleware is still uninitialised. if self._request_middleware is None: self.load_middleware() except: # Unload whatever middleware we got self._request_middleware = None raise finally: self.initLock.release() set_script_prefix(base.get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: try: request = self.request_class(environ) except UnicodeDecodeError: logger.warning('Bad Request (UnicodeDecodeError)', exc_info=sys.exc_info(), extra={ 'status_code': 400, } ) response = http.HttpResponseBadRequest() else: response = self.get_response(request) finally: signals.request_finished.send(sender=self.__class__) try: status_text = STATUS_CODE_TEXT[response.status_code] except KeyError: status_text = 'UNKNOWN STATUS CODE' status = '%s %s' % (response.status_code, status_text) response_headers = [(str(k), str(v)) for k, v in response.items()] for c in response.cookies.values(): response_headers.append(('Set-Cookie', str(c.output(header='')))) start_response(status, response_headers) return response
Python
""" This module converts requested URLs to callback view functions. RegexURLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a tuple in this format: (view_function, function_args, function_kwargs) """ import re from threading import local from django.http import Http404 from django.conf import settings from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.utils.datastructures import MultiValueDict from django.utils.encoding import iri_to_uri, force_unicode, smart_str from django.utils.functional import memoize from django.utils.importlib import import_module from django.utils.regex_helper import normalize _resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances. _callable_cache = {} # Maps view and url pattern names to their view functions. # SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for # the current thread (which is the only one we ever access), it is assumed to # be empty. _prefixes = local() # Overridden URLconfs for each thread are stored here. _urlconfs = local() class ResolverMatch(object): def __init__(self, func, args, kwargs, url_name=None, app_name=None, namespaces=None): self.func = func self.args = args self.kwargs = kwargs self.app_name = app_name if namespaces: self.namespaces = [x for x in namespaces if x] else: self.namespaces = [] if not url_name: if not hasattr(func, '__name__'): # An instance of a callable class url_name = '.'.join([func.__class__.__module__, func.__class__.__name__]) else: # A function url_name = '.'.join([func.__module__, func.__name__]) self.url_name = url_name def namespace(self): return ':'.join(self.namespaces) namespace = property(namespace) def view_name(self): return ':'.join([ x for x in [ self.namespace, self.url_name ] if x ]) view_name = property(view_name) def __getitem__(self, index): return (self.func, self.args, self.kwargs)[index] def __repr__(self): return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name='%s', app_name='%s', namespace='%s')" % ( self.func, self.args, self.kwargs, self.url_name, self.app_name, self.namespace) class Resolver404(Http404): pass class NoReverseMatch(Exception): # Don't make this raise an error when used in a template. silent_variable_failure = True def get_callable(lookup_view, can_fail=False): """ Convert a string version of a function name to the callable object. If the lookup_view is not an import path, it is assumed to be a URL pattern label and the original string is returned. If can_fail is True, lookup_view might be a URL pattern label, so errors during the import fail and the string is returned. """ if not callable(lookup_view): try: # Bail early for non-ASCII strings (they can't be functions). lookup_view = lookup_view.encode('ascii') mod_name, func_name = get_mod_func(lookup_view) if func_name != '': lookup_view = getattr(import_module(mod_name), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) except (ImportError, AttributeError): if not can_fail: raise except UnicodeEncodeError: pass return lookup_view get_callable = memoize(get_callable, _callable_cache, 1) def get_resolver(urlconf): if urlconf is None: from django.conf import settings urlconf = settings.ROOT_URLCONF return RegexURLResolver(r'^/', urlconf) get_resolver = memoize(get_resolver, _resolver_cache, 1) def get_mod_func(callback): # Converts 'django.views.news.stories.story_detail' to # ['django.views.news.stories', 'story_detail'] try: dot = callback.rindex('.') except ValueError: return callback, '' return callback[:dot], callback[dot+1:] class RegexURLPattern(object): def __init__(self, regex, callback, default_args=None, name=None): # regex is a string representing a regular expression. # callback is either a string like 'foo.views.news.stories.story_detail' # which represents the path to a module and a view function name, or a # callable object (view). self.regex = re.compile(regex, re.UNICODE) if callable(callback): self._callback = callback else: self._callback = None self._callback_str = callback self.default_args = default_args or {} self.name = name def __repr__(self): return '<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern) def add_prefix(self, prefix): """ Adds the prefix string to a string-based callback. """ if not prefix or not hasattr(self, '_callback_str'): return self._callback_str = prefix + '.' + self._callback_str def resolve(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. kwargs = match.groupdict() if kwargs: args = () else: args = match.groups() # In both cases, pass any extra_kwargs as **kwargs. kwargs.update(self.default_args) return ResolverMatch(self.callback, args, kwargs, self.name) def _get_callback(self): if self._callback is not None: return self._callback try: self._callback = get_callable(self._callback_str) except ImportError, e: mod_name, _ = get_mod_func(self._callback_str) raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e))) except AttributeError, e: mod_name, func_name = get_mod_func(self._callback_str) raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))) return self._callback callback = property(_get_callback) class RegexURLResolver(object): def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None): # regex is a string representing a regular expression. # urlconf_name is a string representing the module containing URLconfs. self.regex = re.compile(regex, re.UNICODE) self.urlconf_name = urlconf_name if not isinstance(urlconf_name, basestring): self._urlconf_module = self.urlconf_name self.callback = None self.default_kwargs = default_kwargs or {} self.namespace = namespace self.app_name = app_name self._reverse_dict = None self._namespace_dict = None self._app_dict = None def __repr__(self): return '<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern) def _populate(self): lookups = MultiValueDict() namespaces = {} apps = {} for pattern in reversed(self.url_patterns): p_pattern = pattern.regex.pattern if p_pattern.startswith('^'): p_pattern = p_pattern[1:] if isinstance(pattern, RegexURLResolver): if pattern.namespace: namespaces[pattern.namespace] = (p_pattern, pattern) if pattern.app_name: apps.setdefault(pattern.app_name, []).append(pattern.namespace) else: parent = normalize(pattern.regex.pattern) for name in pattern.reverse_dict: for matches, pat in pattern.reverse_dict.getlist(name): new_matches = [] for piece, p_args in parent: new_matches.extend([(piece + suffix, p_args + args) for (suffix, args) in matches]) lookups.appendlist(name, (new_matches, p_pattern + pat)) for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items(): namespaces[namespace] = (p_pattern + prefix, sub_pattern) for app_name, namespace_list in pattern.app_dict.items(): apps.setdefault(app_name, []).extend(namespace_list) else: bits = normalize(p_pattern) lookups.appendlist(pattern.callback, (bits, p_pattern)) if pattern.name is not None: lookups.appendlist(pattern.name, (bits, p_pattern)) self._reverse_dict = lookups self._namespace_dict = namespaces self._app_dict = apps def _get_reverse_dict(self): if self._reverse_dict is None: self._populate() return self._reverse_dict reverse_dict = property(_get_reverse_dict) def _get_namespace_dict(self): if self._namespace_dict is None: self._populate() return self._namespace_dict namespace_dict = property(_get_namespace_dict) def _get_app_dict(self): if self._app_dict is None: self._populate() return self._app_dict app_dict = property(_get_app_dict) def resolve(self, path): tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404, e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([[pattern] + t for t in sub_tried]) else: tried.append([pattern]) else: if sub_match: sub_match_dict = dict([(smart_str(k), v) for k, v in match.groupdict().items()]) sub_match_dict.update(self.default_kwargs) for k, v in sub_match.kwargs.iteritems(): sub_match_dict[smart_str(k)] = v return ResolverMatch(sub_match.func, sub_match.args, sub_match_dict, sub_match.url_name, self.app_name or sub_match.app_name, [self.namespace] + sub_match.namespaces) tried.append([pattern]) raise Resolver404({'tried': tried, 'path': new_path}) raise Resolver404({'path' : path}) def _get_urlconf_module(self): try: return self._urlconf_module except AttributeError: self._urlconf_module = import_module(self.urlconf_name) return self._urlconf_module urlconf_module = property(_get_urlconf_module) def _get_url_patterns(self): patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) try: iter(patterns) except TypeError: raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name) return patterns url_patterns = property(_get_url_patterns) def _resolve_special(self, view_type): callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) if not callback: # No handler specified in file; use default # Lazy import, since urls.defaults imports this file from django.conf.urls import defaults callback = getattr(defaults, 'handler%s' % view_type) try: return get_callable(callback), {} except (ImportError, AttributeError), e: raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, str(e))) def resolve404(self): return self._resolve_special('404') def resolve500(self): return self._resolve_special('500') def reverse(self, lookup_view, *args, **kwargs): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") try: lookup_view = get_callable(lookup_view, True) except (ImportError, AttributeError), e: raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e)) possibilities = self.reverse_dict.getlist(lookup_view) for possibility, pattern in possibilities: for result, params in possibility: if args: if len(args) != len(params): continue unicode_args = [force_unicode(val) for val in args] candidate = result % dict(zip(params, unicode_args)) else: if set(kwargs.keys()) != set(params): continue unicode_kwargs = dict([(k, force_unicode(v)) for (k, v) in kwargs.items()]) candidate = result % unicode_kwargs if re.search(u'^%s' % pattern, candidate, re.UNICODE): return candidate # lookup_view can be URL label, or dotted path, or callable, Any of # these can be passed in at the top, but callables are not friendly in # error messages. m = getattr(lookup_view, '__module__', None) n = getattr(lookup_view, '__name__', None) if m is not None and n is not None: lookup_view_s = "%s.%s" % (m, n) else: lookup_view_s = lookup_view raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword " "arguments '%s' not found." % (lookup_view_s, args, kwargs)) def resolve(path, urlconf=None): if urlconf is None: urlconf = get_urlconf() return get_resolver(urlconf).resolve(path) def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} if prefix is None: prefix = get_script_prefix() if not isinstance(viewname, basestring): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] resolved_path = [] while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances (i.e., the default) # so just pick the first instance as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) prefix = prefix + extra except KeyError, key: if resolved_path: raise NoReverseMatch("%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) return iri_to_uri(u'%s%s' % (prefix, resolver.reverse(view, *args, **kwargs))) def clear_url_caches(): global _resolver_cache global _callable_cache _resolver_cache.clear() _callable_cache.clear() def set_script_prefix(prefix): """ Sets the script prefix for the current thread. """ if not prefix.endswith('/'): prefix += '/' _prefixes.value = prefix def get_script_prefix(): """ Returns the currently active script prefix. Useful for client code that wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner). """ return getattr(_prefixes, "value", u'/') def set_urlconf(urlconf_name): """ Sets the URLconf for the current thread (overriding the default one in settings). Set to None to revert back to the default. """ if urlconf_name: _urlconfs.value = urlconf_name else: if hasattr(_urlconfs, "value"): del _urlconfs.value def get_urlconf(default=None): """ Returns the root URLconf to use for the current thread if it has been changed from the default one. """ return getattr(_urlconfs, "value", default)
Python
from django.dispatch import Signal request_started = Signal() request_finished = Signal() got_request_exception = Signal(providing_args=["request"])
Python
from math import ceil class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass class Paginator(object): def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True): self.object_list = object_list self.per_page = per_page self.orphans = orphans self.allow_empty_first_page = allow_empty_first_page self._num_pages = self._count = None def validate_number(self, number): "Validates the given 1-based page number." try: number = int(number) except ValueError: raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('That page number is less than 1') if number > self.num_pages: if number == 1 and self.allow_empty_first_page: pass else: raise EmptyPage('That page contains no results') return number def page(self, number): "Returns a Page object for the given 1-based page number." number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return Page(self.object_list[bottom:top], number, self) def _get_count(self): "Returns the total number of objects, across all pages." if self._count is None: try: self._count = self.object_list.count() except (AttributeError, TypeError): # AttributeError if object_list has no count() method. # TypeError if object_list.count() requires arguments # (i.e. is of type list). self._count = len(self.object_list) return self._count count = property(_get_count) def _get_num_pages(self): "Returns the total number of pages." if self._num_pages is None: if self.count == 0 and not self.allow_empty_first_page: self._num_pages = 0 else: hits = max(1, self.count - self.orphans) self._num_pages = int(ceil(hits / float(self.per_page))) return self._num_pages num_pages = property(_get_num_pages) def _get_page_range(self): """ Returns a 1-based range of pages for iterating through within a template for loop. """ return range(1, self.num_pages + 1) page_range = property(_get_page_range) QuerySetPaginator = Paginator # For backwards-compatibility. class Page(object): def __init__(self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def __repr__(self): return '<Page %s of %s>' % (self.number, self.paginator.num_pages) def has_next(self): return self.number < self.paginator.num_pages def has_previous(self): return self.number > 1 def has_other_pages(self): return self.has_previous() or self.has_next() def next_page_number(self): return self.number + 1 def previous_page_number(self): return self.number - 1 def start_index(self): """ Returns the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 def end_index(self): """ Returns the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page
Python
""" FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol. Uses the flup python package: http://www.saddi.com/software/flup/ This is a adaptation of the flup package to add FastCGI server support to run Django apps from Web servers that support the FastCGI protocol. This module can be run standalone or from the django-admin / manage.py scripts using the "runfcgi" directive. Run with the extra option "help" for a list of additional options you can pass to this server. """ from django.utils import importlib import sys, os __version__ = "0.1" __all__ = ["runfastcgi"] FASTCGI_HELP = r""" Run this project as a fastcgi (or some other protocol supported by flup) application. To do this, the flup package from http://www.saddi.com/software/flup/ is required. runfcgi [options] [fcgi settings] Optional Fcgi settings: (setting=value) protocol=PROTOCOL fcgi, scgi, ajp, ... (default fcgi) host=HOSTNAME hostname to listen on. port=PORTNUM port to listen on. socket=FILE UNIX socket to listen on. method=IMPL prefork or threaded (default prefork). maxrequests=NUMBER number of requests a child handles before it is killed and a new child is forked (0 = no limit). maxspare=NUMBER max number of spare processes / threads. minspare=NUMBER min number of spare processes / threads. maxchildren=NUMBER hard limit number of processes / threads. daemonize=BOOL whether to detach from terminal. pidfile=FILE write the spawned process-id to this file. workdir=DIRECTORY change to this directory when daemonizing. debug=BOOL set to true to enable flup tracebacks. outlog=FILE write stdout to this file. errlog=FILE write stderr to this file. umask=UMASK umask to use when daemonizing, in octal notation (default 022). Examples: Run a "standard" fastcgi process on a file-descriptor (for Web servers which spawn your processes for you) $ manage.py runfcgi method=threaded Run a scgi server on a TCP host/port $ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025 Run a fastcgi server on a UNIX domain socket (posix platforms only) $ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock Run a fastCGI as a daemon and write the spawned PID in a file $ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \ daemonize=true pidfile=/var/run/django-fcgi.pid """ FASTCGI_OPTIONS = { 'protocol': 'fcgi', 'host': None, 'port': None, 'socket': None, 'method': 'fork', 'daemonize': None, 'workdir': '/', 'pidfile': None, 'maxspare': 5, 'minspare': 2, 'maxchildren': 50, 'maxrequests': 0, 'debug': None, 'outlog': None, 'errlog': None, 'umask': None, } def fastcgi_help(message=None): print FASTCGI_HELP if message: print message return False def runfastcgi(argset=[], **kwargs): options = FASTCGI_OPTIONS.copy() options.update(kwargs) for x in argset: if "=" in x: k, v = x.split('=', 1) else: k, v = x, True options[k.lower()] = v if "help" in options: return fastcgi_help() try: import flup except ImportError, e: print >> sys.stderr, "ERROR: %s" % e print >> sys.stderr, " Unable to load the flup package. In order to run django" print >> sys.stderr, " as a FastCGI application, you will need to get flup from" print >> sys.stderr, " http://www.saddi.com/software/flup/ If you've already" print >> sys.stderr, " installed flup, then make sure you have it in your PYTHONPATH." return False flup_module = 'server.' + options['protocol'] if options['method'] in ('prefork', 'fork'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxChildren': int(options["maxchildren"]), 'maxRequests': int(options["maxrequests"]), } flup_module += '_fork' elif options['method'] in ('thread', 'threaded'): wsgi_opts = { 'maxSpare': int(options["maxspare"]), 'minSpare': int(options["minspare"]), 'maxThreads': int(options["maxchildren"]), } else: return fastcgi_help("ERROR: Implementation must be one of prefork or thread.") wsgi_opts['debug'] = options['debug'] is not None try: module = importlib.import_module('.%s' % flup_module, 'flup') WSGIServer = module.WSGIServer except: print "Can't import flup." + flup_module return False # Prep up and go from django.core.handlers.wsgi import WSGIHandler if options["host"] and options["port"] and not options["socket"]: wsgi_opts['bindAddress'] = (options["host"], int(options["port"])) elif options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = options["socket"] elif not options["socket"] and not options["host"] and not options["port"]: wsgi_opts['bindAddress'] = None else: return fastcgi_help("Invalid combination of host, port, socket.") if options["daemonize"] is None: # Default to daemonizing if we're running on a socket/named pipe. daemonize = (wsgi_opts['bindAddress'] is not None) else: if options["daemonize"].lower() in ('true', 'yes', 't'): daemonize = True elif options["daemonize"].lower() in ('false', 'no', 'f'): daemonize = False else: return fastcgi_help("ERROR: Invalid option for daemonize parameter.") daemon_kwargs = {} if options['outlog']: daemon_kwargs['out_log'] = options['outlog'] if options['errlog']: daemon_kwargs['err_log'] = options['errlog'] if options['umask']: daemon_kwargs['umask'] = int(options['umask'], 8) if daemonize: from django.utils.daemonize import become_daemon become_daemon(our_home_dir=options["workdir"], **daemon_kwargs) if options["pidfile"]: fp = open(options["pidfile"], "w") fp.write("%d\n" % os.getpid()) fp.close() WSGIServer(WSGIHandler(), **wsgi_opts).run() if __name__ == '__main__': runfastcgi(sys.argv[1:])
Python
""" BaseHTTPServer that implements the Python WSGI protocol (PEP 333, rev 1.21). Adapted from wsgiref.simple_server: http://svn.eby-sarna.com/wsgiref/ This is a simple server for use in testing or debugging Django apps. It hasn't been reviewed for security issues. Don't use it for production use. """ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import os import re import socket import sys import urllib import warnings from django.core.management.color import color_style from django.utils.http import http_date from django.utils._os import safe_join from django.views import static from django.contrib.staticfiles import handlers __version__ = "0.1" __all__ = ['WSGIServer','WSGIRequestHandler'] server_version = "WSGIServer/" + __version__ sys_version = "Python/" + sys.version.split()[0] software_version = server_version + ' ' + sys_version class WSGIServerException(Exception): pass class FileWrapper(object): """Wrapper to convert file-like objects to iterables""" def __init__(self, filelike, blksize=8192): self.filelike = filelike self.blksize = blksize if hasattr(filelike,'close'): self.close = filelike.close def __getitem__(self,key): data = self.filelike.read(self.blksize) if data: return data raise IndexError def __iter__(self): return self def next(self): data = self.filelike.read(self.blksize) if data: return data raise StopIteration # Regular expression that matches `special' characters in parameters, the # existence of which force quoting of the parameter value. tspecials = re.compile(r'[ \(\)<>@,;:\\"/\[\]\?=]') def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: if quote or tspecials.search(value): value = value.replace('\\', '\\\\').replace('"', r'\"') return '%s="%s"' % (param, value) else: return '%s=%s' % (param, value) else: return param class Headers(object): """Manage a collection of HTTP response headers""" def __init__(self,headers): if not isinstance(headers, list): raise TypeError("Headers must be a list of name/value tuples") self._headers = headers def __len__(self): """Return the total number of headers, including duplicates.""" return len(self._headers) def __setitem__(self, name, val): """Set the value of a header.""" del self[name] self._headers.append((name, val)) def __delitem__(self,name): """Delete all occurrences of a header, if present. Does *not* raise an exception if the header is missing. """ name = name.lower() self._headers[:] = [kv for kv in self._headers if kv[0].lower()<>name] def __getitem__(self,name): """Get the first header value for 'name' Return None if the header is missing instead of raising an exception. Note that if the header appeared multiple times, the first exactly which occurrance gets returned is undefined. Use getall() to get all the values matching a header field name. """ return self.get(name) def has_key(self, name): """Return true if the message contains the header.""" return self.get(name) is not None __contains__ = has_key def get_all(self, name): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no fields exist with the given name, returns an empty list. """ name = name.lower() return [kv[1] for kv in self._headers if kv[0].lower()==name] def get(self,name,default=None): """Get the first header value for 'name', or return 'default'""" name = name.lower() for k,v in self._headers: if k.lower()==name: return v return default def keys(self): """Return a list of all the header field names. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [k for k, v in self._headers] def values(self): """Return a list of all header values. These will be sorted in the order they appeared in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [v for k, v in self._headers] def items(self): """Get all the header fields and values. These will be sorted in the order they were in the original header list, or were added to this instance, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return self._headers[:] def __repr__(self): return "Headers(%s)" % `self._headers` def __str__(self): """str() returns the formatted headers, complete with end line, suitable for direct HTTP transmission.""" return '\r\n'.join(["%s: %s" % kv for kv in self._headers]+['','']) def setdefault(self,name,value): """Return first matching header value for 'name', or 'value' If there is no header named 'name', add a new header with name 'name' and value 'value'.""" result = self.get(name) if result is None: self._headers.append((name,value)) return value else: return result def add_header(self, _name, _value, **_params): """Extended header setting. _name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. Example: h.add_header('content-disposition', 'attachment', filename='bud.gif') Note that unlike the corresponding 'email.Message' method, this does *not* handle '(charset, language, value)' tuples: all values must be strings or None. """ parts = [] if _value is not None: parts.append(_value) for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) self._headers.append((_name, "; ".join(parts))) def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http' _hop_headers = { 'connection':1, 'keep-alive':1, 'proxy-authenticate':1, 'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1, 'upgrade':1 } def is_hop_by_hop(header_name): """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header""" return header_name.lower() in _hop_headers class ServerHandler(object): """Manage the invocation of a WSGI application""" # Configuration parameters; can override per-subclass or per-instance wsgi_version = (1,0) wsgi_multithread = True wsgi_multiprocess = True wsgi_run_once = False origin_server = True # We are transmitting direct to client http_version = "1.0" # Version that should be used for response server_software = software_version # os_environ is used to supply configuration from the OS environment: # by default it's a copy of 'os.environ' as of import time, but you can # override this in e.g. your __init__ method. os_environ = dict(os.environ.items()) # Collaborator classes wsgi_file_wrapper = FileWrapper # set to None to disable headers_class = Headers # must be a Headers-like class # Error handling (also per-subclass or per-instance) traceback_limit = None # Print entire traceback to self.get_stderr() error_status = "500 INTERNAL SERVER ERROR" error_headers = [('Content-Type','text/plain')] # State variables (don't mess with these) status = result = None headers_sent = False headers = None bytes_sent = 0 def __init__(self, stdin, stdout, stderr, environ, multithread=True, multiprocess=False): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.base_env = environ self.wsgi_multithread = multithread self.wsgi_multiprocess = multiprocess def run(self, application): """Invoke the application""" # Note to self: don't move the close()! Asynchronous servers shouldn't # call close() from finish_response(), so if you close() anywhere but # the double-error branch here, you'll break asynchronous servers by # prematurely closing. Async servers must return from 'run()' without # closing if there might still be output to iterate over. try: self.setup_environ() self.result = application(self.environ, self.start_response) self.finish_response() except: try: self.handle_error() except: # If we get an error handling an error, just give up already! self.close() raise # ...and let the actual server figure it out. def setup_environ(self): """Set up the environment for one request""" env = self.environ = self.os_environ.copy() self.add_cgi_vars() env['wsgi.input'] = self.get_stdin() env['wsgi.errors'] = self.get_stderr() env['wsgi.version'] = self.wsgi_version env['wsgi.run_once'] = self.wsgi_run_once env['wsgi.url_scheme'] = self.get_scheme() env['wsgi.multithread'] = self.wsgi_multithread env['wsgi.multiprocess'] = self.wsgi_multiprocess if self.wsgi_file_wrapper is not None: env['wsgi.file_wrapper'] = self.wsgi_file_wrapper if self.origin_server and self.server_software: env.setdefault('SERVER_SOFTWARE',self.server_software) def finish_response(self): """ Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call 'self.close()' once the response is finished. """ if not self.result_is_file() or not self.sendfile(): for data in self.result: self.write(data) self.finish_content() self.close() def get_scheme(self): """Return the URL scheme being used""" return guess_scheme(self.environ) def set_content_length(self): """Compute Content-Length or switch to chunked encoding if possible""" try: blocks = len(self.result) except (TypeError, AttributeError, NotImplementedError): pass else: if blocks==1: self.headers['Content-Length'] = str(self.bytes_sent) return # XXX Try for chunked encoding if origin server and client is 1.1 def cleanup_headers(self): """Make any necessary header changes or defaults Subclasses can extend this to add other defaults. """ if 'Content-Length' not in self.headers: self.set_content_length() def start_response(self, status, headers,exc_info=None): """'start_response()' callable as specified by PEP 333""" if exc_info: try: if self.headers_sent: # Re-raise original exception if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None # avoid dangling circular ref elif self.headers is not None: raise AssertionError("Headers already set!") assert isinstance(status, str),"Status must be a string" assert len(status)>=4,"Status must be at least 4 characters" assert int(status[:3]),"Status message must begin w/3-digit code" assert status[3]==" ", "Status message must have a space after code" if __debug__: for name,val in headers: assert isinstance(name, str),"Header names must be strings" assert isinstance(val, str),"Header values must be strings" assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed" self.status = status self.headers = self.headers_class(headers) return self.write def send_preamble(self): """Transmit version/status/date/server, via self._write()""" if self.origin_server: if self.client_is_modern(): self._write('HTTP/%s %s\r\n' % (self.http_version,self.status)) if 'Date' not in self.headers: self._write( 'Date: %s\r\n' % http_date() ) if self.server_software and 'Server' not in self.headers: self._write('Server: %s\r\n' % self.server_software) else: self._write('Status: %s\r\n' % self.status) def write(self, data): """'write()' callable as specified by PEP 333""" assert isinstance(data, str), "write() argument must be string" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: self.bytes_sent += len(data) # XXX check Content-Length and truncate if too many bytes written? # If data is too large, socket will choke, so write chunks no larger # than 32MB at a time. length = len(data) if length > 33554432: offset = 0 while offset < length: chunk_size = min(33554432, length) self._write(data[offset:offset+chunk_size]) self._flush() offset += chunk_size else: self._write(data) self._flush() def sendfile(self): """Platform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application's return iterable ('self.result') is an instance of 'self.wsgi_file_wrapper'. This method should return a true value if it was able to actually transmit the wrapped file-like object using a platform-specific approach. It should return a false value if normal iteration should be used instead. An exception can be raised to indicate that transmission was attempted, but failed. NOTE: this method should call 'self.send_headers()' if 'self.headers_sent' is false and it is going to attempt direct transmission of the file1. """ return False # No platform-specific transmission by default def finish_content(self): """Ensure headers and content have both been sent""" if not self.headers_sent: self.headers['Content-Length'] = "0" self.send_headers() else: pass # XXX check if content-length was too short? def close(self): try: self.request_handler.log_request(self.status.split(' ',1)[0], self.bytes_sent) finally: try: if hasattr(self.result,'close'): self.result.close() finally: self.result = self.headers = self.status = self.environ = None self.bytes_sent = 0; self.headers_sent = False def send_headers(self): """Transmit headers to the client, via self._write()""" self.cleanup_headers() self.headers_sent = True if not self.origin_server or self.client_is_modern(): self.send_preamble() self._write(str(self.headers)) def result_is_file(self): """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'""" wrapper = self.wsgi_file_wrapper return wrapper is not None and isinstance(self.result,wrapper) def client_is_modern(self): """True if client can accept status and headers""" return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' def log_exception(self,exc_info): """Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. """ try: from traceback import print_exception stderr = self.get_stderr() print_exception( exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr ) stderr.flush() finally: exc_info = None def handle_error(self): """Log current error, and send error output to client if possible""" self.log_exception(sys.exc_info()) if not self.headers_sent: self.result = self.error_output(self.environ, self.start_response) self.finish_response() # XXX else: attempt advanced recovery techniques for HTML or text? def error_output(self, environ, start_response): import traceback start_response(self.error_status, self.error_headers[:], sys.exc_info()) return ['\n'.join(traceback.format_exception(*sys.exc_info()))] # Pure abstract methods; *must* be overridden in subclasses def _write(self,data): self.stdout.write(data) self._write = self.stdout.write def _flush(self): self.stdout.flush() self._flush = self.stdout.flush def get_stdin(self): return self.stdin def get_stderr(self): return self.stderr def add_cgi_vars(self): self.environ.update(self.base_env) class WSGIServer(HTTPServer): """BaseHTTPServer that implements the Python WSGI protocol""" application = None def __init__(self, *args, **kwargs): if kwargs.pop('ipv6', False): self.address_family = socket.AF_INET6 HTTPServer.__init__(self, *args, **kwargs) def server_bind(self): """Override server_bind to store the server name.""" try: HTTPServer.server_bind(self) except Exception, e: raise WSGIServerException(e) self.setup_environ() def setup_environ(self): # Set up base environment env = self.base_environ = {} env['SERVER_NAME'] = self.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PORT'] = str(self.server_port) env['REMOTE_HOST']='' env['CONTENT_LENGTH']='' env['SCRIPT_NAME'] = '' def get_app(self): return self.application def set_app(self,application): self.application = application class WSGIRequestHandler(BaseHTTPRequestHandler): server_version = "WSGIServer/" + __version__ def __init__(self, *args, **kwargs): from django.conf import settings self.admin_media_prefix = settings.ADMIN_MEDIA_PREFIX # We set self.path to avoid crashes in log_message() on unsupported # requests (like "OPTIONS"). self.path = '' self.style = color_style() BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def get_environ(self): env = self.server.base_environ.copy() env['SERVER_PROTOCOL'] = self.request_version env['REQUEST_METHOD'] = self.command if '?' in self.path: path,query = self.path.split('?',1) else: path,query = self.path,'' env['PATH_INFO'] = urllib.unquote(path) env['QUERY_STRING'] = query env['REMOTE_ADDR'] = self.client_address[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length for h in self.headers.headers: k,v = h.split(':',1) k=k.replace('-','_').upper(); v=v.strip() if k in env: continue # skip content length, type,etc. if 'HTTP_'+k in env: env['HTTP_'+k] += ','+v # comma-separate multiple headers else: env['HTTP_'+k] = v return env def get_stderr(self): return sys.stderr def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ()) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app()) def log_message(self, format, *args): # Don't bother logging requests for admin images or the favicon. if self.path.startswith(self.admin_media_prefix) or self.path == '/favicon.ico': return msg = "[%s] %s\n" % (self.log_date_time_string(), format % args) # Utilize terminal colors, if available if args[1][0] == '2': # Put 2XX first, since it should be the common case msg = self.style.HTTP_SUCCESS(msg) elif args[1][0] == '1': msg = self.style.HTTP_INFO(msg) elif args[1] == '304': msg = self.style.HTTP_NOT_MODIFIED(msg) elif args[1][0] == '3': msg = self.style.HTTP_REDIRECT(msg) elif args[1] == '404': msg = self.style.HTTP_NOT_FOUND(msg) elif args[1][0] == '4': msg = self.style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other response msg = self.style.HTTP_SERVER_ERROR(msg) sys.stderr.write(msg) class AdminMediaHandler(handlers.StaticFilesHandler): """ WSGI middleware that intercepts calls to the admin media directory, as defined by the ADMIN_MEDIA_PREFIX setting, and serves those images. Use this ONLY LOCALLY, for development! This hasn't been tested for security and is not super efficient. This is pending for deprecation since 1.3. """ def get_base_dir(self): import django return os.path.join(django.__path__[0], 'contrib', 'admin', 'media') def get_base_url(self): from django.conf import settings from django.core.exceptions import ImproperlyConfigured if not settings.ADMIN_MEDIA_PREFIX: raise ImproperlyConfigured( "The ADMIN_MEDIA_PREFIX setting can't be empty " "when using the AdminMediaHandler, e.g. with runserver.") return settings.ADMIN_MEDIA_PREFIX def file_path(self, url): """ Returns the path to the media file on disk for the given URL. The passed URL is assumed to begin with ``self.base_url``. If the resulting file path is outside the media directory, then a ValueError is raised. """ relative_url = url[len(self.base_url[2]):] relative_path = urllib.url2pathname(relative_url) return safe_join(self.base_dir, relative_path) def serve(self, request): document_root, path = os.path.split(self.file_path(request.path)) return static.serve(request, path, document_root=document_root) def _should_handle(self, path): """ Checks if the path should be handled. Ignores the path if: * the host is provided as part of the base_url * the request's path isn't under the base path """ return path.startswith(self.base_url[2]) and not self.base_url[1] def run(addr, port, wsgi_handler, ipv6=False): server_address = (addr, port) httpd = WSGIServer(server_address, WSGIRequestHandler, ipv6=ipv6) httpd.set_app(wsgi_handler) httpd.serve_forever()
Python
""" Pages in Django can are served up with custom HTTP headers containing useful information about those pages -- namely, the content type and object ID. This module contains utility functions for retrieving and doing interesting things with these special "X-Headers" (so called because the HTTP spec demands that custom headers are prefixed with "X-"). Next time you're at slashdot.org, watch out for X-Fry and X-Bender. :) """ def populate_xheaders(request, response, model, object_id): """ Adds the "X-Object-Type" and "X-Object-Id" headers to the given HttpResponse according to the given model and object_id -- but only if the given HttpRequest object has an IP address within the INTERNAL_IPS setting or if the request is from a logged in staff member. """ from django.conf import settings if (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or (hasattr(request, 'user') and request.user.is_active and request.user.is_staff)): response['X-Object-Type'] = "%s.%s" % (model._meta.app_label, model._meta.object_name.lower()) response['X-Object-Id'] = str(object_id)
Python
import platform import re import urllib2 import urlparse from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode # These values, if given to validate(), will trigger the self.required check. EMPTY_VALUES = (None, '', [], (), {}) try: from django.conf import settings URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT except ImportError: # It's OK if Django settings aren't configured. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)' class RegexValidator(object): regex = '' message = _(u'Enter a valid value.') code = 'invalid' def __init__(self, regex=None, message=None, code=None): if regex is not None: self.regex = regex if message is not None: self.message = message if code is not None: self.code = code if isinstance(self.regex, basestring): self.regex = re.compile(regex) def __call__(self, value): """ Validates that the input matches the regular expression. """ if not self.regex.search(smart_unicode(value)): raise ValidationError(self.message, code=self.code) class URLValidator(RegexValidator): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) def __init__(self, verify_exists=False, validator_user_agent=URL_VALIDATOR_USER_AGENT): super(URLValidator, self).__init__() self.verify_exists = verify_exists self.user_agent = validator_user_agent def __call__(self, value): try: super(URLValidator, self).__call__(value) except ValidationError, e: # Trivial case failed. Try for possible IDN domain if value: value = smart_unicode(value) scheme, netloc, path, query, fragment = urlparse.urlsplit(value) try: netloc = netloc.encode('idna') # IDN -> ACE except UnicodeError: # invalid domain part raise e url = urlparse.urlunsplit((scheme, netloc, path, query, fragment)) super(URLValidator, self).__call__(url) else: raise else: url = value #This is deprecated and will be removed in a future release. if self.verify_exists: headers = { "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "Accept-Language": "en-us,en;q=0.5", "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7", "Connection": "close", "User-Agent": self.user_agent, } url = url.encode('utf-8') broken_error = ValidationError( _(u'This URL appears to be a broken link.'), code='invalid_link') try: req = urllib2.Request(url, None, headers) req.get_method = lambda: 'HEAD' #Create an opener that does not support local file access opener = urllib2.OpenerDirector() #Don't follow redirects, but don't treat them as errors either error_nop = lambda *args, **kwargs: True http_error_processor = urllib2.HTTPErrorProcessor() http_error_processor.http_error_301 = error_nop http_error_processor.http_error_302 = error_nop http_error_processor.http_error_307 = error_nop handlers = [urllib2.UnknownHandler(), urllib2.HTTPHandler(), urllib2.HTTPDefaultErrorHandler(), urllib2.FTPHandler(), http_error_processor] try: import ssl handlers.append(urllib2.HTTPSHandler()) except: #Python isn't compiled with SSL support pass map(opener.add_handler, handlers) if platform.python_version_tuple() >= (2, 6): opener.open(req, timeout=10) else: opener.open(req) except ValueError: raise ValidationError(_(u'Enter a valid URL.'), code='invalid') except: # urllib2.URLError, httplib.InvalidURL, etc. raise broken_error def validate_integer(value): try: int(value) except (ValueError, TypeError), e: raise ValidationError('') class EmailValidator(RegexValidator): def __call__(self, value): try: super(EmailValidator, self).__call__(value) except ValidationError, e: # Trivial case failed. Try for possible IDN domain-part if value and u'@' in value: parts = value.split(u'@') domain_part = parts[-1] try: parts[-1] = parts[-1].encode('idna') except UnicodeError: raise e super(EmailValidator, self).__call__(u'@'.join(parts)) else: raise email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid') slug_re = re.compile(r'^[-\w]+$') validate_slug = RegexValidator(slug_re, _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid') ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$') validate_ipv4_address = RegexValidator(ipv4_re, _(u'Enter a valid IPv4 address.'), 'invalid') comma_separated_int_list_re = re.compile('^[\d,]+$') validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _(u'Enter only digits separated by commas.'), 'invalid') class BaseValidator(object): compare = lambda self, a, b: a is not b clean = lambda self, x: x message = _(u'Ensure this value is %(limit_value)s (it is %(show_value)s).') code = 'limit_value' def __init__(self, limit_value): self.limit_value = limit_value def __call__(self, value): cleaned = self.clean(value) params = {'limit_value': self.limit_value, 'show_value': cleaned} if self.compare(cleaned, self.limit_value): raise ValidationError( self.message % params, code=self.code, params=params, ) class MaxValueValidator(BaseValidator): compare = lambda self, a, b: a > b message = _(u'Ensure this value is less than or equal to %(limit_value)s.') code = 'max_value' class MinValueValidator(BaseValidator): compare = lambda self, a, b: a < b message = _(u'Ensure this value is greater than or equal to %(limit_value)s.') code = 'min_value' class MinLengthValidator(BaseValidator): compare = lambda self, a, b: a < b clean = lambda self, x: len(x) message = _(u'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).') code = 'min_length' class MaxLengthValidator(BaseValidator): compare = lambda self, a, b: a > b clean = lambda self, x: len(x) message = _(u'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).') code = 'max_length'
Python
""" Global Django exception and warning classes. """ class DjangoRuntimeWarning(RuntimeWarning): pass class ObjectDoesNotExist(Exception): "The requested object does not exist" silent_variable_failure = True class MultipleObjectsReturned(Exception): "The query returned multiple objects when only one was expected." pass class SuspiciousOperation(Exception): "The user did something suspicious" pass class PermissionDenied(Exception): "The user did not have permission to do that" pass class ViewDoesNotExist(Exception): "The requested view does not exist" pass class MiddlewareNotUsed(Exception): "This middleware is not used in this server configuration" pass class ImproperlyConfigured(Exception): "Django is somehow improperly configured" pass class FieldError(Exception): """Some kind of problem with a model field.""" pass NON_FIELD_ERRORS = '__all__' class ValidationError(Exception): """An error while validating data.""" def __init__(self, message, code=None, params=None): import operator from django.utils.encoding import force_unicode """ ValidationError can be passed any object that can be printed (usually a string), a list of objects or a dictionary. """ if isinstance(message, dict): self.message_dict = message # Reduce each list of messages into a single list. message = reduce(operator.add, message.values()) if isinstance(message, list): self.messages = [force_unicode(msg) for msg in message] else: self.code = code self.params = params message = force_unicode(message) self.messages = [message] def __str__(self): # This is needed because, without a __str__(), printing an exception # instance would result in this: # AttributeError: ValidationError instance has no attribute 'args' # See http://www.python.org/doc/current/tut/node10.html#handling if hasattr(self, 'message_dict'): return repr(self.message_dict) return repr(self.messages) def __repr__(self): if hasattr(self, 'message_dict'): return 'ValidationError(%s)' % repr(self.message_dict) return 'ValidationError(%s)' % repr(self.messages) def update_error_dict(self, error_dict): if hasattr(self, 'message_dict'): if error_dict: for k, v in self.message_dict.items(): error_dict.setdefault(k, []).extend(v) else: error_dict = self.message_dict else: error_dict[NON_FIELD_ERRORS] = self.messages return error_dict
Python
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_all from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the CREATE TABLE, custom SQL and CREATE INDEX SQL statements for the given model module name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_all(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
Python
from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand, CommandError from django.core import serializers from django.db import connections, router, DEFAULT_DB_ALIAS from django.utils.datastructures import SortedDict from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--format', default='json', dest='format', help='Specifies the output serialization format for fixtures.'), make_option('--indent', default=None, dest='indent', type='int', help='Specifies the indent level to use when pretty-printing output'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load ' 'fixtures into. Defaults to the "default" database.'), make_option('-e', '--exclude', dest='exclude',action='append', default=[], help='An appname or appname.ModelName to exclude (use multiple --exclude to exclude multiple apps/models).'), make_option('-n', '--natural', action='store_true', dest='use_natural_keys', default=False, help='Use natural keys if they are available.'), make_option('-a', '--all', action='store_true', dest='use_base_manager', default=False, help="Use Django's base manager to dump all models stored in the database, including those that would otherwise be filtered or modified by a custom manager."), ) help = ("Output the contents of the database as a fixture of the given " "format (using each model's default manager unless --all is " "specified).") args = '[appname appname.ModelName ...]' def handle(self, *app_labels, **options): from django.db.models import get_app, get_apps, get_models, get_model format = options.get('format','json') indent = options.get('indent',None) using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] excludes = options.get('exclude',[]) show_traceback = options.get('traceback', False) use_natural_keys = options.get('use_natural_keys', False) use_base_manager = options.get('use_base_manager', False) excluded_apps = set() excluded_models = set() for exclude in excludes: if '.' in exclude: app_label, model_name = exclude.split('.', 1) model_obj = get_model(app_label, model_name) if not model_obj: raise CommandError('Unknown model in excludes: %s' % exclude) excluded_models.add(model_obj) else: try: app_obj = get_app(exclude) excluded_apps.add(app_obj) except ImproperlyConfigured: raise CommandError('Unknown app in excludes: %s' % exclude) if len(app_labels) == 0: app_list = SortedDict((app, None) for app in get_apps() if app not in excluded_apps) else: app_list = SortedDict() for label in app_labels: try: app_label, model_label = label.split('.') try: app = get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) if app in excluded_apps: continue model = get_model(app_label, model_label) if model is None: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) if app in app_list.keys(): if app_list[app] and model not in app_list[app]: app_list[app].append(model) else: app_list[app] = [model] except ValueError: # This is just an app - no model qualifier app_label = label try: app = get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) if app in excluded_apps: continue app_list[app] = None # Check that the serialization format exists; this is a shortcut to # avoid collating all the objects and _then_ failing. if format not in serializers.get_public_serializer_formats(): raise CommandError("Unknown serialization format: %s" % format) try: serializers.get_serializer(format) except KeyError: raise CommandError("Unknown serialization format: %s" % format) # Now collate the objects to be serialized. objects = [] for model in sort_dependencies(app_list.items()): if model in excluded_models: continue if not model._meta.proxy and router.allow_syncdb(using, model): if use_base_manager: objects.extend(model._base_manager.using(using).all()) else: objects.extend(model._default_manager.using(using).all()) try: return serializers.serialize(format, objects, indent=indent, use_natural_keys=use_natural_keys) except Exception, e: if show_traceback: raise raise CommandError("Unable to serialize database: %s" % e) def sort_dependencies(app_list): """Sort a list of app,modellist pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. """ from django.db.models import get_model, get_models # Process the list of models, and get the list of dependencies model_dependencies = [] models = set() for app, model_list in app_list: if model_list is None: model_list = get_models(app) for model in model_list: models.add(model) # Add any explicitly defined dependencies if hasattr(model, 'natural_key'): deps = getattr(model.natural_key, 'dependencies', []) if deps: deps = [get_model(*d.split('.')) for d in deps] else: deps = [] # Now add a dependency for any FK or M2M relation with # a model that defines a natural key for field in model._meta.fields: if hasattr(field.rel, 'to'): rel_model = field.rel.to if hasattr(rel_model, 'natural_key'): deps.append(rel_model) for field in model._meta.many_to_many: rel_model = field.rel.to if hasattr(rel_model, 'natural_key'): deps.append(rel_model) model_dependencies.append((model, deps)) model_dependencies.reverse() # Now sort the models to ensure that dependencies are met. This # is done by repeatedly iterating over the input list of models. # If all the dependencies of a given model are in the final list, # that model is promoted to the end of the final list. This process # continues until the input list is empty, or we do a full iteration # over the input models without promoting a model to the final list. # If we do a full iteration without a promotion, that means there are # circular dependencies in the list. model_list = [] while model_dependencies: skipped = [] changed = False while model_dependencies: model, deps = model_dependencies.pop() # If all of the models in the dependency list are either already # on the final model list, or not on the original serialization list, # then we've found another model with all it's dependencies satisfied. found = True for candidate in ((d not in models or d in model_list) for d in deps): if not candidate: found = False if found: model_list.append(model) changed = True else: skipped.append((model, deps)) if not changed: raise CommandError("Can't resolve dependencies for %s in serialized app list." % ', '.join('%s.%s' % (model._meta.app_label, model._meta.object_name) for model, deps in sorted(skipped, key=lambda obj: obj[0].__name__)) ) model_dependencies = skipped return model_list
Python
import os from django.core.management.base import NoArgsCommand from optparse import make_option class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--plain', action='store_true', dest='plain', help='Tells Django to use plain Python, not IPython.'), ) help = "Runs a Python interactive interpreter. Tries to use IPython, if it's available." shells = ['ipython', 'bpython'] requires_model_validation = False def ipython(self): try: from IPython.frontend.terminal.embed import TerminalInteractiveShell shell = TerminalInteractiveShell() shell.mainloop() except ImportError: # IPython < 0.11 # Explicitly pass an empty list as arguments, because otherwise # IPython would use sys.argv from this script. try: from IPython.Shell import IPShell shell = IPShell(argv=[]) shell.mainloop() except ImportError: # IPython not found at all, raise ImportError raise def bpython(self): import bpython bpython.embed() def run_shell(self): for shell in self.shells: try: return getattr(self, shell)() except ImportError: pass raise ImportError def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. from django.db.models.loading import get_models loaded_models = get_models() use_plain = options.get('plain', False) try: if use_plain: # Don't bother loading IPython, because the user wants plain Python. raise ImportError self.run_shell() except ImportError: import code # Set up a dictionary to serve as the environment for the shell, so # that tab completion works on objects that are imported at runtime. # See ticket 5082. imported_objects = {} try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then import user. if not use_plain: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): try: execfile(pythonrc) except NameError: pass # This will import .pythonrc.py as a side-effect import user code.interact(local=imported_objects)
Python
import codecs import os import sys from optparse import make_option from django.core.management.base import BaseCommand, CommandError def has_bom(fn): f = open(fn, 'r') sample = f.read(4) return sample[:3] == '\xef\xbb\xbf' or \ sample.startswith(codecs.BOM_UTF16_LE) or \ sample.startswith(codecs.BOM_UTF16_BE) def compile_messages(stderr, locale=None): basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This script should be run from the Django SVN tree or your project or app tree, or with the settings module specified.") for basedir in basedirs: if locale: basedir = os.path.join(basedir, locale, 'LC_MESSAGES') for dirpath, dirnames, filenames in os.walk(basedir): for f in filenames: if f.endswith('.po'): stderr.write('processing file %s in %s\n' % (f, dirpath)) fn = os.path.join(dirpath, f) if has_bom(fn): raise CommandError("The %s file has a BOM (Byte Order Mark). Django only supports .po files encoded in UTF-8 and without any BOM." % fn) pf = os.path.splitext(fn)[0] # Store the names of the .mo and .po files in an environment # variable, rather than doing a string replacement into the # command, so that we can take advantage of shell quoting, to # quote any malicious characters/escaping. # See http://cyberelk.net/tim/articles/cmdline/ar01s02.html os.environ['djangocompilemo'] = pf + '.mo' os.environ['djangocompilepo'] = pf + '.po' if sys.platform == 'win32': # Different shell-variable syntax cmd = 'msgfmt --check-format -o "%djangocompilemo%" "%djangocompilepo%"' else: cmd = 'msgfmt --check-format -o "$djangocompilemo" "$djangocompilepo"' os.system(cmd) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--locale', '-l', dest='locale', help='The locale to process. Default is to process all.'), ) help = 'Compiles .po files to .mo files for use with builtin gettext support.' requires_model_validation = False can_import_settings = False def handle(self, **options): locale = options.get('locale') compile_messages(self.stderr, locale=locale)
Python
from django.core.management.base import NoArgsCommand def module_to_dict(module, omittable=lambda k: k.startswith('_')): "Converts a module namespace to a Python dictionary. Used by get_settings_diff." return dict([(k, repr(v)) for k, v in module.__dict__.items() if not omittable(k)]) class Command(NoArgsCommand): help = """Displays differences between the current settings.py and Django's default settings. Settings that don't appear in the defaults are followed by "###".""" requires_model_validation = False def handle_noargs(self, **options): # Inspired by Postfix's "postconf -n". from django.conf import settings, global_settings # Because settings are imported lazily, we need to explicitly load them. settings._setup() user_settings = module_to_dict(settings._wrapped) default_settings = module_to_dict(global_settings) output = [] keys = user_settings.keys() keys.sort() for key in keys: if key not in default_settings: output.append("%s = %s ###" % (key, user_settings[key])) elif user_settings[key] != default_settings[key]: output.append("%s = %s" % (key, user_settings[key])) return '\n'.join(output)
Python
import keyword from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS class Command(NoArgsCommand): help = "Introspects the database tables in the given database and outputs a Django model module." option_list = NoArgsCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to ' 'introspect. Defaults to using the "default" database.'), ) requires_model_validation = False db_module = 'django.db' def handle_noargs(self, **options): try: for line in self.handle_inspection(options): self.stdout.write("%s\n" % line) except NotImplementedError: raise CommandError("Database inspection isn't supported for the currently selected database backend.") def handle_inspection(self, options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '') cursor = connection.cursor() yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield "# Feel free to rename the models, but don't rename db_table values or field names." yield "#" yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'" yield "# into your database." yield '' yield 'from %s import models' % self.db_module yield '' for table_name in connection.introspection.get_table_list(cursor): yield 'class %s(models.Model):' % table2model(table_name) try: relations = connection.introspection.get_relations(cursor, table_name) except NotImplementedError: relations = {} try: indexes = connection.introspection.get_indexes(cursor, table_name) except NotImplementedError: indexes = {} for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)): column_name = row[0] att_name = column_name.lower() comment_notes = [] # Holds Field notes, to be displayed in a Python comment. extra_params = {} # Holds Field parameters such as 'db_column'. # If the column name can't be used verbatim as a Python # attribute, set the "db_column" for this Field. if ' ' in att_name or '-' in att_name or keyword.iskeyword(att_name) or column_name != att_name: extra_params['db_column'] = column_name # Modify the field name to make it Python-compatible. if ' ' in att_name: att_name = att_name.replace(' ', '_') comment_notes.append('Field renamed to remove spaces.') if '-' in att_name: att_name = att_name.replace('-', '_') comment_notes.append('Field renamed to remove dashes.') if column_name != att_name: comment_notes.append('Field name made lowercase.') if i in relations: rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1]) field_type = 'ForeignKey(%s' % rel_to if att_name.endswith('_id'): att_name = att_name[:-3] else: extra_params['db_column'] = column_name else: # Calling `get_field_type` to get the field type string and any # additional paramters and notes. field_type, field_params, field_notes = self.get_field_type(connection, table_name, row) extra_params.update(field_params) comment_notes.extend(field_notes) # Add primary_key and unique, if necessary. if column_name in indexes: if indexes[column_name]['primary_key']: extra_params['primary_key'] = True elif indexes[column_name]['unique']: extra_params['unique'] = True field_type += '(' if keyword.iskeyword(att_name): att_name += '_field' comment_notes.append('Field renamed because it was a Python reserved word.') # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}: continue # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row[6]: # If it's NULL... extra_params['blank'] = True if not field_type in ('TextField(', 'CharField('): extra_params['null'] = True field_desc = '%s = models.%s' % (att_name, field_type) if extra_params: if not field_desc.endswith('('): field_desc += ', ' field_desc += ', '.join(['%s=%r' % (k, v) for k, v in extra_params.items()]) field_desc += ')' if comment_notes: field_desc += ' # ' + ' '.join(comment_notes) yield ' %s' % field_desc for meta_line in self.get_meta(table_name): yield meta_line def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') # This is a hook for DATA_TYPES_REVERSE to return a tuple of # (field_type, field_params_dict). if type(field_type) is tuple: field_type, new_params = field_type field_params.update(new_params) # Add max_length for all CharFields. if field_type == 'CharField' and row[3]: field_params['max_length'] = row[3] if field_type == 'DecimalField': field_params['max_digits'] = row[4] field_params['decimal_places'] = row[5] return field_type, field_params, field_notes def get_meta(self, table_name): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ return [' class Meta:', ' db_table = %r' % table_name, '']
Python
from optparse import make_option from django.conf import settings from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.core.management import call_command from django.core.management.base import NoArgsCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import sql_flush, emit_post_sync_signal from django.utils.importlib import import_module class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to flush. ' 'Defaults to the "default" database.'), ) help = "Executes ``sqlflush`` on the current database." def handle_noargs(self, **options): db = options.get('database', DEFAULT_DB_ALIAS) connection = connections[db] verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive') self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except ImportError: pass sql_list = sql_flush(self.style, connection, only_django=True) if interactive: confirm = raw_input("""You have requested a flush of the database. This will IRREVERSIBLY DESTROY all data currently in the %r database, and return each table to the state it was in after syncdb. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME']) else: confirm = 'yes' if confirm == 'yes': try: cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) except Exception, e: transaction.rollback_unless_managed(using=db) raise CommandError("""Database %s couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run. The full error: %s""" % (connection.settings_dict['NAME'], e)) transaction.commit_unless_managed(using=db) # Emit the post sync signal. This allows individual # applications to respond as if the database had been # sync'd from scratch. all_models = [] for app in models.get_apps(): all_models.extend([ m for m in models.get_models(app, include_auto_created=True) if router.allow_syncdb(db, m) ]) emit_post_sync_signal(set(all_models), verbosity, interactive, db) # Reinstall the initial_data fixture. kwargs = options.copy() kwargs['database'] = db call_command('loaddata', 'initial_data', **kwargs) else: print "Flush cancelled."
Python
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_reset from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_reset(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
Python
from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS class Command(BaseCommand): help = ("Runs the command-line client for specified database, or the " "default database if none is provided.") option_list = BaseCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database onto which to ' 'open a shell. Defaults to the "default" database.'), ) requires_model_validation = False def handle(self, **options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] try: connection.client.runshell() except OSError: # Note that we're assuming OSError means that the client program # isn't installed. There's a possibility OSError would be raised # for some other reason, in which case this error message would be # inaccurate. Still, this message catches the common case. raise CommandError('You appear not to have the %r program installed or on your path.' % \ connection.client.executable_name)
Python
from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = "Validates all installed models." requires_model_validation = False def handle_noargs(self, **options): self.validate(display_num_errors=True)
Python
from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Runs this project as a FastCGI application. Requires flup." args = '[various KEY=val options, use `runfcgi help` for help]' def handle(self, *args, **options): from django.conf import settings from django.utils import translation # Activate the current language, because it won't get activated later. try: translation.activate(settings.LANGUAGE_CODE) except AttributeError: pass from django.core.servers.fastcgi import runfastcgi runfastcgi(args) def usage(self, subcommand): from django.core.servers.fastcgi import FASTCGI_HELP return FASTCGI_HELP
Python
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_indexes from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the CREATE INDEX SQL statements for the given model module name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_indexes(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
Python
import fnmatch import glob import os import re import sys from itertools import dropwhile from optparse import make_option from subprocess import PIPE, Popen from django.core.management.base import CommandError, NoArgsCommand from django.utils.text import get_text_list pythonize_re = re.compile(r'(?:^|\n)\s*//') plural_forms_re = re.compile(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL) def handle_extensions(extensions=('html',)): """ organizes multiple extensions that are separated with commas or passed by using --extension/-e multiple times. for example: running 'django-admin makemessages -e js,txt -e xhtml -a' would result in a extension list: ['.js', '.txt', '.xhtml'] >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py']) ['.html', '.js'] >>> handle_extensions(['.html, txt,.tpl']) ['.html', '.tpl', '.txt'] """ ext_list = [] for ext in extensions: ext_list.extend(ext.replace(' ','').split(',')) for i, ext in enumerate(ext_list): if not ext.startswith('.'): ext_list[i] = '.%s' % ext_list[i] # we don't want *.py files here because of the way non-*.py files # are handled in make_messages() (they are copied to file.ext.py files to # trick xgettext to parse them as Python files) return set([x for x in ext_list if x != '.py']) def _popen(cmd): """ Friendly wrapper around Popen for Windows """ p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True) return p.communicate() def walk(root, topdown=True, onerror=None, followlinks=False): """ A version of os.walk that can follow symlinks for Python < 2.6 """ for dirpath, dirnames, filenames in os.walk(root, topdown, onerror): yield (dirpath, dirnames, filenames) if followlinks: for d in dirnames: p = os.path.join(dirpath, d) if os.path.islink(p): for link_dirpath, link_dirnames, link_filenames in walk(p): yield (link_dirpath, link_dirnames, link_filenames) def is_ignored(path, ignore_patterns): """ Helper function to check if the given path should be ignored or not. """ for pattern in ignore_patterns: if fnmatch.fnmatchcase(path, pattern): return True return False def find_files(root, ignore_patterns, verbosity, symlinks=False): """ Helper function to get all files in the given root. """ all_files = [] for (dirpath, dirnames, filenames) in walk(".", followlinks=symlinks): for f in filenames: norm_filepath = os.path.normpath(os.path.join(dirpath, f)) if is_ignored(norm_filepath, ignore_patterns): if verbosity > 1: sys.stdout.write('ignoring file %s in %s\n' % (f, dirpath)) else: all_files.extend([(dirpath, f)]) all_files.sort() return all_files def copy_plural_forms(msgs, locale, domain, verbosity): """ Copies plural forms header contents from a Django catalog of locale to the msgs string, inserting it at the right place. msgs should be the contents of a newly created .po file. """ import django django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) if domain == 'djangojs': domains = ('djangojs', 'django') else: domains = ('django',) for domain in domains: django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain) if os.path.exists(django_po): m = plural_forms_re.search(open(django_po, 'rU').read()) if m: if verbosity > 1: sys.stderr.write("copying plural forms: %s\n" % m.group('value')) lines = [] seen = False for line in msgs.split('\n'): if not line and not seen: line = '%s\n' % m.group('value') seen = True lines.append(line) msgs = '\n'.join(lines) break return msgs def make_messages(locale=None, domain='django', verbosity='1', all=False, extensions=None, symlinks=False, ignore_patterns=[], no_wrap=False, no_obsolete=False): """ Uses the locale directory from the Django SVN tree or an application/ project to process all """ # Need to ensure that the i18n framework is enabled from django.conf import settings if settings.configured: settings.USE_I18N = True else: settings.configure(USE_I18N = True) from django.utils.translation import templatize invoked_for_django = False if os.path.isdir(os.path.join('conf', 'locale')): localedir = os.path.abspath(os.path.join('conf', 'locale')) invoked_for_django = True # Ignoring all contrib apps ignore_patterns += ['contrib/*'] elif os.path.isdir('locale'): localedir = os.path.abspath('locale') else: raise CommandError("This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or application, maybe you are just missing the conf/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application.") if domain not in ('django', 'djangojs'): raise CommandError("currently makemessages only supports domains 'django' and 'djangojs'") if (locale is None and not all) or domain is None: message = "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1]) raise CommandError(message) # We require gettext version 0.15 or newer. output = _popen('xgettext --version')[0] match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output) if match: xversion = (int(match.group('major')), int(match.group('minor'))) if xversion < (0, 15): raise CommandError("Django internationalization requires GNU gettext 0.15 or newer. You are using version %s, please upgrade your gettext toolset." % match.group()) languages = [] if locale is not None: languages.append(locale) elif all: locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir)) languages = [os.path.basename(l) for l in locale_dirs] wrap = no_wrap and '--no-wrap' or '' for locale in languages: if verbosity > 0: print "processing language", locale basedir = os.path.join(localedir, locale, 'LC_MESSAGES') if not os.path.isdir(basedir): os.makedirs(basedir) pofile = os.path.join(basedir, '%s.po' % domain) potfile = os.path.join(basedir, '%s.pot' % domain) if os.path.exists(potfile): os.unlink(potfile) for dirpath, file in find_files(".", ignore_patterns, verbosity, symlinks=symlinks): file_base, file_ext = os.path.splitext(file) if domain == 'djangojs' and file_ext in extensions: if verbosity > 1: sys.stdout.write('processing file %s in %s\n' % (file, dirpath)) src = open(os.path.join(dirpath, file), "rU").read() src = pythonize_re.sub('\n#', src) thefile = '%s.py' % file f = open(os.path.join(dirpath, thefile), "w") try: f.write(src) finally: f.close() cmd = ( 'xgettext -d %s -L Perl %s --keyword=gettext_noop ' '--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 ' '--keyword=pgettext:1c,2 --keyword=npgettext:1c,2,3 ' '--from-code UTF-8 --add-comments=Translators -o - "%s"' % ( domain, wrap, os.path.join(dirpath, thefile) ) ) msgs, errors = _popen(cmd) if errors: os.unlink(os.path.join(dirpath, thefile)) if os.path.exists(potfile): os.unlink(potfile) raise CommandError( "errors happened while running xgettext on %s\n%s" % (file, errors)) if msgs: old = '#: ' + os.path.join(dirpath, thefile)[2:] new = '#: ' + os.path.join(dirpath, file)[2:] msgs = msgs.replace(old, new) if os.path.exists(potfile): # Strip the header msgs = '\n'.join(dropwhile(len, msgs.split('\n'))) else: msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8') f = open(potfile, 'ab') try: f.write(msgs) finally: f.close() os.unlink(os.path.join(dirpath, thefile)) elif domain == 'django' and (file_ext == '.py' or file_ext in extensions): thefile = file orig_file = os.path.join(dirpath, file) if file_ext in extensions: src = open(orig_file, "rU").read() thefile = '%s.py' % file f = open(os.path.join(dirpath, thefile), "w") try: f.write(templatize(src, orig_file[2:])) finally: f.close() if verbosity > 1: sys.stdout.write('processing file %s in %s\n' % (file, dirpath)) cmd = ( 'xgettext -d %s -L Python %s --keyword=gettext_noop ' '--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 ' '--keyword=ugettext_noop --keyword=ugettext_lazy ' '--keyword=ungettext_lazy:1,2 --keyword=pgettext:1c,2 ' '--keyword=npgettext:1c,2,3 --keyword=pgettext_lazy:1c,2 ' '--keyword=npgettext_lazy:1c,2,3 --from-code UTF-8 ' '--add-comments=Translators -o - "%s"' % ( domain, wrap, os.path.join(dirpath, thefile)) ) msgs, errors = _popen(cmd) if errors: if thefile != file: os.unlink(os.path.join(dirpath, thefile)) if os.path.exists(potfile): os.unlink(potfile) raise CommandError( "errors happened while running xgettext on %s\n%s" % (file, errors)) if msgs: if thefile != file: old = '#: ' + os.path.join(dirpath, thefile)[2:] new = '#: ' + orig_file[2:] msgs = msgs.replace(old, new) if os.path.exists(potfile): # Strip the header msgs = '\n'.join(dropwhile(len, msgs.split('\n'))) else: msgs = msgs.replace('charset=CHARSET', 'charset=UTF-8') f = open(potfile, 'ab') try: f.write(msgs) finally: f.close() if thefile != file: os.unlink(os.path.join(dirpath, thefile)) if os.path.exists(potfile): msgs, errors = _popen('msguniq %s --to-code=utf-8 "%s"' % (wrap, potfile)) if errors: os.unlink(potfile) raise CommandError( "errors happened while running msguniq\n%s" % errors) if os.path.exists(pofile): f = open(potfile, 'w') try: f.write(msgs) finally: f.close() msgs, errors = _popen('msgmerge %s -q "%s" "%s"' % (wrap, pofile, potfile)) if errors: os.unlink(potfile) raise CommandError( "errors happened while running msgmerge\n%s" % errors) elif not invoked_for_django: msgs = copy_plural_forms(msgs, locale, domain, verbosity) msgs = msgs.replace( "#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % domain, "") f = open(pofile, 'wb') try: f.write(msgs) finally: f.close() os.unlink(potfile) if no_obsolete: msgs, errors = _popen('msgattrib %s -o "%s" --no-obsolete "%s"' % (wrap, pofile, pofile)) if errors: raise CommandError( "errors happened while running msgattrib\n%s" % errors) class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--locale', '-l', default=None, dest='locale', help='Creates or updates the message files for the given locale (e.g. pt_BR).'), make_option('--domain', '-d', default='django', dest='domain', help='The domain of the message files (default: "django").'), make_option('--all', '-a', action='store_true', dest='all', default=False, help='Updates the message files for all existing locales.'), make_option('--extension', '-e', dest='extensions', help='The file extension(s) to examine (default: ".html", separate multiple extensions with commas, or use -e multiple times)', action='append'), make_option('--symlinks', '-s', action='store_true', dest='symlinks', default=False, help='Follows symlinks to directories when examining source code and templates for translation strings.'), make_option('--ignore', '-i', action='append', dest='ignore_patterns', default=[], metavar='PATTERN', help='Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more.'), make_option('--no-default-ignore', action='store_false', dest='use_default_ignore_patterns', default=True, help="Don't ignore the common glob-style patterns 'CVS', '.*' and '*~'."), make_option('--no-wrap', action='store_true', dest='no_wrap', default=False, help="Don't break long message lines into several lines"), make_option('--no-obsolete', action='store_true', dest='no_obsolete', default=False, help="Remove obsolete message strings"), ) help = ( "Runs over the entire source tree of the current directory and " "pulls out all strings marked for translation. It creates (or updates) a message " "file in the conf/locale (in the django tree) or locale (for projects and " "applications) directory.\n\nYou must run this command with one of either the " "--locale or --all options.") requires_model_validation = False can_import_settings = False def handle_noargs(self, *args, **options): locale = options.get('locale') domain = options.get('domain') verbosity = int(options.get('verbosity')) process_all = options.get('all') extensions = options.get('extensions') symlinks = options.get('symlinks') ignore_patterns = options.get('ignore_patterns') if options.get('use_default_ignore_patterns'): ignore_patterns += ['CVS', '.*', '*~'] ignore_patterns = list(set(ignore_patterns)) no_wrap = options.get('no_wrap') no_obsolete = options.get('no_obsolete') if domain == 'djangojs': extensions = handle_extensions(extensions or ['js']) else: extensions = handle_extensions(extensions or ['html']) if verbosity > 1: sys.stdout.write('examining files with the extensions: %s\n' % get_text_list(list(extensions), 'and')) make_messages(locale, domain, verbosity, process_all, extensions, symlinks, ignore_patterns, no_wrap, no_obsolete)
Python
from optparse import make_option from django.conf import settings from django.core.management.base import AppCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import sql_reset from django.db import connections, transaction, DEFAULT_DB_ALIAS class Command(AppCommand): option_list = AppCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to reset. ' 'Defaults to the "default" database.'), ) help = "Executes ``sqlreset`` for the given app(s) in the current database." args = '[appname ...]' output_transaction = True def handle_app(self, app, **options): # This command breaks a lot and should be deprecated import warnings warnings.warn( 'This command has been deprecated. The command ``flush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.', PendingDeprecationWarning ) using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] app_name = app.__name__.split('.')[-2] self.style = no_style() sql_list = sql_reset(app, self.style, connection) if options.get('interactive'): confirm = raw_input(""" You have requested a database reset. This will IRREVERSIBLY DESTROY any data for the "%s" application in the database "%s". Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % (app_name, connection.settings_dict['NAME'])) else: confirm = 'yes' if confirm == 'yes': try: cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) except Exception, e: transaction.rollback_unless_managed() raise CommandError("""Error: %s couldn't be reset. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin.py sqlreset %s'. That's the SQL this command wasn't able to run. The full error: %s""" % (app_name, app_name, e)) transaction.commit_unless_managed() else: print "Reset cancelled."
Python
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_create from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the CREATE TABLE SQL statements for the given app name(s)." option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): return u'\n'.join(sql_create(app, self.style, connections[options.get('database', DEFAULT_DB_ALIAS)])).encode('utf-8')
Python
from optparse import make_option from django.core.management.base import NoArgsCommand from django.core.management.sql import sql_flush from django.db import connections, DEFAULT_DB_ALIAS class Command(NoArgsCommand): help = "Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed." option_list = NoArgsCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_noargs(self, **options): return u'\n'.join(sql_flush(self.style, connections[options.get('database', DEFAULT_DB_ALIAS)], only_django=True)).encode('utf-8')
Python
from optparse import make_option from django.core.management.base import AppCommand from django.db import connections, models, DEFAULT_DB_ALIAS class Command(AppCommand): help = 'Prints the SQL statements for resetting sequences for the given app name(s).' option_list = AppCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to print the ' 'SQL for. Defaults to the "default" database.'), ) output_transaction = True def handle_app(self, app, **options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] return u'\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))).encode('utf-8')
Python
from django.core.management.base import BaseCommand from optparse import make_option import sys class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--failfast', action='store_true', dest='failfast', default=False, help='Tells Django to stop running the test suite after first failed test.') ) help = 'Runs the test suite for the specified applications, or the entire site if no apps are specified.' args = '[appname ...]' requires_model_validation = False def handle(self, *test_labels, **options): from django.conf import settings from django.test.utils import get_runner verbosity = int(options.get('verbosity', 1)) interactive = options.get('interactive', True) failfast = options.get('failfast', False) TestRunner = get_runner(settings) if hasattr(TestRunner, 'func_name'): # Pre 1.2 test runners were just functions, # and did not support the 'failfast' option. import warnings warnings.warn( 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.', DeprecationWarning ) failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive) else: test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) failures = test_runner.run_tests(test_labels) if failures: sys.exit(bool(failures))
Python
import sys import os import gzip import zipfile from optparse import make_option from django.conf import settings from django.core import serializers from django.core.management.base import BaseCommand from django.core.management.color import no_style from django.db import connections, router, transaction, DEFAULT_DB_ALIAS from django.db.models import get_apps from django.utils.itercompat import product try: import bz2 has_bz2 = True except ImportError: has_bz2 = False class Command(BaseCommand): help = 'Installs the named fixture(s) in the database.' args = "fixture [fixture ...]" option_list = BaseCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a specific database to load ' 'fixtures into. Defaults to the "default" database.'), ) def handle(self, *fixture_labels, **options): using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] self.style = no_style() verbosity = int(options.get('verbosity', 1)) show_traceback = options.get('traceback', False) # commit is a stealth option - it isn't really useful as # a command line option, but it can be useful when invoking # loaddata from within another script. # If commit=True, loaddata will use its own transaction; # if commit=False, the data load SQL will become part of # the transaction in place when loaddata was invoked. commit = options.get('commit', True) # Keep a count of the installed objects and fixtures fixture_count = 0 loaded_object_count = 0 fixture_object_count = 0 models = set() humanize = lambda dirname: dirname and "'%s'" % dirname or 'absolute path' # Get a cursor (even though we don't need one yet). This has # the side effect of initializing the test database (if # it isn't already initialized). cursor = connection.cursor() # Start transaction management. All fixtures are installed in a # single transaction to ensure that all references are resolved. if commit: transaction.commit_unless_managed(using=using) transaction.enter_transaction_management(using=using) transaction.managed(True, using=using) class SingleZipReader(zipfile.ZipFile): def __init__(self, *args, **kwargs): zipfile.ZipFile.__init__(self, *args, **kwargs) if settings.DEBUG: assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file." def read(self): return zipfile.ZipFile.read(self, self.namelist()[0]) compression_types = { None: file, 'gz': gzip.GzipFile, 'zip': SingleZipReader } if has_bz2: compression_types['bz2'] = bz2.BZ2File app_module_paths = [] for app in get_apps(): if hasattr(app, '__path__'): # It's a 'models/' subpackage for path in app.__path__: app_module_paths.append(path) else: # It's a models.py module app_module_paths.append(app.__file__) app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths] for fixture_label in fixture_labels: parts = fixture_label.split('.') if len(parts) > 1 and parts[-1] in compression_types: compression_formats = [parts[-1]] parts = parts[:-1] else: compression_formats = compression_types.keys() if len(parts) == 1: fixture_name = parts[0] formats = serializers.get_public_serializer_formats() else: fixture_name, format = '.'.join(parts[:-1]), parts[-1] if format in serializers.get_public_serializer_formats(): formats = [format] else: formats = [] if formats: if verbosity >= 2: self.stdout.write("Loading '%s' fixtures...\n" % fixture_name) else: self.stderr.write( self.style.ERROR("Problem installing fixture '%s': %s is not a known serialization format.\n" % (fixture_name, format))) if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) return if os.path.isabs(fixture_name): fixture_dirs = [fixture_name] else: fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + [''] for fixture_dir in fixture_dirs: if verbosity >= 2: self.stdout.write("Checking %s for fixtures...\n" % humanize(fixture_dir)) label_found = False for combo in product([using, None], formats, compression_formats): database, format, compression_format = combo file_name = '.'.join( p for p in [ fixture_name, database, format, compression_format ] if p ) if verbosity >= 3: self.stdout.write("Trying %s for %s fixture '%s'...\n" % \ (humanize(fixture_dir), file_name, fixture_name)) full_path = os.path.join(fixture_dir, file_name) open_method = compression_types[compression_format] try: fixture = open_method(full_path, 'r') if label_found: fixture.close() self.stderr.write(self.style.ERROR("Multiple fixtures named '%s' in %s. Aborting.\n" % (fixture_name, humanize(fixture_dir)))) if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) return else: fixture_count += 1 objects_in_fixture = 0 loaded_objects_in_fixture = 0 if verbosity >= 2: self.stdout.write("Installing %s fixture '%s' from %s.\n" % \ (format, fixture_name, humanize(fixture_dir))) try: objects = serializers.deserialize(format, fixture, using=using) for obj in objects: objects_in_fixture += 1 if router.allow_syncdb(using, obj.object.__class__): loaded_objects_in_fixture += 1 models.add(obj.object.__class__) obj.save(using=using) loaded_object_count += loaded_objects_in_fixture fixture_object_count += objects_in_fixture label_found = True except (SystemExit, KeyboardInterrupt): raise except Exception: import traceback fixture.close() if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) if show_traceback: traceback.print_exc() else: self.stderr.write( self.style.ERROR("Problem installing fixture '%s': %s\n" % (full_path, ''.join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))))) return fixture.close() # If the fixture we loaded contains 0 objects, assume that an # error was encountered during fixture loading. if objects_in_fixture == 0: self.stderr.write( self.style.ERROR("No fixture data found for '%s'. (File format may be invalid.)\n" % (fixture_name))) if commit: transaction.rollback(using=using) transaction.leave_transaction_management(using=using) return except Exception, e: if verbosity >= 2: self.stdout.write("No %s fixture '%s' in %s.\n" % \ (format, fixture_name, humanize(fixture_dir))) # If we found even one object in a fixture, we need to reset the # database sequences. if loaded_object_count > 0: sequence_sql = connection.ops.sequence_reset_sql(self.style, models) if sequence_sql: if verbosity >= 2: self.stdout.write("Resetting sequences\n") for line in sequence_sql: cursor.execute(line) if commit: transaction.commit(using=using) transaction.leave_transaction_management(using=using) if fixture_object_count == 0: if verbosity >= 1: self.stdout.write("No fixtures found.\n") else: if verbosity >= 1: if fixture_object_count == loaded_object_count: self.stdout.write("Installed %d object(s) from %d fixture(s)\n" % ( loaded_object_count, fixture_count)) else: self.stdout.write("Installed %d object(s) (of %d) from %d fixture(s)\n" % ( loaded_object_count, fixture_object_count, fixture_count)) # Close the DB connection. This is required as a workaround for an # edge case in MySQL: if the same connection is used to # create tables, load data, and query, the query can return # incorrect results. See Django #7572, MySQL #37735. if commit: connection.close()
Python