desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Testing /finance/category/add/'
| def test_finance_category_add_out(self):
| response = self.client.get(reverse('finance_category_add'))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/category/edit/<category_id>'
| def test_finance_category_edit_out(self):
| response = self.client.get(reverse('finance_category_edit', args=[self.category.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/category/view/<category_id>'
| def test_finance_category_view_out(self):
| response = self.client.get(reverse('finance_category_view', args=[self.category.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/category/delete/<category_id>'
| def test_finance_category_delete_out(self):
| response = self.client.get(reverse('finance_category_delete', args=[self.category.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/currency/add/'
| def test_finance_currency_add_out(self):
| response = self.client.get(reverse('finance_currency_add'))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/currency/edit/<currency_id>'
| def test_finance_currency_edit_out(self):
| response = self.client.get(reverse('finance_currency_edit', args=[self.currency.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/currency/view/<currency_id>'
| def test_finance_currency_view_out(self):
| response = self.client.get(reverse('finance_currency_view', args=[self.currency.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/currency/delete/<currency_id>'
| def test_finance_currency_delete_out(self):
| response = self.client.get(reverse('finance_currency_delete', args=[self.currency.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/tax/add/'
| def test_finance_tax_add_out(self):
| response = self.client.get(reverse('finance_tax_add'))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/tax/edit/<tax_id>'
| def test_finance_tax_edit_out(self):
| response = self.client.get(reverse('finance_tax_edit', args=[self.tax.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/tax/view/<tax_id>'
| def test_finance_tax_view_out(self):
| response = self.client.get(reverse('finance_tax_view', args=[self.tax.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/tax/delete/<tax_id>'
| def test_finance_tax_delete_out(self):
| response = self.client.get(reverse('finance_tax_delete', args=[self.tax.id]))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/settings/view/'
| def test_finance_settings_view_out(self):
| response = self.client.get(reverse('finance_settings_view'))
self.assertRedirects(response, reverse('user_login'))
|
'Testing /finance/settings/edit/'
| def test_finance_settings_edit_out(self):
| response = self.client.get(reverse('finance_settings_edit'))
self.assertRedirects(response, reverse('user_login'))
|
'Export transactions into CSV file'
| def export_transactions(self, transactions):
| response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = ('attachment; filename=Transactions_%s.csv' % datetime.date.today().isoformat())
writer = csv.writer(response)
headers = ['name', 'source', 'target', 'liability', 'category', 'account', 'datetime', 'value', 'details']
... |
'Import transactions from CSV file'
| def import_transactions(self, content):
| f = StringIO.StringIO(content)
transactions = csv.DictReader(f, delimiter=',')
self.parse_transactions(transactions)
|
'Process form'
| def save(self, *args, **kwargs):
| if self.instance:
if self.is_valid():
if self.cleaned_data['category']:
self.instance.category = self.cleaned_data['category']
self.instance.save()
if self.cleaned_data['delete']:
if (self.cleaned_data['delete'] == 'delete'):
... |
'Sets choices and initial value'
| def __init__(self, user, *args, **kwargs):
| super(SettingsForm, self).__init__(*args, **kwargs)
self.fields['my_company'].queryset = Object.filter_permitted(user, Contact.objects)
self.fields['my_company'].widget.attrs.update({'class': 'autocomplete', 'callback': reverse('identities_ajax_contact_lookup')})
self.fields['default_account'].queryset ... |
'Check that my company has an account'
| def clean_my_company(self, *args, **kwargs):
| my_company = self.cleaned_data['my_company']
if (not my_company.account_set.count()):
raise forms.ValidationError(_('Your company has to have at least one Financial Account'))
return my_company
|
'Check that account owner is the same as my company'
| def clean_default_account(self):
| account = self.cleaned_data['default_account']
try:
company = self.cleaned_data['my_company']
if (not (account.owner_id == company.id)):
raise forms.ValidationError(_('Default Account has to belong to your company'))
except KeyError:
pass
return a... |
'Form processor'
| def save(self):
| try:
ModuleSetting.set_for_module('my_company', self.cleaned_data['my_company'].id, 'treeio.finance')
ModuleSetting.set_for_module('default_account', self.cleaned_data['default_account'].id, 'treeio.finance')
currency = Currency.objects.get(pk=self.cleaned_data['default_currency'])
c... |
'Returns absolute URL of the object'
| def get_absolute_url(self):
| return reverse('changes_status_view', args=[self.id])
|
'Returns absolute URL of the object'
| def get_absolute_url(self):
| return reverse('changes_set_view', args=[self.id])
|
'Returns absolute URL of the object'
| def get_absolute_url(self):
| return reverse('changes_change_view', args=[self.id])
|
'Process form'
| def save(self, *args, **kwargs):
| if self.instance:
if self.is_valid():
if self.cleaned_data['delete']:
if (self.cleaned_data['delete'] == 'delete'):
self.instance.delete()
|
'Label From Instance'
| def label_from_instance(self, obj):
| name = unicode(obj)
obj_type = obj.get_human_type()
label = filters.do_truncate(filters.do_striptags(name), 30)
if obj_type:
label += ((' (' + obj_type) + ')')
return label
|
'Override Save to mark .resolved*'
| def save(self, *args, **kwargs):
| instance = getattr(self, 'instance', None)
user = getattr(self, 'user', None)
if (instance and user):
try:
old_changeset = ChangeSet.objects.get(pk=instance.id)
if ((not (old_changeset.status == instance.status)) and (not instance.status.active) and instance.status.hidden):
... |
'Sets choices and initial value'
| def __init__(self, user, *args, **kwargs):
| super(SettingsForm, self).__init__(*args, **kwargs)
self.fields['default_changeset_status'].queryset = ChangeSetStatus.objects.filter(trash=False)
try:
conf = ModuleSetting.get_for_module('treeio.changes', 'default_changeset_status')[0]
default_changeset_status = ChangeSetStatus.objects.get(... |
'Form processor'
| def save(self):
| try:
ModuleSetting.set_for_module('default_changeset_status', self.cleaned_data['default_changeset_status'].id, 'treeio.changes')
return True
except Exception:
return False
|
'Capture all cron jobs'
| def __init__(self, databases=None, noloop=False, *args, **kwargs):
| if (databases is None):
databases = []
signal.signal(signal.SIGTERM, self.stop)
self.databases = (databases or [])
self.jobs = []
self.sleeptime = getattr(settings, 'HARDTREE_CRON_PERIOD', 60)
self.priority_high = getattr(settings, 'HARDTREE_CRON_HIGH_PRIORITY', 10)
self.priority_low... |
'Adds all jobs to the queue'
| def add_jobs(self):
| cronlogger.info((('Adding ' + unicode(len(self.jobs))) + ' jobs to the queue.'))
for db in self.databases:
cronlogger.debug(('ADDING JOBS FOR ' + unicode(db)))
cache_key = (('hardtree_' + db) + '_last')
last_accessed = cache.get(cache_key)
if last_accessed... |
'Start cron runner'
| def start(self):
| self.add_jobs()
try:
while (not self._stopped):
if (len(self.pool) < self.poolsize):
while ((len(self.queue) > 0) and (len(self.pool) < self.poolsize)):
cron = self.queue.pop()
self.pool.append(cron)
if (('hardtree_%... |
'Process form'
| def save(self):
| if (self.instance and self.is_valid()):
if self.cleaned_data['action']:
if (self.cleaned_data['action'] == 'delete'):
self.instance.delete()
elif (self.cleaned_data['action'] == 'untrash'):
self.instance.trash = False
self.instance.save... |
'Returns a fresh `HttpResponse` when getting
an "attribute". This is backwards compatible
with 0.2, which is important.'
| def __getattr__(self, attr):
| try:
(r, c) = self.CODES.get(attr)
except TypeError:
raise AttributeError(attr)
return HttpResponse(r, content_type='text/plain', status=c)
|
'Gets a function ref to deserialize content
for a certain mimetype.'
| def loader_for_type(self, ctype):
| for (loadee, mimes) in Mimer.TYPES.iteritems():
for mime in mimes:
if ctype.startswith(mime):
return loadee
|
'Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded'
| def content_type(self):
| type_formencoded = 'application/x-www-form-urlencoded'
ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
if (type_formencoded in ctype):
return None
return ctype
|
'Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handler will have to read from
there.... | def translate(self):
| ctype = self.content_type()
self.request.content_type = ctype
if ((not self.is_multipart()) and ctype):
loadee = self.loader_for_type(ctype)
if loadee:
try:
self.request.data = loadee(self.request.body)
self.request.POST = self.request.PUT = dict()... |
'Used to generate random key/secret pairings. Use this after you\'ve
added the other data in place of save().
c = Consumer()
c.name = "My consumer"
c.description = "An app that makes ponies from the API."
c.user = some_user_object
c.generate_random_codes()'
| def generate_random_codes(self):
| key = User.objects.make_random_password(length=KEY_SIZE)
secret = generate_random(SECRET_SIZE)
while Consumer.objects.filter(key__exact=key, secret__exact=secret).count():
secret = generate_random(SECRET_SIZE)
self.key = key
self.secret = secret
self.save()
|
'Shortcut to create a consumer with random key/secret.'
| def create_consumer(self, name, description=None, user=None, using=CONSUMER_DB):
| (consumer, created) = self.using(using).get_or_create(name=name)
if user:
consumer.user = user
if description:
consumer.description = description
if created:
(consumer.key, consumer.secret) = self.generate_random_codes()
consumer.save()
return consumer
|
'Add cache if you use a default resource.'
| def get_default_resource(self, name):
| if (not self._default_resource):
self._default_resource = self.get(name=name)
return self._default_resource
|
'Shortcut to create a token with random key/secret.'
| def create_token(self, consumer_id, token_type, timestamp, user=None, using=None):
| if using:
manager = self.using(using)
else:
manager = self
(token, created) = manager.get_or_create(consumer_id=consumer_id, token_type=token_type, timestamp=timestamp, user=user)
if created:
(token.key, token.secret) = self.generate_random_codes()
token.save()
return... |
'Returns a 401 response with a small bit on
what OAuth is, and where to learn more about it.
When this was written, browsers did not understand
OAuth authentication on the browser side, and hence
the helpful template we render. Maybe some day in the
future, browsers will take care of this stuff for us
and understand th... | def challenge(self):
| response = HttpResponse()
response.status_code = 401
for (k, v) in oauth.build_authenticate_header(realm=self.realm).iteritems():
response[k] = v
response.content = '\n Unable to authenticate.\n M... |
'Return the Consumer for `consumer_key` or raise `InvalidConsumerError`.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer_key`: The consumer key.'
| def get_consumer(self, request, oauth_request, consumer_key):
| raise NotImplementedError
|
'Return the Consumer associated with the `request_token` Token.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`request_token`: The request token to get the consumer for.'
| def get_consumer_for_request_token(self, request, oauth_request, request_token):
| raise NotImplementedError
|
'Return the Consumer associated with the `access_token` Token.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`access_token`: The access Token to get the consumer for.'
| def get_consumer_for_access_token(self, request, oauth_request, access_token):
| raise NotImplementedError
|
'Generate and return a Token.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer`: The Consumer that made the request.'
| def create_request_token(self, request, oauth_request, consumer, callback):
| raise NotImplementedError
|
'Return the Token for `request_token_key` or raise `InvalidTokenError`.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer`: The Consumer that made the request.
`request_token_key`: The request token key.'
| def get_request_token(self, request, oauth_request, request_token_key):
| raise NotImplementedError
|
'Authorize the `request_token` Token and return it.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`request_token`: The request token to authorize.'
| def authorize_request_token(self, request, oauth_request, request_token):
| raise NotImplementedError
|
'Generate and return a Token.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer`: The Consumer that made the request.
`request_token`: The Token used to make the request.'
| def create_access_token(self, request, oauth_request, consumer, request_token):
| raise NotImplementedError
|
'Return the Token for `access_token_key` or raise `InvalidTokenError`.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer`: The Consumer that made the request.
`access_token_key`: The token key used to make the request.'
| def get_access_token(self, request, oauth_request, consumer, access_token_key):
| raise NotImplementedError
|
'Return the associated User for `access_token`.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer`: The Consumer that made the request.
`access_token`: The Token used to make the request.'
| def get_user_for_access_token(self, request, oauth_request, access_token):
| raise NotImplementedError
|
'Return the associated User for `consumer`.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`consumer`: The Consumer that made the request.'
| def get_user_for_consumer(self, request, oauth_request, consumer):
| raise NotImplementedError
|
'Return `True` if the nonce has not yet been used, `False` otherwise.
`request`: The Django request object.
`oauth_request`: The `oauth2.Request` object.
`nonce`: The nonce to check.'
| def check_nonce(self, request, oauth_request, nonce):
| raise NotImplementedError
|
'URI template processor.
See http://bitworking.org/projects/URI-Templates/'
| def get_resource_uri_template(self):
| try:
resource_uri = self.handler.resource_uri()
components = [None, [], {}]
for (i, value) in enumerate(resource_uri):
components[i] = value
(lookup_view, args, kwargs) = components
lookup_view = get_callable(lookup_view, True)
possibilities = get_resolver... |
'INDEX URI template processor.'
| def get_resource_uri_index(self):
| try:
resource_uri = self.handler.resource_uri()
components = [None, [], {}]
for (i, value) in enumerate(resource_uri):
components[i] = value
(lookup_view, args, kwargs) = components
if (args or kwargs):
lookup_view = get_callable(lookup_view, True)
... |
'Returns the database that should be used for the current request'
| def _get_current_database(self):
| if (('request' in box) and ('CURRENT_DATABASE_NAME' not in box)):
current_db = box['request'].get_host().split('.')[0]
else:
current_db = box.get('CURRENT_DATABASE_NAME', 'default')
return current_db
|
'Point all operations to the current database'
| def db_for_read(self, model, **hints):
| if ('instance' in hints):
return hints['instance']._state.db
return self._get_current_database()
|
'Point all operations to the current database'
| def db_for_write(self, model, **hints):
| return self._get_current_database()
|
'Allow any relation'
| def allow_relation(self, obj1, obj2, **hints):
| return True
|
'Allow syncdb'
| def allow_syncdb(self, db, model):
| return True
|
'Run'
| def run(self):
| self.process_email()
|
'Send email'
| def send_email(self):
| self.start()
|
'Returns appropriate SMTP port number depending on incoming server name and boolean ssl'
| def get_smtp_port(self, server):
| port = 25
ssl = False
if (('gmail.com' in server) or ('googlemail.com' in server)):
port = 587
ssl = False
elif (server == 'plus.smtp.mail.yahoo.com'):
if hasattr(smtplib, 'SMTP_SSL'):
port = 465
ssl = True
if ((server == 'smtp.live.com') or (server == 'sm... |
'Create a message and send it'
| def process_email(self):
| try:
msg = MIMEMultipart('alternative')
msg['From'] = self.fromaddr
msg['To'] = self.toaddr
msg['Subject'] = self.subject
text = self.body
html = self.html
if self.signature:
text += self.signature
part1 = MIMEText(text.encode('utf-8'), 'pl... |
'Run'
| def run(self):
| self.get_emails()
|
'Returns appropriate POP port number depending on incoming server name'
| def get_pop_port(self):
| port = 110
ssl = False
if (self.incoming_server_type == 'POP3-SSL'):
port = 995
ssl = True
return (port, ssl)
|
'Returns appropriate IMAP port number depending on incoming server name'
| def get_imap_port(self):
| port = 143
ssl = False
if (self.incoming_server_type == 'IMAP-SSL'):
port = 993
ssl = True
return (port, ssl)
|
'Fetches emails'
| def get_emails(self):
| if ((self.incoming_server_type == 'IMAP') or (self.incoming_server_type == 'IMAP-SSL')):
HARDTREE_MESSAGING_IMAP_LIMIT = getattr(settings, 'HARDTREE_MESSAGING_IMAP_LIMIT', 100)
(port, ssl) = self.get_imap_port()
if ssl:
M = imaplib.IMAP4_SSL(self.incoming_server_name, port)
... |
'Detects string encoding and make it unicode'
| def make_unicode(self, string):
| utf8_detector = re.compile('^(?:\n [\\x09\\x0A\\x0D\\x20-\\x7E] # ASCII\n | [\\xC2-\\xDF][\\x80-\\xBF] # non-overlong 2-... |
'Decodes email subjects'
| def decode_subject(self, subject):
| if (not subject):
subject = 'No subject'
encoding = None
else:
(subject, encoding) = decode_header(subject)[0]
subject = self.decode(subject, encoding)
return (subject, encoding)
|
'Decodes Base64-encoded string'
| def decode_body(self, body):
| if (body is None):
body = 'No message'
else:
body = str(body)
body = base64.b64decode(body)
return body
|
'Removes all the dangerous and useless staff'
| def parse_email_body(self, body):
| body = body.replace('\r', '').replace('=\n', '').replace('=\n\r', '')
body = body.replace('=20\n', '\n\n')
HARDTREE_MESSAGING_UNSAFE_BLOCKS = getattr(settings, 'HARDTREE_MESSAGING_UNSAFE_BLOCKS', ('head', 'object', 'embed', 'applet', 'noframes', 'noscript', 'noembed', 'iframe', 'frame', 'frameset'))
tag... |
'Returns author\'s name and email if any'
| def get_email_author(self, msg):
| try:
header_from = msg['From']
splits = header_from.split('<', 1)
(name, email) = (splits if (len(splits) == 2) else ('', header_from))
email = email.split('>', 1)[0]
if name:
(name, encoding) = decode_header(name.strip(' "\''))[0]
name = self.decod... |
'Identify the current domain and database, set up appropriate variables in the pandora box'
| def process_request(self, request):
| domain = request.get_host().split('.')[0]
try:
setup_domain(domain)
except DatabaseNotFound:
evergreen_url = getattr(settings, 'EVERGREEN_BASE_URL', 'http://tree.io/')
return HttpResponseRedirect(evergreen_url)
except DatabaseError:
from django.db import router
fr... |
'Capture all cron_jobs'
| def __init__(self, *args, **kwargs):
| super(CronRunner, self).__init__(*args, **kwargs)
self.jobs = []
self.sleeptime = settings.HARDTREE_CRON_PERIOD
for module in settings.INSTALLED_APPS:
import_name = ((str(module) + '.') + settings.HARDTREE_MODULE_IDENTIFIER)
try:
hmodule = __import__(import_name, fromlist=[st... |
'Run cron'
| def run(self):
| while True:
for job in self.jobs:
try:
job()
except:
if settings.DEBUG:
raise
else:
import traceback
import sys
from treeio import core
... |
'Process request'
| def process_request(self, request):
| if (getattr(request, 'mobile', False) and (not request.POST) and ('/m' not in request.path[:2]) and ('/static' not in request.path[:7])):
if request.GET.get('nomobile', False):
request.session['nomobile'] = True
elif ('nomobile' not in request.session):
return HttpResponseRed... |
'Adds current user to Subscribers of an Object on creation'
| def do_fresh_subscribers(self, user, request, sender, instance, created, **kwargs):
| auto_notify = getattr(instance, 'auto_notify', True)
if (auto_notify and created):
if (isinstance(instance, Object) and instance.is_searchable()):
instance.subscribers.add(user)
try:
instance.create_notification('create', user)
except:
... |
'Send notifications to subscribers of an Object on Object change'
| def send_notifications_on_save(self, user, request, sender, instance, **kwargs):
| auto_notify = getattr(instance, 'auto_notify', True)
if (auto_notify and isinstance(instance, Object) and instance.id):
try:
instance.create_notification('update', user)
except:
pass
if isinstance(instance, Object):
process_timezone_field(user, instance)
|
'Send notifications to subscribers of an Object on Object delete'
| def send_notifications_on_delete(self, user, request, sender, instance, **kwargs):
| auto_notify = getattr(instance, 'auto_notify', True)
if (auto_notify and isinstance(instance, Object) and instance.get_related_object()):
try:
instance.create_notification('delete', user)
except:
pass
instance.subscribers.clear()
|
'Send notification on changes ManyToMany field (needs to be handled separately due to Django design)'
| def send_notifcations_on_m2m(self, user, request, sender, instance, action, reverse, model, pk_set, **kwargs):
| if isinstance(instance, Object):
attr = sender._meta.object_name.split('_', 1)[1]
if (attr in settings.HARDTREE_OBJECT_BLACKLIST):
return
if ((action == 'pre_clear') or (action == 'pre_remove')):
original = list(getattr(instance, attr).all())
self.objects[... |
'Process response'
| def process_response(self, request, response):
| signals.pre_save.disconnect(dispatch_uid=request)
signals.post_save.disconnect(dispatch_uid=request)
signals.m2m_changed.disconnect(dispatch_uid=request)
signals.pre_delete.disconnect(dispatch_uid=request)
try:
user = request.user.profile
self.objects[unicode[user.id]] = {}
excep... |
'Initialize objects'
| def __init__(self):
| self.objects = {}
|
'Process request'
| def process_request(self, request):
| view = None
try:
(view, args, kwargs) = resolve(request.path)
except Exception:
pass
if (view == ajax_popup):
process_created_object = curry(self.process_created_object, request)
signals.post_save.connect(process_created_object, dispatch_uid=request.user, weak=False)
|
'Store a newly created object and request during which it was created'
| def process_created_object(self, request, sender, instance, created, **kwargs):
| if (isinstance(instance, Object) and created and (not instance.is_attached())):
self.objects.update({unicode(instance.id): {'object': instance, 'request': request}})
|
'Process response'
| def process_response(self, request, response):
| if ((not getattr(request, 'user', None)) or (not request.user.username)):
return response
try:
signals.post_save.disconnect(dispatch_uid=request.user)
except AttributeError:
pass
view = None
try:
(view, args, kwargs) = resolve(request.path)
except Exception:
... |
'Set language for the current user'
| def process_request(self, request):
| lang = getattr(settings, 'HARDTREE_LANGUAGES_DEFAULT', 'en')
if request.user.username:
try:
user = request.user.profile
conf = ModuleSetting.get('language', user=user)[0]
lang = conf.value
except IndexError:
pass
except AttributeError:
... |
'Revert to SSL/no SSL depending on settings'
| def process_request(self, request):
| if getattr(settings, 'HARDTREE_SUBSCRIPTION_SSL_ENABLED', True):
if (getattr(settings, 'HARDTREE_SUBSCRIPTION_SSL_ENFORCE', False) and (not request.is_secure())):
redirect_url = request.build_absolute_uri()
return HttpResponseRedirect(redirect_url.replace('https://', 'http://'))
... |
'Keep protocol'
| def process_response(self, request, response):
| if getattr(settings, 'HARDTREE_SUBSCRIPTION_SSL_ENABLED', True):
if (response.status_code == 302):
redirect_url = request.build_absolute_uri(response['Location'])
if (request.is_secure() or getattr(settings, 'HARDTREE_SUBSCRIPTION_SSL_ENFORCE', False)):
response['Loca... |
'Process response'
| def process_response(self, request, response):
| if ('text/html' in response['Content-Type']):
response.content = short(response.content)
if (settings.HARDTREE_MINIFY_JSON and (settings.HARDTREE_RESPONSE_FORMATS['json'] in response['Content-Type'])):
response.content = _minify_json(response.content)
return response
|
'Process request'
| def process_request(self, request):
| hmodules = dict()
for module in settings.INSTALLED_APPS:
import_name = ((str(module) + '.') + settings.HARDTREE_MODULE_IDENTIFIER)
try:
hmodule = __import__(import_name, fromlist=[str(module)])
hmodules[str(module)] = hmodule.PROPERTIES
except ImportError:
... |
'Process response'
| def process_response(self, request, response):
| if settings.QUERY_DEBUG:
from django.db import connection
totaltime = float(0)
for q in connection.queries:
totaltime += float(q['time'])
if (len(connection.queries) > 3):
if settings.QUERY_DEBUG_FULL:
print '=== DB Queries:'
... |
'Returns absolute URL of the Group'
| def get_absolute_url(self, module='identities'):
| if ((not module) or (module == 'identities')):
try:
return reverse('identities_group_view', args=[self.id])
except NoReverseMatch:
return ''
else:
try:
return reverse('core_administration_group_view', args=[self.id])
except NoReverseMatch:
... |
'Get the root Group'
| def get_root(self):
| root = self
stack = [self]
while getattr(root, 'parent', None):
root = getattr(root, 'parent')
if (root in stack):
break
stack.append(root)
return root
|
'Get tree path as a list() starting with root Group'
| def get_tree_path(self, skipself=False):
| if skipself:
path = []
else:
path = [self]
current = self
while getattr(current, 'parent', None):
parent = getattr(current, 'parent')
if (parent in path):
break
else:
path.insert(0, parent)
current = parent
return path
|
'Returns first available Contact'
| def get_contact(self):
| try:
return self.contact_set.all()[0]
except IndexError:
return None
|
'Returns true if any Contacts exist for this Group'
| def has_contact(self):
| return self.contact_set.exists()
|
'Returns the full name with parent(s) separated by slashes'
| def get_fullname(self, save=True):
| current = self
fullname = self.name
while current.parent:
current = current.parent
fullname = ((current.name + ' / ') + fullname)
return fullname
|
'Returns currently set Perspective for the Group'
| def get_perspective(self):
| ids = []
try:
for setting in ModuleSetting.get_for_module('treeio.core', name='default_perspective', group=self):
ids.append(long(setting.value))
_id = ids[0]
perspective = get_object_or_404(Perspective, pk=_id)
except:
try:
conf = ModuleSetting.get_fo... |
'Sets the Perspective for the Group'
| def set_perspective(self, perspective):
| ModuleSetting.set_for_module('default_perspective', perspective.id, 'treeio.core', group=self)
modules = (perspective.modules.all() or Module.objects.all())
try:
for module in modules:
full_access = ((not module.full_access.exists()) or module.full_access.filter(pk=self.id).exists())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.