More attacking E302 violators

This commit is contained in:
Alex Gaynor 2013-11-02 13:12:09 -07:00
parent 65c4ac3b24
commit 7548aa8ffd
150 changed files with 433 additions and 1 deletions

View File

@ -53,6 +53,8 @@ class SpatiaLiteRelate(SpatiaLiteFunctionParam):
# Valid distance types and substitutions # Valid distance types and substitutions
dtypes = (Decimal, Distance, float) + six.integer_types dtypes = (Decimal, Distance, float) + six.integer_types
def get_dist_ops(operator): def get_dist_ops(operator):
"Returns operations for regular distances; spherical distances are not currently supported." "Returns operations for regular distances; spherical distances are not currently supported."
return (SpatiaLiteDistance(operator),) return (SpatiaLiteDistance(operator),)

View File

@ -4,6 +4,7 @@
OGR methods. OGR methods.
""" """
#### OGR & SRS Exceptions #### #### OGR & SRS Exceptions ####
class GDALException(Exception): class GDALException(Exception):
pass pass

View File

@ -522,6 +522,7 @@ class OGRGeometry(GDALBase):
""" """
return self._geomgen(capi.geom_union, other) return self._geomgen(capi.geom_union, other)
# The subclasses for OGR Geometry. # The subclasses for OGR Geometry.
class Point(OGRGeometry): class Point(OGRGeometry):
@ -550,6 +551,7 @@ class Point(OGRGeometry):
return (self.x, self.y, self.z) return (self.x, self.y, self.z)
coords = tuple coords = tuple
class LineString(OGRGeometry): class LineString(OGRGeometry):
def __getitem__(self, index): def __getitem__(self, index):
@ -605,10 +607,12 @@ class LineString(OGRGeometry):
if self.coord_dim == 3: if self.coord_dim == 3:
return self._listarr(capi.getz) return self._listarr(capi.getz)
# LinearRings are used in Polygons. # LinearRings are used in Polygons.
class LinearRing(LineString): class LinearRing(LineString):
pass pass
class Polygon(OGRGeometry): class Polygon(OGRGeometry):
def __len__(self): def __len__(self):
@ -654,6 +658,7 @@ class Polygon(OGRGeometry):
capi.get_centroid(self.ptr, p.ptr) capi.get_centroid(self.ptr, p.ptr)
return p return p
# Geometry Collection base class. # Geometry Collection base class.
class GeometryCollection(OGRGeometry): class GeometryCollection(OGRGeometry):
"The Geometry Collection class." "The Geometry Collection class."
@ -700,13 +705,16 @@ class GeometryCollection(OGRGeometry):
return tuple(self[i].tuple for i in xrange(self.geom_count)) return tuple(self[i].tuple for i in xrange(self.geom_count))
coords = tuple coords = tuple
# Multiple Geometry types. # Multiple Geometry types.
class MultiPoint(GeometryCollection): class MultiPoint(GeometryCollection):
pass pass
class MultiLineString(GeometryCollection): class MultiLineString(GeometryCollection):
pass pass
class MultiPolygon(GeometryCollection): class MultiPolygon(GeometryCollection):
pass pass

View File

@ -2,7 +2,7 @@ from django.contrib.gis.gdal.error import OGRException
from django.utils import six from django.utils import six
#### OGRGeomType ####
class OGRGeomType(object): class OGRGeomType(object):
"Encapulates OGR Geometry Types." "Encapulates OGR Geometry Types."

View File

@ -55,6 +55,7 @@ if os.name == 'nt':
from ctypes import WinDLL from ctypes import WinDLL
lwingdal = WinDLL(lib_path) lwingdal = WinDLL(lib_path)
def std_call(func): def std_call(func):
""" """
Returns the correct STDCALL function for certain OSR routines on Win32 Returns the correct STDCALL function for certain OSR routines on Win32
@ -72,15 +73,19 @@ _version_info = std_call('GDALVersionInfo')
_version_info.argtypes = [c_char_p] _version_info.argtypes = [c_char_p]
_version_info.restype = c_char_p _version_info.restype = c_char_p
def gdal_version(): def gdal_version():
"Returns only the GDAL version number information." "Returns only the GDAL version number information."
return _version_info(b'RELEASE_NAME') return _version_info(b'RELEASE_NAME')
def gdal_full_version(): def gdal_full_version():
"Returns the full GDAL version information." "Returns the full GDAL version information."
return _version_info('') return _version_info('')
version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?') version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?')
def gdal_version_info(): def gdal_version_info():
ver = gdal_version().decode() ver = gdal_version().decode()
m = version_regex.match(ver) m = version_regex.match(ver)
@ -97,10 +102,13 @@ del _verinfo
# Set library error handling so as errors are logged # Set library error handling so as errors are logged
CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p) CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p)
def err_handler(error_class, error_number, message): def err_handler(error_class, error_number, message):
logger.error('GDAL_ERROR %d: %s' % (error_number, message)) logger.error('GDAL_ERROR %d: %s' % (error_number, message))
err_handler = CPLErrorHandler(err_handler) err_handler = CPLErrorHandler(err_handler)
def function(name, args, restype): def function(name, args, restype):
func = std_call(name) func = std_call(name)
func.argtypes = args func.argtypes = args

View File

@ -15,10 +15,12 @@ def arg_byref(args, offset=-1):
"Returns the pointer argument's by-refernece value." "Returns the pointer argument's by-refernece value."
return args[offset]._obj.value return args[offset]._obj.value
def ptr_byref(args, offset=-1): def ptr_byref(args, offset=-1):
"Returns the pointer argument passed in by-reference." "Returns the pointer argument passed in by-reference."
return args[offset]._obj return args[offset]._obj
### String checking Routines ### ### String checking Routines ###
def check_const_string(result, func, cargs, offset=None): def check_const_string(result, func, cargs, offset=None):
""" """
@ -31,6 +33,7 @@ def check_const_string(result, func, cargs, offset=None):
else: else:
return result return result
def check_string(result, func, cargs, offset=-1, str_result=False): def check_string(result, func, cargs, offset=-1, str_result=False):
""" """
Checks the string output returned from the given function, and frees Checks the string output returned from the given function, and frees
@ -61,12 +64,14 @@ def check_string(result, func, cargs, offset=-1, str_result=False):
### DataSource, Layer error-checking ### ### DataSource, Layer error-checking ###
### Envelope checking ### ### Envelope checking ###
def check_envelope(result, func, cargs, offset=-1): def check_envelope(result, func, cargs, offset=-1):
"Checks a function that returns an OGR Envelope by reference." "Checks a function that returns an OGR Envelope by reference."
env = ptr_byref(cargs, offset) env = ptr_byref(cargs, offset)
return env return env
### Geometry error-checking routines ### ### Geometry error-checking routines ###
def check_geom(result, func, cargs): def check_geom(result, func, cargs):
"Checks a function that returns a geometry." "Checks a function that returns a geometry."
@ -78,12 +83,14 @@ def check_geom(result, func, cargs):
raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__) raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__)
return result return result
def check_geom_offset(result, func, cargs, offset=-1): def check_geom_offset(result, func, cargs, offset=-1):
"Chcks the geometry at the given offset in the C parameter list." "Chcks the geometry at the given offset in the C parameter list."
check_err(result) check_err(result)
geom = ptr_byref(cargs, offset=offset) geom = ptr_byref(cargs, offset=offset)
return check_geom(geom, func, cargs) return check_geom(geom, func, cargs)
### Spatial Reference error-checking routines ### ### Spatial Reference error-checking routines ###
def check_srs(result, func, cargs): def check_srs(result, func, cargs):
if isinstance(result, six.integer_types): if isinstance(result, six.integer_types):
@ -92,6 +99,7 @@ def check_srs(result, func, cargs):
raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__) raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__)
return result return result
### Other error-checking routines ### ### Other error-checking routines ###
def check_arg_errcode(result, func, cargs): def check_arg_errcode(result, func, cargs):
""" """
@ -101,12 +109,14 @@ def check_arg_errcode(result, func, cargs):
check_err(arg_byref(cargs)) check_err(arg_byref(cargs))
return result return result
def check_errcode(result, func, cargs): def check_errcode(result, func, cargs):
""" """
Check the error code returned (c_int). Check the error code returned (c_int).
""" """
check_err(result) check_err(result)
def check_pointer(result, func, cargs): def check_pointer(result, func, cargs):
"Makes sure the result pointer is valid." "Makes sure the result pointer is valid."
if isinstance(result, six.integer_types): if isinstance(result, six.integer_types):
@ -116,6 +126,7 @@ def check_pointer(result, func, cargs):
else: else:
raise OGRException('Invalid pointer returned from "%s"' % func.__name__) raise OGRException('Invalid pointer returned from "%s"' % func.__name__)
def check_str_arg(result, func, cargs): def check_str_arg(result, func, cargs):
""" """
This is for the OSRGet[Angular|Linear]Units functions, which This is for the OSRGet[Angular|Linear]Units functions, which

View File

@ -8,9 +8,11 @@ from django.contrib.gis.gdal.prototypes.errcheck import (
check_arg_errcode, check_errcode, check_geom, check_geom_offset, check_arg_errcode, check_errcode, check_geom, check_geom_offset,
check_pointer, check_srs, check_str_arg, check_string, check_const_string) check_pointer, check_srs, check_str_arg, check_string, check_const_string)
class gdal_char_p(c_char_p): class gdal_char_p(c_char_p):
pass pass
def double_output(func, argtypes, errcheck=False, strarg=False): def double_output(func, argtypes, errcheck=False, strarg=False):
"Generates a ctypes function that returns a double value." "Generates a ctypes function that returns a double value."
func.argtypes = argtypes func.argtypes = argtypes
@ -21,6 +23,7 @@ def double_output(func, argtypes, errcheck=False, strarg=False):
func.errcheck = check_str_arg func.errcheck = check_str_arg
return func return func
def geom_output(func, argtypes, offset=None): def geom_output(func, argtypes, offset=None):
""" """
Generates a function that returns a Geometry either by reference Generates a function that returns a Geometry either by reference
@ -43,12 +46,14 @@ def geom_output(func, argtypes, offset=None):
return func return func
def int_output(func, argtypes): def int_output(func, argtypes):
"Generates a ctypes function that returns an integer value." "Generates a ctypes function that returns an integer value."
func.argtypes = argtypes func.argtypes = argtypes
func.restype = c_int func.restype = c_int
return func return func
def srs_output(func, argtypes): def srs_output(func, argtypes):
""" """
Generates a ctypes prototype for the given function with Generates a ctypes prototype for the given function with
@ -60,6 +65,7 @@ def srs_output(func, argtypes):
func.errcheck = check_srs func.errcheck = check_srs
return func return func
def const_string_output(func, argtypes, offset=None, decoding=None): def const_string_output(func, argtypes, offset=None, decoding=None):
func.argtypes = argtypes func.argtypes = argtypes
if offset: if offset:
@ -76,6 +82,7 @@ def const_string_output(func, argtypes, offset=None, decoding=None):
return func return func
def string_output(func, argtypes, offset=-1, str_result=False, decoding=None): def string_output(func, argtypes, offset=-1, str_result=False, decoding=None):
""" """
Generates a ctypes prototype for the given function with the Generates a ctypes prototype for the given function with the
@ -104,6 +111,7 @@ def string_output(func, argtypes, offset=-1, str_result=False, decoding=None):
func.errcheck = _check_str func.errcheck = _check_str
return func return func
def void_output(func, argtypes, errcheck=True): def void_output(func, argtypes, errcheck=True):
""" """
For functions that don't only return an error code that needs to For functions that don't only return an error code that needs to
@ -121,6 +129,7 @@ def void_output(func, argtypes, errcheck=True):
return func return func
def voidptr_output(func, argtypes): def voidptr_output(func, argtypes):
"For functions that return c_void_p." "For functions that return c_void_p."
func.argtypes = argtypes func.argtypes = argtypes

View File

@ -5,6 +5,7 @@ from django.contrib.gis.gdal.prototypes.errcheck import check_envelope
from django.contrib.gis.gdal.prototypes.generation import (const_string_output, from django.contrib.gis.gdal.prototypes.generation import (const_string_output,
double_output, geom_output, int_output, srs_output, string_output, void_output) double_output, geom_output, int_output, srs_output, string_output, void_output)
### Generation routines specific to this module ### ### Generation routines specific to this module ###
def env_func(f, argtypes): def env_func(f, argtypes):
"For getting OGREnvelopes." "For getting OGREnvelopes."
@ -13,10 +14,12 @@ def env_func(f, argtypes):
f.errcheck = check_envelope f.errcheck = check_envelope
return f return f
def pnt_func(f): def pnt_func(f):
"For accessing point information." "For accessing point information."
return double_output(f, [c_void_p, c_int]) return double_output(f, [c_void_p, c_int])
def topology_func(f): def topology_func(f):
f.argtypes = [c_void_p, c_void_p] f.argtypes = [c_void_p, c_void_p]
f.restype = c_int f.restype = c_int

View File

@ -3,6 +3,7 @@ from django.contrib.gis.gdal.libgdal import lgdal, std_call
from django.contrib.gis.gdal.prototypes.generation import (const_string_output, from django.contrib.gis.gdal.prototypes.generation import (const_string_output,
double_output, int_output, srs_output, string_output, void_output) double_output, int_output, srs_output, string_output, void_output)
## Shortcut generation for routines with known parameters. ## Shortcut generation for routines with known parameters.
def srs_double(f): def srs_double(f):
""" """
@ -11,6 +12,7 @@ def srs_double(f):
""" """
return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True) return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True)
def units_func(f): def units_func(f):
""" """
Creates a ctypes function prototype for OSR units functions, e.g., Creates a ctypes function prototype for OSR units functions, e.g.,

View File

@ -1,6 +1,7 @@
from ctypes import c_char_p, c_float, c_int, string_at, Structure, POINTER from ctypes import c_char_p, c_float, c_int, string_at, Structure, POINTER
from django.contrib.gis.geoip.libgeoip import lgeoip, free from django.contrib.gis.geoip.libgeoip import lgeoip, free
#### GeoIP C Structure definitions #### #### GeoIP C Structure definitions ####
class GeoIPRecord(Structure): class GeoIPRecord(Structure):
@ -27,6 +28,7 @@ geoip_encodings = {
1: 'utf8', 1: 'utf8',
} }
class GeoIPTag(Structure): class GeoIPTag(Structure):
pass pass
@ -48,6 +50,7 @@ GeoIPRecord_delete = lgeoip.GeoIPRecord_delete
GeoIPRecord_delete.argtypes = [RECTYPE] GeoIPRecord_delete.argtypes = [RECTYPE]
GeoIPRecord_delete.restype = None GeoIPRecord_delete.restype = None
# For retrieving records by name or address. # For retrieving records by name or address.
def check_record(result, func, cargs): def check_record(result, func, cargs):
if result: if result:
@ -68,6 +71,7 @@ def check_record(result, func, cargs):
else: else:
return None return None
def record_output(func): def record_output(func):
func.argtypes = [DBTYPE, c_char_p] func.argtypes = [DBTYPE, c_char_p]
func.restype = RECTYPE func.restype = RECTYPE
@ -84,10 +88,12 @@ GeoIP_delete = lgeoip.GeoIP_delete
GeoIP_delete.argtypes = [DBTYPE] GeoIP_delete.argtypes = [DBTYPE]
GeoIP_delete.restype = None GeoIP_delete.restype = None
# This is so the string pointer can be freed within Python. # This is so the string pointer can be freed within Python.
class geoip_char_p(c_char_p): class geoip_char_p(c_char_p):
pass pass
def check_string(result, func, cargs): def check_string(result, func, cargs):
if result: if result:
s = string_at(result) s = string_at(result)
@ -100,6 +106,7 @@ GeoIP_database_info = lgeoip.GeoIP_database_info
GeoIP_database_info.restype = geoip_char_p GeoIP_database_info.restype = geoip_char_p
GeoIP_database_info.errcheck = check_string GeoIP_database_info.errcheck = check_string
# String output routines. # String output routines.
def string_output(func): def string_output(func):
def _err_check(result, func, cargs): def _err_check(result, func, cargs):

View File

@ -12,6 +12,7 @@ from django.contrib.gis.geos.polygon import Polygon
from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos import prototypes as capi
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
class GeometryCollection(GEOSGeometry): class GeometryCollection(GEOSGeometry):
_typeid = 7 _typeid = 7
@ -91,11 +92,13 @@ class GeometryCollection(GEOSGeometry):
return tuple(g.tuple for g in self) return tuple(g.tuple for g in self)
coords = tuple coords = tuple
# MultiPoint, MultiLineString, and MultiPolygon class definitions. # MultiPoint, MultiLineString, and MultiPolygon class definitions.
class MultiPoint(GeometryCollection): class MultiPoint(GeometryCollection):
_allowed = Point _allowed = Point
_typeid = 4 _typeid = 4
class MultiLineString(GeometryCollection): class MultiLineString(GeometryCollection):
_allowed = (LineString, LinearRing) _allowed = (LineString, LinearRing)
_typeid = 5 _typeid = 5
@ -108,6 +111,7 @@ class MultiLineString(GeometryCollection):
""" """
return self._topology(capi.geos_linemerge(self.ptr)) return self._topology(capi.geos_linemerge(self.ptr))
class MultiPolygon(GeometryCollection): class MultiPolygon(GeometryCollection):
_allowed = Polygon _allowed = Polygon
_typeid = 6 _typeid = 6

View File

@ -10,6 +10,7 @@ from django.contrib.gis.geos.libgeos import CS_PTR
from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos import prototypes as capi
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
class GEOSCoordSeq(GEOSBase): class GEOSCoordSeq(GEOSBase):
"The internal representation of a list of coordinates inside a Geometry." "The internal representation of a list of coordinates inside a Geometry."

View File

@ -3,10 +3,12 @@
GEOSGeometryIndexError. GEOSGeometryIndexError.
""" """
class GEOSException(Exception): class GEOSException(Exception):
"The base GEOS exception, indicates a GEOS-related error." "The base GEOS exception, indicates a GEOS-related error."
pass pass
class GEOSIndexError(GEOSException, KeyError): class GEOSIndexError(GEOSException, KeyError):
""" """
This exception is raised when an invalid index is encountered, and has This exception is raised when an invalid index is encountered, and has

View File

@ -62,6 +62,8 @@ lgeos = CDLL(lib_path)
# Supposed to mimic the GEOS message handler (C below): # Supposed to mimic the GEOS message handler (C below):
# typedef void (*GEOSMessageHandler)(const char *fmt, ...); # typedef void (*GEOSMessageHandler)(const char *fmt, ...);
NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p) NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
def notice_h(fmt, lst): def notice_h(fmt, lst):
fmt, lst = fmt.decode(), lst.decode() fmt, lst = fmt.decode(), lst.decode()
try: try:
@ -72,6 +74,8 @@ def notice_h(fmt, lst):
notice_h = NOTICEFUNC(notice_h) notice_h = NOTICEFUNC(notice_h)
ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p) ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
def error_h(fmt, lst): def error_h(fmt, lst):
fmt, lst = fmt.decode(), lst.decode() fmt, lst = fmt.decode(), lst.decode()
try: try:
@ -83,16 +87,20 @@ error_h = ERRORFUNC(error_h)
#### GEOS Geometry C data structures, and utility functions. #### #### GEOS Geometry C data structures, and utility functions. ####
# Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR # Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR
class GEOSGeom_t(Structure): class GEOSGeom_t(Structure):
pass pass
class GEOSPrepGeom_t(Structure): class GEOSPrepGeom_t(Structure):
pass pass
class GEOSCoordSeq_t(Structure): class GEOSCoordSeq_t(Structure):
pass pass
class GEOSContextHandle_t(Structure): class GEOSContextHandle_t(Structure):
pass pass
@ -102,6 +110,7 @@ PREPGEOM_PTR = POINTER(GEOSPrepGeom_t)
CS_PTR = POINTER(GEOSCoordSeq_t) CS_PTR = POINTER(GEOSCoordSeq_t)
CONTEXT_PTR = POINTER(GEOSContextHandle_t) CONTEXT_PTR = POINTER(GEOSContextHandle_t)
# Used specifically by the GEOSGeom_createPolygon and GEOSGeom_createCollection # Used specifically by the GEOSGeom_createPolygon and GEOSGeom_createCollection
# GEOS routines # GEOS routines
def get_pointer_arr(n): def get_pointer_arr(n):
@ -121,6 +130,8 @@ version_regex = re.compile(
r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))' r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))'
r'((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d+\.\d+)( r\d+)?$' r'((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d+\.\d+)( r\d+)?$'
) )
def geos_version_info(): def geos_version_info():
""" """
Returns a dictionary containing the various version metadata parsed from Returns a dictionary containing the various version metadata parsed from

View File

@ -6,6 +6,7 @@ from django.contrib.gis.geos.point import Point
from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos import prototypes as capi
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
class LineString(GEOSGeometry): class LineString(GEOSGeometry):
_init_func = capi.create_linestring _init_func = capi.create_linestring
_minlength = 2 _minlength = 2
@ -161,6 +162,7 @@ class LineString(GEOSGeometry):
else: else:
return self._listarr(self._cs.getZ) return self._listarr(self._cs.getZ)
# LinearRings are LineStrings used within Polygons. # LinearRings are LineStrings used within Polygons.
class LinearRing(LineString): class LinearRing(LineString):
_minLength = 4 _minLength = 4

View File

@ -5,6 +5,7 @@ from django.contrib.gis.geos import prototypes as capi
from django.utils import six from django.utils import six
from django.utils.six.moves import xrange from django.utils.six.moves import xrange
class Point(GEOSGeometry): class Point(GEOSGeometry):
_minlength = 2 _minlength = 2
_maxlength = 3 _maxlength = 3

View File

@ -3,6 +3,7 @@ from django.contrib.gis.geos.libgeos import GEOM_PTR, CS_PTR
from django.contrib.gis.geos.prototypes.errcheck import last_arg_byref, GEOSException from django.contrib.gis.geos.prototypes.errcheck import last_arg_byref, GEOSException
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
## Error-checking routines specific to coordinate sequences. ## ## Error-checking routines specific to coordinate sequences. ##
def check_cs_ptr(result, func, cargs): def check_cs_ptr(result, func, cargs):
"Error checking on routines that return Geometries." "Error checking on routines that return Geometries."
@ -10,6 +11,7 @@ def check_cs_ptr(result, func, cargs):
raise GEOSException('Error encountered checking Coordinate Sequence returned from GEOS C function "%s".' % func.__name__) raise GEOSException('Error encountered checking Coordinate Sequence returned from GEOS C function "%s".' % func.__name__)
return result return result
def check_cs_op(result, func, cargs): def check_cs_op(result, func, cargs):
"Checks the status code of a coordinate sequence operation." "Checks the status code of a coordinate sequence operation."
if result == 0: if result == 0:
@ -17,12 +19,14 @@ def check_cs_op(result, func, cargs):
else: else:
return result return result
def check_cs_get(result, func, cargs): def check_cs_get(result, func, cargs):
"Checking the coordinate sequence retrieval." "Checking the coordinate sequence retrieval."
check_cs_op(result, func, cargs) check_cs_op(result, func, cargs)
# Object in by reference, return its value. # Object in by reference, return its value.
return last_arg_byref(cargs) return last_arg_byref(cargs)
## Coordinate sequence prototype generation functions. ## ## Coordinate sequence prototype generation functions. ##
def cs_int(func): def cs_int(func):
"For coordinate sequence routines that return an integer." "For coordinate sequence routines that return an integer."
@ -31,6 +35,7 @@ def cs_int(func):
func.errcheck = check_cs_get func.errcheck = check_cs_get
return func return func
def cs_operation(func, ordinate=False, get=False): def cs_operation(func, ordinate=False, get=False):
"For coordinate sequence operations." "For coordinate sequence operations."
if get: if get:
@ -50,6 +55,7 @@ def cs_operation(func, ordinate=False, get=False):
func.restype = c_int func.restype = c_int
return func return func
def cs_output(func, argtypes): def cs_output(func, argtypes):
"For routines that return a coordinate sequence." "For routines that return a coordinate sequence."
func.argtypes = argtypes func.argtypes = argtypes

View File

@ -25,11 +25,13 @@ else:
libc = CDLL(None) libc = CDLL(None)
free = libc.free free = libc.free
### ctypes error checking routines ### ### ctypes error checking routines ###
def last_arg_byref(args): def last_arg_byref(args):
"Returns the last C argument's value by reference." "Returns the last C argument's value by reference."
return args[-1]._obj.value return args[-1]._obj.value
def check_dbl(result, func, cargs): def check_dbl(result, func, cargs):
"Checks the status code and returns the double value passed in by reference." "Checks the status code and returns the double value passed in by reference."
# Checking the status code # Checking the status code
@ -38,12 +40,14 @@ def check_dbl(result, func, cargs):
# Double passed in by reference, return its value. # Double passed in by reference, return its value.
return last_arg_byref(cargs) return last_arg_byref(cargs)
def check_geom(result, func, cargs): def check_geom(result, func, cargs):
"Error checking on routines that return Geometries." "Error checking on routines that return Geometries."
if not result: if not result:
raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__) raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__)
return result return result
def check_minus_one(result, func, cargs): def check_minus_one(result, func, cargs):
"Error checking on routines that should not return -1." "Error checking on routines that should not return -1."
if result == -1: if result == -1:
@ -51,6 +55,7 @@ def check_minus_one(result, func, cargs):
else: else:
return result return result
def check_predicate(result, func, cargs): def check_predicate(result, func, cargs):
"Error checking for unary/binary predicate functions." "Error checking for unary/binary predicate functions."
val = ord(result) # getting the ordinal from the character val = ord(result) # getting the ordinal from the character
@ -61,6 +66,7 @@ def check_predicate(result, func, cargs):
else: else:
raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__) raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
def check_sized_string(result, func, cargs): def check_sized_string(result, func, cargs):
""" """
Error checking for routines that return explicitly sized strings. Error checking for routines that return explicitly sized strings.
@ -77,6 +83,7 @@ def check_sized_string(result, func, cargs):
free(result) free(result)
return s return s
def check_string(result, func, cargs): def check_string(result, func, cargs):
""" """
Error checking for routines that return strings. Error checking for routines that return strings.
@ -91,6 +98,7 @@ def check_string(result, func, cargs):
free(result) free(result)
return s return s
def check_zero(result, func, cargs): def check_zero(result, func, cargs):
"Error checking on routines that should not return 0." "Error checking on routines that should not return 0."
if result == 0: if result == 0:

View File

@ -7,6 +7,7 @@ from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
# This is the return type used by binary output (WKB, HEX) routines. # This is the return type used by binary output (WKB, HEX) routines.
c_uchar_p = POINTER(c_ubyte) c_uchar_p = POINTER(c_ubyte)
# We create a simple subclass of c_char_p here because when the response # We create a simple subclass of c_char_p here because when the response
# type is set to c_char_p, you get a _Python_ string and there's no way # type is set to c_char_p, you get a _Python_ string and there's no way
# to access the string's address inside the error checking function. # to access the string's address inside the error checking function.
@ -17,6 +18,7 @@ c_uchar_p = POINTER(c_ubyte)
class geos_char_p(c_char_p): class geos_char_p(c_char_p):
pass pass
### ctypes generation functions ### ### ctypes generation functions ###
def bin_constructor(func): def bin_constructor(func):
"Generates a prototype for binary construction (HEX, WKB) GEOS routines." "Generates a prototype for binary construction (HEX, WKB) GEOS routines."
@ -25,6 +27,7 @@ def bin_constructor(func):
func.errcheck = check_geom func.errcheck = check_geom
return func return func
# HEX & WKB output # HEX & WKB output
def bin_output(func): def bin_output(func):
"Generates a prototype for the routines that return a sized string." "Generates a prototype for the routines that return a sized string."
@ -33,6 +36,7 @@ def bin_output(func):
func.restype = c_uchar_p func.restype = c_uchar_p
return func return func
def geom_output(func, argtypes): def geom_output(func, argtypes):
"For GEOS routines that return a geometry." "For GEOS routines that return a geometry."
if argtypes: if argtypes:
@ -41,10 +45,12 @@ def geom_output(func, argtypes):
func.errcheck = check_geom func.errcheck = check_geom
return func return func
def geom_index(func): def geom_index(func):
"For GEOS routines that return geometries from an index." "For GEOS routines that return geometries from an index."
return geom_output(func, [GEOM_PTR, c_int]) return geom_output(func, [GEOM_PTR, c_int])
def int_from_geom(func, zero=False): def int_from_geom(func, zero=False):
"Argument is a geometry, return type is an integer." "Argument is a geometry, return type is an integer."
func.argtypes = [GEOM_PTR] func.argtypes = [GEOM_PTR]
@ -55,6 +61,7 @@ def int_from_geom(func, zero=False):
func.errcheck = check_minus_one func.errcheck = check_minus_one
return func return func
def string_from_geom(func): def string_from_geom(func):
"Argument is a Geometry, return type is a string." "Argument is a Geometry, return type is a string."
func.argtypes = [GEOM_PTR] func.argtypes = [GEOM_PTR]

View File

@ -10,16 +10,20 @@ from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
from django.utils import six from django.utils import six
from django.utils.encoding import force_bytes from django.utils.encoding import force_bytes
### The WKB/WKT Reader/Writer structures and pointers ### ### The WKB/WKT Reader/Writer structures and pointers ###
class WKTReader_st(Structure): class WKTReader_st(Structure):
pass pass
class WKTWriter_st(Structure): class WKTWriter_st(Structure):
pass pass
class WKBReader_st(Structure): class WKBReader_st(Structure):
pass pass
class WKBWriter_st(Structure): class WKBWriter_st(Structure):
pass pass
@ -71,6 +75,7 @@ wkb_reader_create.restype = WKB_READ_PTR
wkb_reader_destroy = GEOSFunc('GEOSWKBReader_destroy') wkb_reader_destroy = GEOSFunc('GEOSWKBReader_destroy')
wkb_reader_destroy.argtypes = [WKB_READ_PTR] wkb_reader_destroy.argtypes = [WKB_READ_PTR]
def wkb_read_func(func): def wkb_read_func(func):
# Although the function definitions take `const unsigned char *` # Although the function definitions take `const unsigned char *`
# as their parameter, we use c_char_p here so the function may # as their parameter, we use c_char_p here so the function may
@ -92,6 +97,7 @@ wkb_writer_create.restype = WKB_WRITE_PTR
wkb_writer_destroy = GEOSFunc('GEOSWKBWriter_destroy') wkb_writer_destroy = GEOSFunc('GEOSWKBWriter_destroy')
wkb_writer_destroy.argtypes = [WKB_WRITE_PTR] wkb_writer_destroy.argtypes = [WKB_WRITE_PTR]
# WKB Writing prototypes. # WKB Writing prototypes.
def wkb_write_func(func): def wkb_write_func(func):
func.argtypes = [WKB_WRITE_PTR, GEOM_PTR, POINTER(c_size_t)] func.argtypes = [WKB_WRITE_PTR, GEOM_PTR, POINTER(c_size_t)]
@ -102,12 +108,14 @@ def wkb_write_func(func):
wkb_writer_write = wkb_write_func(GEOSFunc('GEOSWKBWriter_write')) wkb_writer_write = wkb_write_func(GEOSFunc('GEOSWKBWriter_write'))
wkb_writer_write_hex = wkb_write_func(GEOSFunc('GEOSWKBWriter_writeHEX')) wkb_writer_write_hex = wkb_write_func(GEOSFunc('GEOSWKBWriter_writeHEX'))
# WKBWriter property getter/setter prototypes. # WKBWriter property getter/setter prototypes.
def wkb_writer_get(func, restype=c_int): def wkb_writer_get(func, restype=c_int):
func.argtypes = [WKB_WRITE_PTR] func.argtypes = [WKB_WRITE_PTR]
func.restype = restype func.restype = restype
return func return func
def wkb_writer_set(func, argtype=c_int): def wkb_writer_set(func, argtype=c_int):
func.argtypes = [WKB_WRITE_PTR, argtype] func.argtypes = [WKB_WRITE_PTR, argtype]
return func return func
@ -119,6 +127,7 @@ wkb_writer_set_outdim = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setOutputDimensio
wkb_writer_get_include_srid = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getIncludeSRID'), restype=c_char) wkb_writer_get_include_srid = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getIncludeSRID'), restype=c_char)
wkb_writer_set_include_srid = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setIncludeSRID'), argtype=c_char) wkb_writer_set_include_srid = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setIncludeSRID'), argtype=c_char)
### Base I/O Class ### ### Base I/O Class ###
class IOBase(GEOSBase): class IOBase(GEOSBase):
"Base class for GEOS I/O objects." "Base class for GEOS I/O objects."
@ -133,6 +142,7 @@ class IOBase(GEOSBase):
### Base WKB/WKT Reading and Writing objects ### ### Base WKB/WKT Reading and Writing objects ###
# Non-public WKB/WKT reader classes for internal use because # Non-public WKB/WKT reader classes for internal use because
# their `read` methods return _pointers_ instead of GEOSGeometry # their `read` methods return _pointers_ instead of GEOSGeometry
# objects. # objects.
@ -146,6 +156,7 @@ class _WKTReader(IOBase):
raise TypeError raise TypeError
return wkt_reader_read(self.ptr, force_bytes(wkt)) return wkt_reader_read(self.ptr, force_bytes(wkt))
class _WKBReader(IOBase): class _WKBReader(IOBase):
_constructor = wkb_reader_create _constructor = wkb_reader_create
_destructor = wkb_reader_destroy _destructor = wkb_reader_destroy
@ -161,6 +172,7 @@ class _WKBReader(IOBase):
else: else:
raise TypeError raise TypeError
### WKB/WKT Writer Classes ### ### WKB/WKT Writer Classes ###
class WKTWriter(IOBase): class WKTWriter(IOBase):
_constructor = wkt_writer_create _constructor = wkt_writer_create
@ -232,6 +244,7 @@ class WKBWriter(IOBase):
srid = property(_get_include_srid, _set_include_srid) srid = property(_get_include_srid, _set_include_srid)
# `ThreadLocalIO` object holds instances of the WKT and WKB reader/writer # `ThreadLocalIO` object holds instances of the WKT and WKB reader/writer
# objects that are local to the thread. The `GEOSGeometry` internals # objects that are local to the thread. The `GEOSGeometry` internals
# access these instances by calling the module-level functions, defined # access these instances by calling the module-level functions, defined
@ -245,6 +258,7 @@ class ThreadLocalIO(threading.local):
thread_context = ThreadLocalIO() thread_context = ThreadLocalIO()
# These module-level routines return the I/O object that is local to the # These module-level routines return the I/O object that is local to the
# thread. If the I/O object does not exist yet it will be initialized. # thread. If the I/O object does not exist yet it will be initialized.
def wkt_r(): def wkt_r():
@ -252,23 +266,27 @@ def wkt_r():
thread_context.wkt_r = _WKTReader() thread_context.wkt_r = _WKTReader()
return thread_context.wkt_r return thread_context.wkt_r
def wkt_w(dim=2): def wkt_w(dim=2):
if not thread_context.wkt_w: if not thread_context.wkt_w:
thread_context.wkt_w = WKTWriter() thread_context.wkt_w = WKTWriter()
thread_context.wkt_w.outdim = dim thread_context.wkt_w.outdim = dim
return thread_context.wkt_w return thread_context.wkt_w
def wkb_r(): def wkb_r():
if not thread_context.wkb_r: if not thread_context.wkb_r:
thread_context.wkb_r = _WKBReader() thread_context.wkb_r = _WKBReader()
return thread_context.wkb_r return thread_context.wkb_r
def wkb_w(dim=2): def wkb_w(dim=2):
if not thread_context.wkb_w: if not thread_context.wkb_w:
thread_context.wkb_w = WKBWriter() thread_context.wkb_w = WKBWriter()
thread_context.wkb_w.outdim = dim thread_context.wkb_w.outdim = dim
return thread_context.wkb_w return thread_context.wkb_w
def ewkb_w(dim=2): def ewkb_w(dim=2):
if not thread_context.ewkb_w: if not thread_context.ewkb_w:
thread_context.ewkb_w = WKBWriter() thread_context.ewkb_w = WKBWriter()

View File

@ -11,6 +11,7 @@ from django.utils.six.moves import xrange
__all__ = ['geos_area', 'geos_distance', 'geos_length'] __all__ = ['geos_area', 'geos_distance', 'geos_length']
### ctypes generator function ### ### ctypes generator function ###
def dbl_from_geom(func, num_geom=1): def dbl_from_geom(func, num_geom=1):
""" """

View File

@ -7,6 +7,7 @@ from django.contrib.gis.geos.libgeos import GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import check_predicate from django.contrib.gis.geos.prototypes.errcheck import check_predicate
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
## Binary & unary predicate functions ## ## Binary & unary predicate functions ##
def binary_predicate(func, *args): def binary_predicate(func, *args):
"For GEOS binary predicate functions." "For GEOS binary predicate functions."
@ -18,6 +19,7 @@ def binary_predicate(func, *args):
func.errcheck = check_predicate func.errcheck = check_predicate
return func return func
def unary_predicate(func): def unary_predicate(func):
"For GEOS unary predicate functions." "For GEOS unary predicate functions."
func.argtypes = [GEOM_PTR] func.argtypes = [GEOM_PTR]

View File

@ -12,6 +12,7 @@ prepared_destroy = GEOSFunc('GEOSPreparedGeom_destroy')
prepared_destroy.argtpes = [PREPGEOM_PTR] prepared_destroy.argtpes = [PREPGEOM_PTR]
prepared_destroy.restype = None prepared_destroy.restype = None
# Prepared geometry binary predicate support. # Prepared geometry binary predicate support.
def prepared_predicate(func): def prepared_predicate(func):
func.argtypes = [PREPGEOM_PTR, GEOM_PTR] func.argtypes = [PREPGEOM_PTR, GEOM_PTR]

View File

@ -1,6 +1,7 @@
import threading import threading
from django.contrib.gis.geos.libgeos import lgeos, notice_h, error_h, CONTEXT_PTR from django.contrib.gis.geos.libgeos import lgeos, notice_h, error_h, CONTEXT_PTR
class GEOSContextHandle(object): class GEOSContextHandle(object):
""" """
Python object representing a GEOS context handle. Python object representing a GEOS context handle.
@ -14,6 +15,7 @@ class GEOSContextHandle(object):
if self.ptr: if self.ptr:
lgeos.finishGEOS_r(self.ptr) lgeos.finishGEOS_r(self.ptr)
# Defining a thread-local object and creating an instance # Defining a thread-local object and creating an instance
# to hold a reference to GEOSContextHandle for this thread. # to hold a reference to GEOSContextHandle for this thread.
class GEOSContext(threading.local): class GEOSContext(threading.local):
@ -21,6 +23,7 @@ class GEOSContext(threading.local):
thread_context = GEOSContext() thread_context = GEOSContext()
class GEOSFunc(object): class GEOSFunc(object):
""" """
Class that serves as a wrapper for GEOS C Functions, and will Class that serves as a wrapper for GEOS C Functions, and will

View File

@ -13,6 +13,7 @@ from django.contrib.gis.geos.prototypes.errcheck import check_geom, check_minus_
from django.contrib.gis.geos.prototypes.geom import geos_char_p from django.contrib.gis.geos.prototypes.geom import geos_char_p
from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
def topology(func, *args, **kwargs): def topology(func, *args, **kwargs):
"For GEOS unary topology functions." "For GEOS unary topology functions."
argtypes = [GEOM_PTR] argtypes = [GEOM_PTR]

View File

@ -16,42 +16,55 @@ if HAS_GEOS:
def api_get_distance(x): def api_get_distance(x):
return x.distance(Point(-200, -200)) return x.distance(Point(-200, -200))
def api_get_buffer(x): def api_get_buffer(x):
return x.buffer(10) return x.buffer(10)
def api_get_geom_typeid(x): def api_get_geom_typeid(x):
return x.geom_typeid return x.geom_typeid
def api_get_num_coords(x): def api_get_num_coords(x):
return x.num_coords return x.num_coords
def api_get_centroid(x): def api_get_centroid(x):
return x.centroid return x.centroid
def api_get_empty(x): def api_get_empty(x):
return x.empty return x.empty
def api_get_valid(x): def api_get_valid(x):
return x.valid return x.valid
def api_get_simple(x): def api_get_simple(x):
return x.simple return x.simple
def api_get_ring(x): def api_get_ring(x):
return x.ring return x.ring
def api_get_boundary(x): def api_get_boundary(x):
return x.boundary return x.boundary
def api_get_convex_hull(x): def api_get_convex_hull(x):
return x.convex_hull return x.convex_hull
def api_get_extent(x): def api_get_extent(x):
return x.extent return x.extent
def api_get_area(x): def api_get_area(x):
return x.area return x.area
def api_get_length(x): def api_get_length(x):
return x.length return x.length

View File

@ -39,18 +39,21 @@ class UserListA(ListMixin):
def _get_single_external(self, index): def _get_single_external(self, index):
return self._list[index] return self._list[index]
class UserListB(UserListA): class UserListB(UserListA):
_mytype = list _mytype = list
def _set_single(self, index, value): def _set_single(self, index, value):
self._list[index] = value self._list[index] = value
def nextRange(length): def nextRange(length):
nextRange.start += 100 nextRange.start += 100
return range(nextRange.start, nextRange.start + length) return range(nextRange.start, nextRange.start + length)
nextRange.start = 0 nextRange.start = 0
class ListMixinTest(unittest.TestCase): class ListMixinTest(unittest.TestCase):
""" """
Tests base class ListMixin by comparing a list clone which is Tests base class ListMixin by comparing a list clone which is
@ -418,5 +421,6 @@ class ListMixinTest(unittest.TestCase):
self.assertTrue(pl < ul, 'cmp for lt self') self.assertTrue(pl < ul, 'cmp for lt self')
self.assertTrue(pl < ul, 'cmp for lt self') self.assertTrue(pl < ul, 'cmp for lt self')
class ListMixinTestSingle(ListMixinTest): class ListMixinTestSingle(ListMixinTest):
listType = UserListB listType = UserListB

View File

@ -1,5 +1,6 @@
from django.core.management.commands.inspectdb import Command as InspectDBCommand from django.core.management.commands.inspectdb import Command as InspectDBCommand
class Command(InspectDBCommand): class Command(InspectDBCommand):
db_module = 'django.contrib.gis.db' db_module = 'django.contrib.gis.db'
gis_tables = {} gis_tables = {}

View File

@ -2,6 +2,7 @@ from optparse import make_option
from django.contrib.gis import gdal from django.contrib.gis import gdal
from django.core.management.base import LabelCommand, CommandError from django.core.management.base import LabelCommand, CommandError
def layer_option(option, opt, value, parser): def layer_option(option, opt, value, parser):
""" """
Callback for `make_option` for the `ogrinspect` `layer_key` Callback for `make_option` for the `ogrinspect` `layer_key`
@ -13,6 +14,7 @@ def layer_option(option, opt, value, parser):
dest = value dest = value
setattr(parser.values, option.dest, dest) setattr(parser.values, option.dest, dest)
def list_option(option, opt, value, parser): def list_option(option, opt, value, parser):
""" """
Callback for `make_option` for `ogrinspect` keywords that require Callback for `make_option` for `ogrinspect` keywords that require
@ -25,6 +27,7 @@ def list_option(option, opt, value, parser):
dest = [s for s in value.split(',')] dest = [s for s in value.split(',')]
setattr(parser.values, option.dest, dest) setattr(parser.values, option.dest, dest)
class Command(LabelCommand): class Command(LabelCommand):
help = ('Inspects the given OGR-compatible data source (e.g., a shapefile) and outputs\n' help = ('Inspects the given OGR-compatible data source (e.g., a shapefile) and outputs\n'
'a GeoDjango model with the given model name. For example:\n' 'a GeoDjango model with the given model name. For example:\n'

View File

@ -6,6 +6,7 @@ from django.utils.six.moves import xrange
from django.contrib.gis.maps.google.overlays import GPolygon, GPolyline, GMarker from django.contrib.gis.maps.google.overlays import GPolygon, GPolyline, GMarker
class GoogleMapException(Exception): class GoogleMapException(Exception):
pass pass
@ -154,6 +155,7 @@ class GoogleMap(object):
"Returns a sequence of GIcon objects in this map." "Returns a sequence of GIcon objects in this map."
return set(marker.icon for marker in self.markers if marker.icon) return set(marker.icon for marker in self.markers if marker.icon)
class GoogleMapSet(GoogleMap): class GoogleMapSet(GoogleMap):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View File

@ -54,6 +54,7 @@ class GEvent(object):
"Returns the parameter part of a GEvent." "Returns the parameter part of a GEvent."
return mark_safe('"%s", %s' % (self.event, self.action)) return mark_safe('"%s", %s' % (self.event, self.action))
@python_2_unicode_compatible @python_2_unicode_compatible
class GOverlayBase(object): class GOverlayBase(object):
def __init__(self): def __init__(self):
@ -71,6 +72,7 @@ class GOverlayBase(object):
"The string representation is the JavaScript API call." "The string representation is the JavaScript API call."
return mark_safe('%s(%s)' % (self.__class__.__name__, self.js_params)) return mark_safe('%s(%s)' % (self.__class__.__name__, self.js_params))
class GPolygon(GOverlayBase): class GPolygon(GOverlayBase):
""" """
A Python wrapper for the Google GPolygon object. For more information A Python wrapper for the Google GPolygon object. For more information
@ -130,6 +132,7 @@ class GPolygon(GOverlayBase):
return '%s, "%s", %s, %s, "%s", %s' % (self.points, self.stroke_color, self.stroke_weight, self.stroke_opacity, return '%s, "%s", %s, %s, "%s", %s' % (self.points, self.stroke_color, self.stroke_weight, self.stroke_opacity,
self.fill_color, self.fill_opacity) self.fill_color, self.fill_opacity)
class GPolyline(GOverlayBase): class GPolyline(GOverlayBase):
""" """
A Python wrapper for the Google GPolyline object. For more information A Python wrapper for the Google GPolyline object. For more information
@ -253,6 +256,7 @@ class GIcon(object):
# equal hash(GIcon('varname')). # equal hash(GIcon('varname')).
return hash(self.__class__) ^ hash(self.varname) return hash(self.__class__) ^ hash(self.varname)
class GMarker(GOverlayBase): class GMarker(GOverlayBase):
""" """
A Python wrapper for the Google GMarker object. For more information A Python wrapper for the Google GMarker object. For more information

View File

@ -7,6 +7,7 @@ from math import pi, sin, log, exp, atan
DTOR = pi / 180. DTOR = pi / 180.
RTOD = 180. / pi RTOD = 180. / pi
class GoogleZoom(object): class GoogleZoom(object):
""" """
GoogleZoom is a utility for performing operations related to the zoom GoogleZoom is a utility for performing operations related to the zoom

View File

@ -37,6 +37,7 @@ def index(request, sitemaps):
xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites}) xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites})
return HttpResponse(xml, content_type='application/xml') return HttpResponse(xml, content_type='application/xml')
def sitemap(request, sitemaps, section=None): def sitemap(request, sitemaps, section=None):
""" """
This view generates a sitemap with additional geographic This view generates a sitemap with additional geographic
@ -65,6 +66,7 @@ def sitemap(request, sitemaps, section=None):
xml = loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls}) xml = loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})
return HttpResponse(xml, content_type='application/xml') return HttpResponse(xml, content_type='application/xml')
def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS): def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):
""" """
This view generates KML for the given app label, model, and field name. This view generates KML for the given app label, model, and field name.
@ -109,6 +111,7 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB
render = render_to_kml render = render_to_kml
return render('gis/kml/placemarks.kml', {'places': placemarks}) return render('gis/kml/placemarks.kml', {'places': placemarks})
def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS): def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS):
""" """
This view returns KMZ for the given app label, model, and field name. This view returns KMZ for the given app label, model, and field name.

View File

@ -1,6 +1,7 @@
from django.contrib.gis.db import models from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class SouthTexasCity(models.Model): class SouthTexasCity(models.Model):
"City model on projected coordinate system for South Texas." "City model on projected coordinate system for South Texas."
@ -11,6 +12,7 @@ class SouthTexasCity(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class SouthTexasCityFt(models.Model): class SouthTexasCityFt(models.Model):
"Same City model as above, but U.S. survey feet are the units." "Same City model as above, but U.S. survey feet are the units."
@ -21,6 +23,7 @@ class SouthTexasCityFt(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class AustraliaCity(models.Model): class AustraliaCity(models.Model):
"City model for Australia, using WGS84." "City model for Australia, using WGS84."
@ -31,6 +34,7 @@ class AustraliaCity(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class CensusZipcode(models.Model): class CensusZipcode(models.Model):
"Model for a few South Texas ZIP codes (in original Census NAD83)." "Model for a few South Texas ZIP codes (in original Census NAD83)."
@ -41,6 +45,7 @@ class CensusZipcode(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class SouthTexasZipcode(models.Model): class SouthTexasZipcode(models.Model):
"Model for a few South Texas ZIP codes." "Model for a few South Texas ZIP codes."
@ -51,6 +56,7 @@ class SouthTexasZipcode(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Interstate(models.Model): class Interstate(models.Model):
"Geodetic model for U.S. Interstates." "Geodetic model for U.S. Interstates."
@ -61,6 +67,7 @@ class Interstate(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class SouthTexasInterstate(models.Model): class SouthTexasInterstate(models.Model):
"Projected model for South Texas Interstates." "Projected model for South Texas Interstates."

View File

@ -1,6 +1,7 @@
from django.contrib.gis.db import models from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class City3D(models.Model): class City3D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -10,6 +11,7 @@ class City3D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Interstate2D(models.Model): class Interstate2D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -19,6 +21,7 @@ class Interstate2D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Interstate3D(models.Model): class Interstate3D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -28,6 +31,7 @@ class Interstate3D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class InterstateProj2D(models.Model): class InterstateProj2D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -37,6 +41,7 @@ class InterstateProj2D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class InterstateProj3D(models.Model): class InterstateProj3D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -46,6 +51,7 @@ class InterstateProj3D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Polygon2D(models.Model): class Polygon2D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -55,6 +61,7 @@ class Polygon2D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Polygon3D(models.Model): class Polygon3D(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -64,14 +71,17 @@ class Polygon3D(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Point2D(models.Model): class Point2D(models.Model):
point = models.PointField() point = models.PointField()
objects = models.GeoManager() objects = models.GeoManager()
class Point3D(models.Model): class Point3D(models.Model):
point = models.PointField(dim=3) point = models.PointField(dim=3)
objects = models.GeoManager() objects = models.GeoManager()
class MultiPoint3D(models.Model): class MultiPoint3D(models.Model):
mpoint = models.MultiPointField(dim=3) mpoint = models.MultiPointField(dim=3)
objects = models.GeoManager() objects = models.GeoManager()

View File

@ -2,6 +2,7 @@ from django.contrib.gis.db import models
from django.contrib.gis import admin from django.contrib.gis import admin
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class City(models.Model): class City(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)

View File

@ -18,6 +18,7 @@ class TestGeoRSS1(feeds.Feed):
def item_geometry(self, item): def item_geometry(self, item):
return item.point return item.point
class TestGeoRSS2(TestGeoRSS1): class TestGeoRSS2(TestGeoRSS1):
def geometry(self, obj): def geometry(self, obj):
# This should attach a <georss:box> element for the extent of # This should attach a <georss:box> element for the extent of
@ -30,9 +31,11 @@ class TestGeoRSS2(TestGeoRSS1):
# Returning a simple tuple for the geometry. # Returning a simple tuple for the geometry.
return item.point.x, item.point.y return item.point.x, item.point.y
class TestGeoAtom1(TestGeoRSS1): class TestGeoAtom1(TestGeoRSS1):
feed_type = feeds.GeoAtom1Feed feed_type = feeds.GeoAtom1Feed
class TestGeoAtom2(TestGeoRSS2): class TestGeoAtom2(TestGeoRSS2):
feed_type = feeds.GeoAtom1Feed feed_type = feeds.GeoAtom1Feed
@ -40,13 +43,16 @@ class TestGeoAtom2(TestGeoRSS2):
# This time we'll use a 2-tuple of coordinates for the box. # This time we'll use a 2-tuple of coordinates for the box.
return ((-123.30, -41.32), (174.78, 48.46)) return ((-123.30, -41.32), (174.78, 48.46))
class TestW3CGeo1(TestGeoRSS1): class TestW3CGeo1(TestGeoRSS1):
feed_type = feeds.W3CGeoFeed feed_type = feeds.W3CGeoFeed
# The following feeds are invalid, and will raise exceptions. # The following feeds are invalid, and will raise exceptions.
class TestW3CGeo2(TestGeoRSS2): class TestW3CGeo2(TestGeoRSS2):
feed_type = feeds.W3CGeoFeed feed_type = feeds.W3CGeoFeed
class TestW3CGeo3(TestGeoRSS1): class TestW3CGeo3(TestGeoRSS1):
feed_type = feeds.W3CGeoFeed feed_type = feeds.W3CGeoFeed

View File

@ -5,6 +5,7 @@ from django.utils.encoding import python_2_unicode_compatible
# MySQL spatial indices can't handle NULL geometries. # MySQL spatial indices can't handle NULL geometries.
null_flag = not mysql null_flag = not mysql
@python_2_unicode_compatible @python_2_unicode_compatible
class Country(models.Model): class Country(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -14,6 +15,7 @@ class Country(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class City(models.Model): class City(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -23,12 +25,14 @@ class City(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
# This is an inherited model from City # This is an inherited model from City
class PennsylvaniaCity(City): class PennsylvaniaCity(City):
county = models.CharField(max_length=30) county = models.CharField(max_length=30)
founded = models.DateTimeField(null=True) founded = models.DateTimeField(null=True)
objects = models.GeoManager() # TODO: This should be implicitly inherited. objects = models.GeoManager() # TODO: This should be implicitly inherited.
@python_2_unicode_compatible @python_2_unicode_compatible
class State(models.Model): class State(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -38,6 +42,7 @@ class State(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Track(models.Model): class Track(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -47,6 +52,7 @@ class Track(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class Truth(models.Model): class Truth(models.Model):
val = models.BooleanField(default=False) val = models.BooleanField(default=False)
objects = models.GeoManager() objects = models.GeoManager()

View File

@ -1,6 +1,7 @@
from django.contrib.gis.db import models from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class City(models.Model): class City(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -10,6 +11,7 @@ class City(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
@python_2_unicode_compatible @python_2_unicode_compatible
class Zipcode(models.Model): class Zipcode(models.Model):
code = models.CharField(max_length=10) code = models.CharField(max_length=10)
@ -19,6 +21,7 @@ class Zipcode(models.Model):
def __str__(self): def __str__(self):
return self.code return self.code
@python_2_unicode_compatible @python_2_unicode_compatible
class County(models.Model): class County(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)

View File

@ -1,5 +1,6 @@
from django.contrib.gis.db import models from django.contrib.gis.db import models
class AllOGRFields(models.Model): class AllOGRFields(models.Model):
f_decimal = models.FloatField() f_decimal = models.FloatField()
f_float = models.FloatField() f_float = models.FloatField()

View File

@ -1,20 +1,24 @@
from django.contrib.gis.db import models from django.contrib.gis.db import models
class State(models.Model): class State(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
objects = models.GeoManager() objects = models.GeoManager()
class County(models.Model): class County(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
state = models.ForeignKey(State) state = models.ForeignKey(State)
mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in NAD83 mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in NAD83
objects = models.GeoManager() objects = models.GeoManager()
class CountyFeat(models.Model): class CountyFeat(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
poly = models.PolygonField(srid=4269) poly = models.PolygonField(srid=4269)
objects = models.GeoManager() objects = models.GeoManager()
class City(models.Model): class City(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
name_txt = models.TextField(default='') name_txt = models.TextField(default='')
@ -24,12 +28,14 @@ class City(models.Model):
point = models.PointField() point = models.PointField()
objects = models.GeoManager() objects = models.GeoManager()
class Interstate(models.Model): class Interstate(models.Model):
name = models.CharField(max_length=20) name = models.CharField(max_length=20)
length = models.DecimalField(max_digits=6, decimal_places=2) length = models.DecimalField(max_digits=6, decimal_places=2)
path = models.LineStringField() path = models.LineStringField()
objects = models.GeoManager() objects = models.GeoManager()
# Same as `City` above, but for testing model inheritance. # Same as `City` above, but for testing model inheritance.
class CityBase(models.Model): class CityBase(models.Model):
name = models.CharField(max_length=25) name = models.CharField(max_length=25)
@ -38,12 +44,15 @@ class CityBase(models.Model):
point = models.PointField() point = models.PointField()
objects = models.GeoManager() objects = models.GeoManager()
class ICity1(CityBase): class ICity1(CityBase):
dt = models.DateField() dt = models.DateField()
class ICity2(ICity1): class ICity2(ICity1):
dt_time = models.DateTimeField(auto_now=True) dt_time = models.DateTimeField(auto_now=True)
class Invalid(models.Model): class Invalid(models.Model):
point = models.PointField() point = models.PointField()

View File

@ -304,6 +304,7 @@ class LayerMapTest(TestCase):
self.assertEqual(City.objects.count(), 1) self.assertEqual(City.objects.count(), 1)
self.assertEqual(City.objects.all()[0].name, "Zürich") self.assertEqual(City.objects.all()[0].name, "Zürich")
class OtherRouter(object): class OtherRouter(object):
def db_for_read(self, model, **hints): def db_for_read(self, model, **hints):
return 'other' return 'other'

View File

@ -1,6 +1,7 @@
from django.contrib.gis.db import models from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class Location(models.Model): class Location(models.Model):
point = models.PointField() point = models.PointField()
@ -9,6 +10,7 @@ class Location(models.Model):
def __str__(self): def __str__(self):
return self.point.wkt return self.point.wkt
@python_2_unicode_compatible @python_2_unicode_compatible
class City(models.Model): class City(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
@ -19,15 +21,18 @@ class City(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class AugmentedLocation(Location): class AugmentedLocation(Location):
extra_text = models.TextField(blank=True) extra_text = models.TextField(blank=True)
objects = models.GeoManager() objects = models.GeoManager()
class DirectoryEntry(models.Model): class DirectoryEntry(models.Model):
listing_text = models.CharField(max_length=50) listing_text = models.CharField(max_length=50)
location = models.ForeignKey(AugmentedLocation) location = models.ForeignKey(AugmentedLocation)
objects = models.GeoManager() objects = models.GeoManager()
@python_2_unicode_compatible @python_2_unicode_compatible
class Parcel(models.Model): class Parcel(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
@ -42,17 +47,20 @@ class Parcel(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
# These use the GeoManager but do not have any geographic fields. # These use the GeoManager but do not have any geographic fields.
class Author(models.Model): class Author(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
dob = models.DateField() dob = models.DateField()
objects = models.GeoManager() objects = models.GeoManager()
class Article(models.Model): class Article(models.Model):
title = models.CharField(max_length=100) title = models.CharField(max_length=100)
author = models.ForeignKey(Author, unique=True) author = models.ForeignKey(Author, unique=True)
objects = models.GeoManager() objects = models.GeoManager()
class Book(models.Model): class Book(models.Model):
title = models.CharField(max_length=100) title = models.CharField(max_length=100)
author = models.ForeignKey(Author, related_name='books', null=True) author = models.ForeignKey(Author, related_name='books', null=True)

View File

@ -264,12 +264,14 @@ class AreaTest(unittest.TestCase):
self.assertEqual(repr(a1), 'Area(sq_m=100.0)') self.assertEqual(repr(a1), 'Area(sq_m=100.0)')
self.assertEqual(repr(a2), 'Area(sq_km=3.5)') self.assertEqual(repr(a2), 'Area(sq_km=3.5)')
def suite(): def suite():
s = unittest.TestSuite() s = unittest.TestSuite()
s.addTest(unittest.makeSuite(DistanceTest)) s.addTest(unittest.makeSuite(DistanceTest))
s.addTest(unittest.makeSuite(AreaTest)) s.addTest(unittest.makeSuite(AreaTest))
return s return s
def run(verbosity=2): def run(verbosity=2):
unittest.TextTestRunner(verbosity=verbosity).run(suite()) unittest.TextTestRunner(verbosity=verbosity).run(suite())

View File

@ -32,6 +32,7 @@ test_srs = ({'srid': 4326,
}, },
) )
@unittest.skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, @unittest.skipUnless(HAS_GDAL and HAS_SPATIALREFSYS,
"SpatialRefSysTest needs gdal support and a spatial database") "SpatialRefSysTest needs gdal support and a spatial database")
class SpatialRefSysTest(unittest.TestCase): class SpatialRefSysTest(unittest.TestCase):
@ -94,10 +95,12 @@ class SpatialRefSysTest(unittest.TestCase):
for i in range(3): for i in range(3):
self.assertAlmostEqual(ellps1[i], ellps2[i], prec[i]) self.assertAlmostEqual(ellps1[i], ellps2[i], prec[i])
def suite(): def suite():
s = unittest.TestSuite() s = unittest.TestSuite()
s.addTest(unittest.makeSuite(SpatialRefSysTest)) s.addTest(unittest.makeSuite(SpatialRefSysTest))
return s return s
def run(verbosity=2): def run(verbosity=2):
unittest.TextTestRunner(verbosity=verbosity).run(suite()) unittest.TextTestRunner(verbosity=verbosity).run(suite())

View File

@ -24,18 +24,23 @@ from django.utils.encoding import force_text
class LayerMapError(Exception): class LayerMapError(Exception):
pass pass
class InvalidString(LayerMapError): class InvalidString(LayerMapError):
pass pass
class InvalidDecimal(LayerMapError): class InvalidDecimal(LayerMapError):
pass pass
class InvalidInteger(LayerMapError): class InvalidInteger(LayerMapError):
pass pass
class MissingForeignKey(LayerMapError): class MissingForeignKey(LayerMapError):
pass pass
class LayerMapping(object): class LayerMapping(object):
"A class that maps OGR Layers to GeoDjango Models." "A class that maps OGR Layers to GeoDjango Models."

View File

@ -7,6 +7,7 @@ produced by the `ogrinfo` utility.
from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.geometries import GEO_CLASSES from django.contrib.gis.gdal.geometries import GEO_CLASSES
def ogrinfo(data_source, num_features=10): def ogrinfo(data_source, num_features=10):
""" """
Walks the available layers in the supplied `data_source`, displaying Walks the available layers in the supplied `data_source`, displaying

View File

@ -9,6 +9,7 @@ from django.contrib.gis.gdal import DataSource
from django.contrib.gis.gdal.field import OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime from django.contrib.gis.gdal.field import OFTDate, OFTDateTime, OFTInteger, OFTReal, OFTString, OFTTime
from django.utils import six from django.utils import six
def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False): def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
""" """
Given a DataSource, generates a dictionary that may be used Given a DataSource, generates a dictionary that may be used
@ -48,6 +49,7 @@ def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
_mapping[geom_name] = prefix + str(gtype).upper() _mapping[geom_name] = prefix + str(gtype).upper()
return _mapping return _mapping
def ogrinspect(*args, **kwargs): def ogrinspect(*args, **kwargs):
""" """
Given a data source (either a string or a DataSource object) and a string Given a data source (either a string or a DataSource object) and a string
@ -118,6 +120,7 @@ def ogrinspect(*args, **kwargs):
""" """
return '\n'.join(s for s in _ogrinspect(*args, **kwargs)) return '\n'.join(s for s in _ogrinspect(*args, **kwargs))
def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None, def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None,
multi_geom=False, name_field=None, imports=True, multi_geom=False, name_field=None, imports=True,
decimal=False, blank=False, null=False): decimal=False, blank=False, null=False):

View File

@ -1,5 +1,6 @@
from django.contrib.gis.gdal import SpatialReference from django.contrib.gis.gdal import SpatialReference
def add_srs_entry(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None, def add_srs_entry(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None,
database=None): database=None):
""" """

View File

@ -4,6 +4,7 @@
from django.utils import six from django.utils import six
def precision_wkt(geom, prec): def precision_wkt(geom, prec):
""" """
Returns WKT text of the geometry according to the given precision (an Returns WKT text of the geometry according to the given precision (an

View File

@ -46,6 +46,7 @@ class MessageDecoder(json.JSONDecoder):
decoded = super(MessageDecoder, self).decode(s, **kwargs) decoded = super(MessageDecoder, self).decode(s, **kwargs)
return self.process_messages(decoded) return self.process_messages(decoded)
class CookieStorage(BaseStorage): class CookieStorage(BaseStorage):
""" """
Stores messages in a cookie. Stores messages in a cookie.

View File

@ -2,6 +2,7 @@ from django.contrib.messages.storage.base import BaseStorage
from django.contrib.messages.storage.cookie import CookieStorage from django.contrib.messages.storage.cookie import CookieStorage
from django.contrib.messages.storage.session import SessionStorage from django.contrib.messages.storage.session import SessionStorage
class FallbackStorage(BaseStorage): class FallbackStorage(BaseStorage):
""" """
Tries to store all messages in the first backend, storing any unstored Tries to store all messages in the first backend, storing any unstored

View File

@ -2,6 +2,7 @@ from django.test import TestCase
from django.contrib.messages.tests.urls import ContactFormViewWithMsg from django.contrib.messages.tests.urls import ContactFormViewWithMsg
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
class SuccessMessageMixinTests(TestCase): class SuccessMessageMixinTests(TestCase):
urls = 'django.contrib.messages.tests.urls' urls = 'django.contrib.messages.tests.urls'

View File

@ -20,6 +20,7 @@ TEMPLATE = """{% if messages %}
{% endif %} {% endif %}
""" """
@never_cache @never_cache
def add(request, message_type): def add(request, message_type):
# don't default to False here, because we want to test that it defaults # don't default to False here, because we want to test that it defaults
@ -35,6 +36,7 @@ def add(request, message_type):
show_url = reverse('django.contrib.messages.tests.urls.show') show_url = reverse('django.contrib.messages.tests.urls.show')
return HttpResponseRedirect(show_url) return HttpResponseRedirect(show_url)
@never_cache @never_cache
def add_template_response(request, message_type): def add_template_response(request, message_type):
for msg in request.POST.getlist('messages'): for msg in request.POST.getlist('messages'):
@ -43,11 +45,13 @@ def add_template_response(request, message_type):
show_url = reverse('django.contrib.messages.tests.urls.show_template_response') show_url = reverse('django.contrib.messages.tests.urls.show_template_response')
return HttpResponseRedirect(show_url) return HttpResponseRedirect(show_url)
@never_cache @never_cache
def show(request): def show(request):
t = Template(TEMPLATE) t = Template(TEMPLATE)
return HttpResponse(t.render(RequestContext(request))) return HttpResponse(t.render(RequestContext(request)))
@never_cache @never_cache
def show_template_response(request): def show_template_response(request):
return TemplateResponse(request, Template(TEMPLATE)) return TemplateResponse(request, Template(TEMPLATE))

View File

@ -3,6 +3,7 @@ from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class Redirect(models.Model): class Redirect(models.Model):
site = models.ForeignKey(Site) site = models.ForeignKey(Site)

View File

@ -20,6 +20,7 @@ from django.contrib.sessions.exceptions import SuspiciousSession
# on case insensitive file systems. # on case insensitive file systems.
VALID_KEY_CHARS = string.ascii_lowercase + string.digits VALID_KEY_CHARS = string.ascii_lowercase + string.digits
class CreateError(Exception): class CreateError(Exception):
""" """
Used internally as a consistent exception type to catch from save (see the Used internally as a consistent exception type to catch from save (see the
@ -27,6 +28,7 @@ class CreateError(Exception):
""" """
pass pass
class SessionBase(object): class SessionBase(object):
""" """
Base class for all Session classes. Base class for all Session classes.

View File

@ -6,6 +6,7 @@ from django.db import IntegrityError, transaction, router
from django.utils import timezone from django.utils import timezone
from django.utils.encoding import force_text from django.utils.encoding import force_text
class SessionStore(SessionBase): class SessionStore(SessionBase):
""" """
Implements database session store. Implements database session store.

View File

@ -13,6 +13,7 @@ from django.utils.encoding import force_text
from django.contrib.sessions.exceptions import InvalidSessionKey from django.contrib.sessions.exceptions import InvalidSessionKey
class SessionStore(SessionBase): class SessionStore(SessionBase):
""" """
Implements a file based session store. Implements a file based session store.

View File

@ -5,6 +5,7 @@ from django.conf import settings
from django.utils.cache import patch_vary_headers from django.utils.cache import patch_vary_headers
from django.utils.http import cookie_date from django.utils.http import cookie_date
class SessionMiddleware(object): class SessionMiddleware(object):
def __init__(self): def __init__(self):
engine = import_module(settings.SESSION_ENGINE) engine = import_module(settings.SESSION_ENGINE)

View File

@ -6,6 +6,7 @@ from django.conf import settings
from .base import SitemapTestsBase from .base import SitemapTestsBase
class FlatpagesSitemapTests(SitemapTestsBase): class FlatpagesSitemapTests(SitemapTestsBase):
@skipUnless("django.contrib.flatpages" in settings.INSTALLED_APPS, @skipUnless("django.contrib.flatpages" in settings.INSTALLED_APPS,

View File

@ -6,6 +6,7 @@ from django.test.utils import override_settings
from .base import SitemapTestsBase from .base import SitemapTestsBase
class HTTPSSitemapTests(SitemapTestsBase): class HTTPSSitemapTests(SitemapTestsBase):
protocol = 'https' protocol = 'https'
urls = 'django.contrib.sitemaps.tests.urls.https' urls = 'django.contrib.sitemaps.tests.urls.https'

View File

@ -2,6 +2,7 @@ from django.conf.urls import patterns
from .http import SimpleSitemap from .http import SimpleSitemap
class HTTPSSitemap(SimpleSitemap): class HTTPSSitemap(SimpleSitemap):
protocol = 'https' protocol = 'https'

View File

@ -9,6 +9,7 @@ from django.template.response import TemplateResponse
from django.utils import six from django.utils import six
from django.utils.http import http_date from django.utils.http import http_date
def x_robots_tag(func): def x_robots_tag(func):
@wraps(func) @wraps(func)
def inner(request, *args, **kwargs): def inner(request, *args, **kwargs):
@ -17,6 +18,7 @@ def x_robots_tag(func):
return response return response
return inner return inner
@x_robots_tag @x_robots_tag
def index(request, sitemaps, def index(request, sitemaps,
template_name='sitemap_index.xml', content_type='application/xml', template_name='sitemap_index.xml', content_type='application/xml',
@ -40,6 +42,7 @@ def index(request, sitemaps,
return TemplateResponse(request, template_name, {'sitemaps': sites}, return TemplateResponse(request, template_name, {'sitemaps': sites},
content_type=content_type) content_type=content_type)
@x_robots_tag @x_robots_tag
def sitemap(request, sitemaps, section=None, def sitemap(request, sitemaps, section=None,
template_name='sitemap.xml', content_type='application/xml'): template_name='sitemap.xml', content_type='application/xml'):

View File

@ -2,6 +2,7 @@ from django.conf import settings
from django.db import models from django.db import models
from django.db.models.fields import FieldDoesNotExist from django.db.models.fields import FieldDoesNotExist
class CurrentSiteManager(models.Manager): class CurrentSiteManager(models.Manager):
"Use this to limit objects to those associated with the current site." "Use this to limit objects to those associated with the current site."
def __init__(self, field_name=None): def __init__(self, field_name=None):

View File

@ -7,6 +7,7 @@ from django.utils.encoding import force_text
from django.contrib.staticfiles import finders from django.contrib.staticfiles import finders
class Command(LabelCommand): class Command(LabelCommand):
help = "Finds the absolute paths for the given static file(s)." help = "Finds the absolute paths for the given static file(s)."
args = "[file ...]" args = "[file ...]"

View File

@ -5,6 +5,7 @@ from django.core.management.commands.runserver import Command as RunserverComman
from django.contrib.staticfiles.handlers import StaticFilesHandler from django.contrib.staticfiles.handlers import StaticFilesHandler
class Command(RunserverCommand): class Command(RunserverCommand):
option_list = RunserverCommand.option_list + ( option_list = RunserverCommand.option_list + (
make_option('--nostatic', action="store_false", dest='use_static_handler', default=True, make_option('--nostatic', action="store_false", dest='use_static_handler', default=True,

View File

@ -3,6 +3,7 @@ import fnmatch
from django.conf import settings from django.conf import settings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
def matches_patterns(path, patterns=None): def matches_patterns(path, patterns=None):
""" """
Return True or False depending on whether the ``path`` should be Return True or False depending on whether the ``path`` should be
@ -15,6 +16,7 @@ def matches_patterns(path, patterns=None):
return True return True
return False return False
def get_files(storage, ignore_patterns=None, location=''): def get_files(storage, ignore_patterns=None, location=''):
""" """
Recursively walk the storage directories yielding the paths Recursively walk the storage directories yielding the paths
@ -37,6 +39,7 @@ def get_files(storage, ignore_patterns=None, location=''):
for fn in get_files(storage, ignore_patterns, dir): for fn in get_files(storage, ignore_patterns, dir):
yield fn yield fn
def check_settings(base_url=None): def check_settings(base_url=None):
""" """
Checks if the staticfiles settings have sane values. Checks if the staticfiles settings have sane values.

View File

@ -13,6 +13,7 @@ from django.views import static
from django.contrib.staticfiles import finders from django.contrib.staticfiles import finders
def serve(request, path, insecure=False, **kwargs): def serve(request, path, insecure=False, **kwargs):
""" """
Serve static files below a given point in the directory structure or Serve static files below a given point in the directory structure or

View File

@ -42,6 +42,7 @@ COMMON_WORDS = ('lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt',
'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua') 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua')
def sentence(): def sentence():
""" """
Returns a randomly generated sentence of lorem ipsum text. Returns a randomly generated sentence of lorem ipsum text.
@ -56,6 +57,7 @@ def sentence():
# Convert to sentence case and add end punctuation. # Convert to sentence case and add end punctuation.
return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.'))
def paragraph(): def paragraph():
""" """
Returns a randomly generated paragraph of lorem ipsum text. Returns a randomly generated paragraph of lorem ipsum text.
@ -64,6 +66,7 @@ def paragraph():
""" """
return ' '.join(sentence() for i in range(random.randint(1, 4))) return ' '.join(sentence() for i in range(random.randint(1, 4)))
def paragraphs(count, common=True): def paragraphs(count, common=True):
""" """
Returns a list of paragraphs as returned by paragraph(). Returns a list of paragraphs as returned by paragraph().
@ -80,6 +83,7 @@ def paragraphs(count, common=True):
paras.append(paragraph()) paras.append(paragraph())
return paras return paras
def words(count, common=True): def words(count, common=True):
""" """
Returns a string of `count` lorem ipsum words separated by a single space. Returns a string of `count` lorem ipsum words separated by a single space.

View File

@ -5,6 +5,7 @@ from django import template
register = template.Library() register = template.Library()
class LoremNode(template.Node): class LoremNode(template.Node):
def __init__(self, count, method, common): def __init__(self, count, method, common):
self.count, self.method, self.common = count, method, common self.count, self.method, self.common = count, method, common
@ -22,6 +23,7 @@ class LoremNode(template.Node):
paras = ['<p>%s</p>' % p for p in paras] paras = ['<p>%s</p>' % p for p in paras]
return '\n\n'.join(paras) return '\n\n'.join(paras)
@register.tag @register.tag
def lorem(parser, token): def lorem(parser, token):
""" """

View File

@ -31,6 +31,7 @@ class Options(object):
self.managed = True self.managed = True
self.proxy = False self.proxy = False
class BaseDatabaseCache(BaseCache): class BaseDatabaseCache(BaseCache):
def __init__(self, table, params): def __init__(self, table, params):
BaseCache.__init__(self, params) BaseCache.__init__(self, params)
@ -40,6 +41,7 @@ class BaseDatabaseCache(BaseCache):
_meta = Options(table) _meta = Options(table)
self.cache_model_class = CacheEntry self.cache_model_class = CacheEntry
class DatabaseCache(BaseDatabaseCache): class DatabaseCache(BaseDatabaseCache):
# This class uses cursors provided by the database connection. This means # This class uses cursors provided by the database connection. This means
@ -198,6 +200,7 @@ class DatabaseCache(BaseDatabaseCache):
cursor = connections[db].cursor() cursor = connections[db].cursor()
cursor.execute('DELETE FROM %s' % table) cursor.execute('DELETE FROM %s' % table)
# For backwards compatibility # For backwards compatibility
class CacheClass(DatabaseCache): class CacheClass(DatabaseCache):
pass pass

View File

@ -2,6 +2,7 @@
from django.core.cache.backends.base import BaseCache, DEFAULT_TIMEOUT from django.core.cache.backends.base import BaseCache, DEFAULT_TIMEOUT
class DummyCache(BaseCache): class DummyCache(BaseCache):
def __init__(self, host, *args, **kwargs): def __init__(self, host, *args, **kwargs):
BaseCache.__init__(self, *args, **kwargs) BaseCache.__init__(self, *args, **kwargs)
@ -41,6 +42,7 @@ class DummyCache(BaseCache):
def clear(self): def clear(self):
pass pass
# For backwards compatibility # For backwards compatibility
class CacheClass(DummyCache): class CacheClass(DummyCache):
pass pass

View File

@ -152,6 +152,7 @@ class FileBasedCache(BaseCache):
except (IOError, OSError): except (IOError, OSError):
pass pass
# For backwards compatibility # For backwards compatibility
class CacheClass(FileBasedCache): class CacheClass(FileBasedCache):
pass pass

View File

@ -157,6 +157,7 @@ class BaseMemcachedCache(six.with_metaclass(BaseMemcachedCacheMethods, BaseCache
def clear(self): def clear(self):
self._cache.flush_all() self._cache.flush_all()
class MemcachedCache(BaseMemcachedCache): class MemcachedCache(BaseMemcachedCache):
"An implementation of a cache binding using python-memcached" "An implementation of a cache binding using python-memcached"
def __init__(self, server, params): def __init__(self, server, params):
@ -171,6 +172,7 @@ class MemcachedCache(BaseMemcachedCache):
self._client = self._lib.Client(self._servers, pickleProtocol=pickle.HIGHEST_PROTOCOL) self._client = self._lib.Client(self._servers, pickleProtocol=pickle.HIGHEST_PROTOCOL)
return self._client return self._client
class PyLibMCCache(BaseMemcachedCache): class PyLibMCCache(BaseMemcachedCache):
"An implementation of a cache binding using pylibmc" "An implementation of a cache binding using pylibmc"
def __init__(self, server, params): def __init__(self, server, params):

View File

@ -2,6 +2,7 @@ from __future__ import unicode_literals
from django.db import models from django.db import models
def check_test_runner(): def check_test_runner():
""" """
Checks if the user has *not* overridden the ``TEST_RUNNER`` setting & Checks if the user has *not* overridden the ``TEST_RUNNER`` setting &
@ -23,6 +24,7 @@ def check_test_runner():
] ]
return ' '.join(message) return ' '.join(message)
def check_boolean_field_default_value(): def check_boolean_field_default_value():
""" """
Checks if there are any BooleanFields without a default value, & Checks if there are any BooleanFields without a default value, &

View File

@ -33,6 +33,7 @@ def csrf(request):
return {'csrf_token': _get_val()} return {'csrf_token': _get_val()}
def debug(request): def debug(request):
"Returns context variables helpful for debugging." "Returns context variables helpful for debugging."
context_extras = {} context_extras = {}
@ -42,6 +43,7 @@ def debug(request):
context_extras['sql_queries'] = connection.queries context_extras['sql_queries'] = connection.queries
return context_extras return context_extras
def i18n(request): def i18n(request):
from django.utils import translation from django.utils import translation
@ -52,11 +54,13 @@ def i18n(request):
return context_extras return context_extras
def tz(request): def tz(request):
from django.utils import timezone from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()} return {'TIME_ZONE': timezone.get_current_timezone_name()}
def static(request): def static(request):
""" """
Adds static-related context variables to the context. Adds static-related context variables to the context.
@ -64,6 +68,7 @@ def static(request):
""" """
return {'STATIC_URL': settings.STATIC_URL} return {'STATIC_URL': settings.STATIC_URL}
def media(request): def media(request):
""" """
Adds media-related context variables to the context. Adds media-related context variables to the context.
@ -71,5 +76,6 @@ def media(request):
""" """
return {'MEDIA_URL': settings.MEDIA_URL} return {'MEDIA_URL': settings.MEDIA_URL}
def request(request): def request(request):
return {'request': request} return {'request': request}

View File

@ -8,6 +8,7 @@ from django.core.files.utils import FileProxyMixin
from django.utils import six from django.utils import six
from django.utils.encoding import force_bytes, python_2_unicode_compatible from django.utils.encoding import force_bytes, python_2_unicode_compatible
@python_2_unicode_compatible @python_2_unicode_compatible
class File(FileProxyMixin): class File(FileProxyMixin):
DEFAULT_CHUNK_SIZE = 64 * 2**10 DEFAULT_CHUNK_SIZE = 64 * 2**10
@ -128,6 +129,7 @@ class File(FileProxyMixin):
def close(self): def close(self):
self.file.close() self.file.close()
@python_2_unicode_compatible @python_2_unicode_compatible
class ContentFile(File): class ContentFile(File):
""" """

View File

@ -39,6 +39,7 @@ try:
except (ImportError, AttributeError): except (ImportError, AttributeError):
pass pass
def fd(f): def fd(f):
"""Get a filedescriptor from something which could be a file or an fd.""" """Get a filedescriptor from something which could be a file or an fd."""
return f.fileno() if hasattr(f, 'fileno') else f return f.fileno() if hasattr(f, 'fileno') else f

View File

@ -24,6 +24,7 @@ except ImportError:
__all__ = ['file_move_safe'] __all__ = ['file_move_safe']
def _samefile(src, dst): def _samefile(src, dst):
# Macintosh, Unix. # Macintosh, Unix.
if hasattr(os.path, 'samefile'): if hasattr(os.path, 'samefile'):
@ -36,6 +37,7 @@ def _samefile(src, dst):
return (os.path.normcase(os.path.abspath(src)) == return (os.path.normcase(os.path.abspath(src)) ==
os.path.normcase(os.path.abspath(dst))) os.path.normcase(os.path.abspath(dst)))
def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_overwrite=False): def file_move_safe(old_file_name, new_file_name, chunk_size = 1024*64, allow_overwrite=False):
""" """
Moves a file from one location to another in the safest way possible. Moves a file from one location to another in the safest way possible.

View File

@ -17,6 +17,7 @@ from django.utils._os import safe_join, abspathu
__all__ = ('Storage', 'FileSystemStorage', 'DefaultStorage', 'default_storage') __all__ = ('Storage', 'FileSystemStorage', 'DefaultStorage', 'default_storage')
class Storage(object): class Storage(object):
""" """
A base storage class, providing some default behaviors that all other A base storage class, providing some default behaviors that all other
@ -142,6 +143,7 @@ class Storage(object):
""" """
raise NotImplementedError('subclasses of Storage must provide a modified_time() method') raise NotImplementedError('subclasses of Storage must provide a modified_time() method')
class FileSystemStorage(Storage): class FileSystemStorage(Storage):
""" """
Standard filesystem storage Standard filesystem storage
@ -292,9 +294,11 @@ class FileSystemStorage(Storage):
def modified_time(self, name): def modified_time(self, name):
return datetime.fromtimestamp(os.path.getmtime(self.path(name))) return datetime.fromtimestamp(os.path.getmtime(self.path(name)))
def get_storage_class(import_path=None): def get_storage_class(import_path=None):
return import_by_path(import_path or settings.DEFAULT_FILE_STORAGE) return import_by_path(import_path or settings.DEFAULT_FILE_STORAGE)
class DefaultStorage(LazyObject): class DefaultStorage(LazyObject):
def _setup(self): def _setup(self):
self._wrapped = get_storage_class()() self._wrapped = get_storage_class()()

View File

@ -17,12 +17,14 @@ __all__ = [
'StopFutureHandlers' 'StopFutureHandlers'
] ]
class UploadFileException(Exception): class UploadFileException(Exception):
""" """
Any error having to do with uploading files. Any error having to do with uploading files.
""" """
pass pass
@python_2_unicode_compatible @python_2_unicode_compatible
class StopUpload(UploadFileException): class StopUpload(UploadFileException):
""" """
@ -42,12 +44,14 @@ class StopUpload(UploadFileException):
else: else:
return 'StopUpload: Consume request data, then halt.' return 'StopUpload: Consume request data, then halt.'
class SkipFile(UploadFileException): class SkipFile(UploadFileException):
""" """
This exception is raised by an upload handler that wants to skip a given file. This exception is raised by an upload handler that wants to skip a given file.
""" """
pass pass
class StopFutureHandlers(UploadFileException): class StopFutureHandlers(UploadFileException):
""" """
Upload handers that have handled a file and do not want future handlers to Upload handers that have handled a file and do not want future handlers to
@ -55,6 +59,7 @@ class StopFutureHandlers(UploadFileException):
""" """
pass pass
class FileUploadHandler(object): class FileUploadHandler(object):
""" """
Base class for streaming upload handlers. Base class for streaming upload handlers.
@ -124,6 +129,7 @@ class FileUploadHandler(object):
""" """
pass pass
class TemporaryFileUploadHandler(FileUploadHandler): class TemporaryFileUploadHandler(FileUploadHandler):
""" """
Upload handler that streams data into a temporary file. Upload handler that streams data into a temporary file.
@ -146,6 +152,7 @@ class TemporaryFileUploadHandler(FileUploadHandler):
self.file.size = file_size self.file.size = file_size
return self.file return self.file
class MemoryFileUploadHandler(FileUploadHandler): class MemoryFileUploadHandler(FileUploadHandler):
""" """
File upload handler to stream uploads into memory (used for small files). File upload handler to stream uploads into memory (used for small files).

View File

@ -1,5 +1,6 @@
"""Base email backend class.""" """Base email backend class."""
class BaseEmailBackend(object): class BaseEmailBackend(object):
""" """
Base class for email backend implementations. Base class for email backend implementations.

View File

@ -6,6 +6,7 @@ import threading
from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend): class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.stream = kwargs.pop('stream', sys.stdout) self.stream = kwargs.pop('stream', sys.stdout)

View File

@ -4,6 +4,7 @@ Dummy email backend that does nothing.
from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend): class EmailBackend(BaseEmailBackend):
def send_messages(self, email_messages): def send_messages(self, email_messages):
return len(list(email_messages)) return len(list(email_messages))

View File

@ -8,6 +8,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend
from django.utils import six from django.utils import six
class EmailBackend(ConsoleEmailBackend): class EmailBackend(ConsoleEmailBackend):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self._fname = None self._fname = None

View File

@ -5,6 +5,7 @@ Backend for test environment.
from django.core import mail from django.core import mail
from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend): class EmailBackend(BaseEmailBackend):
"""A email backend for use during test sessions. """A email backend for use during test sessions.

View File

@ -17,6 +17,7 @@ from django import get_version
# doesn't have to reload every time it's called. # doesn't have to reload every time it's called.
_commands = None _commands = None
def find_commands(management_dir): def find_commands(management_dir):
""" """
Given a path to a management directory, returns a list of all the command Given a path to a management directory, returns a list of all the command
@ -31,6 +32,7 @@ def find_commands(management_dir):
except OSError: except OSError:
return [] return []
def find_management_module(app_name): def find_management_module(app_name):
""" """
Determines the path to the management module for the given app_name, Determines the path to the management module for the given app_name,
@ -66,6 +68,7 @@ def find_management_module(app_name):
f.close() f.close()
return path return path
def load_command_class(app_name, name): def load_command_class(app_name, name):
""" """
Given a command name and an application name, returns the Command Given a command name and an application name, returns the Command
@ -75,6 +78,7 @@ def load_command_class(app_name, name):
module = import_module('%s.management.commands.%s' % (app_name, name)) module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command() return module.Command()
def get_commands(): def get_commands():
""" """
Returns a dictionary mapping command names to their callback applications. Returns a dictionary mapping command names to their callback applications.
@ -121,6 +125,7 @@ def get_commands():
return _commands return _commands
def call_command(name, *args, **options): def call_command(name, *args, **options):
""" """
Calls the given command, with the given options and args/kwargs. Calls the given command, with the given options and args/kwargs.
@ -158,6 +163,7 @@ def call_command(name, *args, **options):
return klass.execute(*args, **defaults) return klass.execute(*args, **defaults)
class LaxOptionParser(OptionParser): class LaxOptionParser(OptionParser):
""" """
An option parser that doesn't raise any errors on unknown options. An option parser that doesn't raise any errors on unknown options.
@ -212,6 +218,7 @@ class LaxOptionParser(OptionParser):
except: # Needed because we might need to catch a SystemExit except: # Needed because we might need to catch a SystemExit
largs.append(arg) largs.append(arg)
class ManagementUtility(object): class ManagementUtility(object):
""" """
Encapsulates the logic of the django-admin.py and manage.py utilities. Encapsulates the logic of the django-admin.py and manage.py utilities.
@ -400,6 +407,7 @@ class ManagementUtility(object):
else: else:
self.fetch_command(subcommand).run_from_argv(self.argv) self.fetch_command(subcommand).run_from_argv(self.argv)
def execute_from_command_line(argv=None): def execute_from_command_line(argv=None):
""" """
A simple method that runs a ManagementUtility. A simple method that runs a ManagementUtility.

View File

@ -7,6 +7,7 @@ import sys
from django.utils import termcolors from django.utils import termcolors
def supports_color(): def supports_color():
""" """
Returns True if the running system's terminal supports color, and False Returns True if the running system's terminal supports color, and False
@ -19,6 +20,7 @@ def supports_color():
return False return False
return True return True
def color_style(): def color_style():
"""Returns a Style object with the Django color scheme.""" """Returns a Style object with the Django color scheme."""
if not supports_color(): if not supports_color():
@ -43,6 +45,7 @@ def color_style():
style = no_style() style = no_style()
return style return style
def no_style(): def no_style():
"""Returns a Style object that has no colors.""" """Returns a Style object that has no colors."""
class dummy: class dummy:

View File

@ -8,6 +8,7 @@ from django.core.management.base import BaseCommand, CommandError
from django.core.management.utils import find_command, popen_wrapper from django.core.management.utils import find_command, popen_wrapper
from django.utils._os import npath from django.utils._os import npath
def has_bom(fn): def has_bom(fn):
with open(fn, 'rb') as f: with open(fn, 'rb') as f:
sample = f.read(4) sample = f.read(4)
@ -15,6 +16,7 @@ def has_bom(fn):
sample.startswith(codecs.BOM_UTF16_LE) or \ sample.startswith(codecs.BOM_UTF16_LE) or \
sample.startswith(codecs.BOM_UTF16_BE) sample.startswith(codecs.BOM_UTF16_BE)
def compile_messages(stdout, locale=None): def compile_messages(stdout, locale=None):
program = 'msgfmt' program = 'msgfmt'
if find_command(program) is None: if find_command(program) is None:

View File

@ -3,6 +3,7 @@ from optparse import make_option
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(BaseCommand): class Command(BaseCommand):
help = ("Runs the command-line client for specified database, or the " help = ("Runs the command-line client for specified database, or the "
"default database if none is provided.") "default database if none is provided.")

View File

@ -2,10 +2,12 @@ from optparse import make_option
from django.core.management.base import NoArgsCommand from django.core.management.base import NoArgsCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')): def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Converts a module namespace to a Python dictionary.""" """Converts a module namespace to a Python dictionary."""
return dict((k, repr(v)) for k, v in module.__dict__.items() if not omittable(k)) return dict((k, repr(v)) for k, v in module.__dict__.items() if not omittable(k))
class Command(NoArgsCommand): class Command(NoArgsCommand):
help = """Displays differences between the current settings.py and Django's help = """Displays differences between the current settings.py and Django's
default settings. Settings that don't appear in the defaults are default settings. Settings that don't appear in the defaults are

View File

@ -152,6 +152,7 @@ class Command(BaseCommand):
raise raise
raise CommandError("Unable to serialize database: %s" % e) raise CommandError("Unable to serialize database: %s" % e)
def sort_dependencies(app_list): def sort_dependencies(app_list):
"""Sort a list of app,modellist pairs into a single list of models. """Sort a list of app,modellist pairs into a single list of models.

View File

@ -150,6 +150,7 @@ class TranslatableFile(object):
if is_templatized: if is_templatized:
os.unlink(work_file) os.unlink(work_file)
def write_pot_file(potfile, msgs): def write_pot_file(potfile, msgs):
""" """
Write the :param potfile: POT file with the :param msgs: contents, Write the :param potfile: POT file with the :param msgs: contents,

View File

@ -2,6 +2,7 @@ import warnings
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
class Command(BaseCommand): class Command(BaseCommand):
help = "Runs this project as a FastCGI application. Requires flup." help = "Runs this project as a FastCGI application. Requires flup."
args = '[various KEY=val options, use `runfcgi help` for help]' args = '[various KEY=val options, use `runfcgi help` for help]'

View File

@ -6,6 +6,7 @@ from django.core.management.base import AppCommand
from django.core.management.sql import sql_create from django.core.management.sql import sql_create
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(AppCommand): class Command(AppCommand):
help = "Prints the CREATE TABLE SQL statements for the given app name(s)." help = "Prints the CREATE TABLE SQL statements for the given app name(s)."

View File

@ -6,6 +6,7 @@ from django.core.management.base import AppCommand
from django.core.management.sql import sql_delete from django.core.management.sql import sql_delete
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(AppCommand): class Command(AppCommand):
help = "Prints the DROP TABLE SQL statements for the given app name(s)." help = "Prints the DROP TABLE SQL statements for the given app name(s)."

View File

@ -6,6 +6,7 @@ from django.core.management.base import AppCommand
from django.core.management.sql import sql_custom from django.core.management.sql import sql_custom
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(AppCommand): class Command(AppCommand):
help = "Prints the custom table modifying SQL statements for the given app name(s)." help = "Prints the custom table modifying SQL statements for the given app name(s)."

View File

@ -6,6 +6,7 @@ from django.core.management.base import AppCommand
from django.core.management.sql import sql_destroy_indexes from django.core.management.sql import sql_destroy_indexes
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(AppCommand): class Command(AppCommand):
help = "Prints the DROP INDEX SQL statements for the given model module name(s)." help = "Prints the DROP INDEX SQL statements for the given model module name(s)."

View File

@ -6,6 +6,7 @@ from django.core.management.base import NoArgsCommand
from django.core.management.sql import sql_flush from django.core.management.sql import sql_flush
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(NoArgsCommand): 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." 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."

View File

@ -6,6 +6,7 @@ from django.core.management.base import AppCommand
from django.core.management.sql import sql_indexes from django.core.management.sql import sql_indexes
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(AppCommand): class Command(AppCommand):
help = "Prints the CREATE INDEX SQL statements for the given model module name(s)." help = "Prints the CREATE INDEX SQL statements for the given model module name(s)."

Some files were not shown because too many files have changed in this diff Show More