code
stringlengths
1
1.72M
language
stringclasses
1 value
from django.core import signals from django.dispatch import dispatcher from django import http import sys class BaseHandler(object): def __init__(self): self._request_middleware = self._view_middleware = self._response_middleware = self._exception_middleware = None def load_middleware(self): """ Populate middleware lists from settings.MIDDLEWARE_CLASSES. Must be called after the environment is fixed (see __call__). """ from django.conf import settings from django.core import exceptions self._request_middleware = [] self._view_middleware = [] self._response_middleware = [] self._exception_middleware = [] for middleware_path in settings.MIDDLEWARE_CLASSES: try: dot = middleware_path.rindex('.') except ValueError: raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:] try: mod = __import__(mw_module, {}, {}, ['']) except ImportError, e: raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e) try: mw_class = getattr(mod, mw_classname) except AttributeError: raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname) try: mw_instance = mw_class() except exceptions.MiddlewareNotUsed: continue if hasattr(mw_instance, 'process_request'): self._request_middleware.append(mw_instance.process_request) if hasattr(mw_instance, 'process_view'): self._view_middleware.append(mw_instance.process_view) if hasattr(mw_instance, 'process_response'): self._response_middleware.insert(0, mw_instance.process_response) if hasattr(mw_instance, 'process_exception'): self._exception_middleware.insert(0, mw_instance.process_exception) def get_response(self, request): "Returns an HttpResponse object for the given HttpRequest" from django.core import exceptions, urlresolvers from django.core.mail import mail_admins from django.conf import settings # Apply request middleware for middleware_method in self._request_middleware: response = middleware_method(request) if response: return response # Get urlconf from request object, if available. Otherwise use default. urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) try: callback, callback_args, callback_kwargs = resolver.resolve(request.path) # Apply view middleware for middleware_method in self._view_middleware: response = middleware_method(request, callback, callback_args, callback_kwargs) if response: return response try: response = callback(request, *callback_args, **callback_kwargs) except Exception, e: # If the view raised an exception, run it through exception # middleware, and if the exception middleware returns a # response, use that. Otherwise, reraise the exception. for middleware_method in self._exception_middleware: response = middleware_method(request, e) if response: return response raise # Complain if the view returned None (a common error). if response is None: try: view_name = callback.func_name # If it's a function except AttributeError: view_name = callback.__class__.__name__ + '.__call__' # If it's a class raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name) return response except http.Http404, e: if settings.DEBUG: from django.views import debug return debug.technical_404_response(request, e) else: callback, param_dict = resolver.resolve404() return callback(request, **param_dict) except exceptions.PermissionDenied: return http.HttpResponseForbidden('<h1>Permission denied</h1>') except SystemExit: pass # See http://code.djangoproject.com/ticket/1023 except: # Handle everything else, including SuspiciousOperation, etc. if settings.DEBUG: from django.views import debug return debug.technical_500_response(request, *sys.exc_info()) else: # Get the exception info now, in case another exception is thrown later. exc_info = sys.exc_info() receivers = dispatcher.send(signal=signals.got_request_exception) # When DEBUG is False, send an error message to the admins. subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr) mail_admins(subject, message, fail_silently=True) # Return an HttpResponse that displays a friendly error message. callback, param_dict = resolver.resolve500() return callback(request, **param_dict) def _get_traceback(self, exc_info=None): "Helper function to return the traceback as a string" import traceback return '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info())))
Python
import hotshot, time, os from django.core.handlers.modpython import ModPythonHandler PROFILE_DATA_DIR = "/var/log/cmsprofile" def handler(req): ''' Handler that uses hotshot to store profile data. Stores profile data in PROFILE_DATA_DIR. Since hotshot has no way (that I know of) to append profile data to a single file, each request gets its own profile. The file names are in the format <url>.<n>.prof where <url> is the request path with "/" replaced by ".", and <n> is a timestamp with microseconds to prevent overwriting files. Use the gather_profile_stats.py script to gather these individual request profiles into aggregated profiles by request path. ''' profname = "%s.%.3f.prof" % (req.uri.strip("/").replace('/', '.'), time.time()) profname = os.path.join(PROFILE_DATA_DIR, profname) prof = hotshot.Profile(profname) return prof.runcall(ModPythonHandler(), req)
Python
from django.core.handlers.base import BaseHandler from django.core import signals from django.dispatch import dispatcher from django.utils import datastructures from django import http from pprint import pformat from shutil import copyfileobj try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html STATUS_CODE_TEXT = { 100: 'CONTINUE', 101: 'SWITCHING PROTOCOLS', 200: 'OK', 201: 'CREATED', 202: 'ACCEPTED', 203: 'NON-AUTHORITATIVE INFORMATION', 204: 'NO CONTENT', 205: 'RESET CONTENT', 206: 'PARTIAL CONTENT', 300: 'MULTIPLE CHOICES', 301: 'MOVED PERMANENTLY', 302: 'FOUND', 303: 'SEE OTHER', 304: 'NOT MODIFIED', 305: 'USE PROXY', 306: 'RESERVED', 307: 'TEMPORARY REDIRECT', 400: 'BAD REQUEST', 401: 'UNAUTHORIZED', 402: 'PAYMENT REQUIRED', 403: 'FORBIDDEN', 404: 'NOT FOUND', 405: 'METHOD NOT ALLOWED', 406: 'NOT ACCEPTABLE', 407: 'PROXY AUTHENTICATION REQUIRED', 408: 'REQUEST TIMEOUT', 409: 'CONFLICT', 410: 'GONE', 411: 'LENGTH REQUIRED', 412: 'PRECONDITION FAILED', 413: 'REQUEST ENTITY TOO LARGE', 414: 'REQUEST-URI TOO LONG', 415: 'UNSUPPORTED MEDIA TYPE', 416: 'REQUESTED RANGE NOT SATISFIABLE', 417: 'EXPECTATION FAILED', 500: 'INTERNAL SERVER ERROR', 501: 'NOT IMPLEMENTED', 502: 'BAD GATEWAY', 503: 'SERVICE UNAVAILABLE', 504: 'GATEWAY TIMEOUT', 505: 'HTTP VERSION NOT SUPPORTED', } def safe_copyfileobj(fsrc, fdst, length=16*1024, size=0): """ A version of shutil.copyfileobj that will not read more than 'size' bytes. This makes it safe from clients sending more than CONTENT_LENGTH bytes of data in the body. """ if not size: return while size > 0: buf = fsrc.read(min(length, size)) if not buf: break fdst.write(buf) size -= len(buf) class WSGIRequest(http.HttpRequest): def __init__(self, environ): self.environ = environ self.path = environ['PATH_INFO'] self.META = environ self.method = environ['REQUEST_METHOD'].upper() def __repr__(self): # Since this is called as part of error handling, we need to be very # robust against potentially malformed input. try: get = pformat(self.GET) except: get = '<could not parse>' try: post = pformat(self.POST) except: post = '<could not parse>' try: cookies = pformat(self.COOKIES) except: cookies = '<could not parse>' try: meta = pformat(self.META) except: meta = '<could not parse>' return '<WSGIRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \ (get, post, cookies, meta) def get_full_path(self): return '%s%s' % (self.path, self.environ.get('QUERY_STRING', '') and ('?' + self.environ.get('QUERY_STRING', '')) or '') def is_secure(self): return self.environ.has_key('HTTPS') and self.environ['HTTPS'] == 'on' def _load_post_and_files(self): # Populates self._post and self._files if self.method == 'POST': if self.environ.get('CONTENT_TYPE', '').startswith('multipart'): header_dict = dict([(k, v) for k, v in self.environ.items() if k.startswith('HTTP_')]) header_dict['Content-Type'] = self.environ.get('CONTENT_TYPE', '') self._post, self._files = http.parse_file_upload(header_dict, self.raw_post_data) else: self._post, self._files = http.QueryDict(self.raw_post_data), datastructures.MultiValueDict() else: self._post, self._files = http.QueryDict(''), datastructures.MultiValueDict() def _get_request(self): if not hasattr(self, '_request'): self._request = datastructures.MergeDict(self.POST, self.GET) return self._request def _get_get(self): if not hasattr(self, '_get'): # The WSGI spec says 'QUERY_STRING' may be absent. self._get = http.QueryDict(self.environ.get('QUERY_STRING', '')) return self._get def _set_get(self, get): self._get = get def _get_post(self): if not hasattr(self, '_post'): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_cookies(self): if not hasattr(self, '_cookies'): self._cookies = http.parse_cookie(self.environ.get('HTTP_COOKIE', '')) return self._cookies def _set_cookies(self, cookies): self._cookies = cookies def _get_files(self): if not hasattr(self, '_files'): self._load_post_and_files() return self._files def _get_raw_post_data(self): try: return self._raw_post_data except AttributeError: buf = StringIO() try: # CONTENT_LENGTH might be absent if POST doesn't have content at all (lighttpd) content_length = int(self.environ.get('CONTENT_LENGTH', 0)) except ValueError: # if CONTENT_LENGTH was empty string or not an integer content_length = 0 safe_copyfileobj(self.environ['wsgi.input'], buf, size=content_length) self._raw_post_data = buf.getvalue() buf.close() return self._raw_post_data GET = property(_get_get, _set_get) POST = property(_get_post, _set_post) COOKIES = property(_get_cookies, _set_cookies) FILES = property(_get_files) REQUEST = property(_get_request) raw_post_data = property(_get_raw_post_data) class WSGIHandler(BaseHandler): def __call__(self, environ, start_response): from django.conf import settings # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._request_middleware is None: self.load_middleware() dispatcher.send(signal=signals.request_started) try: request = WSGIRequest(environ) response = self.get_response(request) # Apply response middleware for middleware_method in self._response_middleware: response = middleware_method(request, response) finally: dispatcher.send(signal=signals.request_finished) try: status_text = STATUS_CODE_TEXT[response.status_code] except KeyError: status_text = 'UNKNOWN STATUS CODE' status = '%s %s' % (response.status_code, status_text) response_headers = response.headers.items() for c in response.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) start_response(status, response_headers) return response
Python
from django.core import validators from django.core.exceptions import PermissionDenied from django.utils.html import escape from django.conf import settings from django.utils.translation import gettext, ngettext FORM_FIELD_ID_PREFIX = 'id_' class EmptyValue(Exception): "This is raised when empty data is provided" pass class Manipulator(object): # List of permission strings. User must have at least one to manipulate. # None means everybody has permission. required_permission = '' def __init__(self): # List of FormField objects self.fields = [] def __getitem__(self, field_name): "Looks up field by field name; raises KeyError on failure" for field in self.fields: if field.field_name == field_name: return field raise KeyError, "Field %s not found\n%s" % (field_name, repr(self.fields)) def __delitem__(self, field_name): "Deletes the field with the given field name; raises KeyError on failure" for i, field in enumerate(self.fields): if field.field_name == field_name: del self.fields[i] return raise KeyError, "Field %s not found" % field_name def check_permissions(self, user): """Confirms user has required permissions to use this manipulator; raises PermissionDenied on failure.""" if self.required_permission is None: return if user.has_perm(self.required_permission): return raise PermissionDenied def prepare(self, new_data): """ Makes any necessary preparations to new_data, in place, before data has been validated. """ for field in self.fields: field.prepare(new_data) def get_validation_errors(self, new_data): "Returns dictionary mapping field_names to error-message lists" errors = {} self.prepare(new_data) for field in self.fields: errors.update(field.get_validation_errors(new_data)) val_name = 'validate_%s' % field.field_name if hasattr(self, val_name): val = getattr(self, val_name) try: field.run_validator(new_data, val) except (validators.ValidationError, validators.CriticalValidationError), e: errors.setdefault(field.field_name, []).extend(e.messages) # if field.is_required and not new_data.get(field.field_name, False): # errors.setdefault(field.field_name, []).append(gettext_lazy('This field is required.')) # continue # try: # validator_list = field.validator_list # if hasattr(self, 'validate_%s' % field.field_name): # validator_list.append(getattr(self, 'validate_%s' % field.field_name)) # for validator in validator_list: # if field.is_required or new_data.get(field.field_name, False) or hasattr(validator, 'always_test'): # try: # if hasattr(field, 'requires_data_list'): # validator(new_data.getlist(field.field_name), new_data) # else: # validator(new_data.get(field.field_name, ''), new_data) # except validators.ValidationError, e: # errors.setdefault(field.field_name, []).extend(e.messages) # # If a CriticalValidationError is raised, ignore any other ValidationErrors # # for this particular field # except validators.CriticalValidationError, e: # errors.setdefault(field.field_name, []).extend(e.messages) return errors def save(self, new_data): "Saves the changes and returns the new object" # changes is a dictionary-like object keyed by field_name raise NotImplementedError def do_html2python(self, new_data): """ Convert the data from HTML data types to Python datatypes, changing the object in place. This happens after validation but before storage. This must happen after validation because html2python functions aren't expected to deal with invalid input. """ for field in self.fields: field.convert_post_data(new_data) class FormWrapper(object): """ A wrapper linking a Manipulator to the template system. This allows dictionary-style lookups of formfields. It also handles feeding prepopulated data and validation error messages to the formfield objects. """ def __init__(self, manipulator, data=None, error_dict=None, edit_inline=True): self.manipulator = manipulator if data is None: data = {} if error_dict is None: error_dict = {} self.data = data self.error_dict = error_dict self._inline_collections = None self.edit_inline = edit_inline def __repr__(self): return repr(self.__dict__) def __getitem__(self, key): for field in self.manipulator.fields: if field.field_name == key: data = field.extract_data(self.data) return FormFieldWrapper(field, data, self.error_dict.get(field.field_name, [])) if self.edit_inline: self.fill_inline_collections() for inline_collection in self._inline_collections: # The 'orig_name' comparison is for backwards compatibility # with hand-crafted forms. if inline_collection.name == key or (':' not in key and inline_collection.orig_name == key): return inline_collection raise KeyError, "Could not find Formfield or InlineObjectCollection named %r" % key def fill_inline_collections(self): if not self._inline_collections: ic = [] related_objects = self.manipulator.get_related_objects() for rel_obj in related_objects: data = rel_obj.extract_data(self.data) inline_collection = InlineObjectCollection(self.manipulator, rel_obj, data, self.error_dict) ic.append(inline_collection) self._inline_collections = ic def has_errors(self): return self.error_dict != {} def _get_fields(self): try: return self._fields except AttributeError: self._fields = [self.__getitem__(field.field_name) for field in self.manipulator.fields] return self._fields fields = property(_get_fields) class FormFieldWrapper(object): "A bridge between the template system and an individual form field. Used by FormWrapper." def __init__(self, formfield, data, error_list): self.formfield, self.data, self.error_list = formfield, data, error_list self.field_name = self.formfield.field_name # for convenience in templates def __str__(self): "Renders the field" return str(self.formfield.render(self.data)) def __repr__(self): return '<FormFieldWrapper for "%s">' % self.formfield.field_name def field_list(self): """ Like __str__(), but returns a list. Use this when the field's render() method returns a list. """ return self.formfield.render(self.data) def errors(self): return self.error_list def html_error_list(self): if self.errors(): return '<ul class="errorlist"><li>%s</li></ul>' % '</li><li>'.join([escape(e) for e in self.errors()]) else: return '' def get_id(self): return self.formfield.get_id() class FormFieldCollection(FormFieldWrapper): "A utility class that gives the template access to a dict of FormFieldWrappers" def __init__(self, formfield_dict): self.formfield_dict = formfield_dict def __str__(self): return str(self.formfield_dict) def __getitem__(self, template_key): "Look up field by template key; raise KeyError on failure" return self.formfield_dict[template_key] def __repr__(self): return "<FormFieldCollection: %s>" % self.formfield_dict def errors(self): "Returns list of all errors in this collection's formfields" errors = [] for field in self.formfield_dict.values(): if hasattr(field, 'errors'): errors.extend(field.errors()) return errors def has_errors(self): return bool(len(self.errors())) def html_combined_error_list(self): return ''.join([field.html_error_list() for field in self.formfield_dict.values() if hasattr(field, 'errors')]) class InlineObjectCollection(object): "An object that acts like a sparse list of form field collections." def __init__(self, parent_manipulator, rel_obj, data, errors): self.parent_manipulator = parent_manipulator self.rel_obj = rel_obj self.data = data self.errors = errors self._collections = None self.name = rel_obj.name # This is the name used prior to fixing #1839. Needs for backwards # compatibility. self.orig_name = rel_obj.opts.module_name def __len__(self): self.fill() return self._collections.__len__() def __getitem__(self, k): self.fill() return self._collections.__getitem__(k) def __setitem__(self, k, v): self.fill() return self._collections.__setitem__(k,v) def __delitem__(self, k): self.fill() return self._collections.__delitem__(k) def __iter__(self): self.fill() return iter(self._collections.values()) def items(self): self.fill() return self._collections.items() def fill(self): if self._collections: return else: var_name = self.rel_obj.opts.object_name.lower() collections = {} orig = None if hasattr(self.parent_manipulator, 'original_object'): orig = self.parent_manipulator.original_object orig_list = self.rel_obj.get_list(orig) for i, instance in enumerate(orig_list): collection = {'original': instance} for f in self.rel_obj.editable_fields(): for field_name in f.get_manipulator_field_names(''): full_field_name = '%s.%d.%s' % (var_name, i, field_name) field = self.parent_manipulator[full_field_name] data = field.extract_data(self.data) errors = self.errors.get(full_field_name, []) collection[field_name] = FormFieldWrapper(field, data, errors) collections[i] = FormFieldCollection(collection) self._collections = collections class FormField(object): """Abstract class representing a form field. Classes that extend FormField should define the following attributes: field_name The field's name for use by programs. validator_list A list of validation tests (callback functions) that the data for this field must pass in order to be added or changed. is_required A Boolean. Is it a required field? Subclasses should also implement a render(data) method, which is responsible for rending the form field in XHTML. """ def __str__(self): return self.render('') def __repr__(self): return 'FormField "%s"' % self.field_name def prepare(self, new_data): "Hook for doing something to new_data (in place) before validation." pass def html2python(data): "Hook for converting an HTML datatype (e.g. 'on' for checkboxes) to a Python type" return data html2python = staticmethod(html2python) def render(self, data): raise NotImplementedError def get_member_name(self): if hasattr(self, 'member_name'): return self.member_name else: return self.field_name def extract_data(self, data_dict): if hasattr(self, 'requires_data_list') and hasattr(data_dict, 'getlist'): data = data_dict.getlist(self.get_member_name()) else: data = data_dict.get(self.get_member_name(), None) if data is None: data = '' return data def convert_post_data(self, new_data): name = self.get_member_name() if new_data.has_key(self.field_name): d = new_data.getlist(self.field_name) try: converted_data = [self.__class__.html2python(data) for data in d] except ValueError: converted_data = d new_data.setlist(name, converted_data) else: try: #individual fields deal with None values themselves new_data.setlist(name, [self.__class__.html2python(None)]) except EmptyValue: new_data.setlist(name, []) def run_validator(self, new_data, validator): if self.is_required or new_data.get(self.field_name, False) or hasattr(validator, 'always_test'): if hasattr(self, 'requires_data_list'): validator(new_data.getlist(self.field_name), new_data) else: validator(new_data.get(self.field_name, ''), new_data) def get_validation_errors(self, new_data): errors = {} if self.is_required and not new_data.get(self.field_name, False): errors.setdefault(self.field_name, []).append(gettext('This field is required.')) return errors try: for validator in self.validator_list: try: self.run_validator(new_data, validator) except validators.ValidationError, e: errors.setdefault(self.field_name, []).extend(e.messages) # If a CriticalValidationError is raised, ignore any other ValidationErrors # for this particular field except validators.CriticalValidationError, e: errors.setdefault(self.field_name, []).extend(e.messages) return errors def get_id(self): "Returns the HTML 'id' attribute for this form field." return FORM_FIELD_ID_PREFIX + self.field_name #################### # GENERIC WIDGETS # #################### class TextField(FormField): input_type = "text" def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None, member_name=None): if validator_list is None: validator_list = [] self.field_name = field_name self.length, self.maxlength = length, maxlength self.is_required = is_required self.validator_list = [self.isValidLength, self.hasNoNewlines] + validator_list if member_name != None: self.member_name = member_name def isValidLength(self, data, form): if data and self.maxlength and len(data.decode(settings.DEFAULT_CHARSET)) > self.maxlength: raise validators.ValidationError, ngettext("Ensure your text is less than %s character.", "Ensure your text is less than %s characters.", self.maxlength) % self.maxlength def hasNoNewlines(self, data, form): if data and '\n' in data: raise validators.ValidationError, gettext("Line breaks are not allowed here.") def render(self, data): if data is None: data = '' maxlength = '' if self.maxlength: maxlength = 'maxlength="%s" ' % self.maxlength if isinstance(data, unicode): data = data.encode(settings.DEFAULT_CHARSET) return '<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \ (self.input_type, self.get_id(), self.__class__.__name__, self.is_required and ' required' or '', self.field_name, self.length, escape(data), maxlength) def html2python(data): return data html2python = staticmethod(html2python) class PasswordField(TextField): input_type = "password" class LargeTextField(TextField): def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=None, maxlength=None): if validator_list is None: validator_list = [] self.field_name = field_name self.rows, self.cols, self.is_required = rows, cols, is_required self.validator_list = validator_list[:] if maxlength: self.validator_list.append(self.isValidLength) self.maxlength = maxlength def render(self, data): if data is None: data = '' if isinstance(data, unicode): data = data.encode(settings.DEFAULT_CHARSET) return '<textarea id="%s" class="v%s%s" name="%s" rows="%s" cols="%s">%s</textarea>' % \ (self.get_id(), self.__class__.__name__, self.is_required and ' required' or '', self.field_name, self.rows, self.cols, escape(data)) class HiddenField(FormField): def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] self.field_name, self.is_required = field_name, is_required self.validator_list = validator_list[:] def render(self, data): return '<input type="hidden" id="%s" name="%s" value="%s" />' % \ (self.get_id(), self.field_name, escape(data)) class CheckboxField(FormField): def __init__(self, field_name, checked_by_default=False, validator_list=None, is_required=False): if validator_list is None: validator_list = [] self.field_name = field_name self.checked_by_default = checked_by_default self.is_required = is_required self.validator_list = validator_list[:] def render(self, data): checked_html = '' if data or (data is '' and self.checked_by_default): checked_html = ' checked="checked"' return '<input type="checkbox" id="%s" class="v%s" name="%s"%s />' % \ (self.get_id(), self.__class__.__name__, self.field_name, checked_html) def html2python(data): "Convert value from browser ('on' or '') to a Python boolean" if data == 'on': return True return False html2python = staticmethod(html2python) class SelectField(FormField): def __init__(self, field_name, choices=None, size=1, is_required=False, validator_list=None, member_name=None): if validator_list is None: validator_list = [] if choices is None: choices = [] self.field_name = field_name # choices is a list of (value, human-readable key) tuples because order matters self.choices, self.size, self.is_required = choices, size, is_required self.validator_list = [self.isValidChoice] + validator_list if member_name != None: self.member_name = member_name def render(self, data): output = ['<select id="%s" class="v%s%s" name="%s" size="%s">' % \ (self.get_id(), self.__class__.__name__, self.is_required and ' required' or '', self.field_name, self.size)] str_data = str(data) # normalize to string for value, display_name in self.choices: selected_html = '' if str(value) == str_data: selected_html = ' selected="selected"' output.append(' <option value="%s"%s>%s</option>' % (escape(value), selected_html, escape(display_name))) output.append(' </select>') return '\n'.join(output) def isValidChoice(self, data, form): str_data = str(data) str_choices = [str(item[0]) for item in self.choices] if str_data not in str_choices: raise validators.ValidationError, gettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data': str_data, 'choices': str_choices} class NullSelectField(SelectField): "This SelectField converts blank fields to None" def html2python(data): if not data: return None return data html2python = staticmethod(html2python) class RadioSelectField(FormField): def __init__(self, field_name, choices=None, ul_class='', is_required=False, validator_list=None, member_name=None): if validator_list is None: validator_list = [] if choices is None: choices = [] self.field_name = field_name # choices is a list of (value, human-readable key) tuples because order matters self.choices, self.is_required = choices, is_required self.validator_list = [self.isValidChoice] + validator_list self.ul_class = ul_class if member_name != None: self.member_name = member_name def render(self, data): """ Returns a special object, RadioFieldRenderer, that is iterable *and* has a default str() rendered output. This allows for flexible use in templates. You can just use the default rendering: {{ field_name }} ...which will output the radio buttons in an unordered list. Or, you can manually traverse each radio option for special layout: {% for option in field_name.field_list %} {{ option.field }} {{ option.label }}<br /> {% endfor %} """ class RadioFieldRenderer: def __init__(self, datalist, ul_class): self.datalist, self.ul_class = datalist, ul_class def __str__(self): "Default str() output for this radio field -- a <ul>" output = ['<ul%s>' % (self.ul_class and ' class="%s"' % self.ul_class or '')] output.extend(['<li>%s %s</li>' % (d['field'], d['label']) for d in self.datalist]) output.append('</ul>') return ''.join(output) def __iter__(self): for d in self.datalist: yield d def __len__(self): return len(self.datalist) datalist = [] str_data = str(data) # normalize to string for i, (value, display_name) in enumerate(self.choices): selected_html = '' if str(value) == str_data: selected_html = ' checked="checked"' datalist.append({ 'value': value, 'name': display_name, 'field': '<input type="radio" id="%s" name="%s" value="%s"%s/>' % \ (self.get_id() + '_' + str(i), self.field_name, value, selected_html), 'label': '<label for="%s">%s</label>' % \ (self.get_id() + '_' + str(i), display_name), }) return RadioFieldRenderer(datalist, self.ul_class) def isValidChoice(self, data, form): str_data = str(data) str_choices = [str(item[0]) for item in self.choices] if str_data not in str_choices: raise validators.ValidationError, gettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data':str_data, 'choices':str_choices} class NullBooleanField(SelectField): "This SelectField provides 'Yes', 'No' and 'Unknown', mapping results to True, False or None" def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] SelectField.__init__(self, field_name, choices=[('1', _('Unknown')), ('2', _('Yes')), ('3', _('No'))], is_required=is_required, validator_list=validator_list) def render(self, data): if data is None: data = '1' elif data == True: data = '2' elif data == False: data = '3' return SelectField.render(self, data) def html2python(data): return {None: None, '1': None, '2': True, '3': False}[data] html2python = staticmethod(html2python) class SelectMultipleField(SelectField): requires_data_list = True def render(self, data): output = ['<select id="%s" class="v%s%s" name="%s" size="%s" multiple="multiple">' % \ (self.get_id(), self.__class__.__name__, self.is_required and ' required' or '', self.field_name, self.size)] str_data_list = map(str, data) # normalize to strings for value, choice in self.choices: selected_html = '' if str(value) in str_data_list: selected_html = ' selected="selected"' output.append(' <option value="%s"%s>%s</option>' % (escape(value), selected_html, escape(choice))) output.append(' </select>') return '\n'.join(output) def isValidChoice(self, field_data, all_data): # data is something like ['1', '2', '3'] str_choices = [str(item[0]) for item in self.choices] for val in map(str, field_data): if val not in str_choices: raise validators.ValidationError, gettext("Select a valid choice; '%(data)s' is not in %(choices)s.") % {'data':val, 'choices':str_choices} def html2python(data): if data is None: raise EmptyValue return data html2python = staticmethod(html2python) class CheckboxSelectMultipleField(SelectMultipleField): """ This has an identical interface to SelectMultipleField, except the rendered widget is different. Instead of a <select multiple>, this widget outputs a <ul> of <input type="checkbox">es. Of course, that results in multiple form elements for the same "single" field, so this class's prepare() method flattens the split data elements back into the single list that validators, renderers and save() expect. """ requires_data_list = True def __init__(self, field_name, choices=None, ul_class='', validator_list=None): if validator_list is None: validator_list = [] if choices is None: choices = [] self.ul_class = ul_class SelectMultipleField.__init__(self, field_name, choices, size=1, is_required=False, validator_list=validator_list) def prepare(self, new_data): # new_data has "split" this field into several fields, so flatten it # back into a single list. data_list = [] for value, readable_value in self.choices: if new_data.get('%s%s' % (self.field_name, value), '') == 'on': data_list.append(value) new_data.setlist(self.field_name, data_list) def render(self, data): output = ['<ul%s>' % (self.ul_class and ' class="%s"' % self.ul_class or '')] str_data_list = map(str, data) # normalize to strings for value, choice in self.choices: checked_html = '' if str(value) in str_data_list: checked_html = ' checked="checked"' field_name = '%s%s' % (self.field_name, value) output.append('<li><input type="checkbox" id="%s" class="v%s" name="%s"%s value="on" /> <label for="%s">%s</label></li>' % \ (self.get_id() + escape(value), self.__class__.__name__, field_name, checked_html, self.get_id() + escape(value), choice)) output.append('</ul>') return '\n'.join(output) #################### # FILE UPLOADS # #################### class FileUploadField(FormField): def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] self.field_name, self.is_required = field_name, is_required self.validator_list = [self.isNonEmptyFile] + validator_list def isNonEmptyFile(self, field_data, all_data): try: content = field_data['content'] except TypeError: raise validators.CriticalValidationError, gettext("No file was submitted. Check the encoding type on the form.") if not content: raise validators.CriticalValidationError, gettext("The submitted file is empty.") def render(self, data): return '<input type="file" id="%s" class="v%s" name="%s" />' % \ (self.get_id(), self.__class__.__name__, self.field_name) def html2python(data): if data is None: raise EmptyValue return data html2python = staticmethod(html2python) class ImageUploadField(FileUploadField): "A FileUploadField that raises CriticalValidationError if the uploaded file isn't an image." def __init__(self, *args, **kwargs): FileUploadField.__init__(self, *args, **kwargs) self.validator_list.insert(0, self.isValidImage) def isValidImage(self, field_data, all_data): try: validators.isValidImage(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages #################### # INTEGERS/FLOATS # #################### class IntegerField(TextField): def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None, member_name=None): if validator_list is None: validator_list = [] validator_list = [self.isInteger] + validator_list if member_name is not None: self.member_name = member_name TextField.__init__(self, field_name, length, maxlength, is_required, validator_list) def isInteger(self, field_data, all_data): try: validators.isInteger(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def html2python(data): if data == '' or data is None: return None return int(data) html2python = staticmethod(html2python) class SmallIntegerField(IntegerField): def __init__(self, field_name, length=5, maxlength=5, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isSmallInteger] + validator_list IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list) def isSmallInteger(self, field_data, all_data): if not -32768 <= int(field_data) <= 32767: raise validators.CriticalValidationError, gettext("Enter a whole number between -32,768 and 32,767.") class PositiveIntegerField(IntegerField): def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isPositive] + validator_list IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list) def isPositive(self, field_data, all_data): if int(field_data) < 0: raise validators.CriticalValidationError, gettext("Enter a positive number.") class PositiveSmallIntegerField(IntegerField): def __init__(self, field_name, length=5, maxlength=None, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isPositiveSmall] + validator_list IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list) def isPositiveSmall(self, field_data, all_data): if not 0 <= int(field_data) <= 32767: raise validators.CriticalValidationError, gettext("Enter a whole number between 0 and 32,767.") class FloatField(TextField): def __init__(self, field_name, max_digits, decimal_places, is_required=False, validator_list=None): if validator_list is None: validator_list = [] self.max_digits, self.decimal_places = max_digits, decimal_places validator_list = [self.isValidFloat] + validator_list TextField.__init__(self, field_name, max_digits+2, max_digits+2, is_required, validator_list) def isValidFloat(self, field_data, all_data): v = validators.IsValidFloat(self.max_digits, self.decimal_places) try: v(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def html2python(data): if data == '' or data is None: return None return float(data) html2python = staticmethod(html2python) #################### # DATES AND TIMES # #################### class DatetimeField(TextField): """A FormField that automatically converts its data to a datetime.datetime object. The data should be in the format YYYY-MM-DD HH:MM:SS.""" def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None): if validator_list is None: validator_list = [] self.field_name = field_name self.length, self.maxlength = length, maxlength self.is_required = is_required self.validator_list = [validators.isValidANSIDatetime] + validator_list def html2python(data): "Converts the field into a datetime.datetime object" import datetime try: date, time = data.split() y, m, d = date.split('-') timebits = time.split(':') h, mn = timebits[:2] if len(timebits) > 2: s = int(timebits[2]) else: s = 0 return datetime.datetime(int(y), int(m), int(d), int(h), int(mn), s) except ValueError: return None html2python = staticmethod(html2python) class DateField(TextField): """A FormField that automatically converts its data to a datetime.date object. The data should be in the format YYYY-MM-DD.""" def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidDate] + validator_list TextField.__init__(self, field_name, length=10, maxlength=10, is_required=is_required, validator_list=validator_list) def isValidDate(self, field_data, all_data): try: validators.isValidANSIDate(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def html2python(data): "Converts the field into a datetime.date object" import time, datetime try: time_tuple = time.strptime(data, '%Y-%m-%d') return datetime.date(*time_tuple[0:3]) except (ValueError, TypeError): return None html2python = staticmethod(html2python) class TimeField(TextField): """A FormField that automatically converts its data to a datetime.time object. The data should be in the format HH:MM:SS or HH:MM:SS.mmmmmm.""" def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidTime] + validator_list TextField.__init__(self, field_name, length=8, maxlength=8, is_required=is_required, validator_list=validator_list) def isValidTime(self, field_data, all_data): try: validators.isValidANSITime(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def html2python(data): "Converts the field into a datetime.time object" import time, datetime try: part_list = data.split('.') try: time_tuple = time.strptime(part_list[0], '%H:%M:%S') except ValueError: # seconds weren't provided time_tuple = time.strptime(part_list[0], '%H:%M') t = datetime.time(*time_tuple[3:6]) if (len(part_list) == 2): t = t.replace(microsecond=int(part_list[1])) return t except (ValueError, TypeError, AttributeError): return None html2python = staticmethod(html2python) #################### # INTERNET-RELATED # #################### class EmailField(TextField): "A convenience FormField for validating e-mail addresses" def __init__(self, field_name, length=50, maxlength=75, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidEmail] + validator_list TextField.__init__(self, field_name, length, maxlength=maxlength, is_required=is_required, validator_list=validator_list) def isValidEmail(self, field_data, all_data): try: validators.isValidEmail(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages class URLField(TextField): "A convenience FormField for validating URLs" def __init__(self, field_name, length=50, maxlength=200, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidURL] + validator_list TextField.__init__(self, field_name, length=length, maxlength=maxlength, is_required=is_required, validator_list=validator_list) def isValidURL(self, field_data, all_data): try: validators.isValidURL(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages class IPAddressField(TextField): def __init__(self, field_name, length=15, maxlength=15, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidIPAddress] + validator_list TextField.__init__(self, field_name, length=length, maxlength=maxlength, is_required=is_required, validator_list=validator_list) def isValidIPAddress(self, field_data, all_data): try: validators.isValidIPAddress4(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def html2python(data): return data or None html2python = staticmethod(html2python) #################### # MISCELLANEOUS # #################### class FilePathField(SelectField): "A SelectField whose choices are the files in a given directory." def __init__(self, field_name, path, match=None, recursive=False, is_required=False, validator_list=None): import os from django.db.models import BLANK_CHOICE_DASH if match is not None: import re match_re = re.compile(match) choices = not is_required and BLANK_CHOICE_DASH[:] or [] if recursive: for root, dirs, files in os.walk(path): for f in files: if match is None or match_re.search(f): choices.append((os.path.join(root, f), f)) else: try: for f in os.listdir(path): full_file = os.path.join(path, f) if os.path.isfile(full_file) and (match is None or match_re.search(f)): choices.append((full_file, f)) except OSError: pass SelectField.__init__(self, field_name, choices, 1, is_required, validator_list) class PhoneNumberField(TextField): "A convenience FormField for validating phone numbers (e.g. '630-555-1234')" def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidPhone] + validator_list TextField.__init__(self, field_name, length=12, maxlength=12, is_required=is_required, validator_list=validator_list) def isValidPhone(self, field_data, all_data): try: validators.isValidPhone(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages class USStateField(TextField): "A convenience FormField for validating U.S. states (e.g. 'IL')" def __init__(self, field_name, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isValidUSState] + validator_list TextField.__init__(self, field_name, length=2, maxlength=2, is_required=is_required, validator_list=validator_list) def isValidUSState(self, field_data, all_data): try: validators.isValidUSState(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def html2python(data): if data: return data.upper() # Should always be stored in upper case return data html2python = staticmethod(html2python) class CommaSeparatedIntegerField(TextField): "A convenience FormField for validating comma-separated integer fields" def __init__(self, field_name, maxlength=None, is_required=False, validator_list=None): if validator_list is None: validator_list = [] validator_list = [self.isCommaSeparatedIntegerList] + validator_list TextField.__init__(self, field_name, length=20, maxlength=maxlength, is_required=is_required, validator_list=validator_list) def isCommaSeparatedIntegerList(self, field_data, all_data): try: validators.isCommaSeparatedIntegerList(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages def render(self, data): if data is None: data = '' elif isinstance(data, (list, tuple)): data = ','.join(data) return super(CommaSeparatedIntegerField, self).render(data) class RawIdAdminField(CommaSeparatedIntegerField): def html2python(data): if data: return data.split(',') else: return [] html2python = staticmethod(html2python) class XMLLargeTextField(LargeTextField): """ A LargeTextField with an XML validator. The schema_path argument is the full path to a Relax NG compact schema to validate against. """ def __init__(self, field_name, schema_path, **kwargs): self.schema_path = schema_path kwargs.setdefault('validator_list', []).insert(0, self.isValidXML) LargeTextField.__init__(self, field_name, **kwargs) def isValidXML(self, field_data, all_data): v = validators.RelaxNGCompact(self.schema_path) try: v(field_data, all_data) except validators.ValidationError, e: raise validators.CriticalValidationError, e.messages
Python
from django.conf import settings from django import http from django.core.mail import mail_managers import md5 import re class CommonMiddleware(object): """ "Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - ETags: If the USE_ETAGS setting is set, ETags will be calculated from the entire page content and Not Modified responses will be returned appropriately. """ def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents if request.META.has_key('HTTP_USER_AGENT'): for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): return http.HttpResponseForbidden('<h1>Forbidden</h1>') # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW host = http.get_host(request) old_url = [host, request.path] new_url = old_url[:] if settings.PREPEND_WWW and old_url[0] and not old_url[0].startswith('www.'): new_url[0] = 'www.' + old_url[0] # Append a slash if append_slash is set and the URL doesn't have a # trailing slash or a file extension. if settings.APPEND_SLASH and (old_url[1][-1] != '/') and ('.' not in old_url[1].split('/')[-1]): new_url[1] = new_url[1] + '/' if settings.DEBUG and request.method == 'POST': raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1]) if new_url != old_url: # Redirect if new_url[0]: newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], new_url[1]) else: newurl = new_url[1] if request.GET: newurl += '?' + request.GET.urlencode() return http.HttpResponsePermanentRedirect(newurl) return None def process_response(self, request, response): "Check for a flat page (for 404s) and calculate the Etag, if needed." if response.status_code == 404: if settings.SEND_BROKEN_LINK_EMAILS: # If the referrer was from an internal link or a non-search-engine site, # send a note to the managers. domain = http.get_host(request) referer = request.META.get('HTTP_REFERER', None) is_internal = _is_internal_request(domain, referer) path = request.get_full_path() if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer): ua = request.META.get('HTTP_USER_AGENT', '<none>') mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" % (referer, request.get_full_path(), ua)) return response # Use ETags, if requested. if settings.USE_ETAGS: etag = md5.new(response.content).hexdigest() if request.META.get('HTTP_IF_NONE_MATCH') == etag: response = http.HttpResponseNotModified() else: response['ETag'] = etag return response def _is_ignorable_404(uri): "Returns True if a 404 at the given URL *shouldn't* notify the site managers" for start in settings.IGNORABLE_404_STARTS: if uri.startswith(start): return True for end in settings.IGNORABLE_404_ENDS: if uri.endswith(end): return True return False def _is_internal_request(domain, referer): "Return true if the referring URL is the same domain as the current request" # Different subdomains are treated as different domains. return referer is not None and re.match("^https?://%s/" % re.escape(domain), referer)
Python
from django.conf import settings from django.core.cache import cache from django.utils.cache import get_cache_key, learn_cache_key, patch_response_headers class CacheMiddleware(object): """ Cache middleware. If this is enabled, each Django-powered page will be cached for CACHE_MIDDLEWARE_SECONDS seconds. Cache is based on URLs. Only parameter-less GET or HEAD-requests with status code 200 are cached. If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests (i.e., those node made by a logged-in user) will be cached. This is a simple and effective way of avoiding the caching of the Django admin (and any other user-specific content). This middleware expects that a HEAD request is answered with a response exactly like the corresponding GET request. When a hit occurs, a shallow copy of the original response object is returned from process_request. Pages will be cached based on the contents of the request headers listed in the response's "Vary" header. This means that pages shouldn't change their "Vary" header. This middleware also sets ETag, Last-Modified, Expires and Cache-Control headers on the response object. """ def __init__(self, cache_timeout=None, key_prefix=None, cache_anonymous_only=None): self.cache_timeout = cache_timeout if cache_timeout is None: self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = key_prefix if key_prefix is None: self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_anonymous_only is None: self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) else: self.cache_anonymous_only = cache_anonymous_only def process_request(self, request): "Checks whether the page is already cached and returns the cached version if available." if self.cache_anonymous_only: assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if not request.method in ('GET', 'HEAD') or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. if self.cache_anonymous_only and request.user.is_authenticated(): request._cache_update_cache = False return None # Don't cache requests from authenticated users. cache_key = get_cache_key(request, self.key_prefix) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. request._cache_update_cache = False return response def process_response(self, request, response): "Sets the cache, if needed." if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache: # We don't need to update the cache, just return. return response if request.method != 'GET': # This is a stronger requirement than above. It is needed # because of interactions between this middleware and the # HTTPMiddleware, which throws the body of a HEAD-request # away before this middleware gets a chance to cache it. return response if not response.status_code == 200: return response patch_response_headers(response, self.cache_timeout) cache_key = learn_cache_key(request, response, self.cache_timeout, self.key_prefix) cache.set(cache_key, response, self.cache_timeout) return response
Python
import re from django.utils.text import compress_string from django.utils.cache import patch_vary_headers re_accepts_gzip = re.compile(r'\bgzip\b') class GZipMiddleware(object): """ This middleware compresses content if the browser allows gzip compression. It sets the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header. """ def process_response(self, request, response): patch_vary_headers(response, ('Accept-Encoding',)) # Avoid gzipping if we've already got a content-encoding or if the # content-type is Javascript (silly IE...) is_js = "javascript" in response.headers.get('Content-Type', '').lower() if response.has_header('Content-Encoding') or is_js: return response ae = request.META.get('HTTP_ACCEPT_ENCODING', '') if not re_accepts_gzip.search(ae): return response response.content = compress_string(response.content) response['Content-Encoding'] = 'gzip' response['Content-Length'] = str(len(response.content)) return response
Python
"this is the locale selecting middleware that will look at accept headers" from django.utils.cache import patch_vary_headers from django.utils import translation class LocaleMiddleware(object): """ This is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course). """ def process_request(self, request): language = translation.get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): patch_vary_headers(response, ('Accept-Language',)) response['Content-Language'] = translation.get_language() translation.deactivate() return response
Python
from django.conf import settings from django import http class XViewMiddleware(object): """ Adds an X-View header to internal HEAD requests -- used by the documentation system. """ def process_view(self, request, view_func, view_args, view_kwargs): """ If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, quickly return with an x-header indicating the view function. This is used by the documentation module to lookup the view function for an arbitrary page. """ if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or (request.user.is_authenticated() and request.user.is_staff)): response = http.HttpResponse() response['X-View'] = "%s.%s" % (view_func.__module__, view_func.__name__) return response
Python
import datetime class ConditionalGetMiddleware(object): """ Handles conditional GET operations. If the response has a ETag or Last-Modified header, and the request has If-None-Match or If-Modified-Since, the response is replaced by an HttpNotModified. Removes the content from any response to a HEAD request. Also sets the Date and Content-Length response-headers. """ def process_response(self, request, response): now = datetime.datetime.utcnow() response['Date'] = now.strftime('%a, %d %b %Y %H:%M:%S GMT') if not response.has_header('Content-Length'): response['Content-Length'] = str(len(response.content)) if response.has_header('ETag'): if_none_match = request.META.get('HTTP_IF_NONE_MATCH', None) if if_none_match == response['ETag']: response.status_code = 304 response.content = '' response['Content-Length'] = '0' if response.has_header('Last-Modified'): last_mod = response['Last-Modified'] if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE', None) if if_modified_since == response['Last-Modified']: response.status_code = 304 response.content = '' response['Content-Length'] = '0' if request.method == 'HEAD': response.content = '' return response class SetRemoteAddrFromForwardedFor(object): """ Middleware that sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, if the latter is set. This is useful if you're sitting behind a reverse proxy that causes each request's REMOTE_ADDR to be set to 127.0.0.1. Note that this does NOT validate HTTP_X_FORWARDED_FOR. If you're not behind a reverse proxy that sets HTTP_X_FORWARDED_FOR automatically, do not use this middleware. Anybody can spoof the value of HTTP_X_FORWARDED_FOR, and because this sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, that means anybody can "fake" their IP address. Only use this when you can absolutely trust the value of HTTP_X_FORWARDED_FOR. """ def process_request(self, request): try: real_ip = request.META['HTTP_X_FORWARDED_FOR'] except KeyError: return None else: # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. # Take just the first one. real_ip = real_ip.split(",")[0] request.META['REMOTE_ADDR'] = real_ip
Python
from django.db import transaction class TransactionMiddleware(object): """ Transaction middleware. If this is enabled, each view function will be run with commit_on_response activated - that way a save() doesn't do a direct commit, the commit is done when a successful response is created. If an exception happens, the database is rolled back. """ def process_request(self, request): """Enters transaction management""" transaction.enter_transaction_management() transaction.managed(True) def process_exception(self, request, exception): """Rolls back the database and leaves transaction management""" if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() def process_response(self, request, response): """Commits and leaves transaction management.""" if transaction.is_managed(): if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() return response
Python
def curry(_curried_func, *args, **kwargs): def _curried(*moreargs, **morekwargs): return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs)) return _curried class Promise: """ This is just a base class for the proxy class created in the closure of the lazy function. It can be used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turns any callable into a lazy evaluated callable. You need to give result classes or types -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ class __proxy__(Promise): # This inner class encapsulates the code that should be evaluated # lazily. On calling of one of the magic methods it will force # the evaluation and store the result. Afterwards, the result # is delivered directly. So the result is memoized. def __init__(self, args, kw): self.__func = func self.__args = args self.__kw = kw self.__dispatch = {} for resultclass in resultclasses: self.__dispatch[resultclass] = {} for (k, v) in resultclass.__dict__.items(): setattr(self, k, self.__promise__(resultclass, k, v)) def __promise__(self, klass, funcname, func): # Builds a wrapper around some magic method and registers that magic # method for the given type and method name. def __wrapper__(*args, **kw): # Automatically triggers the evaluation of a lazy value and # applies the given magic method of the result type. res = self.__func(*self.__args, **self.__kw) return self.__dispatch[type(res)][funcname](res, *args, **kw) if not self.__dispatch.has_key(klass): self.__dispatch[klass] = {} self.__dispatch[klass][funcname] = func return __wrapper__ def __wrapper__(*args, **kw): # Creates the proxy object, instead of the actual value. return __proxy__(args, kw) return __wrapper__
Python
""" termcolors.py """ color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) background = dict([(color_names[x], '4%s' % x) for x in range(8)]) del color_names RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold' 'underscore' 'blink' 'reverse' 'conceal' 'noreset' - string will not be auto-terminated with the RESET code Examples: colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize() colorize('goodbye', opts=('underscore',)) print colorize('first line', fg='red', opts=('noreset',)) print 'this should be red too' print colorize('and so should this') print 'this should not be red' """ text = str(text) code_list = [] if text == '' and len(opts) == 1 and opts[0] == 'reset': return '\x1b[%sm' % RESET for k, v in kwargs.iteritems(): if k == 'fg': code_list.append(foreground[v]) elif k == 'bg': code_list.append(background[v]) for o in opts: if o in opt_dict: code_list.append(opt_dict[o]) if 'noreset' not in opts: text = text + '\x1b[%sm' % RESET return ('\x1b[%sm' % ';'.join(code_list)) + text def make_style(opts=(), **kwargs): """ Returns a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print bold_red('hello') KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',)) """ return lambda text: colorize(text, opts, **kwargs)
Python
import os import sys if os.name == 'posix': def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null'): "Robustly turn into a UNIX daemon, running in our_home_dir." # First fork try: if os.fork() > 0: sys.exit(0) # kill off parent except OSError, e: sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) os.setsid() os.chdir(our_home_dir) os.umask(0) # Second fork try: if os.fork() > 0: sys.exit(0) except OSError, e: sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) si = open('/dev/null', 'r') so = open(out_log, 'a+', 0) se = open(err_log, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) else: def become_daemon(our_home_dir='.', out_log=None, err_log=None): """ If we're not running under a POSIX system, just simulate the daemon mode by doing redirections and directory changing. """ os.chdir(our_home_dir) os.umask(0) sys.stdin.close() sys.stdout.close() sys.stderr.close() if err_log: sys.stderr = open(err_log, 'a', 0) else: sys.stderr = NullDevice() if out_log: sys.stdout = open(out_log, 'a', 0) else: sys.stdout = NullDevice() class NullDevice: "A writeable object that writes to nowhere -- like /dev/null." def write(self, s): pass
Python
""" Synchronization primitives: - reader-writer lock (preference to writers) (Contributed to Django by eugene@lazutkin.com) """ try: import threading except ImportError: import dummy_threading as threading class RWLock: """ Classic implementation of reader-writer lock with preference to writers. Readers can access a resource simultaneously. Writers get an exclusive access. API is self-descriptive: reader_enters() reader_leaves() writer_enters() writer_leaves() """ def __init__(self): self.mutex = threading.RLock() self.can_read = threading.Semaphore(0) self.can_write = threading.Semaphore(0) self.active_readers = 0 self.active_writers = 0 self.waiting_readers = 0 self.waiting_writers = 0 def reader_enters(self): self.mutex.acquire() try: if self.active_writers == 0 and self.waiting_writers == 0: self.active_readers += 1 self.can_read.release() else: self.waiting_readers += 1 finally: self.mutex.release() self.can_read.acquire() def reader_leaves(self): self.mutex.acquire() try: self.active_readers -= 1 if self.active_readers == 0 and self.waiting_writers != 0: self.active_writers += 1 self.waiting_writers -= 1 self.can_write.release() finally: self.mutex.release() def writer_enters(self): self.mutex.acquire() try: if self.active_writers == 0 and self.waiting_writers == 0 and self.active_readers == 0: self.active_writers += 1 self.can_write.release() else: self.waiting_writers += 1 finally: self.mutex.release() self.can_write.acquire() def writer_leaves(self): self.mutex.acquire() try: self.active_writers -= 1 if self.waiting_writers != 0: self.active_writers += 1 self.waiting_writers -= 1 self.can_write.release() elif self.waiting_readers != 0: t = self.waiting_readers self.waiting_readers = 0 self.active_readers += t while t > 0: self.can_read.release() t -= 1 finally: self.mutex.release()
Python
# Performance note: I benchmarked this code using a set instead of # a list for the stopwords and was surprised to find that the list # performed /better/ than the set - maybe because it's only a small # list. stopwords = ''' i a an are as at be by for from how in is it of on or that the this to was what when where '''.split() def strip_stopwords(sentence): "Removes stopwords - also normalizes whitespace" words = sentence.split() sentence = [] for word in words: if word.lower() not in stopwords: sentence.append(word) return ' '.join(sentence)
Python
"""Thread-local objects (Note that this module provides a Python version of thread threading.local class. Depending on the version of Python you're using, there may be a faster one available. You should always import the local class from threading.) Thread-local objects support the management of thread-local data. If you have data that you want to be local to a thread, simply create a thread-local object and use its attributes: >>> mydata = local() >>> mydata.number = 42 >>> mydata.number 42 You can also access the local-object's dictionary: >>> mydata.__dict__ {'number': 42} >>> mydata.__dict__.setdefault('widgets', []) [] >>> mydata.widgets [] What's important about thread-local objects is that their data are local to a thread. If we access the data in a different thread: >>> log = [] >>> def f(): ... items = mydata.__dict__.items() ... items.sort() ... log.append(items) ... mydata.number = 11 ... log.append(mydata.number) >>> import threading >>> thread = threading.Thread(target=f) >>> thread.start() >>> thread.join() >>> log [[], 11] we get different data. Furthermore, changes made in the other thread don't affect data seen in this thread: >>> mydata.number 42 Of course, values you get from a local object, including a __dict__ attribute, are for whatever thread was current at the time the attribute was read. For that reason, you generally don't want to save these values across threads, as they apply only to the thread they came from. You can create custom local objects by subclassing the local class: >>> class MyLocal(local): ... number = 2 ... initialized = False ... def __init__(self, **kw): ... if self.initialized: ... raise SystemError('__init__ called too many times') ... self.initialized = True ... self.__dict__.update(kw) ... def squared(self): ... return self.number ** 2 This can be useful to support default values, methods and initialization. Note that if you define an __init__ method, it will be called each time the local object is used in a separate thread. This is necessary to initialize each thread's dictionary. Now if we create a local object: >>> mydata = MyLocal(color='red') Now we have a default number: >>> mydata.number 2 an initial color: >>> mydata.color 'red' >>> del mydata.color And a method that operates on the data: >>> mydata.squared() 4 As before, we can access the data in a separate thread: >>> log = [] >>> thread = threading.Thread(target=f) >>> thread.start() >>> thread.join() >>> log [[('color', 'red'), ('initialized', True)], 11] without affecting this thread's data: >>> mydata.number 2 >>> mydata.color Traceback (most recent call last): ... AttributeError: 'MyLocal' object has no attribute 'color' Note that subclasses can define slots, but they are not thread local. They are shared across threads: >>> class MyLocal(local): ... __slots__ = 'number' >>> mydata = MyLocal() >>> mydata.number = 42 >>> mydata.color = 'red' So, the separate thread: >>> thread = threading.Thread(target=f) >>> thread.start() >>> thread.join() affects what we see: >>> mydata.number 11 >>> del mydata """ # Threading import is at end class _localbase(object): __slots__ = '_local__key', '_local__args', '_local__lock' def __new__(cls, *args, **kw): self = object.__new__(cls) key = '_local__key', 'thread.local.' + str(id(self)) object.__setattr__(self, '_local__key', key) object.__setattr__(self, '_local__args', (args, kw)) object.__setattr__(self, '_local__lock', RLock()) if args or kw and (cls.__init__ is object.__init__): raise TypeError("Initialization arguments are not supported") # We need to create the thread dict in anticipation of # __init__ being called, to make sure we don't call it # again ourselves. dict = object.__getattribute__(self, '__dict__') currentThread().__dict__[key] = dict return self def _patch(self): key = object.__getattribute__(self, '_local__key') d = currentThread().__dict__.get(key) if d is None: d = {} currentThread().__dict__[key] = d object.__setattr__(self, '__dict__', d) # we have a new instance dict, so call out __init__ if we have # one cls = type(self) if cls.__init__ is not object.__init__: args, kw = object.__getattribute__(self, '_local__args') cls.__init__(self, *args, **kw) else: object.__setattr__(self, '__dict__', d) class local(_localbase): def __getattribute__(self, name): lock = object.__getattribute__(self, '_local__lock') lock.acquire() try: _patch(self) return object.__getattribute__(self, name) finally: lock.release() def __setattr__(self, name, value): lock = object.__getattribute__(self, '_local__lock') lock.acquire() try: _patch(self) return object.__setattr__(self, name, value) finally: lock.release() def __delattr__(self, name): lock = object.__getattribute__(self, '_local__lock') lock.acquire() try: _patch(self) return object.__delattr__(self, name) finally: lock.release() def __del__(): threading_enumerate = enumerate __getattribute__ = object.__getattribute__ def __del__(self): key = __getattribute__(self, '_local__key') try: threads = list(threading_enumerate()) except: # if enumerate fails, as it seems to do during # shutdown, we'll skip cleanup under the assumption # that there is nothing to clean up return for thread in threads: try: __dict__ = thread.__dict__ except AttributeError: # Thread is dying, rest in peace continue if key in __dict__: try: del __dict__[key] except KeyError: pass # didn't have anything in this thread return __del__ __del__ = __del__() try: from threading import currentThread, enumerate, RLock except ImportError: from dummy_threading import currentThread, enumerate, RLock
Python
""" Utilities for XML generation/parsing. """ from xml.sax.saxutils import XMLGenerator class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents) self.endElement(name)
Python
"HTML utilities suitable for global use." import re, string # Configuration for urlize() function LEADING_PUNCTUATION = ['(', '<', '&lt;'] TRAILING_PUNCTUATION = ['.', ',', ')', '>', '\n', '&gt;'] # list of possible strings used for bullets in bulleted lists DOTS = ['&middot;', '*', '\xe2\x80\xa2', '&#149;', '&bull;', '&#8226;'] unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'(\s+)') punctuation_re = re.compile('^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % \ ('|'.join([re.escape(x) for x in LEADING_PUNCTUATION]), '|'.join([re.escape(x) for x in TRAILING_PUNCTUATION]))) simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$') link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+') html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE) hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join([re.escape(x) for x in DOTS]), re.DOTALL) trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z') del x # Temporary variable def escape(html): "Returns the given HTML with ampersands, quotes and carets encoded" if not isinstance(html, basestring): html = str(html) return html.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') def linebreaks(value): "Converts newlines into <p> and <br />s" value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines paras = re.split('\n{2,}', value) paras = ['<p>%s</p>' % p.strip().replace('\n', '<br />') for p in paras] return '\n\n'.join(paras) def strip_tags(value): "Returns the given HTML with all tags stripped" return re.sub(r'<[^>]*?>', '', value) def strip_spaces_between_tags(value): "Returns the given HTML with spaces between tags normalized to a single space" return re.sub(r'>\s+<', '> <', value) def strip_entities(value): "Returns the given HTML with all entities (&something;) stripped" return re.sub(r'&(?:\w+|#\d);', '', value) def fix_ampersands(value): "Returns the given HTML with all unencoded ampersands encoded correctly" return unencoded_ampersands_re.sub('&amp;', value) def urlize(text, trim_url_limit=None, nofollow=False): """ Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text will be limited to trim_url_limit characters. If nofollow is True, the URLs in link text will get a rel="nofollow" attribute. """ trim_url = lambda x, limit=trim_url_limit: limit is not None and (x[:limit] + (len(x) >=limit and '...' or '')) or x words = word_split_re.split(text) nofollow_attr = nofollow and ' rel="nofollow"' or '' for i, word in enumerate(words): match = punctuation_re.match(word) if match: lead, middle, trail = match.groups() if middle.startswith('www.') or ('@' not in middle and not middle.startswith('http://') and \ len(middle) > 0 and middle[0] in string.letters + string.digits and \ (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))): middle = '<a href="http://%s"%s>%s</a>' % (middle, nofollow_attr, trim_url(middle)) if middle.startswith('http://') or middle.startswith('https://'): middle = '<a href="%s"%s>%s</a>' % (middle, nofollow_attr, trim_url(middle)) if '@' in middle and not middle.startswith('www.') and not ':' in middle \ and simple_email_re.match(middle): middle = '<a href="mailto:%s">%s</a>' % (middle, middle) if lead + middle + trail != word: words[i] = lead + middle + trail return ''.join(words) def clean_html(text): """ Cleans the given HTML. Specifically, it does the following: * Converts <b> and <i> to <strong> and <em>. * Encodes all ampersands correctly. * Removes all "target" attributes from <a> tags. * Removes extraneous HTML, such as presentational tags that open and immediately close and <br clear="all">. * Converts hard-coded bullets into HTML unordered lists. * Removes stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom of the text. """ from django.utils.text import normalize_newlines text = normalize_newlines(text) text = re.sub(r'<(/?)\s*b\s*>', '<\\1strong>', text) text = re.sub(r'<(/?)\s*i\s*>', '<\\1em>', text) text = fix_ampersands(text) # Remove all target="" attributes from <a> tags. text = link_target_attribute_re.sub('\\1', text) # Trim stupid HTML such as <br clear="all">. text = html_gunk_re.sub('', text) # Convert hard-coded bullets into HTML unordered lists. def replace_p_tags(match): s = match.group().replace('</p>', '</li>') for d in DOTS: s = s.replace('<p>%s' % d, '<li>') return '<ul>\n%s\n</ul>' % s text = hard_coded_bullets_re.sub(replace_p_tags, text) # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom of the text. text = trailing_empty_content_re.sub('', text) return text
Python
"Implementation of tzinfo classes for use with datetime.datetime." import time from datetime import timedelta, tzinfo class FixedOffset(tzinfo): "Fixed offset in minutes east from UTC." def __init__(self, offset): self.__offset = timedelta(minutes=offset) self.__name = "%+03d%02d" % (offset // 60, offset % 60) def __repr__(self): return self.__name def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return timedelta(0) class LocalTimezone(tzinfo): "Proxy timezone information from time module." def __init__(self, dt): tzinfo.__init__(self, dt) self._tzname = time.tzname[self._isdst(dt)] def __repr__(self): return self._tzname def utcoffset(self, dt): if self._isdst(dt): return timedelta(seconds=-time.altzone) else: return timedelta(seconds=-time.timezone) def dst(self, dt): if self._isdst(dt): return timedelta(seconds=-time.altzone) - timedelta(seconds=-time.timezone) else: return timedelta(0) def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1) stamp = time.mktime(tt) tt = time.localtime(stamp) return tt.tm_isdst > 0
Python
# Autoreloading launcher. # Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org). # Some taken from Ian Bicking's Paste (http://pythonpaste.org/). # # Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the CherryPy Team nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os, sys, time try: import thread except ImportError: import dummy_thread as thread # This import does nothing, but it's necessary to avoid some race conditions # in the threading module. See http://code.djangoproject.com/ticket/2330 . try: import threading except ImportError: pass RUN_RELOADER = True def reloader_thread(): mtimes = {} win = (sys.platform == "win32") while RUN_RELOADER: for filename in filter(lambda v: v, map(lambda m: getattr(m, "__file__", None), sys.modules.values())): if filename.endswith(".pyc") or filename.endswith("*.pyo"): filename = filename[:-1] if not os.path.exists(filename): continue # File might be in an egg, so it can't be reloaded. stat = os.stat(filename) mtime = stat.st_mtime if win: mtime -= stat.st_ctime if filename not in mtimes: mtimes[filename] = mtime continue if mtime != mtimes[filename]: sys.exit(3) # force reload time.sleep(1) def restart_with_reloader(): while True: args = [sys.executable] + sys.argv if sys.platform == "win32": args = ['"%s"' % arg for arg in args] new_environ = os.environ.copy() new_environ["RUN_MAIN"] = 'true' exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) if exit_code != 3: return exit_code def main(main_func, args=None, kwargs=None): if os.environ.get("RUN_MAIN") == "true": if args is None: args = () if kwargs is None: kwargs = {} thread.start_new_thread(main_func, args, kwargs) try: reloader_thread() except KeyboardInterrupt: pass else: try: sys.exit(restart_with_reloader()) except KeyboardInterrupt: pass
Python
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44 Essentially, the "Vary" HTTP header defines which headers a cache should take into account when building its cache key. Requests with the same path but different header content for headers named in "Vary" need to get different cache keys to prevent delivery of wrong content. A example: i18n middleware would need to distinguish caches by the "Accept-language" header. """ import datetime, md5, re from django.conf import settings from django.core.cache import cache cc_delim_re = re.compile(r'\s*,\s*') def patch_cache_control(response, **kwargs): """ This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true value), only the parameter name is added to the header. * All other parameters are added with their value, after applying str() to it. """ def dictitem(s): t = s.split('=',1) if len(t) > 1: return (t[0].lower().replace('-', '_'), t[1]) else: return (t[0].lower().replace('-', '_'), True) def dictvalue(t): if t[1] == True: return t[0] else: return t[0] + '=' + str(t[1]) if response.has_header('Cache-Control'): cc = cc_delim_re.split(response['Cache-Control']) cc = dict([dictitem(el) for el in cc]) else: cc = {} for (k,v) in kwargs.items(): cc[k.replace('_', '-')] = v cc = ', '.join([dictvalue(el) for el in cc.items()]) response['Cache-Control'] = cc vary_delim_re = re.compile(r',\s*') def patch_response_headers(response, cache_timeout=None): """ Adds some useful headers to the given HttpResponse object: ETag, Last-Modified, Expires and Cache-Control Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS now = datetime.datetime.utcnow() if not response.has_header('ETag'): response['ETag'] = md5.new(response.content).hexdigest() if not response.has_header('Last-Modified'): response['Last-Modified'] = now.strftime('%a, %d %b %Y %H:%M:%S GMT') if not response.has_header('Expires'): expires = now + datetime.timedelta(0, cache_timeout) response['Expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S GMT') if cache_timeout < 0: cache_timeout = 0 # Can't have max-age negative patch_cache_control(response, max_age=cache_timeout) def add_never_cache_headers(response): """ Add headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) def patch_vary_headers(response, newheaders): """ Adds (or updates) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". Existing headers in "Vary" aren't removed. """ # Note that we need to keep the original order intact, because cache # implementations may rely on the order of the Vary contents in, say, # computing an MD5 hash. vary = [] if response.has_header('Vary'): vary = vary_delim_re.split(response['Vary']) oldheaders = dict([(el.lower(), 1) for el in vary]) for newheader in newheaders: if not newheader.lower() in oldheaders: vary.append(newheader) response['Vary'] = ', '.join(vary) def _generate_cache_key(request, headerlist, key_prefix): "Returns a cache key from the headers given in the header list." ctx = md5.new() for header in headerlist: value = request.META.get(header, None) if value is not None: ctx.update(value) return 'views.decorators.cache.cache_page.%s.%s.%s' % (key_prefix, request.path, ctx.hexdigest()) def get_cache_key(request, key_prefix=None): """ Returns a cache key based on the request path. It can be used in the request phase because it pulls the list of headers to take into account from the global path registry and uses those to build a cache key to check against. If there is no headerlist stored, the page needs to be rebuilt, so this function returns None. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix, request.path) headerlist = cache.get(cache_key, None) if headerlist is not None: return _generate_cache_key(request, headerlist, key_prefix) else: return None def learn_cache_key(request, response, cache_timeout=None, key_prefix=None): """ Learns what headers to take into account for some request path from the response object. It stores those headers in a global path registry so that later access to that path will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = 'views.decorators.cache.cache_header.%s.%s' % (key_prefix, request.path) if response.has_header('Vary'): headerlist = ['HTTP_'+header.upper().replace('-', '_') for header in vary_delim_re.split(response['Vary'])] cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.path cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, [], key_prefix)
Python
"Commonly-used date structures" from django.utils.translation import gettext_lazy as _ WEEKDAYS = { 0:_('Monday'), 1:_('Tuesday'), 2:_('Wednesday'), 3:_('Thursday'), 4:_('Friday'), 5:_('Saturday'), 6:_('Sunday') } WEEKDAYS_REV = { 'monday':0, 'tuesday':1, 'wednesday':2, 'thursday':3, 'friday':4, 'saturday':5, 'sunday':6 } MONTHS = { 1:_('January'), 2:_('February'), 3:_('March'), 4:_('April'), 5:_('May'), 6:_('June'), 7:_('July'), 8:_('August'), 9:_('September'), 10:_('October'), 11:_('November'), 12:_('December') } MONTHS_3 = { 1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'), 5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'), 9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec') } MONTHS_3_REV = { 'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12 } MONTHS_AP = { # month names in Associated Press style 1:_('Jan.'), 2:_('Feb.'), 3:_('March'), 4:_('April'), 5:_('May'), 6:_('June'), 7:_('July'), 8:_('Aug.'), 9:_('Sept.'), 10:_('Oct.'), 11:_('Nov.'), 12:_('Dec.') }
Python
""" Providing iterator functions that are not in all version of Python we support. Where possible, we try to use the system-native version and only fall back to these implementations if necessary. """ import itertools def compat_tee(iterable): """Return two independent iterators from a single iterable. Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html """ # Note: Using a dictionary and a list as the default arguments here is # deliberate and safe in this instance. def gen(next, data={}, cnt=[0]): dpop = data.pop for i in itertools.count(): if i == cnt[0]: item = data[i] = next() cnt[0] += 1 else: item = dpop(i) yield item next = iter(iterable).next return gen(next), gen(next) if hasattr(itertools, 'tee'): tee = itertools.tee else: tee = compat_tee
Python
""" Utility functions for handling images. Requires PIL, as you might imagine. """ import ImageFile def get_image_dimensions(path): """Returns the (width, height) of an image at a given path.""" p = ImageFile.Parser() fp = open(path, 'rb') while 1: data = fp.read(1024) if not data: break p.feed(data) if p.image: return p.image.size break fp.close() return None
Python
""" Iterator based sre token scanner """ import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object): def __init__(self, lexicon, flags=FLAGS): self.actions = [None] # combine phrases into a compound pattern s = sre_parse.Pattern() s.flags = flags p = [] for idx, token in enumerate(lexicon): phrase = token.pattern try: subpattern = sre_parse.SubPattern(s, [(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))]) except sre_constants.error: raise p.append(subpattern) self.actions.append(token) p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def iterscan(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is None: break matchbegin, matchend = m.span() if lastend == matchend: break action = actions[m.lastindex] if action is not None: rval, next_pos = action(m, context) if next_pos is not None and next_pos != matchend: # "fast forward" the scanner matchend = next_pos match = self.scanner.scanner(string, matchend).match yield rval, matchend lastend = matchend def pattern(pattern, flags=FLAGS): def decorator(fn): fn.pattern = pattern fn.regex = re.compile(pattern, flags) return fn return decorator
Python
from django.utils import simplejson import cgi class JSONFilter(object): def __init__(self, app, mime_type='text/x-json'): self.app = app self.mime_type = mime_type def __call__(self, environ, start_response): # Read JSON POST input to jsonfilter.json if matching mime type response = {'status': '200 OK', 'headers': []} def json_start_response(status, headers): response['status'] = status response['headers'].extend(headers) environ['jsonfilter.mime_type'] = self.mime_type if environ.get('REQUEST_METHOD', '') == 'POST': if environ.get('CONTENT_TYPE', '') == self.mime_type: args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _] data = environ['wsgi.input'].read(*map(int, args)) environ['jsonfilter.json'] = simplejson.loads(data) res = simplejson.dumps(self.app(environ, json_start_response)) jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp') if jsonp: content_type = 'text/javascript' res = ''.join(jsonp + ['(', res, ')']) elif 'Opera' in environ.get('HTTP_USER_AGENT', ''): # Opera has bunk XMLHttpRequest support for most mime types content_type = 'text/plain' else: content_type = self.mime_type headers = [ ('Content-type', content_type), ('Content-length', len(res)), ] headers.extend(response['headers']) start_response(response['status'], headers) return [res] def factory(app, global_conf, **kw): return JSONFilter(app, **kw)
Python
""" Implementation of JSONDecoder """ import re from django.utils.simplejson.scanner import Scanner, pattern FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): import struct import sys _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, 'true': True, 'false': False, 'null': None, } def JSONConstant(match, context, c=_CONSTANTS): return c[match.group(0)], None pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant) def JSONNumber(match, context): match = JSONNumber.regex.match(match.string, *match.span()) integer, frac, exp = match.groups() if frac or exp: res = float(integer + (frac or '') + (exp or '')) else: res = int(integer) return res, None pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber) STRINGCHUNK = re.compile(r'(.*?)(["\\])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match): if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) if terminator == '"': break try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) if esc != 'u': try: m = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: esc = s[end + 1:end + 5] try: m = unichr(int(esc, 16)) if len(esc) != 4 or not esc.isalnum(): raise ValueError except ValueError: raise ValueError(errmsg("Invalid \\uXXXX escape", s, end)) end += 5 _append(m) return u''.join(chunks), end def JSONString(match, context): encoding = getattr(context, 'encoding', None) return scanstring(match.string, match.end(), encoding) pattern(r'"')(JSONString) WHITESPACE = re.compile(r'\s*', FLAGS) def JSONObject(match, context, _w=WHITESPACE.match): pairs = {} s = match.string end = _w(s, match.end()).end() nextchar = s[end:end + 1] # trivial empty object if nextchar == '}': return pairs, end + 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 encoding = getattr(context, 'encoding', None) iterscan = JSONScanner.iterscan while True: key, end = scanstring(s, end, encoding) end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end = _w(s, end + 1).end() try: value, end = iterscan(s, idx=end, context=context).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == '}': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) object_hook = getattr(context, 'object_hook', None) if object_hook is not None: pairs = object_hook(pairs) return pairs, end pattern(r'{')(JSONObject) def JSONArray(match, context, _w=WHITESPACE.match): values = [] s = match.string end = _w(s, match.end()).end() # look-ahead for trivial empty array nextchar = s[end:end + 1] if nextchar == ']': return values, end + 1 iterscan = JSONScanner.iterscan while True: try: value, end = iterscan(s, idx=end, context=context).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) values.append(value) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) end = _w(s, end).end() return values, end pattern(r'\[')(JSONArray) ANYTHING = [ JSONObject, JSONArray, JSONString, JSONConstant, JSONNumber, ] JSONScanner = Scanner(ANYTHING) class JSONDecoder(object): """ Simple JSON <http://json.org> decoder Performs the following translations in decoding: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ _scanner = Scanner(ANYTHING) __all__ = ['__init__', 'decode', 'raw_decode'] def __init__(self, encoding=None, object_hook=None): """ ``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). """ self.encoding = encoding self.object_hook = object_hook def decode(self, s, _w=WHITESPACE.match): """ Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, **kw): """ Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ kw.setdefault('context', self) try: obj, end = self._scanner.iterscan(s, **kw).next() except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end __all__ = ['JSONDecoder']
Python
""" Implementation of JSONEncoder """ import re ESCAPE = re.compile(r'[\x00-\x19\\"\b\f\n\r\t]') ESCAPE_ASCII = re.compile(r'([\\"/]|[^\ -~])') ESCAPE_DCT = { # escape all forward slashes to prevent </script> attack '/': '\\/', '\\': '\\\\', '"': '\\"', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', } for i in range(0x20): ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) # assume this produces an infinity on all machines (probably not guaranteed) INFINITY = float('1e66666') def floatstr(o, allow_nan=True): # Check for specials. Note that this type of test is processor- and/or # platform-specific, so do tests which don't depend on the internals. if o != o: text = 'NaN' elif o == INFINITY: text = 'Infinity' elif o == -INFINITY: text = '-Infinity' else: return str(o) if not allow_nan: raise ValueError("Out of range float values are not JSON compliant: %r" % (o,)) return text def encode_basestring(s): """ Return a JSON representation of a Python string """ def replace(match): return ESCAPE_DCT[match.group(0)] return '"' + ESCAPE.sub(replace, s) + '"' def encode_basestring_ascii(s): def replace(match): s = match.group(0) try: return ESCAPE_DCT[s] except KeyError: return '\\u%04x' % (ord(s),) return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' class JSONEncoder(object): """ Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str, unicode | string | +-------------------+---------------+ | int, long, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """ __all__ = ['__init__', 'default', 'encode', 'iterencode'] item_separator = ', ' key_separator = ': ' def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None): """ Constructor for JSONEncoder, with sensible defaults. If skipkeys is False, then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If ensure_ascii is false, the output will be unicode object. If check_circular is True, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is True, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is True, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be a (item_separator, key_separator) tuple. The default is (', ', ': '). To get the most compact JSON representation you should specify (',', ':') to eliminate whitespace. """ self.skipkeys = skipkeys self.ensure_ascii = ensure_ascii self.check_circular = check_circular self.allow_nan = allow_nan self.sort_keys = sort_keys self.indent = indent self.current_indent_level = 0 if separators is not None: self.item_separator, self.key_separator = separators def _newline_indent(self): return '\n' + (' ' * (self.indent * self.current_indent_level)) def _iterencode_list(self, lst, markers=None): if not lst: yield '[]' return if markers is not None: markerid = id(lst) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = lst yield '[' if self.indent is not None: self.current_indent_level += 1 newline_indent = self._newline_indent() separator = self.item_separator + newline_indent yield newline_indent else: newline_indent = None separator = self.item_separator first = True for value in lst: if first: first = False else: yield separator for chunk in self._iterencode(value, markers): yield chunk if newline_indent is not None: self.current_indent_level -= 1 yield self._newline_indent() yield ']' if markers is not None: del markers[markerid] def _iterencode_dict(self, dct, markers=None): if not dct: yield '{}' return if markers is not None: markerid = id(dct) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = dct yield '{' key_separator = self.key_separator if self.indent is not None: self.current_indent_level += 1 newline_indent = self._newline_indent() item_separator = self.item_separator + newline_indent yield newline_indent else: newline_indent = None item_separator = self.item_separator first = True if self.ensure_ascii: encoder = encode_basestring_ascii else: encoder = encode_basestring allow_nan = self.allow_nan if self.sort_keys: keys = dct.keys() keys.sort() items = [(k, dct[k]) for k in keys] else: items = dct.iteritems() for key, value in items: if isinstance(key, basestring): pass # JavaScript is weakly typed for these, so it makes sense to # also allow them. Many encoders seem to do something like this. elif isinstance(key, float): key = floatstr(key, allow_nan) elif isinstance(key, (int, long)): key = str(key) elif key is True: key = 'true' elif key is False: key = 'false' elif key is None: key = 'null' elif self.skipkeys: continue else: raise TypeError("key %r is not a string" % (key,)) if first: first = False else: yield item_separator yield encoder(key) yield key_separator for chunk in self._iterencode(value, markers): yield chunk if newline_indent is not None: self.current_indent_level -= 1 yield self._newline_indent() yield '}' if markers is not None: del markers[markerid] def _iterencode(self, o, markers=None): if isinstance(o, basestring): if self.ensure_ascii: encoder = encode_basestring_ascii else: encoder = encode_basestring yield encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield floatstr(o, self.allow_nan) elif isinstance(o, (list, tuple)): for chunk in self._iterencode_list(o, markers): yield chunk elif isinstance(o, dict): for chunk in self._iterencode_dict(o, markers): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o for chunk in self._iterencode_default(o, markers): yield chunk if markers is not None: del markers[markerid] def _iterencode_default(self, o, markers=None): newobj = self.default(o) return self._iterencode(newobj, markers) def default(self, o): """ Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) return JSONEncoder.default(self, o) """ raise TypeError("%r is not JSON serializable" % (o,)) def encode(self, o): """ Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo":["bar", "baz"]}' """ # This doesn't pass the iterator directly to ''.join() because it # sucks at reporting exceptions. It's going to do this internally # anyway because it uses PySequence_Fast or similar. chunks = list(self.iterencode(o)) return ''.join(chunks) def iterencode(self, o): """ Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ if self.check_circular: markers = {} else: markers = None return self._iterencode(o, markers) __all__ = ['JSONEncoder']
Python
r""" A simple, fast, extensible JSON encoder and decoder JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. simplejson exposes an API familiar to uses of the standard library marshal and pickle modules. Encoding basic Python object hierarchies:: >>> import simplejson >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print simplejson.dumps("\"foo\bar") "\"foo\bar" >>> print simplejson.dumps(u'\u1234') "\u1234" >>> print simplejson.dumps('\\') "\\" >>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> simplejson.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson >>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson >>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> simplejson.loads('"\\"foo\\bar"') u'"foo\x08ar' >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> simplejson.load(io) [u'streaming API'] Specializing JSON object decoding:: >>> import simplejson >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) Extending JSONEncoder:: >>> import simplejson >>> class ComplexEncoder(simplejson.JSONEncoder): ... def default(self, obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... return simplejson.JSONEncoder.default(self, obj) ... >>> dumps(2 + 1j, cls=ComplexEncoder) '[2.0, 1.0]' >>> ComplexEncoder().encode(2 + 1j) '[2.0, 1.0]' >>> list(ComplexEncoder().iterencode(2 + 1j)) ['[', '2.0', ', ', '1.0', ']'] Note that the JSON produced by this module's default settings is a subset of YAML, so it may be used as a serializer for that as well. """ __version__ = '1.5' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder', ] from django.utils.simplejson.decoder import JSONDecoder from django.utils.simplejson.encoder import JSONEncoder def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, **kw): """ Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, **kw): """ Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is ``False``, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is ``False``, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, **kw).encode(obj) def load(fp, encoding=None, cls=None, object_hook=None, **kw): """ Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook return cls(encoding=encoding, **kw).decode(fp.read()) def loads(s, encoding=None, cls=None, object_hook=None, **kw): """ Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook return cls(encoding=encoding, **kw).decode(s) def read(s): """ json-py API compatibility hook. Use loads(s) instead. """ import warnings warnings.warn("simplejson.loads(s) should be used instead of read(s)", DeprecationWarning) return loads(s) def write(obj): """ json-py API compatibility hook. Use dumps(s) instead. """ import warnings warnings.warn("simplejson.dumps(s) should be used instead of write(s)", DeprecationWarning) return dumps(obj)
Python
"Translation helper functions" import locale import os import re import sys import gettext as gettext_module from cStringIO import StringIO from django.utils.functional import lazy try: import threading hasThreads = True except ImportError: hasThreads = False if hasThreads: currentThread = threading.currentThread else: def currentThread(): return 'no threading' # Translations are cached in a dictionary for every language+app tuple. # The active translations are stored by threadid to make them thread local. _translations = {} _active = {} # The default translation is based on the settings file. _default = None # This is a cache for normalised accept-header languages to prevent multiple # file lookups when checking the same locale on repeated requests. _accepted = {} # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9. accept_language_re = re.compile(r''' ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*) # "en", "en-au", "x-y-z", "*" (?:;q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8" (?:\s*,\s*|$) # Multiple accepts per header. ''', re.VERBOSE) def to_locale(language, to_lower=False): "Turns a language name (en-us) into a locale name (en_US)." p = language.find('-') if p >= 0: if to_lower: return language[:p].lower()+'_'+language[p+1:].lower() else: return language[:p].lower()+'_'+language[p+1:].upper() else: return language.lower() def to_language(locale): "Turns a locale name (en_US) into a language name (en-us)." p = locale.find('_') if p >= 0: return locale[:p].lower()+'-'+locale[p+1:].lower() else: return locale.lower() class DjangoTranslation(gettext_module.GNUTranslations): """ This class sets up the GNUTranslations context with regard to output charset. Django uses a defined DEFAULT_CHARSET as the output charset on Python 2.4. With Python 2.3, use DjangoTranslation23. """ def __init__(self, *args, **kw): from django.conf import settings gettext_module.GNUTranslations.__init__(self, *args, **kw) # Starting with Python 2.4, there's a function to define # the output charset. Before 2.4, the output charset is # identical with the translation file charset. try: self.set_output_charset(settings.DEFAULT_CHARSET) except AttributeError: pass self.django_output_charset = settings.DEFAULT_CHARSET self.__language = '??' def merge(self, other): self._catalog.update(other._catalog) def set_language(self, language): self.__language = language def language(self): return self.__language def __repr__(self): return "<DjangoTranslation lang:%s>" % self.__language class DjangoTranslation23(DjangoTranslation): """ Compatibility class that is only used with Python 2.3. Python 2.3 doesn't support set_output_charset on translation objects and needs this wrapper class to make sure input charsets from translation files are correctly translated to output charsets. With a full switch to Python 2.4, this can be removed from the source. """ def gettext(self, msgid): res = self.ugettext(msgid) return res.encode(self.django_output_charset) def ngettext(self, msgid1, msgid2, n): res = self.ungettext(msgid1, msgid2, n) return res.encode(self.django_output_charset) def translation(language): """ Returns a translation object. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct a object for the requested language and add a fallback to the default language, if it's different from the requested language. """ global _translations t = _translations.get(language, None) if t is not None: return t from django.conf import settings # set up the right translation class klass = DjangoTranslation if sys.version_info < (2, 4): klass = DjangoTranslation23 globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if settings.SETTINGS_MODULE is not None: parts = settings.SETTINGS_MODULE.split('.') project = __import__(parts[0], {}, {}, []) projectpath = os.path.join(os.path.dirname(project.__file__), 'locale') else: projectpath = None def _fetch(lang, fallback=None): global _translations loc = to_locale(lang) res = _translations.get(lang, None) if res is not None: return res def _translation(path): try: t = gettext_module.translation('django', path, [loc], klass) t.set_language(lang) return t except IOError, e: return None res = _translation(globalpath) def _merge(path): t = _translation(path) if t is not None: if res is None: return t else: res.merge(t) return res if hasattr(settings, 'LOCALE_PATHS'): for localepath in settings.LOCALE_PATHS: if os.path.isdir(localepath): res = _merge(localepath) if projectpath and os.path.isdir(projectpath): res = _merge(projectpath) for appname in settings.INSTALLED_APPS: p = appname.rfind('.') if p >= 0: app = getattr(__import__(appname[:p], {}, {}, [appname[p+1:]]), appname[p+1:]) else: app = __import__(appname, {}, {}, []) apppath = os.path.join(os.path.dirname(app.__file__), 'locale') if os.path.isdir(apppath): res = _merge(apppath) if res is None: if fallback is not None: res = fallback else: return gettext_module.NullTranslations() _translations[lang] = res return res default_translation = _fetch(settings.LANGUAGE_CODE) current_translation = _fetch(language, fallback=default_translation) return current_translation def activate(language): """ Fetches the translation object for a given tuple of application name and language and installs it as the current translation object for the current thread. """ _active[currentThread()] = translation(language) def deactivate(): """ Deinstalls the currently active translation object so that further _ calls will resolve against the default translation object, again. """ global _active if _active.has_key(currentThread()): del _active[currentThread()] def get_language(): "Returns the currently selected language." t = _active.get(currentThread(), None) if t is not None: try: return to_language(t.language()) except AttributeError: pass # If we don't have a real translation object, assume it's the default language. from django.conf import settings return settings.LANGUAGE_CODE def get_language_bidi(): """ Returns selected language's BiDi layout. False = left-to-right layout True = right-to-left layout """ from django.conf import settings return get_language() in settings.LANGUAGES_BIDI def catalog(): """ This function returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default, _active t = _active.get(currentThread(), None) if t is not None: return t if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default def gettext(message): """ This function will be patched into the builtins module to provide the _ helper function. It will use the current thread as a discriminator to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default, _active t = _active.get(currentThread(), None) if t is not None: return t.gettext(message) if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default.gettext(message) def gettext_noop(message): """ Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message def ngettext(singular, plural, number): """ Returns the translation of either the singular or plural, based on the number. """ global _default, _active t = _active.get(currentThread(), None) if t is not None: return t.ngettext(singular, plural, number) if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default.ngettext(singular, plural, number) gettext_lazy = lazy(gettext, str) ngettext_lazy = lazy(ngettext, str) def check_for_language(lang_code): """ Checks whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. This is only used for language codes from either the cookies or session. """ from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if gettext_module.find('django', globalpath, [to_locale(lang_code)]) is not None: return True else: return False def get_language_from_request(request): """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. """ global _accepted from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') supported = dict(settings.LANGUAGES) if hasattr(request, 'session'): lang_code = request.session.get('django_language', None) if lang_code in supported and lang_code is not None and check_for_language(lang_code): return lang_code lang_code = request.COOKIES.get('django_language') if lang_code and lang_code in supported and check_for_language(lang_code): return lang_code accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for lang, unused in parse_accept_lang_header(accept): if lang == '*': break # We have a very restricted form for our language files (no encoding # specifier, since they all must be UTF-8 and only one possible # language each time. So we avoid the overhead of gettext.find() and # look up the MO file manually. normalized = locale.locale_alias.get(to_locale(lang, True)) if not normalized: continue # Remove the default encoding from locale_alias normalized = normalized.split('.')[0] if normalized in _accepted: # We've seen this locale before and have an MO file for it, so no # need to check again. return _accepted[normalized] for lang in (normalized, normalized.split('_')[0]): if lang not in supported: continue langfile = os.path.join(globalpath, lang, 'LC_MESSAGES', 'django.mo') if os.path.exists(langfile): _accepted[normalized] = lang return lang return settings.LANGUAGE_CODE def get_date_formats(): """ This function checks whether translation files provide a translation for some technical message ID to store date and time formats. If it doesn't contain one, the formats provided in the settings will be used. """ from django.conf import settings date_format = _('DATE_FORMAT') datetime_format = _('DATETIME_FORMAT') time_format = _('TIME_FORMAT') if date_format == 'DATE_FORMAT': date_format = settings.DATE_FORMAT if datetime_format == 'DATETIME_FORMAT': datetime_format = settings.DATETIME_FORMAT if time_format == 'TIME_FORMAT': time_format = settings.TIME_FORMAT return date_format, datetime_format, time_format def get_partial_date_formats(): """ This function checks whether translation files provide a translation for some technical message ID to store partial date formats. If it doesn't contain one, the formats provided in the settings will be used. """ from django.conf import settings year_month_format = _('YEAR_MONTH_FORMAT') month_day_format = _('MONTH_DAY_FORMAT') if year_month_format == 'YEAR_MONTH_FORMAT': year_month_format = settings.YEAR_MONTH_FORMAT if month_day_format == 'MONTH_DAY_FORMAT': month_day_format = settings.MONTH_DAY_FORMAT return year_month_format, month_day_format def install(): """ Installs the gettext function as the default translation function under the name '_'. """ __builtins__['_'] = gettext dot_re = re.compile(r'\S') def blankout(src, char): """ Changes every non-whitespace character to the given char. Used in the templatize function. """ return dot_re.sub(char, src) inline_re = re.compile(r"""^\s*trans\s+((?:".*?")|(?:'.*?'))\s*""") block_re = re.compile(r"""^\s*blocktrans(?:\s+|$)""") endblock_re = re.compile(r"""^\s*endblocktrans$""") plural_re = re.compile(r"""^\s*plural$""") constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?'))\)""") def templatize(src): """ Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """ from django.template import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK out = StringIO() intrans = False inplural = False singular = [] plural = [] for t in Lexer(src, None).tokenize(): if intrans: if t.token_type == TOKEN_BLOCK: endbmatch = endblock_re.match(t.contents) pluralmatch = plural_re.match(t.contents) if endbmatch: if inplural: out.write(' ngettext(%r,%r,count) ' % (''.join(singular), ''.join(plural))) for part in singular: out.write(blankout(part, 'S')) for part in plural: out.write(blankout(part, 'P')) else: out.write(' gettext(%r) ' % ''.join(singular)) for part in singular: out.write(blankout(part, 'S')) intrans = False inplural = False singular = [] plural = [] elif pluralmatch: inplural = True else: raise SyntaxError, "Translation blocks must not include other block tags: %s" % t.contents elif t.token_type == TOKEN_VAR: if inplural: plural.append('%%(%s)s' % t.contents) else: singular.append('%%(%s)s' % t.contents) elif t.token_type == TOKEN_TEXT: if inplural: plural.append(t.contents) else: singular.append(t.contents) else: if t.token_type == TOKEN_BLOCK: imatch = inline_re.match(t.contents) bmatch = block_re.match(t.contents) cmatches = constant_re.findall(t.contents) if imatch: g = imatch.group(1) if g[0] == '"': g = g.strip('"') elif g[0] == "'": g = g.strip("'") out.write(' gettext(%r) ' % g) elif bmatch: intrans = True inplural = False singular = [] plural = [] elif cmatches: for cmatch in cmatches: out.write(' _(%s) ' % cmatch) else: out.write(blankout(t.contents, 'B')) elif t.token_type == TOKEN_VAR: parts = t.contents.split('|') cmatch = constant_re.match(parts[0]) if cmatch: out.write(' _(%s) ' % cmatch.group(1)) for p in parts[1:]: if p.find(':_(') >= 0: out.write(' %s ' % p.split(':',1)[1]) else: out.write(blankout(p, 'F')) else: out.write(blankout(t.contents, 'X')) return out.getvalue() def string_concat(*strings): """" lazy variant of string concatenation, needed for translations that are constructed from multiple parts. Handles lazy strings and non-strings by first turning all arguments to strings, before joining them. """ return ''.join([str(el) for el in strings]) string_concat = lazy(string_concat, str) def parse_accept_lang_header(lang_string): """ Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values. Any format errors in lang_string results in an empty list being returned. """ result = [] pieces = accept_language_re.split(lang_string) if pieces[-1]: return [] for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i : i + 3] if first: return [] priority = priority and float(priority) or 1.0 result.append((lang, priority)) result.sort(lambda x, y: -cmp(x[1], y[1])) return result
Python
from django.conf import settings if settings.USE_I18N: from trans_real import * else: from trans_null import * del settings
Python
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. from django.conf import settings def ngettext(singular, plural, number): if number == 1: return singular return plural ngettext_lazy = ngettext gettext = gettext_noop = gettext_lazy = _ = lambda x: x string_concat = lambda *strings: ''.join([str(el) for el in strings]) activate = lambda x: None deactivate = install = lambda: None get_language = lambda: settings.LANGUAGE_CODE get_language_bidi = lambda: settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI get_date_formats = lambda: (settings.DATE_FORMAT, settings.DATETIME_FORMAT, settings.TIME_FORMAT) get_partial_date_formats = lambda: (settings.YEAR_MONTH_FORMAT, settings.MONTH_DAY_FORMAT) check_for_language = lambda x: True def to_locale(language): p = language.find('-') if p >= 0: return language[:p].lower()+'_'+language[p+1:].upper() else: return language.lower() def get_language_from_request(request): return settings.LANGUAGE_CODE
Python
"Functions that help with dynamically creating decorators for views." def decorator_from_middleware(middleware_class): """ Given a middleware class (not an instance), returns a view decorator. This lets you use middleware functionality on a per-view basis. """ def _decorator_from_middleware(view_func, *args, **kwargs): middleware = middleware_class(*args, **kwargs) def _wrapped_view(request, *args, **kwargs): if hasattr(middleware, 'process_request'): result = middleware.process_request(request) if result is not None: return result if hasattr(middleware, 'process_view'): result = middleware.process_view(request, view_func, *args, **kwargs) if result is not None: return result try: response = view_func(request, *args, **kwargs) except Exception, e: if hasattr(middleware, 'process_exception'): result = middleware.process_exception(request, e) if result is not None: return result raise if hasattr(middleware, 'process_response'): result = middleware.process_response(request, response) if result is not None: return result return response return _wrapped_view return _decorator_from_middleware
Python
""" PHP date() style date formatting See http://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print df.format('jS F Y H:i') 7th October 2003 11:39 >>> """ from django.utils.dates import MONTHS, MONTHS_3, MONTHS_AP, WEEKDAYS from django.utils.tzinfo import LocalTimezone from django.utils.translation import gettext as _ from calendar import isleap, monthrange import re, time re_formatchars = re.compile(r'(?<!\\)([aAbBdDfFgGhHiIjlLmMnNOPrsStTUwWyYzZ])') re_escaped = re.compile(r'\\(.)') class Formatter(object): def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(formatstr)): if i % 2: pieces.append(str(getattr(self, piece)())) elif piece: pieces.append(re_escaped.sub(r'\1', piece)) return ''.join(pieces) class TimeFormat(Formatter): def __init__(self, t): self.data = t def a(self): "'a.m.' or 'p.m.'" if self.data.hour > 11: return _('p.m.') return _('a.m.') def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _('PM') return _('AM') def B(self): "Swatch Internet time" raise NotImplementedError def f(self): """ Time, in 12-hour hours and minutes, with minutes left off if they're zero. Examples: '1', '1:30', '2:05', '2' Proprietary extension. """ if self.data.minute == 0: return self.g() return '%s:%s' % (self.g(), self.i()) def g(self): "Hour, 12-hour format without leading zeros; i.e. '1' to '12'" if self.data.hour == 0: return 12 if self.data.hour > 12: return self.data.hour - 12 return self.data.hour def G(self): "Hour, 24-hour format without leading zeros; i.e. '0' to '23'" return self.data.hour def h(self): "Hour, 12-hour format; i.e. '01' to '12'" return '%02d' % self.g() def H(self): "Hour, 24-hour format; i.e. '00' to '23'" return '%02d' % self.G() def i(self): "Minutes; i.e. '00' to '59'" return '%02d' % self.data.minute def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _('midnight') if self.data.minute == 0 and self.data.hour == 12: return _('noon') return '%s %s' % (self.f(), self.a()) def s(self): "Seconds; i.e. '00' to '59'" return '%02d' % self.data.second class DateFormat(TimeFormat): year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] def __init__(self, dt): # Accepts either a datetime or date object. self.data = dt self.timezone = getattr(dt, 'tzinfo', None) if hasattr(self.data, 'hour') and not self.timezone: self.timezone = LocalTimezone(dt) def b(self): "Month, textual, 3 letters, lowercase; e.g. 'jan'" return MONTHS_3[self.data.month] def d(self): "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" return '%02d' % self.data.day def D(self): "Day of the week, textual, 3 letters; e.g. 'Fri'" return WEEKDAYS[self.data.weekday()][0:3] def F(self): "Month, textual, long; e.g. 'January'" return MONTHS[self.data.month] def I(self): "'1' if Daylight Savings Time, '0' otherwise." if self.timezone.dst(self.data): return '1' else: return '0' def j(self): "Day of the month without leading zeros; i.e. '1' to '31'" return self.data.day def l(self): "Day of the week, textual, long; e.g. 'Friday'" return WEEKDAYS[self.data.weekday()] def L(self): "Boolean for whether it is a leap year; i.e. True or False" return isleap(self.data.year) def m(self): "Month; i.e. '01' to '12'" return '%02d' % self.data.month def M(self): "Month, textual, 3 letters; e.g. 'Jan'" return MONTHS_3[self.data.month].title() def n(self): "Month without leading zeros; i.e. '1' to '12'" return self.data.month def N(self): "Month abbreviation in Associated Press style. Proprietary extension." return MONTHS_AP[self.data.month] def O(self): "Difference to Greenwich time in hours; e.g. '+0200'" tz = self.timezone.utcoffset(self.data) return "%+03d%02d" % (tz.seconds // 3600, (tz.seconds // 60) % 60) def r(self): "RFC 822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" return self.format('D, j M Y H:i:s O') def S(self): "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" if self.data.day in (11, 12, 13): # Special case return 'th' last = self.data.day % 10 if last == 1: return 'st' if last == 2: return 'nd' if last == 3: return 'rd' return 'th' def t(self): "Number of days in the given month; i.e. '28' to '31'" return '%02d' % monthrange(self.data.year, self.data.month)[1] def T(self): "Time zone of this machine; e.g. 'EST' or 'MDT'" name = self.timezone.tzname(self.data) if name is None: name = self.format('O') return name def U(self): "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)" off = self.timezone.utcoffset(self.data) return int(time.mktime(self.data.timetuple())) + off.seconds * 60 def w(self): "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)" return (self.data.weekday() + 1) % 7 def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt week_number = None jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4: if jan1_weekday == 5 or (jan1_weekday == 6 and isleap(self.data.year-1)): week_number = 53 else: week_number = 52 else: if isleap(self.data.year): i = 366 else: i = 365 if (i - day_of_year) < (4 - weekday): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j / 7 if jan1_weekday > 4: week_number -= 1 return week_number def y(self): "Year, 2 digits; e.g. '99'" return str(self.data.year)[2:] def Y(self): "Year, 4 digits; e.g. '1999'" return self.data.year def z(self): "Day of the year; i.e. '0' to '365'" doy = self.year_days[self.data.month] + self.data.day if self.L() and self.data.month > 2: doy += 1 return doy def Z(self): """Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.""" return self.timezone.utcoffset(self.data).seconds def format(value, format_string): "Convenience function" df = DateFormat(value) return df.format(format_string) def time_format(value, format_string): "Convenience function" tf = TimeFormat(value) return tf.format(format_string)
Python
class MergeDict(object): """ A simple class for creating new "virtual" dictionaries that actualy look up values in more than one dictionary, passed in the constructor. """ def __init__(self, *dicts): self.dicts = dicts def __getitem__(self, key): for dict in self.dicts: try: return dict[key] except KeyError: pass raise KeyError def __contains__(self, key): return self.has_key(key) def __copy__(self): return self.__class__(*self.dicts) def get(self, key, default=None): try: return self[key] except KeyError: return default def getlist(self, key): for dict in self.dicts: try: return dict.getlist(key) except KeyError: pass raise KeyError def items(self): item_list = [] for dict in self.dicts: item_list.extend(dict.items()) return item_list def has_key(self, key): for dict in self.dicts: if dict.has_key(key): return True return False def copy(self): """ returns a copy of this object""" return self.__copy__() class SortedDict(dict): "A dictionary that keeps its keys in the order in which they're inserted." def __init__(self, data=None): if data is None: data = {} dict.__init__(self, data) self.keyOrder = data.keys() def __setitem__(self, key, value): dict.__setitem__(self, key, value) if key not in self.keyOrder: self.keyOrder.append(key) def __delitem__(self, key): dict.__delitem__(self, key) self.keyOrder.remove(key) def __iter__(self): for k in self.keyOrder: yield k def items(self): return zip(self.keyOrder, self.values()) def keys(self): return self.keyOrder[:] def values(self): return [dict.__getitem__(self, k) for k in self.keyOrder] def update(self, dict): for k, v in dict.items(): self.__setitem__(k, v) def setdefault(self, key, default): if key not in self.keyOrder: self.keyOrder.append(key) return dict.setdefault(self, key, default) def value_for_index(self, index): "Returns the value of the item at the given zero-based index." return self[self.keyOrder[index]] def copy(self): "Returns a copy of this object." # This way of initializing the copy means it works for subclasses, too. obj = self.__class__(self) obj.keyOrder = self.keyOrder return obj class MultiValueDictKeyError(KeyError): pass class MultiValueDict(dict): """ A subclass of dictionary customized to handle multiple values for the same key. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) >>> d['name'] 'Simon' >>> d.getlist('name') ['Adrian', 'Simon'] >>> d.get('lastname', 'nonexistent') 'nonexistent' >>> d.setlist('lastname', ['Holovaty', 'Willison']) This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most Web forms submit single name-value pairs. """ def __init__(self, key_to_list_mapping=()): dict.__init__(self, key_to_list_mapping) def __repr__(self): return "<MultiValueDict: %s>" % dict.__repr__(self) def __getitem__(self, key): """ Returns the last data value for this key, or [] if it's an empty list; raises KeyError if not found. """ try: list_ = dict.__getitem__(self, key) except KeyError: raise MultiValueDictKeyError, "Key %r not found in %r" % (key, self) try: return list_[-1] except IndexError: return [] def __setitem__(self, key, value): dict.__setitem__(self, key, [value]) def __copy__(self): return self.__class__(dict.items(self)) def __deepcopy__(self, memo=None): import copy if memo is None: memo = {} result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def get(self, key, default=None): "Returns the default value if the requested data doesn't exist" try: val = self[key] except KeyError: return default if val == []: return default return val def getlist(self, key): "Returns an empty list if the requested data doesn't exist" try: return dict.__getitem__(self, key) except KeyError: return [] def setlist(self, key, list_): dict.__setitem__(self, key, list_) def setdefault(self, key, default=None): if key not in self: self[key] = default return self[key] def setlistdefault(self, key, default_list=()): if key not in self: self.setlist(key, default_list) return self.getlist(key) def appendlist(self, key, value): "Appends an item to the internal list associated with key" self.setlistdefault(key, []) dict.__setitem__(self, key, self.getlist(key) + [value]) def items(self): """ Returns a list of (key, value) pairs, where value is the last item in the list associated with the key. """ return [(key, self[key]) for key in self.keys()] def lists(self): "Returns a list of (key, list) pairs." return dict.items(self) def values(self): "Returns a list of the last value on every key list." return [self[key] for key in self.keys()] def copy(self): "Returns a copy of this object." return self.__deepcopy__() def update(self, *args, **kwargs): "update() extends rather than replaces existing key lists. Also accepts keyword args." if len(args) > 1: raise TypeError, "update expected at most 1 arguments, got %d", len(args) if args: other_dict = args[0] if isinstance(other_dict, MultiValueDict): for key, value_list in other_dict.lists(): self.setlistdefault(key, []).extend(value_list) else: try: for key, value in other_dict.items(): self.setlistdefault(key, []).append(value) except TypeError: raise ValueError, "MultiValueDict.update() takes either a MultiValueDict or dictionary" for key, value in kwargs.iteritems(): self.setlistdefault(key, []).append(value) class DotExpandedDict(dict): """ A special dictionary constructor that takes a dictionary in which the keys may contain dots to specify inner dictionaries. It's confusing, but this example should make sense. >>> d = DotExpandedDict({'person.1.firstname': ['Simon'], 'person.1.lastname': ['Willison'], 'person.2.firstname': ['Adrian'], 'person.2.lastname': ['Holovaty']}) >>> d {'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}} >>> d['person'] {'1': {'firstname': ['Simon'], 'lastname': ['Willison'], '2': {'firstname': ['Adrian'], 'lastname': ['Holovaty']} >>> d['person']['1'] {'firstname': ['Simon'], 'lastname': ['Willison']} # Gotcha: Results are unpredictable if the dots are "uneven": >>> DotExpandedDict({'c.1': 2, 'c.2': 3, 'c': 1}) >>> {'c': 1} """ def __init__(self, key_to_list_mapping): for k, v in key_to_list_mapping.items(): current = self bits = k.split('.') for bit in bits[:-1]: current = current.setdefault(bit, {}) # Now assign value to current position try: current[bits[-1]] = v except TypeError: # Special-case if current isn't a dict. current = {bits[-1] : v}
Python
import re from django.conf import settings # Capitalizes the first letter of a string. capfirst = lambda x: x and x[0].upper() + x[1:] def wrap(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines. """ def _generator(): it = iter(text.split(' ')) word = it.next() yield word pos = len(word) - word.rfind('\n') - 1 for word in it: if "\n" in word: lines = word.split('\n') else: lines = (word,) pos += len(lines[0]) + 1 if pos > width: yield '\n' pos = len(lines[-1]) else: yield ' ' if len(lines) > 1: pos = len(lines[-1]) yield word return "".join(_generator()) def truncate_words(s, num): "Truncates a string after a certain number of words." length = int(num) words = s.split() if len(words) > length: words = words[:length] if not words[-1].endswith('...'): words.append('...') return ' '.join(words) def truncate_html_words(s, num): """ Truncates html to a certain number of words (not counting tags and comments). Closes opened tags if they were correctly closed in the given html. """ length = int(num) if length <= 0: return '' html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input') # Set up regular expressions re_words = re.compile(r'&.*?;|<.*?>|([A-Za-z0-9][\w-]*)') re_tag = re.compile(r'<(/)?([^ ]+?)(?: (/)| .*?)?>') # Count non-HTML words and keep note of open tags pos = 0 ellipsis_pos = 0 words = 0 open_tags = [] while words <= length: m = re_words.search(s, pos) if not m: # Checked through whole string break pos = m.end(0) if m.group(1): # It's an actual non-HTML word words += 1 if words == length: ellipsis_pos = pos continue # Check for tag tag = re_tag.match(m.group(0)) if not tag or ellipsis_pos: # Don't worry about non tags or tags after our truncate point continue closing_tag, tagname, self_closing = tag.groups() tagname = tagname.lower() # Element names are always case-insensitive if self_closing or tagname in html4_singlets: pass elif closing_tag: # Check for match in open tags list try: i = open_tags.index(tagname) except ValueError: pass else: # SGML: An end tag closes, back to the matching start tag, all unclosed intervening start tags with omitted end tags open_tags = open_tags[i+1:] else: # Add it to the start of the open tags list open_tags.insert(0, tagname) if words <= length: # Don't try to close tags if we don't need to truncate return s out = s[:ellipsis_pos] + ' ...' # Close any tags still open for tag in open_tags: out += '</%s>' % tag # Return string return out def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and all non-filename-safe characters are removed. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = s.strip().replace(' ', '_') return re.sub(r'[^-A-Za-z0-9_.]', '', s) def get_text_list(list_, last_word='or'): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' """ if len(list_) == 0: return '' if len(list_) == 1: return list_[0] return '%s %s %s' % (', '.join([str(i) for i in list_][:-1]), last_word, list_[-1]) def normalize_newlines(text): return re.sub(r'\r\n|\r|\n', '\n', text) def recapitalize(text): "Recapitalizes text, placing caps after end-of-sentence punctuation." # capwords = () text = text.lower() capsRE = re.compile(r'(?:^|(?<=[\.\?\!] ))([a-z])') text = capsRE.sub(lambda x: x.group(1).upper(), text) # for capword in capwords: # capwordRE = re.compile(r'\b%s\b' % capword, re.I) # text = capwordRE.sub(capword, text) return text def phone2numeric(phone): "Converts a phone number with letters into its numeric equivalent." letters = re.compile(r'[A-PR-Y]', re.I) char2number = lambda m: {'a': '2', 'c': '2', 'b': '2', 'e': '3', 'd': '3', 'g': '4', 'f': '3', 'i': '4', 'h': '4', 'k': '5', 'j': '5', 'm': '6', 'l': '5', 'o': '6', 'n': '6', 'p': '7', 's': '7', 'r': '7', 'u': '8', 't': '8', 'w': '9', 'v': '8', 'y': '9', 'x': '9'}.get(m.group(0).lower()) return letters.sub(char2number, phone) # From http://www.xhaus.com/alan/python/httpcomp.html#gzip # Used with permission. def compress_string(s): import cStringIO, gzip zbuf = cStringIO.StringIO() zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(s) zfile.close() return zbuf.getvalue() ustring_re = re.compile(u"([\u0080-\uffff])") def javascript_quote(s, quote_double_quotes=False): def fix(match): return r"\u%04x" % ord(match.group(1)) if type(s) == str: s = s.decode(settings.DEFAULT_CHARSET) elif type(s) != unicode: raise TypeError, s s = s.replace('\\', '\\\\') s = s.replace('\r', '\\r') s = s.replace('\n', '\\n') s = s.replace('\t', '\\t') s = s.replace("'", "\\'") if quote_double_quotes: s = s.replace('"', '&quot;') return str(ustring_re.sub(fix, s)) smart_split_re = re.compile('("(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'(?:[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'|[^\\s]+)') def smart_split(text): """ Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks. >>> list(smart_split('This is "a person\'s" test.')) ['This', 'is', '"a person\'s"', 'test.'] """ for bit in smart_split_re.finditer(text): bit = bit.group(0) if bit[0] == '"': yield '"' + bit[1:-1].replace('\\"', '"').replace('\\\\', '\\') + '"' elif bit[0] == "'": yield "'" + bit[1:-1].replace("\\'", "'").replace("\\\\", "\\") + "'" else: yield bit
Python
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> feed = feedgenerator.Rss201rev2Feed( ... title=u"Poynter E-Media Tidbits", ... link=u"http://www.poynter.org/column.asp?id=31", ... description=u"A group weblog by the sharpest minds in online media/journalism/publishing.", ... language=u"en", ... ) >>> feed.add_item(title="Hello", link=u"http://www.holovaty.com/test/", description="Testing.") >>> fp = open('test.rss', 'w') >>> feed.write(fp, 'utf-8') >>> fp.close() For definitions of the different versions of RSS, see: http://diveintomark.org/archives/2004/02/04/incompatible-rss """ from django.utils.xmlutils import SimplerXMLGenerator import datetime, re, time import email.Utils def rfc2822_date(date): return email.Utils.formatdate(time.mktime(date.timetuple())) def rfc3339_date(date): return date.strftime('%Y-%m-%dT%H:%M:%SZ') def get_tag_uri(url, date): "Creates a TagURI. See http://diveintomark.org/archives/2004/05/28/howto-atom-id" tag = re.sub('^http://', '', url) if date is not None: tag = re.sub('/', ',%s:/' % date.strftime('%Y-%m-%d'), tag, 1) tag = re.sub('#', '/', tag) return 'tag:' + tag class SyndicationFeed(object): "Base class for all syndication feeds. Subclasses should provide write()" def __init__(self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None): self.feed = { 'title': title, 'link': link, 'description': description, 'language': language, 'author_email': author_email, 'author_name': author_name, 'author_link': author_link, 'subtitle': subtitle, 'categories': categories or (), 'feed_url': feed_url, 'feed_copyright': feed_copyright, } self.items = [] def add_item(self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, enclosure=None, categories=(), item_copyright=None): """ Adds an item to the feed. All args are expected to be Python Unicode objects except pubdate, which is a datetime.datetime object, and enclosure, which is an instance of the Enclosure class. """ self.items.append({ 'title': title, 'link': link, 'description': description, 'author_email': author_email, 'author_name': author_name, 'author_link': author_link, 'pubdate': pubdate, 'comments': comments, 'unique_id': unique_id, 'enclosure': enclosure, 'categories': categories or (), 'item_copyright': item_copyright, }) def num_items(self): return len(self.items) def write(self, outfile, encoding): """ Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. """ raise NotImplementedError def writeString(self, encoding): """ Returns the feed in the given encoding as a string. """ from StringIO import StringIO s = StringIO() self.write(s, encoding) return s.getvalue() def latest_post_date(self): """ Returns the latest item's pubdate. If none of them have a pubdate, this returns the current date/time. """ updates = [i['pubdate'] for i in self.items if i['pubdate'] is not None] if len(updates) > 0: updates.sort() return updates[-1] else: return datetime.datetime.now() class Enclosure(object): "Represents an RSS enclosure" def __init__(self, url, length, mime_type): "All args are expected to be Python Unicode objects" self.url, self.length, self.mime_type = url, length, mime_type class RssFeed(SyndicationFeed): mime_type = 'application/rss+xml' def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() handler.startElement(u"rss", {u"version": self._version}) handler.startElement(u"channel", {}) handler.addQuickElement(u"title", self.feed['title']) handler.addQuickElement(u"link", self.feed['link']) handler.addQuickElement(u"description", self.feed['description']) if self.feed['language'] is not None: handler.addQuickElement(u"language", self.feed['language']) for cat in self.feed['categories']: handler.addQuickElement(u"category", cat) if self.feed['feed_copyright'] is not None: handler.addQuickElement(u"copyright", self.feed['feed_copyright']) self.write_items(handler) self.endChannelElement(handler) handler.endElement(u"rss") def endChannelElement(self, handler): handler.endElement(u"channel") class RssUserland091Feed(RssFeed): _version = u"0.91" def write_items(self, handler): for item in self.items: handler.startElement(u"item", {}) handler.addQuickElement(u"title", item['title']) handler.addQuickElement(u"link", item['link']) if item['description'] is not None: handler.addQuickElement(u"description", item['description']) handler.endElement(u"item") class Rss201rev2Feed(RssFeed): # Spec: http://blogs.law.harvard.edu/tech/rss _version = u"2.0" def write_items(self, handler): for item in self.items: handler.startElement(u"item", {}) handler.addQuickElement(u"title", item['title']) handler.addQuickElement(u"link", item['link']) if item['description'] is not None: handler.addQuickElement(u"description", item['description']) # Author information. if item["author_name"] and item["author_email"]: handler.addQuickElement(u"author", "%s (%s)" % \ (item['author_email'], item['author_name'])) elif item["author_email"]: handler.addQuickElement(u"author", item["author_email"]) if item['pubdate'] is not None: handler.addQuickElement(u"pubDate", rfc2822_date(item['pubdate']).decode('ascii')) if item['comments'] is not None: handler.addQuickElement(u"comments", item['comments']) if item['unique_id'] is not None: handler.addQuickElement(u"guid", item['unique_id']) # Enclosure. if item['enclosure'] is not None: handler.addQuickElement(u"enclosure", '', {u"url": item['enclosure'].url, u"length": item['enclosure'].length, u"type": item['enclosure'].mime_type}) # Categories. for cat in item['categories']: handler.addQuickElement(u"category", cat) handler.endElement(u"item") class Atom1Feed(SyndicationFeed): # Spec: http://atompub.org/2005/07/11/draft-ietf-atompub-format-10.html mime_type = 'application/atom+xml' ns = u"http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() if self.feed['language'] is not None: handler.startElement(u"feed", {u"xmlns": self.ns, u"xml:lang": self.feed['language']}) else: handler.startElement(u"feed", {u"xmlns": self.ns}) handler.addQuickElement(u"title", self.feed['title']) handler.addQuickElement(u"link", "", {u"rel": u"alternate", u"href": self.feed['link']}) if self.feed['feed_url'] is not None: handler.addQuickElement(u"link", "", {u"rel": u"self", u"href": self.feed['feed_url']}) handler.addQuickElement(u"id", self.feed['link']) handler.addQuickElement(u"updated", rfc3339_date(self.latest_post_date()).decode('ascii')) if self.feed['author_name'] is not None: handler.startElement(u"author", {}) handler.addQuickElement(u"name", self.feed['author_name']) if self.feed['author_email'] is not None: handler.addQuickElement(u"email", self.feed['author_email']) if self.feed['author_link'] is not None: handler.addQuickElement(u"uri", self.feed['author_link']) handler.endElement(u"author") if self.feed['subtitle'] is not None: handler.addQuickElement(u"subtitle", self.feed['subtitle']) for cat in self.feed['categories']: handler.addQuickElement(u"category", "", {u"term": cat}) if self.feed['feed_copyright'] is not None: handler.addQuickElement(u"rights", self.feed['feed_copyright']) self.write_items(handler) handler.endElement(u"feed") def write_items(self, handler): for item in self.items: handler.startElement(u"entry", {}) handler.addQuickElement(u"title", item['title']) handler.addQuickElement(u"link", u"", {u"href": item['link'], u"rel": u"alternate"}) if item['pubdate'] is not None: handler.addQuickElement(u"updated", rfc3339_date(item['pubdate']).decode('ascii')) # Author information. if item['author_name'] is not None: handler.startElement(u"author", {}) handler.addQuickElement(u"name", item['author_name']) if item['author_email'] is not None: handler.addQuickElement(u"email", item['author_email']) if item['author_link'] is not None: handler.addQuickElement(u"uri", item['author_link']) handler.endElement(u"author") # Unique ID. if item['unique_id'] is not None: unique_id = item['unique_id'] else: unique_id = get_tag_uri(item['link'], item['pubdate']) handler.addQuickElement(u"id", unique_id) # Summary. if item['description'] is not None: handler.addQuickElement(u"summary", item['description'], {u"type": u"html"}) # Enclosure. if item['enclosure'] is not None: handler.addQuickElement(u"link", '', {u"rel": u"enclosure", u"href": item['enclosure'].url, u"length": item['enclosure'].length, u"type": item['enclosure'].mime_type}) # Categories. for cat in item['categories']: handler.addQuickElement(u"category", u"", {u"term": cat}) # Rights. if item['item_copyright'] is not None: handler.addQuickElement(u"rights", item['item_copyright']) handler.endElement(u"entry") # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". DefaultFeed = Rss201rev2Feed
Python
import datetime, math, time from django.utils.tzinfo import LocalTimezone from django.utils.translation import ngettext def timesince(d, now=None): """ Takes two datetime objects and returns the time between then and now as a nicely formatted string, e.g "10 minutes" Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, lambda n: ngettext('year', 'years', n)), (60 * 60 * 24 * 30, lambda n: ngettext('month', 'months', n)), (60 * 60 * 24 * 7, lambda n : ngettext('week', 'weeks', n)), (60 * 60 * 24, lambda n : ngettext('day', 'days', n)), (60 * 60, lambda n: ngettext('hour', 'hours', n)), (60, lambda n: ngettext('minute', 'minutes', n)) ) # Convert datetime.date to datetime.datetime for comparison if d.__class__ is not datetime.datetime: d = datetime.datetime(d.year, d.month, d.day) if now: t = now.timetuple() else: t = time.localtime() if d.tzinfo: tz = LocalTimezone(d) else: tz = None now = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], tzinfo=tz) # ignore microsecond part of 'd' since we removed it from 'now' delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) since = delta.days * 24 * 60 * 60 + delta.seconds for i, (seconds, name) in enumerate(chunks): count = since / seconds if count != 0: break if count < 0: return '%d milliseconds' % math.floor((now - d).microseconds / 1000) s = '%d %s' % (count, name(count)) if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) / seconds2 if count2 != 0: s += ', %d %s' % (count2, name2(count2)) return s def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ if now == None: now = datetime.datetime.now() return timesince(now, d)
Python
import os from Cookie import SimpleCookie from pprint import pformat from urllib import urlencode, quote from django.utils.datastructures import MultiValueDict RESERVED_CHARS="!*'();:@&=+$,/?%#[]" try: # The mod_python version is more efficient, so try importing it first. from mod_python.util import parse_qsl except ImportError: from cgi import parse_qsl class Http404(Exception): pass class HttpRequest(object): "A basic HTTP request" def __init__(self): self.GET, self.POST, self.COOKIES, self.META, self.FILES = {}, {}, {}, {}, {} self.path = '' self.method = None def __repr__(self): return '<HttpRequest\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' % \ (pformat(self.GET), pformat(self.POST), pformat(self.COOKIES), pformat(self.META)) def __getitem__(self, key): for d in (self.POST, self.GET): if d.has_key(key): return d[key] raise KeyError, "%s not found in either POST or GET" % key def has_key(self, key): return self.GET.has_key(key) or self.POST.has_key(key) def get_full_path(self): return '' def is_secure(self): return os.environ.get("HTTPS") == "on" def parse_file_upload(header_dict, post_data): "Returns a tuple of (POST MultiValueDict, FILES MultiValueDict)" import email, email.Message from cgi import parse_header raw_message = '\r\n'.join(['%s:%s' % pair for pair in header_dict.items()]) raw_message += '\r\n\r\n' + post_data msg = email.message_from_string(raw_message) POST = MultiValueDict() FILES = MultiValueDict() for submessage in msg.get_payload(): if submessage and isinstance(submessage, email.Message.Message): name_dict = parse_header(submessage['Content-Disposition'])[1] # name_dict is something like {'name': 'file', 'filename': 'test.txt'} for file uploads # or {'name': 'blah'} for POST fields # We assume all uploaded files have a 'filename' set. if name_dict.has_key('filename'): assert type([]) != type(submessage.get_payload()), "Nested MIME messages are not supported" if not name_dict['filename'].strip(): continue # IE submits the full path, so trim everything but the basename. # (We can't use os.path.basename because it expects Linux paths.) filename = name_dict['filename'][name_dict['filename'].rfind("\\")+1:] FILES.appendlist(name_dict['name'], { 'filename': filename, 'content-type': (submessage.has_key('Content-Type') and submessage['Content-Type'] or None), 'content': submessage.get_payload(), }) else: POST.appendlist(name_dict['name'], submessage.get_payload()) return POST, FILES class QueryDict(MultiValueDict): """A specialized MultiValueDict that takes a query string when initialized. This is immutable unless you create a copy of it.""" def __init__(self, query_string, mutable=False): MultiValueDict.__init__(self) self._mutable = True for key, value in parse_qsl((query_string or ''), True): # keep_blank_values=True self.appendlist(key, value) self._mutable = mutable def _assert_mutable(self): if not self._mutable: raise AttributeError, "This QueryDict instance is immutable" def __setitem__(self, key, value): self._assert_mutable() MultiValueDict.__setitem__(self, key, value) def __copy__(self): result = self.__class__('', mutable=True) for key, value in dict.items(self): dict.__setitem__(result, key, value) return result def __deepcopy__(self, memo={}): import copy result = self.__class__('', mutable=True) memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__(result, copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def setlist(self, key, list_): self._assert_mutable() MultiValueDict.setlist(self, key, list_) def appendlist(self, key, value): self._assert_mutable() MultiValueDict.appendlist(self, key, value) def update(self, other_dict): self._assert_mutable() MultiValueDict.update(self, other_dict) def pop(self, key): self._assert_mutable() return MultiValueDict.pop(self, key) def popitem(self): self._assert_mutable() return MultiValueDict.popitem(self) def clear(self): self._assert_mutable() MultiValueDict.clear(self) def setdefault(self, *args): self._assert_mutable() return MultiValueDict.setdefault(self, *args) def copy(self): "Returns a mutable copy of this object." return self.__deepcopy__() def urlencode(self): output = [] for k, list_ in self.lists(): output.extend([urlencode({k: v}) for v in list_]) return '&'.join(output) def parse_cookie(cookie): if cookie == '': return {} c = SimpleCookie() c.load(cookie) cookiedict = {} for key in c.keys(): cookiedict[key] = c.get(key).value return cookiedict class HttpResponse(object): "A basic HTTP response, with content and dictionary-accessed headers" def __init__(self, content='', mimetype=None): from django.conf import settings self._charset = settings.DEFAULT_CHARSET if not mimetype: mimetype = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE, settings.DEFAULT_CHARSET) if not isinstance(content, basestring) and hasattr(content, '__iter__'): self._container = content self._is_string = False else: self._container = [content] self._is_string = True self.headers = {'Content-Type': mimetype} self.cookies = SimpleCookie() self.status_code = 200 def __str__(self): "Full HTTP message, including headers" return '\n'.join(['%s: %s' % (key, value) for key, value in self.headers.items()]) \ + '\n\n' + self.content def __setitem__(self, header, value): self.headers[header] = value def __delitem__(self, header): try: del self.headers[header] except KeyError: pass def __getitem__(self, header): return self.headers[header] def has_header(self, header): "Case-insensitive check for a header" header = header.lower() for key in self.headers.keys(): if key.lower() == header: return True return False def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None): self.cookies[key] = value for var in ('max_age', 'path', 'domain', 'secure', 'expires'): val = locals()[var] if val is not None: self.cookies[key][var.replace('_', '-')] = val def delete_cookie(self, key, path='/', domain=None): self.cookies[key] = '' if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain self.cookies[key]['expires'] = 0 self.cookies[key]['max-age'] = 0 def _get_content(self): content = ''.join(self._container) if isinstance(content, unicode): content = content.encode(self._charset) return content def _set_content(self, value): self._container = [value] self._is_string = True content = property(_get_content, _set_content) def __iter__(self): self._iterator = self._container.__iter__() return self def next(self): chunk = self._iterator.next() if isinstance(chunk, unicode): chunk = chunk.encode(self._charset) return chunk def close(self): if hasattr(self._container, 'close'): self._container.close() # The remaining methods partially implement the file-like object interface. # See http://docs.python.org/lib/bltin-file-objects.html def write(self, content): if not self._is_string: raise Exception, "This %s instance is not writable" % self.__class__ self._container.append(content) def flush(self): pass def tell(self): if not self._is_string: raise Exception, "This %s instance cannot tell its position" % self.__class__ return sum([len(chunk) for chunk in self._container]) class HttpResponseRedirect(HttpResponse): def __init__(self, redirect_to): HttpResponse.__init__(self) self['Location'] = quote(redirect_to, safe=RESERVED_CHARS) self.status_code = 302 class HttpResponsePermanentRedirect(HttpResponse): def __init__(self, redirect_to): HttpResponse.__init__(self) self['Location'] = quote(redirect_to, safe=RESERVED_CHARS) self.status_code = 301 class HttpResponseNotModified(HttpResponse): def __init__(self): HttpResponse.__init__(self) self.status_code = 304 class HttpResponseNotFound(HttpResponse): def __init__(self, *args, **kwargs): HttpResponse.__init__(self, *args, **kwargs) self.status_code = 404 class HttpResponseForbidden(HttpResponse): def __init__(self, *args, **kwargs): HttpResponse.__init__(self, *args, **kwargs) self.status_code = 403 class HttpResponseNotAllowed(HttpResponse): def __init__(self, permitted_methods): HttpResponse.__init__(self) self['Allow'] = ', '.join(permitted_methods) self.status_code = 405 class HttpResponseGone(HttpResponse): def __init__(self, *args, **kwargs): HttpResponse.__init__(self, *args, **kwargs) self.status_code = 410 class HttpResponseServerError(HttpResponse): def __init__(self, *args, **kwargs): HttpResponse.__init__(self, *args, **kwargs) self.status_code = 500 def get_host(request): "Gets the HTTP host from the environment or request headers." host = request.META.get('HTTP_X_FORWARDED_HOST', '') if not host: host = request.META.get('HTTP_HOST', '') return host
Python
DATA_TYPES = {}
Python
from django.db.backends.dummy.base import complain get_table_list = complain get_table_description = complain get_relations = complain get_indexes = complain DATA_TYPES_REVERSE = {}
Python
""" Dummy database backend for Django. Django uses this if the DATABASE_ENGINE setting is empty (None or empty string). Each of these API functions, except connection.close(), raises ImproperlyConfigured. """ from django.core.exceptions import ImproperlyConfigured def complain(*args, **kwargs): raise ImproperlyConfigured, "You haven't set the DATABASE_ENGINE setting yet." class DatabaseError(Exception): pass class DatabaseWrapper: cursor = complain _commit = complain _rollback = complain def __init__(self, **kwargs): pass def close(self): pass # close() supports_constraints = False quote_name = complain dictfetchone = complain dictfetchmany = complain dictfetchall = complain get_last_insert_id = complain get_date_extract_sql = complain get_date_trunc_sql = complain get_limit_offset_sql = complain get_random_function_sql = complain get_deferrable_sql = complain get_fulltext_search_sql = complain get_drop_foreignkey_sql = complain get_sql_flush = complain OPERATOR_MAPPING = {}
Python
from django.db.backends.dummy.base import complain runshell = complain
Python
# This dictionary maps Field objects to their associated MySQL column # types, as strings. Column-type strings can contain format strings; they'll # be interpolated against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. DATA_TYPES = { 'AutoField': 'integer AUTO_INCREMENT', 'BooleanField': 'bool', 'CharField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'DateField': 'date', 'DateTimeField': 'datetime', 'FileField': 'varchar(100)', 'FilePathField': 'varchar(100)', 'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'ImageField': 'varchar(100)', 'IntegerField': 'integer', 'IPAddressField': 'char(15)', 'ManyToManyField': None, 'NullBooleanField': 'bool', 'OneToOneField': 'integer', 'PhoneNumberField': 'varchar(20)', 'PositiveIntegerField': 'integer UNSIGNED', 'PositiveSmallIntegerField': 'smallint UNSIGNED', 'SlugField': 'varchar(%(maxlength)s)', 'SmallIntegerField': 'smallint', 'TextField': 'longtext', 'TimeField': 'time', 'USStateField': 'varchar(2)', }
Python
from django.db.backends.mysql.base import quote_name from MySQLdb import ProgrammingError, OperationalError from MySQLdb.constants import FIELD_TYPE import re foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)") def get_table_list(cursor): "Returns a list of table names in the current database." cursor.execute("SHOW TABLES") return [row[0] for row in cursor.fetchall()] def get_table_description(cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name)) return cursor.description def _name_to_index(cursor, table_name): """ Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based. """ return dict([(d[0], i) for i, d in enumerate(get_table_description(cursor, table_name))]) def get_relations(cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ my_field_dict = _name_to_index(cursor, table_name) constraints = [] relations = {} try: # This should work for MySQL 5.0. cursor.execute(""" SELECT column_name, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE table_name = %s AND table_schema = DATABASE() AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL""", [table_name]) constraints.extend(cursor.fetchall()) except (ProgrammingError, OperationalError): # Fall back to "SHOW CREATE TABLE", for previous MySQL versions. # Go through all constraints and save the equal matches. cursor.execute("SHOW CREATE TABLE %s" % quote_name(table_name)) for row in cursor.fetchall(): pos = 0 while True: match = foreign_key_re.search(row[1], pos) if match == None: break pos = match.end() constraints.append(match.groups()) for my_fieldname, other_table, other_field in constraints: other_field_index = _name_to_index(cursor, other_table)[other_field] my_field_index = my_field_dict[my_fieldname] relations[my_field_index] = (other_field_index, other_table) return relations def get_indexes(cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ cursor.execute("SHOW INDEX FROM %s" % quote_name(table_name)) indexes = {} for row in cursor.fetchall(): indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': not bool(row[1])} return indexes DATA_TYPES_REVERSE = { FIELD_TYPE.BLOB: 'TextField', FIELD_TYPE.CHAR: 'CharField', FIELD_TYPE.DECIMAL: 'FloatField', FIELD_TYPE.DATE: 'DateField', FIELD_TYPE.DATETIME: 'DateTimeField', FIELD_TYPE.DOUBLE: 'FloatField', FIELD_TYPE.FLOAT: 'FloatField', FIELD_TYPE.INT24: 'IntegerField', FIELD_TYPE.LONG: 'IntegerField', FIELD_TYPE.LONGLONG: 'IntegerField', FIELD_TYPE.SHORT: 'IntegerField', FIELD_TYPE.STRING: 'TextField', FIELD_TYPE.TIMESTAMP: 'DateTimeField', FIELD_TYPE.TINY: 'IntegerField', FIELD_TYPE.TINY_BLOB: 'TextField', FIELD_TYPE.MEDIUM_BLOB: 'TextField', FIELD_TYPE.LONG_BLOB: 'TextField', FIELD_TYPE.VAR_STRING: 'CharField', }
Python
""" MySQL database backend for Django. Requires MySQLdb: http://sourceforge.net/projects/mysql-python """ from django.db.backends import util try: import MySQLdb as Database except ImportError, e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "Error loading MySQLdb module: %s" % e # We want version (1, 2, 1, 'final', 2) or later. We can't just use # lexicographic ordering in this check because then (1, 2, 1, 'gamma') # inadvertently passes the version test. version = Database.version_info if (version < (1,2,1) or (version[:3] == (1, 2, 1) and (len(version) < 5 or version[3] != 'final' or version[4] < 2))): raise ImportError, "MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__ from MySQLdb.converters import conversions from MySQLdb.constants import FIELD_TYPE import types import re DatabaseError = Database.DatabaseError # MySQLdb-1.2.1 supports the Python boolean type, and only uses datetime # module for time-related columns; older versions could have used mx.DateTime # or strings if there were no datetime module. However, MySQLdb still returns # TIME columns as timedelta -- they are more like timedelta in terms of actual # behavior as they are signed and include days -- and Django expects time, so # we still need to override that. django_conversions = conversions.copy() django_conversions.update({ FIELD_TYPE.TIME: util.typecast_time, }) # This should match the numerical portion of the version numbers (we can treat # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version # at http://dev.mysql.com/doc/refman/4.1/en/news.html and # http://dev.mysql.com/doc/refman/5.0/en/news.html . server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})') # MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on # MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the # point is to raise Warnings as exceptions, this can be done with the Python # warning module, and this is setup when the connection is created, and the # standard util.CursorDebugWrapper can be used. Also, using sql_mode # TRADITIONAL will automatically cause most warnings to be treated as errors. try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] self.server_version = None self.options = kwargs def _valid_connection(self): if self.connection is not None: try: self.connection.ping() return True except DatabaseError: self.connection.close() self.connection = None return False def cursor(self): from django.conf import settings from warnings import filterwarnings if not self._valid_connection(): kwargs = { 'conv': django_conversions, 'charset': 'utf8', 'use_unicode': False, } if settings.DATABASE_USER: kwargs['user'] = settings.DATABASE_USER if settings.DATABASE_NAME: kwargs['db'] = settings.DATABASE_NAME if settings.DATABASE_PASSWORD: kwargs['passwd'] = settings.DATABASE_PASSWORD if settings.DATABASE_HOST.startswith('/'): kwargs['unix_socket'] = settings.DATABASE_HOST elif settings.DATABASE_HOST: kwargs['host'] = settings.DATABASE_HOST if settings.DATABASE_PORT: kwargs['port'] = int(settings.DATABASE_PORT) kwargs.update(self.options) self.connection = Database.connect(**kwargs) cursor = self.connection.cursor() else: cursor = self.connection.cursor() if settings.DEBUG: filterwarnings("error", category=Database.Warning) return util.CursorDebugWrapper(cursor, self) return cursor def _commit(self): if self.connection is not None: self.connection.commit() def _rollback(self): if self.connection is not None: try: self.connection.rollback() except Database.NotSupportedError: pass def close(self): if self.connection is not None: self.connection.close() self.connection = None def get_server_version(self): if not self.server_version: if not self._valid_connection(): self.cursor() m = server_version_re.match(self.connection.get_server_info()) if not m: raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info()) self.server_version = tuple([int(x) for x in m.groups()]) return self.server_version supports_constraints = True def quote_name(name): if name.startswith("`") and name.endswith("`"): return name # Quoting once is enough. return "`%s`" % name dictfetchone = util.dictfetchone dictfetchmany = util.dictfetchmany dictfetchall = util.dictfetchall def get_last_insert_id(cursor, table_name, pk_name): return cursor.lastrowid def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), table_name) def get_date_trunc_sql(lookup_type, field_name): # lookup_type is 'year', 'month', 'day' fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields.index(lookup_type) + 1 except ValueError: sql = field_name else: format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) return sql def get_limit_offset_sql(limit, offset=None): sql = "LIMIT " if offset and offset != 0: sql += "%s," % offset return sql + str(limit) def get_random_function_sql(): return "RAND()" def get_deferrable_sql(): return "" def get_fulltext_search_sql(field_name): return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name def get_drop_foreignkey_sql(): return "DROP FOREIGN KEY" def get_pk_default_value(): return "DEFAULT" def get_sql_flush(style, tables, sequences): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ # NB: The generated SQL below is specific to MySQL # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements # to clear all tables of all data if tables: sql = ['SET FOREIGN_KEY_CHECKS = 0;'] + \ ['%s %s;' % \ (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)) ) for table in tables] + \ ['SET FOREIGN_KEY_CHECKS = 1;'] # 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements # to reset sequence indices sql.extend(["%s %s %s %s %s;" % \ (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('TABLE'), style.SQL_TABLE(quote_name(sequence['table'])), style.SQL_KEYWORD('AUTO_INCREMENT'), style.SQL_FIELD('= 1'), ) for sequence in sequences]) return sql else: return [] OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': 'LIKE %s', 'contains': 'LIKE BINARY %s', 'icontains': 'LIKE %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE BINARY %s', 'endswith': 'LIKE BINARY %s', 'istartswith': 'LIKE %s', 'iendswith': 'LIKE %s', }
Python
from django.conf import settings import os def runshell(): args = [''] db = settings.DATABASE_OPTIONS.get('db', settings.DATABASE_NAME) user = settings.DATABASE_OPTIONS.get('user', settings.DATABASE_USER) passwd = settings.DATABASE_OPTIONS.get('passwd', settings.DATABASE_PASSWORD) host = settings.DATABASE_OPTIONS.get('host', settings.DATABASE_HOST) port = settings.DATABASE_OPTIONS.get('port', settings.DATABASE_PORT) defaults_file = settings.DATABASE_OPTIONS.get('read_default_file') # Seems to be no good way to set sql_mode with CLI if defaults_file: args += ["--defaults-file=%s" % defaults_file] if user: args += ["--user=%s" % user] if passwd: args += ["--password=%s" % passwd] if host: args += ["--host=%s" % host] if port: args += ["--port=%s" % port] if db: args += [db] os.execvp('mysql', args)
Python
# SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. DATA_TYPES = { 'AutoField': 'integer', 'BooleanField': 'bool', 'CharField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'DateField': 'date', 'DateTimeField': 'datetime', 'FileField': 'varchar(100)', 'FilePathField': 'varchar(100)', 'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'ImageField': 'varchar(100)', 'IntegerField': 'integer', 'IPAddressField': 'char(15)', 'ManyToManyField': None, 'NullBooleanField': 'bool', 'OneToOneField': 'integer', 'PhoneNumberField': 'varchar(20)', 'PositiveIntegerField': 'integer unsigned', 'PositiveSmallIntegerField': 'smallint unsigned', 'SlugField': 'varchar(%(maxlength)s)', 'SmallIntegerField': 'smallint', 'TextField': 'text', 'TimeField': 'time', 'USStateField': 'varchar(2)', }
Python
from django.db.backends.sqlite3.base import quote_name def get_table_list(cursor): "Returns a list of table names in the current database." # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND NOT name='sqlite_sequence' ORDER BY name""") return [row[0] for row in cursor.fetchall()] def get_table_description(cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." return [(info['name'], info['type'], None, None, None, None, info['null_ok']) for info in _table_info(cursor, table_name)] def get_relations(cursor, table_name): raise NotImplementedError def get_indexes(cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ indexes = {} for info in _table_info(cursor, table_name): indexes[info['name']] = {'primary_key': info['pk'] != 0, 'unique': False} cursor.execute('PRAGMA index_list(%s)' % quote_name(table_name)) # seq, name, unique for index, unique in [(field[1], field[2]) for field in cursor.fetchall()]: if not unique: continue cursor.execute('PRAGMA index_info(%s)' % quote_name(index)) info = cursor.fetchall() # Skip indexes across multiple fields if len(info) != 1: continue name = info[0][2] # seqno, cid, name indexes[name]['unique'] = True return indexes def _table_info(cursor, name): cursor.execute('PRAGMA table_info(%s)' % quote_name(name)) # cid, name, type, notnull, dflt_value, pk return [{'name': field[1], 'type': field[2], 'null_ok': not field[3], 'pk': field[5] # undocumented } for field in cursor.fetchall()] # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. BASE_DATA_TYPES_REVERSE = { 'bool': 'BooleanField', 'boolean': 'BooleanField', 'smallint': 'SmallIntegerField', 'smallinteger': 'SmallIntegerField', 'int': 'IntegerField', 'integer': 'IntegerField', 'text': 'TextField', 'char': 'CharField', 'date': 'DateField', 'datetime': 'DateTimeField', 'time': 'TimeField', } # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: def __getitem__(self, key): key = key.lower() try: return BASE_DATA_TYPES_REVERSE[key] except KeyError: import re m = re.search(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$', key) if m: return ('CharField', {'maxlength': int(m.group(1))}) raise KeyError DATA_TYPES_REVERSE = FlexibleFieldLookupDict()
Python
""" SQLite3 backend for django. Requires pysqlite2 (http://pysqlite.org/). """ from django.db.backends import util try: try: from sqlite3 import dbapi2 as Database except ImportError: from pysqlite2 import dbapi2 as Database except ImportError, e: import sys from django.core.exceptions import ImproperlyConfigured if sys.version_info < (2, 5, 0): module = 'pysqlite2' else: module = 'sqlite3' raise ImproperlyConfigured, "Error loading %s module: %s" % (module, e) DatabaseError = Database.DatabaseError Database.register_converter("bool", lambda s: str(s) == '1') Database.register_converter("time", util.typecast_time) Database.register_converter("date", util.typecast_date) Database.register_converter("datetime", util.typecast_timestamp) Database.register_converter("timestamp", util.typecast_timestamp) Database.register_converter("TIMESTAMP", util.typecast_timestamp) def utf8rowFactory(cursor, row): def utf8(s): if type(s) == unicode: return s.encode("utf-8") else: return s return [utf8(r) for r in row] try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] self.options = kwargs def cursor(self): from django.conf import settings if self.connection is None: kwargs = { 'database': settings.DATABASE_NAME, 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, } kwargs.update(self.options) self.connection = Database.connect(**kwargs) # Register extract and date_trunc functions. self.connection.create_function("django_extract", 2, _sqlite_extract) self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc) cursor = self.connection.cursor(factory=SQLiteCursorWrapper) cursor.row_factory = utf8rowFactory if settings.DEBUG: return util.CursorDebugWrapper(cursor, self) else: return cursor def _commit(self): if self.connection is not None: self.connection.commit() def _rollback(self): if self.connection is not None: self.connection.rollback() def close(self): from django.conf import settings # If database is in memory, closing the connection destroys the database. # To prevent accidental data loss, ignore close requests on an in-memory db. if self.connection is not None and settings.DATABASE_NAME != ":memory:": self.connection.close() self.connection = None class SQLiteCursorWrapper(Database.Cursor): """ Django uses "format" style placeholders, but pysqlite2 uses "qmark" style. This fixes it -- but note that if you want to use a literal "%s" in a query, you'll need to use "%%s". """ def execute(self, query, params=()): query = self.convert_query(query, len(params)) return Database.Cursor.execute(self, query, params) def executemany(self, query, param_list): query = self.convert_query(query, len(param_list[0])) return Database.Cursor.executemany(self, query, param_list) def convert_query(self, query, num_params): return query % tuple("?" * num_params) supports_constraints = False def quote_name(name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name dictfetchone = util.dictfetchone dictfetchmany = util.dictfetchmany dictfetchall = util.dictfetchall def get_last_insert_id(cursor, table_name, pk_name): return cursor.lastrowid def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' # sqlite doesn't support extract, so we fake it with the user-defined # function _sqlite_extract that's registered in connect(), above. return 'django_extract("%s", %s)' % (lookup_type.lower(), table_name) def _sqlite_extract(lookup_type, dt): try: dt = util.typecast_timestamp(dt) except (ValueError, TypeError): return None return str(getattr(dt, lookup_type)) def get_date_trunc_sql(lookup_type, field_name): # lookup_type is 'year', 'month', 'day' # sqlite doesn't support DATE_TRUNC, so we fake it as above. return 'django_date_trunc("%s", %s)' % (lookup_type.lower(), field_name) def get_limit_offset_sql(limit, offset=None): sql = "LIMIT %s" % limit if offset and offset != 0: sql += " OFFSET %s" % offset return sql def get_random_function_sql(): return "RANDOM()" def get_deferrable_sql(): return "" def get_fulltext_search_sql(field_name): raise NotImplementedError def get_drop_foreignkey_sql(): return "" def get_pk_default_value(): return "NULL" def get_sql_flush(style, tables, sequences): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ # NB: The generated SQL below is specific to SQLite # Note: The DELETE FROM... SQL generated below works for SQLite databases # because constraints don't exist sql = ['%s %s %s;' % \ (style.SQL_KEYWORD('DELETE'), style.SQL_KEYWORD('FROM'), style.SQL_FIELD(quote_name(table)) ) for table in tables] # Note: No requirement for reset of auto-incremented indices (cf. other # get_sql_flush() implementations). Just return SQL at this point return sql def _sqlite_date_trunc(lookup_type, dt): try: dt = util.typecast_timestamp(dt) except (ValueError, TypeError): return None if lookup_type == 'year': return "%i-01-01 00:00:00" % dt.year elif lookup_type == 'month': return "%i-%02i-01 00:00:00" % (dt.year, dt.month) elif lookup_type == 'day': return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day) # SQLite requires LIKE statements to include an ESCAPE clause if the value # being escaped has a percent or underscore in it. # See http://www.sqlite.org/lang_expr.html for an explanation. OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': "LIKE %s ESCAPE '\\'", 'contains': "LIKE %s ESCAPE '\\'", 'icontains': "LIKE %s ESCAPE '\\'", 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': "LIKE %s ESCAPE '\\'", 'endswith': "LIKE %s ESCAPE '\\'", 'istartswith': "LIKE %s ESCAPE '\\'", 'iendswith': "LIKE %s ESCAPE '\\'", }
Python
from django.conf import settings import os def runshell(): args = ['', settings.DATABASE_NAME] os.execvp('sqlite3', args)
Python
from django.db.backends.postgresql.creation import *
Python
from django.db.backends.postgresql_psycopg2.base import quote_name def get_table_list(cursor): "Returns a list of table names in the current database." cursor.execute(""" SELECT c.relname FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v', '') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid)""") return [row[0] for row in cursor.fetchall()] def get_table_description(cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name)) return cursor.description def get_relations(cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ cursor.execute(""" SELECT con.conkey, con.confkey, c2.relname FROM pg_constraint con, pg_class c1, pg_class c2 WHERE c1.oid = con.conrelid AND c2.oid = con.confrelid AND c1.relname = %s AND con.contype = 'f'""", [table_name]) relations = {} for row in cursor.fetchall(): try: # row[0] and row[1] are like "{2}", so strip the curly braces. relations[int(row[0][1:-1]) - 1] = (int(row[1][1:-1]) - 1, row[2]) except ValueError: continue return relations def get_indexes(cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ # This query retrieves each index on the given table, including the # first associated field name cursor.execute(""" SELECT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index idx, pg_catalog.pg_attribute attr WHERE c.oid = idx.indrelid AND idx.indexrelid = c2.oid AND attr.attrelid = c.oid AND attr.attnum = idx.indkey[0] AND c.relname = %s""", [table_name]) indexes = {} for row in cursor.fetchall(): # row[1] (idx.indkey) is stored in the DB as an array. It comes out as # a string of space-separated integers. This designates the field # indexes (1-based) of the fields that have indexes on the table. # Here, we skip any indexes across multiple fields. if ' ' in row[1]: continue indexes[row[0]] = {'primary_key': row[3], 'unique': row[2]} return indexes # Maps type codes to Django Field types. DATA_TYPES_REVERSE = { 16: 'BooleanField', 21: 'SmallIntegerField', 23: 'IntegerField', 25: 'TextField', 869: 'IPAddressField', 1043: 'CharField', 1082: 'DateField', 1083: 'TimeField', 1114: 'DateTimeField', 1184: 'DateTimeField', 1266: 'TimeField', 1700: 'FloatField', }
Python
""" PostgreSQL database backend for Django. Requires psycopg 2: http://initd.org/projects/psycopg2 """ from django.db.backends import util try: import psycopg2 as Database except ImportError, e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "Error loading psycopg2 module: %s" % e DatabaseError = Database.DatabaseError try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local postgres_version = None class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] self.options = kwargs def cursor(self): from django.conf import settings set_tz = False if self.connection is None: set_tz = True if settings.DATABASE_NAME == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "You need to specify DATABASE_NAME in your Django settings file." conn_string = "dbname=%s" % settings.DATABASE_NAME if settings.DATABASE_USER: conn_string = "user=%s %s" % (settings.DATABASE_USER, conn_string) if settings.DATABASE_PASSWORD: conn_string += " password='%s'" % settings.DATABASE_PASSWORD if settings.DATABASE_HOST: conn_string += " host=%s" % settings.DATABASE_HOST if settings.DATABASE_PORT: conn_string += " port=%s" % settings.DATABASE_PORT self.connection = Database.connect(conn_string, **self.options) self.connection.set_isolation_level(1) # make transactions transparent to all cursors cursor = self.connection.cursor() cursor.tzinfo_factory = None if set_tz: cursor.execute("SET TIME ZONE %s", [settings.TIME_ZONE]) global postgres_version if not postgres_version: cursor.execute("SELECT version()") postgres_version = [int(val) for val in cursor.fetchone()[0].split()[1].split('.')] if settings.DEBUG: return util.CursorDebugWrapper(cursor, self) return cursor def _commit(self): if self.connection is not None: return self.connection.commit() def _rollback(self): if self.connection is not None: return self.connection.rollback() def close(self): if self.connection is not None: self.connection.close() self.connection = None supports_constraints = True def quote_name(name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name dictfetchone = util.dictfetchone dictfetchmany = util.dictfetchmany dictfetchall = util.dictfetchall def get_last_insert_id(cursor, table_name, pk_name): cursor.execute("SELECT CURRVAL('\"%s_%s_seq\"')" % (table_name, pk_name)) return cursor.fetchone()[0] def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT return "EXTRACT('%s' FROM %s)" % (lookup_type, table_name) def get_date_trunc_sql(lookup_type, field_name): # lookup_type is 'year', 'month', 'day' # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name) def get_limit_offset_sql(limit, offset=None): sql = "LIMIT %s" % limit if offset and offset != 0: sql += " OFFSET %s" % offset return sql def get_random_function_sql(): return "RANDOM()" def get_deferrable_sql(): return " DEFERRABLE INITIALLY DEFERRED" def get_fulltext_search_sql(field_name): raise NotImplementedError def get_drop_foreignkey_sql(): return "DROP CONSTRAINT" def get_pk_default_value(): return "DEFAULT" def get_sql_flush(style, tables, sequences): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ if tables: if postgres_version[0] >= 8 and postgres_version[1] >= 1: # Postgres 8.1+ can do 'TRUNCATE x, y, z...;'. In fact, it *has to* in order to be able to # truncate tables referenced by a foreign key in any other table. The result is a # single SQL TRUNCATE statement sql = ['%s %s;' % \ (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(', '.join([quote_name(table) for table in tables])) )] else: sql = ['%s %s %s;' % \ (style.SQL_KEYWORD('DELETE'), style.SQL_KEYWORD('FROM'), style.SQL_FIELD(quote_name(table)) ) for table in tables] # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements # to reset sequence indices for sequence in sequences: table_name = sequence['table'] column_name = sequence['column'] if column_name and len(column_name) > 0: # sequence name in this case will be <table>_<column>_seq sql.append("%s %s %s %s %s %s;" % \ (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('SEQUENCE'), style.SQL_FIELD('%s_%s_seq' % (table_name, column_name)), style.SQL_KEYWORD('RESTART'), style.SQL_KEYWORD('WITH'), style.SQL_FIELD('1') ) ) else: # sequence name in this case will be <table>_id_seq sql.append("%s %s %s %s %s %s;" % \ (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('SEQUENCE'), style.SQL_FIELD('%s_id_seq' % table_name), style.SQL_KEYWORD('RESTART'), style.SQL_KEYWORD('WITH'), style.SQL_FIELD('1') ) ) return sql else: return [] OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': 'ILIKE %s', 'contains': 'LIKE %s', 'icontains': 'ILIKE %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE %s', 'endswith': 'LIKE %s', 'istartswith': 'ILIKE %s', 'iendswith': 'ILIKE %s', }
Python
from django.db.backends.postgresql.client import *
Python
import datetime from time import time class CursorDebugWrapper(object): def __init__(self, cursor, db): self.cursor = cursor self.db = db def execute(self, sql, params=()): start = time() try: return self.cursor.execute(sql, params) finally: stop = time() # If params was a list, convert it to a tuple, because string # formatting with '%' only works with tuples or dicts. if not isinstance(params, (tuple, dict)): params = tuple(params) self.db.queries.append({ 'sql': sql % params, 'time': "%.3f" % (stop - start), }) def executemany(self, sql, param_list): start = time() try: return self.cursor.executemany(sql, param_list) finally: stop = time() self.db.queries.append({ 'sql': 'MANY: ' + sql + ' ' + str(tuple(param_list)), 'time': "%.3f" % (stop - start), }) def __getattr__(self, attr): if self.__dict__.has_key(attr): return self.__dict__[attr] else: return getattr(self.cursor, attr) ############################################### # Converters from database (string) to Python # ############################################### def typecast_date(s): return s and datetime.date(*map(int, s.split('-'))) or None # returns None if s is null def typecast_time(s): # does NOT store time zone information if not s: return None hour, minutes, seconds = s.split(':') if '.' in seconds: # check whether seconds have a fractional part seconds, microseconds = seconds.split('.') else: microseconds = '0' return datetime.time(int(hour), int(minutes), int(seconds), int(float('.'+microseconds) * 1000000)) def typecast_timestamp(s): # does NOT store time zone information # "2005-07-29 15:48:00.590358-05" # "2005-07-29 09:56:00-05" if not s: return None if not ' ' in s: return typecast_date(s) d, t = s.split() # Extract timezone information, if it exists. Currently we just throw # it away, but in the future we may make use of it. if '-' in t: t, tz = t.split('-', 1) tz = '-' + tz elif '+' in t: t, tz = t.split('+', 1) tz = '+' + tz else: tz = '' dates = d.split('-') times = t.split(':') seconds = times[2] if '.' in seconds: # check whether seconds have a fractional part seconds, microseconds = seconds.split('.') else: microseconds = '0' return datetime.datetime(int(dates[0]), int(dates[1]), int(dates[2]), int(times[0]), int(times[1]), int(seconds), int(float('.'+microseconds) * 1000000)) def typecast_boolean(s): if s is None: return None if not s: return False return str(s)[0].lower() == 't' ############################################### # Converters from Python to database (string) # ############################################### def rev_typecast_boolean(obj, d): return obj and '1' or '0' ################################################################################## # Helper functions for dictfetch* for databases that don't natively support them # ################################################################################## def _dict_helper(desc, row): "Returns a dictionary for the given cursor.description and result row." return dict(zip([col[0] for col in desc], row)) def dictfetchone(cursor): "Returns a row from the cursor as a dict" row = cursor.fetchone() if not row: return None return _dict_helper(cursor.description, row) def dictfetchmany(cursor, number): "Returns a certain number of rows from a cursor as a dict" desc = cursor.description for row in cursor.fetchmany(number): yield _dict_helper(desc, row) def dictfetchall(cursor): "Returns all rows from a cursor as a dict" desc = cursor.description for row in cursor.fetchall(): yield _dict_helper(desc, row)
Python
# This dictionary maps Field objects to their associated PostgreSQL column # types, as strings. Column-type strings can contain format strings; they'll # be interpolated against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. DATA_TYPES = { 'AutoField': 'serial', 'BooleanField': 'boolean', 'CharField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'DateField': 'date', 'DateTimeField': 'timestamp with time zone', 'FileField': 'varchar(100)', 'FilePathField': 'varchar(100)', 'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'ImageField': 'varchar(100)', 'IntegerField': 'integer', 'IPAddressField': 'inet', 'ManyToManyField': None, 'NullBooleanField': 'boolean', 'OneToOneField': 'integer', 'PhoneNumberField': 'varchar(20)', 'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)', 'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)', 'SlugField': 'varchar(%(maxlength)s)', 'SmallIntegerField': 'smallint', 'TextField': 'text', 'TimeField': 'time', 'USStateField': 'varchar(2)', }
Python
from django.db.backends.postgresql.base import quote_name def get_table_list(cursor): "Returns a list of table names in the current database." cursor.execute(""" SELECT c.relname FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v', '') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid)""") return [row[0] for row in cursor.fetchall()] def get_table_description(cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name)) return cursor.description def get_relations(cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ cursor.execute(""" SELECT con.conkey, con.confkey, c2.relname FROM pg_constraint con, pg_class c1, pg_class c2 WHERE c1.oid = con.conrelid AND c2.oid = con.confrelid AND c1.relname = %s AND con.contype = 'f'""", [table_name]) relations = {} for row in cursor.fetchall(): try: # row[0] and row[1] are like "{2}", so strip the curly braces. relations[int(row[0][1:-1]) - 1] = (int(row[1][1:-1]) - 1, row[2]) except ValueError: continue return relations def get_indexes(cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ # This query retrieves each index on the given table, including the # first associated field name cursor.execute(""" SELECT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index idx, pg_catalog.pg_attribute attr WHERE c.oid = idx.indrelid AND idx.indexrelid = c2.oid AND attr.attrelid = c.oid AND attr.attnum = idx.indkey[0] AND c.relname = %s""", [table_name]) indexes = {} for row in cursor.fetchall(): # row[1] (idx.indkey) is stored in the DB as an array. It comes out as # a string of space-separated integers. This designates the field # indexes (1-based) of the fields that have indexes on the table. # Here, we skip any indexes across multiple fields. if ' ' in row[1]: continue indexes[row[0]] = {'primary_key': row[3], 'unique': row[2]} return indexes # Maps type codes to Django Field types. DATA_TYPES_REVERSE = { 16: 'BooleanField', 21: 'SmallIntegerField', 23: 'IntegerField', 25: 'TextField', 869: 'IPAddressField', 1043: 'CharField', 1082: 'DateField', 1083: 'TimeField', 1114: 'DateTimeField', 1184: 'DateTimeField', 1266: 'TimeField', 1700: 'FloatField', }
Python
""" PostgreSQL database backend for Django. Requires psycopg 1: http://initd.org/projects/psycopg1 """ from django.db.backends import util try: import psycopg as Database except ImportError, e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "Error loading psycopg module: %s" % e DatabaseError = Database.DatabaseError try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local def smart_basestring(s, charset): if isinstance(s, unicode): return s.encode(charset) return s class UnicodeCursorWrapper(object): """ A thin wrapper around psycopg cursors that allows them to accept Unicode strings as params. This is necessary because psycopg doesn't apply any DB quoting to parameters that are Unicode strings. If a param is Unicode, this will convert it to a bytestring using DEFAULT_CHARSET before passing it to psycopg. """ def __init__(self, cursor, charset): self.cursor = cursor self.charset = charset def execute(self, sql, params=()): return self.cursor.execute(sql, [smart_basestring(p, self.charset) for p in params]) def executemany(self, sql, param_list): new_param_list = [tuple([smart_basestring(p, self.charset) for p in params]) for params in param_list] return self.cursor.executemany(sql, new_param_list) def __getattr__(self, attr): if self.__dict__.has_key(attr): return self.__dict__[attr] else: return getattr(self.cursor, attr) postgres_version = None class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] self.options = kwargs def cursor(self): from django.conf import settings set_tz = False if self.connection is None: set_tz = True if settings.DATABASE_NAME == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "You need to specify DATABASE_NAME in your Django settings file." conn_string = "dbname=%s" % settings.DATABASE_NAME if settings.DATABASE_USER: conn_string = "user=%s %s" % (settings.DATABASE_USER, conn_string) if settings.DATABASE_PASSWORD: conn_string += " password='%s'" % settings.DATABASE_PASSWORD if settings.DATABASE_HOST: conn_string += " host=%s" % settings.DATABASE_HOST if settings.DATABASE_PORT: conn_string += " port=%s" % settings.DATABASE_PORT self.connection = Database.connect(conn_string, **self.options) self.connection.set_isolation_level(1) # make transactions transparent to all cursors cursor = self.connection.cursor() if set_tz: cursor.execute("SET TIME ZONE %s", [settings.TIME_ZONE]) cursor = UnicodeCursorWrapper(cursor, settings.DEFAULT_CHARSET) global postgres_version if not postgres_version: cursor.execute("SELECT version()") postgres_version = [int(val) for val in cursor.fetchone()[0].split()[1].split('.')] if settings.DEBUG: return util.CursorDebugWrapper(cursor, self) return cursor def _commit(self): if self.connection is not None: return self.connection.commit() def _rollback(self): if self.connection is not None: return self.connection.rollback() def close(self): if self.connection is not None: self.connection.close() self.connection = None supports_constraints = True def quote_name(name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name def dictfetchone(cursor): "Returns a row from the cursor as a dict" return cursor.dictfetchone() def dictfetchmany(cursor, number): "Returns a certain number of rows from a cursor as a dict" return cursor.dictfetchmany(number) def dictfetchall(cursor): "Returns all rows from a cursor as a dict" return cursor.dictfetchall() def get_last_insert_id(cursor, table_name, pk_name): cursor.execute("SELECT CURRVAL('\"%s_%s_seq\"')" % (table_name, pk_name)) return cursor.fetchone()[0] def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT return "EXTRACT('%s' FROM %s)" % (lookup_type, table_name) def get_date_trunc_sql(lookup_type, field_name): # lookup_type is 'year', 'month', 'day' # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name) def get_limit_offset_sql(limit, offset=None): sql = "LIMIT %s" % limit if offset and offset != 0: sql += " OFFSET %s" % offset return sql def get_random_function_sql(): return "RANDOM()" def get_deferrable_sql(): return " DEFERRABLE INITIALLY DEFERRED" def get_fulltext_search_sql(field_name): raise NotImplementedError def get_drop_foreignkey_sql(): return "DROP CONSTRAINT" def get_pk_default_value(): return "DEFAULT" def get_sql_flush(style, tables, sequences): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ if tables: if postgres_version[0] >= 8 and postgres_version[1] >= 1: # Postgres 8.1+ can do 'TRUNCATE x, y, z...;'. In fact, it *has to* in order to be able to # truncate tables referenced by a foreign key in any other table. The result is a # single SQL TRUNCATE statement. sql = ['%s %s;' % \ (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(', '.join([quote_name(table) for table in tables])) )] else: # Older versions of Postgres can't do TRUNCATE in a single call, so they must use # a simple delete. sql = ['%s %s %s;' % \ (style.SQL_KEYWORD('DELETE'), style.SQL_KEYWORD('FROM'), style.SQL_FIELD(quote_name(table)) ) for table in tables] # 'ALTER SEQUENCE sequence_name RESTART WITH 1;'... style SQL statements # to reset sequence indices for sequence_info in sequences: table_name = sequence_info['table'] column_name = sequence_info['column'] if column_name and len(column_name)>0: # sequence name in this case will be <table>_<column>_seq sql.append("%s %s %s %s %s %s;" % \ (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('SEQUENCE'), style.SQL_FIELD('%s_%s_seq' % (table_name, column_name)), style.SQL_KEYWORD('RESTART'), style.SQL_KEYWORD('WITH'), style.SQL_FIELD('1') ) ) else: # sequence name in this case will be <table>_id_seq sql.append("%s %s %s %s %s %s;" % \ (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('SEQUENCE'), style.SQL_FIELD('%s_id_seq' % table_name), style.SQL_KEYWORD('RESTART'), style.SQL_KEYWORD('WITH'), style.SQL_FIELD('1') ) ) return sql else: return [] # Register these custom typecasts, because Django expects dates/times to be # in Python's native (standard-library) datetime/time format, whereas psycopg # use mx.DateTime by default. try: Database.register_type(Database.new_type((1082,), "DATE", util.typecast_date)) except AttributeError: raise Exception, "You appear to be using psycopg version 2. Set your DATABASE_ENGINE to 'postgresql_psycopg2' instead of 'postgresql'." Database.register_type(Database.new_type((1083,1266), "TIME", util.typecast_time)) Database.register_type(Database.new_type((1114,1184), "TIMESTAMP", util.typecast_timestamp)) Database.register_type(Database.new_type((16,), "BOOLEAN", util.typecast_boolean)) OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': 'ILIKE %s', 'contains': 'LIKE %s', 'icontains': 'ILIKE %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE %s', 'endswith': 'LIKE %s', 'istartswith': 'ILIKE %s', 'iendswith': 'ILIKE %s', }
Python
from django.conf import settings import os def runshell(): args = ['psql'] if settings.DATABASE_USER: args += ["-U", settings.DATABASE_USER] if settings.DATABASE_PASSWORD: args += ["-W"] if settings.DATABASE_HOST: args.extend(["-h", settings.DATABASE_HOST]) if settings.DATABASE_PORT: args.extend(["-p", str(settings.DATABASE_PORT)]) args += [settings.DATABASE_NAME] os.execvp('psql', args)
Python
# This dictionary maps Field objects to their associated MySQL column # types, as strings. Column-type strings can contain format strings; they'll # be interpolated against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. DATA_TYPES = { 'AutoField': 'integer AUTO_INCREMENT', 'BooleanField': 'bool', 'CharField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'DateField': 'date', 'DateTimeField': 'datetime', 'FileField': 'varchar(100)', 'FilePathField': 'varchar(100)', 'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'ImageField': 'varchar(100)', 'IntegerField': 'integer', 'IPAddressField': 'char(15)', 'ManyToManyField': None, 'NullBooleanField': 'bool', 'OneToOneField': 'integer', 'PhoneNumberField': 'varchar(20)', 'PositiveIntegerField': 'integer UNSIGNED', 'PositiveSmallIntegerField': 'smallint UNSIGNED', 'SlugField': 'varchar(%(maxlength)s)', 'SmallIntegerField': 'smallint', 'TextField': 'longtext', 'TimeField': 'time', 'USStateField': 'varchar(2)', }
Python
from django.db.backends.mysql_old.base import quote_name from MySQLdb import ProgrammingError, OperationalError from MySQLdb.constants import FIELD_TYPE import re foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)") def get_table_list(cursor): "Returns a list of table names in the current database." cursor.execute("SHOW TABLES") return [row[0] for row in cursor.fetchall()] def get_table_description(cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name)) return cursor.description def _name_to_index(cursor, table_name): """ Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based. """ return dict([(d[0], i) for i, d in enumerate(get_table_description(cursor, table_name))]) def get_relations(cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ my_field_dict = _name_to_index(cursor, table_name) constraints = [] relations = {} try: # This should work for MySQL 5.0. cursor.execute(""" SELECT column_name, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE table_name = %s AND table_schema = DATABASE() AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL""", [table_name]) constraints.extend(cursor.fetchall()) except (ProgrammingError, OperationalError): # Fall back to "SHOW CREATE TABLE", for previous MySQL versions. # Go through all constraints and save the equal matches. cursor.execute("SHOW CREATE TABLE %s" % quote_name(table_name)) for row in cursor.fetchall(): pos = 0 while True: match = foreign_key_re.search(row[1], pos) if match == None: break pos = match.end() constraints.append(match.groups()) for my_fieldname, other_table, other_field in constraints: other_field_index = _name_to_index(cursor, other_table)[other_field] my_field_index = my_field_dict[my_fieldname] relations[my_field_index] = (other_field_index, other_table) return relations def get_indexes(cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ cursor.execute("SHOW INDEX FROM %s" % quote_name(table_name)) indexes = {} for row in cursor.fetchall(): indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': not bool(row[1])} return indexes DATA_TYPES_REVERSE = { FIELD_TYPE.BLOB: 'TextField', FIELD_TYPE.CHAR: 'CharField', FIELD_TYPE.DECIMAL: 'FloatField', FIELD_TYPE.DATE: 'DateField', FIELD_TYPE.DATETIME: 'DateTimeField', FIELD_TYPE.DOUBLE: 'FloatField', FIELD_TYPE.FLOAT: 'FloatField', FIELD_TYPE.INT24: 'IntegerField', FIELD_TYPE.LONG: 'IntegerField', FIELD_TYPE.LONGLONG: 'IntegerField', FIELD_TYPE.SHORT: 'IntegerField', FIELD_TYPE.STRING: 'TextField', FIELD_TYPE.TIMESTAMP: 'DateTimeField', FIELD_TYPE.TINY: 'IntegerField', FIELD_TYPE.TINY_BLOB: 'TextField', FIELD_TYPE.MEDIUM_BLOB: 'TextField', FIELD_TYPE.LONG_BLOB: 'TextField', FIELD_TYPE.VAR_STRING: 'CharField', }
Python
""" MySQL database backend for Django. Requires MySQLdb: http://sourceforge.net/projects/mysql-python """ from django.db.backends import util try: import MySQLdb as Database except ImportError, e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "Error loading MySQLdb module: %s" % e from MySQLdb.converters import conversions from MySQLdb.constants import FIELD_TYPE import types import re DatabaseError = Database.DatabaseError django_conversions = conversions.copy() django_conversions.update({ types.BooleanType: util.rev_typecast_boolean, FIELD_TYPE.DATETIME: util.typecast_timestamp, FIELD_TYPE.DATE: util.typecast_date, FIELD_TYPE.TIME: util.typecast_time, }) # This should match the numerical portion of the version numbers (we can treat # versions like 5.0.24 and 5.0.24a as the same). Based on the list of version # at http://dev.mysql.com/doc/refman/4.1/en/news.html and # http://dev.mysql.com/doc/refman/5.0/en/news.html . server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})') # This is an extra debug layer over MySQL queries, to display warnings. # It's only used when DEBUG=True. class MysqlDebugWrapper: def __init__(self, cursor): self.cursor = cursor def execute(self, sql, params=()): try: return self.cursor.execute(sql, params) except Database.Warning, w: self.cursor.execute("SHOW WARNINGS") raise Database.Warning, "%s: %s" % (w, self.cursor.fetchall()) def executemany(self, sql, param_list): try: return self.cursor.executemany(sql, param_list) except Database.Warning, w: self.cursor.execute("SHOW WARNINGS") raise Database.Warning, "%s: %s" % (w, self.cursor.fetchall()) def __getattr__(self, attr): if self.__dict__.has_key(attr): return self.__dict__[attr] else: return getattr(self.cursor, attr) try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] self.server_version = None self.options = kwargs def _valid_connection(self): if self.connection is not None: try: self.connection.ping() return True except DatabaseError: self.connection.close() self.connection = None return False def cursor(self): from django.conf import settings if not self._valid_connection(): kwargs = { 'user': settings.DATABASE_USER, 'db': settings.DATABASE_NAME, 'passwd': settings.DATABASE_PASSWORD, 'conv': django_conversions, } if settings.DATABASE_HOST.startswith('/'): kwargs['unix_socket'] = settings.DATABASE_HOST else: kwargs['host'] = settings.DATABASE_HOST if settings.DATABASE_PORT: kwargs['port'] = int(settings.DATABASE_PORT) kwargs.update(self.options) self.connection = Database.connect(**kwargs) cursor = self.connection.cursor() if self.connection.get_server_info() >= '4.1': cursor.execute("SET NAMES 'utf8'") else: cursor = self.connection.cursor() if settings.DEBUG: return util.CursorDebugWrapper(MysqlDebugWrapper(cursor), self) return cursor def _commit(self): if self.connection is not None: self.connection.commit() def _rollback(self): if self.connection is not None: try: self.connection.rollback() except Database.NotSupportedError: pass def close(self): if self.connection is not None: self.connection.close() self.connection = None def get_server_version(self): if not self.server_version: if not self._valid_connection(): self.cursor() m = server_version_re.match(self.connection.get_server_info()) if not m: raise Exception('Unable to determine MySQL version from version string %r' % self.connection.get_server_info()) self.server_version = tuple([int(x) for x in m.groups()]) return self.server_version supports_constraints = True def quote_name(name): if name.startswith("`") and name.endswith("`"): return name # Quoting once is enough. return "`%s`" % name dictfetchone = util.dictfetchone dictfetchmany = util.dictfetchmany dictfetchall = util.dictfetchall def get_last_insert_id(cursor, table_name, pk_name): return cursor.lastrowid def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), table_name) def get_date_trunc_sql(lookup_type, field_name): # lookup_type is 'year', 'month', 'day' fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields.index(lookup_type) + 1 except ValueError: sql = field_name else: format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) return sql def get_limit_offset_sql(limit, offset=None): sql = "LIMIT " if offset and offset != 0: sql += "%s," % offset return sql + str(limit) def get_random_function_sql(): return "RAND()" def get_deferrable_sql(): return "" def get_fulltext_search_sql(field_name): return 'MATCH (%s) AGAINST (%%s IN BOOLEAN MODE)' % field_name def get_drop_foreignkey_sql(): return "DROP FOREIGN KEY" def get_pk_default_value(): return "DEFAULT" def get_sql_flush(style, tables, sequences): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ # NB: The generated SQL below is specific to MySQL # 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements # to clear all tables of all data if tables: sql = ['SET FOREIGN_KEY_CHECKS = 0;'] + \ ['%s %s;' % \ (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)) ) for table in tables] + \ ['SET FOREIGN_KEY_CHECKS = 1;'] # 'ALTER TABLE table AUTO_INCREMENT = 1;'... style SQL statements # to reset sequence indices sql.extend(["%s %s %s %s %s;" % \ (style.SQL_KEYWORD('ALTER'), style.SQL_KEYWORD('TABLE'), style.SQL_TABLE(quote_name(sequence['table'])), style.SQL_KEYWORD('AUTO_INCREMENT'), style.SQL_FIELD('= 1'), ) for sequence in sequences]) return sql else: return [] OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': 'LIKE %s', 'contains': 'LIKE BINARY %s', 'icontains': 'LIKE %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE BINARY %s', 'endswith': 'LIKE BINARY %s', 'istartswith': 'LIKE %s', 'iendswith': 'LIKE %s', }
Python
from django.conf import settings import os def runshell(): args = [''] args += ["--user=%s" % settings.DATABASE_USER] if settings.DATABASE_PASSWORD: args += ["--password=%s" % settings.DATABASE_PASSWORD] if settings.DATABASE_HOST: args += ["--host=%s" % settings.DATABASE_HOST] if settings.DATABASE_PORT: args += ["--port=%s" % settings.DATABASE_PORT] args += [settings.DATABASE_NAME] os.execvp('mysql', args)
Python
DATA_TYPES = { 'AutoField': 'number(38)', 'BooleanField': 'number(1)', 'CharField': 'varchar2(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar2(%(maxlength)s)', 'DateField': 'date', 'DateTimeField': 'date', 'FileField': 'varchar2(100)', 'FilePathField': 'varchar2(100)', 'FloatField': 'number(%(max_digits)s, %(decimal_places)s)', 'ImageField': 'varchar2(100)', 'IntegerField': 'integer', 'IPAddressField': 'char(15)', 'ManyToManyField': None, 'NullBooleanField': 'integer', 'OneToOneField': 'integer', 'PhoneNumberField': 'varchar(20)', 'PositiveIntegerField': 'integer', 'PositiveSmallIntegerField': 'smallint', 'SlugField': 'varchar(50)', 'SmallIntegerField': 'smallint', 'TextField': 'long', 'TimeField': 'timestamp', 'USStateField': 'varchar(2)', }
Python
import re foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)") def get_table_list(cursor): "Returns a list of table names in the current database." cursor.execute("SELECT TABLE_NAME FROM USER_TABLES") return [row[0] for row in cursor.fetchall()] def get_table_description(cursor, table_name): return table_name def _name_to_index(cursor, table_name): """ Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based. """ return dict([(d[0], i) for i, d in enumerate(get_table_description(cursor, table_name))]) def get_relations(cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ raise NotImplementedError def get_indexes(cursor, table_name): """ Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {'primary_key': boolean representing whether it's the primary key, 'unique': boolean representing whether it's a unique index} """ raise NotImplementedError # Maps type codes to Django Field types. DATA_TYPES_REVERSE = { 16: 'BooleanField', 21: 'SmallIntegerField', 23: 'IntegerField', 25: 'TextField', 869: 'IPAddressField', 1043: 'CharField', 1082: 'DateField', 1083: 'TimeField', 1114: 'DateTimeField', 1184: 'DateTimeField', 1266: 'TimeField', 1700: 'FloatField', }
Python
""" Oracle database backend for Django. Requires cx_Oracle: http://www.python.net/crew/atuining/cx_Oracle/ """ from django.db.backends import util try: import cx_Oracle as Database except ImportError, e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "Error loading cx_Oracle module: %s" % e DatabaseError = Database.Error try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] self.options = kwargs def _valid_connection(self): return self.connection is not None def cursor(self): from django.conf import settings if not self._valid_connection(): if len(settings.DATABASE_HOST.strip()) == 0: settings.DATABASE_HOST = 'localhost' if len(settings.DATABASE_PORT.strip()) != 0: dsn = Database.makedsn(settings.DATABASE_HOST, int(settings.DATABASE_PORT), settings.DATABASE_NAME) self.connection = Database.connect(settings.DATABASE_USER, settings.DATABASE_PASSWORD, dsn, **self.options) else: conn_string = "%s/%s@%s" % (settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME) self.connection = Database.connect(conn_string, **self.options) return FormatStylePlaceholderCursor(self.connection) def _commit(self): if self.connection is not None: self.connection.commit() def _rollback(self): if self.connection is not None: try: self.connection.rollback() except Database.NotSupportedError: pass def close(self): if self.connection is not None: self.connection.close() self.connection = None supports_constraints = True class FormatStylePlaceholderCursor(Database.Cursor): """ Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var" style. This fixes it -- but note that if you want to use a literal "%s" in a query, you'll need to use "%%s". """ def execute(self, query, params=None): if params is None: params = [] query = self.convert_arguments(query, len(params)) return Database.Cursor.execute(self, query, params) def executemany(self, query, params=None): if params is None: params = [] query = self.convert_arguments(query, len(params[0])) return Database.Cursor.executemany(self, query, params) def convert_arguments(self, query, num_params): # replace occurances of "%s" with ":arg" - Oracle requires colons for parameter placeholders. args = [':arg' for i in range(num_params)] return query % tuple(args) def quote_name(name): return name dictfetchone = util.dictfetchone dictfetchmany = util.dictfetchmany dictfetchall = util.dictfetchall def get_last_insert_id(cursor, table_name, pk_name): query = "SELECT %s_sq.currval from dual" % table_name cursor.execute(query) return cursor.fetchone()[0] def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' # http://www.psoug.org/reference/date_func.html return "EXTRACT(%s FROM %s)" % (lookup_type, table_name) def get_date_trunc_sql(lookup_type, field_name): return "EXTRACT(%s FROM TRUNC(%s))" % (lookup_type, field_name) def get_limit_offset_sql(limit, offset=None): # Limits and offset are too complicated to be handled here. # Instead, they are handled in django/db/query.py. pass def get_random_function_sql(): return "DBMS_RANDOM.RANDOM" def get_deferrable_sql(): return " DEFERRABLE INITIALLY DEFERRED" def get_fulltext_search_sql(field_name): raise NotImplementedError def get_drop_foreignkey_sql(): return "DROP FOREIGN KEY" def get_pk_default_value(): return "DEFAULT" def get_sql_flush(style, tables, sequences): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ # Return a list of 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements # TODO - SQL not actually tested against Oracle yet! # TODO - autoincrement indices reset required? See other get_sql_flush() implementations sql = ['%s %s;' % \ (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)) ) for table in tables] OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': 'LIKE %s', 'contains': 'LIKE %s', 'icontains': 'LIKE %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE %s', 'endswith': 'LIKE %s', 'istartswith': 'LIKE %s', 'iendswith': 'LIKE %s', }
Python
from django.conf import settings import os def runshell(): args = '' args += settings.DATABASE_USER if settings.DATABASE_PASSWORD: args += "/%s" % settings.DATABASE_PASSWORD args += "@%s" % settings.DATABASE_NAME os.execvp('sqlplus', args)
Python
DATA_TYPES = { 'AutoField': 'int IDENTITY (1, 1)', 'BooleanField': 'bit', 'CharField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'DateField': 'smalldatetime', 'DateTimeField': 'smalldatetime', 'FileField': 'varchar(100)', 'FilePathField': 'varchar(100)', 'FloatField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'ImageField': 'varchar(100)', 'IntegerField': 'int', 'IPAddressField': 'char(15)', 'ManyToManyField': None, 'NullBooleanField': 'bit', 'OneToOneField': 'int', 'PhoneNumberField': 'varchar(20)', 'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)', 'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)', 'SlugField': 'varchar(%(maxlength)s)', 'SmallIntegerField': 'smallint', 'TextField': 'text', 'TimeField': 'time', 'USStateField': 'varchar(2)', }
Python
def get_table_list(cursor): raise NotImplementedError def get_table_description(cursor, table_name): raise NotImplementedError def get_relations(cursor, table_name): raise NotImplementedError def get_indexes(cursor, table_name): raise NotImplementedError DATA_TYPES_REVERSE = {}
Python
""" ADO MSSQL database backend for Django. Requires adodbapi 2.0.1: http://adodbapi.sourceforge.net/ """ from django.db.backends import util try: import adodbapi as Database except ImportError, e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "Error loading adodbapi module: %s" % e import datetime try: import mx except ImportError: mx = None DatabaseError = Database.DatabaseError # We need to use a special Cursor class because adodbapi expects question-mark # param style, but Django expects "%s". This cursor converts question marks to # format-string style. class Cursor(Database.Cursor): def executeHelper(self, operation, isStoredProcedureCall, parameters=None): if parameters is not None and "%s" in operation: operation = operation.replace("%s", "?") Database.Cursor.executeHelper(self, operation, isStoredProcedureCall, parameters) class Connection(Database.Connection): def cursor(self): return Cursor(self) Database.Connection = Connection origCVtoP = Database.convertVariantToPython def variantToPython(variant, adType): if type(variant) == bool and adType == 11: return variant # bool not 1/0 res = origCVtoP(variant, adType) if mx is not None and type(res) == mx.DateTime.mxDateTime.DateTimeType: # Convert ms.DateTime objects to Python datetime.datetime objects. tv = list(res.tuple()[:7]) tv[-2] = int(tv[-2]) return datetime.datetime(*tuple(tv)) if type(res) == float and str(res)[-2:] == ".0": return int(res) # If float but int, then int. return res Database.convertVariantToPython = variantToPython try: # Only exists in Python 2.4+ from threading import local except ImportError: # Import copy of _thread_local.py from Python 2.4 from django.utils._threading_local import local class DatabaseWrapper(local): def __init__(self, **kwargs): self.connection = None self.queries = [] def cursor(self): from django.conf import settings if self.connection is None: if settings.DATABASE_NAME == '' or settings.DATABASE_USER == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured, "You need to specify both DATABASE_NAME and DATABASE_USER in your Django settings file." if not settings.DATABASE_HOST: settings.DATABASE_HOST = "127.0.0.1" # TODO: Handle DATABASE_PORT. conn_string = "PROVIDER=SQLOLEDB;DATA SOURCE=%s;UID=%s;PWD=%s;DATABASE=%s" % (settings.DATABASE_HOST, settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME) self.connection = Database.connect(conn_string) cursor = self.connection.cursor() if settings.DEBUG: return util.CursorDebugWrapper(cursor, self) return cursor def _commit(self): if self.connection is not None: return self.connection.commit() def _rollback(self): if self.connection is not None: return self.connection.rollback() def close(self): if self.connection is not None: self.connection.close() self.connection = None supports_constraints = True def quote_name(name): if name.startswith('[') and name.endswith(']'): return name # Quoting once is enough. return '[%s]' % name dictfetchone = util.dictfetchone dictfetchmany = util.dictfetchmany dictfetchall = util.dictfetchall def get_last_insert_id(cursor, table_name, pk_name): cursor.execute("SELECT %s FROM %s WHERE %s = @@IDENTITY" % (pk_name, table_name, pk_name)) return cursor.fetchone()[0] def get_date_extract_sql(lookup_type, table_name): # lookup_type is 'year', 'month', 'day' return "DATEPART(%s, %s)" % (lookup_type, table_name) def get_date_trunc_sql(lookup_type, field_name): # lookup_type is 'year', 'month', 'day' if lookup_type=='year': return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/01/01')" % field_name if lookup_type=='month': return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/' + Convert(varchar, DATEPART(month, %s)) + '/01')" % (field_name, field_name) if lookup_type=='day': return "Convert(datetime, Convert(varchar(12), %s))" % field_name def get_limit_offset_sql(limit, offset=None): # TODO: This is a guess. Make sure this is correct. sql = "LIMIT %s" % limit if offset and offset != 0: sql += " OFFSET %s" % offset return sql def get_random_function_sql(): return "RAND()" def get_deferrable_sql(): return " DEFERRABLE INITIALLY DEFERRED" def get_fulltext_search_sql(field_name): raise NotImplementedError def get_drop_foreignkey_sql(): return "DROP CONSTRAINT" def get_pk_default_value(): return "DEFAULT" def get_sql_flush(sql_styler, full_table_list): """Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty 'initial' state """ # Return a list of 'TRUNCATE x;', 'TRUNCATE y;', 'TRUNCATE z;'... style SQL statements # TODO - SQL not actually tested against ADO MSSQL yet! # TODO - autoincrement indices reset required? See other get_sql_flush() implementations sql_list = ['%s %s;' % \ (sql_styler.SQL_KEYWORD('TRUNCATE'), sql_styler.SQL_FIELD(quote_name(table)) ) for table in full_table_list] OPERATOR_MAPPING = { 'exact': '= %s', 'iexact': 'LIKE %s', 'contains': 'LIKE %s', 'icontains': 'LIKE %s', 'gt': '> %s', 'gte': '>= %s', 'lt': '< %s', 'lte': '<= %s', 'startswith': 'LIKE %s', 'endswith': 'LIKE %s', 'istartswith': 'LIKE %s', 'iendswith': 'LIKE %s', }
Python
def runshell(): raise NotImplementedError
Python
class BoundRelatedObject(object): def __init__(self, related_object, field_mapping, original): self.relation = related_object self.field_mappings = field_mapping[related_object.name] def template_name(self): raise NotImplementedError def __repr__(self): return repr(self.__dict__) class RelatedObject(object): def __init__(self, parent_model, model, field): self.parent_model = parent_model self.model = model self.opts = model._meta self.field = field self.edit_inline = field.rel.edit_inline self.name = '%s:%s' % (self.opts.app_label, self.opts.module_name) self.var_name = self.opts.object_name.lower() def flatten_data(self, follow, obj=None): new_data = {} rel_instances = self.get_list(obj) for i, rel_instance in enumerate(rel_instances): instance_data = {} for f in self.opts.fields + self.opts.many_to_many: # TODO: Fix for recursive manipulators. fol = follow.get(f.name, None) if fol: field_data = f.flatten_data(fol, rel_instance) for name, value in field_data.items(): instance_data['%s.%d.%s' % (self.var_name, i, name)] = value new_data.update(instance_data) return new_data def extract_data(self, data): """ Pull out the data meant for inline objects of this class, i.e. anything starting with our module name. """ return data # TODO def get_list(self, parent_instance=None): "Get the list of this type of object from an instance of the parent class." if parent_instance is not None: attr = getattr(parent_instance, self.get_accessor_name()) if self.field.rel.multiple: # For many-to-many relationships, return a list of objects # corresponding to the xxx_num_in_admin options of the field objects = list(attr.all()) count = len(objects) + self.field.rel.num_extra_on_change if self.field.rel.min_num_in_admin: count = max(count, self.field.rel.min_num_in_admin) if self.field.rel.max_num_in_admin: count = min(count, self.field.rel.max_num_in_admin) change = count - len(objects) if change > 0: return objects + [None] * change if change < 0: return objects[:change] else: # Just right return objects else: # A one-to-one relationship, so just return the single related # object return [attr] else: if self.field.rel.min_num_in_admin: return [None] * max(self.field.rel.num_in_admin, self.field.rel.min_num_in_admin) else: return [None] * self.field.rel.num_in_admin def get_db_prep_lookup(self, lookup_type, value): # Defer to the actual field definition for db prep return self.field.get_db_prep_lookup(lookup_type, value) def editable_fields(self): "Get the fields in this class that should be edited inline." return [f for f in self.opts.fields + self.opts.many_to_many if f.editable and f != self.field] def get_follow(self, override=None): if isinstance(override, bool): if override: over = {} else: return None else: if override: over = override.copy() elif self.edit_inline: over = {} else: return None over[self.field.name] = False return self.opts.get_follow(over) def get_manipulator_fields(self, opts, manipulator, change, follow): if self.field.rel.multiple: if change: attr = getattr(manipulator.original_object, self.get_accessor_name()) count = attr.count() count += self.field.rel.num_extra_on_change else: count = self.field.rel.num_in_admin if self.field.rel.min_num_in_admin: count = max(count, self.field.rel.min_num_in_admin) if self.field.rel.max_num_in_admin: count = min(count, self.field.rel.max_num_in_admin) else: count = 1 fields = [] for i in range(count): for f in self.opts.fields + self.opts.many_to_many: if follow.get(f.name, False): prefix = '%s.%d.' % (self.var_name, i) fields.extend(f.get_manipulator_fields(self.opts, manipulator, change, name_prefix=prefix, rel=True)) return fields def __repr__(self): return "<RelatedObject: %s related to %s>" % (self.name, self.field.name) def bind(self, field_mapping, original, bound_related_object_class=BoundRelatedObject): return bound_related_object_class(self, field_mapping, original) def get_accessor_name(self): # This method encapsulates the logic that decides what name to give an # accessor descriptor that retrieves related many-to-one or # many-to-many objects. It uses the lower-cased object_name + "_set", # but this can be overridden with the "related_name" option. if self.field.rel.multiple: # If this is a symmetrical m2m relation on self, there is no reverse accessor. if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model: return None return self.field.rel.related_name or (self.opts.object_name.lower() + '_set') else: return self.field.rel.related_name or (self.opts.object_name.lower())
Python
class_prepared = object() pre_init= object() post_init = object() pre_save = object() post_save = object() pre_delete = object() post_delete = object() post_syncdb = object()
Python
from django.db import backend, connection, transaction from django.db.models.fields import DateField, FieldDoesNotExist from django.db.models.fields.generic import GenericRelation from django.db.models import signals from django.dispatch import dispatcher from django.utils.datastructures import SortedDict import operator import re # For Python 2.3 if not hasattr(__builtins__, 'set'): from sets import Set as set # The string constant used to separate query parts LOOKUP_SEPARATOR = '__' # The list of valid query types QUERY_TERMS = ( 'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in', 'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year', 'month', 'day', 'isnull', 'search', ) # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERATOR_CHUNK_SIZE = 100 class EmptyResultSet(Exception): pass #################### # HELPER FUNCTIONS # #################### # Django currently supports two forms of ordering. # Form 1 (deprecated) example: # order_by=(('pub_date', 'DESC'), ('headline', 'ASC'), (None, 'RANDOM')) # Form 2 (new-style) example: # order_by=('-pub_date', 'headline', '?') # Form 1 is deprecated and will no longer be supported for Django's first # official release. The following code converts from Form 1 to Form 2. LEGACY_ORDERING_MAPPING = {'ASC': '_', 'DESC': '-_', 'RANDOM': '?'} def handle_legacy_orderlist(order_list): if not order_list or isinstance(order_list[0], basestring): return order_list else: import warnings new_order_list = [LEGACY_ORDERING_MAPPING[j.upper()].replace('_', str(i)) for i, j in order_list] warnings.warn("%r ordering syntax is deprecated. Use %r instead." % (order_list, new_order_list), DeprecationWarning) return new_order_list def orderfield2column(f, opts): try: return opts.get_field(f, False).column except FieldDoesNotExist: return f def orderlist2sql(order_list, opts, prefix=''): if prefix.endswith('.'): prefix = backend.quote_name(prefix[:-1]) + '.' output = [] for f in handle_legacy_orderlist(order_list): if f.startswith('-'): output.append('%s%s DESC' % (prefix, backend.quote_name(orderfield2column(f[1:], opts)))) elif f == '?': output.append(backend.get_random_function_sql()) else: output.append('%s%s ASC' % (prefix, backend.quote_name(orderfield2column(f, opts)))) return ', '.join(output) def quote_only_if_word(word): if re.search('\W', word): # Don't quote if there are spaces or non-word chars. return word else: return backend.quote_name(word) class QuerySet(object): "Represents a lazy database lookup for a set of objects" def __init__(self, model=None): self.model = model self._filters = Q() self._order_by = None # Ordering, e.g. ('date', '-name'). If None, use model's ordering. self._select_related = False # Whether to fill cache for related objects. self._max_related_depth = 0 # Maximum "depth" for select_related self._distinct = False # Whether the query should use SELECT DISTINCT. self._select = {} # Dictionary of attname -> SQL. self._where = [] # List of extra WHERE clauses to use. self._params = [] # List of params to use for extra WHERE clauses. self._tables = [] # List of extra tables to use. self._offset = None # OFFSET clause. self._limit = None # LIMIT clause. self._result_cache = None ######################## # PYTHON MAGIC METHODS # ######################## def __repr__(self): return repr(self._get_data()) def __len__(self): return len(self._get_data()) def __iter__(self): return iter(self._get_data()) def __getitem__(self, k): "Retrieve an item or slice from the set of results." if not isinstance(k, (slice, int)): raise TypeError assert (not isinstance(k, slice) and (k >= 0)) \ or (isinstance(k, slice) and (k.start is None or k.start >= 0) and (k.stop is None or k.stop >= 0)), \ "Negative indexing is not supported." if self._result_cache is None: if isinstance(k, slice): # Offset: if self._offset is None: offset = k.start elif k.start is None: offset = self._offset else: offset = self._offset + k.start # Now adjust offset to the bounds of any existing limit: if self._limit is not None and k.start is not None: limit = self._limit - k.start else: limit = self._limit # Limit: if k.stop is not None and k.start is not None: if limit is None: limit = k.stop - k.start else: limit = min((k.stop - k.start), limit) else: if limit is None: limit = k.stop else: if k.stop is not None: limit = min(k.stop, limit) if k.step is None: return self._clone(_offset=offset, _limit=limit) else: return list(self._clone(_offset=offset, _limit=limit))[::k.step] else: try: return list(self._clone(_offset=k, _limit=1))[0] except self.model.DoesNotExist, e: raise IndexError, e.args else: return self._result_cache[k] def __and__(self, other): combined = self._combine(other) combined._filters = self._filters & other._filters return combined def __or__(self, other): combined = self._combine(other) combined._filters = self._filters | other._filters return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def iterator(self): "Performs the SELECT database lookup of this QuerySet." try: select, sql, params = self._get_sql_clause() except EmptyResultSet: raise StopIteration # self._select is a dictionary, and dictionaries' key order is # undefined, so we convert it to a list of tuples. extra_select = self._select.items() cursor = connection.cursor() cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) fill_cache = self._select_related index_end = len(self.model._meta.fields) while 1: rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE) if not rows: raise StopIteration for row in rows: if fill_cache: obj, index_end = get_cached_row(klass=self.model, row=row, index_start=0, max_depth=self._max_related_depth) else: obj = self.model(*row[:index_end]) for i, k in enumerate(extra_select): setattr(obj, k[0], row[index_end+i]) yield obj def count(self): """ Performs a SELECT COUNT() and returns the number of records as an integer. If the queryset is already cached (i.e. self._result_cache is set) this simply returns the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None: return len(self._result_cache) counter = self._clone() counter._order_by = () counter._select_related = False offset = counter._offset limit = counter._limit counter._offset = None counter._limit = None try: select, sql, params = counter._get_sql_clause() except EmptyResultSet: return 0 cursor = connection.cursor() if self._distinct: id_col = "%s.%s" % (backend.quote_name(self.model._meta.db_table), backend.quote_name(self.model._meta.pk.column)) cursor.execute("SELECT COUNT(DISTINCT(%s))" % id_col + sql, params) else: cursor.execute("SELECT COUNT(*)" + sql, params) count = cursor.fetchone()[0] # Apply any offset and limit constraints manually, since using LIMIT or # OFFSET in SQL doesn't change the output of COUNT. if offset: count = max(0, count - offset) if limit: count = min(limit, count) return count def get(self, *args, **kwargs): "Performs the SELECT and returns a single object matching the given keyword arguments." clone = self.filter(*args, **kwargs) # clean up SQL by removing unneeded ORDER BY if not clone._order_by: clone._order_by = () obj_list = list(clone) if len(obj_list) < 1: raise self.model.DoesNotExist, "%s matching query does not exist." % self.model._meta.object_name assert len(obj_list) == 1, "get() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.model._meta.object_name, len(obj_list), kwargs) return obj_list[0] def create(self, **kwargs): """ Create a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) obj.save() return obj def get_or_create(self, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ assert len(kwargs), 'get_or_create() must be passed at least one keyword argument' defaults = kwargs.pop('defaults', {}) try: return self.get(**kwargs), False except self.model.DoesNotExist: params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) params.update(defaults) obj = self.model(**params) obj.save() return obj, True def latest(self, field_name=None): """ Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name. """ latest_by = field_name or self.model._meta.get_latest_by assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model" assert self._limit is None and self._offset is None, \ "Cannot change a query once a slice has been taken." return self._clone(_limit=1, _order_by=('-'+latest_by,)).get() def in_bulk(self, id_list): """ Returns a dictionary mapping each of the given IDs to the object with that ID. """ assert self._limit is None and self._offset is None, \ "Cannot use 'limit' or 'offset' with in_bulk" assert isinstance(id_list, (tuple, list)), "in_bulk() must be provided with a list of IDs." id_list = list(id_list) if id_list == []: return {} qs = self._clone() qs._where.append("%s.%s IN (%s)" % (backend.quote_name(self.model._meta.db_table), backend.quote_name(self.model._meta.pk.column), ",".join(['%s'] * len(id_list)))) qs._params.extend(id_list) return dict([(obj._get_pk_val(), obj) for obj in qs.iterator()]) def delete(self): """ Deletes the records in the current QuerySet. """ assert self._limit is None and self._offset is None, \ "Cannot use 'limit' or 'offset' with delete." del_query = self._clone() # disable non-supported fields del_query._select_related = False del_query._order_by = [] # Delete objects in chunks to prevent an the list of # related objects from becoming too long more_objects = True while more_objects: # Collect all the objects to be deleted in this chunk, and all the objects # that are related to the objects that are to be deleted seen_objs = SortedDict() more_objects = False for object in del_query[0:GET_ITERATOR_CHUNK_SIZE]: more_objects = True object._collect_sub_objects(seen_objs) # If one or more objects were found, delete them. # Otherwise, stop looping. if more_objects: delete_objects(seen_objs) # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None delete.alters_data = True ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def values(self, *fields): return self._clone(klass=ValuesQuerySet, _fields=fields) def dates(self, field_name, kind, order='ASC'): """ Returns a list of datetime objects representing all available dates for the given field_name, scoped to 'kind'. """ assert kind in ("month", "year", "day"), "'kind' must be one of 'year', 'month' or 'day'." assert order in ('ASC', 'DESC'), "'order' must be either 'ASC' or 'DESC'." # Let the FieldDoesNotExist exception propagate. field = self.model._meta.get_field(field_name, many_to_many=False) assert isinstance(field, DateField), "%r isn't a DateField." % field_name return self._clone(klass=DateQuerySet, _field=field, _kind=kind, _order=order) ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def filter(self, *args, **kwargs): "Returns a new QuerySet instance with the args ANDed to the existing set." return self._filter_or_exclude(None, *args, **kwargs) def exclude(self, *args, **kwargs): "Returns a new QuerySet instance with NOT (args) ANDed to the existing set." return self._filter_or_exclude(QNot, *args, **kwargs) def _filter_or_exclude(self, mapper, *args, **kwargs): # mapper is a callable used to transform Q objects, # or None for identity transform if mapper is None: mapper = lambda x: x if len(args) > 0 or len(kwargs) > 0: assert self._limit is None and self._offset is None, \ "Cannot filter a query once a slice has been taken." clone = self._clone() if len(kwargs) > 0: clone._filters = clone._filters & mapper(Q(**kwargs)) if len(args) > 0: clone._filters = clone._filters & reduce(operator.and_, map(mapper, args)) return clone def complex_filter(self, filter_obj): """Returns a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object (has 'get_sql' method) or a dictionary of keyword lookup arguments.""" # This exists to support framework features such as 'limit_choices_to', # and usually it will be more natural to use other methods. if hasattr(filter_obj, 'get_sql'): return self._filter_or_exclude(None, filter_obj) else: return self._filter_or_exclude(None, **filter_obj) def select_related(self, true_or_false=True, depth=0): "Returns a new QuerySet instance with '_select_related' modified." return self._clone(_select_related=true_or_false, _max_related_depth=depth) def order_by(self, *field_names): "Returns a new QuerySet instance with the ordering changed." assert self._limit is None and self._offset is None, \ "Cannot reorder a query once a slice has been taken." return self._clone(_order_by=field_names) def distinct(self, true_or_false=True): "Returns a new QuerySet instance with '_distinct' modified." return self._clone(_distinct=true_or_false) def extra(self, select=None, where=None, params=None, tables=None): assert self._limit is None and self._offset is None, \ "Cannot change a query once a slice has been taken" clone = self._clone() if select: clone._select.update(select) if where: clone._where.extend(where) if params: clone._params.extend(params) if tables: clone._tables.extend(tables) return clone ################### # PRIVATE METHODS # ################### def _clone(self, klass=None, **kwargs): if klass is None: klass = self.__class__ c = klass() c.model = self.model c._filters = self._filters c._order_by = self._order_by c._select_related = self._select_related c._max_related_depth = self._max_related_depth c._distinct = self._distinct c._select = self._select.copy() c._where = self._where[:] c._params = self._params[:] c._tables = self._tables[:] c._offset = self._offset c._limit = self._limit c.__dict__.update(kwargs) return c def _combine(self, other): assert self._limit is None and self._offset is None \ and other._limit is None and other._offset is None, \ "Cannot combine queries once a slice has been taken." assert self._distinct == other._distinct, \ "Cannot combine a unique query with a non-unique query" # use 'other's order by # (so that A.filter(args1) & A.filter(args2) does the same as # A.filter(args1).filter(args2) combined = other._clone() if self._select: combined._select.update(self._select) if self._where: combined._where.extend(self._where) if self._params: combined._params.extend(self._params) if self._tables: combined._tables.extend(self._tables) # If 'self' is ordered and 'other' isn't, propagate 'self's ordering if (self._order_by is not None and len(self._order_by) > 0) and \ (combined._order_by is None or len(combined._order_by) == 0): combined._order_by = self._order_by return combined def _get_data(self): if self._result_cache is None: self._result_cache = list(self.iterator()) return self._result_cache def _get_sql_clause(self): opts = self.model._meta # Construct the fundamental parts of the query: SELECT X FROM Y WHERE Z. select = ["%s.%s" % (backend.quote_name(opts.db_table), backend.quote_name(f.column)) for f in opts.fields] tables = [quote_only_if_word(t) for t in self._tables] joins = SortedDict() where = self._where[:] params = self._params[:] # Convert self._filters into SQL. joins2, where2, params2 = self._filters.get_sql(opts) joins.update(joins2) where.extend(where2) params.extend(params2) # Add additional tables and WHERE clauses based on select_related. if self._select_related: fill_table_cache(opts, select, tables, where, old_prefix=opts.db_table, cache_tables_seen=[opts.db_table], max_depth=self._max_related_depth) # Add any additional SELECTs. if self._select: select.extend(['(%s) AS %s' % (quote_only_if_word(s[1]), backend.quote_name(s[0])) for s in self._select.items()]) # Start composing the body of the SQL statement. sql = [" FROM", backend.quote_name(opts.db_table)] # Compose the join dictionary into SQL describing the joins. if joins: sql.append(" ".join(["%s %s AS %s ON %s" % (join_type, table, alias, condition) for (alias, (table, join_type, condition)) in joins.items()])) # Compose the tables clause into SQL. if tables: sql.append(", " + ", ".join(tables)) # Compose the where clause into SQL. if where: sql.append(where and "WHERE " + " AND ".join(where)) # ORDER BY clause order_by = [] if self._order_by is not None: ordering_to_use = self._order_by else: ordering_to_use = opts.ordering for f in handle_legacy_orderlist(ordering_to_use): if f == '?': # Special case. order_by.append(backend.get_random_function_sql()) else: if f.startswith('-'): col_name = f[1:] order = "DESC" else: col_name = f order = "ASC" if "." in col_name: table_prefix, col_name = col_name.split('.', 1) table_prefix = backend.quote_name(table_prefix) + '.' else: # Use the database table as a column prefix if it wasn't given, # and if the requested column isn't a custom SELECT. if "." not in col_name and col_name not in (self._select or ()): table_prefix = backend.quote_name(opts.db_table) + '.' else: table_prefix = '' order_by.append('%s%s %s' % (table_prefix, backend.quote_name(orderfield2column(col_name, opts)), order)) if order_by: sql.append("ORDER BY " + ", ".join(order_by)) # LIMIT and OFFSET clauses if self._limit is not None: sql.append("%s " % backend.get_limit_offset_sql(self._limit, self._offset)) else: assert self._offset is None, "'offset' is not allowed without 'limit'" return select, " ".join(sql), params class ValuesQuerySet(QuerySet): def __init__(self, *args, **kwargs): super(ValuesQuerySet, self).__init__(*args, **kwargs) # select_related and select aren't supported in values(). self._select_related = False self._select = {} def iterator(self): try: select, sql, params = self._get_sql_clause() except EmptyResultSet: raise StopIteration # self._fields is a list of field names to fetch. if self._fields: columns = [self.model._meta.get_field(f, many_to_many=False).column for f in self._fields] field_names = self._fields else: # Default to all fields. columns = [f.column for f in self.model._meta.fields] field_names = [f.attname for f in self.model._meta.fields] select = ['%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(c)) for c in columns] cursor = connection.cursor() cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) while 1: rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE) if not rows: raise StopIteration for row in rows: yield dict(zip(field_names, row)) def _clone(self, klass=None, **kwargs): c = super(ValuesQuerySet, self)._clone(klass, **kwargs) c._fields = self._fields[:] return c class DateQuerySet(QuerySet): def iterator(self): from django.db.backends.util import typecast_timestamp self._order_by = () # Clear this because it'll mess things up otherwise. if self._field.null: self._where.append('%s.%s IS NOT NULL' % \ (backend.quote_name(self.model._meta.db_table), backend.quote_name(self._field.column))) try: select, sql, params = self._get_sql_clause() except EmptyResultSet: raise StopIteration sql = 'SELECT %s %s GROUP BY 1 ORDER BY 1 %s' % \ (backend.get_date_trunc_sql(self._kind, '%s.%s' % (backend.quote_name(self.model._meta.db_table), backend.quote_name(self._field.column))), sql, self._order) cursor = connection.cursor() cursor.execute(sql, params) # We have to manually run typecast_timestamp(str()) on the results, because # MySQL doesn't automatically cast the result of date functions as datetime # objects -- MySQL returns the values as strings, instead. return [typecast_timestamp(str(row[0])) for row in cursor.fetchall()] def _clone(self, klass=None, **kwargs): c = super(DateQuerySet, self)._clone(klass, **kwargs) c._field = self._field c._kind = self._kind c._order = self._order return c class EmptyQuerySet(QuerySet): def __init__(self, model=None): super(EmptyQuerySet, self).__init__(model) self._result_cache = [] def count(self): return 0 def delete(self): pass def _clone(self, klass=None, **kwargs): c = super(EmptyQuerySet, self)._clone(klass, **kwargs) c._result_cache = [] return c def _get_sql_clause(self): raise EmptyResultSet class QOperator(object): "Base class for QAnd and QOr" def __init__(self, *args): self.args = args def get_sql(self, opts): joins, where, params = SortedDict(), [], [] for val in self.args: try: joins2, where2, params2 = val.get_sql(opts) joins.update(joins2) where.extend(where2) params.extend(params2) except EmptyResultSet: if not isinstance(self, QOr): raise EmptyResultSet if where: return joins, ['(%s)' % self.operator.join(where)], params return joins, [], params class QAnd(QOperator): "Encapsulates a combined query that uses 'AND'." operator = ' AND ' def __or__(self, other): return QOr(self, other) def __and__(self, other): if isinstance(other, QAnd): return QAnd(*(self.args+other.args)) elif isinstance(other, (Q, QOr)): return QAnd(*(self.args+(other,))) else: raise TypeError, other class QOr(QOperator): "Encapsulates a combined query that uses 'OR'." operator = ' OR ' def __and__(self, other): return QAnd(self, other) def __or__(self, other): if isinstance(other, QOr): return QOr(*(self.args+other.args)) elif isinstance(other, (Q, QAnd)): return QOr(*(self.args+(other,))) else: raise TypeError, other class Q(object): "Encapsulates queries as objects that can be combined logically." def __init__(self, **kwargs): self.kwargs = kwargs def __and__(self, other): return QAnd(self, other) def __or__(self, other): return QOr(self, other) def get_sql(self, opts): return parse_lookup(self.kwargs.items(), opts) class QNot(Q): "Encapsulates NOT (...) queries as objects" def __init__(self, q): "Creates a negation of the q object passed in." self.q = q def get_sql(self, opts): try: joins, where, params = self.q.get_sql(opts) where2 = ['(NOT (%s))' % " AND ".join(where)] except EmptyResultSet: return SortedDict(), [], [] return joins, where2, params def get_where_clause(lookup_type, table_prefix, field_name, value): if table_prefix.endswith('.'): table_prefix = backend.quote_name(table_prefix[:-1])+'.' field_name = backend.quote_name(field_name) try: return '%s%s %s' % (table_prefix, field_name, (backend.OPERATOR_MAPPING[lookup_type] % '%s')) except KeyError: pass if lookup_type == 'in': in_string = ','.join(['%s' for id in value]) if in_string: return '%s%s IN (%s)' % (table_prefix, field_name, in_string) else: raise EmptyResultSet elif lookup_type in ('range', 'year'): return '%s%s BETWEEN %%s AND %%s' % (table_prefix, field_name) elif lookup_type in ('month', 'day'): return "%s = %%s" % backend.get_date_extract_sql(lookup_type, table_prefix + field_name) elif lookup_type == 'isnull': return "%s%s IS %sNULL" % (table_prefix, field_name, (not value and 'NOT ' or '')) elif lookup_type == 'search': return backend.get_fulltext_search_sql(table_prefix + field_name) raise TypeError, "Got invalid lookup_type: %s" % repr(lookup_type) def get_cached_row(klass, row, index_start, max_depth=0, cur_depth=0): """Helper function that recursively returns an object with cache filled""" # If we've got a max_depth set and we've exceeded that depth, bail now. if max_depth and cur_depth > max_depth: return None index_end = index_start + len(klass._meta.fields) obj = klass(*row[index_start:index_end]) for f in klass._meta.fields: if f.rel and not f.null: cached_row = get_cached_row(f.rel.to, row, index_end, max_depth, cur_depth+1) if cached_row: rel_obj, index_end = cached_row setattr(obj, f.get_cache_name(), rel_obj) return obj, index_end def fill_table_cache(opts, select, tables, where, old_prefix, cache_tables_seen, max_depth=0, cur_depth=0): """ Helper function that recursively populates the select, tables and where (in place) for select_related queries. """ # If we've got a max_depth set and we've exceeded that depth, bail now. if max_depth and cur_depth > max_depth: return None qn = backend.quote_name for f in opts.fields: if f.rel and not f.null: db_table = f.rel.to._meta.db_table if db_table not in cache_tables_seen: tables.append(qn(db_table)) else: # The table was already seen, so give it a table alias. new_prefix = '%s%s' % (db_table, len(cache_tables_seen)) tables.append('%s %s' % (qn(db_table), qn(new_prefix))) db_table = new_prefix cache_tables_seen.append(db_table) where.append('%s.%s = %s.%s' % \ (qn(old_prefix), qn(f.column), qn(db_table), qn(f.rel.get_related_field().column))) select.extend(['%s.%s' % (qn(db_table), qn(f2.column)) for f2 in f.rel.to._meta.fields]) fill_table_cache(f.rel.to._meta, select, tables, where, db_table, cache_tables_seen, max_depth, cur_depth+1) def parse_lookup(kwarg_items, opts): # Helper function that handles converting API kwargs # (e.g. "name__exact": "tom") to SQL. # Returns a tuple of (joins, where, params). # 'joins' is a sorted dictionary describing the tables that must be joined # to complete the query. The dictionary is sorted because creation order # is significant; it is a dictionary to ensure uniqueness of alias names. # # Each key-value pair follows the form # alias: (table, join_type, condition) # where # alias is the AS alias for the joined table # table is the actual table name to be joined # join_type is the type of join (INNER JOIN, LEFT OUTER JOIN, etc) # condition is the where-like statement over which narrows the join. # alias will be derived from the lookup list name. # # At present, this method only every returns INNER JOINs; the option is # there for others to implement custom Q()s, etc that return other join # types. joins, where, params = SortedDict(), [], [] for kwarg, value in kwarg_items: path = kwarg.split(LOOKUP_SEPARATOR) # Extract the last elements of the kwarg. # The very-last is the lookup_type (equals, like, etc). # The second-last is the table column on which the lookup_type is # to be performed. If this name is 'pk', it will be substituted with # the name of the primary key. # If there is only one part, or the last part is not a query # term, assume that the query is an __exact lookup_type = path.pop() if lookup_type == 'pk': lookup_type = 'exact' path.append(None) elif len(path) == 0 or lookup_type not in QUERY_TERMS: path.append(lookup_type) lookup_type = 'exact' if len(path) < 1: raise TypeError, "Cannot parse keyword query %r" % kwarg if value is None: # Interpret '__exact=None' as the sql '= NULL'; otherwise, reject # all uses of None as a query value. if lookup_type != 'exact': raise ValueError, "Cannot use None as a query value" joins2, where2, params2 = lookup_inner(path, lookup_type, value, opts, opts.db_table, None) joins.update(joins2) where.extend(where2) params.extend(params2) return joins, where, params class FieldFound(Exception): "Exception used to short circuit field-finding operations." pass def find_field(name, field_list, related_query): """ Finds a field with a specific name in a list of field instances. Returns None if there are no matches, or several matches. """ if related_query: matches = [f for f in field_list if f.field.related_query_name() == name] else: matches = [f for f in field_list if f.name == name] if len(matches) != 1: return None return matches[0] def lookup_inner(path, lookup_type, value, opts, table, column): qn = backend.quote_name joins, where, params = SortedDict(), [], [] current_opts = opts current_table = table current_column = column intermediate_table = None join_required = False name = path.pop(0) # Has the primary key been requested? If so, expand it out # to be the name of the current class' primary key if name is None or name == 'pk': name = current_opts.pk.name # Try to find the name in the fields associated with the current class try: # Does the name belong to a defined many-to-many field? field = find_field(name, current_opts.many_to_many, False) if field: new_table = current_table + '__' + name new_opts = field.rel.to._meta new_column = new_opts.pk.column # Need to create an intermediate table join over the m2m table # This process hijacks current_table/column to point to the # intermediate table. current_table = "m2m_" + new_table intermediate_table = field.m2m_db_table() join_column = field.m2m_reverse_name() intermediate_column = field.m2m_column_name() raise FieldFound # Does the name belong to a reverse defined many-to-many field? field = find_field(name, current_opts.get_all_related_many_to_many_objects(), True) if field: new_table = current_table + '__' + name new_opts = field.opts new_column = new_opts.pk.column # Need to create an intermediate table join over the m2m table. # This process hijacks current_table/column to point to the # intermediate table. current_table = "m2m_" + new_table intermediate_table = field.field.m2m_db_table() join_column = field.field.m2m_column_name() intermediate_column = field.field.m2m_reverse_name() raise FieldFound # Does the name belong to a one-to-many field? field = find_field(name, current_opts.get_all_related_objects(), True) if field: new_table = table + '__' + name new_opts = field.opts new_column = field.field.column join_column = opts.pk.column # 1-N fields MUST be joined, regardless of any other conditions. join_required = True raise FieldFound # Does the name belong to a one-to-one, many-to-one, or regular field? field = find_field(name, current_opts.fields, False) if field: if field.rel: # One-to-One/Many-to-one field new_table = current_table + '__' + name new_opts = field.rel.to._meta new_column = new_opts.pk.column join_column = field.column raise FieldFound elif path: # For regular fields, if there are still items on the path, # an error has been made. We munge "name" so that the error # properly identifies the cause of the problem. name += LOOKUP_SEPARATOR + path[0] else: raise FieldFound except FieldFound: # Match found, loop has been shortcut. pass else: # No match found. raise TypeError, "Cannot resolve keyword '%s' into field" % name # Check whether an intermediate join is required between current_table # and new_table. if intermediate_table: joins[qn(current_table)] = ( qn(intermediate_table), "LEFT OUTER JOIN", "%s.%s = %s.%s" % (qn(table), qn(current_opts.pk.column), qn(current_table), qn(intermediate_column)) ) if path: # There are elements left in the path. More joins are required. if len(path) == 1 and path[0] in (new_opts.pk.name, None) \ and lookup_type in ('exact', 'isnull') and not join_required: # If the next and final name query is for a primary key, # and the search is for isnull/exact, then the current # (for N-1) or intermediate (for N-N) table can be used # for the search. No need to join an extra table just # to check the primary key. new_table = current_table else: # There are 1 or more name queries pending, and we have ruled out # any shortcuts; therefore, a join is required. joins[qn(new_table)] = ( qn(new_opts.db_table), "INNER JOIN", "%s.%s = %s.%s" % (qn(current_table), qn(join_column), qn(new_table), qn(new_column)) ) # If we have made the join, we don't need to tell subsequent # recursive calls about the column name we joined on. join_column = None # There are name queries remaining. Recurse deeper. joins2, where2, params2 = lookup_inner(path, lookup_type, value, new_opts, new_table, join_column) joins.update(joins2) where.extend(where2) params.extend(params2) else: # No elements left in path. Current element is the element on which # the search is being performed. if join_required: # Last query term is a RelatedObject if field.field.rel.multiple: # RelatedObject is from a 1-N relation. # Join is required; query operates on joined table. column = new_opts.pk.name joins[qn(new_table)] = ( qn(new_opts.db_table), "INNER JOIN", "%s.%s = %s.%s" % (qn(current_table), qn(join_column), qn(new_table), qn(new_column)) ) current_table = new_table else: # RelatedObject is from a 1-1 relation, # No need to join; get the pk value from the related object, # and compare using that. column = current_opts.pk.name elif intermediate_table: # Last query term is a related object from an N-N relation. # Join from intermediate table is sufficient. column = join_column elif name == current_opts.pk.name and lookup_type in ('exact', 'isnull') and current_column: # Last query term is for a primary key. If previous iterations # introduced a current/intermediate table that can be used to # optimize the query, then use that table and column name. column = current_column else: # Last query term was a normal field. column = field.column where.append(get_where_clause(lookup_type, current_table + '.', column, value)) params.extend(field.get_db_prep_lookup(lookup_type, value)) return joins, where, params def delete_objects(seen_objs): "Iterate through a list of seen classes, and remove any instances that are referred to" qn = backend.quote_name ordered_classes = seen_objs.keys() ordered_classes.reverse() cursor = connection.cursor() for cls in ordered_classes: seen_objs[cls] = seen_objs[cls].items() seen_objs[cls].sort() # Pre notify all instances to be deleted for pk_val, instance in seen_objs[cls]: dispatcher.send(signal=signals.pre_delete, sender=cls, instance=instance) pk_list = [pk for pk,instance in seen_objs[cls]] for related in cls._meta.get_all_related_many_to_many_objects(): if not isinstance(related.field, GenericRelation): for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): cursor.execute("DELETE FROM %s WHERE %s IN (%s)" % \ (qn(related.field.m2m_db_table()), qn(related.field.m2m_reverse_name()), ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]])), pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]) for f in cls._meta.many_to_many: if isinstance(f, GenericRelation): from django.contrib.contenttypes.models import ContentType query_extra = 'AND %s=%%s' % f.rel.to._meta.get_field(f.content_type_field_name).column args_extra = [ContentType.objects.get_for_model(cls).id] else: query_extra = '' args_extra = [] for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): cursor.execute(("DELETE FROM %s WHERE %s IN (%s)" % \ (qn(f.m2m_db_table()), qn(f.m2m_column_name()), ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]]))) + query_extra, pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE] + args_extra) for field in cls._meta.fields: if field.rel and field.null and field.rel.to in seen_objs: for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): cursor.execute("UPDATE %s SET %s=NULL WHERE %s IN (%s)" % \ (qn(cls._meta.db_table), qn(field.column), qn(cls._meta.pk.column), ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]])), pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]) # Now delete the actual data for cls in ordered_classes: seen_objs[cls].reverse() pk_list = [pk for pk,instance in seen_objs[cls]] for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): cursor.execute("DELETE FROM %s WHERE %s IN (%s)" % \ (qn(cls._meta.db_table), qn(cls._meta.pk.column), ','.join(['%s' for pk in pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]])), pk_list[offset:offset+GET_ITERATOR_CHUNK_SIZE]) # Last cleanup; set NULLs where there once was a reference to the object, # NULL the primary key of the found objects, and perform post-notification. for pk_val, instance in seen_objs[cls]: for field in cls._meta.fields: if field.rel and field.null and field.rel.to in seen_objs: setattr(instance, field.attname, None) setattr(instance, cls._meta.pk.attname, None) dispatcher.send(signal=signals.post_delete, sender=cls, instance=instance) transaction.commit_unless_managed()
Python
import django.db.models.manipulators import django.db.models.manager from django.core import validators from django.core.exceptions import ObjectDoesNotExist from django.db.models.fields import AutoField, ImageField, FieldDoesNotExist from django.db.models.fields.related import OneToOneRel, ManyToOneRel from django.db.models.query import delete_objects from django.db.models.options import Options, AdminOptions from django.db import connection, backend, transaction from django.db.models import signals from django.db.models.loading import register_models, get_model from django.dispatch import dispatcher from django.utils.datastructures import SortedDict from django.utils.functional import curry from django.conf import settings from itertools import izip import types import sys import os class ModelBase(type): "Metaclass for all models" def __new__(cls, name, bases, attrs): # If this isn't a subclass of Model, don't do anything special. if name == 'Model' or not filter(lambda b: issubclass(b, Model), bases): return super(ModelBase, cls).__new__(cls, name, bases, attrs) # Create the class. new_class = type.__new__(cls, name, bases, {'__module__': attrs.pop('__module__')}) new_class.add_to_class('_meta', Options(attrs.pop('Meta', None))) new_class.add_to_class('DoesNotExist', types.ClassType('DoesNotExist', (ObjectDoesNotExist,), {})) # Build complete list of parents for base in bases: # TODO: Checking for the presence of '_meta' is hackish. if '_meta' in dir(base): new_class._meta.parents.append(base) new_class._meta.parents.extend(base._meta.parents) model_module = sys.modules[new_class.__module__] if getattr(new_class._meta, 'app_label', None) is None: # Figure out the app_label by looking one level up. # For 'django.contrib.sites.models', this would be 'sites'. new_class._meta.app_label = model_module.__name__.split('.')[-2] # Bail out early if we have already created this class. m = get_model(new_class._meta.app_label, name, False) if m is not None: return m # Add all attributes to the class. for obj_name, obj in attrs.items(): new_class.add_to_class(obj_name, obj) # Add Fields inherited from parents for parent in new_class._meta.parents: for field in parent._meta.fields: # Only add parent fields if they aren't defined for this class. try: new_class._meta.get_field(field.name) except FieldDoesNotExist: field.contribute_to_class(new_class, field.name) new_class._prepare() register_models(new_class._meta.app_label, new_class) # Because of the way imports happen (recursively), we may or may not be # the first class for this model to register with the framework. There # should only be one class for each model, so we must always return the # registered version. return get_model(new_class._meta.app_label, name, False) class Model(object): __metaclass__ = ModelBase def _get_pk_val(self): return getattr(self, self._meta.pk.attname) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self) def __str__(self): return '%s object' % self.__class__.__name__ def __eq__(self, other): return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val() def __ne__(self, other): return not self.__eq__(other) def __init__(self, *args, **kwargs): dispatcher.send(signal=signals.pre_init, sender=self.__class__, args=args, kwargs=kwargs) # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The reason for the kwargs check is that standard iterator passes in by # args, and nstantiation for iteration is 33% faster. args_len = len(args) if args_len > len(self._meta.fields): # Daft, but matches old exception sans the err msg. raise IndexError("Number of args exceeds number of fields") fields_iter = iter(self._meta.fields) if not kwargs: # The ordering of the izip calls matter - izip throws StopIteration # when an iter throws it. So if the first iter throws it, the second # is *not* consumed. We rely on this, so don't change the order # without changing the logic. for val, field in izip(args, fields_iter): setattr(self, field.attname, val) else: # Slower, kwargs-ready version. for val, field in izip(args, fields_iter): setattr(self, field.attname, val) kwargs.pop(field.name, None) # Maintain compatibility with existing calls. if isinstance(field.rel, ManyToOneRel): kwargs.pop(field.attname, None) # Now we're left with the unprocessed fields that *must* come from # keywords, or default. for field in fields_iter: if kwargs: if isinstance(field.rel, ManyToOneRel): try: # Assume object instance was passed in. rel_obj = kwargs.pop(field.name) except KeyError: try: # Object instance wasn't passed in -- must be an ID. val = kwargs.pop(field.attname) except KeyError: val = field.get_default() else: # Object instance was passed in. Special case: You can # pass in "None" for related objects if it's allowed. if rel_obj is None and field.null: val = None else: try: val = getattr(rel_obj, field.rel.get_related_field().attname) except AttributeError: raise TypeError("Invalid value: %r should be a %s instance, not a %s" % (field.name, field.rel.to, type(rel_obj))) else: val = kwargs.pop(field.attname, field.get_default()) else: val = field.get_default() setattr(self, field.attname, val) if kwargs: for prop in kwargs.keys(): try: if isinstance(getattr(self.__class__, prop), property): setattr(self, prop, kwargs.pop(prop)) except AttributeError: pass if kwargs: raise TypeError, "'%s' is an invalid keyword argument for this function" % kwargs.keys()[0] dispatcher.send(signal=signals.post_init, sender=self.__class__, instance=self) def add_to_class(cls, name, value): if name == 'Admin': assert type(value) == types.ClassType, "%r attribute of %s model must be a class, not a %s object" % (name, cls.__name__, type(value)) value = AdminOptions(**dict([(k, v) for k, v in value.__dict__.items() if not k.startswith('_')])) if hasattr(value, 'contribute_to_class'): value.contribute_to_class(cls, name) else: setattr(cls, name, value) add_to_class = classmethod(add_to_class) def _prepare(cls): # Creates some methods once self._meta has been populated. opts = cls._meta opts._prepare(cls) if opts.order_with_respect_to: cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True) cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False) setattr(opts.order_with_respect_to.rel.to, 'get_%s_order' % cls.__name__.lower(), curry(method_get_order, cls)) setattr(opts.order_with_respect_to.rel.to, 'set_%s_order' % cls.__name__.lower(), curry(method_set_order, cls)) # Give the class a docstring -- its definition. if cls.__doc__ is None: cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join([f.attname for f in opts.fields])) if hasattr(cls, 'get_absolute_url'): cls.get_absolute_url = curry(get_absolute_url, opts, cls.get_absolute_url) dispatcher.send(signal=signals.class_prepared, sender=cls) _prepare = classmethod(_prepare) def save(self): dispatcher.send(signal=signals.pre_save, sender=self.__class__, instance=self) non_pks = [f for f in self._meta.fields if not f.primary_key] cursor = connection.cursor() # First, try an UPDATE. If that doesn't update anything, do an INSERT. pk_val = self._get_pk_val() pk_set = bool(pk_val) record_exists = True if pk_set: # Determine whether a record with the primary key already exists. cursor.execute("SELECT 1 FROM %s WHERE %s=%%s LIMIT 1" % \ (backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column)), [pk_val]) # If it does already exist, do an UPDATE. if cursor.fetchone(): db_values = [f.get_db_prep_save(f.pre_save(self, False)) for f in non_pks] if db_values: cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \ (backend.quote_name(self._meta.db_table), ','.join(['%s=%%s' % backend.quote_name(f.column) for f in non_pks]), backend.quote_name(self._meta.pk.column)), db_values + [pk_val]) else: record_exists = False if not pk_set or not record_exists: field_names = [backend.quote_name(f.column) for f in self._meta.fields if not isinstance(f, AutoField)] db_values = [f.get_db_prep_save(f.pre_save(self, True)) for f in self._meta.fields if not isinstance(f, AutoField)] # If the PK has been manually set, respect that. if pk_set: field_names += [f.column for f in self._meta.fields if isinstance(f, AutoField)] db_values += [f.get_db_prep_save(f.pre_save(self, True)) for f in self._meta.fields if isinstance(f, AutoField)] placeholders = ['%s'] * len(field_names) if self._meta.order_with_respect_to: field_names.append(backend.quote_name('_order')) # TODO: This assumes the database supports subqueries. placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \ (backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.order_with_respect_to.column))) db_values.append(getattr(self, self._meta.order_with_respect_to.attname)) if db_values: cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \ (backend.quote_name(self._meta.db_table), ','.join(field_names), ','.join(placeholders)), db_values) else: # Create a new record with defaults for everything. cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % (backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column), backend.get_pk_default_value())) if self._meta.has_auto_field and not pk_set: setattr(self, self._meta.pk.attname, backend.get_last_insert_id(cursor, self._meta.db_table, self._meta.pk.column)) transaction.commit_unless_managed() # Run any post-save hooks. dispatcher.send(signal=signals.post_save, sender=self.__class__, instance=self) save.alters_data = True def validate(self): """ First coerces all fields on this instance to their proper Python types. Then runs validation on every field. Returns a dictionary of field_name -> error_list. """ error_dict = {} invalid_python = {} for f in self._meta.fields: try: setattr(self, f.attname, f.to_python(getattr(self, f.attname, f.get_default()))) except validators.ValidationError, e: error_dict[f.name] = e.messages invalid_python[f.name] = 1 for f in self._meta.fields: if f.name in invalid_python: continue errors = f.validate_full(getattr(self, f.attname, f.get_default()), self.__dict__) if errors: error_dict[f.name] = errors return error_dict def _collect_sub_objects(self, seen_objs): """ Recursively populates seen_objs with all objects related to this object. When done, seen_objs will be in the format: {model_class: {pk_val: obj, pk_val: obj, ...}, model_class: {pk_val: obj, pk_val: obj, ...}, ...} """ pk_val = self._get_pk_val() if pk_val in seen_objs.setdefault(self.__class__, {}): return seen_objs.setdefault(self.__class__, {})[pk_val] = self for related in self._meta.get_all_related_objects(): rel_opts_name = related.get_accessor_name() if isinstance(related.field.rel, OneToOneRel): try: sub_obj = getattr(self, rel_opts_name) except ObjectDoesNotExist: pass else: sub_obj._collect_sub_objects(seen_objs) else: for sub_obj in getattr(self, rel_opts_name).all(): sub_obj._collect_sub_objects(seen_objs) def delete(self): assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) # Find all the objects than need to be deleted seen_objs = SortedDict() self._collect_sub_objects(seen_objs) # Actually delete the objects delete_objects(seen_objs) delete.alters_data = True def _get_FIELD_display(self, field): value = getattr(self, field.attname) return dict(field.choices).get(value, value) def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): op = is_next and '>' or '<' where = '(%s %s %%s OR (%s = %%s AND %s.%s %s %%s))' % \ (backend.quote_name(field.column), op, backend.quote_name(field.column), backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column), op) param = str(getattr(self, field.attname)) q = self.__class__._default_manager.filter(**kwargs).order_by((not is_next and '-' or '') + field.name, (not is_next and '-' or '') + self._meta.pk.name) q._where.append(where) q._params.extend([param, param, getattr(self, self._meta.pk.attname)]) try: return q[0] except IndexError: raise self.DoesNotExist, "%s matching query does not exist." % self.__class__._meta.object_name def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next if not hasattr(self, cachename): op = is_next and '>' or '<' order_field = self._meta.order_with_respect_to where = ['%s %s (SELECT %s FROM %s WHERE %s=%%s)' % \ (backend.quote_name('_order'), op, backend.quote_name('_order'), backend.quote_name(self._meta.db_table), backend.quote_name(self._meta.pk.column)), '%s=%%s' % backend.quote_name(order_field.column)] params = [self._get_pk_val(), getattr(self, order_field.attname)] obj = self._default_manager.order_by('_order').extra(where=where, params=params)[:1].get() setattr(self, cachename, obj) return getattr(self, cachename) def _get_FIELD_filename(self, field): if getattr(self, field.attname): # value is not blank return os.path.join(settings.MEDIA_ROOT, getattr(self, field.attname)) return '' def _get_FIELD_url(self, field): if getattr(self, field.attname): # value is not blank import urlparse return urlparse.urljoin(settings.MEDIA_URL, getattr(self, field.attname)).replace('\\', '/') return '' def _get_FIELD_size(self, field): return os.path.getsize(self._get_FIELD_filename(field)) def _save_FIELD_file(self, field, filename, raw_contents, save=True): directory = field.get_directory_name() try: # Create the date-based directory if it doesn't exist. os.makedirs(os.path.join(settings.MEDIA_ROOT, directory)) except OSError: # Directory probably already exists. pass filename = field.get_filename(filename) # If the filename already exists, keep adding an underscore to the name of # the file until the filename doesn't exist. while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)): try: dot_index = filename.rindex('.') except ValueError: # filename has no dot filename += '_' else: filename = filename[:dot_index] + '_' + filename[dot_index:] # Write the file to disk. setattr(self, field.attname, filename) full_filename = self._get_FIELD_filename(field) fp = open(full_filename, 'wb') fp.write(raw_contents) fp.close() # Save the width and/or height, if applicable. if isinstance(field, ImageField) and (field.width_field or field.height_field): from django.utils.images import get_image_dimensions width, height = get_image_dimensions(full_filename) if field.width_field: setattr(self, field.width_field, width) if field.height_field: setattr(self, field.height_field, height) # Save the object because it has changed unless save is False if save: self.save() _save_FIELD_file.alters_data = True def _get_FIELD_width(self, field): return self._get_image_dimensions(field)[0] def _get_FIELD_height(self, field): return self._get_image_dimensions(field)[1] def _get_image_dimensions(self, field): cachename = "__%s_dimensions_cache" % field.name if not hasattr(self, cachename): from django.utils.images import get_image_dimensions filename = self._get_FIELD_filename(field) setattr(self, cachename, get_image_dimensions(filename)) return getattr(self, cachename) ############################################ # HELPER FUNCTIONS (CURRIED MODEL METHODS) # ############################################ # ORDERING METHODS ######################### def method_set_order(ordered_obj, self, id_list): cursor = connection.cursor() # Example: "UPDATE poll_choices SET _order = %s WHERE poll_id = %s AND id = %s" sql = "UPDATE %s SET %s = %%s WHERE %s = %%s AND %s = %%s" % \ (backend.quote_name(ordered_obj._meta.db_table), backend.quote_name('_order'), backend.quote_name(ordered_obj._meta.order_with_respect_to.column), backend.quote_name(ordered_obj._meta.pk.column)) rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) cursor.executemany(sql, [(i, rel_val, j) for i, j in enumerate(id_list)]) transaction.commit_unless_managed() def method_get_order(ordered_obj, self): cursor = connection.cursor() # Example: "SELECT id FROM poll_choices WHERE poll_id = %s ORDER BY _order" sql = "SELECT %s FROM %s WHERE %s = %%s ORDER BY %s" % \ (backend.quote_name(ordered_obj._meta.pk.column), backend.quote_name(ordered_obj._meta.db_table), backend.quote_name(ordered_obj._meta.order_with_respect_to.column), backend.quote_name('_order')) rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name) cursor.execute(sql, [rel_val]) return [r[0] for r in cursor.fetchall()] ############################################## # HELPER FUNCTIONS (CURRIED MODEL FUNCTIONS) # ############################################## def get_absolute_url(opts, func, self): return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self)
Python
from django.core.exceptions import ObjectDoesNotExist from django import oldforms from django.core import validators from django.db.models.fields import FileField, AutoField from django.dispatch import dispatcher from django.db.models import signals from django.utils.functional import curry from django.utils.datastructures import DotExpandedDict from django.utils.text import capfirst import types def add_manipulators(sender): cls = sender cls.add_to_class('AddManipulator', AutomaticAddManipulator) cls.add_to_class('ChangeManipulator', AutomaticChangeManipulator) dispatcher.connect(add_manipulators, signal=signals.class_prepared) class ManipulatorDescriptor(object): # This class provides the functionality that makes the default model # manipulators (AddManipulator and ChangeManipulator) available via the # model class. def __init__(self, name, base): self.man = None # Cache of the manipulator class. self.name = name self.base = base def __get__(self, instance, model=None): if instance != None: raise AttributeError, "Manipulator cannot be accessed via instance" else: if not self.man: # Create a class that inherits from the "Manipulator" class # given in the model class (if specified) and the automatic # manipulator. bases = [self.base] if hasattr(model, 'Manipulator'): bases = [model.Manipulator] + bases self.man = types.ClassType(self.name, tuple(bases), {}) self.man._prepare(model) return self.man class AutomaticManipulator(oldforms.Manipulator): def _prepare(cls, model): cls.model = model cls.manager = model._default_manager cls.opts = model._meta for field_name_list in cls.opts.unique_together: setattr(cls, 'isUnique%s' % '_'.join(field_name_list), curry(manipulator_validator_unique_together, field_name_list, cls.opts)) for f in cls.opts.fields: if f.unique_for_date: setattr(cls, 'isUnique%sFor%s' % (f.name, f.unique_for_date), curry(manipulator_validator_unique_for_date, f, cls.opts.get_field(f.unique_for_date), cls.opts, 'date')) if f.unique_for_month: setattr(cls, 'isUnique%sFor%s' % (f.name, f.unique_for_month), curry(manipulator_validator_unique_for_date, f, cls.opts.get_field(f.unique_for_month), cls.opts, 'month')) if f.unique_for_year: setattr(cls, 'isUnique%sFor%s' % (f.name, f.unique_for_year), curry(manipulator_validator_unique_for_date, f, cls.opts.get_field(f.unique_for_year), cls.opts, 'year')) _prepare = classmethod(_prepare) def contribute_to_class(cls, other_cls, name): setattr(other_cls, name, ManipulatorDescriptor(name, cls)) contribute_to_class = classmethod(contribute_to_class) def __init__(self, follow=None): self.follow = self.opts.get_follow(follow) self.fields = [] for f in self.opts.fields + self.opts.many_to_many: if self.follow.get(f.name, False): self.fields.extend(f.get_manipulator_fields(self.opts, self, self.change)) # Add fields for related objects. for f in self.opts.get_all_related_objects(): if self.follow.get(f.name, False): fol = self.follow[f.name] self.fields.extend(f.get_manipulator_fields(self.opts, self, self.change, fol)) # Add field for ordering. if self.change and self.opts.get_ordered_objects(): self.fields.append(oldforms.CommaSeparatedIntegerField(field_name="order_")) def save(self, new_data): # TODO: big cleanup when core fields go -> use recursive manipulators. params = {} for f in self.opts.fields: # Fields with auto_now_add should keep their original value in the change stage. auto_now_add = self.change and getattr(f, 'auto_now_add', False) if self.follow.get(f.name, None) and not auto_now_add: param = f.get_manipulator_new_data(new_data) else: if self.change: param = getattr(self.original_object, f.attname) else: param = f.get_default() params[f.attname] = param if self.change: params[self.opts.pk.attname] = self.obj_key # First, create the basic object itself. new_object = self.model(**params) # Now that the object's been created, save any uploaded files. for f in self.opts.fields: if isinstance(f, FileField): f.save_file(new_data, new_object, self.change and self.original_object or None, self.change, rel=False, save=False) # Now save the object new_object.save() # Calculate which primary fields have changed. if self.change: self.fields_added, self.fields_changed, self.fields_deleted = [], [], [] for f in self.opts.fields: if not f.primary_key and str(getattr(self.original_object, f.attname)) != str(getattr(new_object, f.attname)): self.fields_changed.append(f.verbose_name) # Save many-to-many objects. Example: Set sites for a poll. for f in self.opts.many_to_many: if self.follow.get(f.name, None): if not f.rel.edit_inline: if f.rel.raw_id_admin: new_vals = new_data.get(f.name, ()) else: new_vals = new_data.getlist(f.name) # First, clear the existing values. rel_manager = getattr(new_object, f.name) rel_manager.clear() # Then, set the new values. for n in new_vals: rel_manager.add(f.rel.to._default_manager.get(pk=n)) # TODO: Add to 'fields_changed' expanded_data = DotExpandedDict(dict(new_data)) # Save many-to-one objects. Example: Add the Choice objects for a Poll. for related in self.opts.get_all_related_objects(): # Create obj_list, which is a DotExpandedDict such as this: # [('0', {'id': ['940'], 'choice': ['This is the first choice']}), # ('1', {'id': ['941'], 'choice': ['This is the second choice']}), # ('2', {'id': [''], 'choice': ['']})] child_follow = self.follow.get(related.name, None) if child_follow: obj_list = expanded_data.get(related.var_name, {}).items() if not obj_list: continue obj_list.sort(lambda x, y: cmp(int(x[0]), int(y[0]))) # For each related item... for _, rel_new_data in obj_list: params = {} # Keep track of which core=True fields were provided. # If all core fields were given, the related object will be saved. # If none of the core fields were given, the object will be deleted. # If some, but not all, of the fields were given, the validator would # have caught that. all_cores_given, all_cores_blank = True, True # Get a reference to the old object. We'll use it to compare the # old to the new, to see which fields have changed. old_rel_obj = None if self.change: if rel_new_data[related.opts.pk.name][0]: try: old_rel_obj = getattr(self.original_object, related.get_accessor_name()).get(**{'%s__exact' % related.opts.pk.name: rel_new_data[related.opts.pk.attname][0]}) except ObjectDoesNotExist: pass for f in related.opts.fields: if f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) in (None, ''): all_cores_given = False elif f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) not in (None, ''): all_cores_blank = False # If this field isn't editable, give it the same value it had # previously, according to the given ID. If the ID wasn't # given, use a default value. FileFields are also a special # case, because they'll be dealt with later. if f == related.field: param = getattr(new_object, related.field.rel.get_related_field().attname) elif (not self.change) and isinstance(f, AutoField): param = None elif self.change and (isinstance(f, FileField) or not child_follow.get(f.name, None)): if old_rel_obj: param = getattr(old_rel_obj, f.column) else: param = f.get_default() else: param = f.get_manipulator_new_data(rel_new_data, rel=True) if param != None: params[f.attname] = param # Create the related item. new_rel_obj = related.model(**params) # If all the core fields were provided (non-empty), save the item. if all_cores_given: new_rel_obj.save() # Save any uploaded files. for f in related.opts.fields: if child_follow.get(f.name, None): if isinstance(f, FileField) and rel_new_data.get(f.name, False): f.save_file(rel_new_data, new_rel_obj, self.change and old_rel_obj or None, old_rel_obj is not None, rel=True) # Calculate whether any fields have changed. if self.change: if not old_rel_obj: # This object didn't exist before. self.fields_added.append('%s "%s"' % (related.opts.verbose_name, new_rel_obj)) else: for f in related.opts.fields: if not f.primary_key and f != related.field and str(getattr(old_rel_obj, f.attname)) != str(getattr(new_rel_obj, f.attname)): self.fields_changed.append('%s for %s "%s"' % (f.verbose_name, related.opts.verbose_name, new_rel_obj)) # Save many-to-many objects. for f in related.opts.many_to_many: if child_follow.get(f.name, None) and not f.rel.edit_inline: new_value = rel_new_data[f.attname] if f.rel.raw_id_admin: new_value = new_value[0] setattr(new_rel_obj, f.name, f.rel.to.objects.filter(pk__in=new_value)) if self.change: self.fields_changed.append('%s for %s "%s"' % (f.verbose_name, related.opts.verbose_name, new_rel_obj)) # If, in the change stage, all of the core fields were blank and # the primary key (ID) was provided, delete the item. if self.change and all_cores_blank and old_rel_obj: new_rel_obj.delete() self.fields_deleted.append('%s "%s"' % (related.opts.verbose_name, old_rel_obj)) # Save the order, if applicable. if self.change and self.opts.get_ordered_objects(): order = new_data['order_'] and map(int, new_data['order_'].split(',')) or [] for rel_opts in self.opts.get_ordered_objects(): getattr(new_object, 'set_%s_order' % rel_opts.object_name.lower())(order) return new_object def get_related_objects(self): return self.opts.get_followed_related_objects(self.follow) def flatten_data(self): new_data = {} obj = self.change and self.original_object or None for f in self.opts.get_data_holders(self.follow): fol = self.follow.get(f.name) new_data.update(f.flatten_data(fol, obj)) return new_data class AutomaticAddManipulator(AutomaticManipulator): change = False class AutomaticChangeManipulator(AutomaticManipulator): change = True def __init__(self, obj_key, follow=None): self.obj_key = obj_key try: self.original_object = self.manager.get(pk=obj_key) except ObjectDoesNotExist: # If the object doesn't exist, this might be a manipulator for a # one-to-one related object that hasn't created its subobject yet. # For example, this might be a Restaurant for a Place that doesn't # yet have restaurant information. if self.opts.one_to_one_field: # Sanity check -- Make sure the "parent" object exists. # For example, make sure the Place exists for the Restaurant. # Let the ObjectDoesNotExist exception propagate up. limit_choices_to = self.opts.one_to_one_field.rel.limit_choices_to lookup_kwargs = {'%s__exact' % self.opts.one_to_one_field.rel.field_name: obj_key} self.opts.one_to_one_field.rel.to.get_model_module().complex_filter(limit_choices_to).get(**lookup_kwargs) params = dict([(f.attname, f.get_default()) for f in self.opts.fields]) params[self.opts.pk.attname] = obj_key self.original_object = self.opts.get_model_module().Klass(**params) else: raise super(AutomaticChangeManipulator, self).__init__(follow=follow) def manipulator_validator_unique_together(field_name_list, opts, self, field_data, all_data): from django.db.models.fields.related import ManyToOneRel from django.utils.text import get_text_list field_list = [opts.get_field(field_name) for field_name in field_name_list] if isinstance(field_list[0].rel, ManyToOneRel): kwargs = {'%s__%s__iexact' % (field_name_list[0], field_list[0].rel.field_name): field_data} else: kwargs = {'%s__iexact' % field_name_list[0]: field_data} for f in field_list[1:]: # This is really not going to work for fields that have different # form fields, e.g. DateTime. # This validation needs to occur after html2python to be effective. field_val = all_data.get(f.name, None) if field_val is None: # This will be caught by another validator, assuming the field # doesn't have blank=True. return if isinstance(f.rel, ManyToOneRel): kwargs['%s__pk' % f.name] = field_val else: kwargs['%s__iexact' % f.name] = field_val try: old_obj = self.manager.get(**kwargs) except ObjectDoesNotExist: return if hasattr(self, 'original_object') and self.original_object._get_pk_val() == old_obj._get_pk_val(): pass else: raise validators.ValidationError, _("%(object)s with this %(type)s already exists for the given %(field)s.") % \ {'object': capfirst(opts.verbose_name), 'type': field_list[0].verbose_name, 'field': get_text_list([f.verbose_name for f in field_list[1:]], _('and'))} def manipulator_validator_unique_for_date(from_field, date_field, opts, lookup_type, self, field_data, all_data): from django.db.models.fields.related import ManyToOneRel date_str = all_data.get(date_field.get_manipulator_field_names('')[0], None) date_val = oldforms.DateField.html2python(date_str) if date_val is None: return # Date was invalid. This will be caught by another validator. lookup_kwargs = {'%s__year' % date_field.name: date_val.year} if isinstance(from_field.rel, ManyToOneRel): lookup_kwargs['%s__pk' % from_field.name] = field_data else: lookup_kwargs['%s__iexact' % from_field.name] = field_data if lookup_type in ('month', 'date'): lookup_kwargs['%s__month' % date_field.name] = date_val.month if lookup_type == 'date': lookup_kwargs['%s__day' % date_field.name] = date_val.day try: old_obj = self.manager.get(**lookup_kwargs) except ObjectDoesNotExist: return else: if hasattr(self, 'original_object') and self.original_object._get_pk_val() == old_obj._get_pk_val(): pass else: format_string = (lookup_type == 'date') and '%B %d, %Y' or '%B %Y' raise validators.ValidationError, "Please enter a different %s. The one you entered is already being used for %s." % \ (from_field.verbose_name, date_val.strftime(format_string))
Python
from django.conf import settings from django.db.models.related import RelatedObject from django.db.models.fields.related import ManyToManyRel from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.loading import get_models from django.db.models.query import orderlist2sql from django.db.models import Manager from bisect import bisect import re # Calculate the verbose_name by converting from InitialCaps to "lowercase with spaces". get_verbose_name = lambda class_name: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', ' \\1', class_name).lower().strip() DEFAULT_NAMES = ('verbose_name', 'db_table', 'ordering', 'unique_together', 'permissions', 'get_latest_by', 'order_with_respect_to', 'app_label') class Options(object): def __init__(self, meta): self.fields, self.many_to_many = [], [] self.module_name, self.verbose_name = None, None self.verbose_name_plural = None self.db_table = '' self.ordering = [] self.unique_together = [] self.permissions = [] self.object_name, self.app_label = None, None self.get_latest_by = None self.order_with_respect_to = None self.admin = None self.meta = meta self.pk = None self.has_auto_field = False self.one_to_one_field = None self.parents = [] def contribute_to_class(self, cls, name): cls._meta = self self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS # First, construct the default values for these options. self.object_name = cls.__name__ self.module_name = self.object_name.lower() self.verbose_name = get_verbose_name(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__ del meta_attrs['__module__'] del meta_attrs['__doc__'] for attr_name in DEFAULT_NAMES: setattr(self, attr_name, meta_attrs.pop(attr_name, getattr(self, attr_name))) # verbose_name_plural is a special case because it uses a 's' # by default. setattr(self, 'verbose_name_plural', meta_attrs.pop('verbose_name_plural', self.verbose_name + 's')) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError, "'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()) else: self.verbose_name_plural = self.verbose_name + 's' del self.meta def _prepare(self, model): if self.order_with_respect_to: self.order_with_respect_to = self.get_field(self.order_with_respect_to) self.ordering = ('_order',) else: self.order_with_respect_to = None if self.pk is None: auto = AutoField(verbose_name='ID', primary_key=True) auto.creation_counter = -1 model.add_to_class('id', auto) # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) def add_field(self, field): # Insert the given field in the order in which it was created, using # the "creation_counter" attribute of the field. # Move many-to-many related fields from self.fields into self.many_to_many. if field.rel and isinstance(field.rel, ManyToManyRel): self.many_to_many.insert(bisect(self.many_to_many, field), field) else: self.fields.insert(bisect(self.fields, field), field) if not self.pk and field.primary_key: self.pk = field field.serialize = False def __repr__(self): return '<Options for %s>' % self.object_name def __str__(self): return "%s.%s" % (self.app_label, self.module_name) def get_field(self, name, many_to_many=True): "Returns the requested field by name. Raises FieldDoesNotExist on error." to_search = many_to_many and (self.fields + self.many_to_many) or self.fields for f in to_search: if f.name == name: return f raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name) def get_order_sql(self, table_prefix=''): "Returns the full 'ORDER BY' clause for this object, according to self.ordering." if not self.ordering: return '' pre = table_prefix and (table_prefix + '.') or '' return 'ORDER BY ' + orderlist2sql(self.ordering, self, pre) def get_add_permission(self): return 'add_%s' % self.object_name.lower() def get_change_permission(self): return 'change_%s' % self.object_name.lower() def get_delete_permission(self): return 'delete_%s' % self.object_name.lower() def get_all_related_objects(self): try: # Try the cache first. return self._all_related_objects except AttributeError: rel_objs = [] for klass in get_models(): for f in klass._meta.fields: if f.rel and self == f.rel.to._meta: rel_objs.append(RelatedObject(f.rel.to, klass, f)) self._all_related_objects = rel_objs return rel_objs def get_followed_related_objects(self, follow=None): if follow == None: follow = self.get_follow() return [f for f in self.get_all_related_objects() if follow.get(f.name, None)] def get_data_holders(self, follow=None): if follow == None: follow = self.get_follow() return [f for f in self.fields + self.many_to_many + self.get_all_related_objects() if follow.get(f.name, None)] def get_follow(self, override=None): follow = {} for f in self.fields + self.many_to_many + self.get_all_related_objects(): if override and override.has_key(f.name): child_override = override[f.name] else: child_override = None fol = f.get_follow(child_override) if fol != None: follow[f.name] = fol return follow def get_all_related_many_to_many_objects(self): try: # Try the cache first. return self._all_related_many_to_many_objects except AttributeError: rel_objs = [] for klass in get_models(): for f in klass._meta.many_to_many: if f.rel and self == f.rel.to._meta: rel_objs.append(RelatedObject(f.rel.to, klass, f)) self._all_related_many_to_many_objects = rel_objs return rel_objs def get_ordered_objects(self): "Returns a list of Options objects that are ordered with respect to this object." if not hasattr(self, '_ordered_objects'): objects = [] # TODO #for klass in get_models(get_app(self.app_label)): # opts = klass._meta # if opts.order_with_respect_to and opts.order_with_respect_to.rel \ # and self == opts.order_with_respect_to.rel.to._meta: # objects.append(opts) self._ordered_objects = objects return self._ordered_objects def has_field_type(self, field_type, follow=None): """ Returns True if this object's admin form has at least one of the given field_type (e.g. FileField). """ # TODO: follow if not hasattr(self, '_field_types'): self._field_types = {} if not self._field_types.has_key(field_type): try: # First check self.fields. for f in self.fields: if isinstance(f, field_type): raise StopIteration # Failing that, check related fields. for related in self.get_followed_related_objects(follow): for f in related.opts.fields: if isinstance(f, field_type): raise StopIteration except StopIteration: self._field_types[field_type] = True else: self._field_types[field_type] = False return self._field_types[field_type] class AdminOptions(object): def __init__(self, fields=None, js=None, list_display=None, list_display_links=None, list_filter=None, date_hierarchy=None, save_as=False, ordering=None, search_fields=None, save_on_top=False, list_select_related=False, manager=None, list_per_page=100): self.fields = fields self.js = js or [] self.list_display = list_display or ['__str__'] self.list_display_links = list_display_links or [] self.list_filter = list_filter or [] self.date_hierarchy = date_hierarchy self.save_as, self.ordering = save_as, ordering self.search_fields = search_fields or [] self.save_on_top = save_on_top self.list_select_related = list_select_related self.list_per_page = list_per_page self.manager = manager or Manager() def get_field_sets(self, opts): "Returns a list of AdminFieldSet objects for this AdminOptions object." if self.fields is None: field_struct = ((None, {'fields': [f.name for f in opts.fields + opts.many_to_many if f.editable and not isinstance(f, AutoField)]}),) else: field_struct = self.fields new_fieldset_list = [] for fieldset in field_struct: fs_options = fieldset[1] classes = fs_options.get('classes', ()) description = fs_options.get('description', '') new_fieldset_list.append(AdminFieldSet(fieldset[0], classes, opts.get_field, fs_options['fields'], description)) return new_fieldset_list def contribute_to_class(self, cls, name): cls._meta.admin = self # Make sure the admin manager has access to the model self.manager.model = cls class AdminFieldSet(object): def __init__(self, name, classes, field_locator_func, line_specs, description): self.name = name self.field_lines = [AdminFieldLine(field_locator_func, line_spec) for line_spec in line_specs] self.classes = classes self.description = description def __repr__(self): return "FieldSet: (%s, %s)" % (self.name, self.field_lines) def bind(self, field_mapping, original, bound_field_set_class): return bound_field_set_class(self, field_mapping, original) def __iter__(self): for field_line in self.field_lines: yield field_line def __len__(self): return len(self.field_lines) class AdminFieldLine(object): def __init__(self, field_locator_func, linespec): if isinstance(linespec, basestring): self.fields = [field_locator_func(linespec)] else: self.fields = [field_locator_func(field_name) for field_name in linespec] def bind(self, field_mapping, original, bound_field_line_class): return bound_field_line_class(self, field_mapping, original) def __iter__(self): for field in self.fields: yield field def __len__(self): return len(self.fields)
Python
""" Classes allowing "generic" relations through ContentType and object-id fields. """ from django import oldforms from django.core.exceptions import ObjectDoesNotExist from django.db import backend from django.db.models import signals from django.db.models.fields.related import RelatedField, Field, ManyToManyRel from django.db.models.loading import get_model from django.dispatch import dispatcher from django.utils.functional import curry class GenericForeignKey(object): """ Provides a generic relation to any object through content-type/object-id fields. """ def __init__(self, ct_field="content_type", fk_field="object_id"): self.ct_field = ct_field self.fk_field = fk_field def contribute_to_class(self, cls, name): # Make sure the fields exist (these raise FieldDoesNotExist, # which is a fine error to raise here) self.name = name self.model = cls self.cache_attr = "_%s_cache" % name # For some reason I don't totally understand, using weakrefs here doesn't work. dispatcher.connect(self.instance_pre_init, signal=signals.pre_init, sender=cls, weak=False) # Connect myself as the descriptor for this field setattr(cls, name, self) def instance_pre_init(self, signal, sender, args, kwargs): # Handle initalizing an object with the generic FK instaed of # content-type/object-id fields. if kwargs.has_key(self.name): value = kwargs.pop(self.name) kwargs[self.ct_field] = self.get_content_type(value) kwargs[self.fk_field] = value._get_pk_val() def get_content_type(self, obj): # Convenience function using get_model avoids a circular import when using this model ContentType = get_model("contenttypes", "contenttype") return ContentType.objects.get_for_model(obj) def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.name try: return getattr(instance, self.cache_attr) except AttributeError: rel_obj = None ct = getattr(instance, self.ct_field) if ct: try: rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field)) except ObjectDoesNotExist: pass setattr(instance, self.cache_attr, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.related.opts.object_name ct = None fk = None if value is not None: ct = self.get_content_type(value) fk = value._get_pk_val() setattr(instance, self.ct_field, ct) setattr(instance, self.fk_field, fk) setattr(instance, self.cache_attr, value) class GenericRelation(RelatedField, Field): """Provides an accessor to generic related objects (i.e. comments)""" def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = GenericRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', True)) # Override content-type/object-id field names on the related class self.object_id_field_name = kwargs.pop("object_id_field", "object_id") self.content_type_field_name = kwargs.pop("content_type_field", "content_type") kwargs['blank'] = True kwargs['editable'] = False kwargs['serialize'] = False Field.__init__(self, **kwargs) def get_manipulator_field_objs(self): choices = self.get_choices_default() return [curry(oldforms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)] def get_choices_default(self): return Field.get_choices(self, include_blank=False) def flatten_data(self, follow, obj = None): new_data = {} if obj: instance_ids = [instance._get_pk_val() for instance in getattr(obj, self.name).all()] new_data[self.name] = instance_ids return new_data def m2m_db_table(self): return self.rel.to._meta.db_table def m2m_column_name(self): return self.object_id_field_name def m2m_reverse_name(self): return self.object_id_field_name def contribute_to_class(self, cls, name): super(GenericRelation, self).contribute_to_class(cls, name) # Save a reference to which model this class is on for future use self.model = cls # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseGenericRelatedObjectsDescriptor(self)) def contribute_to_related_class(self, cls, related): pass def set_attributes_from_rel(self): pass def get_internal_type(self): return "ManyToManyField" class ReverseGenericRelatedObjectsDescriptor(object): """ This class provides the functionality that makes the related-object managers available as attributes on a model class, for fields that have multiple "remote" values and have a GenericRelation defined in their model (rather than having another model pointed *at* them). In the example "article.publications", the publications attribute is a ReverseGenericRelatedObjectsDescriptor instance. """ def __init__(self, field): self.field = field def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "Manager must be accessed via instance" # This import is done here to avoid circular import importing this module from django.contrib.contenttypes.models import ContentType # Dynamically create a class that subclasses the related model's # default manager. rel_model = self.field.rel.to superclass = rel_model._default_manager.__class__ RelatedManager = create_generic_related_manager(superclass) manager = RelatedManager( model = rel_model, instance = instance, symmetrical = (self.field.rel.symmetrical and instance.__class__ == rel_model), join_table = backend.quote_name(self.field.m2m_db_table()), source_col_name = backend.quote_name(self.field.m2m_column_name()), target_col_name = backend.quote_name(self.field.m2m_reverse_name()), content_type = ContentType.objects.get_for_model(self.field.model), content_type_field_name = self.field.content_type_field_name, object_id_field_name = self.field.object_id_field_name ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError, "Manager must be accessed via instance" manager = self.__get__(instance) manager.clear() for obj in value: manager.add(obj) def create_generic_related_manager(superclass): """ Factory function for a manager that subclasses 'superclass' (which is a Manager) and adds behavior for generic related objects. """ class GenericRelatedObjectManager(superclass): def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None, join_table=None, source_col_name=None, target_col_name=None, content_type=None, content_type_field_name=None, object_id_field_name=None): super(GenericRelatedObjectManager, self).__init__() self.core_filters = core_filters or {} self.model = model self.content_type = content_type self.symmetrical = symmetrical self.instance = instance self.join_table = join_table self.join_table = model._meta.db_table self.source_col_name = source_col_name self.target_col_name = target_col_name self.content_type_field_name = content_type_field_name self.object_id_field_name = object_id_field_name self.pk_val = self.instance._get_pk_val() def get_query_set(self): query = { '%s__pk' % self.content_type_field_name : self.content_type.id, '%s__exact' % self.object_id_field_name : self.pk_val, } return superclass.get_query_set(self).filter(**query) def add(self, *objs): for obj in objs: setattr(obj, self.content_type_field_name, self.content_type) setattr(obj, self.object_id_field_name, self.pk_val) obj.save() add.alters_data = True def remove(self, *objs): for obj in objs: obj.delete() remove.alters_data = True def clear(self): for obj in self.all(): obj.delete() clear.alters_data = True def create(self, **kwargs): kwargs[self.content_type_field_name] = self.content_type kwargs[self.object_id_field_name] = self.pk_val obj = self.model(**kwargs) obj.save() return obj create.alters_data = True return GenericRelatedObjectManager class GenericRel(ManyToManyRel): def __init__(self, to, related_name=None, limit_choices_to=None, symmetrical=True): self.to = to self.num_in_admin = 0 self.related_name = related_name self.filter_interface = None self.limit_choices_to = limit_choices_to or {} self.edit_inline = False self.raw_id_admin = False self.symmetrical = symmetrical self.multiple = True assert not (self.raw_id_admin and self.filter_interface), \ "Generic relations may not use both raw_id_admin and filter_interface"
Python
from django.db import backend, transaction from django.db.models import signals, get_model from django.db.models.fields import AutoField, Field, IntegerField, get_ul_class from django.db.models.related import RelatedObject from django.utils.text import capfirst from django.utils.translation import gettext_lazy, string_concat, ngettext from django.utils.functional import curry from django.core import validators from django import oldforms from django import newforms as forms from django.dispatch import dispatcher # For Python 2.3 if not hasattr(__builtins__, 'set'): from sets import Set as set # Values for Relation.edit_inline. TABULAR, STACKED = 1, 2 RECURSIVE_RELATIONSHIP_CONSTANT = 'self' pending_lookups = {} def add_lookup(rel_cls, field): name = field.rel.to module = rel_cls.__module__ key = (module, name) # Has the model already been loaded? # If so, resolve the string reference right away model = get_model(rel_cls._meta.app_label, field.rel.to, False) if model: field.rel.to = model field.do_related_class(model, rel_cls) else: # Mark the related field for later lookup pending_lookups.setdefault(key, []).append((rel_cls, field)) def do_pending_lookups(sender): other_cls = sender key = (other_cls.__module__, other_cls.__name__) for rel_cls, field in pending_lookups.setdefault(key, []): field.rel.to = other_cls field.do_related_class(other_cls, rel_cls) dispatcher.connect(do_pending_lookups, signal=signals.class_prepared) def manipulator_valid_rel_key(f, self, field_data, all_data): "Validates that the value is a valid foreign key" klass = f.rel.to try: klass._default_manager.get(**{f.rel.field_name: field_data}) except klass.DoesNotExist: raise validators.ValidationError, _("Please enter a valid %s.") % f.verbose_name #HACK class RelatedField(object): def contribute_to_class(self, cls, name): sup = super(RelatedField, self) # Add an accessor to allow easy determination of the related query path for this field self.related_query_name = curry(self._get_related_query_name, cls._meta) if hasattr(sup, 'contribute_to_class'): sup.contribute_to_class(cls, name) other = self.rel.to if isinstance(other, basestring): if other == RECURSIVE_RELATIONSHIP_CONSTANT: self.rel.to = cls.__name__ add_lookup(cls, self) else: self.do_related_class(other, cls) def set_attributes_from_rel(self): self.name = self.name or (self.rel.to._meta.object_name.lower() + '_' + self.rel.to._meta.pk.name) self.verbose_name = self.verbose_name or self.rel.to._meta.verbose_name self.rel.field_name = self.rel.field_name or self.rel.to._meta.pk.name def do_related_class(self, other, cls): self.set_attributes_from_rel() related = RelatedObject(other, cls, self) self.contribute_to_related_class(other, related) def get_db_prep_lookup(self, lookup_type, value): # If we are doing a lookup on a Related Field, we must be # comparing object instances. The value should be the PK of value, # not value itself. def pk_trace(value): # Value may be a primary key, or an object held in a relation. # If it is an object, then we need to get the primary key value for # that object. In certain conditions (especially one-to-one relations), # the primary key may itself be an object - so we need to keep drilling # down until we hit a value that can be used for a comparison. v = value try: while True: v = getattr(v, v._meta.pk.name) except AttributeError: pass return v if lookup_type == 'exact': return [pk_trace(value)] if lookup_type == 'in': return [pk_trace(v) for v in value] elif lookup_type == 'isnull': return [] raise TypeError, "Related Field has invalid lookup: %s" % lookup_type def _get_related_query_name(self, opts): # This method defines the name that can be used to identify this related object # in a table-spanning query. It uses the lower-cased object_name by default, # but this can be overridden with the "related_name" option. return self.rel.related_name or opts.object_name.lower() class SingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class pointed to by a related field. # In the example "place.restaurant", the restaurant attribute is a # SingleRelatedObjectDescriptor instance. def __init__(self, related): self.related = related def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.related.opts.object_name params = {'%s__pk' % self.related.field.name: instance._get_pk_val()} rel_obj = self.related.model._default_manager.get(**params) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.related.opts.object_name # Set the value of the related field setattr(value, self.related.field.rel.get_related_field().attname, instance) # Clear the cache, if it exists try: delattr(value, self.related.field.get_cache_name()) except AttributeError: pass class ReverseSingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class that defines the related field. # In the example "choice.poll", the poll attribute is a # ReverseSingleRelatedObjectDescriptor instance. def __init__(self, field_with_rel): self.field = field_with_rel def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.field.name cache_name = self.field.get_cache_name() try: return getattr(instance, cache_name) except AttributeError: val = getattr(instance, self.field.attname) if val is None: # If NULL is an allowed value, return it. if self.field.null: return None raise self.field.rel.to.DoesNotExist other_field = self.field.rel.get_related_field() if other_field.rel: params = {'%s__pk' % self.field.rel.field_name: val} else: params = {'%s__exact' % self.field.rel.field_name: val} rel_obj = self.field.rel.to._default_manager.get(**params) setattr(instance, cache_name, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError, "%s must be accessed via instance" % self._field.name # Set the value of the related field try: val = getattr(value, self.field.rel.get_related_field().attname) except AttributeError: val = None setattr(instance, self.field.attname, val) # Clear the cache, if it exists try: delattr(instance, self.field.get_cache_name()) except AttributeError: pass class ForeignRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ForeignKey pointed at them by # some other model. In the example "poll.choice_set", the choice_set # attribute is a ForeignRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "Manager must be accessed via instance" rel_field = self.related.field rel_model = self.related.model # Dynamically create a class that subclasses the related # model's default manager. superclass = self.related.model._default_manager.__class__ class RelatedManager(superclass): def get_query_set(self): return superclass.get_query_set(self).filter(**(self.core_filters)) def add(self, *objs): for obj in objs: setattr(obj, rel_field.name, instance) obj.save() add.alters_data = True def create(self, **kwargs): new_obj = self.model(**kwargs) self.add(new_obj) return new_obj create.alters_data = True # remove() and clear() are only provided if the ForeignKey can have a value of null. if rel_field.null: def remove(self, *objs): val = getattr(instance, rel_field.rel.get_related_field().attname) for obj in objs: # Is obj actually part of this descriptor set? if getattr(obj, rel_field.attname) == val: setattr(obj, rel_field.name, None) obj.save() else: raise rel_field.rel.to.DoesNotExist, "%r is not related to %r." % (obj, instance) remove.alters_data = True def clear(self): for obj in self.all(): setattr(obj, rel_field.name, None) obj.save() clear.alters_data = True manager = RelatedManager() manager.core_filters = {'%s__pk' % rel_field.name: getattr(instance, rel_field.rel.get_related_field().attname)} manager.model = self.related.model return manager def __set__(self, instance, value): if instance is None: raise AttributeError, "Manager must be accessed via instance" manager = self.__get__(instance) # If the foreign key can support nulls, then completely clear the related set. # Otherwise, just move the named objects into the set. if self.related.field.null: manager.clear() manager.add(*value) def create_many_related_manager(superclass): """Creates a manager that subclasses 'superclass' (which is a Manager) and adds behavior for many-to-many related objects.""" class ManyRelatedManager(superclass): def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None, join_table=None, source_col_name=None, target_col_name=None): super(ManyRelatedManager, self).__init__() self.core_filters = core_filters self.model = model self.symmetrical = symmetrical self.instance = instance self.join_table = join_table self.source_col_name = source_col_name self.target_col_name = target_col_name self._pk_val = self.instance._get_pk_val() if self._pk_val is None: raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % model) def get_query_set(self): return superclass.get_query_set(self).filter(**(self.core_filters)) def add(self, *objs): self._add_items(self.source_col_name, self.target_col_name, *objs) # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table if self.symmetrical: self._add_items(self.target_col_name, self.source_col_name, *objs) add.alters_data = True def remove(self, *objs): self._remove_items(self.source_col_name, self.target_col_name, *objs) # If this is a symmetrical m2m relation to self, remove the mirror entry in the m2m table if self.symmetrical: self._remove_items(self.target_col_name, self.source_col_name, *objs) remove.alters_data = True def clear(self): self._clear_items(self.source_col_name) # If this is a symmetrical m2m relation to self, clear the mirror entry in the m2m table if self.symmetrical: self._clear_items(self.target_col_name) clear.alters_data = True def create(self, **kwargs): new_obj = self.model(**kwargs) new_obj.save() self.add(new_obj) return new_obj create.alters_data = True def _add_items(self, source_col_name, target_col_name, *objs): # join_table: name of the m2m link table # source_col_name: the PK colname in join_table for the source object # target_col_name: the PK colname in join_table for the target object # *objs - objects to add. Either object instances, or primary keys of object instances. from django.db import connection # If there aren't any objects, there is nothing to do. if objs: # Check that all the objects are of the right type new_ids = set() for obj in objs: if isinstance(obj, self.model): new_ids.add(obj._get_pk_val()) else: new_ids.add(obj) # Add the newly created or already existing objects to the join table. # First find out which items are already added, to avoid adding them twice cursor = connection.cursor() cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \ (target_col_name, self.join_table, source_col_name, target_col_name, ",".join(['%s'] * len(new_ids))), [self._pk_val] + list(new_ids)) if cursor.rowcount is not None and cursor.rowcount != 0: existing_ids = set([row[0] for row in cursor.fetchmany(cursor.rowcount)]) else: existing_ids = set() # Add the ones that aren't there already for obj_id in (new_ids - existing_ids): cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \ (self.join_table, source_col_name, target_col_name), [self._pk_val, obj_id]) transaction.commit_unless_managed() def _remove_items(self, source_col_name, target_col_name, *objs): # source_col_name: the PK colname in join_table for the source object # target_col_name: the PK colname in join_table for the target object # *objs - objects to remove from django.db import connection # If there aren't any objects, there is nothing to do. if objs: # Check that all the objects are of the right type old_ids = set() for obj in objs: if isinstance(obj, self.model): old_ids.add(obj._get_pk_val()) else: old_ids.add(obj) # Remove the specified objects from the join table cursor = connection.cursor() cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s IN (%s)" % \ (self.join_table, source_col_name, target_col_name, ",".join(['%s'] * len(old_ids))), [self._pk_val] + list(old_ids)) transaction.commit_unless_managed() def _clear_items(self, source_col_name): # source_col_name: the PK colname in join_table for the source object from django.db import connection cursor = connection.cursor() cursor.execute("DELETE FROM %s WHERE %s = %%s" % \ (self.join_table, source_col_name), [self._pk_val]) transaction.commit_unless_managed() return ManyRelatedManager class ManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField pointed at them by # some other model (rather than having a ManyToManyField themselves). # In the example "publication.article_set", the article_set attribute is a # ManyRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "Manager must be accessed via instance" # Dynamically create a class that subclasses the related # model's default manager. rel_model = self.related.model superclass = rel_model._default_manager.__class__ RelatedManager = create_many_related_manager(superclass) qn = backend.quote_name manager = RelatedManager( model=rel_model, core_filters={'%s__pk' % self.related.field.name: instance._get_pk_val()}, instance=instance, symmetrical=False, join_table=qn(self.related.field.m2m_db_table()), source_col_name=qn(self.related.field.m2m_reverse_name()), target_col_name=qn(self.related.field.m2m_column_name()) ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError, "Manager must be accessed via instance" manager = self.__get__(instance) manager.clear() manager.add(*value) class ReverseManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField defined in their # model (rather than having another model pointed *at* them). # In the example "article.publications", the publications attribute is a # ReverseManyRelatedObjectsDescriptor instance. def __init__(self, m2m_field): self.field = m2m_field def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "Manager must be accessed via instance" # Dynamically create a class that subclasses the related # model's default manager. rel_model=self.field.rel.to superclass = rel_model._default_manager.__class__ RelatedManager = create_many_related_manager(superclass) qn = backend.quote_name manager = RelatedManager( model=rel_model, core_filters={'%s__pk' % self.field.related_query_name(): instance._get_pk_val()}, instance=instance, symmetrical=(self.field.rel.symmetrical and instance.__class__ == rel_model), join_table=qn(self.field.m2m_db_table()), source_col_name=qn(self.field.m2m_column_name()), target_col_name=qn(self.field.m2m_reverse_name()) ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError, "Manager must be accessed via instance" manager = self.__get__(instance) manager.clear() manager.add(*value) class ForeignKey(RelatedField, Field): empty_strings_allowed = False def __init__(self, to, to_field=None, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "ForeignKey(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (to, RECURSIVE_RELATIONSHIP_CONSTANT) else: to_field = to_field or to._meta.pk.name kwargs['verbose_name'] = kwargs.get('verbose_name', '') if kwargs.has_key('edit_inline_type'): import warnings warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.") kwargs['edit_inline'] = kwargs.pop('edit_inline_type') kwargs['rel'] = ManyToOneRel(to, to_field, num_in_admin=kwargs.pop('num_in_admin', 3), min_num_in_admin=kwargs.pop('min_num_in_admin', None), max_num_in_admin=kwargs.pop('max_num_in_admin', None), num_extra_on_change=kwargs.pop('num_extra_on_change', 1), edit_inline=kwargs.pop('edit_inline', False), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), raw_id_admin=kwargs.pop('raw_id_admin', False)) Field.__init__(self, **kwargs) self.db_index = True def get_attname(self): return '%s_id' % self.name def get_validator_unique_lookup_type(self): return '%s__%s__exact' % (self.name, self.rel.get_related_field().name) def prepare_field_objs_and_params(self, manipulator, name_prefix): params = {'validator_list': self.validator_list[:], 'member_name': name_prefix + self.attname} if self.rel.raw_id_admin: field_objs = self.get_manipulator_field_objs() params['validator_list'].append(curry(manipulator_valid_rel_key, self, manipulator)) else: if self.radio_admin: field_objs = [oldforms.RadioSelectField] params['ul_class'] = get_ul_class(self.radio_admin) else: if self.null: field_objs = [oldforms.NullSelectField] else: field_objs = [oldforms.SelectField] params['choices'] = self.get_choices_default() return field_objs, params def get_manipulator_field_objs(self): rel_field = self.rel.get_related_field() if self.rel.raw_id_admin and not isinstance(rel_field, AutoField): return rel_field.get_manipulator_field_objs() else: return [oldforms.IntegerField] def get_db_prep_save(self, value): if value == '' or value == None: return None else: return self.rel.get_related_field().get_db_prep_save(value) def flatten_data(self, follow, obj=None): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # (radio_admin=False), we have to check that the length of choices # is *2*, not 1, because SelectFields always have an initial # "blank" value. Otherwise (radio_admin=True), we check that the # length is 1. if not self.blank and (not self.rel.raw_id_admin or self.choices): choice_list = self.get_choices_default() if self.radio_admin and len(choice_list) == 1: return {self.attname: choice_list[0][0]} if not self.radio_admin and len(choice_list) == 2: return {self.attname: choice_list[1][0]} return Field.flatten_data(self, follow, obj) def contribute_to_class(self, cls, name): super(ForeignKey, self).contribute_to_class(cls, name) setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self)) def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), ForeignRelatedObjectsDescriptor(related)) def formfield(self, **kwargs): defaults = {'queryset': self.rel.to._default_manager.all(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.ModelChoiceField(**defaults) class OneToOneField(RelatedField, IntegerField): def __init__(self, to, to_field=None, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "OneToOneField(%r) is invalid. First parameter to OneToOneField must be either a model, a model name, or the string %r" % (to, RECURSIVE_RELATIONSHIP_CONSTANT) else: to_field = to_field or to._meta.pk.name kwargs['verbose_name'] = kwargs.get('verbose_name', '') if kwargs.has_key('edit_inline_type'): import warnings warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.") kwargs['edit_inline'] = kwargs.pop('edit_inline_type') kwargs['rel'] = OneToOneRel(to, to_field, num_in_admin=kwargs.pop('num_in_admin', 0), edit_inline=kwargs.pop('edit_inline', False), related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), raw_id_admin=kwargs.pop('raw_id_admin', False)) kwargs['primary_key'] = True IntegerField.__init__(self, **kwargs) self.db_index = True def get_attname(self): return '%s_id' % self.name def get_validator_unique_lookup_type(self): return '%s__%s__exact' % (self.name, self.rel.get_related_field().name) # TODO: Copied from ForeignKey... putting this in RelatedField adversely affects # ManyToManyField. This works for now. def prepare_field_objs_and_params(self, manipulator, name_prefix): params = {'validator_list': self.validator_list[:], 'member_name': name_prefix + self.attname} if self.rel.raw_id_admin: field_objs = self.get_manipulator_field_objs() params['validator_list'].append(curry(manipulator_valid_rel_key, self, manipulator)) else: if self.radio_admin: field_objs = [oldforms.RadioSelectField] params['ul_class'] = get_ul_class(self.radio_admin) else: if self.null: field_objs = [oldforms.NullSelectField] else: field_objs = [oldforms.SelectField] params['choices'] = self.get_choices_default() return field_objs, params def contribute_to_class(self, cls, name): super(OneToOneField, self).contribute_to_class(cls, name) setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self)) def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), SingleRelatedObjectDescriptor(related)) if not cls._meta.one_to_one_field: cls._meta.one_to_one_field = self def formfield(self, **kwargs): defaults = {'queryset': self.rel.to._default_manager.all(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.ModelChoiceField(**defaults) class ManyToManyField(RelatedField, Field): def __init__(self, to, **kwargs): kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, num_in_admin=kwargs.pop('num_in_admin', 0), related_name=kwargs.pop('related_name', None), filter_interface=kwargs.pop('filter_interface', None), limit_choices_to=kwargs.pop('limit_choices_to', None), raw_id_admin=kwargs.pop('raw_id_admin', False), symmetrical=kwargs.pop('symmetrical', True)) self.db_table = kwargs.pop('db_table', None) if kwargs["rel"].raw_id_admin: kwargs.setdefault("validator_list", []).append(self.isValidIDList) Field.__init__(self, **kwargs) if self.rel.raw_id_admin: msg = gettext_lazy('Separate multiple IDs with commas.') else: msg = gettext_lazy('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg) def get_manipulator_field_objs(self): if self.rel.raw_id_admin: return [oldforms.RawIdAdminField] else: choices = self.get_choices_default() return [curry(oldforms.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)] def get_choices_default(self): return Field.get_choices(self, include_blank=False) def _get_m2m_db_table(self, opts): "Function that can be curried to provide the m2m table name for this relation" if self.db_table: return self.db_table else: return '%s_%s' % (opts.db_table, self.name) def _get_m2m_column_name(self, related): "Function that can be curried to provide the source column name for the m2m table" # If this is an m2m relation to self, avoid the inevitable name clash if related.model == related.parent_model: return 'from_' + related.model._meta.object_name.lower() + '_id' else: return related.model._meta.object_name.lower() + '_id' def _get_m2m_reverse_name(self, related): "Function that can be curried to provide the related column name for the m2m table" # If this is an m2m relation to self, avoid the inevitable name clash if related.model == related.parent_model: return 'to_' + related.parent_model._meta.object_name.lower() + '_id' else: return related.parent_model._meta.object_name.lower() + '_id' def isValidIDList(self, field_data, all_data): "Validates that the value is a valid list of foreign keys" mod = self.rel.to try: pks = map(int, field_data.split(',')) except ValueError: # the CommaSeparatedIntegerField validator will catch this error return objects = mod._default_manager.in_bulk(pks) if len(objects) != len(pks): badkeys = [k for k in pks if k not in objects] raise validators.ValidationError, ngettext("Please enter valid %(self)s IDs. The value %(value)r is invalid.", "Please enter valid %(self)s IDs. The values %(value)r are invalid.", len(badkeys)) % { 'self': self.verbose_name, 'value': len(badkeys) == 1 and badkeys[0] or tuple(badkeys), } def flatten_data(self, follow, obj = None): new_data = {} if obj: instance_ids = [instance._get_pk_val() for instance in getattr(obj, self.name).all()] if self.rel.raw_id_admin: new_data[self.name] = ",".join([str(id) for id in instance_ids]) else: new_data[self.name] = instance_ids else: # In required many-to-many fields with only one available choice, # select that one available choice. if not self.blank and not self.rel.edit_inline and not self.rel.raw_id_admin: choices_list = self.get_choices_default() if len(choices_list) == 1: new_data[self.name] = [choices_list[0][0]] return new_data def contribute_to_class(self, cls, name): super(ManyToManyField, self).contribute_to_class(cls, name) # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self)) # Set up the accessor for the m2m table name for the relation self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta) def contribute_to_related_class(self, cls, related): # m2m relations to self do not have a ManyRelatedObjectsDescriptor, # as it would be redundant - unless the field is non-symmetrical. if related.model != related.parent_model or not self.rel.symmetrical: # Add the descriptor for the m2m relation setattr(cls, related.get_accessor_name(), ManyRelatedObjectsDescriptor(related)) # Set up the accessors for the column names on the m2m table self.m2m_column_name = curry(self._get_m2m_column_name, related) self.m2m_reverse_name = curry(self._get_m2m_reverse_name, related) def set_attributes_from_rel(self): pass def value_from_object(self, obj): "Returns the value of this field in the given model instance." return getattr(obj, self.attname).all() def formfield(self, **kwargs): # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if kwargs.get('initial') is not None: kwargs['initial'] = [i._get_pk_val() for i in kwargs['initial']] defaults = {'queryset' : self.rel.to._default_manager.all(), 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.ModelMultipleChoiceField(**defaults) class ManyToOneRel(object): def __init__(self, to, field_name, num_in_admin=3, min_num_in_admin=None, max_num_in_admin=None, num_extra_on_change=1, edit_inline=False, related_name=None, limit_choices_to=None, lookup_overrides=None, raw_id_admin=False): try: to._meta except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "'to' must be either a model, a model name or the string %r" % RECURSIVE_RELATIONSHIP_CONSTANT self.to, self.field_name = to, field_name self.num_in_admin, self.edit_inline = num_in_admin, edit_inline self.min_num_in_admin, self.max_num_in_admin = min_num_in_admin, max_num_in_admin self.num_extra_on_change, self.related_name = num_extra_on_change, related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.lookup_overrides = lookup_overrides or {} self.raw_id_admin = raw_id_admin self.multiple = True def get_related_field(self): "Returns the Field in the 'to' object to which this relationship is tied." return self.to._meta.get_field(self.field_name) class OneToOneRel(ManyToOneRel): def __init__(self, to, field_name, num_in_admin=0, edit_inline=False, related_name=None, limit_choices_to=None, lookup_overrides=None, raw_id_admin=False): self.to, self.field_name = to, field_name self.num_in_admin, self.edit_inline = num_in_admin, edit_inline self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.lookup_overrides = lookup_overrides or {} self.raw_id_admin = raw_id_admin self.multiple = False class ManyToManyRel(object): def __init__(self, to, num_in_admin=0, related_name=None, filter_interface=None, limit_choices_to=None, raw_id_admin=False, symmetrical=True): self.to = to self.num_in_admin = num_in_admin self.related_name = related_name self.filter_interface = filter_interface if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.edit_inline = False self.raw_id_admin = raw_id_admin self.symmetrical = symmetrical self.multiple = True assert not (self.raw_id_admin and self.filter_interface), "ManyToManyRels may not use both raw_id_admin and filter_interface"
Python
from django.db.models import signals from django.dispatch import dispatcher from django.conf import settings from django.core import validators from django import oldforms from django import newforms as forms from django.core.exceptions import ObjectDoesNotExist from django.utils.functional import curry from django.utils.itercompat import tee from django.utils.text import capfirst from django.utils.translation import gettext, gettext_lazy import datetime, os, time class NOT_PROVIDED: pass # Values for filter_interface. HORIZONTAL, VERTICAL = 1, 2 # The values to use for "blank" in SelectFields. Will be appended to the start of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] BLANK_CHOICE_NONE = [("", "None")] # prepares a value for use in a LIKE query prep_for_like_query = lambda x: str(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_") # returns the <ul> class for a given radio_admin value get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') class FieldDoesNotExist(Exception): pass def manipulator_validator_unique(f, opts, self, field_data, all_data): "Validates that the value is unique for this field." lookup_type = f.get_validator_unique_lookup_type() try: old_obj = self.manager.get(**{lookup_type: field_data}) except ObjectDoesNotExist: return if getattr(self, 'original_object', None) and self.original_object._get_pk_val() == old_obj._get_pk_val(): return raise validators.ValidationError, gettext("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name} # A guide to Field parameters: # # * name: The name of the field specifed in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) class Field(object): # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True # Tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, verbose_name=None, name=None, primary_key=False, maxlength=None, unique=False, blank=False, null=False, db_index=False, core=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, prepopulate_from=None, unique_for_date=None, unique_for_month=None, unique_for_year=None, validator_list=None, choices=None, radio_admin=None, help_text='', db_column=None): self.name = name self.verbose_name = verbose_name self.primary_key = primary_key self.maxlength, self.unique = maxlength, unique self.blank, self.null = blank, null self.core, self.rel, self.default = core, rel, default self.editable = editable self.serialize = serialize self.validator_list = validator_list or [] self.prepopulate_from = prepopulate_from self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month self.unique_for_year = unique_for_year self._choices = choices or [] self.radio_admin = radio_admin self.help_text = help_text self.db_column = db_column # Set db_index to True if the field has a relationship and doesn't explicitly set db_index. self.db_index = db_index # Increase the creation counter, and save our local copy. self.creation_counter = Field.creation_counter Field.creation_counter += 1 def __cmp__(self, other): # This is needed because bisect does not take a comparison function. return cmp(self.creation_counter, other.creation_counter) def to_python(self, value): """ Converts the input value into the expected Python data type, raising validators.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. """ return value def validate_full(self, field_data, all_data): """ Returns a list of errors for this field. This is the main interface, as it encapsulates some basic validation logic used by all fields. Subclasses should implement validate(), not validate_full(). """ if not self.blank and not field_data: return [gettext_lazy('This field is required.')] try: self.validate(field_data, all_data) except validators.ValidationError, e: return e.messages return [] def validate(self, field_data, all_data): """ Raises validators.ValidationError if field_data has any errors. Subclasses should override this to specify field-specific validation logic. This method should assume field_data has already been converted into the appropriate data type by Field.to_python(). """ pass def set_attributes_from_name(self, name): self.name = name self.attname, self.column = self.get_attname_column() self.verbose_name = self.verbose_name or (name and name.replace('_', ' ')) def contribute_to_class(self, cls, name): self.set_attributes_from_name(name) cls._meta.add_field(self) if self.choices: setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_cache_name(self): return '_%s_cache' % self.name def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): "Returns field's value just before saving." return getattr(model_instance, self.attname) def get_db_prep_save(self, value): "Returns field's value prepared for saving into a database." return value def get_db_prep_lookup(self, lookup_type, value): "Returns field's value prepared for database lookup." if lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte', 'month', 'day', 'search'): return [value] elif lookup_type in ('range', 'in'): return value elif lookup_type in ('contains', 'icontains'): return ["%%%s%%" % prep_for_like_query(value)] elif lookup_type == 'iexact': return [prep_for_like_query(value)] elif lookup_type in ('startswith', 'istartswith'): return ["%s%%" % prep_for_like_query(value)] elif lookup_type in ('endswith', 'iendswith'): return ["%%%s" % prep_for_like_query(value)] elif lookup_type == 'isnull': return [] elif lookup_type == 'year': try: value = int(value) except ValueError: raise ValueError("The __year lookup type requires an integer argument") return ['%s-01-01 00:00:00' % value, '%s-12-31 23:59:59.999999' % value] raise TypeError("Field has invalid lookup: %s" % lookup_type) def has_default(self): "Returns a boolean of whether this field has a default value." return self.default is not NOT_PROVIDED def get_default(self): "Returns the default value for this field." if self.default is not NOT_PROVIDED: if callable(self.default): return self.default() return self.default if not self.empty_strings_allowed or self.null: return None return "" def get_manipulator_field_names(self, name_prefix): """ Returns a list of field names that this object adds to the manipulator. """ return [name_prefix + self.name] def prepare_field_objs_and_params(self, manipulator, name_prefix): params = {'validator_list': self.validator_list[:]} if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter. params['maxlength'] = self.maxlength if self.choices: if self.radio_admin: field_objs = [oldforms.RadioSelectField] params['ul_class'] = get_ul_class(self.radio_admin) else: field_objs = [oldforms.SelectField] params['choices'] = self.get_choices_default() else: field_objs = self.get_manipulator_field_objs() return (field_objs, params) def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): """ Returns a list of oldforms.FormField instances for this field. It calculates the choices at runtime, not at compile time. name_prefix is a prefix to prepend to the "field_name" argument. rel is a boolean specifying whether this field is in a related context. """ field_objs, params = self.prepare_field_objs_and_params(manipulator, name_prefix) # Add the "unique" validator(s). for field_name_list in opts.unique_together: if field_name_list[0] == self.name: params['validator_list'].append(getattr(manipulator, 'isUnique%s' % '_'.join(field_name_list))) # Add the "unique for..." validator(s). if self.unique_for_date: params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_date))) if self.unique_for_month: params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_month))) if self.unique_for_year: params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_year))) if self.unique or (self.primary_key and not rel): params['validator_list'].append(curry(manipulator_validator_unique, self, opts, manipulator)) # Only add is_required=True if the field cannot be blank. Primary keys # are a special case, and fields in a related context should set this # as False, because they'll be caught by a separate validator -- # RequiredIfOtherFieldGiven. params['is_required'] = not self.blank and not self.primary_key and not rel # BooleanFields (CheckboxFields) are a special case. They don't take # is_required. if isinstance(self, BooleanField): del params['is_required'] # If this field is in a related context, check whether any other fields # in the related object have core=True. If so, add a validator -- # RequiredIfOtherFieldsGiven -- to this FormField. if rel and not self.blank and not isinstance(self, AutoField) and not isinstance(self, FileField): # First, get the core fields, if any. core_field_names = [] for f in opts.fields: if f.core and f != self: core_field_names.extend(f.get_manipulator_field_names(name_prefix)) # Now, if there are any, add the validator to this FormField. if core_field_names: params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, gettext_lazy("This field is required."))) # Finally, add the field_names. field_names = self.get_manipulator_field_names(name_prefix) return [man(field_name=field_names[i], **params) for i, man in enumerate(field_objs)] def get_validator_unique_lookup_type(self): return '%s__exact' % self.name def get_manipulator_new_data(self, new_data, rel=False): """ Given the full new_data dictionary (from the manipulator), returns this field's data. """ if rel: return new_data.get(self.name, [self.get_default()])[0] val = new_data.get(self.name, self.get_default()) if not self.empty_strings_allowed and val == '' and self.null: val = None return val def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): "Returns a list of tuples used as SelectField choices for this field." first_choice = include_blank and blank_choice or [] if self.choices: return first_choice + list(self.choices) rel_model = self.rel.to if hasattr(self.rel, 'get_related_field'): lst = [(getattr(x, self.rel.get_related_field().attname), str(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] else: lst = [(x._get_pk_val(), str(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] return first_choice + lst def get_choices_default(self): if self.radio_admin: return self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE) else: return self.get_choices() def _get_val_from_obj(self, obj): if obj: return getattr(obj, self.attname) else: return self.get_default() def flatten_data(self, follow, obj=None): """ Returns a dictionary mapping the field's manipulator field names to its "flattened" string values for the admin view. obj is the instance to extract the values from. """ return {self.attname: self._get_val_from_obj(obj)} def get_follow(self, override=None): if override != None: return override else: return self.editable def bind(self, fieldmapping, original, bound_field_class): return bound_field_class(self, fieldmapping, original) def _get_choices(self): if hasattr(self._choices, 'next'): choices, self._choices = tee(self._choices) return choices else: return self._choices choices = property(_get_choices) def formfield(self, **kwargs): "Returns a django.newforms.Field instance for this database Field." defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.CharField(**defaults) def value_from_object(self, obj): "Returns the value of this field in the given model instance." return getattr(obj, self.attname) class AutoField(Field): empty_strings_allowed = False def __init__(self, *args, **kwargs): assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__ kwargs['blank'] = True Field.__init__(self, *args, **kwargs) def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise validators.ValidationError, gettext("This value must be an integer.") def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): if not rel: return [] # Don't add a FormField unless it's in a related context. return Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) def get_manipulator_field_objs(self): return [oldforms.HiddenField] def get_manipulator_new_data(self, new_data, rel=False): # Never going to be called # Not in main change pages # ignored in related context if not rel: return None return Field.get_manipulator_new_data(self, new_data, rel) def contribute_to_class(self, cls, name): assert not cls._meta.has_auto_field, "A model can't have more than one AutoField." super(AutoField, self).contribute_to_class(cls, name) cls._meta.has_auto_field = True def formfield(self, **kwargs): return None class BooleanField(Field): def __init__(self, *args, **kwargs): kwargs['blank'] = True Field.__init__(self, *args, **kwargs) def to_python(self, value): if value in (True, False): return value if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False raise validators.ValidationError, gettext("This value must be either True or False.") def get_manipulator_field_objs(self): return [oldforms.CheckboxField] def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.BooleanField(**defaults) class CharField(Field): def get_manipulator_field_objs(self): return [oldforms.TextField] def to_python(self, value): if isinstance(value, basestring): return value if value is None: if self.null: return value else: raise validators.ValidationError, gettext_lazy("This field cannot be null.") return str(value) def formfield(self, **kwargs): defaults = {'max_length': self.maxlength, 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.CharField(**defaults) # TODO: Maybe move this into contrib, because it's specialized. class CommaSeparatedIntegerField(CharField): def get_manipulator_field_objs(self): return [oldforms.CommaSeparatedIntegerField] class DateField(Field): empty_strings_allowed = False def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add #HACKs : auto_now_add/auto_now should be done as a default or a pre_save. if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True Field.__init__(self, verbose_name, name, **kwargs) def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value validators.isValidANSIDate(value, None) try: return datetime.date(*time.strptime(value, '%Y-%m-%d')[:3]) except ValueError: raise validators.ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.') def get_db_prep_lookup(self, lookup_type, value): if lookup_type == 'range': value = [str(v) for v in value] elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte') and hasattr(value, 'strftime'): value = value.strftime('%Y-%m-%d') else: value = str(value) return Field.get_db_prep_lookup(self, lookup_type, value) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now() setattr(model_instance, self.attname, value) return value else: return super(DateField, self).pre_save(model_instance, add) def contribute_to_class(self, cls, name): super(DateField,self).contribute_to_class(cls, name) if not self.null: setattr(cls, 'get_next_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) setattr(cls, 'get_previous_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) # Needed because of horrible auto_now[_add] behaviour wrt. editable def get_follow(self, override=None): if override != None: return override else: return self.editable or self.auto_now or self.auto_now_add def get_db_prep_save(self, value): # Casts dates into string format for entry into database. if value is not None: value = value.strftime('%Y-%m-%d') return Field.get_db_prep_save(self, value) def get_manipulator_field_objs(self): return [oldforms.DateField] def flatten_data(self, follow, obj=None): val = self._get_val_from_obj(obj) return {self.attname: (val is not None and val.strftime("%Y-%m-%d") or '')} def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.DateField(**defaults) class DateTimeField(DateField): def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): return datetime.datetime(value.year, value.month, value.day) try: # Seconds are optional, so try converting seconds first. return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6]) except ValueError: try: # Try without seconds. return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5]) except ValueError: # Try without hour/minutes/seconds. try: return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3]) except ValueError: raise validators.ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.') def get_db_prep_save(self, value): # Casts dates into string format for entry into database. if value is not None: # MySQL will throw a warning if microseconds are given, because it # doesn't support microseconds. if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): value = value.replace(microsecond=0) value = str(value) return Field.get_db_prep_save(self, value) def get_db_prep_lookup(self, lookup_type, value): if lookup_type == 'range': value = [str(v) for v in value] else: value = str(value) return Field.get_db_prep_lookup(self, lookup_type, value) def get_manipulator_field_objs(self): return [oldforms.DateField, oldforms.TimeField] def get_manipulator_field_names(self, name_prefix): return [name_prefix + self.name + '_date', name_prefix + self.name + '_time'] def get_manipulator_new_data(self, new_data, rel=False): date_field, time_field = self.get_manipulator_field_names('') if rel: d = new_data.get(date_field, [None])[0] t = new_data.get(time_field, [None])[0] else: d = new_data.get(date_field, None) t = new_data.get(time_field, None) if d is not None and t is not None: return datetime.datetime.combine(d, t) return self.get_default() def flatten_data(self,follow, obj = None): val = self._get_val_from_obj(obj) date_field, time_field = self.get_manipulator_field_names('') return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''), time_field: (val is not None and val.strftime("%H:%M:%S") or '')} def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.DateTimeField(**defaults) class EmailField(CharField): def __init__(self, *args, **kwargs): kwargs['maxlength'] = 75 CharField.__init__(self, *args, **kwargs) def get_internal_type(self): return "CharField" def get_manipulator_field_objs(self): return [oldforms.EmailField] def validate(self, field_data, all_data): validators.isValidEmail(field_data, all_data) def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.EmailField(**defaults) class FileField(Field): def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs): self.upload_to = upload_to Field.__init__(self, verbose_name, name, **kwargs) def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) if not self.blank: if rel: # This validator makes sure FileFields work in a related context. class RequiredFileField(object): def __init__(self, other_field_names, other_file_field_name): self.other_field_names = other_field_names self.other_file_field_name = other_file_field_name self.always_test = True def __call__(self, field_data, all_data): if not all_data.get(self.other_file_field_name, False): c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, gettext_lazy("This field is required.")) c(field_data, all_data) # First, get the core fields, if any. core_field_names = [] for f in opts.fields: if f.core and f != self: core_field_names.extend(f.get_manipulator_field_names(name_prefix)) # Now, if there are any, add the validator to this FormField. if core_field_names: field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name)) else: v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, gettext_lazy("This field is required.")) v.always_test = True field_list[0].validator_list.append(v) field_list[0].is_required = field_list[1].is_required = False # If the raw path is passed in, validate it's under the MEDIA_ROOT. def isWithinMediaRoot(field_data, all_data): f = os.path.abspath(os.path.join(settings.MEDIA_ROOT, field_data)) if not f.startswith(os.path.abspath(os.path.normpath(settings.MEDIA_ROOT))): raise validators.ValidationError, _("Enter a valid filename.") field_list[1].validator_list.append(isWithinMediaRoot) return field_list def contribute_to_class(self, cls, name): super(FileField, self).contribute_to_class(cls, name) setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self)) setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self)) setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self)) setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents, save=True: instance._save_FIELD_file(self, filename, raw_contents, save)) dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls) def delete_file(self, instance): if getattr(instance, self.attname): file_name = getattr(instance, 'get_%s_filename' % self.name)() # If the file exists and no other object of this type references it, # delete it from the filesystem. if os.path.exists(file_name) and \ not instance.__class__._default_manager.filter(**{'%s__exact' % self.name: getattr(instance, self.attname)}): os.remove(file_name) def get_manipulator_field_objs(self): return [oldforms.FileUploadField, oldforms.HiddenField] def get_manipulator_field_names(self, name_prefix): return [name_prefix + self.name + '_file', name_prefix + self.name] def save_file(self, new_data, new_object, original_object, change, rel, save=True): upload_field_name = self.get_manipulator_field_names('')[0] if new_data.get(upload_field_name, False): func = getattr(new_object, 'save_%s_file' % self.name) if rel: func(new_data[upload_field_name][0]["filename"], new_data[upload_field_name][0]["content"], save) else: func(new_data[upload_field_name]["filename"], new_data[upload_field_name]["content"], save) def get_directory_name(self): return os.path.normpath(datetime.datetime.now().strftime(self.upload_to)) def get_filename(self, filename): from django.utils.text import get_valid_filename f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename))) return os.path.normpath(f) class FilePathField(Field): def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs): self.path, self.match, self.recursive = path, match, recursive Field.__init__(self, verbose_name, name, **kwargs) def get_manipulator_field_objs(self): return [curry(oldforms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)] class FloatField(Field): empty_strings_allowed = False def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places Field.__init__(self, verbose_name, name, **kwargs) def get_manipulator_field_objs(self): return [curry(oldforms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)] class ImageField(FileField): def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field FileField.__init__(self, verbose_name, name, **kwargs) def get_manipulator_field_objs(self): return [oldforms.ImageUploadField, oldforms.HiddenField] def contribute_to_class(self, cls, name): super(ImageField, self).contribute_to_class(cls, name) # Add get_BLAH_width and get_BLAH_height methods, but only if the # image field doesn't have width and height cache fields. if not self.width_field: setattr(cls, 'get_%s_width' % self.name, curry(cls._get_FIELD_width, field=self)) if not self.height_field: setattr(cls, 'get_%s_height' % self.name, curry(cls._get_FIELD_height, field=self)) def save_file(self, new_data, new_object, original_object, change, rel, save=True): FileField.save_file(self, new_data, new_object, original_object, change, rel, save) # If the image has height and/or width field(s) and they haven't # changed, set the width and/or height field(s) back to their original # values. if change and (self.width_field or self.height_field) and save: if self.width_field: setattr(new_object, self.width_field, getattr(original_object, self.width_field)) if self.height_field: setattr(new_object, self.height_field, getattr(original_object, self.height_field)) new_object.save() class IntegerField(Field): empty_strings_allowed = False def get_manipulator_field_objs(self): return [oldforms.IntegerField] def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.IntegerField(**defaults) class IPAddressField(Field): def __init__(self, *args, **kwargs): kwargs['maxlength'] = 15 Field.__init__(self, *args, **kwargs) def get_manipulator_field_objs(self): return [oldforms.IPAddressField] def validate(self, field_data, all_data): validators.isValidIPAddress4(field_data, None) class NullBooleanField(Field): def __init__(self, *args, **kwargs): kwargs['null'] = True Field.__init__(self, *args, **kwargs) def to_python(self, value): if value in (None, True, False): return value if value in ('None'): return None if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False raise validators.ValidationError, gettext("This value must be either None, True or False.") def get_manipulator_field_objs(self): return [oldforms.NullBooleanField] class PhoneNumberField(IntegerField): def get_manipulator_field_objs(self): return [oldforms.PhoneNumberField] def validate(self, field_data, all_data): validators.isValidPhone(field_data, all_data) def formfield(self, **kwargs): from django.contrib.localflavor.usa.forms import USPhoneNumberField defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return USPhoneNumberField(**defaults) class PositiveIntegerField(IntegerField): def get_manipulator_field_objs(self): return [oldforms.PositiveIntegerField] class PositiveSmallIntegerField(IntegerField): def get_manipulator_field_objs(self): return [oldforms.PositiveSmallIntegerField] class SlugField(Field): def __init__(self, *args, **kwargs): kwargs['maxlength'] = kwargs.get('maxlength', 50) kwargs.setdefault('validator_list', []).append(validators.isSlug) # Set db_index=True unless it's been set manually. if not kwargs.has_key('db_index'): kwargs['db_index'] = True Field.__init__(self, *args, **kwargs) def get_manipulator_field_objs(self): return [oldforms.TextField] class SmallIntegerField(IntegerField): def get_manipulator_field_objs(self): return [oldforms.SmallIntegerField] class TextField(Field): def get_manipulator_field_objs(self): return [oldforms.LargeTextField] def formfield(self, **kwargs): defaults = {'required': not self.blank, 'widget': forms.Textarea, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.CharField(**defaults) class TimeField(Field): empty_strings_allowed = False def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs['editable'] = False Field.__init__(self, verbose_name, name, **kwargs) def get_db_prep_lookup(self, lookup_type, value): if lookup_type == 'range': value = [str(v) for v in value] else: value = str(value) return Field.get_db_prep_lookup(self, lookup_type, value) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super(TimeField, self).pre_save(model_instance, add) def get_db_prep_save(self, value): # Casts dates into string format for entry into database. if value is not None: # MySQL will throw a warning if microseconds are given, because it # doesn't support microseconds. if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): value = value.replace(microsecond=0) value = str(value) return Field.get_db_prep_save(self, value) def get_manipulator_field_objs(self): return [oldforms.TimeField] def flatten_data(self,follow, obj = None): val = self._get_val_from_obj(obj) return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')} def formfield(self, **kwargs): defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.TimeField(**defaults) class URLField(CharField): def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): kwargs['maxlength'] = kwargs.get('maxlength', 200) if verify_exists: kwargs.setdefault('validator_list', []).append(validators.isExistingURL) self.verify_exists = verify_exists CharField.__init__(self, verbose_name, name, **kwargs) def get_manipulator_field_objs(self): return [oldforms.URLField] def get_internal_type(self): return "CharField" def formfield(self, **kwargs): defaults = {'required': not self.blank, 'verify_exists': self.verify_exists, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.URLField(**defaults) class USStateField(Field): def get_manipulator_field_objs(self): return [oldforms.USStateField] class XMLField(TextField): def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs): self.schema_path = schema_path Field.__init__(self, verbose_name, name, **kwargs) def get_internal_type(self): return "TextField" def get_manipulator_field_objs(self): return [curry(oldforms.XMLLargeTextField, schema_path=self.schema_path)] class OrderingField(IntegerField): empty_strings_allowed=False def __init__(self, with_respect_to, **kwargs): self.wrt = with_respect_to kwargs['null'] = True IntegerField.__init__(self, **kwargs ) def get_internal_type(self): return "IntegerField" def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): return [oldforms.HiddenField(name_prefix + self.name)]
Python
from django.db.models.query import QuerySet, EmptyQuerySet from django.dispatch import dispatcher from django.db.models import signals from django.db.models.fields import FieldDoesNotExist # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERATOR_CHUNK_SIZE = 100 def ensure_default_manager(sender): cls = sender if not hasattr(cls, '_default_manager'): # Create the default manager, if needed. try: cls._meta.get_field('objects') raise ValueError, "Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__ except FieldDoesNotExist: pass cls.add_to_class('objects', Manager()) dispatcher.connect(ensure_default_manager, signal=signals.class_prepared) class Manager(object): # Tracks each time a Manager instance is created. Used to retain order. creation_counter = 0 def __init__(self): super(Manager, self).__init__() # Increase the creation counter, and save our local copy. self.creation_counter = Manager.creation_counter Manager.creation_counter += 1 self.model = None def contribute_to_class(self, model, name): # TODO: Use weakref because of possible memory leak / circular reference. self.model = model setattr(model, name, ManagerDescriptor(self)) if not hasattr(model, '_default_manager') or self.creation_counter < model._default_manager.creation_counter: model._default_manager = self ####################### # PROXIES TO QUERYSET # ####################### def get_empty_query_set(self): return EmptyQuerySet(self.model) def get_query_set(self): """Returns a new QuerySet object. Subclasses can override this method to easily customise the behaviour of the Manager. """ return QuerySet(self.model) def none(self): return self.get_empty_query_set() def all(self): return self.get_query_set() def count(self): return self.get_query_set().count() def dates(self, *args, **kwargs): return self.get_query_set().dates(*args, **kwargs) def distinct(self, *args, **kwargs): return self.get_query_set().distinct(*args, **kwargs) def extra(self, *args, **kwargs): return self.get_query_set().extra(*args, **kwargs) def get(self, *args, **kwargs): return self.get_query_set().get(*args, **kwargs) def get_or_create(self, **kwargs): return self.get_query_set().get_or_create(**kwargs) def create(self, **kwargs): return self.get_query_set().create(**kwargs) def filter(self, *args, **kwargs): return self.get_query_set().filter(*args, **kwargs) def complex_filter(self, *args, **kwargs): return self.get_query_set().complex_filter(*args, **kwargs) def exclude(self, *args, **kwargs): return self.get_query_set().exclude(*args, **kwargs) def in_bulk(self, *args, **kwargs): return self.get_query_set().in_bulk(*args, **kwargs) def iterator(self, *args, **kwargs): return self.get_query_set().iterator(*args, **kwargs) def latest(self, *args, **kwargs): return self.get_query_set().latest(*args, **kwargs) def order_by(self, *args, **kwargs): return self.get_query_set().order_by(*args, **kwargs) def select_related(self, *args, **kwargs): return self.get_query_set().select_related(*args, **kwargs) def values(self, *args, **kwargs): return self.get_query_set().values(*args, **kwargs) class ManagerDescriptor(object): # This class ensures managers aren't accessible via model instances. # For example, Poll.objects works, but poll_obj.objects raises AttributeError. def __init__(self, manager): self.manager = manager def __get__(self, instance, type=None): if instance != None: raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__ return self.manager
Python
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core import validators from django.db import backend, connection from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models from django.db.models.query import Q from django.db.models.manager import Manager from django.db.models.base import Model, AdminOptions from django.db.models.fields import * from django.db.models.fields.related import ForeignKey, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel, TABULAR, STACKED from django.db.models.fields.generic import GenericRelation, GenericRel, GenericForeignKey from django.db.models import signals from django.utils.functional import curry from django.utils.text import capfirst # Admin stages. ADD, CHANGE, BOTH = 1, 2, 3 # Decorator. Takes a function that returns a tuple in this format: # (viewname, viewargs, viewkwargs) # Returns a function that calls urlresolvers.reverse() on that data, to return # the URL for those parameters. def permalink(func): from django.core.urlresolvers import reverse def inner(*args, **kwargs): bits = func(*args, **kwargs) viewname = bits[0] return reverse(bits[0], None, *bits[1:3]) return inner class LazyDate(object): """ Use in limit_choices_to to compare the field to dates calculated at run time instead of when the model is loaded. For example:: ... limit_choices_to = {'date__gt' : models.LazyDate(days=-3)} ... which will limit the choices to dates greater than three days ago. """ def __init__(self, **kwargs): self.delta = datetime.timedelta(**kwargs) def __str__(self): return str(self.__get_value__()) def __repr__(self): return "<LazyDate: %s>" % self.delta def __get_value__(self): return (datetime.datetime.now() + self.delta).date() def __getattr__(self, attr): if attr == 'delta': # To fix ticket #3377. Note that normal accesses to LazyDate.delta # (after construction) will still work, because they don't go # through __getattr__). This is mainly needed for unpickling. raise AttributeError return getattr(self.__get_value__(), attr)
Python
"Utilities for loading models and the modules that contain them." from django.conf import settings from django.core.exceptions import ImproperlyConfigured import sys import os __all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models') _app_list = [] # Cache of installed apps. # Entry is not placed in app_list cache until entire app is loaded. _app_models = {} # Dictionary of models against app label # Each value is a dictionary of model name: model class # Applabel and Model entry exists in cache when individual model is loaded. _app_errors = {} # Dictionary of errors that were experienced when loading the INSTALLED_APPS # Key is the app_name of the model, value is the exception that was raised # during model loading. _loaded = False # Has the contents of settings.INSTALLED_APPS been loaded? # i.e., has get_apps() been called? def get_apps(): "Returns a list of all installed modules that contain models." global _app_list global _loaded if not _loaded: _loaded = True for app_name in settings.INSTALLED_APPS: try: load_app(app_name) except Exception, e: # Problem importing the app _app_errors[app_name] = e return _app_list def get_app(app_label, emptyOK=False): "Returns the module containing the models for the given app_label. If the app has no models in it and 'emptyOK' is True, returns None." get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish. for app_name in settings.INSTALLED_APPS: if app_label == app_name.split('.')[-1]: mod = load_app(app_name) if mod is None: if emptyOK: return None else: return mod raise ImproperlyConfigured, "App with label %s could not be found" % app_label def load_app(app_name): "Loads the app with the provided fully qualified name, and returns the model module." global _app_list mod = __import__(app_name, {}, {}, ['models']) if not hasattr(mod, 'models'): return None if mod.models not in _app_list: _app_list.append(mod.models) return mod.models def get_app_errors(): "Returns the map of known problems with the INSTALLED_APPS" global _app_errors get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish. return _app_errors def get_models(app_mod=None): """ Given a module containing models, returns a list of the models. Otherwise returns a list of all installed models. """ app_list = get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish. if app_mod: return _app_models.get(app_mod.__name__.split('.')[-2], {}).values() else: model_list = [] for app_mod in app_list: model_list.extend(get_models(app_mod)) return model_list def get_model(app_label, model_name, seed_cache=True): """ Returns the model matching the given app_label and case-insensitive model_name. Returns None if no model is found. """ if seed_cache: get_apps() try: model_dict = _app_models[app_label] except KeyError: return None try: return model_dict[model_name.lower()] except KeyError: return None def register_models(app_label, *models): """ Register a set of models as belonging to an app. """ for model in models: # Store as 'name: model' pair in a dictionary # in the _app_models dictionary model_name = model._meta.object_name.lower() model_dict = _app_models.setdefault(app_label, {}) if model_dict.has_key(model_name): # The same model may be imported via different paths (e.g. # appname.models and project.appname.models). We use the source # filename as a means to detect identity. fname1 = os.path.abspath(sys.modules[model.__module__].__file__) fname2 = os.path.abspath(sys.modules[model_dict[model_name].__module__].__file__) # Since the filename extension could be .py the first time and .pyc # or .pyo the second time, ignore the extension when comparing. if os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]: continue model_dict[model_name] = model
Python
""" This module implements a transaction manager that can be used to define transaction handling in a request or view function. It is used by transaction control middleware and decorators. The transaction manager can be in managed or in auto state. Auto state means the system is using a commit-on-save strategy (actually it's more like commit-on-change). As soon as the .save() or .delete() (or related) methods are called, a commit is made. Managed transactions don't do those commits, but will need some kind of manual or implicit commits or rollbacks. """ try: import thread except ImportError: import dummy_thread as thread from django.db import connection from django.conf import settings class TransactionManagementError(Exception): """ This exception is thrown when something bad happens with transaction management. """ pass # The state is a dictionary of lists. The key to the dict is the current # thread and the list is handled as a stack of values. state = {} # The dirty flag is set by *_unless_managed functions to denote that the # code under transaction management has changed things to require a # database commit. dirty = {} def enter_transaction_management(): """ Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or from the settings, if there is no surrounding block (dirty is always false when no current block is running). """ thread_ident = thread.get_ident() if state.has_key(thread_ident) and state[thread_ident]: state[thread_ident].append(state[thread_ident][-1]) else: state[thread_ident] = [] state[thread_ident].append(settings.TRANSACTIONS_MANAGED) if not dirty.has_key(thread_ident): dirty[thread_ident] = False def leave_transaction_management(): """ Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) """ thread_ident = thread.get_ident() if state.has_key(thread_ident) and state[thread_ident]: del state[thread_ident][-1] else: raise TransactionManagementError("This code isn't under transaction management") if dirty.get(thread_ident, False): rollback() raise TransactionManagementError("Transaction managed block ended with pending COMMIT/ROLLBACK") dirty[thread_ident] = False def is_dirty(): """ Returns True if the current transaction requires a commit for changes to happen. """ return dirty.get(thread.get_ident(), False) def set_dirty(): """ Sets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether there are open changes waiting for commit. """ thread_ident = thread.get_ident() if dirty.has_key(thread_ident): dirty[thread_ident] = True else: raise TransactionManagementError("This code isn't under transaction management") def set_clean(): """ Resets a dirty flag for the current thread and code streak. This can be used to decide in a managed block of code to decide whether a commit or rollback should happen. """ thread_ident = thread.get_ident() if dirty.has_key(thread_ident): dirty[thread_ident] = False else: raise TransactionManagementError("This code isn't under transaction management") def is_managed(): """ Checks whether the transaction manager is in manual or in auto state. """ thread_ident = thread.get_ident() if state.has_key(thread_ident): if state[thread_ident]: return state[thread_ident][-1] return settings.TRANSACTIONS_MANAGED def managed(flag=True): """ Puts the transaction manager into a manual state: managed transactions have to be committed explicitly by the user. If you switch off transaction management and there is a pending commit/rollback, the data will be commited. """ thread_ident = thread.get_ident() top = state.get(thread_ident, None) if top: top[-1] = flag if not flag and is_dirty(): connection._commit() set_clean() else: raise TransactionManagementError("This code isn't under transaction management") def commit_unless_managed(): """ Commits changes if the system is not in managed transaction mode. """ if not is_managed(): connection._commit() else: set_dirty() def rollback_unless_managed(): """ Rolls back changes if the system is not in managed transaction mode. """ if not is_managed(): connection._rollback() else: set_dirty() def commit(): """ Does the commit itself and resets the dirty flag. """ connection._commit() set_clean() def rollback(): """ This function does the rollback itself and resets the dirty flag. """ connection._rollback() set_clean() ############## # DECORATORS # ############## def autocommit(func): """ Decorator that activates commit on save. This is Django's default behavior; this decorator is useful if you globally activated transaction management in your settings file and want the default behavior in some view functions. """ def _autocommit(*args, **kw): try: enter_transaction_management() managed(False) return func(*args, **kw) finally: leave_transaction_management() return _autocommit def commit_on_success(func): """ This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in web apps. """ def _commit_on_success(*args, **kw): try: enter_transaction_management() managed(True) try: res = func(*args, **kw) except Exception, e: if is_dirty(): rollback() raise else: if is_dirty(): commit() return res finally: leave_transaction_management() return _commit_on_success def commit_manually(func): """ Decorator that activates manual transaction control. It just disables automatic transaction control and doesn't do any commit/rollback of its own -- it's up to the user to call the commit and rollback functions themselves. """ def _commit_manually(*args, **kw): try: enter_transaction_management() managed(True) return func(*args, **kw) finally: leave_transaction_management() return _commit_manually
Python
from django.conf import settings from django.core import signals from django.dispatch import dispatcher __all__ = ('backend', 'connection', 'DatabaseError') if not settings.DATABASE_ENGINE: settings.DATABASE_ENGINE = 'dummy' try: backend = __import__('django.db.backends.%s.base' % settings.DATABASE_ENGINE, {}, {}, ['']) except ImportError, e: # The database backend wasn't found. Display a helpful error message # listing all possible database backends. from django.core.exceptions import ImproperlyConfigured import os backend_dir = os.path.join(__path__[0], 'backends') available_backends = [f for f in os.listdir(backend_dir) if not f.startswith('_') and not f.startswith('.') and not f.endswith('.py') and not f.endswith('.pyc')] available_backends.sort() if settings.DATABASE_ENGINE not in available_backends: raise ImproperlyConfigured, "%r isn't an available database backend. Available options are: %s" % \ (settings.DATABASE_ENGINE, ", ".join(map(repr, available_backends))) else: raise # If there's some other error, this must be an error in Django itself. get_introspection_module = lambda: __import__('django.db.backends.%s.introspection' % settings.DATABASE_ENGINE, {}, {}, ['']) get_creation_module = lambda: __import__('django.db.backends.%s.creation' % settings.DATABASE_ENGINE, {}, {}, ['']) runshell = lambda: __import__('django.db.backends.%s.client' % settings.DATABASE_ENGINE, {}, {}, ['']).runshell() connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS) DatabaseError = backend.DatabaseError # Register an event that closes the database connection # when a Django request is finished. dispatcher.connect(connection.close, signal=signals.request_finished) # Register an event that resets connection.queries # when a Django request is started. def reset_queries(): connection.queries = [] dispatcher.connect(reset_queries, signal=signals.request_started) # Register an event that rolls back the connection # when a Django request has an exception. def _rollback_on_exception(): from django.db import transaction transaction.rollback_unless_managed() dispatcher.connect(_rollback_on_exception, signal=signals.got_request_exception)
Python
# Default Django settings. Override these with settings in the module # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. gettext_noop = lambda s: s #################### # CORE # #################### DEBUG = False TEMPLATE_DEBUG = False # Whether to use the "Etag" header. This saves bandwidth but slows down performance. USE_ETAGS = False # People who get code error notifications. # In the format (('Full Name', 'email@domain.com'), ('Full Name', 'anotheremail@domain.com')) ADMINS = () # Tuple of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = () # Local time zone for this installation. All choices can be found here: # http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box. The language name # should be the utf-8 encoded local name for the language. LANGUAGES = ( ('ar', gettext_noop('Arabic')), ('bn', gettext_noop('Bengali')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('es', gettext_noop('Spanish')), ('es_AR', gettext_noop('Argentinean Spanish')), ('fi', gettext_noop('Finnish')), ('fr', gettext_noop('French')), ('gl', gettext_noop('Galician')), ('hu', gettext_noop('Hungarian')), ('he', gettext_noop('Hebrew')), ('is', gettext_noop('Icelandic')), ('it', gettext_noop('Italian')), ('ja', gettext_noop('Japanese')), ('kn', gettext_noop('Kannada')), ('lv', gettext_noop('Latvian')), ('mk', gettext_noop('Macedonian')), ('nl', gettext_noop('Dutch')), ('no', gettext_noop('Norwegian')), ('pl', gettext_noop('Polish')), ('pt', gettext_noop('Portugese')), ('pt-br', gettext_noop('Brazilian')), ('ro', gettext_noop('Romanian')), ('ru', gettext_noop('Russian')), ('sk', gettext_noop('Slovak')), ('sl', gettext_noop('Slovenian')), ('sr', gettext_noop('Serbian')), ('sv', gettext_noop('Swedish')), ('ta', gettext_noop('Tamil')), ('te', gettext_noop('Telugu')), ('tr', gettext_noop('Turkish')), ('uk', gettext_noop('Ukrainian')), ('zh-cn', gettext_noop('Simplified Chinese')), ('zh-tw', gettext_noop('Traditional Chinese')), ) # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ("he", "ar") # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Not-necessarily-technical managers of the site. They get broken link # notifications and other various e-mails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET = 'utf-8' # E-mail address that error messages come from. SERVER_EMAIL = 'root@localhost' # Whether to send broken-link e-mails. SEND_BROKEN_LINK_EMAILS = False # Database connection info. DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. DATABASE_OPTIONS = {} # Set to empty dictionary for default. # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 25 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' # List of strings representing installed apps. INSTALLED_APPS = () # List of locations of the template source files, in search order. TEMPLATE_DIRS = () # List of callables that know how to import templates from various sources. # See the comments in django/core/template/loader.py for interface # documentation. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) # List of processors used by RequestContext to populate the context. # Each one should be a callable that takes the request object as its # only parameter and returns a dictionary to add to the context. TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', # 'django.core.context_processors.request', ) # Output to use in template system for invalid (e.g. misspelled) variables. TEMPLATE_STRING_IF_INVALID = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Default e-mail address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = ( # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search') # ) DISALLOWED_USER_AGENTS = () ABSOLUTE_URL_OVERRIDES = {} # Tuple of strings representing allowed prefixes for the {% ssi %} tag. # Example: ('/home/html', '/var/www') ALLOWED_INCLUDE_ROOTS = () # If this is a admin settings module, this should be a list of # settings modules (in the format 'foo.bar.baz') for which this admin # is an admin. ADMIN_FOR = () # 404s that may be ignored. IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf') IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php') # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = '' # Path to the "jing" executable -- needed to validate XMLFields JING_PATH = "/usr/bin/jing" # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = '' # Default formatting for date objects. See all available format strings here: # http://www.djangoproject.com/documentation/templates/#now DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here: # http://www.djangoproject.com/documentation/templates/#now DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here: # http://www.djangoproject.com/documentation/templates/#now TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # http://www.djangoproject.com/documentation/templates/#now YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # http://www.djangoproject.com/documentation/templates/#now MONTH_DAY_FORMAT = 'F j' # Do you want to manage transactions manually? # Hint: you really don't! TRANSACTIONS_MANAGED = False # The User-Agent string to use when checking for URL validity through the # isExistingURL validator. URL_VALIDATOR_USER_AGENT = "Django/0.96.1 (http://www.djangoproject.com)" ############## # MIDDLEWARE # ############## # List of middleware classes to use. Order is important; in the request phase, # this middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.middleware.http.ConditionalGetMiddleware', # 'django.middleware.gzip.GZipMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.doc.XViewMiddleware', ) ############ # SESSIONS # ############ SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether sessions expire when a user closes his browser. ######### # CACHE # ######### # The cache backend to use. See the docstring in django.core.cache for the # possible values. CACHE_BACKEND = 'simple://' CACHE_MIDDLEWARE_KEY_PREFIX = '' #################### # COMMENTS # #################### COMMENTS_ALLOW_PROFANITIES = False # The profanities that will trigger a validation error in the # 'hasNoProfanities' validator. All of these should be in lowercase. PROFANITIES_LIST = ('asshat', 'asshead', 'asshole', 'cunt', 'fuck', 'gook', 'nigger', 'shit') # The group ID that designates which users are banned. # Set to None if you're not using it. COMMENTS_BANNED_USERS_GROUP = None # The group ID that designates which users can moderate comments. # Set to None if you're not using it. COMMENTS_MODERATORS_GROUP = None # The group ID that designates the users whose comments should be e-mailed to MANAGERS. # Set to None if you're not using it. COMMENTS_SKETCHY_USERS_GROUP = None # The system will e-mail MANAGERS the first COMMENTS_FIRST_FEW comments by each # user. Set this to 0 if you want to disable it. COMMENTS_FIRST_FEW = 0 # A tuple of IP addresses that have been banned from participating in various # Django-powered features. BANNED_IPS = () ################## # AUTHENTICATION # ################## AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) ########### # TESTING # ########### # The name of the method to use to invoke the test suite TEST_RUNNER = 'django.test.simple.run_tests' # The name of the database to use for testing purposes. # If None, a name of 'test_' + DATABASE_NAME will be assumed TEST_DATABASE_NAME = None ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = ()
Python
from django.db import models # Create your models here.
Python
# Create your views here.
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', # Example: # (r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), # Uncomment this for admin: # (r'^admin/', include('django.contrib.admin.urls')), )
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
# Django settings for {{ project_name }} project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE # although not all variations may be possible on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', ) ROOT_URLCONF = '{{ project_name }}.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', )
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import os import time # Needed for Windows from django.conf import global_settings ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" class LazySettings(object): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def __init__(self): # _target must be either None or something that supports attribute # access (getattr, hasattr, etc). self._target = None def __getattr__(self, name): if self._target is None: self._import_settings() if name == '__members__': # Used to implement dir(obj), for example. return self._target.get_all_members() return getattr(self._target, name) def __setattr__(self, name, value): if name == '_target': # Assign directly to self.__dict__, because otherwise we'd call # __setattr__(), which would be an infinite loop. self.__dict__['_target'] = value else: setattr(self._target, name, value) def _import_settings(self): """ Load the settings module pointed to by the environment variable. This is used the first time we need any settings at all, if the user has not previously configured the settings manually. """ try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if not settings_module: # If it's set but is an empty string. raise KeyError except KeyError: raise EnvironmentError, "Environment variable %s is undefined." % ENVIRONMENT_VARIABLE self._target = Settings(settings_module) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._target != None: raise EnvironmentError, 'Settings already configured.' holder = UserSettingsHolder(default_settings) for name, value in options.items(): setattr(holder, name, value) self._target = holder class Settings(object): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting == setting.upper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module try: mod = __import__(self.SETTINGS_MODULE, {}, {}, ['']) except ImportError, e: raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) # Settings that should be converted into tuples if they're mistakenly entered # as strings. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") for setting in dir(mod): if setting == setting.upper(): setting_value = getattr(mod, setting) if setting in tuple_settings and type(setting_value) == str: setting_value = (setting_value,) # In case the user forgot the comma. setattr(self, setting, setting_value) # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list # of all those apps. new_installed_apps = [] for app in self.INSTALLED_APPS: if app.endswith('.*'): appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__) for d in os.listdir(appdir): if d.isalpha() and os.path.isdir(os.path.join(appdir, d)): new_installed_apps.append('%s.%s' % (app[:-2], d)) else: new_installed_apps.append(app) self.INSTALLED_APPS = new_installed_apps if hasattr(time, 'tzset'): # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE def get_all_members(self): return dir(self) class UserSettingsHolder(object): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.default_settings = default_settings def __getattr__(self, name): return getattr(self.default_settings, name) def get_all_members(self): return dir(self) + dir(self.default_settings) settings = LazySettings() # This function replaces itself with django.utils.translation.gettext() the # first time it's run. This is necessary because the import of # django.utils.translation requires a working settings module, and loading it # from within this file would cause a circular import. def first_time_gettext(*args): from django.utils.translation import gettext __builtins__['_'] = gettext return gettext(*args) __builtins__['_'] = first_time_gettext
Python
from django.conf.urls.defaults import * urlpatterns = patterns('django.views', (r'^(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', 'defaults.shortcut'), )
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^setlang/$', 'django.views.i18n.set_language'), )
Python
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver __all__ = ['handler404', 'handler500', 'include', 'patterns'] handler404 = 'django.views.defaults.page_not_found' handler500 = 'django.views.defaults.server_error' include = lambda urlconf_module: [urlconf_module] def patterns(prefix, *tuples): pattern_list = [] for t in tuples: regex, view_or_include = t[:2] default_kwargs = t[2:] if type(view_or_include) == list: pattern_list.append(RegexURLResolver(regex, view_or_include[0], *default_kwargs)) else: pattern_list.append(RegexURLPattern(regex, prefix and (prefix + '.' + view_or_include) or view_or_include, *default_kwargs)) return pattern_list
Python
from django.oldforms import *
Python
# This module collects helper functions and classes that "span" multiple levels # of MVC. In other words, these functions/classes introduce controlled coupling # for convenience's sake. from django.template import loader from django.http import HttpResponse, Http404 from django.db.models.manager import Manager def render_to_response(*args, **kwargs): return HttpResponse(loader.render_to_string(*args, **kwargs)) load_and_render = render_to_response # For backwards compatibility. def get_object_or_404(klass, *args, **kwargs): if isinstance(klass, Manager): manager = klass klass = manager.model else: manager = klass._default_manager try: return manager.get(*args, **kwargs) except klass.DoesNotExist: raise Http404('No %s matches the given query.' % klass._meta.object_name) def get_list_or_404(klass, *args, **kwargs): if isinstance(klass, Manager): manager = klass else: manager = klass._default_manager obj_list = list(manager.filter(*args, **kwargs)) if not obj_list: raise Http404('No %s matches the given query.' % manager.model._meta.object_name) return obj_list
Python