desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Always returns False. This is a way of comparing User objects to anonymous users.'
def is_anonymous(self):
return False
'Always return True. This is a way to tell if the user has been authenticated in templates.'
def is_authenticated(self):
return True
'Returns the first_name plus the last_name, with a space in between.'
def get_full_name(self):
full_name = ('%s %s' % (self.first_name, self.last_name)) return full_name.strip()
'Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes.'
def check_password(self, raw_password):
if ('$' not in self.password): import md5 is_correct = (self.password == md5.new(raw_password).hexdigest()) if is_correct: self.set_password(raw_password) self.save() return is_correct return check_password(raw_password, self.password)
'Returns a list of permission strings that this user has through his/her groups.'
def get_group_permissions(self):
if (not hasattr(self, '_group_perm_cache')): import sets cursor = connection.cursor() sql = ('\n SELECT ct.%s, p.%s\n FROM %s p, %s gp, %s ug,...
'Returns True if the user has the specified permission.'
def has_perm(self, perm):
if (not self.is_active): return False if self.is_superuser: return True return (perm in self.get_all_permissions())
'Returns True if the user has each of the specified permissions.'
def has_perms(self, perm_list):
for perm in perm_list: if (not self.has_perm(perm)): return False return True
'Returns True if the user has any permissions in the given app label.'
def has_module_perms(self, app_label):
if (not self.is_active): return False if self.is_superuser: return True return bool(len([p for p in self.get_all_permissions() if (p[:p.index('.')] == app_label)]))
'Sends an e-mail to this User.'
def email_user(self, subject, message, from_email=None):
from django.core.mail import send_mail send_mail(subject, message, from_email, [self.email])
'Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles.'
def get_profile(self):
if (not hasattr(self, '_profile_cache')): from django.conf import settings if (not settings.AUTH_PROFILE_MODULE): raise SiteProfileNotAvailable try: (app_label, model_name) = settings.AUTH_PROFILE_MODULE.split('.') model = models.get_model(app_label, model...
'Creates the user.'
def save(self, new_data):
return User.objects.create_user(new_data['username'], '', new_data['password1'])
'If request is passed in, the manipulator will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validator.'
def __init__(self, request=None):
self.request = request self.fields = [oldforms.TextField(field_name='username', length=15, maxlength=30, is_required=True, validator_list=[self.isValidUser, self.hasCookiesEnabled]), oldforms.PasswordField(field_name='password', length=15, maxlength=30, is_required=True)] self.user_cache = None
'Validates that a user exists with the given e-mail address'
def isValidUserEmail(self, new_data, all_data):
try: self.user_cache = User.objects.get(email__iexact=new_data) except User.DoesNotExist: raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
'Calculates a new password randomly and sends it to the user'
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
from django.core.mail import send_mail new_pass = User.objects.make_random_password() self.user_cache.set_password(new_pass) self.user_cache.save() if (not domain_override): current_site = Site.objects.get_current() site_name = current_site.name domain = current_site.domain ...
'Validates that the old_password field is correct.'
def isValidOldPassword(self, new_data, all_data):
if (not self.user.check_password(new_data)): raise validators.ValidationError, _('Your old password was entered incorrectly. Please enter it again.')
'Saves the new password.'
def save(self, new_data):
self.user.set_password(new_data['new_password1']) self.user.save()
'Saves the new password.'
def save(self, new_data):
self.user.set_password(new_data['password1']) self.user.save()
'Given a first-choice name, adds an underscore to the name until it reaches a name that isn\'t claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form.'
def unused_name(self, name):
while 1: try: f = self.form.fields[name] except KeyError: break name += '_' return name
'Displays the form'
def preview_get(self, request):
f = self.form(auto_id=AUTO_ID) return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state}, context_instance=RequestContext(request))
'Validates the POST data. If valid, displays the preview page. Else, redisplays form.'
def preview_post(self, request):
f = self.form(request.POST, auto_id=AUTO_ID) context = {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state} if f.is_valid(): context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(request, f) return render_to_response(self.pr...
'Validates the POST data. If valid, calls done(). Else, redisplays form.'
def post_post(self, request):
f = self.form(request.POST, auto_id=AUTO_ID) if f.is_valid(): if (self.security_hash(request, f) != request.POST.get(self.unused_name('hash'))): return self.failed_hash(request) return self.done(request, f.clean_data) else: return render_to_response(self.form_template, {'...
'Given captured args and kwargs from the URLconf, saves something in self.state and/or raises Http404 if necessary. For example, this URLconf captures a user_id variable: (r\'^contact/(?P<user_id>\d{1,6})/$\', MyFormPreview(MyForm)), In this case, the kwargs variable in parse_params would be {\'user_id\': 32} for a req...
def parse_params(self, *args, **kwargs):
pass
'Calculates the security hash for the given Form instance. This creates a list of the form field names/values in a deterministic order, pickles the result with the SECRET_KEY setting and takes an md5 hash of that. Subclasses may want to take into account request-specific information such as the IP address.'
def security_hash(self, request, form):
data = ([(bf.name, bf.data) for bf in form] + [settings.SECRET_KEY]) pickled = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL) return md5.new(pickled).hexdigest()
'Returns an HttpResponse in the case of an invalid security hash.'
def failed_hash(self, request):
return self.preview_post(request)
'Does something with the clean_data and returns an HttpResponseRedirect.'
def done(self, request, clean_data):
raise NotImplementedError(('You must define a done() method on your %s subclass.' % self.__class__.__name__))
'Returns the ContentType object for the given model, creating the ContentType if necessary.'
def get_for_model(self, model):
opts = model._meta key = (opts.app_label, opts.object_name.lower()) try: ct = CONTENT_TYPE_CACHE[key] except KeyError: (ct, created) = self.model._default_manager.get_or_create(app_label=key[0], model=key[1], defaults={'name': str(opts.verbose_name)}) CONTENT_TYPE_CACHE[key] = ct...
'Clear out the content-type cache. This needs to happen during database flushes to prevent caching of "stale" content type IDs (see django.contrib.contenttypes.management.create_contenttypes for where this gets called).'
def clear_cache(self):
global CONTENT_TYPE_CACHE CONTENT_TYPE_CACHE = {}
'Returns the Python model class for this type of content.'
def model_class(self):
from django.db import models return models.get_model(self.app_label, self.model)
'Returns an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type\'s get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it.'
def get_object_for_this_type(self, **kwargs):
return self.model_class()._default_manager.get(**kwargs)
'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.'
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):
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_copyri...
'Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.'
def write(self, outfile, encoding):
raise NotImplementedError
'Returns the feed in the given encoding as a string.'
def writeString(self, encoding):
from StringIO import StringIO s = StringIO() self.write(s, encoding) return s.getvalue()
'Returns the latest item\'s pubdate. If none of them have a pubdate, this returns the current date/time.'
def latest_post_date(self):
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()
'All args are expected to be Python Unicode objects'
def __init__(self, url, length, mime_type):
(self.url, self.length, self.mime_type) = (url, length, mime_type)
'returns a copy of this object'
def copy(self):
return self.__copy__()
'Returns the value of the item at the given zero-based index.'
def value_for_index(self, index):
return self[self.keyOrder[index]]
'Returns a copy of this object.'
def copy(self):
obj = self.__class__(self) obj.keyOrder = self.keyOrder return obj
'Returns the last data value for this key, or [] if it\'s an empty list; raises KeyError if not found.'
def __getitem__(self, key):
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 []
'Returns the default value if the requested data doesn\'t exist'
def get(self, key, default=None):
try: val = self[key] except KeyError: return default if (val == []): return default return val
'Returns an empty list if the requested data doesn\'t exist'
def getlist(self, key):
try: return dict.__getitem__(self, key) except KeyError: return []
'Appends an item to the internal list associated with key'
def appendlist(self, key, value):
self.setlistdefault(key, []) dict.__setitem__(self, key, (self.getlist(key) + [value]))
'Returns a list of (key, value) pairs, where value is the last item in the list associated with the key.'
def items(self):
return [(key, self[key]) for key in self.keys()]
'Returns a list of (key, list) pairs.'
def lists(self):
return dict.items(self)
'Returns a list of the last value on every key list.'
def values(self):
return [self[key] for key in self.keys()]
'Returns a copy of this object.'
def copy(self):
return self.__deepcopy__()
'update() extends rather than replaces existing key lists. Also accepts keyword args.'
def update(self, *args, **kwargs):
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, []...
'Convenience method for adding an element with no children'
def addQuickElement(self, name, contents=None, attrs=None):
if (attrs is None): attrs = {} self.startElement(name, attrs) if (contents is not None): self.characters(contents) self.endElement(name)
'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 ch...
def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None):
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) = separat...
'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 l...
def default(self, o):
raise TypeError(('%r is not JSON serializable' % (o,)))
'Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) \'{"foo":["bar", "baz"]}\''
def encode(self, o):
chunks = list(self.iterencode(o)) return ''.join(chunks)
'Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk)'
def iterencode(self, o):
if self.check_circular: markers = {} else: markers = None return self._iterencode(o, markers)
'Yield match, end_idx for each match'
def iterscan(self, string, idx=0, context=None):
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.la...
'``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...
def __init__(self, encoding=None, object_hook=None):
self.encoding = encoding self.object_hook = object_hook
'Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document)'
def decode(self, s, _w=WHITESPACE.match):
(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
'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.'
def raw_decode(self, s, **kw):
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)
'\'a.m.\' or \'p.m.\''
def a(self):
if (self.data.hour > 11): return _('p.m.') return _('a.m.')
'\'AM\' or \'PM\''
def A(self):
if (self.data.hour > 11): return _('PM') return _('AM')
'Swatch Internet time'
def B(self):
raise NotImplementedError
'Time, in 12-hour hours and minutes, with minutes left off if they\'re zero. Examples: \'1\', \'1:30\', \'2:05\', \'2\' Proprietary extension.'
def f(self):
if (self.data.minute == 0): return self.g() return ('%s:%s' % (self.g(), self.i()))
'Hour, 12-hour format without leading zeros; i.e. \'1\' to \'12\''
def g(self):
if (self.data.hour == 0): return 12 if (self.data.hour > 12): return (self.data.hour - 12) return self.data.hour
'Hour, 24-hour format without leading zeros; i.e. \'0\' to \'23\''
def G(self):
return self.data.hour
'Hour, 12-hour format; i.e. \'01\' to \'12\''
def h(self):
return ('%02d' % self.g())
'Hour, 24-hour format; i.e. \'00\' to \'23\''
def H(self):
return ('%02d' % self.G())
'Minutes; i.e. \'00\' to \'59\''
def i(self):
return ('%02d' % self.data.minute)
'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.'
def P(self):
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()))
'Seconds; i.e. \'00\' to \'59\''
def s(self):
return ('%02d' % self.data.second)
'Month, textual, 3 letters, lowercase; e.g. \'jan\''
def b(self):
return MONTHS_3[self.data.month]
'Day of the month, 2 digits with leading zeros; i.e. \'01\' to \'31\''
def d(self):
return ('%02d' % self.data.day)
'Day of the week, textual, 3 letters; e.g. \'Fri\''
def D(self):
return WEEKDAYS[self.data.weekday()][0:3]
'Month, textual, long; e.g. \'January\''
def F(self):
return MONTHS[self.data.month]
'\'1\' if Daylight Savings Time, \'0\' otherwise.'
def I(self):
if self.timezone.dst(self.data): return '1' else: return '0'
'Day of the month without leading zeros; i.e. \'1\' to \'31\''
def j(self):
return self.data.day
'Day of the week, textual, long; e.g. \'Friday\''
def l(self):
return WEEKDAYS[self.data.weekday()]
'Boolean for whether it is a leap year; i.e. True or False'
def L(self):
return isleap(self.data.year)
'Month; i.e. \'01\' to \'12\''
def m(self):
return ('%02d' % self.data.month)
'Month, textual, 3 letters; e.g. \'Jan\''
def M(self):
return MONTHS_3[self.data.month].title()
'Month without leading zeros; i.e. \'1\' to \'12\''
def n(self):
return self.data.month
'Month abbreviation in Associated Press style. Proprietary extension.'
def N(self):
return MONTHS_AP[self.data.month]
'Difference to Greenwich time in hours; e.g. \'+0200\''
def O(self):
tz = self.timezone.utcoffset(self.data) return ('%+03d%02d' % ((tz.seconds // 3600), ((tz.seconds // 60) % 60)))
'RFC 822 formatted date; e.g. \'Thu, 21 Dec 2000 16:01:07 +0200\''
def r(self):
return self.format('D, j M Y H:i:s O')
'English ordinal suffix for the day of the month, 2 characters; i.e. \'st\', \'nd\', \'rd\' or \'th\''
def S(self):
if (self.data.day in (11, 12, 13)): return 'th' last = (self.data.day % 10) if (last == 1): return 'st' if (last == 2): return 'nd' if (last == 3): return 'rd' return 'th'
'Number of days in the given month; i.e. \'28\' to \'31\''
def t(self):
return ('%02d' % monthrange(self.data.year, self.data.month)[1])
'Time zone of this machine; e.g. \'EST\' or \'MDT\''
def T(self):
name = self.timezone.tzname(self.data) if (name is None): name = self.format('O') return name
'Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)'
def U(self):
off = self.timezone.utcoffset(self.data) return (int(time.mktime(self.data.timetuple())) + (off.seconds * 60))
'Day of the week, numeric, i.e. \'0\' (Sunday) to \'6\' (Saturday)'
def w(self):
return ((self.data.weekday() + 1) % 7)
'ISO-8601 week number of year, weeks starting on Monday'
def W(self):
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)))): ...
'Year, 2 digits; e.g. \'99\''
def y(self):
return str(self.data.year)[2:]
'Year, 4 digits; e.g. \'1999\''
def Y(self):
return self.data.year
'Day of the year; i.e. \'0\' to \'365\''
def z(self):
doy = (self.year_days[self.data.month] + self.data.day) if (self.L() and (self.data.month > 2)): doy += 1 return doy
'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.'
def Z(self):
return self.timezone.utcoffset(self.data).seconds
'Modify the request headers to add the appropriate Authorization header. Over-ride this in sub-classes.'
def request(self, method, request_uri, headers, content):
pass
'Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true.'
def response(self, response, content):
return False
'Modify the request headers to add the appropriate Authorization header.'
def request(self, method, request_uri, headers, content):
headers['authorization'] = ('Basic ' + base64.b64encode(('%s:%s' % self.credentials)).strip())
'Modify the request headers'
def request(self, method, request_uri, headers, content, cnonce=None):
H = (lambda x: _md5(x).hexdigest()) KD = (lambda s, d: H(('%s:%s' % (s, d)))) A2 = ''.join([method, ':', request_uri]) self.challenge['cnonce'] = (cnonce or _cnonce()) request_digest = ('"%s"' % KD(H(self.A1), ('%s:%s:%s:%s:%s' % (self.challenge['nonce'], ('%08x' % self.challenge['nc']), self.challe...
'Modify the request headers'
def request(self, method, request_uri, headers, content):
keys = _get_end2end_headers(headers) keylist = ''.join([('%s ' % k) for k in keys]) headers_val = ''.join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) cnonce = _cnonce() request_digest = ('%s:%s:%s:%s:%s' % (method, request_uri, cnonce, self.challen...
'Modify the request headers to add the appropriate Authorization header.'
def request(self, method, request_uri, headers, content):
headers['authorization'] = 'WSSE profile="UsernameToken"' iso_now = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers['X-WSSE'] = ('UsernameToken Username="%s", PasswordDigest="%s", N...
'Modify the request headers to add the appropriate Authorization header.'
def request(self, method, request_uri, headers, content):
headers['authorization'] = ('GoogleLogin Auth=' + self.Auth)
'The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host=\'localhost\', proxy_port=8000)'
def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None):
self.proxy_type = proxy_type self.proxy_host = proxy_host self.proxy_port = proxy_port self.proxy_rdns = proxy_rdns self.proxy_user = proxy_user self.proxy_pass = proxy_pass
'Read proxy info from the environment variables.'
@classmethod def from_environment(cls, method='http'):
if (method not in ['http', 'https']): return env_var = (method + '_proxy') url = os.environ.get(env_var, os.environ.get(env_var.upper())) if (not url): return pi = cls.from_url(url, method) no_proxy = os.environ.get('no_proxy', os.environ.get('NO_PROXY', '')) bypass_hosts = [...
'Construct a ProxyInfo from a URL (such as http_proxy env var)'
@classmethod def from_url(cls, url, method='http'):
url = urlparse.urlparse(url) username = None password = None port = None if ('@' in url[1]): (ident, host_port) = url[1].split('@', 1) if (':' in ident): (username, password) = ident.split(':', 1) else: password = ident else: host_port = ur...