text stringlengths 0 1.05M | meta dict |
|---|---|
from functools import update_wrapper
from django.contrib import admin
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from .forms import MessageForm
from .models import get_device_model
Device = get_device_model()
class DeviceAdmin(admin.ModelAdmin):
list_display = ['dev_id', 'name', 'modified_date', 'is_active']
search_fields = ('dev_id', 'name')
list_filter = ['is_active']
date_hierarchy = 'modified_date'
readonly_fields = ('dev_id', 'reg_id')
actions = ['send_message_action']
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urlpatterns = patterns(
'',
url(r'^send-message/$', wrap(self.send_message_view),
name=self.build_admin_url('send_message')),
)
return urlpatterns + super(DeviceAdmin, self).get_urls()
def build_admin_url(self, url_name):
return '%s_%s_%s' % (self.model._meta.app_label,
self.model._meta.model_name,
url_name)
def send_message_view(self, request):
base_view = 'admin:%s' % self.build_admin_url('changelist')
session_key = 'device_ids'
device_ids = request.session.get(session_key)
if not device_ids:
return redirect(base_view)
form = MessageForm(data=request.POST or None)
if form.is_valid():
devices = Device.objects.filter(pk__in=device_ids)
for device in devices:
device.send_message(form.cleaned_data['message'])
self.message_user(request, _('Message was sent.'))
del request.session[session_key]
return redirect(base_view)
context = {'form': form, 'opts': self.model._meta, 'add': False}
return render_to_response('gcm/admin/send_message.html', context,
context_instance=RequestContext(request))
def send_message_action(self, request, queryset):
ids = queryset.values_list('id', flat=True)
request.session['device_ids'] = list(ids)
url = 'admin:%s' % self.build_admin_url('send_message')
return redirect(url)
send_message_action.short_description = _("Send message")
admin.site.register(Device, DeviceAdmin)
| {
"repo_name": "johnofkorea/django-gcm",
"path": "gcm/admin.py",
"copies": "1",
"size": "2571",
"license": "bsd-2-clause",
"hash": 6773004666555543000,
"line_mean": 36.2608695652,
"line_max": 75,
"alpha_frac": 0.6122131466,
"autogenerated": false,
"ratio": 3.9372128637059722,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5049426010305972,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.core.urlresolvers import RegexURLPattern
from django.contrib import admin
class InvalidAdmin(RuntimeError):
pass
def make_admin_class(name, urls, app_label, dont_register=False,
site=admin.site):
label = app_label
required_name = "%s_%s_changelist" % (app_label, name.lower())
for url in urls:
if getattr(url, 'name', None) == required_name:
break
else:
raise InvalidAdmin(
"You must have an url with the name %r otherwise the admin "
"will fail to reverse it." % required_name
)
class _meta:
abstract = False
app_label = label
module_name = name.lower()
verbose_name_plural = name
verbose_name = name
model_name = name.lower()
object_name = name
swapped = False
model_class = type(name, (object,), {'_meta': _meta})
class admin_class(admin.ModelAdmin):
has_add_permission = lambda *args: False
has_change_permission = lambda *args: True
has_delete_permission = lambda *args: False
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
return [ # they are already prefixed
RegexURLPattern(
str(url.regex.pattern),
wrap(url.callback),
url.default_args,
url.name
)
if isinstance(url, RegexURLPattern)
else url
for url in urls
]
@classmethod
def register(cls):
site.register((model_class,), cls)
if not dont_register:
admin_class.register()
return admin_class
| {
"repo_name": "mattcaldwell/django-admin-utils",
"path": "src/admin_utils/mock.py",
"copies": "1",
"size": "1924",
"license": "bsd-2-clause",
"hash": -4840503743560686000,
"line_mean": 29.5396825397,
"line_max": 76,
"alpha_frac": 0.5514553015,
"autogenerated": false,
"ratio": 4.474418604651163,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009404250100528612,
"num_lines": 63
} |
from functools import update_wrapper
from django.http import Http404, HttpResponseRedirect
from django.contrib.admin import ModelAdmin, actions
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.admin.admin_names import change_label
from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME
from django.contrib.contenttypes import views as contenttype_views
from django.views.decorators.csrf import csrf_protect
from django.db.models.base import ModelBase
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.response import TemplateResponse
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from django.conf import settings
LOGIN_FORM_KEY = 'this_is_the_login_form'
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
def __init__(self, name='admin', app_name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self.app_name = app_name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured('The model %s is abstract, so it '
'cannot be registered with admin.' % model.__name__)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
if admin_class is not ModelAdmin and settings.DEBUG:
admin_class.validate(model)
# Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
def unregister(self, model_or_iterable):
"""
Unregisters the given model(s).
If a model isn't already registered, this will raise NotRegistered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotRegistered('The model %s is not registered' % model.__name__)
del self._registry[model]
def add_action(self, action, name=None):
"""
Register an action to be available globally.
"""
name = name or action.__name__
self._actions[name] = action
self._global_actions[name] = action
def disable_action(self, name):
"""
Disable a globally-registered action. Raises KeyError for invalid names.
"""
del self._actions[name]
def get_action(self, name):
"""
Explicitly get a registered global action whether it's enabled or
not. Raises KeyError for invalid names.
"""
return self._global_actions[name]
@property
def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
return six.iteritems(self._actions)
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
return request.user.is_active and request.user.is_staff
def check_dependencies(self):
"""
Check that all things needed to run the admin have been correctly installed.
The default implementation checks that LogEntry, ContentType and the
auth context processor are installed.
"""
from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.models import ContentType
if not LogEntry._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.admin' in your "
"INSTALLED_APPS setting in order to use the admin application.")
if not ContentType._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
"your INSTALLED_APPS setting in order to use the admin application.")
if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
"in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def admin_view(self, view, cacheable=False):
"""
Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You'll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import patterns, url
urls = super(MyAdminSite, self).get_urls()
urls += patterns('',
url(r'^my_view/$', self.admin_view(some_view))
)
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.
"""
def inner(request, *args, **kwargs):
if LOGIN_FORM_KEY in request.POST and request.user.is_authenticated():
auth_logout(request)
if not self.has_permission(request):
if request.path == reverse('admin:logout',
current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
return self.login(request)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import patterns, url, include
if settings.DEBUG:
self.check_dependencies()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = patterns('',
url(r'^$',
wrap(self.index),
name='index'),
url(r'^logout/$',
wrap(self.logout),
name='logout'),
url(r'^password_change/$',
wrap(self.password_change, cacheable=True),
name='password_change'),
url(r'^password_change/done/$',
wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$',
wrap(self.i18n_javascript, cacheable=True),
name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$',
wrap(contenttype_views.shortcut),
name='view_on_site'),
url(r'^(?P<app_label>\w+)/$',
wrap(self.app_index),
name='app_list')
)
# Add in each model's views.
for model, model_admin in six.iteritems(self._registry):
urlpatterns += patterns('',
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name),
include(model_admin.urls))
)
return urlpatterns
@property
def urls(self):
return self.get_urls(), self.app_name, self.name
def password_change(self, request):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.auth.views import password_change
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {
'current_app': self.name,
'post_change_redirect': url
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
return password_change(request, **defaults)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import password_change_done
defaults = {
'current_app': self.name,
'extra_context': extra_context or {},
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
return password_change_done(request, **defaults)
def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
"""
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import logout
defaults = {
'current_app': self.name,
'extra_context': extra_context or {},
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
return logout(request, **defaults)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
from django.contrib.auth.views import login
context = {
'title': _('Log in'),
'app_path': request.get_full_path(),
REDIRECT_FIELD_NAME: request.get_full_path(),
}
context.update(extra_context or {})
defaults = {
'extra_context': context,
'current_app': self.name,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'admin/login.html',
}
return login(request, **defaults)
@never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_dict = {}
user = request.user
for model, model_admin in self._registry.items():
app_label = model._meta.app_label
has_module_perms = user.has_module_perms(app_label)
if has_module_perms:
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True in perms.values():
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change', False):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add', False):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': app_label.title(),
'app_label': app_label,
'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
# Sort the apps alphabetically.
app_list = list(six.itervalues(app_dict))
app_list.sort(key=lambda x: x['name'])
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
context = {
'title': _('Site administration'),
'app_list': app_list,
}
context.update(extra_context or {})
return TemplateResponse(request, self.index_template or
'admin/index.html', context,
current_app=self.name)
def app_index(self, request, app_label, extra_context=None):
user = request.user
has_module_perms = user.has_module_perms(app_label)
app_dict = {}
for model, model_admin in self._registry.items():
if app_label == model._meta.app_label:
if has_module_perms:
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True in perms.values():
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change', False):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add', False):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_dict:
app_dict['models'].append(model_dict),
else:
# First time around, now that we know there's
# something to display, add in the necessary meta
# information.
app_dict = {
'name': app_label.title(),
'app_label': app_label,
'app_url': '',
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
context = {
'title': _('%s administration') % capfirst(
change_label(app_label)
),
'app_list': [app_dict],
}
context.update(extra_context or {})
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context, current_app=self.name)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
| {
"repo_name": "yaroslavprogrammer/django",
"path": "django/contrib/admin/sites.py",
"copies": "1",
"size": "18808",
"license": "bsd-3-clause",
"hash": 8045601814860977000,
"line_mean": 40.3362637363,
"line_max": 121,
"alpha_frac": 0.5610910251,
"autogenerated": false,
"ratio": 4.640513200098693,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5701604225198693,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.http import Http404, HttpResponseRedirect
#from django.contrib.admin import ModelAdmin, actions
from django.contrib.auth import REDIRECT_FIELD_NAME
#from django.contrib.contenttypes import views as contenttype_views
from django.views.decorators.csrf import csrf_protect
#from django.db.models.base import ModelBase
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, reverse_lazy, NoReverseMatch
from django.template.response import TemplateResponse
#from django.utils.safestring import mark_safe
#from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from django.conf import settings
from homework.orders.forms import AuthenticationForm
from homework.orders import views
LOGIN_FORM_KEY = 'this_is_the_login_form'
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class OrdersSite(object):
def has_permission(self, request):
return request.user.is_active and request.user.is_authenticated
def check_dependencies(self):
"""
Check that all things needed to run the admin have been correctly installed.
The default implementation checks that LogEntry, ContentType and the
auth context processor are installed.
"""
from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.models import ContentType
if not LogEntry._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.admin' in your "
"INSTALLED_APPS setting in order to use the admin application.")
if not ContentType._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
"your INSTALLED_APPS setting in order to use the admin application.")
if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
"in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def wrap_view(self, view, cacheable=False):
def inner(request, *args, **kwargs):
if not self.has_permission(request):
return self.login(request)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import patterns, url, include
if settings.DEBUG:
self.check_dependencies()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.wrap_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
# site-wide views.
urlpatterns = patterns('',
url(r'^$', wrap(self.index), name='index'),
url(r'^logout/$', self.logout, name='logout'),
url(r'^password_change/$',
wrap(self.password_change, cacheable=True),
name='password_change'),
url(r'^password_change_done/$',
wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^password_reset/$', self.password_reset, name='password_reset'),
url(r'^password_reset_done/$', self.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
self.password_reset_confirm,
name='password_reset_confirm'),
url(r'^reset_done/$', self.password_reset_complete, name='password_reset_complete'),
# url(r'^jsi18n/$',
# wrap(self.i18n_javascript, cacheable=True),
# name='jsi18n'),
# url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$',
# wrap(contenttype_views.shortcut)),
# url(r'^(?P<app_label>\w+)/$',
# wrap(self.app_index),
# name='app_list')
)
# # Add in each model's views.
# for model, model_admin in self._registry.iteritems():
# urlpatterns += patterns('',
# url(r'^%s/%s/' % (model._meta.app_label, model._meta.module_name),
# include(model_admin.urls))
# )
return urlpatterns
@property
def urls(self):
return self.get_urls() #, self.app_name, self.name
def password_change(self, request):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.auth.views import password_change
url = reverse('site:password_change_done')
defaults = {
'post_change_redirect': url,
'template_name': 'auth/password_change_form.html'
}
return password_change(request, **defaults)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import password_change_done
defaults = {
'extra_context': extra_context or {},
'template_name': 'auth/password_change_done.html'
}
return password_change_done(request, **defaults)
@never_cache
def password_reset(self, request):
"""
Handles the "reset password" task -- both form display and validation.
"""
from django.contrib.auth.views import password_reset
url = reverse('site:password_reset_done')
defaults = {
'is_admin_site' : False,
'template_name' : 'auth/password_reset_form.html',
'email_template_name' : 'auth/password_reset_email.html',
#'subject_template_name' = 'auth/password_reset_subject.txt',
'post_reset_redirect' : url,
}
return password_reset(request, **defaults)
def password_reset_done(self, request, extra_context=None):
"""
Displays the "success" page after a password reset.
"""
from django.contrib.auth.views import password_reset_done
defaults = {
'extra_context': extra_context or {},
'template_name': 'auth/password_reset_done.html'
}
return password_reset_done(request, **defaults)
@never_cache
def password_reset_confirm(self, request, extra_context=None):
from django.contrib.auth.views import password_reset_confirm
url = reverse('site:password_reset_complete')
defaults = {
'extra_context': extra_context or {},
'template_name': 'auth/password_reset_confirm.html',
'post_reset_redirect': url,
}
return password_reset_confirm(request, **defaults)
def password_reset_complete(self, request, extra_context=None):
from django.contrib.auth.views import password_reset_complete
extra = extra_context or {}
extra ['login_url'] = reverse_lazy('site:index')
defaults = {
'extra_context': extra,
'template_name': 'auth/password_reset_complete.html',
}
return password_reset_complete(request, **defaults)
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import logout
defaults = {
'extra_context': extra_context or {},
'template_name': 'auth/logged_out.html'
}
return logout(request, **defaults)
@never_cache
def index(self, request, extra_context=None):
context = {
'title': _('Welcome to log in!'),
}
#return views.index(request, context)
return TemplateResponse(request, ['orders/index.html'], context)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
from django.contrib.auth.views import login
context = {
'title': _('Log in'),
'app_path': request.get_full_path(),
REDIRECT_FIELD_NAME: request.get_full_path(),
}
context.update(extra_context or {})
defaults = {
'extra_context': context,
'authentication_form': AuthenticationForm,
'template_name': 'auth/login.html',
}
return login(request, **defaults)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = OrdersSite()
| {
"repo_name": "bubufox/HomeWork",
"path": "homework/orders/sites.py",
"copies": "1",
"size": "8629",
"license": "bsd-3-clause",
"hash": -2311148001202657300,
"line_mean": 36.0343347639,
"line_max": 100,
"alpha_frac": 0.6678641789,
"autogenerated": false,
"ratio": 3.888688598467778,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00800482519851488,
"num_lines": 233
} |
from functools import update_wrapper
from django.http import Http404, HttpResponseRedirect
from django.contrib.admin import ModelAdmin, actions
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.csrf import csrf_protect
from django.db.models.base import ModelBase
from django.apps import apps
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.engine import Engine
from django.template.response import TemplateResponse
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy, ugettext as _
from django.views.decorators.cache import never_cache
from django.conf import settings
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Django site admin')
# Text to put in each page's <h1>.
site_header = ugettext_lazy('Django administration')
# Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration')
# URL for the "View site" link at the top of each admin page.
site_url = '/'
login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
def __init__(self, name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured('The model %s is abstract, so it '
'cannot be registered with admin.' % model.__name__)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
if admin_class is not ModelAdmin and settings.DEBUG:
admin_class.check(model)
# Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
def unregister(self, model_or_iterable):
"""
Unregisters the given model(s).
If a model isn't already registered, this will raise NotRegistered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotRegistered('The model %s is not registered' % model.__name__)
del self._registry[model]
def is_registered(self, model):
"""
Check if a model class is registered with this `AdminSite`.
"""
return model in self._registry
def add_action(self, action, name=None):
"""
Register an action to be available globally.
"""
name = name or action.__name__
self._actions[name] = action
self._global_actions[name] = action
def disable_action(self, name):
"""
Disable a globally-registered action. Raises KeyError for invalid names.
"""
del self._actions[name]
def get_action(self, name):
"""
Explicitly get a registered global action whether it's enabled or
not. Raises KeyError for invalid names.
"""
return self._global_actions[name]
@property
def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
return six.iteritems(self._actions)
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
return request.user.is_active and request.user.is_staff
def check_dependencies(self):
"""
Check that all things needed to run the admin have been correctly installed.
The default implementation checks that admin and contenttypes apps are
installed, as well as the auth context processor.
"""
if not apps.is_installed('django.contrib.admin'):
raise ImproperlyConfigured("Put 'django.contrib.admin' in "
"your INSTALLED_APPS setting in order to use the admin application.")
if not apps.is_installed('django.contrib.contenttypes'):
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
"your INSTALLED_APPS setting in order to use the admin application.")
if 'django.contrib.auth.context_processors.auth' not in Engine.get_default().context_processors:
raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
"in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def admin_view(self, view, cacheable=False):
"""
Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You'll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import url
urls = super(MyAdminSite, self).get_urls()
urls += [
url(r'^my_view/$', self.admin_view(some_view))
]
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.
"""
def inner(request, *args, **kwargs):
if not self.has_permission(request):
if request.path == reverse('admin:logout', current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
# Inner import to prevent django.contrib.admin (app) from
# importing django.contrib.auth.models.User (unrelated model).
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
request.get_full_path(),
reverse('admin:login', current_app=self.name)
)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import url, include
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
if settings.DEBUG:
self.check_dependencies()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^$', wrap(self.index), name='index'),
url(r'^login/$', self.login, name='login'),
url(r'^logout/$', wrap(self.logout), name='logout'),
url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
name='view_on_site'),
]
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
for model, model_admin in six.iteritems(self._registry):
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
# If there were ModelAdmins registered, we should have a list of app
# labels for which we need to allow access to the app_index view,
if valid_app_labels:
regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
urlpatterns += [
url(regex, wrap(self.app_index), name='app_list'),
]
return urlpatterns
@property
def urls(self):
return self.get_urls(), 'admin', self.name
def each_context(self):
"""
Returns a dictionary of variables to put in the template context for
*every* page in the admin site.
"""
return {
'site_title': self.site_title,
'site_header': self.site_header,
'site_url': self.site_url,
}
def password_change(self, request, extra_context=None):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.admin.forms import AdminPasswordChangeForm
from django.contrib.auth.views import password_change
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {
'current_app': self.name,
'password_change_form': AdminPasswordChangeForm,
'post_change_redirect': url,
'extra_context': dict(self.each_context(), **(extra_context or {})),
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
return password_change(request, **defaults)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import password_change_done
defaults = {
'current_app': self.name,
'extra_context': dict(self.each_context(), **(extra_context or {})),
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
return password_change_done(request, **defaults)
def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
"""
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import logout
defaults = {
'current_app': self.name,
'extra_context': dict(self.each_context(), **(extra_context or {})),
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
return logout(request, **defaults)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
if request.method == 'GET' and self.has_permission(request):
# Already logged-in, redirect to admin index
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
from django.contrib.auth.views import login
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.admin.forms eventually imports User.
from django.contrib.admin.forms import AdminAuthenticationForm
context = dict(self.each_context(),
title=_('Log in'),
app_path=request.get_full_path(),
)
if (REDIRECT_FIELD_NAME not in request.GET and
REDIRECT_FIELD_NAME not in request.POST):
context[REDIRECT_FIELD_NAME] = request.get_full_path()
context.update(extra_context or {})
defaults = {
'extra_context': context,
'current_app': self.name,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'admin/login.html',
}
return login(request, **defaults)
@never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_dict = {}
for model, model_admin in self._registry.items():
app_label = model._meta.app_label
has_module_perms = model_admin.has_module_permission(request)
if has_module_perms:
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True in perms.values():
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change', False):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add', False):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': apps.get_app_config(app_label).verbose_name,
'app_label': app_label,
'app_url': reverse(
'admin:app_list',
kwargs={'app_label': app_label},
current_app=self.name,
),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
# Sort the apps alphabetically.
app_list = list(six.itervalues(app_dict))
app_list.sort(key=lambda x: x['name'].lower())
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
context = dict(
self.each_context(),
title=self.index_title,
app_list=app_list,
)
context.update(extra_context or {})
return TemplateResponse(request, self.index_template or
'admin/index.html', context,
current_app=self.name)
def app_index(self, request, app_label, extra_context=None):
app_name = apps.get_app_config(app_label).verbose_name
app_dict = {}
for model, model_admin in self._registry.items():
if app_label == model._meta.app_label:
has_module_perms = model_admin.has_module_permission(request)
if not has_module_perms:
raise PermissionDenied
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True in perms.values():
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change'):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add'):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_dict:
app_dict['models'].append(model_dict),
else:
# First time around, now that we know there's
# something to display, add in the necessary meta
# information.
app_dict = {
'name': app_name,
'app_label': app_label,
'app_url': '',
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
context = dict(self.each_context(),
title=_('%(app)s administration') % {'app': app_name},
app_list=[app_dict],
app_label=app_label,
)
context.update(extra_context or {})
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context, current_app=self.name)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
| {
"repo_name": "andyzsf/django",
"path": "django/contrib/admin/sites.py",
"copies": "2",
"size": "21209",
"license": "bsd-3-clause",
"hash": -3553218821901971500,
"line_mean": 41.2490039841,
"line_max": 117,
"alpha_frac": 0.5740487529,
"autogenerated": false,
"ratio": 4.563037865748709,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009376017151123593,
"num_lines": 502
} |
from functools import update_wrapper
from django.http import HttpResponseRedirect
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.csrf import csrf_protect
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator
from django.views.decorators.cache import never_cache
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django import forms
from . import models
from . forms import BaseFilterForm
try:
try:
from ..versioning import manager
from ..versioning.models import BaseVersionedModel
except ValueError:
from versioning import manager
from versioning.models import BaseVersionedModel
except ImportError:
manager = None
LOGIN_FORM_KEY = 'this_is_the_login_form'
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
Heavily copied from django's admin site
but instead of registering models
we register CMSBundle objects.
:param login_form: A Form class to use for the login form. \
Defaults to django's AdminAuthenticationForm.
:param login_template: Template for login page. Defaults to \
'cms/login.html'.
:param logout_template: Template for logout page. Defaults to \
'cms/logged_out.html'.
:param password_change_template: Template for password change page. \
Defaults to 'cms/password_change_form.html'.
:param password_change_done_template: Template displayed after \
password is changed. Defaults to 'cms/password_change_done.html'.
:param dashboard_template: Dashboard template. Defaults to \
cms/dashboard.html.
:param dashboard_home_url: Dashboard Homepage URL. Defaults to /admin/.
"""
login_form = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
dashboard_template = None
def __init__(self, name='default'):
self._registry = {}
self._model_registry = {}
self._titles = {}
self._order = {}
self.name = name
def register_model(self, model, bundle):
"""
Registers a bundle as the main bundle for a
model. Used when we need to lookup urls by
a model.
"""
if model in self._model_registry:
raise AlreadyRegistered('The model %s is already registered' \
% model)
if bundle.url_params:
raise Exception("A primary model bundle cannot have dynamic \
url_parameters")
self._model_registry[model] = bundle
def get_bundle_for_model(self, model):
"""
Returns the main bundle for the given
model
"""
return self._model_registry.get(model)
def unregister_model(self, model):
"""
Unregisters the given model.
"""
if model not in self._model_registry:
raise NotRegistered('The model %s is not registered' % model)
del self._model_registry[model]
def register(self, slug, bundle, order=1, title=None):
"""
Registers the bundle for a certain slug.
If a slug is already registered, this will raise AlreadyRegistered.
:param slug: The slug to register.
:param bundle: The bundle instance being registered.
:param order: An integer that controls where this bundle's \
dashboard links appear in relation to others.
"""
if slug in self._registry:
raise AlreadyRegistered('The url %s is already registered' % slug)
# Instantiate the admin class to save in the registry.
self._registry[slug] = bundle
self._order[slug] = order
if title:
self._titles[slug] = title
bundle.set_admin_site(self)
def unregister(self, slug):
"""
Unregisters the given url.
If a slug isn't already registered, this will raise NotRegistered.
"""
if slug not in self._registry:
raise NotRegistered('The slug %s is not registered' % slug)
bundle = self._registry[slug]
if bundle._meta.model and bundle._meta.primary_model_bundle:
self.unregister_model(bundle._meta.model)
del self._registry[slug]
del self._order[slug]
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
Currently checks that the user is active and a staff member.
"""
return request.user.is_active and request.user.is_staff
def admin_view(self, view, cacheable=False):
def inner(request, *args, **kwargs):
if manager:
manager.activate(BaseVersionedModel.DRAFT)
if not self.has_permission(request):
if request.path == reverse('admin:cms_logout'):
index_path = reverse('admin:cms_index')
return HttpResponseRedirect(index_path)
return self.login(request)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import url, include
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^$',
wrap(self.index),
name='cms_index'),
url(r'^logout/$',
wrap(self.logout),
name='cms_logout'),
url(r'^password_change/$',
wrap(self.password_change, cacheable=True),
name='cms_password_change'),
url(r'^password_change/done/$',
wrap(self.password_change_done, cacheable=True),
name='cms_password_change_done'),
]
# Add in each model's views.
for base, bundle in self._registry.iteritems():
urlpatterns += [
url(r'^%s/' % base, include(bundle.get_urls()))
]
return urlpatterns
@property
def urls(self):
return self.get_urls(), 'admin', self.name
def password_change(self, request):
"""
Handles the "change password" task -- both form display and validation.
Uses the default auth views.
"""
from django.contrib.auth.views import password_change
url = reverse('admin:cms_password_change_done')
defaults = {
'post_change_redirect': url,
'template_name': 'cms/password_change_form.html',
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
return password_change(request, **defaults)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import password_change_done
defaults = {
'extra_context': extra_context or {},
'template_name': 'cms/password_change_done.html',
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
return password_change_done(request, **defaults)
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import logout
defaults = {
'extra_context': extra_context or {},
'template_name': 'cms/logged_out.html',
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
return logout(request, **defaults)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
from django.contrib.auth.views import login
context = {
'title': _('Log in'),
'app_path': request.get_full_path(),
REDIRECT_FIELD_NAME: request.get_full_path(),
}
context.update(extra_context or {})
defaults = {
'extra_context': context,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'cms/login.html',
}
return login(request, **defaults)
def get_dashboard_urls(self, request):
nav = []
for k in sorted(self._order, key=self._order.get):
v = self._registry[k]
urls = v.get_dashboard_urls(request)
if urls:
title = self._titles.get(k, v.get_title())
nav.append((title, urls, v.name))
return nav
def get_dashboard_blocks(self, request):
blocks = []
for k in sorted(self._order, key=self._order.get):
v = self._registry[k]
block = v.get_dashboard_block(request)
if block:
title = self._titles.get(k, v.get_title())
blocks.append((title, block))
return blocks
def _get_allowed_sections(self, dashboard):
"""
Get the sections to display based on dashboard
"""
allowed_titles = [x[0] for x in dashboard]
allowed_sections = [x[2] for x in dashboard]
return tuple(allowed_sections), tuple(allowed_titles)
@never_cache
def index(self, request, extra_context=None):
"""
Displays the dashboard. Includes the main
navigation that the user has permission for as well
as the cms log for those sections. The log list can
be filtered by those same sections
and is paginated.
"""
dashboard = self.get_dashboard_urls(request)
dash_blocks = self.get_dashboard_blocks(request)
sections, titles = self._get_allowed_sections(dashboard)
choices = zip(sections, titles)
choices.sort(key=lambda tup: tup[1])
choices.insert(0, ('', 'All'))
class SectionFilterForm(BaseFilterForm):
section = forms.ChoiceField(required=False, choices=choices)
form = SectionFilterForm(request.GET)
filter_kwargs = form.get_filter_kwargs()
if not filter_kwargs and not request.user.is_superuser:
filter_kwargs['section__in'] = sections
cms_logs = models.CMSLog.objects.filter(**filter_kwargs
).order_by('-when')
template = self.dashboard_template or 'cms/dashboard.html'
paginator = Paginator(cms_logs[:20 * 100], 20,
allow_empty_first_page=True)
page_number = request.GET.get('page') or 1
try:
page_number = int(page_number)
except ValueError:
page_number = 1
page = paginator.page(page_number)
return TemplateResponse(request, [template], {
'dashboard': dashboard, 'blocks': dash_blocks,
'page': page, 'bundle': self._registry.values()[0],
'form': form},)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
| {
"repo_name": "ff0000/scarlet",
"path": "scarlet/cms/sites.py",
"copies": "1",
"size": "12103",
"license": "mit",
"hash": 6195971963326500000,
"line_mean": 33.9797687861,
"line_max": 79,
"alpha_frac": 0.6055523424,
"autogenerated": false,
"ratio": 4.394698620188816,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5500250962588816,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_protect
from django.contrib import admin
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from django.template.response import TemplateResponse
from django.views.decorators.cache import never_cache
from apps import Application
class Site(admin.AdminSite):
login_template = "auth/login.html"
logout_template = "auth/logout.html"
login_form = AuthenticationForm
widgets = ()
menus = []
def __init__(self, *args, **kwargs ):
super(Site, self).__init__(*args, **kwargs)
self._actions = {}
def set_menu_items(self, request):
if 'menu' not in request.session:
menus = []
self.menus = sorted(self.menus, key=lambda student: student[0])
for index, Menu in self.menus:
menus.extend(Menu.get_menus(request))
request.session['menu'] = menus
def get_menu_items(self, request):
if 'menu' not in request.session:
self.set_menu_items(request)
return request.session['menu']
def get_menu_item(self, request, name):
try:
return next(x for x in self.get_menu_items(request) if x.name == name)
except StopIteration:
raise PermissionDenied
def has_perm(self,perms_dict, request):
perm_name = perms_dict['perm']
perm_obj = None
if 'instance' in perms_dict:
perm_obj = perms_dict['instance']
return request.user.has_perm(perm_name, obj= perm_obj)
def admin_view(self, view, cacheable = False):
def inner(request, *args, **kwargs):
if not self.has_permission(request):
if request.path == reverse('logout',
current_app=self.name):
index_path = reverse('index', current_app=self.name)
return HttpResponseRedirect(index_path)
return self.login(request)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
@never_cache
def index(self, request):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
items =self.get_menu_items(request)
if hasattr(request, 'user') and not isinstance(request.user, AnonymousUser):
app_name = self.get_menu_items(request)[0].name if items else ''
return self.app_index(request,app_name)
else:
return self.login(request)
def register(self, model_or_iterable, admin_class=None, **options):
if not admin_class:
admin_class = Application
return super(Site, self).register(model_or_iterable,admin_class, **options)
def has_permission(self,request):
from django.core.urlresolvers import resolve
match = resolve(request.path)
if match.url_name == "pedagogico_matricula_candidate":
return True
if isinstance(request.user, AnonymousUser) and hasattr(request.user, 'roles') and request.user.roles:
return True
return request.user.is_authenticated() and request.user.is_active
def app_index(self, request, app_label):
print request.user.has_module_perms(app_label)
if request.user.has_module_perms(app_label):
enabled= {}
print 'uai?'
app = self.get_menu_item(request,app_label)
request.session['app'] = app
print 'uai?'
for Widget in app.widgets:
widget = Widget(request)
if widget.show_widget():
enabled[widget.name] = widget
print 'uai?'
context = {
'active_model': None,
'widgets': enabled
}
print 'uai?'
return TemplateResponse(request, app.template or [
'%s/app_index.html' % app_label,
'app_index.html'
], context, current_app=self.name)
else:
raise PermissionDenied
| {
"repo_name": "jAlpedrinha/DeclRY",
"path": "declry/main_application.py",
"copies": "1",
"size": "4666",
"license": "bsd-3-clause",
"hash": -9035134937290613000,
"line_mean": 37.8833333333,
"line_max": 109,
"alpha_frac": 0.6054436348,
"autogenerated": false,
"ratio": 4.284664830119375,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5390108464919375,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django import forms
from django.conf import settings
from django.contrib.admin.templatetags.admin_static import static
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView
from . import models, signals
from .formset import AdminForm
from .helpers import HierarchicalClass
from .const import *
class OptionsPageCollector():
def __init__(self, admin_site):
self.pages = []
self.admin_site =admin_site
def register(self, pageView):
if pageView in self.pages: return
# prepare form classes
form_classes = pageView.form_class_list[:]
if pageView.form_class:
form_classes.insert(0,pageView.form_class)
if not form_classes:
# autoload inner OptionForm classes
from django_options.forms import OptionsForm
form_classes = OptionsForm.nested_classes_in(pageView)
setattr(pageView,'form_class_list',form_classes)
if pageView.parent:
page = self.get_page(pageView.parent.code)
if not page:
raise ImproperlyConfigured('Cannot register a page "%s" with un-registered page "%s"' % (pageView.code, pageView.parent.code))
page.addChild(pageView)
else:
self.pages.append( pageView )
# auto register nested PageAdmin classes
for nestedView in BaseOptionsPage.nested_classes_in(pageView):
setattr(nestedView, 'parent', pageView)
self.register( nestedView )
def get_page(self, code):
for page in self.pages:
if page.code == code:
return page
elif code.startswith( page.code + SEPARATOR ):
return page.getChild( code )
return None
def as_view(self,**initkwargs):
@staff_member_required
def view(request, *args, **kwargs):
pageView = self.get_page(kwargs.get('page_code'))(**initkwargs)
if hasattr(pageView, 'get') and not hasattr(pageView, 'head'):
pageView.head = pageView.get
return pageView.dispatch(request, *args, **kwargs)
return view
def as_history_view(self):
@staff_member_required
def view(request, page_code):
"""The 'history' admin view for this model."""
from django.contrib.admin.models import LogEntry
from django.template.response import TemplateResponse
from django.db.models import Q
model = models.Option
action_list = LogEntry.objects.filter(
content_type__id__exact = ContentType.objects.get_for_model(model).id
).select_related().order_by('action_time')
full_page_code = PREFIX + page_code
if request.GET.get('full',False):
action_list = action_list.filter(Q(object_id= full_page_code ) | Q(object_id__startswith= full_page_code + SEPARATOR))
else:
action_list = action_list.filter(object_id = full_page_code)
# If no history was found, see whether this object even exists.
obj = self.get_page(page_code)
context = {
'title': _('Options changes history'),
'action_list': action_list,
'current_page': obj,
'is_full_history': request.GET.get('full',False)
}
return TemplateResponse(request, 'admin/options_page_history.html', context)
return view
def url_pattern(self, url):
if url[0] == '^':
return url[0] + PREFIX_URL_PATTERN + url[1:]
return PREFIX_URL_PATTERN + url
def view_wrap(self, view, admin_site):
def wrapper(*args, **kwargs):
return admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
class BaseOptionsPage(FormView, HierarchicalClass):
template_name = 'admin/options_page.html'
form_class = None
form_class_list = []
do_not_call_in_templates = True
def __init__(self, **kwargs):
super(BaseOptionsPage,self).__init__(**kwargs)
form_list_from_class = self.__class__.form_class_list[:]
self.form_class_list = []
for form_class in form_list_from_class:
self.addForm(form_class)
@classmethod
def full_title(cls):
if not hasattr(cls,'parent') or not cls.parent:
return cls.title
return cls.parent.full_title() + TITLE_SEPARATOR + (cls.title or cls.code.title())
def get_context_data(self, **kwargs):
context = super(BaseOptionsPage, self).get_context_data(**kwargs)
# context['options_page_list'] = option_pages.pages
context['current_page'] = self.__class__
return context
def get(self, request, *args, **kwargs):
"""
Override to allow multiple form
"""
context = {
'sections': [],
'media': self.media
}
for form_class in self.form_class_list:
form_instance = form_class()
adminForm = AdminForm(
form_instance,
form_instance.get_optionsets()
)
context['sections'].append(adminForm)
context['media'] += adminForm.media
return self.render_to_response(self.get_context_data(**context))
def log_form_saved(self,form , actions):
"""
Logging with contrib LogEntry model, useful information
to check latest changes of options form.
:return: message of log
"""
def make_list(elements):
if not elements: return ''
copy_elements = elements[:]
last = copy_elements.pop()
if not copy_elements: return last
return _("%(elements)s and %(last)s") % { 'elements': ", ".join(copy_elements), 'last': last }
list_dict = lambda x: {'element_list': make_list(actions[x]) }
message = []
if actions['added']:
message.append(_("%(element_list)s is added.") % list_dict('added'))
if actions['edited']:
message.append(_("%(element_list)s is edited.") % list_dict('edited'))
if actions['deleted']:
message.append(_("%(element_list)s is deleted.") % list_dict('deleted'))
message = _("%(option_page)s: %(actions)s") % {
'option_page': force_unicode(form.full_title()),
'actions': " ".join(message)
}
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = self.request.user.pk,
content_type_id = ContentType.objects.get_for_model(models.Option).pk,
object_id = PREFIX + self.get_code(),
object_repr = force_unicode(form.full_title()),
action_flag = CHANGE,
change_message = message
)
return message
def form_valid(self, form):
"""
Save a form and log results
"""
actions= {
'added' : [],
'edited' : [],
'deleted' : []
}
def collect_change_messages(sender, **kwargs):
option = kwargs.pop('option')
new_value = kwargs.pop('new_value')
old_value = kwargs.pop('old_value')
if old_value is None:
actions['added'].append(option)
elif new_value is None:
actions['deleted'].append(option)
elif old_value != new_value:
actions['edited'].append(option)
signals.option_value_changed.connect(collect_change_messages)
form.save()
signals.option_value_changed.disconnect(collect_change_messages)
from django.contrib import messages
if actions['added'] or actions['edited'] or actions['deleted']:
messages.success(self.request, self.log_form_saved(form, actions))
else:
messages.warning(self.request, _("Not option changes"))
self.success_url = reverse('admin:options-page', kwargs={'page_code':self.get_code()})
return super(BaseOptionsPage, self).form_valid(form)
def form_invalid(self, form):
"""
Prepare context for admin form errors
"""
sections = []
media = self.media
for form_class in self.form_class_list:
form_instance = form_class() if not isinstance(form, form_class) else form
adminForm = AdminForm(
form_instance,
form_instance.get_optionsets()
)
sections.append(adminForm)
media += adminForm.media
context = {
'sections': sections,
'media': media
}
from django.contrib import messages
messages.error(self.request, _("Check form errors"))
return self.render_to_response(self.get_context_data(**context))
def get_form_class(self):
"""
Override to allow single form submit
"""
request_code = self.request.POST.get(REQUEST_CODE_KEY)
assert request_code.startswith( self.get_code() ), "OptionsForm has invalid code"
for form in self.form_class_list:
if form.get_code() == request_code:
return form
return None
def addForm(self, form):
form.page = self
self.form_class_list.append(form)
@property
def media(self):
extra = '' if settings.DEBUG else '.min'
js = [
'core.js',
'admin/RelatedObjectLookups.js',
'jquery%s.js' % extra,
'jquery.init.js'
]
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
| {
"repo_name": "joke2k/django-options",
"path": "django_options/options.py",
"copies": "1",
"size": "10153",
"license": "bsd-3-clause",
"hash": -779648181966172500,
"line_mean": 31.857605178,
"line_max": 142,
"alpha_frac": 0.5823894415,
"autogenerated": false,
"ratio": 4.216362126245847,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5298751567745846,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django import http
from django.core.exceptions import ImproperlyConfigured
from django.template import RequestContext, loader
from django.template.response import TemplateResponse
from django.utils.log import getLogger
from django.utils.decorators import classonlymethod
logger = getLogger('django.request')
class View(object):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.iteritems():
setattr(self, key, value)
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(u"You tried to pass in the %s method name as a "
u"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError(u"%s() received an invalid keyword %r" % (
cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
self.request = request
self.args = args
self.kwargs = kwargs
return handler(request, *args, **kwargs)
def http_method_not_allowed(self, request, *args, **kwargs):
allowed_methods = [m for m in self.http_method_names if hasattr(self, m)]
logger.warning('Method Not Allowed (%s): %s' % (request.method, request.path),
extra={
'status_code': 405,
'request': self.request
}
)
return http.HttpResponseNotAllowed(allowed_methods)
def head(self, *args, **kwargs):
return self.get(*args, **kwargs)
class TemplateResponseMixin(object):
"""
A mixin that can be used to render a template.
"""
template_name = None
response_class = TemplateResponse
def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template rendered with the given context.
"""
return self.response_class(
request = self.request,
template = self.get_template_names(),
context = context,
**response_kwargs
)
def get_template_names(self):
"""
Returns a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
"""
if self.template_name is None:
raise ImproperlyConfigured(
"TemplateResponseMixin requires either a definition of "
"'template_name' or an implementation of 'get_template_names()'")
else:
return [self.template_name]
class TemplateView(TemplateResponseMixin, View):
"""
A view that renders a template.
"""
def get_context_data(self, **kwargs):
return {
'params': kwargs
}
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
class RedirectView(View):
"""
A view that provides a redirect on any GET request.
"""
permanent = True
url = None
query_string = False
def get_redirect_url(self, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
args = self.request.META["QUERY_STRING"]
if args and self.query_string:
url = "%s?%s" % (self.url, args)
else:
url = self.url
return url % kwargs
else:
return None
def get(self, request, *args, **kwargs):
url = self.get_redirect_url(**kwargs)
if url:
if self.permanent:
return http.HttpResponsePermanentRedirect(url)
else:
return http.HttpResponseRedirect(url)
else:
logger.warning('Gone: %s' % self.request.path,
extra={
'status_code': 410,
'request': self.request
})
return http.HttpResponseGone()
def head(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def options(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
| {
"repo_name": "mitsuhiko/django",
"path": "django/views/generic/base.py",
"copies": "1",
"size": "6175",
"license": "bsd-3-clause",
"hash": -1348190229672931000,
"line_mean": 33.1160220994,
"line_max": 89,
"alpha_frac": 0.5834817814,
"autogenerated": false,
"ratio": 4.458483754512636,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0017943279358119961,
"num_lines": 181
} |
from functools import update_wrapper
from django import http
from django.core.exceptions import ImproperlyConfigured
from django.template.response import TemplateResponse
from django.utils.log import getLogger
from django.utils.decorators import classonlymethod
logger = getLogger('django.request')
class ContextMixin(object):
"""
A default context mixin that passes the keyword arguments received by
get_context_data as the template context.
"""
def get_context_data(self, **kwargs):
return kwargs
class View(object):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""
http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
def __init__(self, **kwargs):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in kwargs.iteritems():
setattr(self, key, value)
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(u"You tried to pass in the %s method name as a "
u"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError(u"%s() received an invalid keyword %r" % (
cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
self.request = request
self.args = args
self.kwargs = kwargs
return handler(request, *args, **kwargs)
def http_method_not_allowed(self, request, *args, **kwargs):
allowed_methods = [m for m in self.http_method_names if hasattr(self, m)]
logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
extra={
'status_code': 405,
'request': self.request
}
)
return http.HttpResponseNotAllowed(allowed_methods)
class TemplateResponseMixin(object):
"""
A mixin that can be used to render a template.
"""
template_name = None
response_class = TemplateResponse
def render_to_response(self, context, **response_kwargs):
"""
Returns a response with a template rendered with the given context.
"""
return self.response_class(
request = self.request,
template = self.get_template_names(),
context = context,
**response_kwargs
)
def get_template_names(self):
"""
Returns a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
"""
if self.template_name is None:
raise ImproperlyConfigured(
"TemplateResponseMixin requires either a definition of "
"'template_name' or an implementation of 'get_template_names()'")
else:
return [self.template_name]
class TemplateView(TemplateResponseMixin, ContextMixin, View):
"""
A view that renders a template. This view is different from all the others
insofar as it also passes ``kwargs`` as ``params`` to the template context.
"""
def get(self, request, *args, **kwargs):
context = self.get_context_data(params=kwargs)
return self.render_to_response(context)
class RedirectView(View):
"""
A view that provides a redirect on any GET request.
"""
permanent = True
url = None
query_string = False
def get_redirect_url(self, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
url = self.url % kwargs
args = self.request.META.get('QUERY_STRING', '')
if args and self.query_string:
url = "%s?%s" % (url, args)
return url
else:
return None
def get(self, request, *args, **kwargs):
url = self.get_redirect_url(**kwargs)
if url:
if self.permanent:
return http.HttpResponsePermanentRedirect(url)
else:
return http.HttpResponseRedirect(url)
else:
logger.warning('Gone: %s', self.request.path,
extra={
'status_code': 410,
'request': self.request
})
return http.HttpResponseGone()
def head(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def options(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
| {
"repo_name": "akaihola/django",
"path": "django/views/generic/base.py",
"copies": "10",
"size": "6401",
"license": "bsd-3-clause",
"hash": 6564770375400275000,
"line_mean": 33.7880434783,
"line_max": 89,
"alpha_frac": 0.5905327293,
"autogenerated": false,
"ratio": 4.4575208913649025,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0017673036163759236,
"num_lines": 184
} |
from functools import update_wrapper
from django_pyres.conf import settings
from django import db
from .core import pyres
def close_connection_after(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if settings.PYRES_USE_QUEUE:
db.close_connection()
return result
update_wrapper(wrapper, func)
return wrapper
class Job(object):
"""
Class that wraps a function to enqueue in pyres
"""
_resque_conn = pyres
def __init__(self, func, queue):
self.func = close_connection_after(func)
#self.priority = priority
# Allow this class to be called by pyres
self.queue = str(queue)
self.perform = self.func
# Wrap func
update_wrapper(self, func)
# _resque wraps the underlying resque connection and delays initialization
# until needed
@property
def _resque(self):
return self._resque_conn
@_resque.setter # NOQA
def _resque(self, val):
self._resque_conn = val
def enqueue(self, *args, **kwargs):
if settings.PYRES_USE_QUEUE:
queue = kwargs.pop('queue', self.queue)
if kwargs:
raise Exception("Cannot pass kwargs to enqueued tasks")
class_str = '%s.%s' % (self.__module__, self.__name__)
self._resque.enqueue_from_string(class_str, queue, *args)
else:
return self.func(*args, **kwargs)
def enqueue_at(self, dt, *args, **kwargs):
queue = kwargs.pop('queue', self.queue)
if kwargs:
raise Exception('Cannot pass kwargs to enqueued tasks')
class_str = '%s.%s' % (self.__module__, self.__name__)
self._resque.enqueue_at_from_string(dt, class_str, queue, *args)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __repr__(self):
return 'Job(func=%s, queue=%s)' % (self.func, self.queue)
def job(queue, cls=Job):
def _task(f):
return cls(f, queue)
return _task
| {
"repo_name": "Pyres/django-pyres",
"path": "django_pyres/decorators.py",
"copies": "1",
"size": "2039",
"license": "bsd-3-clause",
"hash": 6072300572393844000,
"line_mean": 27.7183098592,
"line_max": 78,
"alpha_frac": 0.595389897,
"autogenerated": false,
"ratio": 3.7550644567219154,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4850454353721915,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.views.generic import View
class MethodMapView(View):
@classmethod
def as_view(cls, method_map=None, **initkwargs):
if method_map:
# NOTE: The below has been taken from super.as_view.
# If that code changes this will also need to be updated. The only thing modified
# below is the mapping of methods.
def view(request, *args, **kwargs):
self = cls(**initkwargs)
# The below mapping allows us to use this class for multiple URL patterns
for http_method, method in method_map.items():
setattr(self, http_method, getattr(self, method))
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
update_wrapper(view, cls, updated=())
update_wrapper(view, cls.dispatch, assigned=())
return view
else:
return super(MethodMapView, cls).as_view(**initkwargs) | {
"repo_name": "svisser/silk",
"path": "django_silky/silk/views/method_map_view.py",
"copies": "4",
"size": "1213",
"license": "mit",
"hash": -5687353836519815000,
"line_mean": 43.962962963,
"line_max": 93,
"alpha_frac": 0.5754328112,
"autogenerated": false,
"ratio": 4.577358490566038,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7152791301766038,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from functools import partial
from inspect import signature, Parameter
from parsl.app.errors import wrap_error
from parsl.app.app import AppBase
from parsl.dataflow.dflow import DataFlowKernelLoader
def remote_side_bash_executor(func, *args, **kwargs):
"""Executes the supplied function with *args and **kwargs to get a
command-line to run, and then run that command-line using bash.
"""
import os
import subprocess
import parsl.app.errors as pe
from parsl.utils import get_std_fname_mode
func_name = func.__name__
executable = None
# Try to run the func to compose the commandline
try:
# Execute the func to get the commandline
executable = func(*args, **kwargs)
if not isinstance(executable, str):
raise ValueError(f"Expected a str for bash_app commandline, got {type(executable)}")
except AttributeError as e:
if executable is not None:
raise pe.AppBadFormatting("App formatting failed for app '{}' with AttributeError: {}".format(func_name, e))
else:
raise pe.BashAppNoReturn("Bash app '{}' did not return a value, or returned None - with this exception: {}".format(func_name, e))
except IndexError as e:
raise pe.AppBadFormatting("App formatting failed for app '{}' with IndexError: {}".format(func_name, e))
except Exception as e:
raise e
# Updating stdout, stderr if values passed at call time.
def open_std_fd(fdname):
# fdname is 'stdout' or 'stderr'
stdfspec = kwargs.get(fdname) # spec is str name or tuple (name, mode)
if stdfspec is None:
return None
fname, mode = get_std_fname_mode(fdname, stdfspec)
try:
if os.path.dirname(fname):
os.makedirs(os.path.dirname(fname), exist_ok=True)
fd = open(fname, mode)
except Exception as e:
raise pe.BadStdStreamFile(fname, e)
return fd
std_out = open_std_fd('stdout')
std_err = open_std_fd('stderr')
timeout = kwargs.get('walltime')
if std_err is not None:
print('--> executable follows <--\n{}\n--> end executable <--'.format(executable), file=std_err, flush=True)
returncode = None
try:
proc = subprocess.Popen(executable, stdout=std_out, stderr=std_err, shell=True, executable='/bin/bash', close_fds=False)
proc.wait(timeout=timeout)
returncode = proc.returncode
except subprocess.TimeoutExpired:
raise pe.AppTimeout("[{}] App exceeded walltime: {} seconds".format(func_name, timeout))
except Exception as e:
raise pe.AppException("[{}] App caught exception with returncode: {}".format(func_name, returncode), e)
if returncode != 0:
raise pe.BashExitFailure(func_name, proc.returncode)
# TODO : Add support for globs here
missing = []
for outputfile in kwargs.get('outputs', []):
fpath = outputfile.filepath
if not os.path.exists(fpath):
missing.extend([outputfile])
if missing:
raise pe.MissingOutputs("[{}] Missing outputs".format(func_name), missing)
return returncode
class BashApp(AppBase):
def __init__(self, func, data_flow_kernel=None, cache=False, executors='all', ignore_for_cache=None):
super().__init__(func, data_flow_kernel=data_flow_kernel, executors=executors, cache=cache, ignore_for_cache=ignore_for_cache)
self.kwargs = {}
# We duplicate the extraction of parameter defaults
# to self.kwargs to ensure availability at point of
# command string format. Refer: #349
sig = signature(func)
for s in sig.parameters:
if sig.parameters[s].default is not Parameter.empty:
self.kwargs[s] = sig.parameters[s].default
# update_wrapper allows remote_side_bash_executor to masquerade as self.func
# partial is used to attach the first arg the "func" to the remote_side_bash_executor
# this is done to avoid passing a function type in the args which parsl.serializer
# doesn't support
remote_fn = partial(update_wrapper(remote_side_bash_executor, self.func), self.func)
remote_fn.__name__ = self.func.__name__
self.wrapped_remote_function = wrap_error(remote_fn)
def __call__(self, *args, **kwargs):
"""Handle the call to a Bash app.
Args:
- Arbitrary
Kwargs:
- Arbitrary
Returns:
App_fut
"""
invocation_kwargs = {}
invocation_kwargs.update(self.kwargs)
invocation_kwargs.update(kwargs)
if self.data_flow_kernel is None:
dfk = DataFlowKernelLoader.dfk()
else:
dfk = self.data_flow_kernel
app_fut = dfk.submit(self.wrapped_remote_function,
app_args=args,
executors=self.executors,
cache=self.cache,
ignore_for_cache=self.ignore_for_cache,
app_kwargs=invocation_kwargs)
return app_fut
| {
"repo_name": "Parsl/parsl",
"path": "parsl/app/bash.py",
"copies": "1",
"size": "5202",
"license": "apache-2.0",
"hash": 6868480102479457000,
"line_mean": 34.1486486486,
"line_max": 141,
"alpha_frac": 0.6228373702,
"autogenerated": false,
"ratio": 4.099290780141844,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5222128150341844,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from importlib import import_module
from django.apps import AppConfig
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.conf import settings
from django.conf.urls import url
from django.template.response import TemplateResponse
class DefaultAppConfig(AppConfig):
name = 'gipsy.dashboard'
def ready(self):
class GipsyAdminSite(AdminSite):
def get_urls(self):
default_urlpatterns = super(GipsyAdminSite, self).get_urls()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args,
**kwargs)
return update_wrapper(wrapper, view)
urlpatterns = [
url(r'^$', wrap(self.dashboard), name='index'),
url(r'^all-apps$',
wrap(self.index),
name='all_apps')
]
return urlpatterns + default_urlpatterns
def init_dashboard_class(self):
dashboard_module = getattr(
settings,
'GIPSY_DASHBOARD',
'gipsy.dashboard.presets.default.DashboardDefault'
)
mod, inst = dashboard_module.rsplit('.', 1)
mod = import_module(mod)
return getattr(mod, inst)
def dashboard(self, request):
"""
Displays the dashboard on the main page and triggers widget
from the settings.GIPSY_DASHBOARD constant.
"""
request.current_app = self.name
context = dict(
dashboard=self.init_dashboard_class()(request),
)
return TemplateResponse(request, 'admin/dashboard.html',
context)
mysite = GipsyAdminSite()
admin.site = mysite
admin.sites.site = mysite
| {
"repo_name": "RevSquare/gipsy",
"path": "gipsy/dashboard/apps.py",
"copies": "1",
"size": "2142",
"license": "mit",
"hash": 9175107532428142000,
"line_mean": 35.9310344828,
"line_max": 76,
"alpha_frac": 0.5210084034,
"autogenerated": false,
"ratio": 5.136690647482014,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6157699050882014,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from importlib import import_module
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.conf import settings
from django.conf.urls import patterns, url
from django.template.response import TemplateResponse
from ..admin import GipsyMenu, ChildrenInline
from .models import GipsyDashboardMenu
class ChildrenDashboardInline(ChildrenInline):
model = GipsyDashboardMenu
exclude = ('icon',)
class GipsyDashboardMenuAdmin(GipsyMenu):
inlines = [ChildrenDashboardInline]
exclude = ('url', 'parent',)
class GipsyAdminSite(AdminSite):
def get_urls(self):
default_urlpatterns = super(GipsyAdminSite, self).get_urls()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
urlpatterns = patterns(
'',
url(r'^$', wrap(self.dashboard), name='index'),
url(r'^all-apps$',
wrap(self.index),
name='all_apps')
)
return urlpatterns + default_urlpatterns
def init_dashboard_class(self):
dashboard_module = getattr(
settings,
'GIPSY_DASHBOARD',
'gipsy.dashboard.presets.default.DashboardDefault'
)
mod, inst = dashboard_module.rsplit('.', 1)
mod = import_module(mod)
return getattr(mod, inst)
def dashboard(self, request):
"""
Displays the dashboard on the main page and triggers widget
from the settings.GIPSY_DASHBOARD constant.
"""
request.current_app = self.name
context = dict(
dashboard=self.init_dashboard_class()(request),
)
return TemplateResponse(request, 'admin/dashboard.html', context)
if not hasattr(settings, 'GIPSY_ENABLE_ADMINSITE') or \
settings.GIPSY_ENABLE_ADMINSITE is not False:
admin.site = GipsyAdminSite(name='gipsy_admin')
admin.site.register(GipsyDashboardMenu, GipsyDashboardMenuAdmin)
| {
"repo_name": "Seha16/gipsy",
"path": "gipsy/dashboard/admin.py",
"copies": "2",
"size": "2121",
"license": "bsd-3-clause",
"hash": -2801167000205613000,
"line_mean": 31.1363636364,
"line_max": 73,
"alpha_frac": 0.6572371523,
"autogenerated": false,
"ratio": 4.1104651162790695,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00027056277056277056,
"num_lines": 66
} |
from functools import update_wrapper
from io import BytesIO
from .._compat import to_native
from .._compat import to_unicode
from .._compat import wsgi_decoding_dance
from .._compat import wsgi_get_bytes
from ..datastructures import CombinedMultiDict
from ..datastructures import EnvironHeaders
from ..datastructures import ImmutableList
from ..datastructures import ImmutableMultiDict
from ..datastructures import ImmutableTypeConversionDict
from ..datastructures import iter_multi_items
from ..datastructures import MultiDict
from ..formparser import default_stream_factory
from ..formparser import FormDataParser
from ..http import parse_cookie
from ..http import parse_options_header
from ..urls import url_decode
from ..utils import cached_property
from ..utils import environ_property
from ..wsgi import get_content_length
from ..wsgi import get_current_url
from ..wsgi import get_host
from ..wsgi import get_input_stream
class BaseRequest(object):
"""Very basic request object. This does not implement advanced stuff like
entity tag parsing or cache controls. The request object is created with
the WSGI environment as first argument and will add itself to the WSGI
environment as ``'werkzeug.request'`` unless it's created with
`populate_request` set to False.
There are a couple of mixins available that add additional functionality
to the request object, there is also a class called `Request` which
subclasses `BaseRequest` and all the important mixins.
It's a good idea to create a custom subclass of the :class:`BaseRequest`
and add missing functionality either via mixins or direct implementation.
Here an example for such subclasses::
from werkzeug.wrappers import BaseRequest, ETagRequestMixin
class Request(BaseRequest, ETagRequestMixin):
pass
Request objects are **read only**. As of 0.5 modifications are not
allowed in any place. Unlike the lower level parsing functions the
request object will use immutable objects everywhere possible.
Per default the request object will assume all the text data is `utf-8`
encoded. Please refer to :doc:`the unicode chapter </unicode>` for more
details about customizing the behavior.
Per default the request object will be added to the WSGI
environment as `werkzeug.request` to support the debugging system.
If you don't want that, set `populate_request` to `False`.
If `shallow` is `True` the environment is initialized as shallow
object around the environ. Every operation that would modify the
environ in any way (such as consuming form data) raises an exception
unless the `shallow` attribute is explicitly set to `False`. This
is useful for middlewares where you don't want to consume the form
data by accident. A shallow request is not populated to the WSGI
environment.
.. versionchanged:: 0.5
read-only mode was enforced by using immutables classes for all
data.
"""
#: the charset for the request, defaults to utf-8
charset = "utf-8"
#: the error handling procedure for errors, defaults to 'replace'
encoding_errors = "replace"
#: the maximum content length. This is forwarded to the form data
#: parsing function (:func:`parse_form_data`). When set and the
#: :attr:`form` or :attr:`files` attribute is accessed and the
#: parsing fails because more than the specified value is transmitted
#: a :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised.
#:
#: Have a look at :ref:`dealing-with-request-data` for more details.
#:
#: .. versionadded:: 0.5
max_content_length = None
#: the maximum form field size. This is forwarded to the form data
#: parsing function (:func:`parse_form_data`). When set and the
#: :attr:`form` or :attr:`files` attribute is accessed and the
#: data in memory for post data is longer than the specified value a
#: :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised.
#:
#: Have a look at :ref:`dealing-with-request-data` for more details.
#:
#: .. versionadded:: 0.5
max_form_memory_size = None
#: the class to use for `args` and `form`. The default is an
#: :class:`~werkzeug.datastructures.ImmutableMultiDict` which supports
#: multiple values per key. alternatively it makes sense to use an
#: :class:`~werkzeug.datastructures.ImmutableOrderedMultiDict` which
#: preserves order or a :class:`~werkzeug.datastructures.ImmutableDict`
#: which is the fastest but only remembers the last key. It is also
#: possible to use mutable structures, but this is not recommended.
#:
#: .. versionadded:: 0.6
parameter_storage_class = ImmutableMultiDict
#: the type to be used for list values from the incoming WSGI environment.
#: By default an :class:`~werkzeug.datastructures.ImmutableList` is used
#: (for example for :attr:`access_list`).
#:
#: .. versionadded:: 0.6
list_storage_class = ImmutableList
#: the type to be used for dict values from the incoming WSGI environment.
#: By default an
#: :class:`~werkzeug.datastructures.ImmutableTypeConversionDict` is used
#: (for example for :attr:`cookies`).
#:
#: .. versionadded:: 0.6
dict_storage_class = ImmutableTypeConversionDict
#: The form data parser that shoud be used. Can be replaced to customize
#: the form date parsing.
form_data_parser_class = FormDataParser
#: Optionally a list of hosts that is trusted by this request. By default
#: all hosts are trusted which means that whatever the client sends the
#: host is will be accepted.
#:
#: Because `Host` and `X-Forwarded-Host` headers can be set to any value by
#: a malicious client, it is recommended to either set this property or
#: implement similar validation in the proxy (if application is being run
#: behind one).
#:
#: .. versionadded:: 0.9
trusted_hosts = None
#: Indicates whether the data descriptor should be allowed to read and
#: buffer up the input stream. By default it's enabled.
#:
#: .. versionadded:: 0.9
disable_data_descriptor = False
def __init__(self, environ, populate_request=True, shallow=False):
self.environ = environ
if populate_request and not shallow:
self.environ["werkzeug.request"] = self
self.shallow = shallow
def __repr__(self):
# make sure the __repr__ even works if the request was created
# from an invalid WSGI environment. If we display the request
# in a debug session we don't want the repr to blow up.
args = []
try:
args.append("'%s'" % to_native(self.url, self.url_charset))
args.append("[%s]" % self.method)
except Exception:
args.append("(invalid WSGI environ)")
return "<%s %s>" % (self.__class__.__name__, " ".join(args))
@property
def url_charset(self):
"""The charset that is assumed for URLs. Defaults to the value
of :attr:`charset`.
.. versionadded:: 0.6
"""
return self.charset
@classmethod
def from_values(cls, *args, **kwargs):
"""Create a new request object based on the values provided. If
environ is given missing values are filled from there. This method is
useful for small scripts when you need to simulate a request from an URL.
Do not use this method for unittesting, there is a full featured client
object (:class:`Client`) that allows to create multipart requests,
support for cookies etc.
This accepts the same options as the
:class:`~werkzeug.test.EnvironBuilder`.
.. versionchanged:: 0.5
This method now accepts the same arguments as
:class:`~werkzeug.test.EnvironBuilder`. Because of this the
`environ` parameter is now called `environ_overrides`.
:return: request object
"""
from ..test import EnvironBuilder
charset = kwargs.pop("charset", cls.charset)
kwargs["charset"] = charset
builder = EnvironBuilder(*args, **kwargs)
try:
return builder.get_request(cls)
finally:
builder.close()
@classmethod
def application(cls, f):
"""Decorate a function as responder that accepts the request as first
argument. This works like the :func:`responder` decorator but the
function is passed the request object as first argument and the
request object will be closed automatically::
@Request.application
def my_wsgi_app(request):
return Response('Hello World!')
As of Werkzeug 0.14 HTTP exceptions are automatically caught and
converted to responses instead of failing.
:param f: the WSGI callable to decorate
:return: a new WSGI callable
"""
#: return a callable that wraps the -2nd argument with the request
#: and calls the function with all the arguments up to that one and
#: the request. The return value is then called with the latest
#: two arguments. This makes it possible to use this decorator for
#: both methods and standalone WSGI functions.
from ..exceptions import HTTPException
def application(*args):
request = cls(args[-2])
with request:
try:
resp = f(*args[:-2] + (request,))
except HTTPException as e:
resp = e.get_response(args[-2])
return resp(*args[-2:])
return update_wrapper(application, f)
def _get_file_stream(
self, total_content_length, content_type, filename=None, content_length=None
):
"""Called to get a stream for the file upload.
This must provide a file-like class with `read()`, `readline()`
and `seek()` methods that is both writeable and readable.
The default implementation returns a temporary file if the total
content length is higher than 500KB. Because many browsers do not
provide a content length for the files only the total content
length matters.
:param total_content_length: the total content length of all the
data in the request combined. This value
is guaranteed to be there.
:param content_type: the mimetype of the uploaded file.
:param filename: the filename of the uploaded file. May be `None`.
:param content_length: the length of this file. This value is usually
not provided because webbrowsers do not provide
this value.
"""
return default_stream_factory(
total_content_length=total_content_length,
filename=filename,
content_type=content_type,
content_length=content_length,
)
@property
def want_form_data_parsed(self):
"""Returns True if the request method carries content. As of
Werkzeug 0.9 this will be the case if a content type is transmitted.
.. versionadded:: 0.8
"""
return bool(self.environ.get("CONTENT_TYPE"))
def make_form_data_parser(self):
"""Creates the form data parser. Instantiates the
:attr:`form_data_parser_class` with some parameters.
.. versionadded:: 0.8
"""
return self.form_data_parser_class(
self._get_file_stream,
self.charset,
self.encoding_errors,
self.max_form_memory_size,
self.max_content_length,
self.parameter_storage_class,
)
def _load_form_data(self):
"""Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this method to
force the parsing of the form data.
.. versionadded:: 0.8
"""
# abort early if we have already consumed the stream
if "form" in self.__dict__:
return
_assert_not_shallow(self)
if self.want_form_data_parsed:
content_type = self.environ.get("CONTENT_TYPE", "")
content_length = get_content_length(self.environ)
mimetype, options = parse_options_header(content_type)
parser = self.make_form_data_parser()
data = parser.parse(
self._get_stream_for_parsing(), mimetype, content_length, options
)
else:
data = (
self.stream,
self.parameter_storage_class(),
self.parameter_storage_class(),
)
# inject the values into the instance dict so that we bypass
# our cached_property non-data descriptor.
d = self.__dict__
d["stream"], d["form"], d["files"] = data
def _get_stream_for_parsing(self):
"""This is the same as accessing :attr:`stream` with the difference
that if it finds cached data from calling :meth:`get_data` first it
will create a new stream out of the cached data.
.. versionadded:: 0.9.3
"""
cached_data = getattr(self, "_cached_data", None)
if cached_data is not None:
return BytesIO(cached_data)
return self.stream
def close(self):
"""Closes associated resources of this request object. This
closes all file handles explicitly. You can also use the request
object in a with statement which will automatically close it.
.. versionadded:: 0.9
"""
files = self.__dict__.get("files")
for _key, value in iter_multi_items(files or ()):
value.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
self.close()
@cached_property
def stream(self):
"""
If the incoming form data was not encoded with a known mimetype
the data is stored unmodified in this stream for consumption. Most
of the time it is a better idea to use :attr:`data` which will give
you that data as a string. The stream only returns the data once.
Unlike :attr:`input_stream` this stream is properly guarded that you
can't accidentally read past the length of the input. Werkzeug will
internally always refer to this stream to read data which makes it
possible to wrap this object with a stream that does filtering.
.. versionchanged:: 0.9
This stream is now always available but might be consumed by the
form parser later on. Previously the stream was only set if no
parsing happened.
"""
_assert_not_shallow(self)
return get_input_stream(self.environ)
input_stream = environ_property(
"wsgi.input",
"""The WSGI input stream.
In general it's a bad idea to use this one because you can
easily read past the boundary. Use the :attr:`stream`
instead.""",
)
@cached_property
def args(self):
"""The parsed URL parameters (the part in the URL after the question
mark).
By default an
:class:`~werkzeug.datastructures.ImmutableMultiDict`
is returned from this function. This can be changed by setting
:attr:`parameter_storage_class` to a different type. This might
be necessary if the order of the form data is important.
"""
return url_decode(
wsgi_get_bytes(self.environ.get("QUERY_STRING", "")),
self.url_charset,
errors=self.encoding_errors,
cls=self.parameter_storage_class,
)
@cached_property
def data(self):
"""
Contains the incoming request data as string in case it came with
a mimetype Werkzeug does not handle.
"""
if self.disable_data_descriptor:
raise AttributeError("data descriptor is disabled")
# XXX: this should eventually be deprecated.
# We trigger form data parsing first which means that the descriptor
# will not cache the data that would otherwise be .form or .files
# data. This restores the behavior that was there in Werkzeug
# before 0.9. New code should use :meth:`get_data` explicitly as
# this will make behavior explicit.
return self.get_data(parse_form_data=True)
def get_data(self, cache=True, as_text=False, parse_form_data=False):
"""This reads the buffered incoming data from the client into one
bytestring. By default this is cached but that behavior can be
changed by setting `cache` to `False`.
Usually it's a bad idea to call this method without checking the
content length first as a client could send dozens of megabytes or more
to cause memory problems on the server.
Note that if the form data was already parsed this method will not
return anything as form data parsing does not cache the data like
this method does. To implicitly invoke form data parsing function
set `parse_form_data` to `True`. When this is done the return value
of this method will be an empty string if the form parser handles
the data. This generally is not necessary as if the whole data is
cached (which is the default) the form parser will used the cached
data to parse the form data. Please be generally aware of checking
the content length first in any case before calling this method
to avoid exhausting server memory.
If `as_text` is set to `True` the return value will be a decoded
unicode string.
.. versionadded:: 0.9
"""
rv = getattr(self, "_cached_data", None)
if rv is None:
if parse_form_data:
self._load_form_data()
rv = self.stream.read()
if cache:
self._cached_data = rv
if as_text:
rv = rv.decode(self.charset, self.encoding_errors)
return rv
@cached_property
def form(self):
"""The form parameters. By default an
:class:`~werkzeug.datastructures.ImmutableMultiDict`
is returned from this function. This can be changed by setting
:attr:`parameter_storage_class` to a different type. This might
be necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but instead
in the :attr:`files` attribute.
.. versionchanged:: 0.9
Previous to Werkzeug 0.9 this would only contain form data for POST
and PUT requests.
"""
self._load_form_data()
return self.form
@cached_property
def values(self):
"""A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`form`."""
args = []
for d in self.args, self.form:
if not isinstance(d, MultiDict):
d = MultiDict(d)
args.append(d)
return CombinedMultiDict(args)
@cached_property
def files(self):
""":class:`~werkzeug.datastructures.MultiDict` object containing
all uploaded files. Each key in :attr:`files` is the name from the
``<input type="file" name="">``. Each value in :attr:`files` is a
Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.
It basically behaves like a standard file object you know from Python,
with the difference that it also has a
:meth:`~werkzeug.datastructures.FileStorage.save` function that can
store the file on the filesystem.
Note that :attr:`files` will only contain data if the request method was
POST, PUT or PATCH and the ``<form>`` that posted to the request had
``enctype="multipart/form-data"``. It will be empty otherwise.
See the :class:`~werkzeug.datastructures.MultiDict` /
:class:`~werkzeug.datastructures.FileStorage` documentation for
more details about the used data structure.
"""
self._load_form_data()
return self.files
@cached_property
def cookies(self):
"""A :class:`dict` with the contents of all cookies transmitted with
the request."""
return parse_cookie(
self.environ,
self.charset,
self.encoding_errors,
cls=self.dict_storage_class,
)
@cached_property
def headers(self):
"""The headers from the WSGI environ as immutable
:class:`~werkzeug.datastructures.EnvironHeaders`.
"""
return EnvironHeaders(self.environ)
@cached_property
def path(self):
"""Requested path as unicode. This works a bit like the regular path
info in the WSGI environment but will always include a leading slash,
even if the URL root is accessed.
"""
raw_path = wsgi_decoding_dance(
self.environ.get("PATH_INFO") or "", self.charset, self.encoding_errors
)
return "/" + raw_path.lstrip("/")
@cached_property
def full_path(self):
"""Requested path as unicode, including the query string."""
return self.path + u"?" + to_unicode(self.query_string, self.url_charset)
@cached_property
def script_root(self):
"""The root path of the script without the trailing slash."""
raw_path = wsgi_decoding_dance(
self.environ.get("SCRIPT_NAME") or "", self.charset, self.encoding_errors
)
return raw_path.rstrip("/")
@cached_property
def url(self):
"""The reconstructed current URL as IRI.
See also: :attr:`trusted_hosts`.
"""
return get_current_url(self.environ, trusted_hosts=self.trusted_hosts)
@cached_property
def base_url(self):
"""Like :attr:`url` but without the querystring
See also: :attr:`trusted_hosts`.
"""
return get_current_url(
self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts
)
@cached_property
def url_root(self):
"""The full URL root (with hostname), this is the application
root as IRI.
See also: :attr:`trusted_hosts`.
"""
return get_current_url(self.environ, True, trusted_hosts=self.trusted_hosts)
@cached_property
def host_url(self):
"""Just the host with scheme as IRI.
See also: :attr:`trusted_hosts`.
"""
return get_current_url(
self.environ, host_only=True, trusted_hosts=self.trusted_hosts
)
@cached_property
def host(self):
"""Just the host including the port if available.
See also: :attr:`trusted_hosts`.
"""
return get_host(self.environ, trusted_hosts=self.trusted_hosts)
query_string = environ_property(
"QUERY_STRING",
"",
read_only=True,
load_func=wsgi_get_bytes,
doc="The URL parameters as raw bytestring.",
)
method = environ_property(
"REQUEST_METHOD",
"GET",
read_only=True,
load_func=lambda x: x.upper(),
doc="The request method. (For example ``'GET'`` or ``'POST'``).",
)
@cached_property
def access_route(self):
"""If a forwarded header exists this is a list of all ip addresses
from the client ip to the last proxy server.
"""
if "HTTP_X_FORWARDED_FOR" in self.environ:
addr = self.environ["HTTP_X_FORWARDED_FOR"].split(",")
return self.list_storage_class([x.strip() for x in addr])
elif "REMOTE_ADDR" in self.environ:
return self.list_storage_class([self.environ["REMOTE_ADDR"]])
return self.list_storage_class()
@property
def remote_addr(self):
"""The remote address of the client."""
return self.environ.get("REMOTE_ADDR")
remote_user = environ_property(
"REMOTE_USER",
doc="""If the server supports user authentication, and the
script is protected, this attribute contains the username the
user has authenticated as.""",
)
scheme = environ_property(
"wsgi.url_scheme",
doc="""
URL scheme (http or https).
.. versionadded:: 0.7""",
)
is_secure = property(
lambda self: self.environ["wsgi.url_scheme"] == "https",
doc="`True` if the request is secure.",
)
is_multithread = environ_property(
"wsgi.multithread",
doc="""boolean that is `True` if the application is served by a
multithreaded WSGI server.""",
)
is_multiprocess = environ_property(
"wsgi.multiprocess",
doc="""boolean that is `True` if the application is served by a
WSGI server that spawns multiple processes.""",
)
is_run_once = environ_property(
"wsgi.run_once",
doc="""boolean that is `True` if the application will be
executed only once in a process lifetime. This is the case for
CGI for example, but it's not guaranteed that the execution only
happens one time.""",
)
def _assert_not_shallow(request):
if request.shallow:
raise RuntimeError(
"A shallow request tried to consume form data. If you really"
" want to do that, set `shallow` to False."
)
| {
"repo_name": "mitsuhiko/werkzeug",
"path": "src/werkzeug/wrappers/base_request.py",
"copies": "1",
"size": "25880",
"license": "bsd-3-clause",
"hash": -1976594031116266500,
"line_mean": 37.7425149701,
"line_max": 85,
"alpha_frac": 0.6342349304,
"autogenerated": false,
"ratio": 4.4977407021202644,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00016173850042410258,
"num_lines": 668
} |
from functools import update_wrapper
from pprint import pprint
import re
def grammar(description, whitespace=r'\s*'):
G = {' ': whitespace}
description = description.replace('\t', ' ') # no tabs!
for line in split(description, '\n'):
lhs, rhs = split(line, ' => ', 1)
alternatives = split(rhs, ' | ')
G[lhs] = tuple(map(split, alternatives))
return G
def split(text, sep=None, maxsplit=-1):
return [t.strip() for t in text.strip().split(sep, maxsplit)]
def decorator(d):
"Make function d a decorator: d wraps a function fn."
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d
@decorator
def memo(f):
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
# some element of args can't be a dict key
return f(args)
return _f
def parse(start_symbol, text, grammar):
tokenizer = grammar[' '] + '(%s)'
def parse_sequence(sequence, text):
result = []
for atom in sequence:
tree, text = parse_atom(atom, text)
if text is None: return Fail
result.append(tree)
return result, text
@memo
def parse_atom(atom, text):
if atom in grammar: # Non-Terminal: tuple of alternatives
for alternative in grammar[atom]:
tree, rem = parse_sequence(alternative, text)
if rem is not None: return [atom]+tree, rem
return Fail
else: # Terminal: match characters against start of text
m = re.match(tokenizer % atom, text)
return Fail if (not m) else (m.group(1), text[m.end():])
# Body of parse:
return parse_atom(start_symbol, text)
Fail = (None, None)
REGRAMMER = grammar(r"""
RE => REPEAT RE | REPEAT
REPEAT => STAR | PLUS | SINGLE
STAR => SINGLE [*]
PLUS => SINGLE [+]
SINGLE => DOT | LIT | ONEOF | ALT
DOT => [.]
LIT => \w+
ONEOF => [[] \w+ []]
ALT => [(] ALTLIST [)]
ALTLIST => RE [|] ALTLIST | RE
""")
def parse_re(pattern):
tree, remains = parse('RE', pattern, REGRAMMER)
if remains == '':
return convert(tree)
else:
raise ValueError('Invalid Pattern: "%s", remains: %s'
% (pattern, remains))
def convert(tree):
def walk(name, *args):
if name in ('RE', 'REPEAT', 'SINGLE'):
subtrees = [walk(*part) for part in args]
return (subtrees[0] if len(subtrees) == 1 else
reduce(seq, subtrees))
if name == 'DOT':
return dot
if name == 'LIT':
return lit(args[0])
if name == 'ONEOF':
_, v, _ = args
return oneof(v)
if name == 'STAR':
return star(walk(*args[0]))
if name == 'PLUS':
return plus(walk(*args[0]))
if name == 'ALT':
_, alist, _ = args
return walk(*alist)
if name == 'ALTLIST':
if len(args) == 1:
return walk(*args[0])
else:
a, _, remains = args
return alt(walk(*a), walk(*remains))
return walk(*tree)
def seq(a, b): return ('seq', a, b)
def lit(a): return ('lit', a)
def oneof(s): return ('oneof', s)
def star(a): return ('star', a)
def plus(a): return ('plus', a)
def alt(a, b): return ('alt', a, b)
dot = ('dot',)
def equals(actual, expected):
if actual != expected:
print ' actual: %s' % (actual,)
print 'expected: %s' % (expected,)
print '==> ' + ('pass' if actual == expected else 'fail') + '\n'
def test():
equals(parse_re('.'), ('dot',))
equals(parse_re('abc'), ('lit', 'abc'))
equals(parse_re('[abc]'), ('oneof', 'abc'))
equals(parse_re('a*'), ('star', ('lit', 'a')))
equals(parse_re('a+'), ('plus', ('lit', 'a')))
equals(parse_re('(a|b)'), ('alt', ('lit', 'a'), ('lit', 'b')))
equals(parse_re('(a|b|c)'), ('alt',
('lit', 'a'),
('alt', ('lit', 'b'), ('lit', 'c'))))
equals(parse_re('[ab]+'), ('plus', ('oneof', 'ab')))
equals(parse_re('[ab]+c'), ('seq', ('plus', ('oneof', 'ab')), ('lit', 'c')))
equals(parse_re('[ab]+c(d|e)'), ('seq',
('plus', ('oneof', 'ab')),
('seq', ('lit', 'c'),
('alt', ('lit', 'd'), ('lit', 'e')))))
test()
| {
"repo_name": "yeonghoey/notes",
"path": "content/udacity/design-of-computer-programs/lesson3/exercises/reparser.py",
"copies": "2",
"size": "4614",
"license": "mit",
"hash": 8365412352384536000,
"line_mean": 28.3885350318,
"line_max": 80,
"alpha_frac": 0.4878630256,
"autogenerated": false,
"ratio": 3.5574402467232074,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0024335381538113164,
"num_lines": 157
} |
from functools import update_wrapper
from types import FunctionType
from typing import cast, Any, Callable, Iterable
from rx.disposable import CompositeDisposable
def add_ref(xs, r):
from rx.core import Observable
def subscribe(observer, scheduler=None):
return CompositeDisposable(r.disposable, xs.subscribe(observer))
return Observable(subscribe)
def is_future(fut: Any) -> bool:
return callable(getattr(fut, 'add_done_callback', None))
def infinite() -> Iterable[int]:
n = 0
while True:
yield n
n += 1
def alias(name: str, doc: str, fun: Callable[..., Any]) -> Callable[..., Any]:
# Adapted from https://stackoverflow.com/questions/13503079/how-to-create-a-copy-of-a-python-function#
# See also help(type(lambda: 0))
_fun = cast(FunctionType, fun)
args = (_fun.__code__, _fun.__globals__)
kwargs = {
'name': name,
'argdefs': _fun.__defaults__,
'closure': _fun.__closure__
}
alias = FunctionType(*args, **kwargs) # type: ignore
alias = cast(FunctionType, update_wrapper(alias, _fun))
alias.__kwdefaults__ = _fun.__kwdefaults__
alias.__doc__ = doc
return alias
class NotSet:
"""Sentinel value."""
def __eq__(self, other):
return self is other
def __repr__(self):
return 'NotSet'
| {
"repo_name": "ReactiveX/RxPY",
"path": "rx/internal/utils.py",
"copies": "1",
"size": "1340",
"license": "mit",
"hash": -8334331044569037000,
"line_mean": 24.7692307692,
"line_max": 106,
"alpha_frac": 0.6298507463,
"autogenerated": false,
"ratio": 3.6118598382749325,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47417105845749324,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from weakref import WeakSet
from django.apps import apps
from django.contrib.admin import ModelAdmin, actions
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import ImproperlyConfigured
from django.db.models.base import ModelBase
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.urls import NoReverseMatch, reverse
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.i18n import JavaScriptCatalog
all_sites = WeakSet()
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Django site admin')
# Text to put in each page's <h1>.
site_header = ugettext_lazy('Django administration')
# Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration')
# URL for the "View site" link at the top of each admin page.
site_url = '/'
_empty_value_display = '-'
login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
def __init__(self, name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
all_sites.add(self)
def check(self, app_configs):
"""
Run the system checks on all ModelAdmins, except if they aren't
customized at all.
"""
if app_configs is None:
app_configs = apps.get_app_configs()
app_configs = set(app_configs) # Speed up lookups below
errors = []
modeladmins = (o for o in self._registry.values() if o.__class__ is not ModelAdmin)
for modeladmin in modeladmins:
if modeladmin.model._meta.app_config in app_configs:
errors.extend(modeladmin.check())
return errors
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured(
'The model %s is abstract, so it cannot be registered with admin.' % model.__name__
)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
# Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
def unregister(self, model_or_iterable):
"""
Unregisters the given model(s).
If a model isn't already registered, this will raise NotRegistered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotRegistered('The model %s is not registered' % model.__name__)
del self._registry[model]
def is_registered(self, model):
"""
Check if a model class is registered with this `AdminSite`.
"""
return model in self._registry
def add_action(self, action, name=None):
"""
Register an action to be available globally.
"""
name = name or action.__name__
self._actions[name] = action
self._global_actions[name] = action
def disable_action(self, name):
"""
Disable a globally-registered action. Raises KeyError for invalid names.
"""
del self._actions[name]
def get_action(self, name):
"""
Explicitly get a registered global action whether it's enabled or
not. Raises KeyError for invalid names.
"""
return self._global_actions[name]
@property
def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
return six.iteritems(self._actions)
@property
def empty_value_display(self):
return self._empty_value_display
@empty_value_display.setter
def empty_value_display(self, empty_value_display):
self._empty_value_display = empty_value_display
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
return request.user.is_active and request.user.is_staff
def admin_view(self, view, cacheable=False):
"""
Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You'll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import url
urls = super(MyAdminSite, self).get_urls()
urls += [
url(r'^my_view/$', self.admin_view(some_view))
]
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.
"""
def inner(request, *args, **kwargs):
if not self.has_permission(request):
if request.path == reverse('admin:logout', current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
# Inner import to prevent django.contrib.admin (app) from
# importing django.contrib.auth.models.User (unrelated model).
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
request.get_full_path(),
reverse('admin:login', current_app=self.name)
)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import url, include
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
wrapper.admin_site = self
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^$', wrap(self.index), name='index'),
url(r'^login/$', self.login, name='login'),
url(r'^logout/$', wrap(self.logout), name='logout'),
url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
name='view_on_site'),
]
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
for model, model_admin in self._registry.items():
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
# If there were ModelAdmins registered, we should have a list of app
# labels for which we need to allow access to the app_index view,
if valid_app_labels:
regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
urlpatterns += [
url(regex, wrap(self.app_index), name='app_list'),
]
return urlpatterns
@property
def urls(self):
return self.get_urls(), 'admin', self.name
def each_context(self, request):
"""
Returns a dictionary of variables to put in the template context for
*every* page in the admin site.
For sites running on a subpath, use the SCRIPT_NAME value if site_url
hasn't been customized.
"""
script_name = request.META['SCRIPT_NAME']
site_url = script_name if self.site_url == '/' and script_name else self.site_url
return {
'site_title': self.site_title,
'site_header': self.site_header,
'site_url': site_url,
'has_permission': self.has_permission(request),
'available_apps': self.get_app_list(request),
}
def password_change(self, request, extra_context=None):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.admin.forms import AdminPasswordChangeForm
from django.contrib.auth.views import PasswordChangeView
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {
'form_class': AdminPasswordChangeForm,
'success_url': url,
'extra_context': dict(self.each_context(request), **(extra_context or {})),
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
request.current_app = self.name
return PasswordChangeView.as_view(**defaults)(request)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import PasswordChangeDoneView
defaults = {
'extra_context': dict(self.each_context(request), **(extra_context or {})),
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
request.current_app = self.name
return PasswordChangeDoneView.as_view(**defaults)(request)
def i18n_javascript(self, request, extra_context=None):
"""
Displays the i18n JavaScript that the Django admin requires.
`extra_context` is unused but present for consistency with the other
admin views.
"""
return JavaScriptCatalog.as_view(packages=['django.contrib.admin'])(request)
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import LogoutView
defaults = {
'extra_context': dict(
self.each_context(request),
# Since the user isn't logged out at this point, the value of
# has_permission must be overridden.
has_permission=False,
**(extra_context or {})
),
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
request.current_app = self.name
return LogoutView.as_view(**defaults)(request)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
if request.method == 'GET' and self.has_permission(request):
# Already logged-in, redirect to admin index
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
from django.contrib.auth.views import LoginView
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.admin.forms eventually imports User.
from django.contrib.admin.forms import AdminAuthenticationForm
context = dict(
self.each_context(request),
title=_('Log in'),
app_path=request.get_full_path(),
username=request.user.get_username(),
)
if (REDIRECT_FIELD_NAME not in request.GET and
REDIRECT_FIELD_NAME not in request.POST):
context[REDIRECT_FIELD_NAME] = reverse('admin:index', current_app=self.name)
context.update(extra_context or {})
defaults = {
'extra_context': context,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'admin/login.html',
}
request.current_app = self.name
return LoginView.as_view(**defaults)(request)
def _build_app_dict(self, request, label=None):
"""
Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app.
"""
app_dict = {}
if label:
models = {
m: m_a for m, m_a in self._registry.items()
if m._meta.app_label == label
}
else:
models = self._registry
for model, model_admin in models.items():
app_label = model._meta.app_label
has_module_perms = model_admin.has_module_permission(request)
if not has_module_perms:
continue
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True not in perms.values():
continue
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change'):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add'):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': apps.get_app_config(app_label).verbose_name,
'app_label': app_label,
'app_url': reverse(
'admin:app_list',
kwargs={'app_label': app_label},
current_app=self.name,
),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if label:
return app_dict.get(label)
return app_dict
def get_app_list(self, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""
app_dict = self._build_app_dict(request)
# Sort the apps alphabetically.
app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
return app_list
@never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_list = self.get_app_list(request)
context = dict(
self.each_context(request),
title=self.index_title,
app_list=app_list,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.index_template or 'admin/login.html', context)
def app_index(self, request, app_label, extra_context=None):
app_dict = self._build_app_dict(request, app_label)
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
app_name = apps.get_app_config(app_label).verbose_name
context = dict(
self.each_context(request),
title=_('%(app)s administration') % {'app': app_name},
app_list=[app_dict],
app_label=app_label,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
| {
"repo_name": "scifiswapnil/Project-LoCatr",
"path": "lib/python2.7/site-packages/django/contrib/admin/sites.py",
"copies": "1",
"size": "20065",
"license": "mit",
"hash": -6299034845019974000,
"line_mean": 37.5865384615,
"line_max": 109,
"alpha_frac": 0.5931223524,
"autogenerated": false,
"ratio": 4.384833916083916,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5477956268483916,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import html
from aiohttp import web
from funkybomb import render, Tag, Template
from pygments import highlight
from pygments.lexers import HtmlLexer, PythonLexer, TextLexer
from pygments.formatters import HtmlFormatter
from application.util import url
def row_cols(node, *cols):
row = node.div(_class='row')
if not cols:
return row.div(_class='col')
divs = []
for col in cols:
col_class = 'col-md-{width}'.format(width=col)
divs.append(row.div(_class=col_class))
return divs
def nav_links(current_url, links):
tmpl = Template()
nav = tmpl.ul(_class='list-unstyled')
for href, text, children in links:
nav_item = nav.li()
_class = ''
if url == current_url:
_class += 'active'
nav_item.a(_class=_class, href=url(href)) + text
if children:
nav_item = nav.li()
nav_item + nav_links(current_url, children)
return nav
def nav_links_new():
nav_groups = (
(
'Basics',
(
('/docs/basics/installation', 'Installation'),
('/docs/basics/syntax', 'Syntax'),
('/docs/basics/templating', 'Templating'),
('/docs/basics/utilities', 'Utilities'),
)
),
(
'Common Patterns',
(
('/docs/patterns/abstraction', 'Abstractions'),
('/docs/patterns/composition', 'Composition'),
('/docs/patterns/reusability', 'Reusability'),
)
),
(
'Integrations',
(
('/docs/integrations/flask', 'Flask'),
)
),
)
tmpl = Template()
nav = tmpl.ul(_class='list-unstyled')
nav.li.a(href=url('/')) + 'Funky Bomb'
for name, links in nav_groups:
nav.li.p(_class='mt-3 mb-1') + name
for u, text in links:
nav.li.a(href=url(u)) + text
nav.li.p(_class='mt-3 mb-1') + 'Other'
nav.li.a(href='https://github.com/glennyonemitsu/funkybomb') + 'GitHub'
return tmpl
def template(tmpl):
"""
aiohttp view decorator.
"""
def decorator(fn):
async def wrapped(req, *args, **kwargs):
context = await fn(req, *args, **kwargs)
context['nav links'] = nav_links_new()
output = render(tmpl, context=context, pretty=False)
return web.Response(text=output, content_type='text/html')
update_wrapper(wrapped, fn)
return wrapped
return decorator
def show_python(text):
return highlight(
source(text), PythonLexer(), HtmlFormatter(style='colorful'))
def show_html(text):
return highlight(source(text), HtmlLexer(), HtmlFormatter(style='colorful'))
def show_text(text):
return highlight(source(text), TextLexer(), HtmlFormatter(style='colorful'))
def source(text):
lines = []
indent = None
for line in text.splitlines():
if indent is None and line != '':
indent = len(line) - len(line.lstrip())
lines.append(line[indent:])
return '\n'.join(lines).strip()
def header(text, level=2):
attr = text.lower().replace(' ', '-')
t = 'h' + str(level)
return Tag(t, id=attr, _class='mt-5') + text
def p(*texts):
tmpl = Template()
for p in texts:
tmpl.p + html.escape(p)
return tmpl
| {
"repo_name": "glennyonemitsu/funkybomb",
"path": "website/templates/util.py",
"copies": "1",
"size": "3428",
"license": "apache-2.0",
"hash": 2108445128561940200,
"line_mean": 25.3692307692,
"line_max": 80,
"alpha_frac": 0.5600933489,
"autogenerated": false,
"ratio": 3.705945945945946,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9765089627229611,
"avg_score": 0.0001899335232668566,
"num_lines": 130
} |
from functools import update_wrapper
import json
from django.conf import settings
from django.conf.urls import patterns, url
from django.contrib import admin
from django.contrib.admin.widgets import url_params_from_lookup_dict
try:
from django.contrib.admin.views.main import IS_POPUP_VAR
except ImportError:
from django.contrib.admin.options import IS_POPUP_VAR
try:
from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
from django.contrib.contenttypes.generic import (GenericForeignKey,
GenericTabularInline)
from django.contrib.contenttypes import admin as GA
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, HttpResponseNotAllowed, Http404
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
from django.utils.text import capfirst
JS_PATH = getattr(settings, 'GENERICADMIN_JS', 'genericadmin/js/')
class BaseGenericModelAdmin(object):
class Media:
js = ()
content_type_lookups = {}
generic_fk_fields = []
content_type_blacklist = []
content_type_whitelist = []
def __init__(self, model, admin_site):
try:
media = list(self.Media.js)
except:
media = []
media.append(JS_PATH + 'genericadmin.js')
self.Media.js = tuple(media)
self.content_type_whitelist = [s.lower() for s in self.content_type_whitelist]
self.content_type_blacklist = [s.lower() for s in self.content_type_blacklist]
super(BaseGenericModelAdmin, self).__init__(model, admin_site)
def get_generic_field_list(self, request, prefix=''):
if hasattr(self, 'ct_field') and hasattr(self, 'ct_fk_field'):
exclude = [self.ct_field, self.ct_fk_field]
else:
exclude = []
field_list = []
if hasattr(self, 'generic_fk_fields') and self.generic_fk_fields:
for fields in self.generic_fk_fields:
if fields['ct_field'] not in exclude and \
fields['fk_field'] not in exclude:
fields['inline'] = prefix != ''
fields['prefix'] = prefix
field_list.append(fields)
else:
for field in self.model._meta.virtual_fields:
if isinstance(field, GenericForeignKey) and\
field.ct_field not in exclude and\
field.fk_field not in exclude:
field_list.append({
'ct_field': field.ct_field,
'fk_field': field.fk_field,
'inline': prefix != '',
'prefix': prefix,
})
if hasattr(self, 'inlines') and len(self.inlines) > 0:
for FormSet, inline in zip(self.get_formsets(request), self.get_inline_instances(request)):
if hasattr(inline, 'get_generic_field_list'):
prefix = FormSet.get_default_prefix()
field_list = field_list + inline.get_generic_field_list(request, prefix)
return field_list
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
custom_urls = patterns(
'',
url(r'^obj-data/$', wrap(self.generic_lookup), name='admin_genericadmin_obj_lookup'),
url(r'^genericadmin-init/$', wrap(self.genericadmin_js_init), name='admin_genericadmin_init'),
)
return custom_urls + super(BaseGenericModelAdmin, self).get_urls()
def genericadmin_js_init(self, request):
if request.method == 'GET':
obj_dict = {}
for c in ContentType.objects.all():
val = force_text('%s/%s' % (c.app_label, c.model))
params = self.content_type_lookups.get('%s.%s' % (c.app_label, c.model), {})
params = url_params_from_lookup_dict(params)
if self.content_type_whitelist:
if val in self.content_type_whitelist:
obj_dict[c.id] = (val, params)
elif val not in self.content_type_blacklist:
obj_dict[c.id] = (val, params)
data = {
'url_array': obj_dict,
'fields': self.get_generic_field_list(request),
'popup_var': IS_POPUP_VAR,
}
resp = json.dumps(data, ensure_ascii=False)
return HttpResponse(resp, content_type='application/json')
return HttpResponseNotAllowed(['GET'])
def generic_lookup(self, request):
if request.method != 'GET':
return HttpResponseNotAllowed(['GET'])
if 'content_type' in request.GET and 'object_id' in request.GET:
content_type_id = request.GET['content_type']
object_id = request.GET['object_id']
obj_dict = {
'content_type_id': content_type_id,
'object_id': object_id,
}
content_type = ContentType.objects.get(pk=content_type_id)
obj_dict["content_type_text"] = capfirst(force_text(content_type))
try:
obj = content_type.get_object_for_this_type(pk=object_id)
obj_dict["object_text"] = capfirst(force_text(obj))
except ObjectDoesNotExist:
raise Http404
resp = json.dumps(obj_dict, ensure_ascii=False)
else:
resp = ''
return HttpResponse(resp, content_type='application/json')
class GenericAdminModelAdmin(BaseGenericModelAdmin, admin.ModelAdmin):
"""Model admin for generic relations. """
class GenericTabularInline(BaseGenericModelAdmin, GA.GenericTabularInline):
"""Model admin for generic tabular inlines. """
class GenericStackedInline(BaseGenericModelAdmin, GA.GenericStackedInline):
"""Model admin for generic stacked inlines. """
class TabularInlineWithGeneric(BaseGenericModelAdmin, admin.TabularInline):
""""Normal tabular inline with a generic relation"""
class StackedInlineWithGeneric(BaseGenericModelAdmin, admin.StackedInline):
""""Normal stacked inline with a generic relation"""
| {
"repo_name": "mikkezavala/django-genericadmin",
"path": "genericadmin/admin.py",
"copies": "2",
"size": "6489",
"license": "mit",
"hash": 5152442043499303000,
"line_mean": 38.0903614458,
"line_max": 106,
"alpha_frac": 0.6028663893,
"autogenerated": false,
"ratio": 4.208171206225681,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5811037595525681,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import logging
from demands.pagination import PaginatedResults, RESULTS_KEY
from opensrs import errors
from opensrs.constants import AUTO_RENEWED_TLDS, OrderProcessingMethods
from opensrs.xcp import XCPMessage, XCPChannel
log = logging.getLogger(__name__)
def format_date(date):
return date.strftime('%Y-%m-%d')
def capture_registration_failures(fn):
def _capture(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except errors.XCPError as e:
if e.response_code == self.CODE_DOMAIN_REGISTRATION_TAKEN:
raise errors.DomainTaken(e)
if e.response_code == self.CODE_DOMAIN_REGISTRATION_FAILED:
if (e.response_text.startswith('Invalid domain syntax') or
e.response_text.startswith(
'Invalid syntax on domain')):
raise errors.InvalidDomain(e)
raise errors.DomainRegistrationFailure(e)
if e.response_code == self.CODE_CLIENT_TIMED_OUT:
raise errors.DomainRegistrationTimedOut(e)
raise
return update_wrapper(_capture, fn)
def is_already_renewed(e):
return (e.response_code == OpenSRS.CODE_ALREADY_RENEWED or
(e.response_code == OpenSRS.CODE_ALREADY_RENEWED_SANDBOX and
e.response_text.startswith(
OpenSRS.MSG_ALREADY_RENEWED_SANDBOX)))
def is_auto_renewed(e, domain_name):
tld = domain_name.rsplit('.', 1)[-1].lower()
return (e.response_code == OpenSRS.CODE_RENEWAL_IS_NOT_ALLOWED and
tld in AUTO_RENEWED_TLDS)
def capture_renewal_failures(fn):
def _capture(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except errors.XCPError as e:
# We cannot control domains which are automatically renewed on
# OpenSRS side. Thus we always treat them as already renewed
# for each renewal attempt.
domain_name = args[0]
if is_already_renewed(e) or is_auto_renewed(e, domain_name):
raise errors.DomainAlreadyRenewed(e)
raise
return update_wrapper(_capture, fn)
def capture_transfer_failures(fn):
def _capture(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except errors.XCPError as e:
if e.response_code == self.CODE_DOMAIN_NOT_TRANSFERABLE:
raise errors.DomainNotTransferable(e)
if e.response_code == self.CODE_DOMAIN_REGISTRATION_FAILED:
if (e.response_text.startswith('Invalid domain syntax') or
e.response_text.startswith(
'Invalid syntax on domain')):
raise errors.InvalidDomain(e)
raise errors.DomainTransferFailure(e)
raise
return update_wrapper(_capture, fn)
def capture_auth_failure(fn):
def _transform(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
except errors.XCPError as e:
if e.response_code == self.CODE_AUTHENTICATION_FAILED:
raise errors.AuthenticationFailure(e)
raise
return update_wrapper(_transform, fn)
class OpenSRS(object):
CODE_DOMAIN_AVAILABLE = '210'
CODE_DOMAIN_TAKEN = '211'
CODE_DOMAIN_TAKEN_AWAITING_REGISTRATION = '221'
CODE_DOMAIN_REGISTRATION_TAKEN = '485'
CODE_DOMAIN_REGISTRATION_FAILED = '465'
CODE_DOMAIN_NOT_TRANSFERABLE = '487'
CODE_DOMAIN_INVALID = '465'
CODE_AUTHENTICATION_FAILED = '415'
CODE_OVER_QUOTA = '3001'
CODE_ALREADY_RENEWED = '555'
CODE_ALREADY_RENEWED_SANDBOX = '465'
CODE_RENEWAL_IS_NOT_ALLOWED = '480'
CODE_CANNOT_REDEEM_DOMAIN = '400'
CODE_CANNOT_PUSH_DOMAIN = '465'
CODE_CLIENT_TIMED_OUT = '705'
MSG_ALREADY_RENEWED_SANDBOX = 'Domain Already Renewed'
def __init__(self, host, port, username, private_key, default_timeout):
self.host = host
self.port = port
self.username = username
self.private_key = private_key
self.default_timeout = default_timeout
def _get_channel(self):
return XCPChannel(self.host, self.port, self.username,
self.private_key, self.default_timeout)
def _req(self, action, object, attributes, **kw):
msg = XCPMessage(action, object, attributes, **kw)
return self._get_channel().make_request(msg)
def make_contact(self, user, domain, **kw):
org_name = kw.get('orgname') or ' '.join([user.first_name,
user.last_name])
return {
'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email,
'phone': user.phone,
'fax': user.fax or '',
'org_name': org_name,
'address1': user.address1,
'address2': user.address2,
'address3': user.address3,
'city': user.city,
'state': user.state,
'country': user.country_code,
'postal_code': user.postal_code or '',
}
def make_nameserver_list(self, nameservers):
return [{'sortorder': str(i + 1), 'name': ns} for i, ns in
enumerate(nameservers)]
# Basic API calls. These return raw XCPMessage objects.
def _lookup_domain(self, domain):
return self._req(action='LOOKUP', object='DOMAIN',
attributes={'domain': domain})
def _check_transfer(self, domain):
return self._req(action='CHECK_TRANSFER', object='DOMAIN',
attributes={'domain': domain})
def _make_common_reg_attrs(self, domain, user, username, password,
reg_domain, **kw):
contact = self.make_contact(user, domain, **kw)
order_processing_method = kw.get(
'order_processing_method', OrderProcessingMethods.SAVE)
# .eu domains require GB instead of UK as the country code
if domain.lower().endswith('.eu') and contact['country'] == 'UK':
contact['country'] = 'GB'
attributes = {
'auto_renew': '0',
'contact_set': {
'owner': contact,
'admin': contact,
'billing': contact,
'tech': contact,
},
'custom_tech_contact': '1',
'domain': domain,
'reg_username': username,
'reg_password': password,
'reg_type': 'new',
'f_lock_domain': '1',
'handle': order_processing_method,
}
if reg_domain is not None:
attributes['reg_domain'] = reg_domain
return attributes
def _make_domain_reg_attrs(self, domain, period, user, username, password,
nameservers, private, reg_domain, **kw):
attributes = self._make_common_reg_attrs(domain, user, username,
password, reg_domain, **kw)
attributes.update({
'reg_type': 'new',
'period': str(period),
'f_whois_privacy': {True: '1', False: '0'}[private],
'custom_nameservers': '0',
})
if nameservers is not None:
attributes['custom_nameservers'] = '1'
attributes['nameserver_list'] = self.make_nameserver_list(
nameservers)
return attributes
def _make_domain_transfer_attrs(self, domain, user, username, password,
nameservers, reg_domain, **kw):
attributes = self._make_common_reg_attrs(domain, user, username,
password, reg_domain, **kw)
attributes.update({
'reg_type': 'transfer',
'custom_transfer_nameservers': '0',
})
if nameservers is not None:
attributes['custom_transfer_nameservers'] = '1'
attributes['nameserver_list'] = self.make_nameserver_list(
nameservers)
return attributes
def _sw_register_domain(self, attributes):
return self._req(action='SW_REGISTER', object='DOMAIN',
attributes=attributes)
def _advanced_update_nameservers(self, cookie, nameservers):
attributes = {
'assign_ns': nameservers,
'op_type': 'assign',
}
return self._req(action='ADVANCED_UPDATE_NAMESERVERS', object='DOMAIN',
cookie=cookie, attributes=attributes)
def _name_suggest_domain(self, search_string, tlds, services, maximum=None,
max_wait_time=None, search_key=None):
attributes = {
'searchstring': search_string,
'tlds': tlds,
'services': services,
}
if max_wait_time is not None:
attributes['max_wait_time'] = str(max_wait_time)
if search_key is not None:
attributes['search_key'] = search_key
if maximum is not None:
attributes['maximum'] = str(maximum)
return self._req(action='NAME_SUGGEST',
object='DOMAIN',
attributes=attributes)
def _process_pending(self, order_id, cancel=False):
attributes = {
'order_id': order_id,
}
if cancel:
attributes['command'] = 'cancel'
return self._req(action='PROCESS_PENDING', object='DOMAIN',
attributes=attributes)
@capture_auth_failure
def _set_cookie(self, domain, reg_username, reg_password):
attributes = {
'domain': domain,
'reg_username': reg_username,
'reg_password': reg_password,
}
return self._req(action='SET', object='COOKIE', attributes=attributes)
def _set_domain_status(self, cookie, status):
attributes = {
'data': 'status',
'lock_state': status,
}
return self._req(action='MODIFY', object='DOMAIN', cookie=cookie,
attributes=attributes)
def _get_domain_status(self, cookie):
attributes = {
'type': 'status',
}
return self._req(action='GET', object='DOMAIN', cookie=cookie,
attributes=attributes)
def _get_domain_info(self, cookie, type='all_info'):
return self._req(action='GET', object='DOMAIN', cookie=cookie,
attributes={'type': type})
def _set_domain_whois_privacy(self, cookie, privacy):
attributes = {
'data': 'whois_privacy_state',
'affect_domains': '0',
'state': privacy,
}
return self._req(action='MODIFY', object='DOMAIN', cookie=cookie,
attributes=attributes)
def _send_authcode(self, domain_name):
return self._req(action='SEND_AUTHCODE', object='DOMAIN',
attributes={'domain_name': domain_name})
@capture_registration_failures
def _register_domain(self, domain, purchase_period, user, user_id,
password, nameservers=None, private_reg=False,
reg_domain=None, extras=None,
order_processing_method=OrderProcessingMethods.SAVE):
extras = extras or {}
attrs = self._make_domain_reg_attrs(
domain, purchase_period, user, user_id, password, nameservers,
private_reg, reg_domain,
order_processing_method=order_processing_method, **extras)
if extras:
attrs.update(extras)
rsp = self._sw_register_domain(attrs)
order_id = rsp.get_data()['attributes']['id']
return {
'domain_name': domain,
'registrar_data': {'ref_number': order_id}
}
@capture_renewal_failures
def _renew_domain(self, domain_name, current_expiration_year, period,
order_processing_method=OrderProcessingMethods.SAVE):
attributes = {
'auto_renew': '0',
'currentexpirationyear': current_expiration_year,
'domain': domain_name,
'handle': order_processing_method,
'period': str(period),
}
rsp = self._req(action='RENEW', object='DOMAIN', attributes=attributes)
return rsp.get_data()['attributes']['order_id']
@capture_transfer_failures
def _transfer_domain(self, domain, user, user_id, password,
nameservers=None, reg_domain=None, extras=None,
order_processing_method=OrderProcessingMethods.SAVE):
attrs = self._make_domain_transfer_attrs(
domain, user, user_id, password, nameservers, reg_domain,
order_processing_method=order_processing_method)
if extras:
attrs.update(extras)
rsp = self._sw_register_domain(attrs)
response_attributes = rsp.get_data()['attributes']
order_id = response_attributes['id']
transfer_id = response_attributes.get('transfer_id')
return {
'domain_name': domain,
'registrar_data': {
'ref_number': order_id,
'transfer_id': transfer_id
},
}
def _get_domains_contacts(self, domains):
return self._req(action='GET_DOMAINS_CONTACTS', object='DOMAIN',
attributes={'domain_list': domains})
def _get_transfers_in(self, transfer_id=None, req_from=None, req_to=None):
attributes = {}
if transfer_id is not None:
attributes['transfer_id'] = transfer_id
if req_from is not None:
attributes['req_from'] = format_date(req_from)
if req_to is not None:
attributes['req_to'] = format_date(req_to)
return self._req(action='GET_TRANSFERS_IN', object='DOMAIN',
attributes=attributes)
def _change_ownership(self, cookie, username, password, reg_domain):
attributes = {
'username': username,
'password': password,
}
if reg_domain is not None:
attributes['reg_domain'] = reg_domain
return self._req(action='CHANGE', object='OWNERSHIP', cookie=cookie,
attributes=attributes)
def _set_domain_contacts(self, cookie, user, domain):
contact = self.make_contact(user, domain)
attributes = {
'affect_domains': '0',
'data': 'contact_info',
'contact_set': {
'owner': contact,
'admin': contact,
'billing': contact,
'tech': contact,
},
}
if domain.endswith('.ca'):
# CA domains fail to update if billing contact info is set, remove
# to handle these cases
del attributes['contact_set']['billing']
return self._req(action='MODIFY', object='DOMAIN', cookie=cookie,
attributes=attributes)
def _revoke_domain(self, domain_name):
attributes = {
'domain': domain_name,
'reseller': self.username
}
return self._req(action='REVOKE', object='DOMAIN',
attributes=attributes)
def _get_user_info(self, cookie, type='all_info'):
return self._req(action='GET', object='USERINFO', cookie=cookie,
attributes={'type': type})
def _get_domain_notes(self, domain, type='domain'):
return self._req(action='GET_NOTES', object='DOMAIN',
attributes={'domain': domain, 'type': type})
def _get_orders_by_domain(self, domain):
return self._req(action='GET_ORDERS_BY_DOMAIN', object='DOMAIN',
attributes={'domain': domain})
def _get_order_info(self, order_id):
return self._req(action='GET_ORDER_INFO', object='DOMAIN',
attributes={'order_id': order_id})
def _activate_domain(self, cookie, domain_name):
return self._req(action='ACTIVATE', object='DOMAIN', cookie=cookie,
attributes={'domainname': domain_name})
# Higher leverl API calls. These parse the response into a
# (hopefully) useful form.
def get_auth_cookie(self, domain, username, password):
rsp = self._set_cookie(domain, username, password)
return rsp.get_data()['attributes']['cookie']
def domain_available(self, domain):
try:
rsp = self._lookup_domain(domain)
except errors.XCPError as e:
if e.response_code == self.CODE_DOMAIN_INVALID:
raise errors.InvalidDomain(e)
raise
code = rsp.get_data()['response_code']
if code == self.CODE_DOMAIN_AVAILABLE:
return True
if code in [self.CODE_DOMAIN_TAKEN,
self.CODE_DOMAIN_TAKEN_AWAITING_REGISTRATION]:
return False
raise errors.OperationFailure(rsp)
def domain_transferable(self, domain):
try:
rsp = self._check_transfer(domain)
except errors.XCPError as e:
if e.response_code == self.CODE_DOMAIN_INVALID:
raise errors.InvalidDomain(e)
raise
attribs = rsp.get_data()['attributes']
return (attribs['transferrable'] == '1', attribs.get('reason', None))
def suggest_domains(self, search_string, tlds, maximum=None,
max_wait_time=None, search_key=None, services=None):
if services is None:
services = ['lookup', 'suggestion']
rsp = self._name_suggest_domain(search_string, tlds, services, maximum,
max_wait_time, search_key)
data = rsp.get_data()
domains = {}
for k in services:
domrsp = data['attributes'].get(k, None)
domains[k] = []
if domrsp is None:
log.debug('Missing "%s" section in name suggestions.', k)
continue
if domrsp.get('is_success', '0') != '1':
rsp_code = domrsp.get('response_code')
rsp_text = domrsp.get('response_text')
if rsp_code == '500':
# These are typically temporary
log.info('Unsuccessful lookup component "%s": %s: %s', k,
rsp_code, rsp_text)
raise errors.DomainLookupUnavailable(rsp, rsp_code,
rsp_text)
log.warn('Unsuccessful lookup component "%s": %s: %s', k,
rsp_code, rsp_text)
raise errors.DomainLookupFailure(rsp, rsp_code, rsp_text)
domains[k] = [{'domain': i['domain'], 'status': i['status']}
for i in domrsp['items']]
if data.get('is_search_completed', '1') == '0':
domains['search_key'] = data['search_key']
return domains
def create_pending_domain_registration(
self, domain, purchase_period, user, user_id,
password, nameservers=None, private_reg=False,
reg_domain=None, extras=None):
return self._register_domain(
domain, purchase_period, user, user_id, password,
nameservers=nameservers, private_reg=private_reg,
reg_domain=reg_domain, extras=extras)
def register_domain(self, domain, purchase_period, user, user_id,
password, nameservers=None, private_reg=False,
reg_domain=None, extras=None):
return self._register_domain(
domain, purchase_period, user, user_id, password,
nameservers=nameservers, private_reg=private_reg,
reg_domain=reg_domain, extras=extras,
order_processing_method=OrderProcessingMethods.PROCESS)
def process_pending(self, order_id, cancel=False):
try:
rsp = self._process_pending(order_id, cancel=cancel)
return rsp.get_data().get('attributes')
except errors.XCPError as e:
if self._already_renewed(e):
raise errors.DomainAlreadyRenewed(e)
raise
def update_nameservers(self, nameservers, cookie):
self._advanced_update_nameservers(cookie, nameservers)
return True
def is_locked(self, cookie):
rsp = self._get_domain_status(cookie)
return {'0': False,
'1': True}[rsp.get_data()['attributes']['lock_state']]
def set_locked(self, cookie, locked):
self._set_domain_status(cookie, {True: '1', False: '0'}[locked])
return True
def send_auth_code(self, domain):
self._send_authcode(domain)
return True
def set_domain_privacy(self, cookie, privacy_enabled):
enable_privacy = 'enable' if privacy_enabled else 'disable'
self._set_domain_whois_privacy(cookie, enable_privacy)
return True
def create_pending_domain_renewal(self, domain, current_expiration_year,
period):
return self._renew_domain(domain, current_expiration_year, period)
def renew_domain(self, domain, current_expiration_year, period):
return self._renew_domain(
domain, current_expiration_year, period,
order_processing_method=OrderProcessingMethods.PROCESS)
def get_domains_by_expiredate(self, start_date, end_date, page=None):
domains = []
page = page or 1
while True:
data = self.list_domains(start_date, end_date, page)
for domain in data['exp_domains']:
domains.append({
'domain': domain['name'],
'domain_expiration': domain['expiredate'],
})
if data['remainder'] == '0':
break
page += 1
return domains
def iterate_domains(self, expiry_from, expiry_to):
pagination_options = {RESULTS_KEY: 'exp_domains'}
return PaginatedResults(
self.list_domains, args=(expiry_from, expiry_to),
**pagination_options)
def list_domains(self, expiry_from, expiry_to, page, page_size=40):
attributes = {
'exp_from': format_date(expiry_from),
'exp_to': format_date(expiry_to),
'page': str(page),
'limit': str(page_size)
}
return self._req(
action='GET_DOMAINS_BY_EXPIREDATE', object='DOMAIN',
attributes=attributes, timeout=300
).get_data()['attributes']
def get_domains_contacts(self, domains, limit=100):
domain_data = {}
while len(domains) > 0:
qdomains = domains[:limit]
domains = domains[limit:]
rsp = self._get_domains_contacts(qdomains)
data = rsp.get_data()
for domain, contact_set in data['attributes'].items():
owner = contact_set['contact_set']['owner']
domain_data[domain] = {
'first_name': owner['first_name'],
'last_name': owner['last_name'],
'email': owner['email'],
}
return domain_data
def create_pending_domain_transfer(self, domain, user, user_id, password,
nameservers=None, reg_domain=None,
extras=None):
return self._transfer_domain(
domain, user, user_id, password, nameservers=nameservers,
reg_domain=reg_domain, extras=extras)
def transfer_domain(self, domain, user, user_id, password,
nameservers=None, reg_domain=None, extras=None):
return self._transfer_domain(
domain, user, user_id, password, nameservers=nameservers,
reg_domain=reg_domain, extras=extras,
order_processing_method=OrderProcessingMethods.PROCESS)
def list_transfers(self, transfer_id=None, start_date=None, end_date=None):
rsp = self._get_transfers_in(transfer_id=transfer_id,
req_from=start_date, req_to=end_date)
transfers = rsp.get_data()['attributes'].get('transfers', [])
return transfers
def get_domain_info(self, cookie):
rsp = self._get_domain_info(cookie)
return rsp.get_data()['attributes']
def get_privacy_state(self, cookie):
rsp = self._get_domain_info(cookie, type='whois_privacy_state')
return rsp.get_data()['attributes']
def change_ownership(self, cookie, username, password, domain=None):
self._change_ownership(cookie, username, password, domain)
return True
def set_contacts(self, cookie, user, domain):
self._set_domain_contacts(cookie, user, domain)
return True
def get_transferred_away_domains(self, page, domain=None):
attributes = {'status': 'completed', 'page': str(page)}
if domain is not None:
attributes.update({
'domain': domain,
'page': '0'
})
response = self._req('GET_TRANSFERS_AWAY', 'DOMAIN', attributes)
return response.get_data()['attributes'].get('transfers', [])
def revoke_domain(self, domain):
return self._revoke_domain(domain).get_data()
def get_user_info(self, cookie):
return self._get_user_info(cookie).get_data()['attributes']
def get_domain_notes(self, domain_name):
return self._get_domain_notes(
domain_name).get_data()['attributes']['notes']
def get_orders_by_domain(self, domain):
rsp = self._get_orders_by_domain(domain)
return rsp.get_data()['attributes']['orders']
def get_order_info(self, order_id):
rsp = self._get_order_info(order_id)
return rsp.get_data()['attributes']['field_hash']
def activate_domain(self, cookie, domain):
return self._activate_domain(cookie, domain).get_data()
def simple_transfer(self, domain_list, nameserver_list=None):
attributes = {
'domain_list': domain_list,
}
if nameserver_list is not None:
attributes['nameserver_list'] = self.make_nameserver_list(
nameserver_list)
return self._req(action='SIMPLE_TRANSFER', object='DOMAIN',
attributes=attributes)
def get_simple_transfer_status(self, simple_transfer_job_id):
attributes = {
'simple_transfer_job_id': simple_transfer_job_id,
}
return self._req(action='SIMPLE_TRANSFER_STATUS', object='DOMAIN',
attributes=attributes)
def bulk_domain_change(self, domains_list, recipient):
attributes = {
'change_items': domains_list,
'gaining_reseller_username': recipient,
'change_type': 'push_domains',
'apply_to_locked_domains': '1',
}
return self._req(action='SUBMIT', object='BULK_CHANGE',
attributes=attributes)
def rsp_domain_transfer(self, domain, recipient):
attributes = {
'domain': domain,
'grsp': recipient,
}
try:
resp = self._req(
action='RSP2RSP_PUSH_TRANSFER', object='DOMAIN',
attributes=attributes)
log.info('opensrsapi.rsp_domain_transfer domain_name=%s, resp=%s',
domain, resp)
return resp
except errors.XCPError as e:
log.error(
'opensrsapi.rsp_domain_transfer fail domain_name=%s error=%s',
domain, e.response_text)
if e.response_code == self.CODE_CANNOT_REDEEM_DOMAIN:
return e.response_text
raise
def redeem_domain(self, domain):
log.info('opensrsapi.redeem_domain domain_name=%s', domain)
attributes = {'domain': domain}
redeem_resp = {'redeem_success': False}
try:
rsp = self._req(action='REDEEM', object='DOMAIN',
attributes=attributes)
data = rsp.get_data()
if int(data.get('is_success')) == 1:
redeem_resp['redeem_success'] = True
return redeem_resp
except errors.XCPError as e:
if e.response_code == self.CODE_CANNOT_REDEEM_DOMAIN:
log.info(('opensrsapi.redeem_domain fail domain_name=%s '
'error=%s code=%s'), domain, e.response_text,
e.response_code)
return redeem_resp
log.error(('opensrsapi.redeem_domain fail domain_name=%s '
'error=%s code=%s'), domain, e.response_text,
e.response_code)
raise
def get_registrant_verification_status(self, domain_name):
return self._make_registrant_verification_call(
domain_name,
'get_registrant_verification_status'
)['attributes']
def send_registrant_verification_email(self, domain_name):
return self._make_registrant_verification_call(
domain_name,
'send_registrant_verification_email'
)['response_text']
@capture_auth_failure
def _make_registrant_verification_call(self, domain_name, operation):
return self._req(
action=operation,
object='domain',
attributes={'domain': domain_name}
).get_data()
def enable_domain_auto_renewal(self, cookie, domain_name):
self._set_domain_auto_renewal_status(cookie, domain_name, True)
def disable_domain_auto_renewal(self, cookie, domain_name):
self._set_domain_auto_renewal_status(cookie, domain_name, False)
def _set_domain_auto_renewal_status(self, cookie, domain_name, enabled):
attributes = {
'data': 'expire_action',
'auto_renew': str(int(enabled)),
'let_expire': str(int(not enabled))
}
return self._req(
action='MODIFY', object='DOMAIN', attributes=attributes,
cookie=cookie
)
def disable_parked_pages_service(self, cookie, domain_name):
attributes = {
'data': 'parkpage_state',
'domain': domain_name,
'state': 'off'
}
self._req(action='MODIFY', object='DOMAIN', attributes=attributes,
cookie=cookie)
| {
"repo_name": "yola/opensrs",
"path": "opensrs/opensrsapi.py",
"copies": "1",
"size": "30735",
"license": "mit",
"hash": -7667981700130625000,
"line_mean": 37.7578814628,
"line_max": 79,
"alpha_frac": 0.5617699691,
"autogenerated": false,
"ratio": 4.123289508988463,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00002425065476767873,
"num_lines": 793
} |
from functools import update_wrapper
import new
class method(object):
def __init__(self, func, expr=None):
self.func = func
self.expr = expr or func
def __get__(self, instance, owner):
if instance is None:
return new.instancemethod(self.expr, owner, owner.__class__)
else:
return new.instancemethod(self.func, instance, owner)
def expression(self, expr):
self.expr = expr
return self
class property_(object):
def __init__(self, fget, fset=None, fdel=None, expr=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.expr = expr or fget
update_wrapper(self, fget)
def __get__(self, instance, owner):
if instance is None:
return self.expr(owner)
else:
return self.fget(instance)
def __set__(self, instance, value):
self.fset(instance, value)
def __delete__(self, instance):
self.fdel(instance)
def setter(self, fset):
self.fset = fset
return self
def deleter(self, fdel):
self.fdel = fdel
return self
def expression(self, expr):
self.expr = expr
return self
### Example code
from sqlalchemy import Table, Column, Integer, create_engine, func
from sqlalchemy.orm import sessionmaker, aliased
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class BaseInterval(object):
@method
def contains(self,point):
"""Return true if the interval contains the given interval."""
return (self.start <= point) & (point < self.end)
@method
def intersects(self, other):
"""Return true if the interval intersects the given interval."""
return (self.start < other.end) & (self.end > other.start)
@method
def _max(self, x, y):
"""Return the max of two values."""
return max(x, y)
@_max.expression
def _max(cls, x, y):
"""Return the SQL max of two values."""
return func.max(x, y)
@method
def max_length(self, other):
"""Return the longer length of this interval and another."""
return self._max(self.length, other.length)
def __repr__(self):
return "%s(%s..%s)" % (self.__class__.__name__, self.start, self.end)
class Interval1(BaseInterval, Base):
"""Interval stored as endpoints"""
__table__ = Table('interval1', Base.metadata,
Column('id', Integer, primary_key=True),
Column('start', Integer, nullable=False),
Column('end', Integer, nullable=False)
)
def __init__(self, start, end):
self.start = start
self.end = end
@property_
def length(self):
return self.end - self.start
class Interval2(BaseInterval, Base):
"""Interval stored as start and length"""
__table__ = Table('interval2', Base.metadata,
Column('id', Integer, primary_key=True),
Column('start', Integer, nullable=False),
Column('length', Integer, nullable=False)
)
def __init__(self, start, length):
self.start = start
self.length = length
@property_
def end(self):
return self.start + self.length
engine = create_engine('sqlite://', echo=True)
Base.metadata.create_all(engine)
session = sessionmaker(engine)()
intervals = [Interval1(1,4), Interval1(3,15), Interval1(11,16)]
for interval in intervals:
session.add(interval)
session.add(Interval2(interval.start, interval.length))
session.commit()
for Interval in (Interval1, Interval2):
print "Querying using interval class %s" % Interval.__name__
print
print '-- length less than 10'
print [(i, i.length) for i in
session.query(Interval).filter(Interval.length < 10).all()]
print
print '-- contains 12'
print session.query(Interval).filter(Interval.contains(12)).all()
print
print '-- intersects 2..10'
other = Interval1(2,10)
result = session.query(Interval).\
filter(Interval.intersects(other)).\
order_by(Interval.length).all()
print [(interval, interval.intersects(other)) for interval in result]
print
print '-- longer length'
interval_alias = aliased(Interval)
print session.query(Interval.length,
interval_alias.length,
Interval.max_length(interval_alias)).all()
| {
"repo_name": "FrankBian/kuma",
"path": "vendor/packages/sqlalchemy/examples/derived_attributes/attributes.py",
"copies": "6",
"size": "4667",
"license": "mpl-2.0",
"hash": 4898390166335225000,
"line_mean": 26.7797619048,
"line_max": 77,
"alpha_frac": 0.5806728091,
"autogenerated": false,
"ratio": 4.1155202821869485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7696193091286949,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import operator
from flatland.exc import AdaptationError
from flatland.util import Unspecified, threading
from .containers import Array, Mapping
from .scalars import Date, Integer, Scalar, String
class _MetaCompound(type):
"""Adds a class-level initialization hook """
_lock = threading.RLock()
def __new__(self, name, bases, members):
members['_compound_prepared'] = False
if '__compound_init__' in members:
members['__compound_init__'] = \
_wrap_compound_init(members['__compound_init__'])
return type.__new__(self, name, bases, members)
def __call__(cls, value=Unspecified, **kw):
"""Run __compound_init__ on first instance construction."""
# Find **kw that would override existing class properties and
# remove them from kw.
overrides = {}
for key in kw.keys():
if hasattr(cls, key):
overrides[key] = kw.pop(key)
if overrides:
# If there are overrides, construct a subtype on the fly
# so that __compound_init__ has a chance to run again with
# this new configuration.
cls = cls.using(**overrides)
cls.__compound_init__()
elif not cls.__dict__.get('_compound_prepared'):
# If this class hasn't been prepared yet, prepare it.
lock = cls._lock
lock.acquire()
try:
if not cls.__dict__.get('_compound_prepared'):
cls.__compound_init__()
finally:
lock.release()
# Finally, implement type.__call__, invoking __init__ with the
# members of kw that were not class overrides.
self = cls.__new__(cls, value, **kw)
if self.__class__ is cls:
if value is Unspecified:
self.__init__(**kw)
else:
self.__init__(value, **kw)
return self
def _wrap_compound_init(fn):
"""Decorate __compound_init__ with a status setter & classmethod."""
if isinstance(fn, classmethod):
fn = fn.__get__(str).im_func # type doesn't matter here
def __compound_init__(cls):
res = fn(cls)
cls._compound_prepared = True
return res
update_wrapper(__compound_init__, fn)
return classmethod(__compound_init__)
class Compound(Mapping, Scalar):
"""A mapping container that acts like a scalar value.
Compound fields are dictionary-like fields that can assemble a
:attr:`.u` and :attr:`.value` from their children, and can
decompose a structured value passed to a :meth:`.set` into values
for its children.
A simple example is a logical calendar date field composed of 3
separate Integer component fields, year, month and day. The
Compound can wrap the 3 parts up into a single logical field that
handles :class:`datetime.date` values. Set a ``date`` on the
logical field and its component fields will be set with year,
month and day; alter the int value of the year component field and
the logical field updates the ``date`` to match.
:class:`Compound` is an abstract class. Subclasses must implement
:meth:`compose` and :meth:`explode`.
Composites run validation after their children.
"""
__metaclass__ = _MetaCompound
def __compound_init__(cls):
"""TODO: doc
Gist: runs *once* per class, at the time the first element is
constructed. You can run it by hand if you want to finalize
the construction (see TODO above).
Changing class params on instance construction will cause this
to run again.
"""
def compose(self):
"""Return a unicode, native tuple built from children's state.
:returns: a 2-tuple of unicode representation, native value.
These correspond to the :meth:`Scalar.serialize_element`
and :meth:`Scalar.adapt_element` methods of :class:`Scalar`
objects.
For example, a compound date field may return a '-' delimited
string of year, month and day digits and a
:class:`datetime.date`.
"""
raise NotImplementedError()
def explode(self, value):
"""Given a compound value, assign values to children.
:param value: a value to be adapted and exploded
For example, a compound date field may read attributes from a
:class:`datetime.date` value and :meth:`.set()` them on child
fields.
The decision to perform type checking on *value* is completely
up to you and you may find you want different rules for
different compound types.
"""
raise NotImplementedError()
def serialize(self, value):
raise TypeError("Not implemented for Compound types.")
def u(self):
uni, value = self.compose()
return uni
def set_u(self, value):
self.explode(value)
u = property(u, set_u)
del set_u
def value(self):
uni, value = self.compose()
return value
def set_value(self, value):
self.explode(value)
value = property(value, set_value)
del set_value
def set(self, value):
try:
# TODO: historically explode() did not need to have a return value
# but it would be nice to return it form set() as below.
res = self.explode(value)
return True if res is None else res
except (SystemExit, KeyboardInterrupt, NotImplementedError):
raise
except Exception:
# not wild about quashing here, but set() doesn't allow
# adaptation exceptions to bubble up.
return False
def _set_flat(self, pairs, sep):
Mapping._set_flat(self, pairs, sep)
def __repr__(self):
try:
return Scalar.__repr__(self)
except Exception, exc:
return '<%s %r; value raised %s>' % (
type(self).__name__, self.name, type(exc).__name__)
@property
def is_empty(self):
"""True if all subfields are empty."""
return reduce(operator.and_, (c.is_empty for c in self.children))
class DateYYYYMMDD(Compound, Date):
@classmethod
def __compound_init__(cls):
assert len(cls.field_schema) < 4
if len(cls.field_schema) == 3:
return
fields = list(cls.field_schema)
optional = cls.optional
if len(fields) == 0:
fields.append(Integer.named(u'year').using(format=u'%04i',
optional=optional))
if len(fields) == 1:
fields.append(Integer.named(u'month').using(format=u'%02i',
optional=optional))
if len(fields) == 2:
fields.append(Integer.named(u'day').using(format=u'%02i',
optional=optional))
cls.field_schema = fields
#if any(not field.name for field in fields):
# raise TypeError("Child fields of %s %r must be named." %
# type(self).__name__, name)
def compose(self):
try:
data = dict([(label, self[child_schema.name].value)
for label, child_schema
in zip(self.used, self.field_schema)])
as_str = self.format % data
value = Date.adapt(self, as_str)
return as_str, value
except (AdaptationError, TypeError):
return u'', None
def explode(self, value):
try:
value = Date.adapt(self, value)
for attrib, child_schema in zip(self.used, self.field_schema):
self[child_schema.name].set(
getattr(value, attrib.encode('ascii')))
except (AdaptationError, TypeError):
for child_schema in self.field_schema:
self[child_schema.name].set(None)
class JoinedString(Array, String):
"""A sequence container that acts like a compounded string such as CSV.
Marshals child element values to and from a single string:
.. doctest::
>>> from flatland import JoinedString
>>> el = JoinedString(['x', 'y', 'z'])
>>> el.value
u'x,y,z'
>>> el2 = JoinedString('foo,bar')
>>> el2[1].value
u'bar'
>>> el2.value
u'foo,bar'
Only the joined representation is considered when flattening or restoring
with :meth:`set_flat`. JoinedStrings run validation after their children.
"""
#: The string used to join children's :attr:`u` representations. Will
#: also be used to split incoming strings, unless :attr:`separator_regex`
#: is also defined.
separator = u','
#: Optional, a regular expression, used preferentially to split an
#: incoming separated value into components. Used in combination with
#: :attr:`separator`, a permissive parsing policy can be combined with
#: a normalized representation, e.g.:
#:
#: .. doctest::
#:
#: >>> import re
#: >>> schema = JoinedString.using(separator=', ',
#: ... separator_regex=re.compile('\s*,\s*'))
#: ...
#: >>> schema('a , b,c,d').value
#: u'a, b, c, d'
separator_regex = None
#: The default child type is :class:`~flatland.schema.scalars.String`,
#: but can be customized with
#: :class:`~flatland.schema.scalars.Integer` or any other type.
member_schema = String
flattenable = True
children_flattenable = False
def set(self, value):
if isinstance(value, (list, tuple)):
values = value
elif not isinstance(value, basestring):
values = list(value)
elif self.separator_regex:
# a basestring, regexp separator
values = self.separator_regex.split(value)
else:
# a basestring, static separator
values = value.split(self.separator)
del self[:]
prune = self.prune_empty
success = []
for value in values:
if prune and not value:
continue
child = self.member_schema()
success.append(child.set(value))
self.append(child)
return all(success)
def _set_flat(self, pairs, sep):
return Scalar._set_flat(self, pairs, sep)
@property
def value(self):
"""A read-only :attr:`separator`-joined string of child values."""
return self.separator.join(child.u for child in self)
@property
def u(self):
"""A read-only :attr:`separator`-joined string of child values."""
return self.value
| {
"repo_name": "wheeler-microfluidics/flatland-fork",
"path": "flatland/schema/compound.py",
"copies": "4",
"size": "10797",
"license": "mit",
"hash": -1083726261330074800,
"line_mean": 32.2215384615,
"line_max": 79,
"alpha_frac": 0.5817356673,
"autogenerated": false,
"ratio": 4.353629032258064,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6935364699558064,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import os
from django.contrib.gis import admin as GeoAdmin
from django.contrib import admin
from dropbox.session import OAuthToken
from singleton_models.admin import SingletonModelAdmin
from dropbox import client, session
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.db import transaction
from django.template.response import TemplateResponse
from django.http import HttpResponseRedirect
from django.db.models import F
from models import Lion, Collar, Position, Pride, Tracking, DropboxAccount
csrf_protect_m = method_decorator(csrf_protect)
class LionListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = 'lion'
# Parameter for the filter that will be used in the URL query.
parameter_name = 'lion'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
lions = Lion.objects.all()
lionlist = [(str(lion.id), lion.name) for lion in lions]
return lionlist
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value():
print self.value()
return queryset.filter(
collar__tracking__lion__pk=int(self.value()),
timestamp__gte=F('collar__tracking__start'),
timestamp__lte=F('collar__tracking__end')
)
class DropboxAdmin(SingletonModelAdmin):
def get_link_url(self):
return reverse('admin:%s_%s_link' % info, current_app=self.admin_site.name)
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
urlpatterns = patterns('',
url(r'^history/$',
wrap(self.history_view),
{'object_id': '1'},
name='%s_%s_history' % info),
url(r'^link/$',
wrap(self.link_view),
{},
name='%s_%s_link' % info),
url(r'^$',
wrap(self.change_view),
{'object_id': '1'},
name='%s_%s_change' % info),
)
return urlpatterns
@csrf_protect_m
@transaction.commit_on_success
def link_view(self, request):
# Get your app key and secret from the Dropbox developer website
APP_KEY = os.environ['DROPBOX_APP_KEY'] if 'DROPBOX_APP_KEY' in os.environ else ''
APP_SECRET = os.environ['DROPBOX_APP_SECRET'] if 'DROPBOX_APP_SECRET' in os.environ else ''
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'app_folder'
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
if 'apply' in request.POST:
access_token = None
try:
rq_token = OAuthToken(request.session['dropbox_request_token_key'],
request.session['dropbox_request_token_secret'])
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(rq_token)
except Exception, err:
self.message_user(request,
"There was an error linking, did you visit the URL and clicked Accept?\n%s." % err)
return HttpResponseRedirect(request.get_full_path())
cl = client.DropboxClient(sess)
dropbox_user = cl.account_info()['display_name']
try:
dropbox = DropboxAccount.objects.get(pk=1)
dropbox.name = dropbox_user
dropbox.key = access_token.key
dropbox.secret = access_token.secret
dropbox.delta = ''
dropbox.save()
except Exception, err:
self.message_user(request, "There was an error saving:\n%s." % err)
return HttpResponseRedirect(request.get_full_path())
self.message_user(request, "Successfully linked to Dropbox account %s." % dropbox_user)
return HttpResponseRedirect('/admin')
else:
request_token = sess.obtain_request_token()
request.session['dropbox_request_token_key'] = request_token.key
request.session['dropbox_request_token_secret'] = request_token.secret
url = sess.build_authorize_url(request_token)
dropbox = DropboxAccount.objects.get(pk=1)
return TemplateResponse(request, 'admin/link_account.html', {
'DROPBOX_URL': url, 'CURRENT_DROPBOX_USER': dropbox.name}, current_app=self.admin_site.name)
link_view.short_description = "Link Dropbox account"
class PositionAdmin(GeoAdmin.OSMGeoAdmin):
list_filter = ('collar', LionListFilter)
ordering = ('-timestamp',)
class TrackingAdmin(admin.ModelAdmin):
list_filter = ('lion',)
ordering = ('-start',)
admin.site.register(Lion)
admin.site.register(Collar)
admin.site.register(Pride)
admin.site.register(Tracking, TrackingAdmin)
admin.site.register(Position, PositionAdmin)
admin.site.register(DropboxAccount, DropboxAdmin)
| {
"repo_name": "JJWTimmer/mnlp-tracking",
"path": "mnlp/lionmap/admin.py",
"copies": "1",
"size": "6085",
"license": "bsd-3-clause",
"hash": 8496167537716988000,
"line_mean": 37.7579617834,
"line_max": 117,
"alpha_frac": 0.595398521,
"autogenerated": false,
"ratio": 4.30035335689046,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5395751877890459,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import requests
from habiter.habit_api.api_call import DeferredAPICallFactory, DeferredAPICall
DEFAULT_API_URL = 'https://habitrpg.com/api/v2/'
DEFAULT_TIMEOUT = 5
def _api_call_description(foo):
def _make_deferred_call(self, *args, errback=None, err_args=(), **kwargs):
return self.call_factory.request(
errback=errback, err_args=err_args, **foo(self, *args, **kwargs))
return update_wrapper(_make_deferred_call, foo)
class HabitAPI:
def __init__(self, api_url=None, timeout=None, call_factory_factory=DeferredAPICallFactory):
if api_url is None:
api_url = DEFAULT_API_URL
if timeout is None:
timeout = DEFAULT_TIMEOUT
self.session = requests.Session()
self.session.headers.update({'Content-Type': 'application/json'})
self.call_factory = call_factory_factory(self.session, timeout=timeout, api_base_url=api_url)
@_api_call_description
def status(self)->DeferredAPICall:
return {
'method': 'get',
'path': 'status',
'postproc': lambda json: json['ok'],
'description': 'ping server for its status',
}
@_api_call_description
def content(self)->DeferredAPICall:
return {
'method': 'get',
'path': 'content',
'description': 'load all text assets',
}
def _get_id(task_or_id):
if isinstance(task_or_id, str):
return task_or_id
return task_or_id.id
class AuthorizedHabitAPI(HabitAPI):
def __init__(self, user_id, api_key, api_url=None, timeout=None, **kwargs):
super().__init__(api_url=api_url, timeout=timeout, **kwargs)
self.session.headers.update({
'x-api-user': user_id,
'x-api-key': api_key,
})
self.user_id = user_id
self.api_key = api_key
@_api_call_description
def get_user(self)->DeferredAPICall:
return {
'method': 'get',
'path': 'user',
'description': 'load entire user document',
}
@_api_call_description
def toggle_sleep(self)->DeferredAPICall:
return {
'method': 'post',
'path': 'user/sleep',
'description': 'toggle sleep',
}
@_api_call_description
def revive(self)->DeferredAPICall:
return {
'method': 'post',
'path': 'user/revive',
'description': 'revive user',
}
@_api_call_description
def get_tasks(self)->DeferredAPICall:
return {
'method': 'get',
'path': 'user/tasks',
'description': 'load all tasks',
}
@_api_call_description
def get_task(self, task_or_id)->DeferredAPICall:
return {
'method': 'get',
'path': 'user/tasks/' + _get_id(task_or_id),
'description': 'load task "{!s}"'.format(task_or_id),
}
@_api_call_description
def new_task(self, task_data: dict)->DeferredAPICall:
return {
'method': 'post',
'path': 'user/tasks/' + task_data['id'],
'body': task_data,
'description': 'create new task "{}"'.format(task_data['text']),
}
@_api_call_description
def update_task(self, task_data: dict)->DeferredAPICall:
return {
'method': 'put',
'path': 'user/tasks/' + task_data['id'],
'body': task_data,
'description': 'update task "{}"'.format(task_data['text']),
}
@_api_call_description
def delete_task(self, task_or_id)->DeferredAPICall:
return {
'method': 'delete',
'path': 'user/tasks/' + _get_id(task_or_id),
'description': 'delete task "{!s}"'.format(task_or_id),
}
@_api_call_description
def score_task(self, task_or_id, direction='up')->DeferredAPICall:
return {
'method': 'post',
'path': 'user/tasks/{id}/{dir}'.format(id=_get_id(task_or_id), dir=direction),
'description': direction + 'score task "{!s}"'.format(task_or_id),
}
| {
"repo_name": "moskupols/habiter",
"path": "habiter/habit_api/api.py",
"copies": "1",
"size": "4180",
"license": "mit",
"hash": -3049674558781839000,
"line_mean": 30.6666666667,
"line_max": 101,
"alpha_frac": 0.55215311,
"autogenerated": false,
"ratio": 3.6221837088388216,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9664403082153769,
"avg_score": 0.001986747337010486,
"num_lines": 132
} |
from functools import update_wrapper
import urlparse
import copy
from django import VERSION as DJANGO_VERSION
from django import http
from django.views import generic
from django.utils.decorators import method_decorator, classonlymethod
from django.views.decorators.csrf import csrf_protect
from django.contrib import messages
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.encoding import force_unicode
from . import helpers
from . import renders
from . import widgets
from .models import CMSLog
from .internal_tags import handler as tag_handler
class BaseView(generic.base.View):
"""
Base view for all Views. This is a class based view
that uses render classes to handle the preparation of an
response.
Render classes are classes that return a response of
some kind from a view, such as a HttpResponse object or a string.
The only requirement is that they have a render method that takes
a request and keyword arguments. Those keyword arguments should be
considered the context.
:param renders: A dictionary where the values are render \
class instances.
:param render_type: A string that denotes what renderer \
should be used. This must but a key in the renders dictionary. \
Default is 'response'.
"""
render_type = 'response'
def get_render_data(self, **kwargs):
"""
Because of the way mixin inheritance works
we can't have a default implementation of
get_context_data on the this class, so this
calls that method if available and returns
the resulting context.
"""
if hasattr(self, 'get_context_data'):
data = self.get_context_data(**kwargs)
else:
data = kwargs
return data
def render(self, request, collect_render_data=True, **kwargs):
"""
Render this view. This will call the render method
on the render class specified.
:param request: The request object
:param collect_render_data: If True we will call \
the get_render_data method to pass a complete context \
to the renderer.
:param kwargs: Any other keyword arguments that should \
be passed to the renderer.
"""
assert self.render_type in self.renders
render = self.renders[self.render_type]
if collect_render_data:
kwargs = self.get_render_data(**kwargs)
return render.render(request, **kwargs)
class SiteView(BaseView):
"""
Base view that provides a classmethod to render
the view as a string instead of as a HttpResponse.
"""
def get_as_string(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
@classonlymethod
def as_string(cls, **initkwargs):
"""
Similar to the as_view classmethod except this method will
render this view as a string. When rendering a view this way
the request will always be routed to the get method.
The default render_type is 'string' unless you specify
something else. If you provide your own render_type be sure
to specify a render class that returns a string.
"""
if not 'render_type' in initkwargs:
initkwargs['render_type'] = 'string'
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(u"You tried to pass in the %s method name as a"
u" keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError(u"%s() received an invalid keyword %r" % (
cls.__name__, key))
def view(request, *args, **kwargs):
try:
self = cls(**initkwargs)
self.request = request
self.args = args
self.kwargs = kwargs
return self.get_as_string(request, *args, **kwargs)
except http.Http404:
return ""
# take name and docstring from class
update_wrapper(view, cls, updated=())
return view
class CMSView(BaseView):
"""
Base class for CMS Views, should be used as the main view
class for all views that will be registered with a bundle.
:param base_template: The default base template, gets passed \
to the main template as 'base'.
:param default_template: The main template for this view.
:param object_header_tmpl: The template to render for an object \
header.
:param render_type: The render_type, defaults to 'response'.
:param renders: The dictionary of render views that this view \
knows how to set. Unless specified otherwise, this will be set \
to a CMSRender instance 'response' and RenderString instance \
'string'; both instances are initialized with the `default_template`.
:param bundle: The bundle that this view instance is attached \
to. Set by the bundle on initialization.
:param can_submit: Does this instance support form submission. \
Set to false by bundle when necessary.
:param required_groups: Groups that are required in order to render \
this view. Defaults to None, may be set by bundle.
"""
object_header_tmpl = "cms/object_header.html"
render_type = 'response'
base_template = 'cms/base_bundle_view.html'
renders = {}
bundle = None
can_submit = True
required_groups = None
ORIGIN_ARGUMENT = 'o'
name = None
def __init__(self, *args, **kwargs):
self.extra_render_data = {}
self.changed_kwargs = kwargs
super(CMSView, self).__init__(*args, **kwargs)
if not self.renders:
self.renders = {
'response': renders.CMSRender(template=self.default_template,
base=self.base_template),
'string': renders.RenderString(template=self.default_template,
base=self.base_template)
}
def customized_return_url(self, default_url):
redirect_url = self.request.GET.get(self.ORIGIN_ARGUMENT)
if redirect_url:
base = self.request.path.split('/')
if len(base) > 1 and redirect_url.startswith('/%s' % base[1]):
return redirect_url
return default_url
def get_navigation(self):
"""
Hook for overiding navigation per view.
Defaults to calling get_navigation on the
bundle.
"""
return self.bundle.get_navigation(self.request, **self.kwargs)
def add_to_render_data(self, **kwargs):
"""
Any keyword arguments provided will be passed to
the renderer when this view is rendered.
"""
self.extra_render_data.update(kwargs)
def get_tags(self, view_object=None):
"""
This method return a list of tags to use in the template
:return: list of tags
"""
tags = [force_unicode(self.bundle.get_title())]
back_bundle = self.get_back_bundle()
if back_bundle and back_bundle != self.bundle:
tags.append(force_unicode(back_bundle.get_title()))
if view_object:
tags.append(force_unicode(view_object))
return tags
def get_back_bundle(self, start_bundle=None):
if not start_bundle:
start_bundle = self.bundle
if getattr(start_bundle, 'main_list', None):
main_list = start_bundle.main_list
bundle = main_list.get_bundle(start_bundle, {}, self.kwargs)
return bundle
return None
def get_render_data(self, **kwargs):
"""
Returns all data that should be passed to the renderer.
By default adds the following arguments:
* **bundle** - The bundle that is attached to this view instance.
* **url_params** - The url keyword arguments. i.e.: self.kwargs.
* **user** - The user attached to this request.
* **base** - Unless base was already specified this gets set to \
'self.base_template'.
* **navigation** - The navigation bar for the page
* **object_header_tmpl** - The template to use for the \
object_header. Set to `self.object_header_tmpl`.
* **back_bundle** - The back_back bundle is bundle that is linked to \
from the object header as part of navigation. If there is an 'obj' \
argument in the context to render, this will be set to the bundle \
pointed to by the `main_list` attribute of this view's bundle. \
If this is not set, the template's back link will point to the \
admin_site's home page.
"""
obj = getattr(self, 'object', None)
data = dict(self.extra_render_data)
data.update(kwargs)
data.update({
'bundle': self.bundle,
'navigation': self.get_navigation(),
'url_params': self.kwargs,
'user': self.request.user,
'object_header_tmpl': self.object_header_tmpl,
'view_tags': tag_handler.tags_to_string(self.get_tags(obj))
})
if not 'base' in data:
data['base'] = self.base_template
if not 'back_bundle' in data:
data['back_bundle'] = self.get_back_bundle()
return super(CMSView, self).get_render_data(**data)
def _user_in_groups(self, user, allowed_groups):
groups = getattr(user, 'cached_groups', None)
if groups is None:
user.cached_groups = user.groups.all()
for group in user.cached_groups:
if group.name in allowed_groups:
return True
return False
def can_view(self, user):
"""
Returns True if user has permission to render this view.
At minimum this requires an active staff user. If the required_groups
attribute is not empty then the user must be a member of at least one
of those groups. If there are no required groups set for the view but
required groups are set for the bundle then the user must be a member
of at least one of those groups. If there are no groups to check this
will return True.
"""
if user.is_staff and user.is_active:
if user.is_superuser:
return True
elif self.required_groups:
return self._user_in_groups(user, self.required_groups)
elif self.bundle.required_groups:
return self._user_in_groups(user, self.bundle.required_groups)
else:
return True
return False
def get_url_kwargs(self, request_kwargs=None, **kwargs):
"""
Get the kwargs needed to reverse this url.
:param request_kwargs: The kwargs from the current request. \
These keyword arguments are only retained if they are present \
in this bundle's known url_parameters.
:param kwargs: Keyword arguments that will always be kept.
"""
if not request_kwargs:
request_kwargs = getattr(self, 'kwargs', {})
for k in self.bundle.url_params:
if k in request_kwargs and not k in kwargs:
kwargs[k] = request_kwargs[k]
return kwargs
def customize_form_widgets(self, form_class, fields=None):
"""
Hook for customizing widgets for a form_class. This is needed
for forms that specify their own fields causing the
default db_field callback to not be run for that field.
Default implementation checks for APIModelChoiceWidgets
or APIManyChoiceWidgets and runs the update_links method
on them. Passing the admin_site and request being used.
Returns a new class that contains the field with the initialized
custom widget.
"""
attrs = {}
if fields:
fields = set(fields)
for k, f in form_class.base_fields.items():
if fields and not k in fields:
continue
if isinstance(f.widget, widgets.APIModelChoiceWidget) \
or isinstance(f.widget, widgets.APIManyChoiceWidget):
field = copy.deepcopy(f)
field.widget.update_links(self.request, self.bundle.admin_site)
attrs[k] = field
if attrs:
form_class = type(form_class.__name__, (form_class,), attrs)
return form_class
@method_decorator(csrf_protect)
def dispatch(self, request, *args, **kwargs):
"""
Overrides the custom dispatch method to raise a Http404
if the current user does not have view permissions.
"""
self.request = request
self.args = args
self.kwargs = kwargs
if not self.can_view(request.user):
raise http.Http404
return super(CMSView, self).dispatch(request, *args, **kwargs)
def as_string(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
class ModelCMSMixin(object):
"""
Mixin for use with all cms views that interact with database models.
:param parent_field: The name of the field on the model \
that points a parent that must be present. This should either be \
a foreign key or a many to many field. Defaults to None.
:param parent_lookups: A list of field names to use when constructing \
the query for the parent object. If `parent_field` is present defaults \
to ('pk',) otherwise default is None.
:param slug_field: The name of the field on the model that should \
be used as the keyword argument when looking up an object. Used in \
combination with `slug_url_kwarg`. Defaults to 'pk'
:param slug_url_kwarg: The name of the URLConf keyword argument \
that contains the value to filter on. Used in combination with \
`slug_field`. Defaults to 'pk'.
:param base_filter_kwargs: Attribute to provide a dictionary of \
default keyword arguments for the base queryset.
"""
parent_lookups = None
parent_field = None
slug_field = 'pk'
slug_url_kwarg = 'pk'
base_filter_kwargs = {}
def get_formfield_overrides(self):
"""
Hook for specifying the default arguments when
creating a form field for a db field.
By default adds DateWidget for date fields,
TimeChoiceWidget for time fields, SplitDateTime
for datetime fields, and APIChoiceWidget for
foreign keys.
"""
return helpers.FORMFIELD_FOR_DBFIELD_DEFAULTS
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given
database Field instance. If kwargs are given, they're
passed to the form Field's constructor.
Default implementation uses the overrides returned by
`get_formfield_overrides`. If a widget is an instance
of APIChoiceWidget this will do lookup on the current
admin site for the bundle that is registered for that
module as the primary bundle for that one model. If a
match is found then this will call update_links on that
widget to store the appropriate urls for the javascript
to call. Otherwise the widget is removed and the default
select widget will be used instead.
"""
overides = self.get_formfield_overrides()
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in overides:
kwargs = dict(overides[klass], **kwargs)
break
# Our custom widgets need special init
mbundle = None
extra = kwargs.pop('widget_kwargs', {})
widget = kwargs.get('widget')
if kwargs.get('widget'):
if widget and isinstance(widget, type) and \
issubclass(widget, widgets.APIChoiceWidget):
mbundle = self.bundle.admin_site.get_bundle_for_model(
db_field.rel.to)
if mbundle:
widget = widget(db_field.rel, **extra)
else:
widget = None
if getattr(self, 'prepopulated_fields', None) and \
not getattr(self, 'object', None) and \
db_field.name in self.prepopulated_fields:
extra = kwargs.pop('widget_kwargs', {})
attr = extra.pop('attrs', {})
attr['data-source-fields'] = self.prepopulated_fields[db_field.name]
extra['attrs'] = attr
if not widget:
from django.forms.widgets import TextInput
widget = TextInput(**extra)
elif widget and isinstance(widget, type):
widget = widget(**extra)
kwargs['widget'] = widget
field = db_field.formfield(**kwargs)
if mbundle:
field.widget.update_links(self.request, self.bundle.admin_site)
return field
def log_action(self, instance, action, action_date=None, url="",
update_parent=True):
"""
Store an action in the database using the CMSLog model.
The following attributes are calculated and set on the log entry:
* **model_repr** - A unicode representation of the instance.
* **object_repr** - The verbose_name of the instance model class.
* **section** - The name of ancestor bundle that is directly \
attached to the admin site.
:param instance: The instance that this action was performed \
on.
:param action: The action type. Must be one of the options \
in CMSLog.ACTIONS.
:param action_date: The datetime the action occurred.
:param url: The url that the log entry should point to, \
Defaults to an empty string.
:param update_parent: If true this will update the last saved time \
on the object pointed to by this bundle's object_view. \
Defaults to True.
"""
section = None
if self.bundle:
bundle = self.bundle
while bundle.parent:
bundle = bundle.parent
section = bundle.name
# if we have a object view that comes from somewhere else
# save it too to update it.
changed_object = instance
bundle = self.bundle
while bundle.object_view == bundle.parent_attr:
bundle = bundle.parent
if update_parent and changed_object.__class__ != bundle._meta.model:
object_view, name = bundle.get_initialized_view_and_name(
bundle.object_view, kwargs=self.kwargs)
changed_object = object_view.get_object()
changed_object.save()
if not section:
section = ""
if url:
url = urlparse.urlparse(url).path
rep = unicode(instance)
if rep:
rep = rep[:255]
log = CMSLog(action=action, url=url, section=section,
model_repr=instance._meta.verbose_name,
object_repr=rep,
user_name=self.request.user.username,
action_date=action_date)
log.save()
def get_filter(self, **filter_kwargs):
"""
Returns a list of Q objects that can be passed
to an queryset for filtering.
Default implementation returns a Q
object for `base_filter_kwargs` and any
passed in keyword arguments.
"""
filter_kwargs.update(self.base_filter_kwargs)
if filter_kwargs:
return [models.Q(**filter_kwargs)]
return []
def get_queryset(self, **filter_kwargs):
"""
Get the list of items for this view. This will
call the `get_parent_object` method before doing
anything else to ensure that a valid parent object
is present. If a parent_object is returned it gets
set to `self.parent_object`.
If a queryset has been set then that queryset will be used.
Otherwise the default manager for the provided
model will be used.
Once we have a queryset, the `get_filter` method
is called and added to the queryset which is then
returned.
"""
self.parent_object = self.get_parent_object()
if self.queryset is not None:
queryset = self.queryset
if hasattr(queryset, '_clone'):
queryset = queryset._clone()
elif self.model is not None:
queryset = self.model._default_manager.filter()
else:
raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"
% self.__class__.__name__)
q_objects = self.get_filter(**filter_kwargs)
queryset = queryset.filter()
for q in q_objects:
queryset = queryset.filter(q)
return queryset
def get_parent_object(self):
"""
Lookup a parent object. If parent_field is None
this will return None. Otherwise this will try to
return that object.
The filter arguments are found by using the known url
parameters of the bundle, finding the value in the url keyword
arguments and matching them with the arguments in
`self.parent_lookups`. The first argument in parent_lookups
matched with the value of the last argument in the list of bundle
url parameters, the second with the second last and so forth.
For example let's say the parent_field attribute is 'gallery'
and the current bundle knows about these url parameters:
* adm_post
* adm_post_gallery
And the current value for 'self.kwargs' is:
* adm_post = 2
* adm_post_gallery = 3
if parent_lookups isn't set the filter for the queryset
on the gallery model will be:
* pk = 3
if parent_lookups is ('pk', 'post__pk') then the filter
on the queryset will be:
* pk = 3
* post__pk = 2
The model to filter on is found by finding the relationship
in self.parent_field and filtering on that model.
If a match is found, 'self.queryset` is changed to
filter on the parent as described above and the parent
object is returned. If no match is found, a Http404 error
is raised.
"""
if self.parent_field:
# Get the model we are querying on
if getattr(self.model._meta, 'init_name_map', None):
# pre-django-1.8
cache = self.model._meta.init_name_map()
field, mod, direct, m2m = cache[self.parent_field]
else:
# 1.10
if DJANGO_VERSION[1] >= 10:
field = self.model._meta.get_field(self.parent_field)
m2m = field.is_relation and field.many_to_many
direct = not field.auto_created or field.concrete
else:
# 1.8 and 1.9
field, mod, direct, m2m = self.model._meta.get_field(self.parent_field)
to = None
field_name = None
if self.parent_lookups is None:
self.parent_lookups = ('pk',)
url_params = list(self.bundle.url_params)
if url_params and getattr(self.bundle, 'delegated', False):
url_params = url_params[:-1]
offset = len(url_params) - len(self.parent_lookups)
kwargs = {}
for i in range(len(self.parent_lookups) - 1):
k = url_params[offset + i]
value = self.kwargs[k]
kwargs[self.parent_lookups[i + 1]] = value
main_arg = self.kwargs[url_params[-1]]
main_key = self.parent_lookups[0]
if m2m:
rel = getattr(self.model, self.parent_field)
kwargs[main_key] = main_arg
if direct:
to = rel.field.rel.to
field_name = self.parent_field
else:
try:
from django.db.models.fields.related import (
ForeignObjectRel)
if isinstance(rel.rel, ForeignObjectRel):
to = rel.rel.related_model
else:
to = rel.rel.model
except ImportError:
to = rel.rel.model
field_name = rel.rel.field.name
else:
to = field.rel.to
if main_key == 'pk':
to_field = field.rel.field_name
if to_field == 'vid':
to_field = 'object_id'
else:
to_field = main_key
kwargs[to_field] = main_arg
# Build the list of arguments
try:
obj = to.objects.get(**kwargs)
if self.queryset is None:
if m2m:
self.queryset = getattr(obj, field_name)
else:
self.queryset = self.model.objects.filter(
**{self.parent_field: obj})
return obj
except to.DoesNotExist:
raise http.Http404
return None
class ModelCMSView(CMSView):
"""
Base view for CMS views that interact with models.
Inherits from CMSView.
:param custom_model_name: A alternate verbose name for the \
given model.
"""
custom_model_name = None
custom_model_name_plural = None
def __init__(self, *args, **kwargs):
super(ModelCMSView, self).__init__(*args, **kwargs)
self.pk_url_kwarg = None
def write_message(self, status=messages.INFO, message=None):
"""
Writes a message to django's messaging framework and
returns the written message.
:param status: The message status level. Defaults to \
messages.INFO.
:param message: The message to write. If not given, \
defaults to appending 'saved' to the unicode representation \
of `self.object`.
"""
if not message:
message = u"%s saved" % self.object
messages.add_message(self.request, status, message)
return message
def get_url_kwargs(self, request_kwargs=None, **kwargs):
"""
If request_kwargs is not specified, self.kwargs is used instead.
If 'object' is one of the kwargs passed. Replaces it with
the value of 'self.slug_field' on the given object.
"""
if not request_kwargs:
request_kwargs = getattr(self, 'kwargs', {})
kwargs = super(ModelCMSView, self).get_url_kwargs(request_kwargs,
**kwargs)
obj = kwargs.pop('object', None)
if obj:
kwargs[self.slug_url_kwarg] = getattr(obj, self.slug_field, None)
elif self.slug_url_kwarg in request_kwargs:
kwargs[self.slug_url_kwarg] = request_kwargs[self.slug_url_kwarg]
return kwargs
def _model_name(self, plural=False):
return helpers.model_name(self.model, self.custom_model_name,
self.custom_model_name_plural,
plural=plural)
@property
def model_name_plural(self):
"""
Property for getting the plural verbose name of the given model.
Returns custom_model_name if present, otherwise returns
the verbose_name of the model.
"""
return self._model_name(plural=True)
@property
def model_name(self):
"""
Property for getting the verbose name of the given model.
Returns custom_model_name if present, otherwise returns
the verbose_name of the model.
"""
return self._model_name(plural=False)
def get_render_data(self, **kwargs):
"""
Adds the model_name to the context, then calls super.
"""
kwargs['model_name'] = self.model_name
kwargs['model_name_plural'] = self.model_name_plural
return super(ModelCMSView, self).get_render_data(**kwargs)
| {
"repo_name": "ff0000/scarlet",
"path": "scarlet/cms/base_views.py",
"copies": "1",
"size": "28738",
"license": "mit",
"hash": 7395063204944968000,
"line_mean": 35.7964148528,
"line_max": 91,
"alpha_frac": 0.5899157909,
"autogenerated": false,
"ratio": 4.469362363919129,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5559278154819128,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import uuid
from django import forms
from django.db.models import Field, SubfieldBase
from django.utils.encoding import smart_unicode
try:
#psycopg2 needs us to register the uuid type
import psycopg2
psycopg2.extras.register_uuid()
except (ImportError, AttributeError):
pass
class StringUUID(uuid.UUID):
def __init__(self, *args, **kwargs):
# get around UUID's immutable setter
object.__setattr__(self, 'hyphenate', kwargs.pop('hyphenate', False))
super(StringUUID, self).__init__(*args, **kwargs)
def __unicode__(self):
return unicode(str(self))
def __str__(self):
if self.hyphenate:
return super(StringUUID, self).__str__()
return self.hex
def __len__(self):
return len(self.__unicode__())
class UUIDField(Field):
"""
A field which stores a UUID value in hex format. This may also have
the Boolean attribute 'auto' which will set the value on initial save to a
new UUID value (calculated using the UUID1 method). Note that while all
UUIDs are expected to be unique we enforce this with a DB constraint.
"""
__metaclass__ = SubfieldBase
def __init__(self, version=4, node=None, clock_seq=None,
namespace=None, name=None, auto=False, *args, **kwargs):
assert version in (1, 3, 4, 5), "UUID version %s is not supported." % version
self.version = version
# We store UUIDs in hex format, which is fixed at 32 characters.
kwargs['max_length'] = 36
if kwargs.get('primary_key', False):
auto = True
self.auto = auto
if auto:
# Do not let the user edit UUIDs if they are auto-assigned.
kwargs['editable'] = False
kwargs['blank'] = True
kwargs['unique'] = True
if version == 1:
self.node, self.clock_seq = node, clock_seq
elif version in (3, 5):
self.namespace, self.name = namespace, name
super(UUIDField, self).__init__(*args, **kwargs)
#def get_internal_type(self):
# return "CharField"
def _create_uuid(self):
if self.version == 1:
args = (self.node, self.clock_seq)
elif self.version in (3, 5):
error_attr = None
if self.name is None:
error_attr = 'name'
elif self.namespace is None:
error_attr = 'namespace'
if error_attr is not None:
raise ValueError("The %s parameter of %s needs to be set." %
(error_attr, self))
if not isinstance(self.namespace, uuid.UUID):
raise ValueError("The name parameter of %s must be an "
"UUID instance." % self)
args = (self.namespace, self.name)
else:
args = ()
return getattr(uuid, 'uuid%s' % self.version)(*args)
def db_type(self, connection=None):
"""
Return the special uuid data type on Postgres databases.
"""
if connection and 'postgres' in connection.vendor:
return 'uuid'
return 'char(%s)' % self.max_length
def pre_save(self, model_instance, add):
"""
This is used to ensure that we auto-set values if required.
See CharField.pre_save
"""
value = getattr(model_instance, self.attname, None)
if self.auto and add and not value:
# Assign a new value for this attribute if required.
uuid = self._create_uuid()
setattr(model_instance, self.attname, uuid)
value = uuid.hex
return value
def get_db_prep_value(self, value, connection, prepared=False):
"""
Casts uuid.UUID values into the format expected by the back end
"""
if isinstance(value, uuid.UUID):
return str(value)
#elif isinstance(value, StringUUID):
# return str(value)
return value
def value_to_string(self, obj):
val = self._get_val_from_obj(obj)
if val is None:
data = ''
else:
data = unicode(val)
return data
def to_python(self, value):
"""
Returns a ``StringUUID`` instance from the value returned by the
database. This doesn't use uuid.UUID directly for backwards
compatibility, as ``StringUUID`` implements ``__unicode__`` with
``uuid.UUID.hex()``.
"""
if not value:
return None
# attempt to parse a UUID including cases in which value is a UUID
# instance already to be able to get our StringUUID in.
return StringUUID(smart_unicode(value))
def get_prep_value(self, value):
value = super(UUIDField, self).get_prep_value(value)
return self.to_python(value)
def formfield(self, **kwargs):
defaults = {
'form_class': forms.CharField,
'max_length': self.max_length,
}
defaults.update(kwargs)
return super(UUIDField, self).formfield(**defaults)
def south_field_triple(self):
"Returns a suitable description of this field for South."
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = "django_uuid_pk.fields.UUIDField"
args, kwargs = introspector(self)
# That's our definition!
return (field_class, args, kwargs)
def contribute_to_class(self, cls, name):
super(UUIDField, self).contribute_to_class(cls, name)
if self.primary_key:
_wrap_model_save(cls)
def _wrap_model_save(model):
if not hasattr(model, '_uuid_patched'):
old_save = getattr(model, 'save')
setattr(model, 'save', _wrap_save(old_save))
model._uuid_patched = True
def _wrap_save(func):
def inner(self, force_insert=False, force_update=False, using=None, **kwargs):
try:
return func(self, force_insert, force_update, using, **kwargs)
except:
self.pk = None
raise
return update_wrapper(inner, func)
| {
"repo_name": "saxix/django-uuid-pk",
"path": "django_uuid_pk/fields.py",
"copies": "1",
"size": "6229",
"license": "bsd-3-clause",
"hash": -4822736693072252000,
"line_mean": 32.4892473118,
"line_max": 85,
"alpha_frac": 0.5842029218,
"autogenerated": false,
"ratio": 4.169344042838019,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5253546964638018,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
def decorator(d):
"Make function d a decorator: d wraps a function fn."
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d
@decorator
def trace(f):
indent = ' '
def _f(*args):
signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args)))
print '%s--> %s' % (trace.level*indent, signature)
trace.level += 1
try:
result = f(*args)
print '%s<-- %s == %s' % ((trace.level-1)*indent,
signature, result)
finally:
# here we're returning so go down a trace level
trace.level -= 1
return result
trace.level = 0
return _f
def special_trace(ignore_args=None, ignore_kwargs=None, pretty=True):
""" Decorator factory. Similar to standard trace, except that this trace allows function
to ignore certain arguments. And set special tracing
parameters:
ignore_args - list of ints...positions in input args to ignore
ignore_kwargs - list of keys; keyword arguments to ignore
pretty - whether to pretty print signature
NOTE: if you just want pretty print can just use @special_trace and it will work
exactly the same as trace
"""
@decorator
def _trace(f):
def _f(*args, **kwargs):
signature = "%s(%s)" % (f.__name__,
_format_signature(args, kwargs))
print '%s--> %s' % (special_trace.level*indent, signature)
special_trace.level += 1
try:
result = f(*args, **kwargs)
print '%s<-- %s == %s' % ((special_trace.level-1)*indent,
signature.replace("\n" + indent, "\n"), result)
finally:
# here we're returning so go down a trace level
special_trace.level -= 1
return result
special_trace.level = 0
return _f
special_trace.indent = indent = ' '
def _format_signature(args, kwargs):
""" returns a string, the format of args and kwargs to be displayed"""
sig = ""
if pretty:
from pprint import pformat
format = lambda *args : pformat(*args)
else:
format = repr
sig += ", ".join(format(arg) for i, arg in enumerate(args) if i not in ignore_args)
sig += ", ".join(format(kw) + " = " + format(val) for kw, val in kwargs.items() if kw not in ignore_kwargs)
if sig: sig = "\n" + sig
return sig.replace("\n", "\n" + special_trace.level * indent)
if type(ignore_args) == type(_format_signature):
# if the first arg was actually a function (meaning was called without any arguments)
# we want this to behave just like a normal decorator
f = ignore_args
ignore_args = set()
ignore_kwargs = set()
return _trace(f)
else:
ignore_args = set(ignore_args or [])
ignore_kwargs = set(ignore_kwargs or [])
return _trace
# initialize special_trace level s.t. special_print can use it to
special_trace.level = 0
def special_print(*args):
""" print from a function as normal, but if using special_trace,
let's you print text with the same indent as trace (making it easier
to see what belongs to what)"""
args = "".join(str(a) for a in args)
indent = special_trace.level * special_trace.indent
print indent + args.replace("\n", "\n" + indent)
| {
"repo_name": "jtratner/simpleutils",
"path": "simpleutils/simpledebug.py",
"copies": "1",
"size": "3544",
"license": "mit",
"hash": -2617540991297125400,
"line_mean": 35.1632653061,
"line_max": 115,
"alpha_frac": 0.5663092551,
"autogenerated": false,
"ratio": 4.068886337543054,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.014973209541582388,
"num_lines": 98
} |
from functools import update_wrapper
def memoize(func):
func.memo = {}
def wrapper(arg):
try:
return func.memo[arg]
except KeyError:
func.memo[arg] = result = func(arg)
return result
return update_wrapper(wrapper, func)
@memoize
def partitions(n):
parts = set([tuple([n])])
for k in xrange(1, n):
for p in partitions(n - k):
parts.add(tuple(sorted([k] + p)))
return map(list, parts)
def zs1(n):
x = [1] * n
x[0], m, h = n, 0, 0
yield [x[0]]
while x[0] != 1:
if x[h] == 2:
m, x[h] = m + 1, 1
h -= 1
else:
r = x[h] - 1
t, x[h] = m - h + 1, r
while t >= r:
h += 1
x[h], t = r, t - r
if t == 0:
m = h
else:
m = h + 1
if t > 1:
h += 1
x[h] = t
yield x[:m + 1]
def zs2(n):
x = [1] * (n + 1)
yield x[1:]
x[:2] = -1, 2
h, m = 1, n - 1
yield x[1: m + 1]
while x[1] != n:
if m - h > 1:
h += 1
x[h], m = 2, m - 1
else:
j = m - 2
while x[j] == x[m - 1]:
x[j] = 1
j -= 1
h = j + 1
x[h], r, x[m] = x[m - 1] + 1, x[m] + x[m - 1] * (m - h - 1), 1
if m - h > 1:
x[m - 1] = 1
m = h + r - 1
yield x[1: m + 1]
if __name__ == "__main__":
print sorted(partitions(6))
print list(zs1(6))
print list(zs2(6))
"""
It strikes me that many recursive solutions will probably be inefficient
(except for Haskell ones, perhaps), since solutions to subproblems are
recomputed every time they're needed, similar to SICP's discussion of Fibonacci
number generation.
First up, a memoizing version (based on a Python version that Programming
Praxis pointed me to on StackOverflow) that stores previous answers.
Next are <code>zs1</code> and <code>zs2</code>, Python versions of two
algorithms found in <code>Fast Algorithms for Generating Integer
Paritions</code> by Zoghbi and Stojmenovic (1998). They're iterative and more
efficient than the first solution, if uglier. I've made them generators instead
of lists, but that's not really relevant to the algorithms.
[sourcecode lang="python"]
[/sourcecode]
"""
| {
"repo_name": "genos/online_problems",
"path": "prog_praxis/partitions.py",
"copies": "1",
"size": "2428",
"license": "mit",
"hash": 5467529176316084000,
"line_mean": 25.6813186813,
"line_max": 79,
"alpha_frac": 0.4880560132,
"autogenerated": false,
"ratio": 3.2590604026845638,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42471164158845637,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.apps import apps
from django.conf import settings
from django.conf.urls import url
from django.contrib import admin
from django.contrib.admin.options import csrf_protect_m
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django_mptt_admin.admin import DjangoMpttAdmin
from mptt.admin import MPTTModelAdmin
from glitter.admin import GlitterAdminMixin
from glitter.models import Version
from .forms import DuplicatePageForm, PageAdminForm
from .models import Page
@admin.register(Page)
class PageAdmin(GlitterAdminMixin, DjangoMpttAdmin, MPTTModelAdmin):
list_display = (
'title', 'url', 'view_url', 'is_published', 'in_nav', 'admin_unpublished_count',
'glitter_app_name',
)
mptt_level_indent = 25
glitter_render = True
change_list_template = 'admin/pages/page/change_list.html'
change_form_template = 'admin/pages/page/change_form.html'
form = PageAdminForm
def get_fieldsets(self, request, obj=None):
fields = [
'url', 'title', 'parent', 'tags', 'login_required', 'show_in_navigation',
]
# Don't show login_required unless needed
if not getattr(settings, 'GLITTER_SHOW_LOGIN_REQUIRED', False):
fields.remove('login_required')
# Show glitter tags if it's set to show.
if not getattr(settings, 'GLITTER_PAGES_TAGS', False):
fields.remove('tags')
fieldsets = [
[None, {'fields': fields}],
['Advanced options', {
'classes': ['collapse'],
'fields': ['glitter_app_name'],
}]
]
return fieldsets
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
template_response = super().changelist_view(request, extra_context)
template_response.template_name = 'admin/pages/page/change_list_tree.html'
return template_response
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urlpatterns = super().get_urls()
info = self.model._meta.app_label, self.model._meta.model_name
urlpatterns = [
url(r'^$', wrap(self.grid_view)),
url(r'^tree/$', wrap(self.changelist_view), name='%s_%s_tree' % info),
url(r'^(\d+)/duplicate/$', wrap(self.duplicate_page), name='%s_%s_duplicate' % info),
] + urlpatterns
return urlpatterns
def get_inline_instances(self, request, obj=None):
# Optional glitter applications. Both are imported after the is_installed check to prevent
# migrations applied to the core glitter app
if apps.is_installed('glitter.publisher'):
from glitter.publisher.admin import ActionInline
if ActionInline not in self.inlines:
self.inlines = self.inlines + [ActionInline]
if apps.is_installed('glitter.reminders'):
from glitter.reminders.admin import ReminderInline
if ReminderInline not in self.inlines:
self.inlines = self.inlines + [ReminderInline]
return super().get_inline_instances(request, obj)
def view_url(self, obj):
info = self.model._meta.app_label, self.model._meta.model_name
redirect_url = reverse('admin:%s_%s_redirect' % info, kwargs={'object_id': obj.id})
return '<a href="%s">View page</a>' % (redirect_url)
view_url.short_description = 'View page'
view_url.allow_tags = True
def in_nav(self, obj):
return obj.show_in_navigation
in_nav.boolean = True
def admin_unpublished_count(self, obj):
return obj.unpublished_count or ''
admin_unpublished_count.short_description = 'Unpublished pages'
admin_unpublished_count.allow_tags = True
@csrf_protect_m
@transaction.atomic
def duplicate_page(self, request, obj_id):
obj = get_object_or_404(Page, id=obj_id)
if not self.has_add_permission(request):
raise PermissionDenied
if request.method == "POST":
form = DuplicatePageForm(request.POST or None)
if form.is_valid():
new_page = form.save()
# Use current version if exists if not get the latest
if obj.current_version:
current_version = obj.current_version
else:
current_version = obj.get_latest_version()
if current_version:
# Create a new version
new_version = Version(content_object=new_page)
new_version.template_name = current_version.template_name
new_version.version_number = 1
new_version.owner = request.user
new_version.save()
self.duplicate_content(current_version, new_version)
return HttpResponseRedirect(
reverse('admin:glitter_pages_page_change', args=(new_page.id,))
)
else:
form = DuplicatePageForm(initial={
'url': obj.url,
'title': obj.title,
'parent': obj.parent,
})
adminForm = admin.helpers.AdminForm(
form=form,
fieldsets=[('Duplicate Page: {}'.format(obj), {
'fields': DuplicatePageForm.Meta.fields
})],
prepopulated_fields=self.get_prepopulated_fields(request, obj),
readonly_fields=self.get_readonly_fields(request, obj),
model_admin=self
)
context = {
'adminform': adminForm,
'opts': obj._meta,
'change': False,
'is_popup': False,
'save_as': False,
'has_delete_permission': self.has_delete_permission(request, obj),
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
}
return render(
request, 'admin/pages/page/duplicate_page.html', context
)
| {
"repo_name": "blancltd/django-glitter",
"path": "glitter/pages/admin.py",
"copies": "2",
"size": "6423",
"license": "bsd-3-clause",
"hash": -4856202407764497000,
"line_mean": 36.3430232558,
"line_max": 98,
"alpha_frac": 0.6056359956,
"autogenerated": false,
"ratio": 4.08587786259542,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000523486432737843,
"num_lines": 172
} |
from functools import update_wrapper
from django.apps import apps
from django.conf import settings
from django.contrib.admin import ModelAdmin, actions
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import ImproperlyConfigured
from django.db.models.base import ModelBase
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.urls import NoReverseMatch, reverse
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.i18n import JavaScriptCatalog
system_check_errors = []
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Django site admin')
# Text to put in each page's <h1>.
site_header = ugettext_lazy('Django administration')
# Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration')
# URL for the "View site" link at the top of each admin page.
site_url = '/'
_empty_value_display = '-'
login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
def __init__(self, name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured(
'The model %s is abstract, so it cannot be registered with admin.' % model.__name__
)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
# Instantiate the admin class to save in the registry
admin_obj = admin_class(model, self)
if admin_class is not ModelAdmin and settings.DEBUG:
system_check_errors.extend(admin_obj.check())
self._registry[model] = admin_obj
def unregister(self, model_or_iterable):
"""
Unregisters the given model(s).
If a model isn't already registered, this will raise NotRegistered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotRegistered('The model %s is not registered' % model.__name__)
del self._registry[model]
def is_registered(self, model):
"""
Check if a model class is registered with this `AdminSite`.
"""
return model in self._registry
def add_action(self, action, name=None):
"""
Register an action to be available globally.
"""
name = name or action.__name__
self._actions[name] = action
self._global_actions[name] = action
def disable_action(self, name):
"""
Disable a globally-registered action. Raises KeyError for invalid names.
"""
del self._actions[name]
def get_action(self, name):
"""
Explicitly get a registered global action whether it's enabled or
not. Raises KeyError for invalid names.
"""
return self._global_actions[name]
@property
def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
return six.iteritems(self._actions)
@property
def empty_value_display(self):
return self._empty_value_display
@empty_value_display.setter
def empty_value_display(self, empty_value_display):
self._empty_value_display = empty_value_display
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
return request.user.is_active and request.user.is_staff
def admin_view(self, view, cacheable=False):
"""
Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You'll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import url
urls = super(MyAdminSite, self).get_urls()
urls += [
url(r'^my_view/$', self.admin_view(some_view))
]
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.
"""
def inner(request, *args, **kwargs):
if not self.has_permission(request):
if request.path == reverse('admin:logout', current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
# Inner import to prevent django.contrib.admin (app) from
# importing django.contrib.auth.models.User (unrelated model).
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
request.get_full_path(),
reverse('admin:login', current_app=self.name)
)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import url, include
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
wrapper.admin_site = self
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^$', wrap(self.index), name='index'),
url(r'^login/$', self.login, name='login'),
url(r'^logout/$', wrap(self.logout), name='logout'),
url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
name='view_on_site'),
]
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
for model, model_admin in self._registry.items():
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
# If there were ModelAdmins registered, we should have a list of app
# labels for which we need to allow access to the app_index view,
if valid_app_labels:
regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
urlpatterns += [
url(regex, wrap(self.app_index), name='app_list'),
]
return urlpatterns
@property
def urls(self):
return self.get_urls(), 'admin', self.name
def each_context(self, request):
"""
Returns a dictionary of variables to put in the template context for
*every* page in the admin site.
For sites running on a subpath, use the SCRIPT_NAME value if site_url
hasn't been customized.
"""
script_name = request.META['SCRIPT_NAME']
site_url = script_name if self.site_url == '/' and script_name else self.site_url
return {
'site_title': self.site_title,
'site_header': self.site_header,
'site_url': site_url,
'has_permission': self.has_permission(request),
'available_apps': self.get_app_list(request),
}
def password_change(self, request, extra_context=None):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.admin.forms import AdminPasswordChangeForm
from django.contrib.auth.views import PasswordChangeView
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {
'form_class': AdminPasswordChangeForm,
'success_url': url,
'extra_context': dict(self.each_context(request), **(extra_context or {})),
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
request.current_app = self.name
return PasswordChangeView.as_view(**defaults)(request)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import PasswordChangeDoneView
defaults = {
'extra_context': dict(self.each_context(request), **(extra_context or {})),
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
request.current_app = self.name
return PasswordChangeDoneView.as_view(**defaults)(request)
def i18n_javascript(self, request, extra_context=None):
"""
Displays the i18n JavaScript that the Django admin requires.
`extra_context` is unused but present for consistency with the other
admin views.
"""
return JavaScriptCatalog.as_view(packages=['django.contrib.admin'])(request)
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import LogoutView
defaults = {
'extra_context': dict(
self.each_context(request),
# Since the user isn't logged out at this point, the value of
# has_permission must be overridden.
has_permission=False,
**(extra_context or {})
),
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
request.current_app = self.name
return LogoutView.as_view(**defaults)(request)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
if request.method == 'GET' and self.has_permission(request):
# Already logged-in, redirect to admin index
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
from django.contrib.auth.views import LoginView
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.admin.forms eventually imports User.
from django.contrib.admin.forms import AdminAuthenticationForm
context = dict(
self.each_context(request),
title=_('Log in'),
app_path=request.get_full_path(),
username=request.user.get_username(),
)
if (REDIRECT_FIELD_NAME not in request.GET and
REDIRECT_FIELD_NAME not in request.POST):
context[REDIRECT_FIELD_NAME] = reverse('admin:index', current_app=self.name)
context.update(extra_context or {})
defaults = {
'extra_context': context,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'admin/login.html',
}
request.current_app = self.name
return LoginView.as_view(**defaults)(request)
def _build_app_dict(self, request, label=None):
"""
Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app.
"""
app_dict = {}
if label:
models = {
m: m_a for m, m_a in self._registry.items()
if m._meta.app_label == label
}
else:
models = self._registry
for model, model_admin in models.items():
app_label = model._meta.app_label
has_module_perms = model_admin.has_module_permission(request)
if not has_module_perms:
continue
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True not in perms.values():
continue
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change'):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add'):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': apps.get_app_config(app_label).verbose_name,
'app_label': app_label,
'app_url': reverse(
'admin:app_list',
kwargs={'app_label': app_label},
current_app=self.name,
),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if label:
return app_dict.get(label)
return app_dict
def get_app_list(self, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""
app_dict = self._build_app_dict(request)
# Sort the apps alphabetically.
app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
return app_list
@never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_list = self.get_app_list(request)
context = dict(
self.each_context(request),
title=self.index_title,
app_list=app_list,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.index_template or 'admin/index.html', context)
def app_index(self, request, app_label, extra_context=None):
app_dict = self._build_app_dict(request, app_label)
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
app_name = apps.get_app_config(app_label).verbose_name
context = dict(
self.each_context(request),
title=_('%(app)s administration') % {'app': app_name},
app_list=[app_dict],
app_label=app_label,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
| {
"repo_name": "syphar/django",
"path": "django/contrib/admin/sites.py",
"copies": "7",
"size": "19625",
"license": "bsd-3-clause",
"hash": -8948218338538918000,
"line_mean": 37.7845849802,
"line_max": 109,
"alpha_frac": 0.5931210191,
"autogenerated": false,
"ratio": 4.395296752519597,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8488417771619596,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from philo.admin import EntityAdmin
from philo.contrib.sobol.models import Search, ResultURL, SearchView
class ResultURLInline(admin.TabularInline):
model = ResultURL
readonly_fields = ('url',)
can_delete = False
extra = 0
max_num = 0
class SearchAdmin(admin.ModelAdmin):
readonly_fields = ('string',)
inlines = [ResultURLInline]
list_display = ['string', 'unique_urls', 'total_clicks']
search_fields = ['string', 'result_urls__url']
actions = ['results_action']
if 'grappelli' in settings.INSTALLED_APPS:
change_form_template = 'admin/sobol/search/grappelli_change_form.html'
def unique_urls(self, obj):
return obj.unique_urls
unique_urls.admin_order_field = 'unique_urls'
def total_clicks(self, obj):
return obj.total_clicks
total_clicks.admin_order_field = 'total_clicks'
def queryset(self, request):
qs = super(SearchAdmin, self).queryset(request)
return qs.annotate(total_clicks=Count('result_urls__clicks', distinct=True), unique_urls=Count('result_urls', distinct=True))
class SearchViewAdmin(EntityAdmin):
raw_id_fields = ('results_page',)
related_lookup_fields = {'fk': raw_id_fields}
admin.site.register(Search, SearchAdmin)
admin.site.register(SearchView, SearchViewAdmin) | {
"repo_name": "ithinksw/philo",
"path": "philo/contrib/sobol/admin.py",
"copies": "1",
"size": "1663",
"license": "isc",
"hash": 5813954156907250000,
"line_mean": 30.3962264151,
"line_max": 127,
"alpha_frac": 0.7684906795,
"autogenerated": false,
"ratio": 3.3938775510204082,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46623682305204084,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.conf import settings
from django.contrib import messages
from django.contrib.admin import ModelAdmin
from django.contrib.admin.options import InlineModelAdmin
from django.contrib.admin.sites import AdminSite
from django.contrib.admin.utils import unquote, quote
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import resolve, reverse
from django.db.models.base import ModelBase
from django.http import Http404, HttpResponseBadRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import slugify
from django.template.response import TemplateResponse
from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from glitter.models import ContentBlock, Version
from glitter.page import Glitter
from glitter.templates import get_layout
from glitter.utils import JSONEncoderForHTML
class BlockAdminSite(AdminSite):
change_form_template = 'blockadmin/change_form.html'
def __init__(self, *args, **kwargs):
# All blocks can be registered to this admin site
self.block_list = {}
super().__init__(*args, **kwargs)
# Use the block admin class by default
def register(self, model_or_iterable, admin_class=None, **options):
if not admin_class:
admin_class = BlockAdmin
category = options.pop('category', None)
if category:
self.register_block(model_or_iterable, category)
super().register(model_or_iterable, admin_class, **options)
# Blocks from the site or other apps can be registered
def register_block(self, block_or_iterable, category):
if category not in self.block_list:
self.block_list[category] = []
if issubclass(block_or_iterable.__class__, ModelBase):
self.block_list[category].append(block_or_iterable)
else:
for block in block_or_iterable:
self.block_list[category].append(block)
def unregister_block(self, block, category):
try:
self.block_list[category].remove(block)
except ValueError:
pass
# Remove all of the default admin URLs, we only want the model views for
# the block admin.
def get_urls(self):
from django.conf.urls import url, include
if settings.DEBUG:
self.check_dependencies()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
]
# Add in each model's views.
for model, model_admin in self._registry.items():
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name),
include(model_admin.urls))
]
return urlpatterns
# We have no logout here, so just raise PermissionDenied if needed
def admin_view(self, view, cacheable=False):
def inner(request, *args, **kwargs):
if not self.has_permission(request):
raise PermissionDenied
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_app_list(self, request):
return {}
class BlockAdmin(ModelAdmin):
# Keep block admin change forms in the blockadmin template directory
@property
def change_form_template(self):
opts = self.model._meta
app_label = opts.app_label
return (
"blockadmin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"blockadmin/%s/change_form.html" % app_label,
"blockadmin/change_form.html"
)
# We only want the change form for the block admin
def get_urls(self):
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
urlpatterns = [
url(r'^add/(?P<version_id>\d+)/$', wrap(self.add_view), name='%s_%s_add' % info),
url(r'^(.+)/continue/$', wrap(self.continue_view), name='%s_%s_continue' % info),
url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
]
return urlpatterns
def log_change(self, request, object, message):
pass
def response_rerender(self, request, obj, template, extra_context=None):
request.current_app = self.admin_site.name
content_block = obj.content_block
version = content_block.obj_version
glitter = Glitter(version, request=request)
columns = glitter.render(edit_mode=True, rerender=True)
context = {
'column': slugify(content_block.column),
'rendered_json': JSONEncoderForHTML().encode({
'content': columns[content_block.column],
}),
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template, context)
# A redirect back to the edit view
def continue_view(self, request, object_id):
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
'name': force_text(self.opts.verbose_name),
'key': escape(object_id)},
)
if not self.has_change_permission(request, obj):
raise PermissionDenied
opts = self.opts.app_label, self.opts.model_name
change_url = reverse(
'admin:%s_%s_change' % opts,
args=(object_id,),
current_app=self.admin_site.name)
# This template will rerender the
return self.response_rerender(request, obj, 'blockadmin/continue.html', {
'change_url': change_url,
})
def get_version(self, request):
# As this is the Django admin and we can't just set self.version_id due to thread safety
# issues, we need to find the version ID of the page when adding a new block. It'll be
# accessible in the URL - although this is a very hacky way to access it.
func, args, kwargs = resolve(request.path)
version_id = kwargs.get('version_id', None)
if version_id is None:
# If a version_id kwarg isn't given - we're probably being called by change_view, so
# there isn't a Version for this request
return None
else:
return Version.objects.get(id=version_id)
def has_glitter_edit_permission(self, request, obj):
"""
Return a boolean if a user has edit access to the glitter object/page this object is on.
"""
# We're testing for the edit permission here with the glitter object - not the current
# object, not the change permission. Once a user has edit access to an object they can edit
# all content on it.
permission_name = '{}.edit_{}'.format(
obj._meta.app_label, obj._meta.model_name,
)
has_permission = (
request.user.has_perm(permission_name) or
request.user.has_perm(permission_name, obj=obj)
)
return has_permission
def has_add_permission(self, request):
# Find the glitter object to see if they've got permission to edit that
version = self.get_version(request=request)
# If a version can't be found for this request, it's probably being called by change_view.
# In this case we just return True as it shouldn't matter.
if version is None:
return True
glitter_obj = version.content_object
# Use the glitter object for permission testing
has_permission = self.has_glitter_edit_permission(request, obj=glitter_obj)
return has_permission
def has_change_permission(self, request, obj=None):
# This shouldn't happen - but given that we need to find out the permissions for the
# glitter object and not just this content block, just fail early incase something goes
# wrong.
if obj is None:
return False
# Find the glitter object to see if they've got permission to edit that
version = obj.content_block.obj_version
glitter_obj = version.content_object
# Use the glitter object for permission testing
has_permission = self.has_glitter_edit_permission(request, obj=glitter_obj)
return has_permission
def add_view(self, request, version_id, form_url='', extra_context=None):
version = get_object_or_404(Version, id=version_id)
# Version must not be saved, and must belong to this user
if version.version_number or version.owner != request.user:
raise PermissionDenied
# Need to ensure that new blocks go into valid columns
template_obj = get_layout(template_name=version.template_name)
column_choices = list(template_obj._meta.columns)
if request.GET.get('column') not in column_choices:
return HttpResponseBadRequest('Invalid column')
return self.changeform_view(request, None, form_url, extra_context)
def change_view(self, request, object_id, form_url='', extra_context=None):
"""The 'change' admin view for this model."""
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
'name': force_text(self.opts.verbose_name),
'key': escape(object_id),
})
if not self.has_change_permission(request, obj):
raise PermissionDenied
content_block = obj.content_block
version = content_block.obj_version
# Version must not be saved, and must belong to this user
if version.version_number or version.owner != request.user:
raise PermissionDenied
return super().change_view(request, object_id, form_url, extra_context)
def response_change(self, request, obj):
"""Determine the HttpResponse for the change_view stage."""
opts = self.opts.app_label, self.opts.model_name
pk_value = obj._get_pk_val()
if '_continue' in request.POST:
msg = _(
'The %(name)s block was changed successfully. You may edit it again below.'
) % {'name': force_text(self.opts.verbose_name)}
self.message_user(request, msg, messages.SUCCESS)
# We redirect to the save and continue page, which updates the
# parent window in javascript and redirects back to the edit page
# in javascript.
return HttpResponseRedirect(reverse(
'admin:%s_%s_continue' % opts,
args=(pk_value,),
current_app=self.admin_site.name
))
# Update column and close popup - don't bother with a message as they won't see it
return self.response_rerender(request, obj, 'admin/glitter/update_column.html')
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
# Whenever we're adding a new block to a page, we'll need to create a ContentBlock to go
# along with it
if change is False:
version = self.get_version(request=request)
# Create a content block to link the version and the block
content_block = ContentBlock(
obj_version=version,
column=request.GET['column'],
content_type=ContentType.objects.get_for_model(obj),
object_id=obj.id,
)
if request.GET.get('top', '').lower() == 'true':
# User wants block at the top of the column, so set the position or it'll end up
# being autosaved to the end of the column
first_block = ContentBlock.objects.filter(
obj_version=version, column=content_block.column,
).first()
if first_block is not None:
content_block.position = first_block.position - 1
content_block.save()
obj.content_block = content_block
obj.save(update_fields=['content_block'])
def response_add(self, request, obj, post_url_continue=None):
opts = obj._meta
pk_value = obj._get_pk_val()
# Save and continue editing - continue with the iframe
if '_continue' in request.POST:
msg = _('The block was added successfully. You may edit it again below.')
self.message_user(request, msg, messages.SUCCESS)
# We redirect to the save and continue page, which updates the
# parent window in javascript and redirects back to the edit page
# in javascript.
post_url_continue = reverse(
'block_admin:%s_%s_continue' % (opts.app_label, opts.model_name),
args=(quote(pk_value),),
current_app=self.admin_site.name
)
return HttpResponseRedirect(post_url_continue)
# Update column and close popup - don't bother with a message as they won't see it
return self.response_rerender(request, obj, 'admin/glitter/update_column.html')
class InlineBlockAdmin(InlineModelAdmin):
# For inline objects we always allow adding/editing/deleting. This is an additional check done
# after the permissions for the object has been checked - everyone needs to be able to edit the
# same content on the same page, so just allow all inlines.
def has_add_permission(self, request):
return True
def has_change_permission(self, request, obj=None):
return True
def has_delete_permission(self, request, obj=None):
return True
class StackedInline(InlineBlockAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularInline(InlineBlockAdmin):
template = 'admin/edit_inline/tabular.html'
site = BlockAdminSite(name='block_admin')
def register(model, admin=None, category=None):
""" Decorator to registering you Admin class. """
def _model_admin_wrapper(admin_class):
site.register(model, admin_class=admin_class)
if category:
site.register_block(model, category)
return admin_class
return _model_admin_wrapper
| {
"repo_name": "blancltd/django-glitter",
"path": "glitter/blockadmin/blocks.py",
"copies": "2",
"size": "15352",
"license": "bsd-3-clause",
"hash": 7042206911200867000,
"line_mean": 37.38,
"line_max": 99,
"alpha_frac": 0.6301459093,
"autogenerated": false,
"ratio": 4.197976483456385,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009382029301367762,
"num_lines": 400
} |
from functools import update_wrapper
# from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
# from django.utils.html import strip_spaces_between_tags as short
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.contrib import admin
try:
from django.contrib.admin.utils import unquote
except ImportError:
from django.contrib.admin.util import unquote
from django.contrib.admin.views.main import ChangeList
class OrderedModelAdmin(admin.ModelAdmin):
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
return patterns('',
url(r'^(.+)/move-(up)/$', wrap(self.move_view),
name='{app}_{model}_order_up'.format(**self._get_model_info())),
url(r'^(.+)/move-(down)/$', wrap(self.move_view),
name='{app}_{model}_order_down'.format(**self._get_model_info())),
) + super(OrderedModelAdmin, self).get_urls()
def _get_changelist(self, request):
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
cl = ChangeList(request, self.model, list_display,
list_display_links, self.list_filter, self.date_hierarchy,
self.search_fields, self.list_select_related,
self.list_per_page, self.list_max_show_all, self.list_editable,
self)
return cl
request_query_string = ''
def changelist_view(self, request, extra_context=None):
cl = self._get_changelist(request)
self.request_query_string = cl.get_query_string()
return super(OrderedModelAdmin, self).changelist_view(request, extra_context)
def move_view(self, request, object_id, direction):
cl = self._get_changelist(request)
# support get_query_set for backward compatibility
get_queryset = getattr(cl, 'get_queryset', None) or getattr(cl, 'get_query_set')
qs = get_queryset(request)
obj = get_object_or_404(self.model, pk=unquote(object_id))
obj.move(direction, qs)
return HttpResponseRedirect('../../%s' % self.request_query_string)
def move_up_down_links(self, obj):
model_info = self._get_model_info()
return render_to_string("ordered_model/admin/order_controls.html", {
'app_label': model_info['app'],
'module_name': model_info['model'],
'object_id': obj.pk,
'urls': {
'up': reverse("admin:{app}_{model}_order_up".format(**model_info), args=[obj.pk, 'up']),
'down': reverse("admin:{app}_{model}_order_down".format(**model_info), args=[obj.pk, 'down']),
},
'query_string': self.request_query_string
})
move_up_down_links.allow_tags = True
move_up_down_links.short_description = _(u'Move')
def _get_model_info(self):
# module_name was renamed to model_name in Django 1.7
if hasattr(self.model._meta, 'model_name'):
model = self.model._meta.model_name
else:
model = self.model._meta.module_name
return {
'app': self.model._meta.app_label,
'model': model
}
| {
"repo_name": "foozmeat/django-ordered-model",
"path": "ordered_model/admin.py",
"copies": "2",
"size": "3603",
"license": "bsd-3-clause",
"hash": -1247356638503631000,
"line_mean": 39.4831460674,
"line_max": 110,
"alpha_frac": 0.6180960311,
"autogenerated": false,
"ratio": 3.882543103448276,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0011895398668602232,
"num_lines": 89
} |
from functools import update_wrapper
from django.conf import settings
from django.http.request import validate_host
from ..exceptions import DenyConnection
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
class BaseOriginValidator(object):
"""
Base class-based decorator for origin validation of WebSocket connect
messages.
This base class handles parsing of the origin header. When the origin header
is missing, empty or contains non-ascii characters, it raises a
DenyConnection exception to reject the connection.
Subclasses must overwrite the method validate_origin(self, message, origin)
to return True when a message should be accepted, False otherwise.
"""
def __init__(self, func):
update_wrapper(self, func)
self.func = func
def __call__(self, message, *args, **kwargs):
origin = self.get_origin(message)
if not self.validate_origin(message, origin):
raise DenyConnection
return self.func(message, *args, **kwargs)
def get_header(self, message, name):
headers = message.content['headers']
for header in headers:
try:
if header[0] == name:
return header[1:]
except IndexError:
continue
raise KeyError('No header named "{}"'.format(name))
def get_origin(self, message):
"""
Returns the origin of a WebSocket connect message.
Raises DenyConnection for messages with missing or non-ascii Origin
header.
"""
try:
header = self.get_header(message, b'origin')[0]
except (IndexError, KeyError):
raise DenyConnection
try:
origin = header.decode('ascii')
except UnicodeDecodeError:
raise DenyConnection
return origin
def validate_origin(self, message, origin):
"""
Validates the origin of a WebSocket connect message.
Must be overwritten by subclasses.
"""
raise NotImplemented('You must overwrite this method.')
class AllowedHostsOnlyOriginValidator(BaseOriginValidator):
"""
Class-based decorator for websocket consumers that checks that
the origin is allowed according to the ALLOWED_HOSTS settings.
"""
def validate_origin(self, message, origin):
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = ['localhost', '127.0.0.1', '[::1]']
origin_hostname = urlparse(origin).hostname
valid = (origin_hostname and
validate_host(origin_hostname, allowed_hosts))
return valid
allowed_hosts_only = AllowedHostsOnlyOriginValidator
| {
"repo_name": "Krukov/channels",
"path": "channels/security/websockets.py",
"copies": "1",
"size": "2800",
"license": "bsd-3-clause",
"hash": 741683387488112900,
"line_mean": 30.1111111111,
"line_max": 80,
"alpha_frac": 0.6482142857,
"autogenerated": false,
"ratio": 4.786324786324786,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5934539072024786,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.admin.utils import unquote
from django.core.urlresolvers import reverse
from django.db.utils import IntegrityError
from django.http import (
Http404, HttpResponseForbidden, HttpResponseNotAllowed,
HttpResponseRedirect)
from django.utils.encoding import force_text
from django.utils.html import format_html, format_html_join
from django.utils.translation import ugettext, ugettext_lazy as _
from olympia import amo
from olympia.abuse.models import AbuseReport
from olympia.access import acl
from olympia.activity.models import ActivityLog, UserLog
from olympia.addons.models import Addon
from olympia.amo.utils import render
from olympia.bandwagon.models import Collection
from olympia.ratings.models import Rating
from . import forms
from .models import DeniedName, GroupUser, UserProfile
class GroupUserInline(admin.TabularInline):
model = GroupUser
raw_id_fields = ('user',)
class UserAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'email', 'is_public', 'deleted')
search_fields = ('id', '^email', '^username')
# A custom field used in search json in zadmin, not django.admin.
search_fields_response = 'email'
inlines = (GroupUserInline,)
readonly_fields = ('id', 'picture_img', 'deleted', 'is_public',
'last_login', 'last_login_ip', 'known_ip_adresses',
'last_known_activity_time', 'ratings_created',
'collections_created', 'addons_created', 'activity',
'abuse_reports_by_this_user',
'abuse_reports_for_this_user')
fieldsets = (
(None, {
'fields': ('id', 'email', 'fxa_id', 'username', 'display_name',
'biography', 'homepage', 'location', 'occupation',
'picture_img'),
}),
('Flags', {
'fields': ('display_collections', 'display_collections_fav',
'deleted', 'is_public'),
}),
('Content', {
'fields': ('addons_created', 'collections_created',
'ratings_created')
}),
('Abuse Reports', {
'fields': ('abuse_reports_by_this_user',
'abuse_reports_for_this_user')
}),
('Admin', {
'fields': ('last_login', 'last_known_activity_time', 'activity',
'last_login_ip', 'known_ip_adresses', 'notes', ),
}),
)
actions = ['ban_action']
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urlpatterns = super(UserAdmin, self).get_urls()
custom_urlpatterns = [
url(r'^(?P<object_id>.+)/ban/$', wrap(self.ban_view),
name='users_userprofile_ban'),
url(r'^(?P<object_id>.+)/delete_picture/$',
wrap(self.delete_picture_view),
name='users_userprofile_delete_picture')
]
return custom_urlpatterns + urlpatterns
def get_actions(self, request):
actions = super(UserAdmin, self).get_actions(request)
if not acl.action_allowed(request, amo.permissions.USERS_EDIT):
# You need Users:Edit to be able to ban users.
actions.pop('user_ban', None)
return actions
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['can_ban'] = acl.action_allowed(
request, amo.permissions.USERS_EDIT)
return super(UserAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)
def delete_model(self, request, obj):
# Deleting a user through the admin also deletes related content
# produced by that user.
ActivityLog.create(amo.LOG.ADMIN_USER_ANONYMIZED, obj)
obj.delete_or_disable_related_content(delete=True)
obj.delete()
def save_model(self, request, obj, form, change):
changes = {k: (form.initial.get(k), form.cleaned_data.get(k))
for k in form.changed_data}
ActivityLog.create(amo.LOG.ADMIN_USER_EDITED, obj, details=changes)
obj.save()
def ban_view(self, request, object_id, extra_context=None):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404()
if not acl.action_allowed(request, amo.permissions.USERS_EDIT):
return HttpResponseForbidden()
ActivityLog.create(amo.LOG.ADMIN_USER_BANNED, obj)
obj.ban_and_disable_related_content()
self.message_user(
request, ugettext('The user "%(user)s" has been banned.' %
{'user': force_text(obj)}))
return HttpResponseRedirect('../')
def delete_picture_view(self, request, object_id, extra_context=None):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404()
if not acl.action_allowed(request, amo.permissions.USERS_EDIT):
return HttpResponseForbidden()
ActivityLog.create(amo.LOG.ADMIN_USER_PICTURE_DELETED, obj)
obj.delete_picture()
self.message_user(
request, ugettext(
'The picture belonging to user "%(user)s" has been deleted.' %
{'user': force_text(obj)}))
return HttpResponseRedirect('../')
def ban_action(self, request, qs):
users = []
for obj in qs:
ActivityLog.create(amo.LOG.ADMIN_USER_BANNED, obj)
obj.ban_and_disable_related_content()
users.append(force_text(obj))
self.message_user(
request, ugettext('The users "%(users)s" have been banned.' %
{'users': u', '.join(users)}))
ban_action.short_description = _('Ban selected users')
def picture_img(self, obj):
return format_html(u'<img src="{}" />', obj.picture_url)
picture_img.short_description = _(u'Profile Photo')
def known_ip_adresses(self, obj):
ip_adresses = set(Rating.objects.filter(user=obj)
.values_list('ip_address', flat=True)
.order_by().distinct())
ip_adresses.add(obj.last_login_ip)
contents = format_html_join(
'', "<li>{}</li>", ((ip,) for ip in ip_adresses))
return format_html('<ul>{}</ul>', contents)
def last_known_activity_time(self, obj):
from django.contrib.admin.utils import display_for_value
# We sort by -created by default, so first() gives us the last one, or
# None.
return display_for_value(UserLog.objects.filter(
user=obj).values_list('created', flat=True).first())
def related_content_link(self, obj, related_class, related_field,
related_manager='objects'):
url = 'admin:{}_{}_changelist'.format(
related_class._meta.app_label, related_class._meta.model_name)
queryset = getattr(related_class, related_manager).filter(
**{related_field: obj})
return format_html(
'<a href="{}?{}={}">{}</a>',
reverse(url), related_field, obj.pk, queryset.count())
def collections_created(self, obj):
return self.related_content_link(obj, Collection, 'author')
collections_created.short_description = _('Collections')
def addons_created(self, obj):
return self.related_content_link(obj, Addon, 'authors',
related_manager='unfiltered')
addons_created.short_description = _('Addons')
def ratings_created(self, obj):
return self.related_content_link(obj, Rating, 'user')
ratings_created.short_description = _('Ratings')
def activity(self, obj):
return self.related_content_link(obj, ActivityLog, 'user')
activity.short_description = _('Activity Logs')
def abuse_reports_by_this_user(self, obj):
return self.related_content_link(obj, AbuseReport, 'reporter')
def abuse_reports_for_this_user(self, obj):
return self.related_content_link(obj, AbuseReport, 'user')
class DeniedModelAdmin(admin.ModelAdmin):
def add_view(self, request, form_url='', extra_context=None):
"""Override the default admin add view for bulk add."""
form = self.model_add_form()
if request.method == 'POST':
form = self.model_add_form(request.POST)
if form.is_valid():
inserted = 0
duplicates = 0
for x in form.cleaned_data[self.add_form_field].splitlines():
# check with the cache
if self.deny_list_model.blocked(x):
duplicates += 1
continue
try:
self.deny_list_model.objects.create(
**{self.model_field: x.lower()})
inserted += 1
except IntegrityError:
# although unlikely, someone else could have added
# the same value.
# note: unless we manage the transactions manually,
# we do lose a primary id here.
duplicates += 1
msg = '%s new values added to the deny list.' % (inserted)
if duplicates:
msg += ' %s duplicates were ignored.' % (duplicates)
messages.success(request, msg)
form = self.model_add_form()
return render(request, self.template_path, {'form': form})
class DeniedNameAdmin(DeniedModelAdmin):
list_display = search_fields = ('name',)
deny_list_model = DeniedName
model_field = 'name'
model_add_form = forms.DeniedNameAddForm
add_form_field = 'names'
template_path = 'users/admin/denied_name/add.html'
admin.site.register(UserProfile, UserAdmin)
admin.site.register(DeniedName, DeniedNameAdmin)
| {
"repo_name": "lavish205/olympia",
"path": "src/olympia/users/admin.py",
"copies": "1",
"size": "10510",
"license": "bsd-3-clause",
"hash": -8100239799642982000,
"line_mean": 39.2681992337,
"line_max": 79,
"alpha_frac": 0.5870599429,
"autogenerated": false,
"ratio": 4.067337461300309,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5154397404200309,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.admin.utils import unquote
from django.urls import reverse
from django.db.utils import IntegrityError
from django.http import (
Http404, HttpResponseForbidden, HttpResponseNotAllowed,
HttpResponseRedirect)
from django.utils.encoding import force_text
from django.utils.html import format_html, format_html_join
from django.utils.translation import ugettext, ugettext_lazy as _
from olympia import amo
from olympia.abuse.models import AbuseReport
from olympia.access import acl
from olympia.activity.models import ActivityLog, UserLog
from olympia.addons.models import Addon
from olympia.amo.utils import render
from olympia.bandwagon.models import Collection
from olympia.ratings.models import Rating
from . import forms
from .models import DeniedName, GroupUser, UserProfile
class GroupUserInline(admin.TabularInline):
model = GroupUser
raw_id_fields = ('user',)
class UserAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'email', 'is_public', 'deleted')
search_fields = ('id', '^email', '^username')
# A custom field used in search json in zadmin, not django.admin.
search_fields_response = 'email'
inlines = (GroupUserInline,)
readonly_fields = ('id', 'picture_img', 'deleted', 'is_public',
'last_login', 'last_login_ip', 'known_ip_adresses',
'last_known_activity_time', 'ratings_created',
'collections_created', 'addons_created', 'activity',
'abuse_reports_by_this_user',
'abuse_reports_for_this_user')
fieldsets = (
(None, {
'fields': ('id', 'email', 'fxa_id', 'username', 'display_name',
'biography', 'homepage', 'location', 'occupation',
'picture_img'),
}),
('Flags', {
'fields': ('display_collections', 'deleted', 'is_public'),
}),
('Content', {
'fields': ('addons_created', 'collections_created',
'ratings_created')
}),
('Abuse Reports', {
'fields': ('abuse_reports_by_this_user',
'abuse_reports_for_this_user')
}),
('Admin', {
'fields': ('last_login', 'last_known_activity_time', 'activity',
'last_login_ip', 'known_ip_adresses', 'notes', ),
}),
)
actions = ['ban_action']
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urlpatterns = super(UserAdmin, self).get_urls()
custom_urlpatterns = [
url(r'^(?P<object_id>.+)/ban/$', wrap(self.ban_view),
name='users_userprofile_ban'),
url(r'^(?P<object_id>.+)/delete_picture/$',
wrap(self.delete_picture_view),
name='users_userprofile_delete_picture')
]
return custom_urlpatterns + urlpatterns
def get_actions(self, request):
actions = super(UserAdmin, self).get_actions(request)
if not acl.action_allowed(request, amo.permissions.USERS_EDIT):
# You need Users:Edit to be able to ban users.
actions.pop('user_ban', None)
return actions
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['can_ban'] = acl.action_allowed(
request, amo.permissions.USERS_EDIT)
return super(UserAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)
def delete_model(self, request, obj):
# Deleting a user through the admin also deletes related content
# produced by that user.
ActivityLog.create(amo.LOG.ADMIN_USER_ANONYMIZED, obj)
obj.delete_or_disable_related_content(delete=True)
obj.delete()
def save_model(self, request, obj, form, change):
changes = {k: (form.initial.get(k), form.cleaned_data.get(k))
for k in form.changed_data}
ActivityLog.create(amo.LOG.ADMIN_USER_EDITED, obj, details=changes)
obj.save()
def ban_view(self, request, object_id, extra_context=None):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404()
if not acl.action_allowed(request, amo.permissions.USERS_EDIT):
return HttpResponseForbidden()
ActivityLog.create(amo.LOG.ADMIN_USER_BANNED, obj)
obj.ban_and_disable_related_content()
kw = {'user': force_text(obj)}
self.message_user(
request, ugettext('The user "%(user)s" has been banned.' % kw))
return HttpResponseRedirect('../')
def delete_picture_view(self, request, object_id, extra_context=None):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404()
if not acl.action_allowed(request, amo.permissions.USERS_EDIT):
return HttpResponseForbidden()
ActivityLog.create(amo.LOG.ADMIN_USER_PICTURE_DELETED, obj)
obj.delete_picture()
kw = {'user': force_text(obj)}
self.message_user(
request, ugettext(
'The picture belonging to user "%(user)s" has been deleted.' %
kw))
return HttpResponseRedirect('../')
def ban_action(self, request, qs):
users = []
for obj in qs:
ActivityLog.create(amo.LOG.ADMIN_USER_BANNED, obj)
obj.ban_and_disable_related_content()
users.append(force_text(obj))
kw = {'users': u', '.join(users)}
self.message_user(
request, ugettext('The users "%(users)s" have been banned.' % kw))
ban_action.short_description = _('Ban selected users')
def picture_img(self, obj):
return format_html(u'<img src="{}" />', obj.picture_url)
picture_img.short_description = _(u'Profile Photo')
def known_ip_adresses(self, obj):
ip_adresses = set(Rating.objects.filter(user=obj)
.values_list('ip_address', flat=True)
.order_by().distinct())
ip_adresses.add(obj.last_login_ip)
contents = format_html_join(
'', "<li>{}</li>", ((ip,) for ip in ip_adresses))
return format_html('<ul>{}</ul>', contents)
def last_known_activity_time(self, obj):
from django.contrib.admin.utils import display_for_value
# We sort by -created by default, so first() gives us the last one, or
# None.
user_log = (
UserLog.objects.filter(user=obj)
.values_list('created', flat=True).first())
return display_for_value(user_log, '')
def related_content_link(self, obj, related_class, related_field,
related_manager='objects'):
url = 'admin:{}_{}_changelist'.format(
related_class._meta.app_label, related_class._meta.model_name)
queryset = getattr(related_class, related_manager).filter(
**{related_field: obj})
return format_html(
'<a href="{}?{}={}">{}</a>',
reverse(url), related_field, obj.pk, queryset.count())
def collections_created(self, obj):
return self.related_content_link(obj, Collection, 'author')
collections_created.short_description = _('Collections')
def addons_created(self, obj):
return self.related_content_link(obj, Addon, 'authors',
related_manager='unfiltered')
addons_created.short_description = _('Addons')
def ratings_created(self, obj):
return self.related_content_link(obj, Rating, 'user')
ratings_created.short_description = _('Ratings')
def activity(self, obj):
return self.related_content_link(obj, ActivityLog, 'user')
activity.short_description = _('Activity Logs')
def abuse_reports_by_this_user(self, obj):
return self.related_content_link(obj, AbuseReport, 'reporter')
def abuse_reports_for_this_user(self, obj):
return self.related_content_link(obj, AbuseReport, 'user')
class DeniedModelAdmin(admin.ModelAdmin):
def add_view(self, request, form_url='', extra_context=None):
"""Override the default admin add view for bulk add."""
form = self.model_add_form()
if request.method == 'POST':
form = self.model_add_form(request.POST)
if form.is_valid():
inserted = 0
duplicates = 0
for x in form.cleaned_data[self.add_form_field].splitlines():
# check with the cache
if self.deny_list_model.blocked(x):
duplicates += 1
continue
try:
self.deny_list_model.objects.create(
**{self.model_field: x.lower()})
inserted += 1
except IntegrityError:
# although unlikely, someone else could have added
# the same value.
# note: unless we manage the transactions manually,
# we do lose a primary id here.
duplicates += 1
msg = '%s new values added to the deny list.' % (inserted)
if duplicates:
msg += ' %s duplicates were ignored.' % (duplicates)
messages.success(request, msg)
form = self.model_add_form()
return render(request, self.template_path, {'form': form})
class DeniedNameAdmin(DeniedModelAdmin):
list_display = search_fields = ('name',)
deny_list_model = DeniedName
model_field = 'name'
model_add_form = forms.DeniedNameAddForm
add_form_field = 'names'
template_path = 'users/admin/denied_name/add.html'
admin.site.register(UserProfile, UserAdmin)
admin.site.register(DeniedName, DeniedNameAdmin)
| {
"repo_name": "atiqueahmedziad/addons-server",
"path": "src/olympia/users/admin.py",
"copies": "1",
"size": "10482",
"license": "bsd-3-clause",
"hash": 556859782616394560,
"line_mean": 38.855513308,
"line_max": 79,
"alpha_frac": 0.5879603129,
"autogenerated": false,
"ratio": 4.0361956103195995,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.51241559232196,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.conf.urls import url
from django.contrib import admin
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.admin.options import csrf_protect_m
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse, resolve
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import slugify
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.encoding import force_text
from django.views.decorators.http import require_POST
from .forms import get_movecolumn_form, get_newpagetemplateform, MoveBlockForm
from .models import ContentBlock, Version
from .page import Glitter
from .signals import page_version_published, page_version_saved, page_version_unpublished
from .templates import get_layout
from .utils import duplicate, JSONEncoderForHTML
from .views import render_page
require_post_m = method_decorator(require_POST)
class GlitterPagePublishedFilter(admin.SimpleListFilter):
title = 'published'
parameter_name = 'published'
def lookups(self, request, model_admin):
return (
('1', 'Yes'),
('0', 'No'),
)
def queryset(self, request, queryset):
if self.value() == '1':
return queryset.filter(published=True).exclude(current_version=None)
if self.value() == '0':
return queryset.filter(published=True, current_version__isnull=True)
class GlitterAdminMixin(object):
list_filter = (GlitterPagePublishedFilter,)
glitter_render = None
def is_published(self, obj):
return obj.published and obj.current_version_id is not None
is_published.boolean = True
is_published.short_description = 'Published'
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
urlpatterns = [
# Start a page with a brand new template
url(r'^(?P<object_id>\d+)/template/$',
wrap(self.page_template_view),
name='%s_%s_template' % info),
# Redirect a user to view the latest appropriate page
url(r'^(?P<object_id>\d+)/redirect/$',
wrap(self.page_redirect_view),
name='%s_%s_redirect' % info),
# View and edit
url(r'^editor/view/(?P<version_id>\d+)/$',
wrap(self.page_version_view),
name='%s_%s_version' % info),
url(r'^editor/edit/(?P<version_id>\d+)/$',
wrap(self.page_edit_view),
name='%s_%s_edit' % info),
# Change template
url(r'^editor/changetemplate/(?P<version_id>\d+)/$',
wrap(self.page_changetemplate_view),
name='%s_%s_changetemplate' % info),
# Save, publish, discard
url(r'^edit/page/(?P<version_id>\d+)/save/$',
wrap(self.page_save_view),
name='%s_%s_save' % info),
url(r'^edit/page/(?P<version_id>\d+)/publish/$',
wrap(self.page_publish_view),
name='%s_%s_publish' % info),
url(r'^edit/page/(?P<version_id>\d+)/unpublish/$',
wrap(self.page_unpublish_view),
name='%s_%s_unpublish' % info),
url(r'^edit/page/(?P<version_id>\d+)/discard/$',
wrap(self.page_discard_view),
name='%s_%s_discard' % info),
# Block editing/updating/moving
url(r'^edit/block/del/(?P<contentblock_id>\d+)/$',
wrap(self.page_block_delete_view),
name='%s_%s_block_delete' % info),
url(r'^edit/block/move/(?P<contentblock_id>\d+)/$',
wrap(self.page_block_move_view),
name='%s_%s_block_move' % info),
url(r'^edit/block/column/(?P<contentblock_id>\d+)/$',
wrap(self.page_block_column_view),
name='%s_%s_block_column' % info),
] + super().get_urls()
return urlpatterns
def has_edit_permission(self, request, obj=None, version=None):
"""
Returns a boolean if the user in the request has edit permission for the object.
Can also be passed a version object to check if the user has permission to edit a version
of the object (if they own it).
"""
# Has the edit permission for this object type
permission_name = '{}.edit_{}'.format(self.opts.app_label, self.opts.model_name)
has_permission = request.user.has_perm(permission_name)
if obj is not None and has_permission is False:
has_permission = request.user.has_perm(permission_name, obj=obj)
if has_permission and version is not None:
# Version must not be saved, and must belong to this user
if version.version_number or version.owner != request.user:
has_permission = False
return has_permission
def has_publish_permission(self, request, obj=None):
"""
Returns a boolean if the user in the request has publish permission for the object.
"""
permission_name = '{}.publish_{}'.format(self.opts.app_label, self.opts.model_name)
has_permission = request.user.has_perm(permission_name)
if obj is not None and has_permission is False:
has_permission = request.user.has_perm(permission_name, obj=obj)
return has_permission
def response_add(self, request, obj, *args, **kwargs):
if '_saveandedit' in request.POST:
return self.page_redirect(request, obj)
else:
return super().response_add(request, obj, *args, **kwargs)
def response_change(self, request, obj, *args, **kwargs):
if '_saveandedit' in request.POST:
return self.page_redirect(request, obj)
else:
return super().response_change(request, obj, *args, **kwargs)
def duplicate_content(self, current_version, new_version):
for content_block in current_version.contentblock_set.all():
content_object = None
if content_block.content_object:
content_object = duplicate(content_block.content_object)
content_object.save()
# Copy the content block
new_content_block = content_block
new_content_block.id = None
new_content_block.obj_version = new_version
if content_object:
new_content_block.content_object = content_object
new_content_block.save()
if content_object:
# Point the block back to the ContentBlock
content_object.content_block = new_content_block
content_object.save()
@csrf_protect_m
@transaction.atomic
def page_template_view(self, request, object_id):
obj = get_object_or_404(self.model, id=object_id)
if not self.has_edit_permission(request, obj):
raise PermissionDenied
NewPageTemplateForm = get_newpagetemplateform(model=self.model)
form = NewPageTemplateForm(request.POST or None)
if form.is_valid():
version = form.save(commit=False)
version.content_type = self.content_type
version.object_id = obj.id
version.owner = request.user
version.save()
opts = self.opts.app_label, self.opts.model_name
return HttpResponseRedirect(reverse('admin:%s_%s_version' % opts, kwargs={
'version_id': version.id,
}))
return TemplateResponse(request, 'admin/glitter/new_template.html', {
'form': form,
})
def page_redirect(self, request, obj):
opts = self.opts.app_label, self.opts.model_name
if not self.has_edit_permission(request, obj):
raise PermissionDenied
# Redirect a user to the published page if it has one
if obj.current_version:
return HttpResponseRedirect(obj.get_absolute_url())
# Otherwise we'll go for the latest version a user has access to
try:
version = Version.objects.filter(
content_type=ContentType.objects.get_for_model(obj), object_id=obj.id).exclude(
~Q(owner=request.user), version_number__isnull=True)[0]
return HttpResponseRedirect(reverse('admin:%s_%s_version' % opts, kwargs={
'version_id': version.id,
}))
except IndexError:
pass
# Last resort is getting the user to create a new page with a new template
return HttpResponseRedirect(reverse('admin:%s_%s_template' % opts, kwargs={
'object_id': obj.id,
}))
def page_redirect_view(self, request, object_id):
page = get_object_or_404(self.model, id=object_id)
return self.page_redirect(request, page)
def page_version_view(self, request, version_id):
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_edit_permission(request, obj):
raise PermissionDenied
# Deny other users from viewing an unsaved version
if not version.version_number and version.owner != request.user:
raise PermissionDenied
if not self.glitter_render:
func, args, kwargs = resolve(obj.get_absolute_url())
kwargs['edit_mode'] = False
kwargs['version'] = version
response = func(request, *args, **kwargs)
return response
else:
return render_page(request, obj, version)
@property
def content_type(self):
return ContentType.objects.get_for_model(self.model)
def version_queryset(self):
return Version.objects.filter(content_type=self.content_type)
def contentblock_queryset(self):
return ContentBlock.objects.filter(obj_version__content_type=self.content_type)
@csrf_protect_m
@transaction.atomic
def page_edit_view(self, request, version_id):
opts = self.opts.app_label, self.opts.model_name
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_edit_permission(request, obj):
raise PermissionDenied
# Deny other users from viewing an unsaved version
if not version.version_number and version.owner != request.user:
raise PermissionDenied
# POST request to initiate
if request.method == 'POST':
# No need to copy a version if they're still editing it
if not version.version_number:
return HttpResponseRedirect(reverse('admin:%s_%s_edit' % opts, kwargs={
'version_id': version_id,
}))
# Create a copy of this version for the user
new_version = Version.objects.create(
content_type=self.content_type,
object_id=obj.id,
template_name=version.template_name,
owner=request.user
)
self.duplicate_content(version, new_version)
return HttpResponseRedirect(reverse('admin:%s_%s_edit' % opts, kwargs={
'version_id': new_version.id,
}))
# Redirect to view if the version is already saved
if version.version_number:
return HttpResponseRedirect(reverse('admin:%s_%s_version' % opts, kwargs={
'version_id': version_id,
}))
if not self.glitter_render:
request = request
func, args, kwargs = resolve(obj.get_absolute_url())
kwargs['edit_mode'] = True
kwargs['version'] = version
response = func(request, *args, **kwargs)
return response
else:
return render_page(request, obj, version, edit=True)
@csrf_protect_m
@transaction.atomic
def page_changetemplate_view(self, request, version_id):
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_edit_permission(request, obj):
raise PermissionDenied
# Can't change a saved version
if version.version_number:
raise PermissionDenied
old_template = get_layout(template_name=version.template_name)
NewPageTemplateForm = get_newpagetemplateform(model=self.model)
form = NewPageTemplateForm(request.POST, instance=version)
# Deny other users from viewing an unsaved version
if not version.version_number and version.owner != request.user:
raise PermissionDenied
if form.is_valid():
version = form.save()
new_template = get_layout(template_name=version.template_name)
# If any columns don't exist in the new template, default them to the first column
for i in old_template._meta.columns:
if i not in new_template._meta.columns:
# Find the first column to put this content in - sadly this is currently the
# first column alphabetically for consistency. In future this will be the first
# column defined (the most important one).
new_column = sorted(new_template._meta.columns.keys())[0]
# Find the last block in the new first column
last_block = ContentBlock.objects.filter(
obj_version=version, column=new_column).last()
if last_block is not None:
next_position = last_block.position + 1
else:
next_position = 1
# Append to the first column
for content in ContentBlock.objects.filter(obj_version=version, column=i):
content.column = new_column
content.position = next_position
content.save()
next_position += 1
opts = self.opts.app_label, self.opts.model_name
return HttpResponseRedirect(reverse('admin:%s_%s_edit' % opts, kwargs={
'version_id': version_id,
}))
@csrf_protect_m
@require_post_m
@transaction.atomic
def page_save_view(self, request, version_id):
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_edit_permission(request, obj):
raise PermissionDenied
# Deny other users from saving a users version
if version.owner != request.user:
raise PermissionDenied
# No need for errors, save anything and only update unsaved versions
if not version.version_number:
version.generate_version()
version.save()
page_version_saved.send(
sender=obj.__class__,
obj=obj,
version=version,
user=request.user)
opts = self.opts.app_label, self.opts.model_name
return HttpResponseRedirect(reverse('admin:%s_%s_version' % opts, kwargs={
'version_id': version_id,
}))
@csrf_protect_m
@require_post_m
@transaction.atomic
def page_publish_view(self, request, version_id):
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_publish_permission(request, obj):
raise PermissionDenied
# Deny other users from publishing an unsaved version
if not version.version_number and version.owner != request.user:
raise PermissionDenied
# Repeated publish - ignore
if obj.current_version == version:
return HttpResponseRedirect(obj.get_absolute_url())
# Save the page if it isn't already
if not version.version_number:
version.generate_version()
version.save()
page_version_saved.send(
sender=obj.__class__,
obj=obj,
version=version,
publish=True,
user=request.user)
# Publish!
previous_version = obj.current_version
obj.current_version = version
obj.save()
page_version_published.send(
sender=obj.__class__,
obj=obj,
version=version,
previous_version=previous_version,
user=request.user)
message = 'Published version %d' % (version.version_number,)
LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=self.content_type.pk,
object_id=obj.id,
object_repr=force_text(obj),
action_flag=CHANGE,
change_message=message
)
return HttpResponseRedirect(obj.get_absolute_url())
@csrf_protect_m
@require_post_m
@transaction.atomic
def page_unpublish_view(self, request, version_id):
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_publish_permission(request, obj):
raise PermissionDenied
# Not the current version? Just ignore the action and view the page again
if obj.current_version == version:
obj.current_version = None
message = 'Unpublished page'
page_version_unpublished.send(
sender=obj.__class__,
obj=obj,
version=version,
user=request.user)
obj.save()
LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=self.content_type.pk,
object_id=obj.id,
object_repr=force_text(obj),
action_flag=CHANGE,
change_message=message
)
opts = self.opts.app_label, self.opts.model_name
return HttpResponseRedirect(reverse('admin:%s_%s_version' % opts, kwargs={
'version_id': version.id,
}))
@csrf_protect_m
@transaction.atomic
def page_discard_view(self, request, version_id):
version = get_object_or_404(self.version_queryset().select_related(), id=version_id)
obj = version.content_object
if not self.has_edit_permission(request, obj, version=version):
raise PermissionDenied
request.current_app = self.admin_site.name
template = 'admin/glitter/version_discard.html'
context = None
# POST request to initiate
if request.method == 'POST':
# Remove all blocks
for i in version.contentblock_set.all():
i.delete()
version.delete()
template = 'admin/glitter/version_discarded.html'
context = {'obj': obj,
'opts': self.model._meta}
return TemplateResponse(request, template, context)
@csrf_protect_m
@transaction.atomic
def page_block_delete_view(self, request, contentblock_id):
content_block = get_object_or_404(self.contentblock_queryset(), id=contentblock_id)
block = content_block.content_object
version = content_block.obj_version
obj = version.content_object
if not self.has_edit_permission(request, obj, version=version):
raise PermissionDenied
request.current_app = self.admin_site.name
if request.POST:
# Save variables for use after deletion
column = content_block.column
# Delete the block
content_block.delete()
# Block not always exists.
if block:
block.delete()
# Render the updated column as a JSON object
glitter = Glitter(version, request=request)
columns = glitter.render(edit_mode=True, rerender=True)
rendered_json = JSONEncoderForHTML().encode({
'content': columns[column],
})
template = 'admin/glitter/update_column.html'
context = {'column': slugify(column),
'rendered_json': rendered_json}
return TemplateResponse(request, template, context)
template = 'admin/glitter/block_delete.html'
context = {'content_block': block}
return TemplateResponse(request, template, context)
@csrf_protect_m
@transaction.atomic
def page_block_move_view(self, request, contentblock_id):
content_block = get_object_or_404(self.contentblock_queryset(), id=contentblock_id)
version = content_block.obj_version
obj = version.content_object
if not self.has_edit_permission(request, obj, version=version):
raise PermissionDenied
form = MoveBlockForm(request.POST)
response_dict = {}
if form.is_valid():
move = form.cleaned_data['move']
if move == MoveBlockForm.MOVE_UP or move == MoveBlockForm.MOVE_DOWN:
# Move up/down involve swapping block positions
try:
if move == MoveBlockForm.MOVE_UP:
other_block = ContentBlock.objects.filter(
obj_version=version,
column=content_block.column,
position__lt=content_block.position).order_by('-position')[0]
else:
other_block = ContentBlock.objects.filter(
obj_version=version,
column=content_block.column,
position__gt=content_block.position)[0]
old_position = content_block.position
new_position = other_block.position
# Temporarily unset other_block's position
other_block.position = None
other_block.save()
# Now set the appropriate positions
content_block.position = new_position
content_block.save()
other_block.position = old_position
other_block.save()
except IndexError:
# User tried to move a block too far
pass
else:
if move == MoveBlockForm.MOVE_TOP:
# Move to top requires setting the position to one less than the first
other_block = ContentBlock.objects.filter(
obj_version=version, column=content_block.column)[0]
# This could be the first block
if content_block != other_block:
content_block.position = other_block.position - 1
content_block.save()
else:
# Move bottom requires setting the position to one greater than the last
other_block = ContentBlock.objects.filter(
obj_version=version,
column=content_block.column).order_by('-position')[0]
# This could be the last block
if content_block != other_block:
content_block.position = other_block.position + 1
content_block.save()
response_dict['column'] = slugify(content_block.column)
glitter = Glitter(version, request=request)
columns = glitter.render(edit_mode=True, rerender=True)
response_dict['content'] = columns[content_block.column]
return JsonResponse(response_dict)
@csrf_protect_m
@transaction.atomic
def page_block_column_view(self, request, contentblock_id):
content_block = get_object_or_404(self.contentblock_queryset(), id=contentblock_id)
version = content_block.obj_version
obj = version.content_object
if not self.has_edit_permission(request, obj, version=version):
raise PermissionDenied
# Need to build a form which only has viable column moves
template_obj = get_layout(template_name=version.template_name)
column_choices = list(template_obj._meta.columns)
column_choices.remove(content_block.column)
MoveColumnForm = get_movecolumn_form(column_choices)
form = MoveColumnForm(request.POST)
response_dict = {}
if form.is_valid():
move = form.cleaned_data['move']
source_column = content_block.column
content_block.column = move
# Find the last block of the column we're moving to
if ContentBlock.objects.filter(
obj_version=version, column=move
).order_by('-position').exists():
last_block = ContentBlock.objects.filter(
obj_version=version, column=move
).order_by('-position')[0]
content_block.position = last_block.position + 1
content_block.save()
# Setup the page that can render both updated columns
glitter = Glitter(version, request=request)
columns = glitter.render(edit_mode=True, rerender=True)
# Old column needs rendering again
response_dict['source_column'] = slugify(source_column)
response_dict['source_content'] = columns[source_column]
# Now render the destination column
response_dict['dest_column'] = slugify(content_block.column)
response_dict['dest_content'] = columns[content_block.column]
return JsonResponse(response_dict)
| {
"repo_name": "developersociety/django-glitter",
"path": "glitter/admin.py",
"copies": "2",
"size": "26519",
"license": "bsd-3-clause",
"hash": 5279434001459174000,
"line_mean": 37.1020114943,
"line_max": 99,
"alpha_frac": 0.5887099815,
"autogenerated": false,
"ratio": 4.389109566368752,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5977819547868752,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.conf.urls import url
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from mptt.admin import MPTTModelAdmin
from treenav import models as treenav
from treenav.forms import GenericInlineMenuItemForm, MenuItemForm, MenuItemInlineForm
class GenericMenuItemInline(GenericStackedInline):
"""
Add this inline to your admin class to support editing related menu items
from that model's admin page.
"""
extra = 0
max_num = 1
model = treenav.MenuItem
form = GenericInlineMenuItemForm
class SubMenuItemInline(admin.TabularInline):
model = treenav.MenuItem
extra = 1
form = MenuItemInlineForm
prepopulated_fields = {"slug": ("label",)}
class MenuItemAdmin(MPTTModelAdmin):
change_list_template = "admin/treenav/menuitem/change_list.html"
list_display = (
"slug",
"label",
"parent",
"link",
"href_link",
"order",
"is_enabled",
)
list_filter = ("parent", "is_enabled")
prepopulated_fields = {"slug": ("label",)}
inlines = (SubMenuItemInline,)
fieldsets = (
(None, {"fields": ("parent", "label", "slug", "order", "is_enabled")}),
(
"URL",
{
"fields": ("link", ("content_type", "object_id")),
"description": "The URL for this menu item, which can be a "
"fully qualified URL, an absolute URL, a named "
"URL, a path to a Django view, a regular "
"expression, or a generic relation to a model that "
"supports get_absolute_url()",
},
),
)
list_editable = ("label",)
form = MenuItemForm
def href_link(self, obj):
return format_html(
'<a href="{}">{}</a>', mark_safe(obj.href), mark_safe(obj.href)
)
href_link.short_description = "HREF"
def get_urls(self):
urls = super().get_urls()
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urls = [
url(
r"^refresh-hrefs/$",
wrap(self.refresh_hrefs),
name="treenav_refresh_hrefs",
),
url(r"^clean-cache/$", wrap(self.clean_cache), name="treenav_clean_cache"),
url(
r"^rebuild-tree/$", wrap(self.rebuild_tree), name="treenav_rebuild_tree"
),
] + urls
return urls
def refresh_hrefs(self, request):
"""
Refresh all the cached menu item HREFs in the database.
"""
for item in treenav.MenuItem.objects.all():
item.save() # refreshes the HREF
self.message_user(request, _("Menu item HREFs refreshed successfully."))
info = self.model._meta.app_label, self.model._meta.model_name
changelist_url = reverse(
"admin:%s_%s_changelist" % info, current_app=self.admin_site.name
)
return redirect(changelist_url)
def clean_cache(self, request):
"""
Remove all MenuItems from Cache.
"""
treenav.delete_cache()
self.message_user(request, _("Cache menuitem cache cleaned successfully."))
info = self.model._meta.app_label, self.model._meta.model_name
changelist_url = reverse(
"admin:%s_%s_changelist" % info, current_app=self.admin_site.name
)
return redirect(changelist_url)
def rebuild_tree(self, request):
"""
Rebuilds the tree and clears the cache.
"""
self.model.objects.rebuild()
self.message_user(request, _("Menu Tree Rebuilt."))
return self.clean_cache(request)
def save_related(self, request, form, formsets, change):
"""
Rebuilds the tree after saving items related to parent.
"""
super().save_related(request, form, formsets, change)
self.model.objects.rebuild()
admin.site.register(treenav.MenuItem, MenuItemAdmin)
| {
"repo_name": "caktus/django-treenav",
"path": "treenav/admin.py",
"copies": "1",
"size": "4390",
"license": "bsd-3-clause",
"hash": -6568072371633322000,
"line_mean": 31.0437956204,
"line_max": 88,
"alpha_frac": 0.5981776765,
"autogenerated": false,
"ratio": 4.012797074954296,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5110974751454296,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib.admin import AdminSite
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
class LibyaAdminSite(AdminSite):
"""Custom AdminSite that restricts entry to superusers only."""
def has_permission(self, request):
"""Require superuser AND staff status to view the admin."""
return request.user.is_active and request.user.is_staff and request.user.is_superuser
def admin_view(self, view, cacheable=False):
"""
Override superclass admin_view to provide our own auth flow.
Specifically:
* Return 403 if authenticated and has_permission returns False
* Redirect to login if not authenticated
"""
def inner(request, *args, **kwargs):
if not self.has_permission(request):
if request.path == reverse('admin:logout', current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
# Inner import to prevent django.contrib.admin (app) from
# importing django.contrib.auth.models.User (unrelated model).
from django.contrib.auth.views import redirect_to_login
# Begin overriden portion here
if not request.user.is_authenticated:
return redirect_to_login(
request.get_full_path(),
reverse('admin:login', current_app=self.name)
)
else:
return HttpResponseForbidden(_('Permission Denied.'))
# End overriden portion
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
admin_site = LibyaAdminSite(name='admin')
| {
"repo_name": "SmartElect/SmartElect",
"path": "libya_elections/admin_site.py",
"copies": "1",
"size": "2346",
"license": "apache-2.0",
"hash": -6720717207076935000,
"line_mean": 43.2641509434,
"line_max": 93,
"alpha_frac": 0.6355498721,
"autogenerated": false,
"ratio": 4.710843373493976,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004280469932721653,
"num_lines": 53
} |
from functools import update_wrapper
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseForbidden
from django.views.decorators.csrf import csrf_protect
class DummyUser(AnonymousUser):
def has_module_perms(self, app_label):
return app_label == 'chamber_of_deputies'
def has_perm(self, permission, obj=None):
return permission == 'chamber_of_deputies.change_reimbursement'
class PublicAdminSite(AdminSite):
site_title = 'Dashboard'
site_header = 'Jarbas Dashboard'
index_title = 'Jarbas'
def __init__(self):
super().__init__('dashboard')
self._actions, self._global_actions = {}, {}
@staticmethod
def valid_url(url):
forbidden = (
'auth',
'login',
'logout',
'password',
'add',
'delete',
)
return all(
label not in url.pattern.regex.pattern for label in forbidden)
@property
def urls(self):
urls = (url for url in self.get_urls() if self.valid_url(url))
return list(urls), 'admin', self.name
def has_permission(self, request):
return request.method == 'GET'
def admin_view(self, view, cacheable=False):
def inner(request, *args, **kwargs):
request.user = DummyUser()
if not self.has_permission(request):
return HttpResponseForbidden()
return view(request, *args, **kwargs)
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
public_admin = PublicAdminSite()
| {
"repo_name": "datasciencebr/serenata-de-amor",
"path": "jarbas/public_admin/sites.py",
"copies": "1",
"size": "1713",
"license": "mit",
"hash": 6798495746509033000,
"line_mean": 27.0819672131,
"line_max": 74,
"alpha_frac": 0.6158785756,
"autogenerated": false,
"ratio": 4.0117096018735365,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5127588177473537,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib.admin.utils import label_for_field
class CSVMixin(object):
"""
Adds a CSV export action to an admin view.
"""
change_list_template = "admin/change_list_csv.html"
# This is the maximum number of records that will be written.
# Exporting massive numbers of records should be done asynchronously.
csv_record_limit = None
csv_fields = []
csv_headers = {}
def get_csv_fields(self, request):
return self.csv_fields or self.list_display
def get_urls(self):
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
opts = self.model._meta
urlname = '{0.app_label}_{0.model_name}_csvdownload'.format(opts)
urlpatterns = [
url('^csv/$', wrap(self.csv_export), name=urlname)
]
return urlpatterns + super(CSVMixin, self).get_urls()
def get_csv_filename(self, request):
return unicode(self.model._meta.verbose_name_plural)
def changelist_view(self, request, extra_context=None):
context = {
'querystring': request.GET.urlencode()
}
context.update(extra_context or {})
return super(CSVMixin, self).changelist_view(request, context)
def csv_header_for_field(self, field_name):
if self.headers.get(field_name):
return self.headers[field_name]
return label_for_field(field_name, self.model, self)
def csv_export(self, request, *args, **kwargs):
import csv
from django.http import HttpResponse
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = (
'attachment; filename={0}.csv'.format(
self.get_csv_filename(request)))
fields = list(self.get_csv_fields(request))
writer = csv.DictWriter(response, fields)
# Write header row.
headers = dict((f, self.csv_header_for_field(f)) for f in fields)
writer.writerow(headers)
# Get the queryset using the changelist
cl_response = self.changelist_view(request)
cl = cl_response.context_data.get('cl')
queryset = cl.get_queryset(request)
# Write records.
if self.csv_record_limit:
queryset = queryset[:self.csv_record_limit]
for r in queryset:
data = {}
for name in fields:
if hasattr(r, name):
data[name] = getattr(r, name)
elif hasattr(self, name):
data[name] = getattr(self, name)(r)
else:
raise ValueError('Unknown field: {}'.format(name))
if callable(data[name]):
data[name] = data[name]()
writer.writerow(data)
return response
csv_export.short_description = \
'Exported selected %(verbose_name_plural)s as CSV'
| {
"repo_name": "bendavis78/django-admin-csv",
"path": "admin_csv/admin.py",
"copies": "1",
"size": "3085",
"license": "mit",
"hash": -4460531629514944000,
"line_mean": 32.9010989011,
"line_max": 73,
"alpha_frac": 0.5938411669,
"autogenerated": false,
"ratio": 4.113333333333333,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 91
} |
from functools import update_wrapper
from django.contrib import admin, messages
from django.contrib.admin import helpers
from django.contrib.admin.options import IS_POPUP_VAR
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from .fields import AccountField
from .forms import AccountCreationForm
from .models import Account
from .provider_pool import providers
from .views import OAuthCallback, OAuthRedirect
from .widgets import AccountRawIdWidget
try:
from urlparse import parse_qsl
except ImportError:
from urllib.parse import parse_qsl
try:
from django.contrib.admin.utils import unquote
except ImportError:
from django.contrib.admin.util import unquote
"""
Piggyback off admin.autodiscover() to discover providers
"""
providers.discover_providers()
PRESERVED_FILTERS_SESSION_KEY = '_preserved_filters'
class AccountAdmin(admin.ModelAdmin):
actions = None
change_form_template = 'admin/connected_accounts/account/change_form.html'
readonly_fields = ('avatar', 'uid', 'provider', 'profile_url',
'oauth_token', 'oauth_token_secret', 'user',
'expires_at', 'date_added', 'last_login', )
list_display = ('avatar', '__str__', 'provider', )
list_display_links = ('__str__', )
fieldsets = (
(None, {
'fields': ('avatar', 'provider', 'uid', 'profile_url', )
}),
(None, {
'fields': ('oauth_token', 'oauth_token_secret', )
}),
(None, {
'fields': ('date_added', 'last_login', 'expires_at', 'user', )
}),
)
class Media:
css = {
'all': (
'css/connected_accounts/admin/connected_accounts.css',
)
}
def get_urls(self):
"""
Add the export view to urls.
"""
urls = super(AccountAdmin, self).get_urls()
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.opts.app_label, self.opts.model_name
extra_urls = [
url(r'^login/(?P<provider>(\w|-)+)/$',
wrap(OAuthRedirect.as_view()), name='%s_%s_login' % info),
url(r'^callback/(?P<provider>(\w|-)+)/$',
wrap(OAuthCallback.as_view()), name='%s_%s_callback' % info),
url(r'^(.+)/json/$', wrap(self.json_view), name='%s_%s_json' % info),
]
return extra_urls + urls
def add_view(self, request, form_url='', extra_context=None):
if not self.has_add_permission(request):
raise PermissionDenied
data = None
changelist_filters = request.GET.get('_changelist_filters')
if request.method == 'GET' and changelist_filters is not None:
changelist_filters = dict(parse_qsl(changelist_filters))
if 'provider' in changelist_filters:
data = {
'provider': changelist_filters['provider']
}
form = AccountCreationForm(data=request.POST if request.method == 'POST' else data)
if form.is_valid():
info = self.model._meta.app_label, self.model._meta.model_name
preserved_filters = self.get_preserved_filters(request)
request.session[PRESERVED_FILTERS_SESSION_KEY] = preserved_filters
redirect_url = reverse('admin:%s_%s_login' % info,
kwargs={'provider': form.cleaned_data['provider']})
return redirect(redirect_url)
fieldsets = (
(None, {
'fields': ('provider', )
}),
)
adminForm = helpers.AdminForm(form, list(fieldsets), {}, model_admin=self)
media = self.media + adminForm.media
context = dict(
adminform=adminForm,
is_popup=IS_POPUP_VAR in request.GET,
media=media,
errors=helpers.AdminErrorList(form, ()),
preserved_filters=self.get_preserved_filters(request),
)
context.update(extra_context or {})
return self.render_change_form(request, context, add=True, change=False, form_url=form_url)
def json_view(self, request, object_id):
obj = self.get_object(request, unquote(object_id))
return HttpResponse(content=obj.to_json(), content_type='application/json')
def response_change(self, request, obj):
opts = self.model._meta
preserved_filters = self.get_preserved_filters(request)
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
if '_reset_data' in request.POST:
if obj.is_expired:
obj.refresh_access_token()
provider = obj.get_provider()
profile_data = provider.get_profile_data(obj.raw_token)
if profile_data is None:
msg = _('Could not retrieve profile data for the %(name)s "%(obj)s" ') % msg_dict
self.message_user(request, msg, messages.ERROR)
else:
obj.extra_data = provider.extract_extra_data(profile_data)
obj.save()
msg = _('The %(name)s "%(obj)s" was updated successfully.') % msg_dict
self.message_user(request, msg, messages.SUCCESS)
redirect_url = request.path
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
return super(AccountAdmin, self).response_change(request, obj)
def avatar(self, obj):
return render_to_string(
'admin/connected_accounts/account/includes/changelist_avatar.html', {
'avatar_url': obj.get_avatar_url(),
})
avatar.allow_tags = True
avatar.short_description = _('Avatar')
def profile_url(self, obj):
if obj.get_profile_url():
return '<a href="{0}" target="_blank">{0}</a>'.format(obj.get_profile_url())
return '—'
profile_url.allow_tags = True
profile_url.short_description = _('Profile URL')
admin.site.register(Account, AccountAdmin)
class ConnectedAccountAdminMixin(object):
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
db = kwargs.get('using')
if isinstance(db_field, AccountField):
self.raw_id_fields = self.raw_id_fields + (db_field.name, )
kwargs['widget'] = AccountRawIdWidget(
db_field.rel, self.admin_site, using=db)
return db_field.formfield(**kwargs)
return super(ConnectedAccountAdminMixin, self).formfield_for_foreignkey(
db_field, request, **kwargs)
| {
"repo_name": "mishbahr/django-connected",
"path": "connected_accounts/admin.py",
"copies": "1",
"size": "7227",
"license": "bsd-3-clause",
"hash": 3580559709167696400,
"line_mean": 35.3165829146,
"line_max": 99,
"alpha_frac": 0.6063373461,
"autogenerated": false,
"ratio": 4.057832678270635,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5164170024370635,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib import admin
from django.contrib.admin.apps import AdminConfig
from django.core.exceptions import ImproperlyConfigured
class WineAdminSite(admin.AdminSite):
def get_urls(self):
"""
Most of this is copy/pasted from AdminSite's get_urls method. I needed
to skip over registering some of the URLs so I could move the "wine"
models to the top level URL. That is:
* Wine is at `/`
* Winery is at `/winery`
Any subsequent models registered in the wine app will have the raised
URL level.
"""
from django.conf.urls import url, include
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
wrapper.admin_site = self
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^list/$', wrap(self.index), name='list'),
url(r'^login/$', self.login, name='login'),
url(r'^logout/$', wrap(self.logout), name='logout'),
url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
name='view_on_site'),
]
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
for model, model_admin in self._registry.items():
# Skip over wine for now, we want to register it on the bottom of
# the URL patterns.
if model._meta.app_label == "wine":
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
continue
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
# If there were ModelAdmins registered, we should have a list of app
# labels for which we need to allow access to the app_index view,
if valid_app_labels:
regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
urlpatterns += [
url(regex, wrap(self.app_index), name='app_list'),
]
# Patch the wine models in.
wine_urls = []
for model, model_admin in self._registry.items():
if model._meta.app_label != "wine":
continue
urlre = r'^%s/' % model._meta.model_name
# Wines get top billing!
if model._meta.model_name == "wine":
# The first URL in the model_admin list is the changelist view.
# We can grab it and change its name to pop in the admin. Since
# it gets pushed onto the list last, it will never be resolved
# but it will fix the "Home" links.
urlre = r'^'
changelist_view = model_admin.urls[0]
changelist_view.name = "index"
wine_urls += [
url(urlre, include(model_admin.urls)),
changelist_view
]
else:
urlpatterns += [
url(urlre, include(model_admin.urls)),
]
# We need to ensure wine is last so everything else gets resolved
# first.
if wine_urls:
urlpatterns += wine_urls
return urlpatterns
class WineAdminAppConfig(AdminConfig):
def ready(self):
from django.contrib import admin
from django.contrib.admin import sites
custom_site = WineAdminSite()
admin.site = custom_site
sites.site = custom_site
super(WineAdminAppConfig, self).ready()
| {
"repo_name": "ctbarna/cellar",
"path": "app/app/admin.py",
"copies": "1",
"size": "4610",
"license": "mit",
"hash": 5289644225446258000,
"line_mean": 38.7413793103,
"line_max": 109,
"alpha_frac": 0.5704989154,
"autogenerated": false,
"ratio": 4.213893967093236,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5284392882493236,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib import admin
from django.core.urlresolvers import RegexURLPattern
class InvalidAdmin(RuntimeError):
pass
def make_admin_class(name, urls, app_label, dont_register=False,
site=admin.site):
label = app_label
required_name = "%s_%s_changelist" % (app_label, name.lower())
for url in urls:
if getattr(url, 'name', None) == required_name:
break
else:
raise InvalidAdmin(
"You must have an url with the name %r otherwise the admin "
"will fail to reverse it." % required_name
)
class _meta:
abstract = False
app_label = label
module_name = name.lower()
verbose_name_plural = name
verbose_name = name
model_name = name.lower()
object_name = name
swapped = False
model_class = type(name, (object,), {'_meta': _meta})
class admin_class(admin.ModelAdmin):
def has_add_permission(*args):
return False
def has_change_permission(*args):
return True
def has_delete_permission(*args):
return False
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
return [ # they are already prefixed
RegexURLPattern(
str(url.regex.pattern),
wrap(url.callback),
url.default_args,
url.name
)
if isinstance(url, RegexURLPattern)
else url
for url in urls
]
@classmethod
def register(cls):
site.register((model_class,), cls)
if not dont_register:
admin_class.register()
return admin_class
| {
"repo_name": "ionelmc/django-admin-utils",
"path": "src/admin_utils/mock.py",
"copies": "1",
"size": "1972",
"license": "bsd-2-clause",
"hash": 3842153330228413400,
"line_mean": 27.5797101449,
"line_max": 76,
"alpha_frac": 0.5425963489,
"autogenerated": false,
"ratio": 4.543778801843318,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 69
} |
from functools import update_wrapper
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.db import models
from django.http import HttpResponseRedirect
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Action(models.Model):
name = models.CharField(max_length=50, primary_key=True)
description = models.CharField(max_length=70)
def __str__(self):
return self.name
class ActionAdmin(admin.ModelAdmin):
"""
A ModelAdmin for the Action model that changes the URL of the add_view
to '<app name>/<model name>/!add/'
The Action model has a CharField PK.
"""
list_display = ('name', 'description')
def remove_url(self, name):
"""
Remove all entries named 'name' from the ModelAdmin instance URL
patterns list
"""
return [url for url in super(ActionAdmin, self).get_urls() if url.name != name]
def get_urls(self):
# Add the URL of our custom 'add_view' view to the front of the URLs
# list. Remove the existing one(s) first
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
view_name = '%s_%s_add' % info
return [
url(r'^!add/$', wrap(self.add_view), name=view_name),
] + self.remove_url(view_name)
class Person(models.Model):
name = models.CharField(max_length=20)
class PersonAdmin(admin.ModelAdmin):
def response_post_save_add(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_history', args=[obj.pk]))
def response_post_save_change(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_delete', args=[obj.pk]))
class Car(models.Model):
name = models.CharField(max_length=20)
class CarAdmin(admin.ModelAdmin):
def response_add(self, request, obj, post_url_continue=None):
return super(CarAdmin, self).response_add(
request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk]))
admin.site.register(Action, ActionAdmin)
admin.site.register(Person, PersonAdmin)
admin.site.register(Car, CarAdmin)
| {
"repo_name": "aerophile/django",
"path": "tests/admin_custom_urls/models.py",
"copies": "78",
"size": "2482",
"license": "bsd-3-clause",
"hash": 3287605848313263600,
"line_mean": 29.2682926829,
"line_max": 106,
"alpha_frac": 0.6663980661,
"autogenerated": false,
"ratio": 3.8361669242658425,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00025255403361170396,
"num_lines": 82
} |
from functools import update_wrapper
from django.contrib import admin
from django.db import models
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Action(models.Model):
name = models.CharField(max_length=50, primary_key=True)
description = models.CharField(max_length=70)
def __str__(self):
return self.name
class ActionAdmin(admin.ModelAdmin):
"""
A ModelAdmin for the Action model that changes the URL of the add_view
to '<app name>/<model name>/!add/'
The Action model has a CharField PK.
"""
list_display = ('name', 'description')
def remove_url(self, name):
"""
Remove all entries named 'name' from the ModelAdmin instance URL
patterns list
"""
return [url for url in super(ActionAdmin, self).get_urls() if url.name != name]
def get_urls(self):
# Add the URL of our custom 'add_view' view to the front of the URLs
# list. Remove the existing one(s) first
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
view_name = '%s_%s_add' % info
return [
url(r'^!add/$', wrap(self.add_view), name=view_name),
] + self.remove_url(view_name)
class Person(models.Model):
name = models.CharField(max_length=20)
class PersonAdmin(admin.ModelAdmin):
def response_post_save_add(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_history', args=[obj.pk]))
def response_post_save_change(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_delete', args=[obj.pk]))
class Car(models.Model):
name = models.CharField(max_length=20)
class CarAdmin(admin.ModelAdmin):
def response_add(self, request, obj, post_url_continue=None):
return super(CarAdmin, self).response_add(
request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk]))
site = admin.AdminSite(name='admin_custom_urls')
site.register(Action, ActionAdmin)
site.register(Person, PersonAdmin)
site.register(Car, CarAdmin)
| {
"repo_name": "dfunckt/django",
"path": "tests/admin_custom_urls/models.py",
"copies": "61",
"size": "2500",
"license": "bsd-3-clause",
"hash": 3401256843802053600,
"line_mean": 29.1204819277,
"line_max": 106,
"alpha_frac": 0.6656,
"autogenerated": false,
"ratio": 3.816793893129771,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00024951121392963524,
"num_lines": 83
} |
from functools import update_wrapper
from django.contrib import admin
from django.db import models
from django.http import HttpResponseRedirect
from django.urls import reverse
class Action(models.Model):
name = models.CharField(max_length=50, primary_key=True)
description = models.CharField(max_length=70)
def __str__(self):
return self.name
class ActionAdmin(admin.ModelAdmin):
"""
A ModelAdmin for the Action model that changes the URL of the add_view
to '<app name>/<model name>/!add/'
The Action model has a CharField PK.
"""
list_display = ('name', 'description')
def remove_url(self, name):
"""
Remove all entries named 'name' from the ModelAdmin instance URL
patterns list
"""
return [url for url in super(ActionAdmin, self).get_urls() if url.name != name]
def get_urls(self):
# Add the URL of our custom 'add_view' view to the front of the URLs
# list. Remove the existing one(s) first
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
view_name = '%s_%s_add' % info
return [
url(r'^!add/$', wrap(self.add_view), name=view_name),
] + self.remove_url(view_name)
class Person(models.Model):
name = models.CharField(max_length=20)
class PersonAdmin(admin.ModelAdmin):
def response_post_save_add(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_history', args=[obj.pk]))
def response_post_save_change(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_delete', args=[obj.pk]))
class Car(models.Model):
name = models.CharField(max_length=20)
class CarAdmin(admin.ModelAdmin):
def response_add(self, request, obj, post_url_continue=None):
return super(CarAdmin, self).response_add(
request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk]))
site = admin.AdminSite(name='admin_custom_urls')
site.register(Action, ActionAdmin)
site.register(Person, PersonAdmin)
site.register(Car, CarAdmin)
| {
"repo_name": "twz915/django",
"path": "tests/admin_custom_urls/models.py",
"copies": "2",
"size": "2409",
"license": "bsd-3-clause",
"hash": -4022372780858808300,
"line_mean": 28.7407407407,
"line_max": 106,
"alpha_frac": 0.6587795766,
"autogenerated": false,
"ratio": 3.8177496038034864,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5476529180403487,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib import admin
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Action(models.Model):
name = models.CharField(max_length=50, primary_key=True)
description = models.CharField(max_length=70)
def __str__(self):
return self.name
class ActionAdmin(admin.ModelAdmin):
"""
A ModelAdmin for the Action model that changes the URL of the add_view
to '<app name>/<model name>/!add/'
The Action model has a CharField PK.
"""
list_display = ('name', 'description')
def remove_url(self, name):
"""
Remove all entries named 'name' from the ModelAdmin instance URL
patterns list
"""
return [url for url in super(ActionAdmin, self).get_urls() if url.name != name]
def get_urls(self):
# Add the URL of our custom 'add_view' view to the front of the URLs
# list. Remove the existing one(s) first
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
view_name = '%s_%s_add' % info
return patterns('',
url(r'^!add/$', wrap(self.add_view), name=view_name),
) + self.remove_url(view_name)
admin.site.register(Action, ActionAdmin)
| {
"repo_name": "pjdelport/django",
"path": "tests/regressiontests/admin_custom_urls/models.py",
"copies": "4",
"size": "1557",
"license": "bsd-3-clause",
"hash": -718795340681687700,
"line_mean": 28.9423076923,
"line_max": 87,
"alpha_frac": 0.6384071933,
"autogenerated": false,
"ratio": 3.8925,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6530907193300001,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib import admin
from django.db import models
class Action(models.Model):
name = models.CharField(max_length=50, primary_key=True)
description = models.CharField(max_length=70)
def __unicode__(self):
return self.name
class ActionAdmin(admin.ModelAdmin):
"""
A ModelAdmin for the Action model that changes the URL of the add_view
to '<app name>/<model name>/!add/'
The Action model has a CharField PK.
"""
list_display = ('name', 'description')
def remove_url(self, name):
"""
Remove all entries named 'name' from the ModelAdmin instance URL
patterns list
"""
return [e for e in super(ActionAdmin, self).get_urls() if e.name != name]
def get_urls(self):
# Add the URL of our custom 'add_view' view to the front of the URLs
# list. Remove the existing one(s) first
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
view_name = '%s_%s_add' % info
return patterns('',
url(r'^!add/$', wrap(self.add_view), name=view_name),
) + self.remove_url(view_name)
admin.site.register(Action, ActionAdmin)
| {
"repo_name": "vsajip/django",
"path": "tests/regressiontests/admin_custom_urls/models.py",
"copies": "1",
"size": "1464",
"license": "bsd-3-clause",
"hash": -2644250564117220400,
"line_mean": 28.28,
"line_max": 81,
"alpha_frac": 0.625,
"autogenerated": false,
"ratio": 3.893617021276596,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005469327420546933,
"num_lines": 50
} |
from functools import update_wrapper
from django.contrib import admin
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from .models import RedisServer
from .utils import PY3
from .views import inspect
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
if PY3:
unicode = str
class RedisServerAdmin(admin.ModelAdmin):
class Media:
css = {
'all': ('redisboard/admin.css',)
}
list_display = (
'__unicode__',
'status',
'memory',
'clients',
'details',
'cpu_utilization',
'slowlog',
'tools',
)
list_filter = 'label', 'hostname', 'port'
ordering = ('hostname', 'port')
def slowlog(self, obj):
output = [(float('inf'), 'Total: %d items' % obj.stats['slowlog_len'])]
for log in obj.stats['slowlog']:
command = log['command']
if len(command) > 255:
command = str(command[:252]) + '...'
output.append((
log['duration'],
u'%.1fms: %r' % (log['duration'] / 1000., command),
))
if output:
return mark_safe('<br>'.join(l for _, l in sorted(output, reverse=True)))
else:
return 'n/a'
slowlog.allow_tags = True
slowlog.long_description = _('Slowlog')
def status(self, obj):
return obj.stats['status']
status.long_description = _("Status")
def memory(self, obj):
return obj.stats['memory']
memory.long_description = _("Memory")
def clients(self, obj):
return obj.stats['clients']
clients.long_description = _("Clients")
def tools(self, obj):
return mark_safe('<a href="%s">%s</a>' % (
reverse("admin:redisboard_redisserver_inspect", args=(obj.id,)),
unicode(_("Inspect"))
))
tools.allow_tags = True
tools.long_description = _("Tools")
def details(self, obj):
output = []
brief_details = obj.stats['brief_details']
for k, v in (brief_details.items() if PY3 else brief_details.iteritems()):
output.append('<dt>%s</dt><dd>%s</dd>' % (k, v))
if output:
return mark_safe('<dl class="details">%s</dl>' % ''.join(output))
return 'n/a'
details.allow_tags = True
details.long_description = _("Details")
def cpu_utilization(self, obj):
stats = obj.stats
if stats['status'] != 'UP':
return 'n/a'
data = (
'used_cpu_sys',
'used_cpu_sys_children',
'used_cpu_user',
'used_cpu_user_children',
)
data = dict((k, stats['details'][k]) for k in data)
total_cpu = sum(data.values() if PY3 else data.itervalues())
uptime = stats['details']['uptime_in_seconds']
data['cpu_utilization'] = '%.3f%%' % (total_cpu / uptime if uptime else 0)
data = sorted(data.items())
output = []
for k, v in data:
k = k.replace('_', ' ')
output.append('<dt>%s</dt><dd>%s</dd>' % (k, v))
return mark_safe('<dl class="details">%s</dl>' % ''.join(output))
cpu_utilization.allow_tags = True
cpu_utilization.long_description = _('CPU Utilization')
def get_urls(self):
urlpatterns = super(RedisServerAdmin, self).get_urls()
try:
from django.conf.urls import url
except ImportError:
from django.conf.urls.defaults import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
return [url(r'^(\d+)/inspect/$',
wrap(self.inspect_view),
name='redisboard_redisserver_inspect')
] + urlpatterns
def inspect_view(self, request, server_id):
server = get_object_or_404(RedisServer, id=server_id)
if (
self.has_change_permission(request, server) and
request.user.has_perm('redisboard.can_inspect')
):
return inspect(request, server)
else:
return HttpResponseForbidden("You can't inspect this server.")
admin.site.register(RedisServer, RedisServerAdmin)
| {
"repo_name": "ionelmc/django-redisboard",
"path": "src/redisboard/admin.py",
"copies": "1",
"size": "4493",
"license": "bsd-2-clause",
"hash": 4008793910395599400,
"line_mean": 29.3581081081,
"line_max": 85,
"alpha_frac": 0.560204763,
"autogenerated": false,
"ratio": 3.9343257443082313,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49945305073082313,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.contrib import messages
from django.contrib.admin.options import csrf_protect_m
from django.contrib.admin.utils import model_ngettext, unquote
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.forms import formset_factory
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.translation import ugettext as _
from guardian.shortcuts import assign_perm, get_groups_with_perms, remove_perm
from .actions import update_permissions
from .forms import get_group_permission_form
PERM_PREFIX = 'perm_'
class GrootAdminMixin(object):
change_form_template = 'admin/groot_change_form.html'
actions = [update_permissions]
groot_permissions = ()
def get_urls(self):
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
wrapper.model_admin = self
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
return [
url(r'^(.+)/groot/$', wrap(self.groot_view), name='%s_%s_groot' % info),
] + super(GrootAdminMixin, self).get_urls()
def get_groot_permissions(self, request):
"""
Returns a list of permissions which can be edited as part of the Group Permissions page.
"""
permission_content_type = ContentType.objects.get_for_model(self.model)
permissions = Permission.objects.filter(content_type=permission_content_type)
if self.groot_permissions:
permissions = permissions.filter(codename__in=self.groot_permissions)
return permissions
@csrf_protect_m
@transaction.atomic
def groot_view(self, request, object_id):
# Only allow superusers to edit permissions
if not request.user.is_superuser:
raise PermissionDenied
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
'name': force_text(opts.verbose_name),
'key': escape(object_id),
})
opts = self.model._meta
app_label = opts.app_label
group_list = Group.objects.all()
group_count = group_list.count()
GroupPermissionForm = get_group_permission_form(
model_perms=self.get_groot_permissions(request),
)
GroupPermissionFormSet = formset_factory(
GroupPermissionForm, extra=0, min_num=group_count, validate_min=True,
max_num=group_count)
obj_group_perms = get_groups_with_perms(obj=obj, attach_perms=True)
initial_data = []
for group in group_list:
try:
group_perms = obj_group_perms[group]
except KeyError:
group_perms = []
group_initial = {
'group': group,
}
for perm in group_perms:
field_name = '%s%s' % (PERM_PREFIX, perm)
group_initial[field_name] = True
initial_data.append(group_initial)
formset = GroupPermissionFormSet(request.POST or None, initial=initial_data)
if formset.is_valid():
# The user has confirmed the update
group_count = 0
for form in formset.forms:
# Only act on changed data
if form.has_changed():
group_count += 1
for field in form.changed_data:
group = form.cleaned_data['group']
changed_perm = field.replace(PERM_PREFIX, '', 1)
add_perm = form.cleaned_data[field]
# Change perm action accordingly
if add_perm:
update_perm = assign_perm
else:
update_perm = remove_perm
update_perm(perm=changed_perm, user_or_group=group, obj=obj)
if group_count:
self.message_user(request, _((
'Successfully updated permissions for %(count)d %(groups)s.'
)) % {
'count': group_count,
'groups': model_ngettext(Group, n=group_count),
}, messages.SUCCESS)
else:
self.message_user(request, _('No permissions were updated.'), messages.INFO)
return HttpResponseRedirect(request.path)
context = self.admin_site.each_context(request)
context.update({
'title': _('Group permissions: %s') % force_text(obj),
'object': obj,
'opts': opts,
'formset': formset,
'group_formsets': zip(group_list, formset.forms),
})
request.current_app = self.admin_site.name
template_name = getattr(self, 'group_permissions_template', None) or [
'admin/%s/%s/group_permissions.html' % (app_label, opts.model_name),
'admin/%s/group_permissions.html' % app_label,
'admin/group_permissions.html'
]
# Display the form page
return TemplateResponse(request, template_name, context)
| {
"repo_name": "blancltd/django-groot",
"path": "groot/admin.py",
"copies": "1",
"size": "5709",
"license": "bsd-3-clause",
"hash": 8981822578883504000,
"line_mean": 34.2407407407,
"line_max": 96,
"alpha_frac": 0.5929234542,
"autogenerated": false,
"ratio": 4.358015267175572,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5450938721375572,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.core.urlresolvers import reverse
from django.template.response import TemplateResponse
from django.contrib import admin
from django.contrib.admin.options import csrf_protect_m
from django.contrib.admin.views.main import ChangeList
from django.contrib.admin.util import unquote, quote
from django.conf.urls import url
from . import utility
from django.http import HttpResponse
# Voorlopig: moet op termijn naar util gebracht
import json
new_title_default = "new"
class FancytreeMpttAdmin(admin.ModelAdmin):
tree_auto_open = 1
# tree_load_on_demand = 1
# Geef hier aan of heel de boom geladen moet worden ?
tree_load_on_demand = 10
trigger_save_after_move = False
change_list_template = 'fancytree_mptt/grid_view.html'
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
if not self.has_change_permission(request, None):
raise PermissionDenied()
change_list = self.get_change_list_for_tree(request)
# prepare the context to pass ths information from the server to the client browser
context = dict(
title=change_list.title,
app_label=self.model._meta.app_label,
cl=change_list,
media=self.media,
has_add_permission=self.has_add_permission(request),
tree_auto_open=utility.get_javascript_value(self.tree_auto_open),
tree_json_url=self.get_admin_url('tree_json'),
tree_services_url = self.get_admin_url('change_tree'),
tree_model_name = utility.get_model_name(self.model),
grid_url=self.get_admin_url('grid'),
new_title = new_title_default,
)
if extra_context:
context.update(extra_context)
return TemplateResponse(
request,
'fancytree_mptt/change_list.html',
context
)
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urlpatterns = super(FancytreeMpttAdmin, self).get_urls()
def add_url(regex, url_name, view):
# Prepend url to list so it has preference before 'change' url
urlpatterns.insert(
0,
url(
regex,
wrap(view),
name='%s_%s_%s' % (
self.model._meta.app_label,
utility.get_model_name(self.model),
url_name
)
)
)
add_url(r'^(.+)/move/$', 'move', self.move_view)
add_url(r'^tree_json/$', 'tree_json', self.tree_json_view)
add_url(r'^change_tree/$', 'change_tree', self.tree_service)
add_url(r'^grid/$', 'grid', self.grid_view)
return urlpatterns
@csrf_protect_m
@utility.django_atomic()
def move_view(self, request, object_id):
instance = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, instance):
raise PermissionDenied()
if request.method != 'POST':
raise SuspiciousOperation()
target_id = request.POST['target_id']
position = request.POST['position']
target_instance = self.get_object(request, target_id)
if position == 'before':
instance.move_to(target_instance, 'left')
elif position == 'after':
instance.move_to(target_instance, 'right')
elif position == 'inside':
instance.move_to(target_instance)
else:
raise Exception('Unknown position')
if self.trigger_save_after_move:
instance.save()
return utility.JsonResponse(
dict(success=True)
)
def get_change_list_for_tree(self, request):
kwargs = dict(
request=request,
model=self.model,
list_display=(),
list_display_links=(),
list_filter=(),
date_hierarchy=None,
search_fields=(),
list_select_related=(),
list_per_page=100,
list_editable=(),
model_admin=self,
list_max_show_all=200,
)
return ChangeList(**kwargs)
def get_changelist(self, request, **kwargs):
if utility.get_short_django_version() >= (1, 5):
return super(FancytreeMpttAdmin, self).get_changelist(request, **kwargs)
else:
return FixedChangeList
def get_admin_url(self, name, args=None):
opts = self.model._meta
url_name = 'admin:%s_%s_%s' % (opts.app_label, utility.get_model_name(self.model), name)
return reverse(
url_name,
args=args,
current_app=self.admin_site.name
)
def get_tree_data(self, qs, max_level):
pk_attname = self.model._meta.pk.attname
def handle_create_node(instance, node_info):
pk = quote(getattr(instance, pk_attname))
node_info.update(
url=self.get_admin_url('change', (quote(pk),)),
move_url=self.get_admin_url('move', (quote(pk),))
)
return utility.get_tree_from_queryset(qs, handle_create_node, max_level)
def tree_json_view(self, request):
node_id = request.GET.get('node')
if node_id:
node = self.model.objects.get(id=node_id)
max_level = node.level + 1
else:
max_level = self.tree_load_on_demand
qs = utility.get_tree_queryset(
model=self.model,
node_id=node_id,
selected_node_id=request.GET.get('selected_node'),
max_level=max_level,
)
tree_data = self.get_tree_data(qs, max_level)
return utility.JsonResponse(tree_data)
def grid_view(self, request):
return super(FancytreeMpttAdmin, self).changelist_view(
request,
dict(tree_url=self.get_admin_url('changelist'))
)
def tree_service(self,request):
model = self.model
try:
data = json.loads(request.body)
source_nodes = data['source_nodes']
target_node = data['target_node']
method = data['method']
hitmode = data['hitmode']
new_id = data['new_id']
response = data['response']
if method=="CHANGETITLE":
node_to_change = model.objects.get(pk=target_node['node_id'])
node_to_change.title = target_node['node_title']
node_to_change.save()
return HttpResponse('OK')
elif method=="GETALLNODES":
return
# def get_tree_data(self, qs, max_level):
# pk_attname = self.model._meta.pk.attname
#
# def handle_create_node(instance, node_info):
# pk = quote(getattr(instance, pk_attname))
#
# node_info.update(
# url=self.get_admin_url('change', (quote(pk),)),
# move_url=self.get_admin_url('move', (quote(pk),))
# )
#
# return utility.get_tree_from_queryset(qs, handle_create_node, max_level)
elif method=="PASTE":
node_to_move = model.objects.get(pk=source_nodes[0].get('node_id'))
target_node = model.objects.get(pk=target_node['node_id'])
model.objects.move_node(node_to_move, target_node, position='last-child')
return HttpResponse('OK')
elif method=="DROP":
node_to_move = model.objects.get(pk=source_nodes[0].get('node_id'))
if hitmode == 'over':
target_node = model.objects.get(pk=target_node['node_id'])
model.objects.move_node(node_to_move, target_node, position='first-child')
elif hitmode == 'before':
target_node = model.objects.get(pk=target_node['node_id'])
model.objects.move_node(node_to_move, target_node, position='left')
elif hitmode == 'after':
target_node = model.objects.get(pk=target_node['node_id'])
model.objects.move_node(node_to_move, target_node, position='right')
return HttpResponse('OK')
elif method=="ADD":
target_node = model.objects.get(pk=target_node['node_id'])
new_node = model()
new_node.title= new_title_default
new_node.insert_at(target_node,position='last-child',save=True)
data['new_id']=new_node.id
dataresponse = json.dumps(data)
resp = HttpResponse( dataresponse)
return resp
elif method=="DELETE":
target_node = model.objects.get(pk=target_node['node_id'])
target_node.delete()
dataresponse = json.dumps(data)
resp = HttpResponse( dataresponse)
return resp
elif method=="REBUILD":
#target_node = model.objects.get(pk=target_node['node_id'])
model.objects.rebuild()
dataresponse = json.dumps(data)
resp = HttpResponse( dataresponse)
return resp
except (KeyError):
# Redisplay the poll voting form.
return
else:
return HttpResponse('OK')
def get_admin_url(self, name, args=None):
opts = self.model._meta
url_name = 'admin:%s_%s_%s' % (opts.app_label, utility.get_model_name(self.model), name)
return reverse(
url_name,
args=args,
current_app=self.admin_site.name
)
def get_tree_data(self, qs, max_level):
pk_attname = self.model._meta.pk.attname
def handle_create_node(instance, node_info):
pk = quote(getattr(instance, pk_attname))
node_info.update(
url=self.get_admin_url('change', (quote(pk),)),
move_url=self.get_admin_url('move', (quote(pk),))
)
return utility.get_tree_from_queryset(qs, handle_create_node, max_level)
def tree_json_view(self, request):
node_id = request.GET.get('node')
if node_id:
node = self.model.objects.get(id=node_id)
max_level = node.level + 1
else:
max_level = self.tree_load_on_demand
qs = utility.get_tree_queryset(
model=self.model,
node_id=node_id,
selected_node_id=request.GET.get('selected_node'),
max_level=max_level,
)
tree_data = self.get_tree_data(qs, max_level)
return utility.JsonResponse(tree_data)
def grid_view(self, request):
return super(FancytreeMpttAdmin, self).changelist_view(
request,
dict(tree_url=self.get_admin_url('changelist'))
)
class FixedChangeList(ChangeList):
"""
Fix issue 1: the changelist must have a correct link to the edit page
"""
def url_for_result(self, result):
pk = getattr(result, self.pk_attname)
return reverse(
'admin:%s_%s_change' % (self.opts.app_label, self.opts.module_name),
args=[quote(pk)],
current_app=self.model_admin.admin_site.name
)
| {
"repo_name": "m-libbrecht/django-arboretum",
"path": "arboretum_project/arboretum/admin.py",
"copies": "1",
"size": "11884",
"license": "mit",
"hash": 1603439603294519800,
"line_mean": 29.0860759494,
"line_max": 100,
"alpha_frac": 0.5475429148,
"autogenerated": false,
"ratio": 3.9692718770875084,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002688486337189968,
"num_lines": 395
} |
from functools import update_wrapper
from django import forms, template
from django.forms.formsets import all_valid
from django.forms.models import modelformset_factory
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers
from django.contrib.admin.utils import unquote, flatten_fieldsets, model_format_dict
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
from django.db import models, router
try:
from django.db.models.related import RelatedObject
except ImportError:
from django.db.models.fields.related import ForeignObjectRel as RelatedObject
from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
from django.db.models.sql.constants import QUERY_TERMS
from django.db.models.constants import LOOKUP_SEP
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.utils.decorators import method_decorator
from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils.functional import curry
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.forms.forms import pretty_name
from django_mongoengine.utils import force_text
from django_mongoengine.fields import (DateTimeField, URLField, IntField,
ListField, EmbeddedDocumentField,
ReferenceField, StringField, FileField,
ImageField)
from django_mongoengine.mongo_admin import helpers as mongodb_helpers
from django_mongoengine.mongo_admin.util import RelationWrapper
from django_mongoengine.mongo_admin.helpers import AdminForm
from django_mongoengine.forms.document_options import DocumentMetaWrapper
from django_mongoengine.forms.documents import (
documentform_factory, DocumentForm,
inlineformset_factory, BaseInlineDocumentFormSet)
from django_mongoengine.forms import (MongoDefaultFormFieldGenerator,
save_instance)
HORIZONTAL, VERTICAL = 1, 2
# returns the <ul> class for a given radio_admin field
get_ul_class = lambda x: 'radiolist%s' % (
(x == HORIZONTAL) and ' inline' or ''
)
class IncorrectLookupParameters(Exception):
pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
DateTimeField: {
'form_class': forms.SplitDateTimeField,
'widget': widgets.AdminSplitDateTime
},
#models.DateField: {'widget': widgets.AdminDateWidget},
#models.TimeField: {'widget': widgets.AdminTimeWidget},
URLField: {'widget': widgets.AdminURLFieldWidget},
IntField: {'widget': widgets.AdminIntegerFieldWidget},
ImageField: {'widget': widgets.AdminFileWidget},
FileField: {'widget': widgets.AdminFileWidget},
}
csrf_protect_m = method_decorator(csrf_protect)
def formfield(field, form_class=None, **kwargs):
"""
Returns a django.forms.Field instance for this database Field.
"""
defaults = {'required': field.required, 'label': pretty_name(field.name)}
if field.default is not None:
if callable(field.default):
defaults['initial'] = field.default()
defaults['show_hidden_initial'] = True
else:
defaults['initial'] = field.default
if hasattr(field, 'max_length') and field.choices is None:
defaults['max_length'] = field.max_length
if field.choices is not None:
# Many of the subclass-specific formfield arguments (min_value,
# max_value) don't apply for choice fields, so be sure to only pass
# the values that TypedChoiceField will understand.
for k in kwargs.keys():
if k not in ('coerce', 'empty_value', 'choices', 'required',
'widget', 'label', 'initial', 'help_text',
'error_messages', 'show_hidden_initial'):
del kwargs[k]
defaults.update(kwargs)
if form_class is not None:
return form_class(**defaults)
else:
return MongoDefaultFormFieldGenerator().generate(field, **defaults)
class BaseDocumentAdmin(object):
"""Functionality common to both ModelAdmin and InlineAdmin."""
__metaclass__ = forms.MediaDefiningClass
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = DocumentForm
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfield_overrides = {}
readonly_fields = ()
ordering = None
def __init__(self):
super(BaseDocumentAdmin, self).__init__()
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
request = kwargs.pop("request", None)
# If the field specifies choices, we don't need to look for special
# admin widgets - we just need to use a select widget of some kind.
if db_field.choices is not None:
return self.formfield_for_choice_field(db_field, request, **kwargs)
if isinstance(db_field, ListField) and isinstance(db_field.field, ReferenceField):
return self.formfield_for_manytomany(db_field, request, **kwargs)
# handle RelatedFields
if isinstance(db_field, ReferenceField):
# For non-raw_id fields, wrap the widget with a wrapper that adds
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
form_field = formfield(db_field, **kwargs)
if db_field.name not in self.raw_id_fields:
related_modeladmin = self.admin_site._registry.get(db_field.document_type)
can_add_related = bool(related_modeladmin and
related_modeladmin.has_add_permission(request))
form_field.widget = widgets.RelatedFieldWidgetWrapper(
form_field.widget, RelationWrapper(db_field.document_type), self.admin_site,
can_add_related=can_add_related)
return form_field
if isinstance(db_field, StringField):
if db_field.max_length is None:
kwargs = dict({'widget': widgets.AdminTextareaWidget}, **kwargs)
else:
kwargs = dict({'widget': widgets.AdminTextInputWidget}, **kwargs)
return formfield(db_field, **kwargs)
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[klass], **kwargs)
return formfield(db_field, **kwargs)
# For any other type of field, just call its formfield() method.
return formfield(db_field, **kwargs)
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
"""
Get a form Field for a database Field that has declared choices.
"""
# If the field is named as a radio_field, use a RadioSelect
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank = db_field.blank,
blank_choice=[('', _('None'))]
)
return formfield(db_field, **kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(pretty_name(db_field.name), (db_field.name in self.filter_vertical))
return formfield(db_field, **kwargs)
def _declared_fieldsets(self):
if self.fieldsets:
return self.fieldsets
elif self.fields:
return [(None, {'fields': self.fields})]
return None
declared_fieldsets = property(_declared_fieldsets)
def get_readonly_fields(self, request, obj=None):
return self.readonly_fields
def queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
# override documents object class to filter
qs = self.document.objects()
#qs = self.model._default_manager.get_query_set()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.ordering or () # otherwise we might try to *None, which is bad ;)
if ordering:
qs = qs.order_by(*ordering)
return qs
def lookup_allowed(self, lookup, value):
model = self.model
# Check FKey lookups that are allowed, so that popups produced by
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
# are allowed to work.
for l in model._meta.related_fkey_lookups:
for k, v in widgets.url_params_from_lookup_dict(l).items():
if k == lookup and v == value:
return True
parts = lookup.split(LOOKUP_SEP)
# Last term in lookup is a query term (__exact, __startswith etc)
# This term can be ignored.
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
# Special case -- foo__id__exact and foo__id queries are implied
# if foo has been specificially included in the lookup list; so
# drop __id if it is the last part. However, first we need to find
# the pk attribute name.
pk_attr_name = None
for part in parts[:-1]:
field, _, _, _ = model._meta.get_field_by_name(part)
if hasattr(field, 'rel'):
model = field.rel.to
pk_attr_name = model._meta.pk.name
elif isinstance(field, RelatedObject):
model = field.model
pk_attr_name = model._meta.pk.name
else:
pk_attr_name = None
if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name:
parts.pop()
try:
self.model._meta.get_field_by_name(parts[0])
except FieldDoesNotExist:
# Lookups on non-existants fields are ok, since they're ignored
# later.
return True
else:
if len(parts) == 1:
return True
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy
class DocumentAdmin(BaseDocumentAdmin):
"Encapsulates all admin options and functionality for a given model."
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
# see __init__ for django < 1.4
list_max_show_all = 200
list_per_page = 100
list_editable = ()
search_fields = ()
date_hierarchy = None
save_as = False
save_on_top = False
paginator = Paginator
inlines = []
exclude = []
# Custom templates (designed to be over-ridden in subclasses)
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
# Actions
actions = []
action_form = helpers.ActionForm
actions_on_top = True
actions_on_bottom = False
actions_selection_counter = True
def __init__(self, document, admin_site):
super(DocumentAdmin, self).__init__()
self.model = document
self.document = self.model
self.model._admin_opts = DocumentMetaWrapper(document)
self.model._meta = self.model._admin_opts
self.opts = self.model._admin_opts
self.admin_site = admin_site
self.inline_instances = []
for inline_class in self.inlines:
# all embedded admins are handled by self.get_inline_instances()
if issubclass(inline_class, EmbeddedDocumentAdmin):
continue
inline_instance = inline_class(self.document, self.admin_site)
self.inline_instances.append(inline_instance)
# Without this exclude is weirdly shared between all
# instances derived from DocumentAdmin.
self.exclude = list(self.exclude)
self.get_inline_instances()
# If someone patched their MAX_SHOW_ALL_ALLOWED in django 1.3, we
# get the value here and proceed as normal.
try:
from django.contrib.admin.views.main import MAX_SHOW_ALL_ALLOWED
self.list_max_show_all = MAX_SHOW_ALL_ALLOWED
except ImportError:
pass
from django.conf import settings
self.log = not settings.DATABASES.get('default', {}).get(
'ENGINE', 'django.db.backends.dummy').endswith('dummy')
def get_inline_instances(self):
for f in self.document._fields.itervalues():
if not (isinstance(f, ListField) and isinstance(getattr(f, 'field', None), EmbeddedDocumentField)) and not isinstance(f, EmbeddedDocumentField):
continue
# Should only reach here if there is an embedded document...
if f.name in self.exclude:
continue
document = self.document()
if hasattr(f, 'field') and f.field is not None:
embedded_document = f.field.document_type
elif hasattr(f, 'document_type'):
embedded_document = f.document_type
else:
# For some reason we found an embedded field were either
# the field attribute or the field's document type is None.
# This shouldn't happen, but apparently does happen:
# https://github.com/jschrewe/django-mongoadmin/issues/4
# The solution for now is to ignore that field entirely.
continue
inline_admin = EmbeddedStackedDocumentAdmin
# check if there is an admin for the embedded document in
# self.inlines. If there is, use this, else use default.
for inline_class in self.inlines:
if inline_class.document == embedded_document:
inline_admin = inline_class
inline_instance = inline_admin(f, document, self.admin_site)
# if f is an EmbeddedDocumentField set the maximum allowed form instances to one
if isinstance(f, EmbeddedDocumentField):
inline_instance.max_num = 1
# exclude field from normal form
if f.name not in self.exclude:
self.exclude.append(f.name)
if f.name == 'created_at' and f.name not in self.exclude:
self.exclude.append(f.name)
self.inline_instances.append(inline_instance)
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.opts.app_label, self.opts.module_name
urlpatterns = patterns('',
url(r'^$',
wrap(self.changelist_view),
name='%s_%s_changelist' % info),
url(r'^add/$',
wrap(self.add_view),
name='%s_%s_add' % info),
url(r'^(.+)/history/$',
wrap(self.history_view),
name='%s_%s_history' % info),
url(r'^(.+)/delete/$',
wrap(self.delete_view),
name='%s_%s_delete' % info),
url(r'^(.+)/$',
wrap(self.change_view),
name='%s_%s_change' % info),
)
return urlpatterns
def urls(self):
return self.get_urls()
urls = property(urls)
def _media(self):
from django.conf import settings
js = ['js/core.js', 'js/admin/RelatedObjectLookups.js',
'js/jquery.min.js', 'js/jquery.init.js']
if self.actions is not None:
js.extend(['js/actions.min.js'])
if self.prepopulated_fields:
js.append('js/urlify.js')
js.append('js/prepopulate.min.js')
if self.opts.get_ordered_objects():
js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js'])
return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
media = property(_media)
def has_add_permission(self, request):
"""
Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
def has_change_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission())
def get_model_perms(self, request):
"""
Returns a dict of all perms for this model. This dict has the keys
``add``, ``change``, and ``delete`` mapping to the True/False for each
of those actions.
"""
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
}
def get_fieldsets(self, request, obj=None):
"Hook for specifying fieldsets for the add form."
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(kwargs.get("exclude", []))
exclude.extend(self.get_readonly_fields(request, obj))
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": fields,
"exclude": exclude,
"formfield_callback": curry(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
document = self.document()
return documentform_factory(document, **defaults)
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
"""
from views import DocumentChangeList
return DocumentChangeList
def get_object(self, request, object_id):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.queryset(request)
model = queryset._document
model._admin_opts = DocumentMetaWrapper(model)
try:
object_id = model._admin_opts.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None
def get_changelist_form(self, request, **kwargs):
"""
Returns a Form class for use in the Formset on the changelist page.
"""
defaults = {
"formfield_callback": curry(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return documentform_factory(self.model, **defaults)
def get_changelist_formset(self, request, **kwargs):
"""
Returns a FormSet class for use on the changelist page if list_editable
is used.
"""
defaults = {
"formfield_callback": curry(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelformset_factory(self.model,
self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults)
def get_formsets(self, request, obj=None):
for inline in self.inline_instances:
yield inline.get_formset(request, obj)
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
def log_addition(self, request, object):
"""
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
"""
if not self.log:
return
from django.contrib.admin.models import LogEntry, ADDITION
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = None,
object_id = object.pk,
object_repr = force_text(object),
action_flag = ADDITION
)
def log_change(self, request, object, message):
"""
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
"""
if not self.log:
return
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = None,
object_id = object.pk,
object_repr = force_text(object),
action_flag = CHANGE,
change_message = message
)
def log_deletion(self, request, object, object_repr):
"""
Log that an object will be deleted. Note that this method is called
before the deletion.
The default implementation creates an admin LogEntry object.
"""
if not self.log:
return
from django.contrib.admin.models import LogEntry, DELETION
LogEntry.objects.log_action(
user_id = request.user.id,
content_type_id = None,
object_id = object.pk,
object_repr = object_repr,
action_flag = DELETION
)
def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk))
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is explicitally set to None that means that we don't
# want *any* actions enabled on this page.
from django.contrib.admin.views.main import IS_POPUP_VAR
if self.actions is None or IS_POPUP_VAR in request.GET:
return SortedDict()
actions = []
# Gather actions from the admin site first
for (name, func) in self.admin_site.actions:
description = getattr(func, 'short_description', name.replace('_', ' '))
actions.append((func, name, description))
# Then gather them from the model admin and all parent classes,
# starting with self and working back up.
for klass in self.__class__.mro()[::-1]:
class_actions = getattr(klass, 'actions', [])
# Avoid trying to iterate over None
if not class_actions:
continue
actions.extend([self.get_action(action) for action in class_actions])
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
# Convert the actions into a SortedDict keyed by name
# and sorted by description.
actions = SortedDict([
(name, (func, name, desc))
for func, name, desc in actions
])
return actions
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in self.get_actions(request).itervalues():
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(action):
func = action
action = action.__name__
# Next, look for a method. Grab it off self.__class__ to get an unbound
# method instead of a bound one; this ensures that the calling
# conventions are the same for functions and methods.
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
# Finally, look for a named method on the admin site
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
if hasattr(func, 'short_description'):
description = func.short_description
else:
description = capfirst(action.replace('_', ' '))
return func, action, description
def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display
def get_list_display_links(self, request, list_display):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or not list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(list_display)[:1]
def get_ordering(self, request):
"""
Hook for specifying field ordering.
"""
return self.ordering or () # otherwise we might try to *None, which is bad ;)
def construct_change_message(self, request, form, formsets):
"""
Construct a change message from a changed object.
"""
change_message = []
if form.changed_data:
change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and')))
if formsets:
for formset in formsets:
for added_object in formset.new_objects:
change_message.append(_('Added %(name)s "%(object)s".')
% {'name': force_text(added_object._meta.verbose_name),
'object': force_text(added_object)})
for changed_object, changed_fields in formset.changed_objects:
change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
% {'list': get_text_list(changed_fields, _('and')),
'name': force_text(changed_object._meta.verbose_name),
'object': force_text(changed_object)})
for deleted_object in formset.deleted_objects:
change_message.append(_('Deleted %(name)s "%(object)s".')
% {'name': force_text(deleted_object._meta.verbose_name),
'object': force_text(deleted_object)})
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
def message_user(self, request, message):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
"""
messages.info(request, message)
def save_form(self, request, form, change):
"""
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
"""
return form.save(commit=False)
def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
save_instance(form, obj)
def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
obj.delete()
def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
return formset.save()
def render_change_form(self, request, context, add=False, change=False,
form_url='', obj=None):
opts = self.model._admin_opts
app_label = opts.app_label
ordered_objects = opts.get_ordered_objects()
context.update({
'add': add,
'change': change,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
#'has_absolute_url': hasattr(self.model, 'get_absolute_url'),
'ordered_objects': ordered_objects,
'form_url': mark_safe(form_url),
'opts': opts,
#'content_type_id': ContentType.objects.get_for_model(self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
'root_path': self.admin_site.root_path,
})
form_template = self.change_form_template
if add and self.add_form_template is not None:
form_template = self.add_form_template
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(form_template or [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"admin/%s/change_form.html" % app_label,
"admin/change_form.html"
], context, context_instance=context_instance)
def response_add(self, request, obj, post_url_continue='../%s/'):
"""
Determines the HttpResponse for the add_view stage.
"""
opts = obj._admin_opts
pk_value = obj.pk.__str__()
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
if "_popup" in request.POST:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
# escape() calls force_text.
(escape(pk_value), escapejs(obj)))
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_text(opts.verbose_name)))
return HttpResponseRedirect(request.path)
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
post_url = '../'
else:
post_url = '../../../'
return HttpResponseRedirect(post_url)
def response_change(self, request, obj):
"""
Determines the HttpResponse for the change_view stage.
"""
opts = obj._admin_opts
verbose_name = opts.verbose_name
# Handle proxy models automatically created by .only() or .defer()
#if obj._deferred:
# opts_ = opts.proxy_for_model._meta
# verbose_name = opts_.verbose_name
pk_value = obj.pk.__str__()
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_text(verbose_name), 'obj': force_text(obj)}
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_text(verbose_name), 'obj': obj}
self.message_user(request, msg)
return HttpResponseRedirect("../%s/" % pk_value)
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_text(verbose_name)))
return HttpResponseRedirect("../add/")
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
return HttpResponseRedirect('../')
else:
return HttpResponseRedirect('../../../')
def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func, name, description = self.get_actions(request)[action]
# Get the list of selected PKs. If nothing's selected, we can't
# perform an action on it, so bail. Except we want to perform
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
return None
if not select_across:
# Perform the action only on the selected objects
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
# Actions may return an HttpResponse, which will be used as the
# response from the POST. If not, we'll be a good little HTTP
# citizen and redirect back to the changelist page.
if isinstance(response, HttpResponse):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _("No action selected.")
self.message_user(request, msg)
return None
@csrf_protect_m
def add_view(self, request, form_url='', extra_context=None):
"The 'add' admin view for this model."
model = self.model
opts = model._admin_opts
if not self.has_add_permission(request):
raise PermissionDenied
DocumentForm = self.get_form(request)
formsets = []
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), self.inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if formset.is_valid() and form_validated:
if isinstance(inline, EmbeddedDocumentAdmin):
embedded_object_list = formset.save()
if isinstance(inline.field, ListField):
setattr(new_object, inline.rel_name, embedded_object_list)
elif len(embedded_object_list) > 0:
setattr(new_object, inline.rel_name, embedded_object_list[0])
else:
setattr(new_object, inline.rel_name, None)
else:
formset.save()
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=False)
for formset in formsets:
self.save_formset(request, form, formset, change=False)
self.log_addition(request, new_object)
return self.response_add(request, new_object)
else:
# Prepare the dict of initial data from the request.
# We have to special-case M2Ms as a list of comma-separated PKs.
initial = dict(request.GET.items())
for k in initial:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
form = DocumentForm(initial=initial)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request),
self.inline_instances):
inline.parent_document = self.document()
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=self.model(), prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = AdminForm(form, list(self.get_fieldsets(request)),
self.prepopulated_fields, self.get_readonly_fields(request),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request))
readonly = list(inline.get_readonly_fields(request))
inline_admin_formset = mongodb_helpers.InlineAdminFormSet(inline,
formset, fieldsets, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Add %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'show_delete': False,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'root_path': self.admin_site.root_path,
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url=form_url, add=True)
@csrf_protect_m
def change_view(self, request, object_id, extra_context=None):
"The 'change' admin view for this model."
model = self.model
opts = model._admin_opts
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url='../add/')
DocumentForm = self.get_form(request, obj)
formsets = []
# TODO: Something is wrong if formsets are invalid
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object),
self.inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
if formset.is_valid() and form_validated:
if isinstance(inline, EmbeddedDocumentAdmin):
embedded_object_list = formset.save()
if isinstance(inline.field, ListField):
setattr(new_object, inline.rel_name, embedded_object_list)
elif len(embedded_object_list) > 0:
setattr(new_object, inline.rel_name, embedded_object_list[0])
else:
setattr(new_object, inline.rel_name, None)
else:
formset.save()
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=True)
for formset in formsets:
self.save_formset(request, form, formset, change=True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = DocumentForm(instance=obj)
prefixes = {}
# set the actual parent document on the inline admins
for FormSet, inline in zip(self.get_formsets(request, obj), self.inline_instances):
inline.parent_document = obj
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = AdminForm(form, self.get_fieldsets(request, obj),
self.prepopulated_fields, self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
inline_admin_formset = mongodb_helpers.InlineAdminFormSet(inline, formset,
fieldsets, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'root_path': self.admin_site.root_path,
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"The 'change list' admin view for this model."
from django.contrib.admin.views.main import ERROR_FLAG
app_label = self.opts.app_label
opts = self.opts
if not self.has_change_permission(request, None):
raise PermissionDenied
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
# Check actions to see if any are available on this changelist
actions = self.get_actions(request)
if actions:
# Add the action checkboxes if there are any actions available.
list_display = ['action_checkbox'] + list(list_display)
ChangeList = self.get_changelist(request)
try:
cl = ChangeList(request, self.model, list_display,
list_display_links, self.list_filter, self.date_hierarchy,
self.search_fields, self.list_select_related,
self.list_per_page, self.list_max_show_all, self.list_editable,
self)
except IncorrectLookupParameters:
# Wacky lookup parameters were given, so redirect to the main
# changelist page, without parameters, and pass an 'invalid=1'
# parameter via the query string. If wacky parameters were given
# and the 'invalid=1' parameter was already in the query string,
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET.keys():
return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
# edit. Try to look up an action or confirmation first, but if this
# isn't an action the POST will fall through to the bulk edit check,
# below.
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set())
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
action_failed = True
# Actions with confirmation
if (actions and request.method == 'POST' and
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set())
if response:
return response
else:
action_failed = True
# If we're allowing changelist editing, we need to construct a formset
# for the changelist given all the fields to be edited. Then we'll
# use the formset to validate/process POSTed data.
formset = cl.formset = None
# Handle POSTed bulk-edit data.
if (request.method == "POST" and cl.list_editable and
'_save' in request.POST and not action_failed):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
form.save_m2m()
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if changecount == 1:
name = force_text(opts.verbose_name)
else:
name = force_text(opts.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
'obj': force_text(obj)}
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
# Handle GET -- construct a formset for display.
elif cl.list_editable:
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
# Build the list of media to be used by the formset.
if formset:
media = self.media + formset.media
else:
media = self.media
# Build the action form and populate it with available actions.
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
else:
action_form = None
selection_note_all = ungettext('%(total_count)s selected',
'All %(total_count)s selected', cl.result_count)
context = {
'module_name': force_text(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'is_popup': cl.is_popup,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'root_path': self.admin_site.root_path,
'app_label': app_label,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.change_list_template or [
'admin/%s/%s/change_document_list.html' % (app_label, opts.object_name.lower()),
'admin/%s/change_document_list.html' % app_label,
'admin/change_document_list.html'
], context, context_instance=context_instance)
@csrf_protect_m
def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._admin_opts
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
print "FIXME: Need to delete nested objects."
#(deleted_objects, perms_needed, protected) = get_deleted_objects(
# [obj], opts, request.user, self.admin_site, using)
if request.POST: # The user has already confirmed the deletion.
#if perms_needed:
# raise PermissionDenied
obj_display = force_text(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect("../../../../")
return HttpResponseRedirect("../../")
object_name = force_text(opts.verbose_name)
#if perms_needed or protected:
# title = _("Cannot delete %(name)s") % {"name": object_name}
#else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": obj,
#"deleted_objects": deleted_objects,
#"perms_lacking": perms_needed,
#"protected": protected,
"opts": opts,
"root_path": self.admin_site.root_path,
"app_label": app_label,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, context_instance=context_instance)
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
model = self.model
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(
object_id = object_id,
content_type__id__exact = ContentType.objects.get_for_model(model).id
).select_related().order_by('action_time')
# If no history was found, see whether this object even exists.
obj = get_object_or_404(model, pk=unquote(object_id))
context = {
'title': _('Change history: %s') % force_text(obj),
'action_list': action_list,
'module_name': capfirst(force_text(opts.verbose_name_plural)),
'object': obj,
'root_path': self.admin_site.root_path,
'app_label': app_label,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context, context_instance=context_instance)
class InlineDocumentAdmin(BaseDocumentAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``name`` to specify the attribute name of the ``ForeignKey`` from
``model`` to its parent. This is required if ``model`` has more than one
``ForeignKey`` to its parent.
"""
document = None
fk_name = None
formset = BaseInlineDocumentFormSet
extra = 1
max_num = None
template = None
verbose_name = None
verbose_name_plural = None
can_delete = True
def __init__(self, parent_document, admin_site):
self.admin_site = admin_site
self.parent_document = parent_document
if not hasattr(self.document, '_admin_opts'):
self.document._admin_opts = DocumentMetaWrapper(self.document)
self.opts = self.document._admin_opts
super(InlineDocumentAdmin, self).__init__()
if self.verbose_name is None:
self.verbose_name = self.document._admin_opts.verbose_name
if self.verbose_name_plural is None:
self.verbose_name_plural = self.document._admin_opts.verbose_name_plural
def _media(self):
from django.conf import settings
js = ['js/jquery.min.js', 'js/jquery.init.js', 'js/inlines.min.js']
if self.prepopulated_fields:
js.append('js/urlify.js')
js.append('js/prepopulate.min.js')
if self.filter_vertical or self.filter_horizontal:
js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js'])
return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
media = property(_media)
def get_formset(self, request, obj=None, **kwargs):
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(kwargs.get("exclude", []))
exclude.extend(self.get_readonly_fields(request, obj))
# if exclude is an empty list we use None, since that's the actual
# default
exclude = exclude or None
defaults = {
"form": self.form,
"formset": self.formset,
"fields": fields,
"exclude": exclude,
"formfield_callback": curry(self.formfield_for_dbfield, request=request),
"extra": self.extra,
"max_num": self.max_num,
"can_delete": self.can_delete,
}
defaults.update(kwargs)
return inlineformset_factory(self.document, **defaults)
def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request).form
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
class EmbeddedDocumentAdmin(InlineDocumentAdmin):
def __init__(self, field, parent_document, admin_site):
if hasattr(field, 'field'):
self.document = field.field.document_type
else:
self.document = field.document_type
self.doc_list = getattr(parent_document, field.name)
self.field = field
if not isinstance(self.doc_list, list):
self.doc_list = []
self.rel_name = field.name
self.document._admin_opts = DocumentMetaWrapper(self.document)
if self.verbose_name is None:
self.verbose_name = "Field: %s (Document: %s)" % (capfirst(field.name), self.document._admin_opts.verbose_name)
if self.verbose_name_plural is None:
self.verbose_name_plural = "Field: %s (Document: %s)" % (capfirst(field.name), self.document._admin_opts.verbose_name_plural)
super(EmbeddedDocumentAdmin, self).__init__(parent_document, admin_site)
def queryset(self, request):
if isinstance(self.field, ListField): # list field
self.doc_list = getattr(self.parent_document, self.rel_name)
else: # embedded field
emb_doc = getattr(self.parent_document, self.rel_name)
if emb_doc is None:
self.doc_list = []
else:
self.doc_list = [emb_doc]
return self.doc_list
class StackedDocumentInline(InlineDocumentAdmin):
template = 'admin/edit_inline/stacked.html'
class EmbeddedStackedDocumentAdmin(EmbeddedDocumentAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularDocumentInline(InlineDocumentAdmin):
template = 'admin/edit_inline/tabular.html'
| {
"repo_name": "arpitgoyaiitkgp/django-mongoengine",
"path": "django_mongoengine/mongo_admin/options.py",
"copies": "2",
"size": "65951",
"license": "bsd-3-clause",
"hash": -621703568592160500,
"line_mean": 41.6867313916,
"line_max": 167,
"alpha_frac": 0.5890585435,
"autogenerated": false,
"ratio": 4.342881601475042,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002067649494516671,
"num_lines": 1545
} |
from functools import update_wrapper
from django import http
from django.core.urlresolvers import reverse
from django.utils.functional import wraps
from django.utils.http import urlquote
from django.core.exceptions import ObjectDoesNotExist
from django_reputation.exceptions import ReputationException
from django_reputation.models import Permission, Reputation, ReputationAction
def ReputationRequired(view_func, permission_name):
"""
Checks to determine if the current logged in user has permissions to use
a part of a the site based on permission_name and redirects
to the reputation-required view if the reputation check fails.
@param permission_name
"""
def dec(target, request, *args, **kwargs):
try:
permission = Permission.objects.get(name = permission_name)
except ObjectDoesNotExist:
permission = None
user = request.user
if user.is_authenticated:
if permission and Reputation.objects.reputation_for_user(user).reputation < permission.required_reputation:
return http.HttpResponseRedirect(reverse('reputation-required', args=[permission_name]))
else:
return view_func(target, request, *args, **kwargs)
else:
return http.HttpResponseRedirect(reverse('reputation-required', args=[permission_name]))
return dec
def reputation_required(permission_name):
"""
Checks to determine if the current logged in user has permissions to use
a part of a the site based on permission_name and redirects
to the reputation-required view if the reputation check fails.
@param permission_name
"""
def dec(view_func):
return _ReputationRequired(permission_name, view_func)
return dec
class _ReputationRequired(object):
"""
Checks to determine if the current logged in user has permissions to use
a part of a the site based on permission_name and redirects
to the reputation-required view if the reputation check fails.
"""
def __init__(self, permission_name, view_func):
self.permission_name = permission_name
try:
self.permission = Permission.objects.get(name = permission_name)
except ObjectDoesNotExist:
self.permission = None
self.view_func = view_func
update_wrapper(self, view_func)
def __call__(self, request, *args, **kwargs):
user = request.user
if user.is_authenticated:
if self.permission and Reputation.objects.reputation_for_user(user).reputation < self.permission.required_reputation:
return http.HttpResponseRedirect(reverse('reputation-required', args=[self.permission_name]))
else:
return self.view_func(request, *args, **kwargs)
else:
return http.HttpResponseRedirect(reverse('reputation-required', args=[self.permission_name]))
| {
"repo_name": "stripathi669/django-reputation",
"path": "django_reputation/decorators.py",
"copies": "1",
"size": "2971",
"license": "mit",
"hash": -8761481352056736000,
"line_mean": 40.2777777778,
"line_max": 129,
"alpha_frac": 0.6856277348,
"autogenerated": false,
"ratio": 4.375552282768778,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.016903000578578683,
"num_lines": 72
} |
from functools import update_wrapper
from django import template
from django.contrib import admin
from django.contrib.admin.utils import unquote
from django.core.exceptions import PermissionDenied
from django.core.management import load_command_class
from django.http import Http404
from django.shortcuts import render_to_response
from django.utils.encoding import force_unicode
from django.utils.html import escape
from django.utils.translation import ugettext as _
from ietf.group.models import Group, GroupHistory, GroupEvent, GroupURL, GroupMilestone, Role, RoleHistory, ChangeStateGroupEvent
class RoleInline(admin.TabularInline):
model = Role
raw_id_fields = ["person", "email"]
class GroupURLInline(admin.TabularInline):
model = GroupURL
class GroupAdmin(admin.ModelAdmin):
list_display = ["acronym", "name", "type", "state", "time", "role_list"]
list_display_links = ["acronym", "name"]
list_filter = ["type", "state", "time"]
search_fields = ["acronym", "name"]
ordering = ["name"]
raw_id_fields = ["charter", "parent"]
inlines = [RoleInline, GroupURLInline]
prepopulated_fields = {"acronym": ("name", )}
def role_list(self, obj):
roles = Role.objects.filter(group=obj).order_by("name", "person__name").select_related('person')
res = []
for r in roles:
res.append(u'<a href="../../person/person/%s/">%s</a> (<a href="../../group/role/%s/">%s)' % (r.person.pk, escape(r.person.plain_name()), r.pk, r.name.name))
return ", ".join(res)
role_list.short_description = "Persons"
role_list.allow_tags = True
# SDO reminder
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
urls = patterns('',
url(r'^reminder/$', wrap(self.send_reminder), name='%s_%s_reminder' % info),
url(r'^(.+)/reminder/$', wrap(self.send_one_reminder), name='%s_%s_one_reminder' % info),
)
urls += super(GroupAdmin, self).get_urls()
return urls
def send_reminder(self, request, sdo=None):
opts = self.model._meta
app_label = opts.app_label
output = None
sdo_pk = sdo and sdo.pk or None
if request.method == 'POST' and request.POST.get('send', False):
command = load_command_class('ietf.liaisons', 'remind_update_sdo_list')
output=command.handle(return_output=True, sdo_pk=sdo_pk)
output='\n'.join(output)
context = {
'opts': opts,
'has_change_permission': self.has_change_permission(request),
'app_label': app_label,
'output': output,
'sdo': sdo,
}
return render_to_response('admin/group/group/send_sdo_reminder.html',
context,
context_instance = template.RequestContext(request, current_app=self.admin_site.name),
)
def send_one_reminder(self, request, object_id):
model = self.model
opts = model._meta
try:
obj = self.queryset(request).get(pk=unquote(object_id))
except model.DoesNotExist:
obj = None
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
return self.send_reminder(request, sdo=obj)
admin.site.register(Group, GroupAdmin)
class GroupHistoryAdmin(admin.ModelAdmin):
list_display = ["time", "acronym", "name", "type"]
list_display_links = ["acronym", "name"]
list_filter = ["type"]
search_fields = ["acronym", "name"]
ordering = ["name"]
raw_id_fields = ["group", "parent"]
admin.site.register(GroupHistory, GroupHistoryAdmin)
class GroupMilestoneAdmin(admin.ModelAdmin):
list_display = ["group", "desc", "due", "resolved", "time"]
search_fields = ["group__name", "group__acronym", "desc", "resolved"]
raw_id_fields = ["group", "docs"]
admin.site.register(GroupMilestone, GroupMilestoneAdmin)
class RoleAdmin(admin.ModelAdmin):
list_display = ["name", "person", "email", "group"]
list_display_links = ["name"]
search_fields = ["name__name", "person__name", "email__address"]
list_filter = ["name", "group"]
ordering = ["id"]
raw_id_fields = ["email", "person", "group"]
admin.site.register(Role, RoleAdmin)
admin.site.register(RoleHistory, RoleAdmin)
class GroupEventAdmin(admin.ModelAdmin):
list_display = ["id", "group", "time", "type", "by", ]
search_fields = ["group__name", "group__acronym"]
admin.site.register(GroupEvent, GroupEventAdmin)
class ChangeStateGroupEventAdmin(admin.ModelAdmin):
list_display = ["id", "group", "state", "time", "type", "by", ]
list_filter = ["state", "time", ]
search_fields = ["group__name", "group__acronym"]
admin.site.register(ChangeStateGroupEvent, ChangeStateGroupEventAdmin)
| {
"repo_name": "wpjesus/codematch",
"path": "ietf/group/admin.py",
"copies": "1",
"size": "5331",
"license": "bsd-3-clause",
"hash": -2792154429567996000,
"line_mean": 36.8085106383,
"line_max": 169,
"alpha_frac": 0.6261489402,
"autogenerated": false,
"ratio": 3.611788617886179,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47379375580861793,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.utils.decorators import classonlymethod
class CtrlViewMixin:
def __init__(self, ctrl):
self.ctrl = ctrl
self.init_handler()
super(CtrlViewMixin, self).__init__()
def init_handler(self):
pass
@classonlymethod
def as_view(cls, ctrl, **initkwargs):
"""
unchanged from super method except for the 4 marked lines below
"""
for key in initkwargs: # pragma: no cover
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
# { changed
self = cls(ctrl, **initkwargs)
self.request = ctrl.request = request
self.args = ctrl.args = args
self.kwargs = ctrl.kwargs = kwargs
# }
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def get_context_data(self, **kwargs):
context = super(CtrlViewMixin, self).get_context_data(**kwargs)
context.update(**self.ctrl.update_context())
return context
class CtrlListView(CtrlViewMixin, ListView):
def init_handler(self):
self.ctrl.list_view_init_handler(self)
def get_queryset(self):
return self.ctrl.get_queryset()
def get_detail_url(self, obj):
return self.ctrl.relative_url('details/{}'.format(obj.pk))
class CtrlDetailView(CtrlViewMixin, DetailView):
def init_handler(self):
self.ctrl.detail_view_init_handler(self)
def get_queryset(self):
return self.ctrl.get_queryset()
class CtrlCreateView(CtrlViewMixin, CreateView):
def init_handler(self):
self.ctrl.create_view_init_handler(self)
def form_valid(self, form):
return self.ctrl.create_form_valid(self, form)
class CtrlUpdateView(CtrlViewMixin, UpdateView):
def init_handler(self):
self.ctrl.update_view_init_handler(self)
def form_valid(self, form):
return self.ctrl.update_form_valid(self, form)
def get_queryset(self):
return self.ctrl.get_queryset()
class CtrlDeleteView(CtrlViewMixin, DeleteView):
def init_handler(self):
self.ctrl.delete_view_init_handler(self)
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.ctrl.get_delete_success_url()
self.ctrl.delete_object(self.object)
return redirect(success_url)
def get_queryset(self):
return self.ctrl.get_queryset()
| {
"repo_name": "samuelcolvin/django-crud",
"path": "django_crud/base_views.py",
"copies": "1",
"size": "3452",
"license": "mit",
"hash": -1349403789220051000,
"line_mean": 31.5660377358,
"line_max": 89,
"alpha_frac": 0.6121089224,
"autogenerated": false,
"ratio": 4.04215456674473,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00021987012322953418,
"num_lines": 106
} |
from functools import update_wrapper
from django.utils.decorators import classonlymethod
from django.core.exceptions import ImproperlyConfigured
class BaseEmail(object):
"""
Simple base class for all class-based emails. Implements the basic
structure for constructing an email message and sending it, along with the
`as_callable` method logic.
"""
@property
def email_message_class(self):
raise ImproperlyConfigured('No `email_message_class` provided')
@email_message_class.setter # NOQA
def email_message_class(self, value):
self.__dict__['email_message_class'] = value
return value
def get_email_message_kwargs(self, **kwargs):
return kwargs
def get_email_message_class(self):
return self.email_message_class
def get_email_message(self):
return self.get_email_message_class()(**self.get_email_message_kwargs())
def get_send_kwargs(self, **kwargs):
return kwargs
def send(self):
self.get_email_message().send(**self.get_send_kwargs())
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
@classonlymethod
def as_callable(cls, **initkwargs):
for key in initkwargs:
if not hasattr(cls, key):
raise TypeError("{0}() received an invalid keyword {1!r}. "
"as_callable only accepts arguments that are "
"already attributes of the "
"class.".format(cls.__name__, key))
EmailClass = type("Callable{0}".format(cls.__name__), (cls,), initkwargs)
def callable(*args, **kwargs):
self = EmailClass(*args, **kwargs)
return self.send()
update_wrapper(callable, EmailClass, updated=())
return callable
| {
"repo_name": "pipermerriam/django-emailtools",
"path": "emailtools/cbe/base.py",
"copies": "1",
"size": "1861",
"license": "bsd-2-clause",
"hash": -136471777093743800,
"line_mean": 31.649122807,
"line_max": 81,
"alpha_frac": 0.612573885,
"autogenerated": false,
"ratio": 4.3583138173302105,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00043054036778184543,
"num_lines": 57
} |
from functools import update_wrapper
from django.utils.translation import ugettext_lazy as _
from django.shortcuts import get_object_or_404
from django.http import HttpResponseForbidden
from django.core.urlresolvers import reverse
from django.contrib import admin
from .models import RedisServer
from .views import inspect
class RedisServerAdmin(admin.ModelAdmin):
class Media:
css = {
'all': ('redisboard/admin.css',)
}
list_display = (
'__unicode__', 'status', 'memory', 'clients', 'details', 'tools'
)
list_filter = 'label', 'hostname'
ordering = ('hostname', 'port')
def status(self, obj):
return obj.stats['status']
status.long_description = _("Status")
def memory(self, obj):
return obj.stats['memory']
memory.long_description = _("Memory")
def clients(self, obj):
return obj.stats['clients']
clients.long_description = _("Clients")
def tools(self, obj):
return '<a href="%s">%s</a>' % (
reverse("admin:redisboard_redisserver_inspect", args=(obj.id,)),
unicode(_("Inspect"))
)
tools.allow_tags = True
tools.long_description = _("Tools")
def details(self, obj):
return '<table class="details">%s</table>' % ''.join(
"<tr><td>%s</td><td>%s</td></tr>" % i for i in
obj.stats['brief_details'].items()
)
details.allow_tags = True
details.long_description = _("Details")
def get_urls(self):
urlpatterns = super(RedisServerAdmin, self).get_urls()
try:
from django.conf.urls.defaults import patterns, url
except:
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
return patterns('',
url(r'^(\d+)/inspect/$',
wrap(self.inspect_view),
name='redisboard_redisserver_inspect'),
) + urlpatterns
def inspect_view(self, request, server_id):
server = get_object_or_404(RedisServer, id=server_id)
if self.has_change_permission(request, server) and request.user.has_perm('redisboard.can_inspect'):
return inspect(request, server)
else:
return HttpResponseForbidden("You can't inspect this server.")
admin.site.register(RedisServer, RedisServerAdmin)
| {
"repo_name": "artscoop/django-redisboard",
"path": "src/redisboard/admin.py",
"copies": "1",
"size": "2506",
"license": "bsd-2-clause",
"hash": -6511919495143079000,
"line_mean": 32.4133333333,
"line_max": 107,
"alpha_frac": 0.6073423783,
"autogenerated": false,
"ratio": 4.094771241830065,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002651313778764759,
"num_lines": 75
} |
from functools import update_wrapper
from PIL import Image
from PIL import ImageEnhance
from PIL import ImageFilter
import click
@click.group(chain=True)
def cli():
"""This script processes a bunch of images through pillow in a unix
pipe. One commands feeds into the next.
Example:
\b
imagepipe open -i example01.jpg resize -w 128 display
imagepipe open -i example02.jpg blur save
"""
@cli.resultcallback()
def process_commands(processors):
"""This result callback is invoked with an iterable of all the chained
subcommands. As in this example each subcommand returns a function
we can chain them together to feed one into the other, similar to how
a pipe on unix works.
"""
# Start with an empty iterable.
stream = ()
# Pipe it through all stream processors.
for processor in processors:
stream = processor(stream)
# Evaluate the stream and throw away the items.
for _ in stream:
pass
def processor(f):
"""Helper decorator to rewrite a function so that it returns another
function from it.
"""
def new_func(*args, **kwargs):
def processor(stream):
return f(stream, *args, **kwargs)
return processor
return update_wrapper(new_func, f)
def generator(f):
"""Similar to the :func:`processor` but passes through old values
unchanged and does not pass through the values as parameter.
"""
@processor
def new_func(stream, *args, **kwargs):
yield from stream
yield from f(*args, **kwargs)
return update_wrapper(new_func, f)
def copy_filename(new, old):
new.filename = old.filename
return new
@cli.command("open")
@click.option(
"-i",
"--image",
"images",
type=click.Path(),
multiple=True,
help="The image file to open.",
)
@generator
def open_cmd(images):
"""Loads one or multiple images for processing. The input parameter
can be specified multiple times to load more than one image.
"""
for image in images:
try:
click.echo(f"Opening '{image}'")
if image == "-":
img = Image.open(click.get_binary_stdin())
img.filename = "-"
else:
img = Image.open(image)
yield img
except Exception as e:
click.echo(f"Could not open image '{image}': {e}", err=True)
@cli.command("save")
@click.option(
"--filename",
default="processed-{:04}.png",
type=click.Path(),
help="The format for the filename.",
show_default=True,
)
@processor
def save_cmd(images, filename):
"""Saves all processed images to a series of files."""
for idx, image in enumerate(images):
try:
fn = filename.format(idx + 1)
click.echo(f"Saving '{image.filename}' as '{fn}'")
yield image.save(fn)
except Exception as e:
click.echo(f"Could not save image '{image.filename}': {e}", err=True)
@cli.command("display")
@processor
def display_cmd(images):
"""Opens all images in an image viewer."""
for image in images:
click.echo(f"Displaying '{image.filename}'")
image.show()
yield image
@cli.command("resize")
@click.option("-w", "--width", type=int, help="The new width of the image.")
@click.option("-h", "--height", type=int, help="The new height of the image.")
@processor
def resize_cmd(images, width, height):
"""Resizes an image by fitting it into the box without changing
the aspect ratio.
"""
for image in images:
w, h = (width or image.size[0], height or image.size[1])
click.echo(f"Resizing '{image.filename}' to {w}x{h}")
image.thumbnail((w, h))
yield image
@cli.command("crop")
@click.option(
"-b", "--border", type=int, help="Crop the image from all sides by this amount."
)
@processor
def crop_cmd(images, border):
"""Crops an image from all edges."""
for image in images:
box = [0, 0, image.size[0], image.size[1]]
if border is not None:
for idx, val in enumerate(box):
box[idx] = max(0, val - border)
click.echo(f"Cropping '{image.filename}' by {border}px")
yield copy_filename(image.crop(box), image)
else:
yield image
def convert_rotation(ctx, param, value):
if value is None:
return
value = value.lower()
if value in ("90", "r", "right"):
return (Image.ROTATE_90, 90)
if value in ("180", "-180"):
return (Image.ROTATE_180, 180)
if value in ("-90", "270", "l", "left"):
return (Image.ROTATE_270, 270)
raise click.BadParameter(f"invalid rotation '{value}'")
def convert_flip(ctx, param, value):
if value is None:
return
value = value.lower()
if value in ("lr", "leftright"):
return (Image.FLIP_LEFT_RIGHT, "left to right")
if value in ("tb", "topbottom", "upsidedown", "ud"):
return (Image.FLIP_LEFT_RIGHT, "top to bottom")
raise click.BadParameter(f"invalid flip '{value}'")
@cli.command("transpose")
@click.option(
"-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"
)
@click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]")
@processor
def transpose_cmd(images, rotate, flip):
"""Transposes an image by either rotating or flipping it."""
for image in images:
if rotate is not None:
mode, degrees = rotate
click.echo(f"Rotate '{image.filename}' by {degrees}deg")
image = copy_filename(image.transpose(mode), image)
if flip is not None:
mode, direction = flip
click.echo(f"Flip '{image.filename}' {direction}")
image = copy_filename(image.transpose(mode), image)
yield image
@cli.command("blur")
@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")
@processor
def blur_cmd(images, radius):
"""Applies gaussian blur."""
blur = ImageFilter.GaussianBlur(radius)
for image in images:
click.echo(f"Blurring '{image.filename}' by {radius}px")
yield copy_filename(image.filter(blur), image)
@cli.command("smoothen")
@click.option(
"-i",
"--iterations",
default=1,
show_default=True,
help="How many iterations of the smoothen filter to run.",
)
@processor
def smoothen_cmd(images, iterations):
"""Applies a smoothening filter."""
for image in images:
click.echo(
f"Smoothening {image.filename!r} {iterations}"
f" time{'s' if iterations != 1 else ''}"
)
for _ in range(iterations):
image = copy_filename(image.filter(ImageFilter.BLUR), image)
yield image
@cli.command("emboss")
@processor
def emboss_cmd(images):
"""Embosses an image."""
for image in images:
click.echo(f"Embossing '{image.filename}'")
yield copy_filename(image.filter(ImageFilter.EMBOSS), image)
@cli.command("sharpen")
@click.option(
"-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True
)
@processor
def sharpen_cmd(images, factor):
"""Sharpens an image."""
for image in images:
click.echo(f"Sharpen '{image.filename}' by {factor}")
enhancer = ImageEnhance.Sharpness(image)
yield copy_filename(enhancer.enhance(max(1.0, factor)), image)
@cli.command("paste")
@click.option("-l", "--left", default=0, help="Offset from left.")
@click.option("-r", "--right", default=0, help="Offset from right.")
@processor
def paste_cmd(images, left, right):
"""Pastes the second image on the first image and leaves the rest
unchanged.
"""
imageiter = iter(images)
image = next(imageiter, None)
to_paste = next(imageiter, None)
if to_paste is None:
if image is not None:
yield image
return
click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")
mask = None
if to_paste.mode == "RGBA" or "transparency" in to_paste.info:
mask = to_paste
image.paste(to_paste, (left, right), mask)
image.filename += f"+{to_paste.filename}"
yield image
yield from imageiter
| {
"repo_name": "mitsuhiko/click",
"path": "examples/imagepipe/imagepipe.py",
"copies": "1",
"size": "8256",
"license": "bsd-3-clause",
"hash": -7866162599414959000,
"line_mean": 27.6666666667,
"line_max": 87,
"alpha_frac": 0.6182170543,
"autogenerated": false,
"ratio": 3.6644474034620504,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47826644577620503,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
import django
from django.contrib import admin
from django.contrib.admin import helpers
from django.shortcuts import redirect, render
from django.template import RequestContext
from .forms import OneOffPointAwardForm
from .models import AwardedPointValue, PointValue
class AwardedPointValueAdmin(admin.ModelAdmin):
list_display = ["pk", "reason_display", "target", "points"]
fields = ["target_user", "value", "timestamp"]
def target(self, obj):
if obj.target_user_id:
return obj.target_user
else:
return obj.target_object
def reason_display(self, obj):
if obj.value_id:
return obj.value.key
else:
if obj.reason:
return obj.reason
else:
return None
reason_display.short_description = "reason"
def get_urls(self):
from django.conf.urls import url
urlpatterns = super(AwardedPointValueAdmin, self).get_urls()
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
if django.VERSION < (1, 7):
info = self.model._meta.app_label, self.model._meta.module_name
else:
info = self.model._meta.app_label, self.model._meta.model_name
return [url(
r"^one_off_points/$",
wrap(self.one_off_points),
name="{0}_{1}_one_off_points".format(info[0], info[1])
)] + urlpatterns
def one_off_points(self, request):
if request.method == "POST":
form = OneOffPointAwardForm(request.POST)
if form.is_valid():
form.award()
return redirect("admin:points_awardedpointvalue_changelist")
else:
form = OneOffPointAwardForm()
form = helpers.AdminForm(
form=form,
fieldsets=[(None, {"fields": form.base_fields.keys()})],
prepopulated_fields={},
model_admin=self
)
ctx = {
"opts": self.model._meta,
"form": form,
}
ctx = RequestContext(request, ctx)
return render(request, "pinax/points/one_off_points.html", ctx)
admin.site.register(AwardedPointValue, AwardedPointValueAdmin)
admin.site.register(PointValue)
| {
"repo_name": "pinax/pinax-points",
"path": "pinax/points/admin.py",
"copies": "1",
"size": "2442",
"license": "mit",
"hash": -5099141765679037000,
"line_mean": 30.3076923077,
"line_max": 76,
"alpha_frac": 0.5904995905,
"autogenerated": false,
"ratio": 4.076794657762938,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5167294248262938,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
_CLASS_CACHE_ATTR_NAME = '_class_cached_properties'
_OBJ_CACHE_ATTR_NAME = '_cached_properties'
def class_cached_property(fn):
def _class_cached_property(self):
return _get_property_value(fn, self.__class__, _CLASS_CACHE_ATTR_NAME)
return property(update_wrapper(_class_cached_property, fn))
def cached_property(fn):
def _cached_property(self):
return _get_property_value(fn, self, _OBJ_CACHE_ATTR_NAME)
return property(update_wrapper(_cached_property, fn))
def truthy_cached_property(fn):
def _truthy_cached_property(self):
return _get_property_value(
fn, self, _OBJ_CACHE_ATTR_NAME, cache_false_results=False)
return property(update_wrapper(_truthy_cached_property, fn))
def set_property_cache(obj, name, value):
cache = _get_cache(obj)
cache[name] = value
setattr(obj, _OBJ_CACHE_ATTR_NAME, cache)
def clear_property_cache(obj, name):
cache = _get_cache(obj)
if name in cache:
del cache[name]
def is_property_cached(obj, name):
cache = _get_cache(obj)
return name in cache
def _get_cache(obj, cache_attr_name=_OBJ_CACHE_ATTR_NAME):
return getattr(obj, cache_attr_name, {})
def _update_cache(obj, cache_attr_name, cache_key, result):
cache = _get_cache(obj, cache_attr_name)
cache[cache_key] = result
setattr(obj, cache_attr_name, cache)
def _get_property_value(fn, obj, cache_attr_name, cache_false_results=True):
cache = _get_cache(obj, cache_attr_name)
cache_key = fn.__name__
if cache_key in cache:
return cache[cache_key]
result = fn(obj)
if result or cache_false_results:
_update_cache(obj, cache_attr_name, cache_key, result)
return result
| {
"repo_name": "yola/property-caching",
"path": "property_caching/__init__.py",
"copies": "1",
"size": "1761",
"license": "mit",
"hash": -8547782386653848000,
"line_mean": 26.0923076923,
"line_max": 78,
"alpha_frac": 0.6734809767,
"autogenerated": false,
"ratio": 3.231192660550459,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9404673637250458,
"avg_score": 0,
"num_lines": 65
} |
from functools import update_wrapper
try:
from django.conf.urls import patterns, url
except ImportError:
# Django <= 1.3
from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from mptt.admin import MPTTModelAdmin
from treenav import models as treenav
from treenav.forms import MenuItemForm, MenuItemInlineForm, GenericInlineMenuItemForm
class GenericMenuItemInline(generic.GenericStackedInline):
"""
Add this inline to your admin class to support editing related menu items
from that model's admin page.
"""
extra = 0
max_num = 1
model = treenav.MenuItem
form = GenericInlineMenuItemForm
class SubMenuItemInline(admin.TabularInline):
model = treenav.MenuItem
extra = 1
form = MenuItemInlineForm
prepopulated_fields = {'slug': ('label',)}
class MenuItemAdmin(MPTTModelAdmin):
change_list_template = 'admin/treenav/menuitem/change_list.html'
list_display = (
'slug',
'label',
'parent',
'link',
'href_link',
'order',
'is_enabled',
)
list_filter = ('parent', 'is_enabled')
prepopulated_fields = {'slug': ('label',)}
inlines = (SubMenuItemInline,)
fieldsets = (
(None, {
'fields': ('parent', 'label', 'slug', 'order', 'is_enabled')
}),
('URL', {
'fields': ('link', ('content_type', 'object_id')),
'description': _("""The URL for this menu item, which can be a
fully qualified URL, an absolute URL, a named
URL, a path to a Django view, a regular
expression, or a generic relation to a model that
supports get_absolute_url()""")
}),
)
list_editable = ('label',)
form = MenuItemForm
def href_link(self, obj):
return '<a href="%s">%s</a>' % (obj.href, obj.href)
href_link.short_description = 'HREF'
href_link.allow_tags = True
def get_urls(self):
urls = super(MenuItemAdmin, self).get_urls()
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
urls = patterns('',
url(r'^refresh-hrefs/$', wrap(self.refresh_hrefs), name='treenav_refresh_hrefs'),
url(r'^clean-cache/$', wrap(self.clean_cache), name='treenav_clean_cache'),
) + urls
return urls
def refresh_hrefs(self, request):
"""
Refresh all the cached menu item HREFs in the database.
"""
for item in treenav.MenuItem.objects.all():
item.save() # refreshes the HREF
self.message_user(request, _('Menu item HREFs refreshed successfully.'))
info = self.model._meta.app_label, self.model._meta.module_name
return redirect('admin:%s_%s_changelist' % info)
def clean_cache(self, request):
"""
Remove all MenuItems from Cache.
"""
treenav.delete_cache()
self.message_user(request, _('Cache menuitem cache cleaned successfully.'))
info = self.model._meta.app_label, self.model._meta.module_name
return redirect('admin:%s_%s_changelist' % info)
admin.site.register(treenav.MenuItem, MenuItemAdmin)
| {
"repo_name": "NetstationMurator/django-treenav",
"path": "treenav/admin.py",
"copies": "1",
"size": "3558",
"license": "bsd-3-clause",
"hash": 3058168317499253000,
"line_mean": 33.2115384615,
"line_max": 93,
"alpha_frac": 0.6138279933,
"autogenerated": false,
"ratio": 4.006756756756757,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5120584750056757,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, partial
from django import forms
from django.conf import settings
from django.forms.formsets import all_valid
from django.forms.models import (modelform_factory, modelformset_factory,
inlineformset_factory, BaseInlineFormSet)
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers
from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_format_dict
from django.contrib.admin.templatetags.admin_static import static
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db import models, transaction, router
from django.db.models.constants import LOOKUP_SEP
from django.db.models.related import RelatedObject
from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
from django.db.models.sql.constants import QUERY_TERMS
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.response import SimpleTemplateResponse, TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.utils.encoding import force_text
HORIZONTAL, VERTICAL = 1, 2
# returns the <ul> class for a given radio_admin field
get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
class IncorrectLookupParameters(Exception):
pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
models.DateTimeField: {
'form_class': forms.SplitDateTimeField,
'widget': widgets.AdminSplitDateTime
},
models.DateField: {'widget': widgets.AdminDateWidget},
models.TimeField: {'widget': widgets.AdminTimeWidget},
models.TextField: {'widget': widgets.AdminTextareaWidget},
models.URLField: {'widget': widgets.AdminURLFieldWidget},
models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget},
models.CharField: {'widget': widgets.AdminTextInputWidget},
models.ImageField: {'widget': widgets.AdminFileWidget},
models.FileField: {'widget': widgets.AdminFileWidget},
}
csrf_protect_m = method_decorator(csrf_protect)
class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)):
"""Functionality common to both ModelAdmin and InlineAdmin."""
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = forms.ModelForm
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfield_overrides = {}
readonly_fields = ()
ordering = None
def __init__(self):
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
request = kwargs.pop("request", None)
# If the field specifies choices, we don't need to look for special
# admin widgets - we just need to use a select widget of some kind.
if db_field.choices:
return self.formfield_for_choice_field(db_field, request, **kwargs)
# ForeignKey or ManyToManyFields
if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
# Combine the field kwargs with any options for formfield_overrides.
# Make sure the passed in **kwargs override anything in
# formfield_overrides because **kwargs is more specific, and should
# always win.
if db_field.__class__ in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
# Get the correct formfield.
if isinstance(db_field, models.ForeignKey):
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
elif isinstance(db_field, models.ManyToManyField):
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
# For non-raw_id fields, wrap the widget with a wrapper that adds
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
if formfield and db_field.name not in self.raw_id_fields:
related_modeladmin = self.admin_site._registry.get(
db_field.rel.to)
can_add_related = bool(related_modeladmin and
related_modeladmin.has_add_permission(request))
formfield.widget = widgets.RelatedFieldWidgetWrapper(
formfield.widget, db_field.rel, self.admin_site,
can_add_related=can_add_related)
return formfield
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[klass], **kwargs)
return db_field.formfield(**kwargs)
# For any other type of field, just call its formfield() method.
return db_field.formfield(**kwargs)
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
"""
Get a form Field for a database Field that has declared choices.
"""
# If the field is named as a radio_field, use a RadioSelect
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank = db_field.blank,
blank_choice=[('', _('None'))]
)
return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ForeignKey.
"""
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel,
self.admin_site, using=db)
elif db_field.name in self.radio_fields:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
kwargs['empty_label'] = db_field.blank and _('None') or None
return db_field.formfield(**kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.rel.through._meta.auto_created:
return None
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel,
self.admin_site, using=db)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
return db_field.formfield(**kwargs)
def _declared_fieldsets(self):
if self.fieldsets:
return self.fieldsets
elif self.fields:
return [(None, {'fields': self.fields})]
return None
declared_fieldsets = property(_declared_fieldsets)
def get_ordering(self, request):
"""
Hook for specifying field ordering.
"""
return self.ordering or () # otherwise we might try to *None, which is bad ;)
def get_readonly_fields(self, request, obj=None):
"""
Hook for specifying custom readonly fields.
"""
return self.readonly_fields
def get_prepopulated_fields(self, request, obj=None):
"""
Hook for specifying custom prepopulated fields.
"""
return self.prepopulated_fields
def queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_query_set()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
def lookup_allowed(self, lookup, value):
model = self.model
# Check FKey lookups that are allowed, so that popups produced by
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
# are allowed to work.
for l in model._meta.related_fkey_lookups:
for k, v in widgets.url_params_from_lookup_dict(l).items():
if k == lookup and v == value:
return True
parts = lookup.split(LOOKUP_SEP)
# Last term in lookup is a query term (__exact, __startswith etc)
# This term can be ignored.
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
# Special case -- foo__id__exact and foo__id queries are implied
# if foo has been specificially included in the lookup list; so
# drop __id if it is the last part. However, first we need to find
# the pk attribute name.
rel_name = None
for part in parts[:-1]:
try:
field, _, _, _ = model._meta.get_field_by_name(part)
except FieldDoesNotExist:
# Lookups on non-existants fields are ok, since they're ignored
# later.
return True
if hasattr(field, 'rel'):
model = field.rel.to
rel_name = field.rel.get_related_field().name
elif isinstance(field, RelatedObject):
model = field.model
rel_name = model._meta.pk.name
else:
rel_name = None
if rel_name and len(parts) > 1 and parts[-1] == rel_name:
parts.pop()
if len(parts) == 1:
return True
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy
def has_add_permission(self, request):
"""
Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
def has_change_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission())
class ModelAdmin(BaseModelAdmin):
"Encapsulates all admin options and functionality for a given model."
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
list_per_page = 100
list_max_show_all = 200
list_editable = ()
search_fields = ()
date_hierarchy = None
save_as = False
save_on_top = False
paginator = Paginator
inlines = []
# Custom templates (designed to be over-ridden in subclasses)
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
# Actions
actions = []
action_form = helpers.ActionForm
actions_on_top = True
actions_on_bottom = False
actions_selection_counter = True
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(ModelAdmin, self).__init__()
def get_inline_instances(self, request):
inline_instances = []
for inline_class in self.inlines:
inline = inline_class(self.model, self.admin_site)
if request:
if not (inline.has_add_permission(request) or
inline.has_change_permission(request) or
inline.has_delete_permission(request)):
continue
if not inline.has_add_permission(request):
inline.max_num = 0
inline_instances.append(inline)
return inline_instances
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
urlpatterns = patterns('',
url(r'^$',
wrap(self.changelist_view),
name='%s_%s_changelist' % info),
url(r'^add/$',
wrap(self.add_view),
name='%s_%s_add' % info),
url(r'^(.+)/history/$',
wrap(self.history_view),
name='%s_%s_history' % info),
url(r'^(.+)/delete/$',
wrap(self.delete_view),
name='%s_%s_delete' % info),
url(r'^(.+)/$',
wrap(self.change_view),
name='%s_%s_change' % info),
)
return urlpatterns
def urls(self):
return self.get_urls()
urls = property(urls)
@property
def media(self):
extra = '' if settings.DEBUG else '.min'
js = [
'core.js',
'admin/RelatedObjectLookups.js',
'jquery%s.js' % extra,
'jquery.init.js'
]
if self.actions is not None:
js.append('actions%s.js' % extra)
if self.prepopulated_fields:
js.extend(['urlify.js', 'prepopulate%s.js' % extra])
if self.opts.get_ordered_objects():
js.extend(['getElementsBySelector.js', 'dom-drag.js' , 'admin/ordering.js'])
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def get_model_perms(self, request):
"""
Returns a dict of all perms for this model. This dict has the keys
``add``, ``change``, and ``delete`` mapping to the True/False for each
of those actions.
"""
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
}
def get_fieldsets(self, request, obj=None):
"Hook for specifying fieldsets for the add form."
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
"""
from django.contrib.admin.views.main import ChangeList
return ChangeList
def get_object(self, request, object_id):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None
def get_changelist_form(self, request, **kwargs):
"""
Returns a Form class for use in the Formset on the changelist page.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist_formset(self, request, **kwargs):
"""
Returns a FormSet class for use on the changelist page if list_editable
is used.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelformset_factory(self.model,
self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults)
def get_formsets(self, request, obj=None):
for inline in self.get_inline_instances(request):
yield inline.get_formset(request, obj)
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
def log_addition(self, request, object):
"""
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, ADDITION
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_text(object),
action_flag = ADDITION
)
def log_change(self, request, object, message):
"""
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_text(object),
action_flag = CHANGE,
change_message = message
)
def log_deletion(self, request, object, object_repr):
"""
Log that an object will be deleted. Note that this method is called
before the deletion.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, DELETION
LogEntry.objects.log_action(
user_id = request.user.id,
content_type_id = ContentType.objects.get_for_model(self.model).pk,
object_id = object.pk,
object_repr = object_repr,
action_flag = DELETION
)
def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk))
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is explicitally set to None that means that we don't
# want *any* actions enabled on this page.
from django.contrib.admin.views.main import IS_POPUP_VAR
if self.actions is None or IS_POPUP_VAR in request.GET:
return SortedDict()
actions = []
# Gather actions from the admin site first
for (name, func) in self.admin_site.actions:
description = getattr(func, 'short_description', name.replace('_', ' '))
actions.append((func, name, description))
# Then gather them from the model admin and all parent classes,
# starting with self and working back up.
for klass in self.__class__.mro()[::-1]:
class_actions = getattr(klass, 'actions', [])
# Avoid trying to iterate over None
if not class_actions:
continue
actions.extend([self.get_action(action) for action in class_actions])
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
# Convert the actions into a SortedDict keyed by name.
actions = SortedDict([
(name, (func, name, desc))
for func, name, desc in actions
])
return actions
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in six.itervalues(self.get_actions(request)):
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(action):
func = action
action = action.__name__
# Next, look for a method. Grab it off self.__class__ to get an unbound
# method instead of a bound one; this ensures that the calling
# conventions are the same for functions and methods.
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
# Finally, look for a named method on the admin site
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
if hasattr(func, 'short_description'):
description = func.short_description
else:
description = capfirst(action.replace('_', ' '))
return func, action, description
def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display
def get_list_display_links(self, request, list_display):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or not list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(list_display)[:1]
def construct_change_message(self, request, form, formsets):
"""
Construct a change message from a changed object.
"""
change_message = []
if form.changed_data:
change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and')))
if formsets:
for formset in formsets:
for added_object in formset.new_objects:
change_message.append(_('Added %(name)s "%(object)s".')
% {'name': force_text(added_object._meta.verbose_name),
'object': force_text(added_object)})
for changed_object, changed_fields in formset.changed_objects:
change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
% {'list': get_text_list(changed_fields, _('and')),
'name': force_text(changed_object._meta.verbose_name),
'object': force_text(changed_object)})
for deleted_object in formset.deleted_objects:
change_message.append(_('Deleted %(name)s "%(object)s".')
% {'name': force_text(deleted_object._meta.verbose_name),
'object': force_text(deleted_object)})
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
def message_user(self, request, message):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
"""
messages.info(request, message)
def save_form(self, request, form, change):
"""
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
"""
return form.save(commit=False)
def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
obj.save()
def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
obj.delete()
def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
def save_related(self, request, form, formsets, change):
"""
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.
"""
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change)
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
opts = self.model._meta
app_label = opts.app_label
ordered_objects = opts.get_ordered_objects()
context.update({
'add': add,
'change': change,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
'has_absolute_url': hasattr(self.model, 'get_absolute_url'),
'ordered_objects': ordered_objects,
'form_url': form_url,
'opts': opts,
'content_type_id': ContentType.objects.get_for_model(self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
})
if add and self.add_form_template is not None:
form_template = self.add_form_template
else:
form_template = self.change_form_template
return TemplateResponse(request, form_template or [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"admin/%s/change_form.html" % app_label,
"admin/change_form.html"
], context, current_app=self.admin_site.name)
def response_add(self, request, obj, post_url_continue='../%s/'):
"""
Determines the HttpResponse for the add_view stage.
"""
opts = obj._meta
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
if "_popup" in request.POST:
return HttpResponse(
'<!DOCTYPE html><html><head><title></title></head><body>'
'<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script></body></html>' % \
# escape() calls force_text.
(escape(pk_value), escapejs(obj)))
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_text(opts.verbose_name)))
return HttpResponseRedirect(request.path)
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
post_url = reverse('admin:%s_%s_changelist' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name)
else:
post_url = reverse('admin:index',
current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def response_change(self, request, obj):
"""
Determines the HttpResponse for the change_view stage.
"""
opts = obj._meta
# Handle proxy models automatically created by .only() or .defer().
# Refs #14529
verbose_name = opts.verbose_name
module_name = opts.module_name
if obj._deferred:
opts_ = opts.proxy_for_model._meta
verbose_name = opts_.verbose_name
module_name = opts_.module_name
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_text(verbose_name), 'obj': force_text(obj)}
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_text(verbose_name), 'obj': obj}
self.message_user(request, msg)
return HttpResponseRedirect(reverse('admin:%s_%s_change' %
(opts.app_label, module_name),
args=(pk_value,),
current_app=self.admin_site.name))
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_text(verbose_name)))
return HttpResponseRedirect(reverse('admin:%s_%s_add' %
(opts.app_label, module_name),
current_app=self.admin_site.name))
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
post_url = reverse('admin:%s_%s_changelist' %
(opts.app_label, module_name),
current_app=self.admin_site.name)
else:
post_url = reverse('admin:index',
current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func, name, description = self.get_actions(request)[action]
# Get the list of selected PKs. If nothing's selected, we can't
# perform an action on it, so bail. Except we want to perform
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
return None
if not select_across:
# Perform the action only on the selected objects
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
# Actions may return an HttpResponse, which will be used as the
# response from the POST. If not, we'll be a good little HTTP
# citizen and redirect back to the changelist page.
if isinstance(response, HttpResponse):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _("No action selected.")
self.message_user(request, msg)
return None
@csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
"The 'add' admin view for this model."
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
inline_instances = self.get_inline_instances(request)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, False)
self.save_related(request, form, formsets, False)
self.log_addition(request, new_object)
return self.response_add(request, new_object)
else:
# Prepare the dict of initial data from the request.
# We have to special-case M2Ms as a list of comma-separated PKs.
initial = dict(request.GET.items())
for k in initial:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
form = ModelForm(initial=initial)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=self.model(), prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
self.get_prepopulated_fields(request),
self.get_readonly_fields(request),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request))
readonly = list(inline.get_readonly_fields(request))
prepopulated = dict(inline.get_prepopulated_fields(request))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Add %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'media': media,
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url=form_url, add=True)
@csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, form_url='', extra_context=None):
"The 'change' admin view for this model."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
ModelForm = self.get_form(request, obj)
formsets = []
inline_instances = self.get_inline_instances(request)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, True)
self.save_related(request, form, formsets, True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.get_prepopulated_fields(request, obj),
self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
prepopulated = dict(inline.get_prepopulated_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': media,
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"""
The 'change list' admin view for this model.
"""
from django.contrib.admin.views.main import ERROR_FLAG
opts = self.model._meta
app_label = opts.app_label
if not self.has_change_permission(request, None):
raise PermissionDenied
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
# Check actions to see if any are available on this changelist
actions = self.get_actions(request)
if actions:
# Add the action checkboxes if there are any actions available.
list_display = ['action_checkbox'] + list(list_display)
ChangeList = self.get_changelist(request)
try:
cl = ChangeList(request, self.model, list_display,
list_display_links, self.list_filter, self.date_hierarchy,
self.search_fields, self.list_select_related,
self.list_per_page, self.list_max_show_all, self.list_editable,
self)
except IncorrectLookupParameters:
# Wacky lookup parameters were given, so redirect to the main
# changelist page, without parameters, and pass an 'invalid=1'
# parameter via the query string. If wacky parameters were given
# and the 'invalid=1' parameter was already in the query string,
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET.keys():
return SimpleTemplateResponse('admin/invalid_setup.html', {
'title': _('Database error'),
})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
# edit. Try to look up an action or confirmation first, but if this
# isn't an action the POST will fall through to the bulk edit check,
# below.
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
action_failed = True
# Actions with confirmation
if (actions and request.method == 'POST' and
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
# If we're allowing changelist editing, we need to construct a formset
# for the changelist given all the fields to be edited. Then we'll
# use the formset to validate/process POSTed data.
formset = cl.formset = None
# Handle POSTed bulk-edit data.
if (request.method == "POST" and cl.list_editable and
'_save' in request.POST and not action_failed):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
self.save_related(request, form, formsets=[], change=True)
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if changecount == 1:
name = force_text(opts.verbose_name)
else:
name = force_text(opts.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
'obj': force_text(obj)}
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
# Handle GET -- construct a formset for display.
elif cl.list_editable:
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
# Build the list of media to be used by the formset.
if formset:
media = self.media + formset.media
else:
media = self.media
# Build the action form and populate it with available actions.
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
else:
action_form = None
selection_note_all = ungettext('%(total_count)s selected',
'All %(total_count)s selected', cl.result_count)
context = {
'module_name': force_text(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'is_popup': cl.is_popup,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'app_label': app_label,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
}
context.update(extra_context or {})
return TemplateResponse(request, self.change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
], context, current_app=self.admin_site.name)
@csrf_protect_m
@transaction.commit_on_success
def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(deleted_objects, perms_needed, protected) = get_deleted_objects(
[obj], opts, request.user, self.admin_site, using)
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
obj_display = force_text(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect(reverse('admin:index',
current_app=self.admin_site.name))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
object_name = force_text(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": obj,
"deleted_objects": deleted_objects,
"perms_lacking": perms_needed,
"protected": protected,
"opts": opts,
"app_label": app_label,
}
context.update(extra_context or {})
return TemplateResponse(request, self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, current_app=self.admin_site.name)
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
model = self.model
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(
object_id = unquote(object_id),
content_type__id__exact = ContentType.objects.get_for_model(model).id
).select_related().order_by('action_time')
# If no history was found, see whether this object even exists.
obj = get_object_or_404(model, pk=unquote(object_id))
context = {
'title': _('Change history: %s') % force_text(obj),
'action_list': action_list,
'module_name': capfirst(force_text(opts.verbose_name_plural)),
'object': obj,
'app_label': app_label,
'opts': opts,
}
context.update(extra_context or {})
return TemplateResponse(request, self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context, current_app=self.admin_site.name)
class InlineModelAdmin(BaseModelAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``name`` to specify the attribute name of the ``ForeignKey`` from
``model`` to its parent. This is required if ``model`` has more than one
``ForeignKey`` to its parent.
"""
model = None
fk_name = None
formset = BaseInlineFormSet
extra = 3
max_num = None
template = None
verbose_name = None
verbose_name_plural = None
can_delete = True
def __init__(self, parent_model, admin_site):
self.admin_site = admin_site
self.parent_model = parent_model
self.opts = self.model._meta
super(InlineModelAdmin, self).__init__()
if self.verbose_name is None:
self.verbose_name = self.model._meta.verbose_name
if self.verbose_name_plural is None:
self.verbose_name_plural = self.model._meta.verbose_name_plural
@property
def media(self):
extra = '' if settings.DEBUG else '.min'
js = ['jquery%s.js' % extra, 'jquery.init.js', 'inlines%s.js' % extra]
if self.prepopulated_fields:
js.extend(['urlify.js', 'prepopulate%s.js' % extra])
if self.filter_vertical or self.filter_horizontal:
js.extend(['SelectBox.js', 'SelectFilter2.js'])
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def get_formset(self, request, obj=None, **kwargs):
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# InlineModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we use None, since that's the actual
# default
exclude = exclude or None
can_delete = self.can_delete and self.has_delete_permission(request, obj)
defaults = {
"form": self.form,
"formset": self.formset,
"fk_name": self.fk_name,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
"extra": self.extra,
"max_num": self.max_num,
"can_delete": can_delete,
}
defaults.update(kwargs)
return inlineformset_factory(self.parent_model, self.model, **defaults)
def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request, obj).form
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def queryset(self, request):
queryset = super(InlineModelAdmin, self).queryset(request)
if not self.has_change_permission(request):
queryset = queryset.none()
return queryset
def has_add_permission(self, request):
if self.opts.auto_created:
# We're checking the rights to an auto-created intermediate model,
# which doesn't have its own individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request)
return request.user.has_perm(
self.opts.app_label + '.' + self.opts.get_add_permission())
def has_change_permission(self, request, obj=None):
opts = self.opts
if opts.auto_created:
# The model was auto-created as intermediary for a
# ManyToMany-relationship, find the target model
for field in opts.fields:
if field.rel and field.rel.to != self.parent_model:
opts = field.rel.to._meta
break
return request.user.has_perm(
opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
if self.opts.auto_created:
# We're checking the rights to an auto-created intermediate model,
# which doesn't have its own individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request, obj)
return request.user.has_perm(
self.opts.app_label + '.' + self.opts.get_delete_permission())
class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularInline(InlineModelAdmin):
template = 'admin/edit_inline/tabular.html'
| {
"repo_name": "RichardLitt/wyrd-django-dev",
"path": "django/contrib/admin/options.py",
"copies": "4",
"size": "63431",
"license": "bsd-3-clause",
"hash": -6242937008255554000,
"line_mean": 42.2680763984,
"line_max": 167,
"alpha_frac": 0.5862590847,
"autogenerated": false,
"ratio": 4.3661205947136565,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6952379679413657,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, partial
from django import forms
from django.forms.formsets import all_valid
from django.forms.models import (modelform_factory, modelformset_factory,
inlineformset_factory, BaseInlineFormSet)
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers
from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_format_dict
from django.contrib.admin.templatetags.admin_static import static
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db import models, transaction, router
from django.db.models.related import RelatedObject
from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
from django.db.models.sql.constants import LOOKUP_SEP, QUERY_TERMS
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.response import SimpleTemplateResponse, TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.utils.encoding import force_unicode
HORIZONTAL, VERTICAL = 1, 2
# returns the <ul> class for a given radio_admin field
get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
class IncorrectLookupParameters(Exception):
pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
models.DateTimeField: {
'form_class': forms.SplitDateTimeField,
'widget': widgets.AdminSplitDateTime
},
models.DateField: {'widget': widgets.AdminDateWidget},
models.TimeField: {'widget': widgets.AdminTimeWidget},
models.TextField: {'widget': widgets.AdminTextareaWidget},
models.URLField: {'widget': widgets.AdminURLFieldWidget},
models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.BigIntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.CharField: {'widget': widgets.AdminTextInputWidget},
models.ImageField: {'widget': widgets.AdminFileWidget},
models.FileField: {'widget': widgets.AdminFileWidget},
}
csrf_protect_m = method_decorator(csrf_protect)
class BaseModelAdmin(object):
"""Functionality common to both ModelAdmin and InlineAdmin."""
__metaclass__ = forms.MediaDefiningClass
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = forms.ModelForm
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfield_overrides = {}
readonly_fields = ()
ordering = None
def __init__(self):
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
request = kwargs.pop("request", None)
# If the field specifies choices, we don't need to look for special
# admin widgets - we just need to use a select widget of some kind.
if db_field.choices:
return self.formfield_for_choice_field(db_field, request, **kwargs)
# ForeignKey or ManyToManyFields
if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
# Combine the field kwargs with any options for formfield_overrides.
# Make sure the passed in **kwargs override anything in
# formfield_overrides because **kwargs is more specific, and should
# always win.
if db_field.__class__ in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
# Get the correct formfield.
if isinstance(db_field, models.ForeignKey):
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
elif isinstance(db_field, models.ManyToManyField):
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
# For non-raw_id fields, wrap the widget with a wrapper that adds
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
if formfield and db_field.name not in self.raw_id_fields:
related_modeladmin = self.admin_site._registry.get(
db_field.rel.to)
can_add_related = bool(related_modeladmin and
related_modeladmin.has_add_permission(request))
formfield.widget = widgets.RelatedFieldWidgetWrapper(
formfield.widget, db_field.rel, self.admin_site,
can_add_related=can_add_related)
return formfield
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[klass], **kwargs)
return db_field.formfield(**kwargs)
# For any other type of field, just call its formfield() method.
return db_field.formfield(**kwargs)
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
"""
Get a form Field for a database Field that has declared choices.
"""
# If the field is named as a radio_field, use a RadioSelect
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank = db_field.blank,
blank_choice=[('', _('None'))]
)
return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ForeignKey.
"""
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel,
self.admin_site, using=db)
elif db_field.name in self.radio_fields:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
kwargs['empty_label'] = db_field.blank and _('None') or None
return db_field.formfield(**kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.rel.through._meta.auto_created:
return None
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel,
self.admin_site, using=db)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
return db_field.formfield(**kwargs)
def _declared_fieldsets(self):
if self.fieldsets:
return self.fieldsets
elif self.fields:
return [(None, {'fields': self.fields})]
return None
declared_fieldsets = property(_declared_fieldsets)
def get_ordering(self, request):
"""
Hook for specifying field ordering.
"""
return self.ordering or () # otherwise we might try to *None, which is bad ;)
def get_readonly_fields(self, request, obj=None):
"""
Hook for specifying custom readonly fields.
"""
return self.readonly_fields
def get_prepopulated_fields(self, request, obj=None):
"""
Hook for specifying custom prepopulated fields.
"""
return self.prepopulated_fields
def queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_query_set()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
def lookup_allowed(self, lookup, value):
model = self.model
# Check FKey lookups that are allowed, so that popups produced by
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
# are allowed to work.
for l in model._meta.related_fkey_lookups:
for k, v in widgets.url_params_from_lookup_dict(l).items():
if k == lookup and v == value:
return True
parts = lookup.split(LOOKUP_SEP)
# Last term in lookup is a query term (__exact, __startswith etc)
# This term can be ignored.
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
# Special case -- foo__id__exact and foo__id queries are implied
# if foo has been specificially included in the lookup list; so
# drop __id if it is the last part. However, first we need to find
# the pk attribute name.
pk_attr_name = None
for part in parts[:-1]:
field, _, _, _ = model._meta.get_field_by_name(part)
if hasattr(field, 'rel'):
model = field.rel.to
pk_attr_name = model._meta.pk.name
elif isinstance(field, RelatedObject):
model = field.model
pk_attr_name = model._meta.pk.name
else:
pk_attr_name = None
if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name:
parts.pop()
try:
self.model._meta.get_field_by_name(parts[0])
except FieldDoesNotExist:
# Lookups on non-existants fields are ok, since they're ignored
# later.
return True
else:
if len(parts) == 1:
return True
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy
def has_add_permission(self, request):
"""
Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
def has_change_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission())
class ModelAdmin(BaseModelAdmin):
"Encapsulates all admin options and functionality for a given model."
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
list_per_page = 100
list_max_show_all = 200
list_editable = ()
search_fields = ()
date_hierarchy = None
save_as = False
save_on_top = False
paginator = Paginator
inlines = []
# Custom templates (designed to be over-ridden in subclasses)
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
# Actions
actions = []
action_form = helpers.ActionForm
actions_on_top = True
actions_on_bottom = False
actions_selection_counter = True
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(ModelAdmin, self).__init__()
def get_inline_instances(self, request):
inline_instances = []
for inline_class in self.inlines:
inline = inline_class(self.model, self.admin_site)
if request:
if not (inline.has_add_permission(request) or
inline.has_change_permission(request) or
inline.has_delete_permission(request)):
continue
if not inline.has_add_permission(request):
inline.max_num = 0
inline_instances.append(inline)
return inline_instances
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
urlpatterns = patterns('',
url(r'^$',
wrap(self.changelist_view),
name='%s_%s_changelist' % info),
url(r'^add/$',
wrap(self.add_view),
name='%s_%s_add' % info),
url(r'^(.+)/history/$',
wrap(self.history_view),
name='%s_%s_history' % info),
url(r'^(.+)/delete/$',
wrap(self.delete_view),
name='%s_%s_delete' % info),
url(r'^(.+)/$',
wrap(self.change_view),
name='%s_%s_change' % info),
)
return urlpatterns
def urls(self):
return self.get_urls()
urls = property(urls)
@property
def media(self):
js = [
'core.js',
'admin/RelatedObjectLookups.js',
'jquery.min.js',
'jquery.init.js'
]
if self.actions is not None:
js.append('actions.min.js')
if self.prepopulated_fields:
js.extend(['urlify.js', 'prepopulate.min.js'])
if self.opts.get_ordered_objects():
js.extend(['getElementsBySelector.js', 'dom-drag.js' , 'admin/ordering.js'])
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def get_model_perms(self, request):
"""
Returns a dict of all perms for this model. This dict has the keys
``add``, ``change``, and ``delete`` mapping to the True/False for each
of those actions.
"""
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
}
def get_fieldsets(self, request, obj=None):
"Hook for specifying fieldsets for the add form."
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
"""
from django.contrib.admin.views.main import ChangeList
return ChangeList
def get_object(self, request, object_id):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None
def get_changelist_form(self, request, **kwargs):
"""
Returns a Form class for use in the Formset on the changelist page.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist_formset(self, request, **kwargs):
"""
Returns a FormSet class for use on the changelist page if list_editable
is used.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelformset_factory(self.model,
self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults)
def get_formsets(self, request, obj=None):
for inline in self.get_inline_instances(request):
yield inline.get_formset(request, obj)
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
def log_addition(self, request, object):
"""
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, ADDITION
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_unicode(object),
action_flag = ADDITION
)
def log_change(self, request, object, message):
"""
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_unicode(object),
action_flag = CHANGE,
change_message = message
)
def log_deletion(self, request, object, object_repr):
"""
Log that an object will be deleted. Note that this method is called
before the deletion.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, DELETION
LogEntry.objects.log_action(
user_id = request.user.id,
content_type_id = ContentType.objects.get_for_model(self.model).pk,
object_id = object.pk,
object_repr = object_repr,
action_flag = DELETION
)
def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_unicode(obj.pk))
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is explicitally set to None that means that we don't
# want *any* actions enabled on this page.
from django.contrib.admin.views.main import IS_POPUP_VAR
if self.actions is None or IS_POPUP_VAR in request.GET:
return SortedDict()
actions = []
# Gather actions from the admin site first
for (name, func) in self.admin_site.actions:
description = getattr(func, 'short_description', name.replace('_', ' '))
actions.append((func, name, description))
# Then gather them from the model admin and all parent classes,
# starting with self and working back up.
for klass in self.__class__.mro()[::-1]:
class_actions = getattr(klass, 'actions', [])
# Avoid trying to iterate over None
if not class_actions:
continue
actions.extend([self.get_action(action) for action in class_actions])
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
# Convert the actions into a SortedDict keyed by name.
actions = SortedDict([
(name, (func, name, desc))
for func, name, desc in actions
])
return actions
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in self.get_actions(request).itervalues():
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(action):
func = action
action = action.__name__
# Next, look for a method. Grab it off self.__class__ to get an unbound
# method instead of a bound one; this ensures that the calling
# conventions are the same for functions and methods.
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
# Finally, look for a named method on the admin site
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
if hasattr(func, 'short_description'):
description = func.short_description
else:
description = capfirst(action.replace('_', ' '))
return func, action, description
def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display
def get_list_display_links(self, request, list_display):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or not list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(list_display)[:1]
def construct_change_message(self, request, form, formsets):
"""
Construct a change message from a changed object.
"""
change_message = []
if form.changed_data:
change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and')))
if formsets:
for formset in formsets:
for added_object in formset.new_objects:
change_message.append(_('Added %(name)s "%(object)s".')
% {'name': force_unicode(added_object._meta.verbose_name),
'object': force_unicode(added_object)})
for changed_object, changed_fields in formset.changed_objects:
change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
% {'list': get_text_list(changed_fields, _('and')),
'name': force_unicode(changed_object._meta.verbose_name),
'object': force_unicode(changed_object)})
for deleted_object in formset.deleted_objects:
change_message.append(_('Deleted %(name)s "%(object)s".')
% {'name': force_unicode(deleted_object._meta.verbose_name),
'object': force_unicode(deleted_object)})
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
def message_user(self, request, message):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
"""
messages.info(request, message)
def save_form(self, request, form, change):
"""
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
"""
return form.save(commit=False)
def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
obj.save()
def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
obj.delete()
def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
def save_related(self, request, form, formsets, change):
"""
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.
"""
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change)
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
opts = self.model._meta
app_label = opts.app_label
ordered_objects = opts.get_ordered_objects()
context.update({
'add': add,
'change': change,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
'has_absolute_url': hasattr(self.model, 'get_absolute_url'),
'ordered_objects': ordered_objects,
'form_url': mark_safe(form_url),
'opts': opts,
'content_type_id': ContentType.objects.get_for_model(self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
})
if add and self.add_form_template is not None:
form_template = self.add_form_template
else:
form_template = self.change_form_template
return TemplateResponse(request, form_template or [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"admin/%s/change_form.html" % app_label,
"admin/change_form.html"
], context, current_app=self.admin_site.name)
def response_add(self, request, obj, post_url_continue='../%s/'):
"""
Determines the HttpResponse for the add_view stage.
"""
opts = obj._meta
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
if "_popup" in request.POST:
return HttpResponse(
'<!DOCTYPE html><html><head><title></title></head><body>'
'<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script></body></html>' % \
# escape() calls force_unicode.
(escape(pk_value), escapejs(obj)))
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect(request.path)
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
post_url = reverse('admin:%s_%s_changelist' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name)
else:
post_url = reverse('admin:index',
current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def response_change(self, request, obj):
"""
Determines the HttpResponse for the change_view stage.
"""
opts = obj._meta
# Handle proxy models automatically created by .only() or .defer().
# Refs #14529
verbose_name = opts.verbose_name
module_name = opts.module_name
if obj._deferred:
opts_ = opts.proxy_for_model._meta
verbose_name = opts_.verbose_name
module_name = opts_.module_name
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(verbose_name), 'obj': force_unicode(obj)}
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(verbose_name), 'obj': obj}
self.message_user(request, msg)
return HttpResponseRedirect(reverse('admin:%s_%s_change' %
(opts.app_label, module_name),
args=(pk_value,),
current_app=self.admin_site.name))
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(verbose_name)))
return HttpResponseRedirect(reverse('admin:%s_%s_add' %
(opts.app_label, module_name),
current_app=self.admin_site.name))
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
post_url = reverse('admin:%s_%s_changelist' %
(opts.app_label, module_name),
current_app=self.admin_site.name)
else:
post_url = reverse('admin:index',
current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func, name, description = self.get_actions(request)[action]
# Get the list of selected PKs. If nothing's selected, we can't
# perform an action on it, so bail. Except we want to perform
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
return None
if not select_across:
# Perform the action only on the selected objects
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
# Actions may return an HttpResponse, which will be used as the
# response from the POST. If not, we'll be a good little HTTP
# citizen and redirect back to the changelist page.
if isinstance(response, HttpResponse):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _("No action selected.")
self.message_user(request, msg)
return None
@csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
"The 'add' admin view for this model."
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
inline_instances = self.get_inline_instances(request)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, False)
self.save_related(request, form, formsets, False)
self.log_addition(request, new_object)
return self.response_add(request, new_object)
else:
# Prepare the dict of initial data from the request.
# We have to special-case M2Ms as a list of comma-separated PKs.
initial = dict(request.GET.items())
for k in initial:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
form = ModelForm(initial=initial)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=self.model(), prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
self.get_prepopulated_fields(request),
self.get_readonly_fields(request),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request))
readonly = list(inline.get_readonly_fields(request))
prepopulated = dict(inline.get_prepopulated_fields(request))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Add %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'show_delete': False,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url=form_url, add=True)
@csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, extra_context=None):
"The 'change' admin view for this model."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
ModelForm = self.get_form(request, obj)
formsets = []
inline_instances = self.get_inline_instances(request)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, True)
self.save_related(request, form, formsets, True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.get_prepopulated_fields(request, obj),
self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
prepopulated = dict(inline.get_prepopulated_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"""
The 'change list' admin view for this model.
"""
from django.contrib.admin.views.main import ERROR_FLAG
opts = self.model._meta
app_label = opts.app_label
if not self.has_change_permission(request, None):
raise PermissionDenied
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
# Check actions to see if any are available on this changelist
actions = self.get_actions(request)
if actions:
# Add the action checkboxes if there are any actions available.
list_display = ['action_checkbox'] + list(list_display)
ChangeList = self.get_changelist(request)
try:
cl = ChangeList(request, self.model, list_display,
list_display_links, self.list_filter, self.date_hierarchy,
self.search_fields, self.list_select_related,
self.list_per_page, self.list_max_show_all, self.list_editable,
self)
except IncorrectLookupParameters:
# Wacky lookup parameters were given, so redirect to the main
# changelist page, without parameters, and pass an 'invalid=1'
# parameter via the query string. If wacky parameters were given
# and the 'invalid=1' parameter was already in the query string,
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET.keys():
return SimpleTemplateResponse('admin/invalid_setup.html', {
'title': _('Database error'),
})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
# edit. Try to look up an action or confirmation first, but if this
# isn't an action the POST will fall through to the bulk edit check,
# below.
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
action_failed = True
# Actions with confirmation
if (actions and request.method == 'POST' and
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
# If we're allowing changelist editing, we need to construct a formset
# for the changelist given all the fields to be edited. Then we'll
# use the formset to validate/process POSTed data.
formset = cl.formset = None
# Handle POSTed bulk-edit data.
if (request.method == "POST" and cl.list_editable and
'_save' in request.POST and not action_failed):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
self.save_related(request, form, formsets=[], change=True)
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if changecount == 1:
name = force_unicode(opts.verbose_name)
else:
name = force_unicode(opts.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
'obj': force_unicode(obj)}
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
# Handle GET -- construct a formset for display.
elif cl.list_editable:
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
# Build the list of media to be used by the formset.
if formset:
media = self.media + formset.media
else:
media = self.media
# Build the action form and populate it with available actions.
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
else:
action_form = None
selection_note_all = ungettext('%(total_count)s selected',
'All %(total_count)s selected', cl.result_count)
context = {
'module_name': force_unicode(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'is_popup': cl.is_popup,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'app_label': app_label,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
}
context.update(extra_context or {})
return TemplateResponse(request, self.change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
], context, current_app=self.admin_site.name)
@csrf_protect_m
@transaction.commit_on_success
def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(deleted_objects, perms_needed, protected) = get_deleted_objects(
[obj], opts, request.user, self.admin_site, using)
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
obj_display = force_unicode(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect(reverse('admin:index',
current_app=self.admin_site.name))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
object_name = force_unicode(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": obj,
"deleted_objects": deleted_objects,
"perms_lacking": perms_needed,
"protected": protected,
"opts": opts,
"app_label": app_label,
}
context.update(extra_context or {})
return TemplateResponse(request, self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, current_app=self.admin_site.name)
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
model = self.model
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(
object_id = object_id,
content_type__id__exact = ContentType.objects.get_for_model(model).id
).select_related().order_by('action_time')
# If no history was found, see whether this object even exists.
obj = get_object_or_404(model, pk=unquote(object_id))
context = {
'title': _('Change history: %s') % force_unicode(obj),
'action_list': action_list,
'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
'object': obj,
'app_label': app_label,
'opts': opts,
}
context.update(extra_context or {})
return TemplateResponse(request, self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context, current_app=self.admin_site.name)
class InlineModelAdmin(BaseModelAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``name`` to specify the attribute name of the ``ForeignKey`` from
``model`` to its parent. This is required if ``model`` has more than one
``ForeignKey`` to its parent.
"""
model = None
fk_name = None
formset = BaseInlineFormSet
extra = 3
max_num = None
template = None
verbose_name = None
verbose_name_plural = None
can_delete = True
def __init__(self, parent_model, admin_site):
self.admin_site = admin_site
self.parent_model = parent_model
self.opts = self.model._meta
super(InlineModelAdmin, self).__init__()
if self.verbose_name is None:
self.verbose_name = self.model._meta.verbose_name
if self.verbose_name_plural is None:
self.verbose_name_plural = self.model._meta.verbose_name_plural
@property
def media(self):
js = ['jquery.min.js', 'jquery.init.js', 'inlines.min.js']
if self.prepopulated_fields:
js.extend(['urlify.js', 'prepopulate.min.js'])
if self.filter_vertical or self.filter_horizontal:
js.extend(['SelectBox.js', 'SelectFilter2.js'])
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def get_formset(self, request, obj=None, **kwargs):
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# InlineModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we use None, since that's the actual
# default
exclude = exclude or None
can_delete = self.can_delete and self.has_delete_permission(request, obj)
defaults = {
"form": self.form,
"formset": self.formset,
"fk_name": self.fk_name,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
"extra": self.extra,
"max_num": self.max_num,
"can_delete": can_delete,
}
defaults.update(kwargs)
return inlineformset_factory(self.parent_model, self.model, **defaults)
def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request, obj).form
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def queryset(self, request):
queryset = super(InlineModelAdmin, self).queryset(request)
if not self.has_change_permission(request):
queryset = queryset.none()
return queryset
def has_add_permission(self, request):
if self.opts.auto_created:
# We're checking the rights to an auto-created intermediate model,
# which doesn't have its own individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request)
return request.user.has_perm(
self.opts.app_label + '.' + self.opts.get_add_permission())
def has_change_permission(self, request, obj=None):
opts = self.opts
if opts.auto_created:
# The model was auto-created as intermediary for a
# ManyToMany-relationship, find the target model
for field in opts.fields:
if field.rel and field.rel.to != self.parent_model:
opts = field.rel.to._meta
break
return request.user.has_perm(
opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
if self.opts.auto_created:
# We're checking the rights to an auto-created intermediate model,
# which doesn't have its own individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request, obj)
return request.user.has_perm(
self.opts.app_label + '.' + self.opts.get_delete_permission())
class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularInline(InlineModelAdmin):
template = 'admin/edit_inline/tabular.html'
| {
"repo_name": "mixman/djangodev",
"path": "django/contrib/admin/options.py",
"copies": "2",
"size": "63392",
"license": "bsd-3-clause",
"hash": -9205463135274297000,
"line_mean": 42.3301435407,
"line_max": 173,
"alpha_frac": 0.5863989147,
"autogenerated": false,
"ratio": 4.372766779333655,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001767211306091417,
"num_lines": 1463
} |
from functools import update_wrapper, partial
from django import forms, template
from django.forms.formsets import all_valid
from django.forms.models import (modelform_factory, modelformset_factory,
inlineformset_factory, BaseInlineFormSet)
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers
from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_format_dict
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
from django.db import models, transaction, router
from django.db.models.related import RelatedObject
from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
from django.db.models.sql.constants import LOOKUP_SEP, QUERY_TERMS
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.utils.decorators import method_decorator
from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.utils.encoding import force_unicode
HORIZONTAL, VERTICAL = 1, 2
# returns the <ul> class for a given radio_admin field
get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
class IncorrectLookupParameters(Exception):
pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
models.DateTimeField: {
'form_class': forms.SplitDateTimeField,
'widget': widgets.AdminSplitDateTime
},
models.DateField: {'widget': widgets.AdminDateWidget},
models.TimeField: {'widget': widgets.AdminTimeWidget},
models.TextField: {'widget': widgets.AdminTextareaWidget},
models.URLField: {'widget': widgets.AdminURLFieldWidget},
models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.BigIntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.CharField: {'widget': widgets.AdminTextInputWidget},
models.ImageField: {'widget': widgets.AdminFileWidget},
models.FileField: {'widget': widgets.AdminFileWidget},
}
csrf_protect_m = method_decorator(csrf_protect)
class BaseModelAdmin(object):
"""Functionality common to both ModelAdmin and InlineAdmin."""
__metaclass__ = forms.MediaDefiningClass
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = forms.ModelForm
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfield_overrides = {}
readonly_fields = ()
ordering = None
def __init__(self):
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
request = kwargs.pop("request", None)
# If the field specifies choices, we don't need to look for special
# admin widgets - we just need to use a select widget of some kind.
if db_field.choices:
return self.formfield_for_choice_field(db_field, request, **kwargs)
# ForeignKey or ManyToManyFields
if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
# Combine the field kwargs with any options for formfield_overrides.
# Make sure the passed in **kwargs override anything in
# formfield_overrides because **kwargs is more specific, and should
# always win.
if db_field.__class__ in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
# Get the correct formfield.
if isinstance(db_field, models.ForeignKey):
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
elif isinstance(db_field, models.ManyToManyField):
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
# For non-raw_id fields, wrap the widget with a wrapper that adds
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
if formfield and db_field.name not in self.raw_id_fields:
related_modeladmin = self.admin_site._registry.get(
db_field.rel.to)
can_add_related = bool(related_modeladmin and
related_modeladmin.has_add_permission(request))
formfield.widget = widgets.RelatedFieldWidgetWrapper(
formfield.widget, db_field.rel, self.admin_site,
can_add_related=can_add_related)
return formfield
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[klass], **kwargs)
return db_field.formfield(**kwargs)
# For any other type of field, just call its formfield() method.
return db_field.formfield(**kwargs)
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
"""
Get a form Field for a database Field that has declared choices.
"""
# If the field is named as a radio_field, use a RadioSelect
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank = db_field.blank,
blank_choice=[('', _('None'))]
)
return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ForeignKey.
"""
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, using=db)
elif db_field.name in self.radio_fields:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
kwargs['empty_label'] = db_field.blank and _('None') or None
return db_field.formfield(**kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.rel.through._meta.auto_created:
return None
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
return db_field.formfield(**kwargs)
def _declared_fieldsets(self):
if self.fieldsets:
return self.fieldsets
elif self.fields:
return [(None, {'fields': self.fields})]
return None
declared_fieldsets = property(_declared_fieldsets)
def get_readonly_fields(self, request, obj=None):
return self.readonly_fields
def queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_query_set()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.ordering or () # otherwise we might try to *None, which is bad ;)
if ordering:
qs = qs.order_by(*ordering)
return qs
def lookup_allowed(self, lookup, value):
model = self.model
# Check FKey lookups that are allowed, so that popups produced by
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
# are allowed to work.
for l in model._meta.related_fkey_lookups:
for k, v in widgets.url_params_from_lookup_dict(l).items():
if k == lookup and v == value:
return True
parts = lookup.split(LOOKUP_SEP)
# Last term in lookup is a query term (__exact, __startswith etc)
# This term can be ignored.
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
# Special case -- foo__id__exact and foo__id queries are implied
# if foo has been specificially included in the lookup list; so
# drop __id if it is the last part. However, first we need to find
# the pk attribute name.
pk_attr_name = None
for part in parts[:-1]:
field, _, _, _ = model._meta.get_field_by_name(part)
if hasattr(field, 'rel'):
model = field.rel.to
pk_attr_name = model._meta.pk.name
elif isinstance(field, RelatedObject):
model = field.model
pk_attr_name = model._meta.pk.name
else:
pk_attr_name = None
if pk_attr_name and len(parts) > 1 and parts[-1] == pk_attr_name:
parts.pop()
try:
self.model._meta.get_field_by_name(parts[0])
except FieldDoesNotExist:
# Lookups on non-existants fields are ok, since they're ignored
# later.
return True
else:
if len(parts) == 1:
return True
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy
class ModelAdmin(BaseModelAdmin):
"Encapsulates all admin options and functionality for a given model."
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
list_per_page = 100
list_editable = ()
search_fields = ()
date_hierarchy = None
save_as = False
save_on_top = False
paginator = Paginator
inlines = []
# Custom templates (designed to be over-ridden in subclasses)
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
# Actions
actions = []
action_form = helpers.ActionForm
actions_on_top = True
actions_on_bottom = False
actions_selection_counter = True
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
self.inline_instances = []
for inline_class in self.inlines:
inline_instance = inline_class(self.model, self.admin_site)
self.inline_instances.append(inline_instance)
if 'action_checkbox' not in self.list_display and self.actions is not None:
self.list_display = ['action_checkbox'] + list(self.list_display)
if not self.list_display_links:
for name in self.list_display:
if name != 'action_checkbox':
self.list_display_links = [name]
break
super(ModelAdmin, self).__init__()
def get_urls(self):
from django.conf.urls.defaults import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
urlpatterns = patterns('',
url(r'^$',
wrap(self.changelist_view),
name='%s_%s_changelist' % info),
url(r'^add/$',
wrap(self.add_view),
name='%s_%s_add' % info),
url(r'^(.+)/history/$',
wrap(self.history_view),
name='%s_%s_history' % info),
url(r'^(.+)/delete/$',
wrap(self.delete_view),
name='%s_%s_delete' % info),
url(r'^(.+)/$',
wrap(self.change_view),
name='%s_%s_change' % info),
)
return urlpatterns
def urls(self):
return self.get_urls()
urls = property(urls)
def _media(self):
from django.conf import settings
js = ['js/core.js', 'js/admin/RelatedObjectLookups.js',
'js/jquery.min.js', 'js/jquery.init.js']
if self.actions is not None:
js.extend(['js/actions.min.js'])
if self.prepopulated_fields:
js.append('js/urlify.js')
js.append('js/prepopulate.min.js')
if self.opts.get_ordered_objects():
js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js'])
return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
media = property(_media)
def has_add_permission(self, request):
"""
Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
def has_change_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission())
def get_model_perms(self, request):
"""
Returns a dict of all perms for this model. This dict has the keys
``add``, ``change``, and ``delete`` mapping to the True/False for each
of those actions.
"""
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
}
def get_fieldsets(self, request, obj=None):
"Hook for specifying fieldsets for the add form."
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(kwargs.get("exclude", []))
exclude.extend(self.get_readonly_fields(request, obj))
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
"""
from django.contrib.admin.views.main import ChangeList
return ChangeList
def get_object(self, request, object_id):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None
def get_changelist_form(self, request, **kwargs):
"""
Returns a Form class for use in the Formset on the changelist page.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist_formset(self, request, **kwargs):
"""
Returns a FormSet class for use on the changelist page if list_editable
is used.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelformset_factory(self.model,
self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults)
def get_formsets(self, request, obj=None):
for inline in self.inline_instances:
yield inline.get_formset(request, obj)
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
def log_addition(self, request, object):
"""
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, ADDITION
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_unicode(object),
action_flag = ADDITION
)
def log_change(self, request, object, message):
"""
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_unicode(object),
action_flag = CHANGE,
change_message = message
)
def log_deletion(self, request, object, object_repr):
"""
Log that an object will be deleted. Note that this method is called
before the deletion.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, DELETION
LogEntry.objects.log_action(
user_id = request.user.id,
content_type_id = ContentType.objects.get_for_model(self.model).pk,
object_id = object.pk,
object_repr = object_repr,
action_flag = DELETION
)
def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_unicode(obj.pk))
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is explicitally set to None that means that we don't
# want *any* actions enabled on this page.
from django.contrib.admin.views.main import IS_POPUP_VAR
if self.actions is None or IS_POPUP_VAR in request.GET:
return SortedDict()
actions = []
# Gather actions from the admin site first
for (name, func) in self.admin_site.actions:
description = getattr(func, 'short_description', name.replace('_', ' '))
actions.append((func, name, description))
# Then gather them from the model admin and all parent classes,
# starting with self and working back up.
for klass in self.__class__.mro()[::-1]:
class_actions = getattr(klass, 'actions', [])
# Avoid trying to iterate over None
if not class_actions:
continue
actions.extend([self.get_action(action) for action in class_actions])
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
# Convert the actions into a SortedDict keyed by name
# and sorted by description.
actions.sort(key=lambda k: k[2].lower())
actions = SortedDict([
(name, (func, name, desc))
for func, name, desc in actions
])
return actions
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in self.get_actions(request).itervalues():
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(action):
func = action
action = action.__name__
# Next, look for a method. Grab it off self.__class__ to get an unbound
# method instead of a bound one; this ensures that the calling
# conventions are the same for functions and methods.
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
# Finally, look for a named method on the admin site
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
if hasattr(func, 'short_description'):
description = func.short_description
else:
description = capfirst(action.replace('_', ' '))
return func, action, description
def construct_change_message(self, request, form, formsets):
"""
Construct a change message from a changed object.
"""
change_message = []
if form.changed_data:
change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and')))
if formsets:
for formset in formsets:
for added_object in formset.new_objects:
change_message.append(_('Added %(name)s "%(object)s".')
% {'name': force_unicode(added_object._meta.verbose_name),
'object': force_unicode(added_object)})
for changed_object, changed_fields in formset.changed_objects:
change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
% {'list': get_text_list(changed_fields, _('and')),
'name': force_unicode(changed_object._meta.verbose_name),
'object': force_unicode(changed_object)})
for deleted_object in formset.deleted_objects:
change_message.append(_('Deleted %(name)s "%(object)s".')
% {'name': force_unicode(deleted_object._meta.verbose_name),
'object': force_unicode(deleted_object)})
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
def message_user(self, request, message):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
"""
messages.info(request, message)
def save_form(self, request, form, change):
"""
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
"""
return form.save(commit=False)
def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
obj.save()
def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
obj.delete()
def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
opts = self.model._meta
app_label = opts.app_label
ordered_objects = opts.get_ordered_objects()
context.update({
'add': add,
'change': change,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
'has_absolute_url': hasattr(self.model, 'get_absolute_url'),
'ordered_objects': ordered_objects,
'form_url': mark_safe(form_url),
'opts': opts,
'content_type_id': ContentType.objects.get_for_model(self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
'root_path': self.admin_site.root_path,
})
if add and self.add_form_template is not None:
form_template = self.add_form_template
else:
form_template = self.change_form_template
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(form_template or [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"admin/%s/change_form.html" % app_label,
"admin/change_form.html"
], context, context_instance=context_instance)
def response_add(self, request, obj, post_url_continue='../%s/'):
"""
Determines the HttpResponse for the add_view stage.
"""
opts = obj._meta
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.POST:
post_url_continue += "?_popup=1"
return HttpResponseRedirect(post_url_continue % pk_value)
if "_popup" in request.POST:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
# escape() calls force_unicode.
(escape(pk_value), escapejs(obj)))
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name)))
return HttpResponseRedirect(request.path)
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
post_url = '../'
else:
post_url = '../../../'
return HttpResponseRedirect(post_url)
def response_change(self, request, obj):
"""
Determines the HttpResponse for the change_view stage.
"""
opts = obj._meta
# Handle proxy models automatically created by .only() or .defer()
verbose_name = opts.verbose_name
if obj._deferred:
opts_ = opts.proxy_for_model._meta
verbose_name = opts_.verbose_name
pk_value = obj._get_pk_val()
msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(verbose_name), 'obj': force_unicode(obj)}
if "_continue" in request.POST:
self.message_user(request, msg + ' ' + _("You may edit it again below."))
if "_popup" in request.REQUEST:
return HttpResponseRedirect(request.path + "?_popup=1")
else:
return HttpResponseRedirect(request.path)
elif "_saveasnew" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(verbose_name), 'obj': obj}
self.message_user(request, msg)
return HttpResponseRedirect("../%s/" % pk_value)
elif "_addanother" in request.POST:
self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(verbose_name)))
return HttpResponseRedirect("../add/")
else:
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
return HttpResponseRedirect('../')
else:
return HttpResponseRedirect('../../../')
def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func, name, description = self.get_actions(request)[action]
# Get the list of selected PKs. If nothing's selected, we can't
# perform an action on it, so bail. Except we want to perform
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
return None
if not select_across:
# Perform the action only on the selected objects
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
# Actions may return an HttpResponse, which will be used as the
# response from the POST. If not, we'll be a good little HTTP
# citizen and redirect back to the changelist page.
if isinstance(response, HttpResponse):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _("No action selected.")
self.message_user(request, msg)
return None
@csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
"The 'add' admin view for this model."
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), self.inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=False)
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=False)
self.log_addition(request, new_object)
return self.response_add(request, new_object)
else:
# Prepare the dict of initial data from the request.
# We have to special-case M2Ms as a list of comma-separated PKs.
initial = dict(request.GET.items())
for k in initial:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
form = ModelForm(initial=initial)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request),
self.inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=self.model(), prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
self.prepopulated_fields, self.get_readonly_fields(request),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request))
readonly = list(inline.get_readonly_fields(request))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Add %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'show_delete': False,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'root_path': self.admin_site.root_path,
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url=form_url, add=True)
@csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, extra_context=None):
"The 'change' admin view for this model."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url='../add/')
ModelForm = self.get_form(request, obj)
formsets = []
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object),
self.inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, change=True)
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj), self.inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.prepopulated_fields, self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(self.inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_unicode(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': mark_safe(media),
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'root_path': self.admin_site.root_path,
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"The 'change list' admin view for this model."
from django.contrib.admin.views.main import ERROR_FLAG
opts = self.model._meta
app_label = opts.app_label
if not self.has_change_permission(request, None):
raise PermissionDenied
# Check actions to see if any are available on this changelist
actions = self.get_actions(request)
# Remove action checkboxes if there aren't any actions available.
list_display = list(self.list_display)
if not actions:
try:
list_display.remove('action_checkbox')
except ValueError:
pass
ChangeList = self.get_changelist(request)
try:
cl = ChangeList(request, self.model, list_display, self.list_display_links,
self.list_filter, self.date_hierarchy, self.search_fields,
self.list_select_related, self.list_per_page, self.list_editable, self)
except IncorrectLookupParameters:
# Wacky lookup parameters were given, so redirect to the main
# changelist page, without parameters, and pass an 'invalid=1'
# parameter via the query string. If wacky parameters were given
# and the 'invalid=1' parameter was already in the query string,
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET.keys():
return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
# edit. Try to look up an action or confirmation first, but if this
# isn't an action the POST will fall through to the bulk edit check,
# below.
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set())
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
action_failed = True
# Actions with confirmation
if (actions and request.method == 'POST' and
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set())
if response:
return response
else:
action_failed = True
# If we're allowing changelist editing, we need to construct a formset
# for the changelist given all the fields to be edited. Then we'll
# use the formset to validate/process POSTed data.
formset = cl.formset = None
# Handle POSTed bulk-edit data.
if (request.method == "POST" and cl.list_editable and
'_save' in request.POST and not action_failed):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
form.save_m2m()
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if changecount == 1:
name = force_unicode(opts.verbose_name)
else:
name = force_unicode(opts.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
'obj': force_unicode(obj)}
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
# Handle GET -- construct a formset for display.
elif cl.list_editable:
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
# Build the list of media to be used by the formset.
if formset:
media = self.media + formset.media
else:
media = self.media
# Build the action form and populate it with available actions.
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
else:
action_form = None
selection_note_all = ungettext('%(total_count)s selected',
'All %(total_count)s selected', cl.result_count)
context = {
'module_name': force_unicode(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'is_popup': cl.is_popup,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'root_path': self.admin_site.root_path,
'app_label': app_label,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
], context, context_instance=context_instance)
@csrf_protect_m
@transaction.commit_on_success
def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(deleted_objects, perms_needed, protected) = get_deleted_objects(
[obj], opts, request.user, self.admin_site, using)
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
obj_display = force_unicode(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect("../../../../")
return HttpResponseRedirect("../../")
object_name = force_unicode(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": obj,
"deleted_objects": deleted_objects,
"perms_lacking": perms_needed,
"protected": protected,
"opts": opts,
"root_path": self.admin_site.root_path,
"app_label": app_label,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, context_instance=context_instance)
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
model = self.model
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(
object_id = object_id,
content_type__id__exact = ContentType.objects.get_for_model(model).id
).select_related().order_by('action_time')
# If no history was found, see whether this object even exists.
obj = get_object_or_404(model, pk=unquote(object_id))
context = {
'title': _('Change history: %s') % force_unicode(obj),
'action_list': action_list,
'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
'object': obj,
'root_path': self.admin_site.root_path,
'app_label': app_label,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context, context_instance=context_instance)
class InlineModelAdmin(BaseModelAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``name`` to specify the attribute name of the ``ForeignKey`` from
``model`` to its parent. This is required if ``model`` has more than one
``ForeignKey`` to its parent.
"""
model = None
fk_name = None
formset = BaseInlineFormSet
extra = 3
max_num = None
template = None
verbose_name = None
verbose_name_plural = None
can_delete = True
def __init__(self, parent_model, admin_site):
self.admin_site = admin_site
self.parent_model = parent_model
self.opts = self.model._meta
super(InlineModelAdmin, self).__init__()
if self.verbose_name is None:
self.verbose_name = self.model._meta.verbose_name
if self.verbose_name_plural is None:
self.verbose_name_plural = self.model._meta.verbose_name_plural
def _media(self):
from django.conf import settings
js = ['js/jquery.min.js', 'js/jquery.init.js', 'js/inlines.min.js']
if self.prepopulated_fields:
js.append('js/urlify.js')
js.append('js/prepopulate.min.js')
if self.filter_vertical or self.filter_horizontal:
js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js'])
return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
media = property(_media)
def get_formset(self, request, obj=None, **kwargs):
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(kwargs.get("exclude", []))
exclude.extend(self.get_readonly_fields(request, obj))
# if exclude is an empty list we use None, since that's the actual
# default
exclude = exclude or None
defaults = {
"form": self.form,
"formset": self.formset,
"fk_name": self.fk_name,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
"extra": self.extra,
"max_num": self.max_num,
"can_delete": self.can_delete,
}
defaults.update(kwargs)
return inlineformset_factory(self.parent_model, self.model, **defaults)
def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request).form
fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularInline(InlineModelAdmin):
template = 'admin/edit_inline/tabular.html'
| {
"repo_name": "jamespacileo/django-france",
"path": "django/contrib/admin/options.py",
"copies": "2",
"size": "58131",
"license": "bsd-3-clause",
"hash": 8925138827111839000,
"line_mean": 42.1238872404,
"line_max": 173,
"alpha_frac": 0.5881887461,
"autogenerated": false,
"ratio": 4.3277992852888625,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5915988031388862,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, partial
import json
import logging
from cachebrowser.models import Host
import click
from cachebrowser.api.core import APIManager, APIRequest
from cachebrowser.bootstrap import BootstrapError
main_commands = ['hostcli', 'cdncli', 'bootstrap']
api = APIManager()
logger = logging.getLogger(__name__)
def forward_to_api(route, params=None):
def wrapper(func):
@click.pass_obj
def inner(context, **kwargs):
request_params = params.copy() if params else {}
request_params.update(kwargs)
request = APIRequest(route, request_params)
request.reply = partial(func, context)
api.handle_api_request(context, request)
return update_wrapper(inner, func)
return wrapper
@click.group('host')
def hostcli():
pass
@hostcli.command('add')
@forward_to_api('/hosts/add')
@click.argument('hostname')
@click.argument('cdn')
@click.option('--ssl/--no-ssl', 'ssl', default=True)
def addhost(context):
click.echo("New host added")
@hostcli.command('list')
@forward_to_api('/hosts', {'page': 0, 'num_per_page': 0})
def listhost(context, hosts):
click.echo('\n'.join([host['hostname'] for host in hosts]))
@click.group('cdn')
def cdncli():
pass
@cdncli.command('add')
@forward_to_api('/cdns/add')
@click.argument('id')
@click.option('--name')
@click.option('--edge-server')
def addcdn(context):
click.echo("New CDN added")
@cdncli.command('list')
@forward_to_api('/cdns', {'page': 0, 'num_per_page': 0})
def listhost(context, cdns):
click.echo('\n'.join([cdn['id'] for cdn in cdns]))
@click.command('bootstrap')
@click.option('--save/--no-save', is_flag=True, default=False,
help="Save bootstrap information to database (default --no-save)")
@click.argument('hostname')
@click.pass_obj
def bootstrap(context, save, hostname):
try:
host_data = context.bootstrapper.lookup_host(hostname)
except BootstrapError:
logger.warning("No bootstrap information found for host '{}'".format(hostname))
return
logger.info(json.dumps(host_data, indent=4))
if save:
host = Host(**host_data)
host.save()
| {
"repo_name": "CacheBrowser/cachebrowser",
"path": "cachebrowser/cli.py",
"copies": "1",
"size": "2209",
"license": "mit",
"hash": 8313855389132703000,
"line_mean": 24.1022727273,
"line_max": 87,
"alpha_frac": 0.6622906292,
"autogenerated": false,
"ratio": 3.4195046439628483,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45817952731628486,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, partial
import warnings
from django import forms
from django.conf import settings
from django.forms.formsets import all_valid
from django.forms.models import (modelform_factory, modelformset_factory,
inlineformset_factory, BaseInlineFormSet)
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers
from django.contrib.admin.util import quote, unquote, flatten_fieldsets, get_deleted_objects, model_format_dict
from django.contrib.admin.templatetags.admin_static import static
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db import models, transaction, router
from django.db.models.constants import LOOKUP_SEP
from django.db.models.related import RelatedObject
from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
from django.db.models.sql.constants import QUERY_TERMS
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.response import SimpleTemplateResponse, TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.utils.encoding import force_text
HORIZONTAL, VERTICAL = 1, 2
# returns the <ul> class for a given radio_admin field
get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
class IncorrectLookupParameters(Exception):
pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
models.DateTimeField: {
'form_class': forms.SplitDateTimeField,
'widget': widgets.AdminSplitDateTime
},
models.DateField: {'widget': widgets.AdminDateWidget},
models.TimeField: {'widget': widgets.AdminTimeWidget},
models.TextField: {'widget': widgets.AdminTextareaWidget},
models.URLField: {'widget': widgets.AdminURLFieldWidget},
models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget},
models.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget},
models.CharField: {'widget': widgets.AdminTextInputWidget},
models.ImageField: {'widget': widgets.AdminFileWidget},
models.FileField: {'widget': widgets.AdminFileWidget},
}
csrf_protect_m = method_decorator(csrf_protect)
class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)):
"""Functionality common to both ModelAdmin and InlineAdmin."""
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = forms.ModelForm
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfield_overrides = {}
readonly_fields = ()
ordering = None
def __init__(self):
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides)
self.formfield_overrides = overrides
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
request = kwargs.pop("request", None)
# If the field specifies choices, we don't need to look for special
# admin widgets - we just need to use a select widget of some kind.
if db_field.choices:
return self.formfield_for_choice_field(db_field, request, **kwargs)
# ForeignKey or ManyToManyFields
if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
# Combine the field kwargs with any options for formfield_overrides.
# Make sure the passed in **kwargs override anything in
# formfield_overrides because **kwargs is more specific, and should
# always win.
if db_field.__class__ in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs)
# Get the correct formfield.
if isinstance(db_field, models.ForeignKey):
formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)
elif isinstance(db_field, models.ManyToManyField):
formfield = self.formfield_for_manytomany(db_field, request, **kwargs)
# For non-raw_id fields, wrap the widget with a wrapper that adds
# extra HTML -- the "add other" interface -- to the end of the
# rendered output. formfield can be None if it came from a
# OneToOneField with parent_link=True or a M2M intermediary.
if formfield and db_field.name not in self.raw_id_fields:
related_modeladmin = self.admin_site._registry.get(
db_field.rel.to)
can_add_related = bool(related_modeladmin and
related_modeladmin.has_add_permission(request))
formfield.widget = widgets.RelatedFieldWidgetWrapper(
formfield.widget, db_field.rel, self.admin_site,
can_add_related=can_add_related)
return formfield
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = dict(self.formfield_overrides[klass], **kwargs)
return db_field.formfield(**kwargs)
# For any other type of field, just call its formfield() method.
return db_field.formfield(**kwargs)
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
"""
Get a form Field for a database Field that has declared choices.
"""
# If the field is named as a radio_field, use a RadioSelect
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank = db_field.blank,
blank_choice=[('', _('None'))]
)
return db_field.formfield(**kwargs)
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ForeignKey.
"""
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel,
self.admin_site, using=db)
elif db_field.name in self.radio_fields:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
kwargs['empty_label'] = db_field.blank and _('None') or None
return db_field.formfield(**kwargs)
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.rel.through._meta.auto_created:
return None
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel,
self.admin_site, using=db)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
return db_field.formfield(**kwargs)
def _declared_fieldsets(self):
if self.fieldsets:
return self.fieldsets
elif self.fields:
return [(None, {'fields': self.fields})]
return None
declared_fieldsets = property(_declared_fieldsets)
def get_ordering(self, request):
"""
Hook for specifying field ordering.
"""
return self.ordering or () # otherwise we might try to *None, which is bad ;)
def get_readonly_fields(self, request, obj=None):
"""
Hook for specifying custom readonly fields.
"""
return self.readonly_fields
def get_prepopulated_fields(self, request, obj=None):
"""
Hook for specifying custom prepopulated fields.
"""
return self.prepopulated_fields
def queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_query_set()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
def lookup_allowed(self, lookup, value):
model = self.model
# Check FKey lookups that are allowed, so that popups produced by
# ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
# are allowed to work.
for l in model._meta.related_fkey_lookups:
for k, v in widgets.url_params_from_lookup_dict(l).items():
if k == lookup and v == value:
return True
parts = lookup.split(LOOKUP_SEP)
# Last term in lookup is a query term (__exact, __startswith etc)
# This term can be ignored.
if len(parts) > 1 and parts[-1] in QUERY_TERMS:
parts.pop()
# Special case -- foo__id__exact and foo__id queries are implied
# if foo has been specificially included in the lookup list; so
# drop __id if it is the last part. However, first we need to find
# the pk attribute name.
rel_name = None
for part in parts[:-1]:
try:
field, _, _, _ = model._meta.get_field_by_name(part)
except FieldDoesNotExist:
# Lookups on non-existants fields are ok, since they're ignored
# later.
return True
if hasattr(field, 'rel'):
model = field.rel.to
rel_name = field.rel.get_related_field().name
elif isinstance(field, RelatedObject):
model = field.model
rel_name = model._meta.pk.name
else:
rel_name = None
if rel_name and len(parts) > 1 and parts[-1] == rel_name:
parts.pop()
if len(parts) == 1:
return True
clean_lookup = LOOKUP_SEP.join(parts)
return clean_lookup in self.list_filter or clean_lookup == self.date_hierarchy
def has_add_permission(self, request):
"""
Returns True if the given request has permission to add an object.
Can be overriden by the user in subclasses.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
def has_change_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
"""
Returns True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overriden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.opts
return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission())
class ModelAdmin(BaseModelAdmin):
"Encapsulates all admin options and functionality for a given model."
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
list_per_page = 100
list_max_show_all = 200
list_editable = ()
search_fields = ()
date_hierarchy = None
save_as = False
save_on_top = False
paginator = Paginator
inlines = []
# Custom templates (designed to be over-ridden in subclasses)
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
# Actions
actions = []
action_form = helpers.ActionForm
actions_on_top = True
actions_on_bottom = False
actions_selection_counter = True
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(ModelAdmin, self).__init__()
def get_inline_instances(self, request, obj=None):
inline_instances = []
for inline_class in self.inlines:
inline = inline_class(self.model, self.admin_site)
if request:
if not (inline.has_add_permission(request) or
inline.has_change_permission(request, obj) or
inline.has_delete_permission(request, obj)):
continue
if not inline.has_add_permission(request):
inline.max_num = 0
inline_instances.append(inline)
return inline_instances
def get_urls(self):
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
urlpatterns = patterns('',
url(r'^$',
wrap(self.changelist_view),
name='%s_%s_changelist' % info),
url(r'^add/$',
wrap(self.add_view),
name='%s_%s_add' % info),
url(r'^(.+)/history/$',
wrap(self.history_view),
name='%s_%s_history' % info),
url(r'^(.+)/delete/$',
wrap(self.delete_view),
name='%s_%s_delete' % info),
url(r'^(.+)/$',
wrap(self.change_view),
name='%s_%s_change' % info),
)
return urlpatterns
def urls(self):
return self.get_urls()
urls = property(urls)
@property
def media(self):
extra = '' if settings.DEBUG else '.min'
js = [
'core.js',
'admin/RelatedObjectLookups.js',
'jquery%s.js' % extra,
'jquery.init.js'
]
if self.actions is not None:
js.append('actions%s.js' % extra)
if self.prepopulated_fields:
js.extend(['urlify.js', 'prepopulate%s.js' % extra])
if self.opts.get_ordered_objects():
js.extend(['getElementsBySelector.js', 'dom-drag.js' , 'admin/ordering.js'])
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def get_model_perms(self, request):
"""
Returns a dict of all perms for this model. This dict has the keys
``add``, ``change``, and ``delete`` mapping to the True/False for each
of those actions.
"""
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
}
def get_fieldsets(self, request, obj=None):
"Hook for specifying fieldsets for the add form."
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_form(request, obj)
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we pass None to be consistant with the
# default on modelform_factory
exclude = exclude or None
defaults = {
"form": self.form,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
"""
from django.contrib.admin.views.main import ChangeList
return ChangeList
def get_object(self, request, object_id):
"""
Returns an instance matching the primary key provided. ``None`` is
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
return queryset.get(pk=object_id)
except (model.DoesNotExist, ValidationError):
return None
def get_changelist_form(self, request, **kwargs):
"""
Returns a Form class for use in the Formset on the changelist page.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelform_factory(self.model, **defaults)
def get_changelist_formset(self, request, **kwargs):
"""
Returns a FormSet class for use on the changelist page if list_editable
is used.
"""
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelformset_factory(self.model,
self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults)
def get_formsets(self, request, obj=None):
for inline in self.get_inline_instances(request, obj):
yield inline.get_formset(request, obj)
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
return self.paginator(queryset, per_page, orphans, allow_empty_first_page)
def log_addition(self, request, object):
"""
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, ADDITION
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_text(object),
action_flag = ADDITION
)
def log_change(self, request, object, message):
"""
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, CHANGE
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(object).pk,
object_id = object.pk,
object_repr = force_text(object),
action_flag = CHANGE,
change_message = message
)
def log_deletion(self, request, object, object_repr):
"""
Log that an object will be deleted. Note that this method is called
before the deletion.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, DELETION
LogEntry.objects.log_action(
user_id = request.user.pk,
content_type_id = ContentType.objects.get_for_model(self.model).pk,
object_id = object.pk,
object_repr = object_repr,
action_flag = DELETION
)
def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk))
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is explicitally set to None that means that we don't
# want *any* actions enabled on this page.
from django.contrib.admin.views.main import IS_POPUP_VAR
if self.actions is None or IS_POPUP_VAR in request.GET:
return SortedDict()
actions = []
# Gather actions from the admin site first
for (name, func) in self.admin_site.actions:
description = getattr(func, 'short_description', name.replace('_', ' '))
actions.append((func, name, description))
# Then gather them from the model admin and all parent classes,
# starting with self and working back up.
for klass in self.__class__.mro()[::-1]:
class_actions = getattr(klass, 'actions', [])
# Avoid trying to iterate over None
if not class_actions:
continue
actions.extend([self.get_action(action) for action in class_actions])
# get_action might have returned None, so filter any of those out.
actions = filter(None, actions)
# Convert the actions into a SortedDict keyed by name.
actions = SortedDict([
(name, (func, name, desc))
for func, name, desc in actions
])
return actions
def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in six.itervalues(self.get_actions(request)):
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices
def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(action):
func = action
action = action.__name__
# Next, look for a method. Grab it off self.__class__ to get an unbound
# method instead of a bound one; this ensures that the calling
# conventions are the same for functions and methods.
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
# Finally, look for a named method on the admin site
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
if hasattr(func, 'short_description'):
description = func.short_description
else:
description = capfirst(action.replace('_', ' '))
return func, action, description
def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display
def get_list_display_links(self, request, list_display):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or not list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(list_display)[:1]
def get_list_filter(self, request):
"""
Returns a sequence containing the fields to be displayed as filters in
the right sidebar of the changelist page.
"""
return self.list_filter
def construct_change_message(self, request, form, formsets):
"""
Construct a change message from a changed object.
"""
change_message = []
if form.changed_data:
change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and')))
if formsets:
for formset in formsets:
for added_object in formset.new_objects:
change_message.append(_('Added %(name)s "%(object)s".')
% {'name': force_text(added_object._meta.verbose_name),
'object': force_text(added_object)})
for changed_object, changed_fields in formset.changed_objects:
change_message.append(_('Changed %(list)s for %(name)s "%(object)s".')
% {'list': get_text_list(changed_fields, _('and')),
'name': force_text(changed_object._meta.verbose_name),
'object': force_text(changed_object)})
for deleted_object in formset.deleted_objects:
change_message.append(_('Deleted %(name)s "%(object)s".')
% {'name': force_text(deleted_object._meta.verbose_name),
'object': force_text(deleted_object)})
change_message = ' '.join(change_message)
return change_message or _('No fields changed.')
def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % l for l in levels)
raise ValueError('Bad message level string: `%s`. '
'Possible values are: %s' % (level, levels_repr))
messages.add_message(request, level, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def save_form(self, request, form, change):
"""
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
"""
return form.save(commit=False)
def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
obj.save()
def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
obj.delete()
def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
def save_related(self, request, form, formsets, change):
"""
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.
"""
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change)
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
opts = self.model._meta
app_label = opts.app_label
ordered_objects = opts.get_ordered_objects()
context.update({
'add': add,
'change': change,
'has_add_permission': self.has_add_permission(request),
'has_change_permission': self.has_change_permission(request, obj),
'has_delete_permission': self.has_delete_permission(request, obj),
'has_file_field': True, # FIXME - this should check if form or formsets have a FileField,
'has_absolute_url': hasattr(self.model, 'get_absolute_url'),
'ordered_objects': ordered_objects,
'form_url': form_url,
'opts': opts,
'content_type_id': ContentType.objects.get_for_model(self.model).id,
'save_as': self.save_as,
'save_on_top': self.save_on_top,
})
if add and self.add_form_template is not None:
form_template = self.add_form_template
else:
form_template = self.change_form_template
return TemplateResponse(request, form_template or [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"admin/%s/change_form.html" % app_label,
"admin/change_form.html"
], context, current_app=self.admin_site.name)
def response_add(self, request, obj, post_url_continue='../%s/',
continue_editing_url=None, add_another_url=None,
hasperm_url=None, noperm_url=None):
"""
Determines the HttpResponse for the add_view stage.
:param request: HttpRequest instance.
:param obj: Object just added.
:param post_url_continue: Deprecated/undocumented.
:param continue_editing_url: URL where user will be redirected after
pressing 'Save and continue editing'.
:param add_another_url: URL where user will be redirected after
pressing 'Save and add another'.
:param hasperm_url: URL to redirect after a successful object creation
when the user has change permissions.
:param noperm_url: URL to redirect after a successful object creation
when the user has no change permissions.
"""
if post_url_continue != '../%s/':
warnings.warn("The undocumented 'post_url_continue' argument to "
"ModelAdmin.response_add() is deprecated, use the new "
"*_url arguments instead.", DeprecationWarning,
stacklevel=2)
opts = obj._meta
pk_value = obj.pk
app_label = opts.app_label
model_name = opts.module_name
site_name = self.admin_site.name
msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if "_continue" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict
self.message_user(request, msg)
if continue_editing_url is None:
continue_editing_url = 'admin:%s_%s_change' % (app_label, model_name)
url = reverse(continue_editing_url, args=(quote(pk_value),),
current_app=site_name)
if "_popup" in request.POST:
url += "?_popup=1"
return HttpResponseRedirect(url)
if "_popup" in request.POST:
return HttpResponse(
'<!DOCTYPE html><html><head><title></title></head><body>'
'<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script></body></html>' % \
# escape() calls force_text.
(escape(pk_value), escapejs(obj)))
elif "_addanother" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.') % msg_dict
self.message_user(request, msg)
if add_another_url is None:
add_another_url = 'admin:%s_%s_add' % (app_label, model_name)
url = reverse(add_another_url, current_app=site_name)
return HttpResponseRedirect(url)
else:
msg = _('The %(name)s "%(obj)s" was added successfully.') % msg_dict
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
if hasperm_url is None:
hasperm_url = 'admin:%s_%s_changelist' % (app_label, model_name)
url = reverse(hasperm_url, current_app=site_name)
else:
if noperm_url is None:
noperm_url = 'admin:index'
url = reverse(noperm_url, current_app=site_name)
return HttpResponseRedirect(url)
def response_change(self, request, obj, continue_editing_url=None,
save_as_new_url=None, add_another_url=None,
hasperm_url=None, noperm_url=None):
"""
Determines the HttpResponse for the change_view stage.
:param request: HttpRequest instance.
:param obj: Object just modified.
:param continue_editing_url: URL where user will be redirected after
pressing 'Save and continue editing'.
:param save_as_new_url: URL where user will be redirected after pressing
'Save as new' (when applicable).
:param add_another_url: URL where user will be redirected after pressing
'Save and add another'.
:param hasperm_url: URL to redirect after a successful object edition when
the user has change permissions.
:param noperm_url: URL to redirect after a successful object edition when
the user has no change permissions.
"""
opts = obj._meta
app_label = opts.app_label
model_name = opts.module_name
site_name = self.admin_site.name
verbose_name = opts.verbose_name
# Handle proxy models automatically created by .only() or .defer().
# Refs #14529
if obj._deferred:
opts_ = opts.proxy_for_model._meta
verbose_name = opts_.verbose_name
model_name = opts_.module_name
msg_dict = {'name': force_text(verbose_name), 'obj': force_text(obj)}
if "_continue" in request.POST:
msg = _('The %(name)s "%(obj)s" was changed successfully. You may edit it again below.') % msg_dict
self.message_user(request, msg)
if continue_editing_url is None:
continue_editing_url = 'admin:%s_%s_change' % (app_label, model_name)
url = reverse(continue_editing_url, args=(quote(obj.pk),),
current_app=site_name)
if "_popup" in request.POST:
url += "?_popup=1"
return HttpResponseRedirect(url)
elif "_saveasnew" in request.POST:
msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict
self.message_user(request, msg)
if save_as_new_url is None:
save_as_new_url = 'admin:%s_%s_change' % (app_label, model_name)
url = reverse(save_as_new_url, args=(quote(obj.pk),),
current_app=site_name)
return HttpResponseRedirect(url)
elif "_addanother" in request.POST:
msg = _('The %(name)s "%(obj)s" was changed successfully. You may add another %(name)s below.') % msg_dict
self.message_user(request, msg)
if add_another_url is None:
add_another_url = 'admin:%s_%s_add' % (app_label, model_name)
url = reverse(add_another_url, current_app=site_name)
return HttpResponseRedirect(url)
else:
msg = _('The %(name)s "%(obj)s" was changed successfully.') % msg_dict
self.message_user(request, msg)
# Figure out where to redirect. If the user has change permission,
# redirect to the change-list page for this object. Otherwise,
# redirect to the admin index.
if self.has_change_permission(request, None):
if hasperm_url is None:
hasperm_url = 'admin:%s_%s_changelist' % (app_label,
model_name)
url = reverse(hasperm_url, current_app=site_name)
else:
if noperm_url is None:
noperm_url = 'admin:index'
url = reverse(noperm_url, current_app=site_name)
return HttpResponseRedirect(url)
def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func, name, description = self.get_actions(request)[action]
# Get the list of selected PKs. If nothing's selected, we can't
# perform an action on it, so bail. Except we want to perform
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
return None
if not select_across:
# Perform the action only on the selected objects
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
# Actions may return an HttpResponse, which will be used as the
# response from the POST. If not, we'll be a good little HTTP
# citizen and redirect back to the changelist page.
if isinstance(response, HttpResponse):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _("No action selected.")
self.message_user(request, msg)
return None
@csrf_protect_m
@transaction.commit_on_success
def add_view(self, request, form_url='', extra_context=None):
"The 'add' admin view for this model."
model = self.model
opts = model._meta
if not self.has_add_permission(request):
raise PermissionDenied
ModelForm = self.get_form(request)
formsets = []
inline_instances = self.get_inline_instances(request, None)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES)
if form.is_valid():
new_object = self.save_form(request, form, change=False)
form_validated = True
else:
form_validated = False
new_object = self.model()
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, False)
self.save_related(request, form, formsets, False)
self.log_addition(request, new_object)
return self.response_add(request, new_object)
else:
# Prepare the dict of initial data from the request.
# We have to special-case M2Ms as a list of comma-separated PKs.
initial = dict(request.GET.items())
for k in initial:
try:
f = opts.get_field(k)
except models.FieldDoesNotExist:
continue
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
form = ModelForm(initial=initial)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=self.model(), prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
self.get_prepopulated_fields(request),
self.get_readonly_fields(request),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request))
readonly = list(inline.get_readonly_fields(request))
prepopulated = dict(inline.get_prepopulated_fields(request))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Add %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'media': media,
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url=form_url, add=True)
@csrf_protect_m
@transaction.commit_on_success
def change_view(self, request, object_id, form_url='', extra_context=None):
"The 'change' admin view for this model."
model = self.model
opts = model._meta
obj = self.get_object(request, unquote(object_id))
if not self.has_change_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
if request.method == 'POST' and "_saveasnew" in request.POST:
return self.add_view(request, form_url=reverse('admin:%s_%s_add' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
ModelForm = self.get_form(request, obj)
formsets = []
inline_instances = self.get_inline_instances(request, obj)
if request.method == 'POST':
form = ModelForm(request.POST, request.FILES, instance=obj)
if form.is_valid():
form_validated = True
new_object = self.save_form(request, form, change=True)
else:
form_validated = False
new_object = obj
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, new_object), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, True)
self.save_related(request, form, formsets, True)
change_message = self.construct_change_message(request, form, formsets)
self.log_change(request, new_object, change_message)
return self.response_change(request, new_object)
else:
form = ModelForm(instance=obj)
prefixes = {}
for FormSet, inline in zip(self.get_formsets(request, obj), inline_instances):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
self.get_prepopulated_fields(request, obj),
self.get_readonly_fields(request, obj),
model_admin=self)
media = self.media + adminForm.media
inline_admin_formsets = []
for inline, formset in zip(inline_instances, formsets):
fieldsets = list(inline.get_fieldsets(request, obj))
readonly = list(inline.get_readonly_fields(request, obj))
prepopulated = dict(inline.get_prepopulated_fields(request, obj))
inline_admin_formset = helpers.InlineAdminFormSet(inline, formset,
fieldsets, prepopulated, readonly, model_admin=self)
inline_admin_formsets.append(inline_admin_formset)
media = media + inline_admin_formset.media
context = {
'title': _('Change %s') % force_text(opts.verbose_name),
'adminform': adminForm,
'object_id': object_id,
'original': obj,
'is_popup': "_popup" in request.REQUEST,
'media': media,
'inline_admin_formsets': inline_admin_formsets,
'errors': helpers.AdminErrorList(form, formsets),
'app_label': opts.app_label,
}
context.update(extra_context or {})
return self.render_change_form(request, context, change=True, obj=obj, form_url=form_url)
@csrf_protect_m
def changelist_view(self, request, extra_context=None):
"""
The 'change list' admin view for this model.
"""
from django.contrib.admin.views.main import ERROR_FLAG
opts = self.model._meta
app_label = opts.app_label
if not self.has_change_permission(request, None):
raise PermissionDenied
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
list_filter = self.get_list_filter(request)
# Check actions to see if any are available on this changelist
actions = self.get_actions(request)
if actions:
# Add the action checkboxes if there are any actions available.
list_display = ['action_checkbox'] + list(list_display)
ChangeList = self.get_changelist(request)
try:
cl = ChangeList(request, self.model, list_display,
list_display_links, list_filter, self.date_hierarchy,
self.search_fields, self.list_select_related,
self.list_per_page, self.list_max_show_all, self.list_editable,
self)
except IncorrectLookupParameters:
# Wacky lookup parameters were given, so redirect to the main
# changelist page, without parameters, and pass an 'invalid=1'
# parameter via the query string. If wacky parameters were given
# and the 'invalid=1' parameter was already in the query string,
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET.keys():
return SimpleTemplateResponse('admin/invalid_setup.html', {
'title': _('Database error'),
})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
# edit. Try to look up an action or confirmation first, but if this
# isn't an action the POST will fall through to the bulk edit check,
# below.
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg)
action_failed = True
# Actions with confirmation
if (actions and request.method == 'POST' and
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
if response:
return response
else:
action_failed = True
# If we're allowing changelist editing, we need to construct a formset
# for the changelist given all the fields to be edited. Then we'll
# use the formset to validate/process POSTed data.
formset = cl.formset = None
# Handle POSTed bulk-edit data.
if (request.method == "POST" and cl.list_editable and
'_save' in request.POST and not action_failed):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
self.save_related(request, form, formsets=[], change=True)
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
if changecount == 1:
name = force_text(opts.verbose_name)
else:
name = force_text(opts.verbose_name_plural)
msg = ungettext("%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount) % {'count': changecount,
'name': name,
'obj': force_text(obj)}
self.message_user(request, msg)
return HttpResponseRedirect(request.get_full_path())
# Handle GET -- construct a formset for display.
elif cl.list_editable:
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
# Build the list of media to be used by the formset.
if formset:
media = self.media + formset.media
else:
media = self.media
# Build the action form and populate it with available actions.
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
else:
action_form = None
selection_note_all = ungettext('%(total_count)s selected',
'All %(total_count)s selected', cl.result_count)
context = {
'module_name': force_text(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'is_popup': cl.is_popup,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'app_label': app_label,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
}
context.update(extra_context or {})
return TemplateResponse(request, self.change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
], context, current_app=self.admin_site.name)
@csrf_protect_m
@transaction.commit_on_success
def delete_view(self, request, object_id, extra_context=None):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
obj = self.get_object(request, unquote(object_id))
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(deleted_objects, perms_needed, protected) = get_deleted_objects(
[obj], opts, request.user, self.admin_site, using)
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
obj_display = force_text(obj)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)})
if not self.has_change_permission(request, None):
return HttpResponseRedirect(reverse('admin:index',
current_app=self.admin_site.name))
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' %
(opts.app_label, opts.module_name),
current_app=self.admin_site.name))
object_name = force_text(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
"title": title,
"object_name": object_name,
"object": obj,
"deleted_objects": deleted_objects,
"perms_lacking": perms_needed,
"protected": protected,
"opts": opts,
"app_label": app_label,
}
context.update(extra_context or {})
return TemplateResponse(request, self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, current_app=self.admin_site.name)
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
model = self.model
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(
object_id = unquote(object_id),
content_type__id__exact = ContentType.objects.get_for_model(model).id
).select_related().order_by('action_time')
# If no history was found, see whether this object even exists.
obj = get_object_or_404(model, pk=unquote(object_id))
context = {
'title': _('Change history: %s') % force_text(obj),
'action_list': action_list,
'module_name': capfirst(force_text(opts.verbose_name_plural)),
'object': obj,
'app_label': app_label,
'opts': opts,
}
context.update(extra_context or {})
return TemplateResponse(request, self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context, current_app=self.admin_site.name)
class InlineModelAdmin(BaseModelAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``name`` to specify the attribute name of the ``ForeignKey`` from
``model`` to its parent. This is required if ``model`` has more than one
``ForeignKey`` to its parent.
"""
model = None
fk_name = None
formset = BaseInlineFormSet
extra = 3
max_num = None
template = None
verbose_name = None
verbose_name_plural = None
can_delete = True
def __init__(self, parent_model, admin_site):
self.admin_site = admin_site
self.parent_model = parent_model
self.opts = self.model._meta
super(InlineModelAdmin, self).__init__()
if self.verbose_name is None:
self.verbose_name = self.model._meta.verbose_name
if self.verbose_name_plural is None:
self.verbose_name_plural = self.model._meta.verbose_name_plural
@property
def media(self):
extra = '' if settings.DEBUG else '.min'
js = ['jquery%s.js' % extra, 'jquery.init.js', 'inlines%s.js' % extra]
if self.prepopulated_fields:
js.extend(['urlify.js', 'prepopulate%s.js' % extra])
if self.filter_vertical or self.filter_horizontal:
js.extend(['SelectBox.js', 'SelectFilter2.js'])
return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def get_formset(self, request, obj=None, **kwargs):
"""Returns a BaseInlineFormSet class for use in admin add/change views."""
if self.declared_fieldsets:
fields = flatten_fieldsets(self.declared_fieldsets)
else:
fields = None
if self.exclude is None:
exclude = []
else:
exclude = list(self.exclude)
exclude.extend(self.get_readonly_fields(request, obj))
if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# InlineModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we use None, since that's the actual
# default
exclude = exclude or None
can_delete = self.can_delete and self.has_delete_permission(request, obj)
defaults = {
"form": self.form,
"formset": self.formset,
"fk_name": self.fk_name,
"fields": fields,
"exclude": exclude,
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
"extra": self.extra,
"max_num": self.max_num,
"can_delete": can_delete,
}
defaults.update(kwargs)
return inlineformset_factory(self.parent_model, self.model, **defaults)
def get_fieldsets(self, request, obj=None):
if self.declared_fieldsets:
return self.declared_fieldsets
form = self.get_formset(request, obj).form
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def queryset(self, request):
queryset = super(InlineModelAdmin, self).queryset(request)
if not self.has_change_permission(request):
queryset = queryset.none()
return queryset
def has_add_permission(self, request):
if self.opts.auto_created:
# We're checking the rights to an auto-created intermediate model,
# which doesn't have its own individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request)
return request.user.has_perm(
self.opts.app_label + '.' + self.opts.get_add_permission())
def has_change_permission(self, request, obj=None):
opts = self.opts
if opts.auto_created:
# The model was auto-created as intermediary for a
# ManyToMany-relationship, find the target model
for field in opts.fields:
if field.rel and field.rel.to != self.parent_model:
opts = field.rel.to._meta
break
return request.user.has_perm(
opts.app_label + '.' + opts.get_change_permission())
def has_delete_permission(self, request, obj=None):
if self.opts.auto_created:
# We're checking the rights to an auto-created intermediate model,
# which doesn't have its own individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request, obj)
return request.user.has_perm(
self.opts.app_label + '.' + self.opts.get_delete_permission())
class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularInline(InlineModelAdmin):
template = 'admin/edit_inline/tabular.html'
| {
"repo_name": "chrisfranzen/django",
"path": "django/contrib/admin/options.py",
"copies": "2",
"size": "67913",
"license": "bsd-3-clause",
"hash": 44911258519806300,
"line_mean": 42.7020592021,
"line_max": 167,
"alpha_frac": 0.5866034485,
"autogenerated": false,
"ratio": 4.362345837615622,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5948949286115622,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper
from django.apps import apps
from django.conf import settings
from django.contrib.admin import ModelAdmin, actions
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.db.models.base import ModelBase
from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.urls import NoReverseMatch, reverse
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
system_check_errors = []
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Django site admin')
# Text to put in each page's <h1>.
site_header = ugettext_lazy('Django administration')
# Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration')
# URL for the "View site" link at the top of each admin page.
site_url = '/'
_empty_value_display = '-'
login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
def __init__(self, name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured('The model %s is abstract, so it '
'cannot be registered with admin.' % model.__name__)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
# Instantiate the admin class to save in the registry
admin_obj = admin_class(model, self)
if admin_class is not ModelAdmin and settings.DEBUG:
system_check_errors.extend(admin_obj.check())
self._registry[model] = admin_obj
def unregister(self, model_or_iterable):
"""
Unregisters the given model(s).
If a model isn't already registered, this will raise NotRegistered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotRegistered('The model %s is not registered' % model.__name__)
del self._registry[model]
def is_registered(self, model):
"""
Check if a model class is registered with this `AdminSite`.
"""
return model in self._registry
def add_action(self, action, name=None):
"""
Register an action to be available globally.
"""
name = name or action.__name__
self._actions[name] = action
self._global_actions[name] = action
def disable_action(self, name):
"""
Disable a globally-registered action. Raises KeyError for invalid names.
"""
del self._actions[name]
def get_action(self, name):
"""
Explicitly get a registered global action whether it's enabled or
not. Raises KeyError for invalid names.
"""
return self._global_actions[name]
@property
def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
return six.iteritems(self._actions)
@property
def empty_value_display(self):
return self._empty_value_display
@empty_value_display.setter
def empty_value_display(self, empty_value_display):
self._empty_value_display = empty_value_display
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
return request.user.is_active and request.user.is_staff
def admin_view(self, view, cacheable=False):
"""
Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You'll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import url
urls = super(MyAdminSite, self).get_urls()
urls += [
url(r'^my_view/$', self.admin_view(some_view))
]
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.
"""
def inner(request, *args, **kwargs):
if not self.has_permission(request):
if request.path == reverse('admin:logout', current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
# Inner import to prevent django.contrib.admin (app) from
# importing django.contrib.auth.models.User (unrelated model).
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
request.get_full_path(),
reverse('admin:login', current_app=self.name)
)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import url, include
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
wrapper.admin_site = self
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = [
url(r'^$', wrap(self.index), name='index'),
url(r'^login/$', self.login, name='login'),
url(r'^logout/$', wrap(self.logout), name='logout'),
url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
name='view_on_site'),
]
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
for model, model_admin in self._registry.items():
urlpatterns += [
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
# If there were ModelAdmins registered, we should have a list of app
# labels for which we need to allow access to the app_index view,
if valid_app_labels:
regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
urlpatterns += [
url(regex, wrap(self.app_index), name='app_list'),
]
return urlpatterns
@property
def urls(self):
return self.get_urls(), 'admin', self.name
def each_context(self, request):
"""
Returns a dictionary of variables to put in the template context for
*every* page in the admin site.
For sites running on a subpath, use the SCRIPT_NAME value if site_url
hasn't been customized.
"""
script_name = request.META['SCRIPT_NAME']
site_url = script_name if self.site_url == '/' and script_name else self.site_url
return {
'site_title': self.site_title,
'site_header': self.site_header,
'site_url': site_url,
'has_permission': self.has_permission(request),
'available_apps': self.get_app_list(request),
}
def password_change(self, request, extra_context=None):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.admin.forms import AdminPasswordChangeForm
from django.contrib.auth.views import password_change
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {
'password_change_form': AdminPasswordChangeForm,
'post_change_redirect': url,
'extra_context': dict(self.each_context(request), **(extra_context or {})),
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
request.current_app = self.name
return password_change(request, **defaults)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import password_change_done
defaults = {
'extra_context': dict(self.each_context(request), **(extra_context or {})),
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
request.current_app = self.name
return password_change_done(request, **defaults)
def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
"""
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import logout
defaults = {
'extra_context': dict(
self.each_context(request),
# Since the user isn't logged out at this point, the value of
# has_permission must be overridden.
has_permission=False,
**(extra_context or {})
),
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
request.current_app = self.name
return logout(request, **defaults)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
if request.method == 'GET' and self.has_permission(request):
# Already logged-in, redirect to admin index
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
from django.contrib.auth.views import login
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.admin.forms eventually imports User.
from django.contrib.admin.forms import AdminAuthenticationForm
context = dict(self.each_context(request),
title=_('Log in'),
app_path=request.get_full_path(),
)
if (REDIRECT_FIELD_NAME not in request.GET and
REDIRECT_FIELD_NAME not in request.POST):
context[REDIRECT_FIELD_NAME] = reverse('admin:index', current_app=self.name)
context.update(extra_context or {})
defaults = {
'extra_context': context,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'admin/login.html',
}
request.current_app = self.name
return login(request, **defaults)
def _build_app_dict(self, request, label=None):
"""
Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app.
"""
app_dict = {}
if label:
models = {
m: m_a for m, m_a in self._registry.items()
if m._meta.app_label == label
}
else:
models = self._registry
for model, model_admin in models.items():
app_label = model._meta.app_label
has_module_perms = model_admin.has_module_permission(request)
if not has_module_perms:
if label:
raise PermissionDenied
continue
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True not in perms.values():
continue
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change'):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add'):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': apps.get_app_config(app_label).verbose_name,
'app_label': app_label,
'app_url': reverse(
'admin:app_list',
kwargs={'app_label': app_label},
current_app=self.name,
),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if label:
return app_dict.get(label)
return app_dict
def get_app_list(self, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""
app_dict = self._build_app_dict(request)
# Sort the apps alphabetically.
app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
return app_list
@never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_list = self.get_app_list(request)
context = dict(
self.each_context(request),
title=self.index_title,
app_list=app_list,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.index_template or
'admin/index.html', context)
def app_index(self, request, app_label, extra_context=None):
app_dict = self._build_app_dict(request, app_label)
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
app_name = apps.get_app_config(app_label).verbose_name
context = dict(self.each_context(request),
title=_('%(app)s administration') % {'app': app_name},
app_list=[app_dict],
app_label=app_label,
)
context.update(extra_context or {})
request.current_app = self.name
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
| {
"repo_name": "yephper/django",
"path": "django/contrib/admin/sites.py",
"copies": "1",
"size": "20295",
"license": "bsd-3-clause",
"hash": -3805233656627014000,
"line_mean": 37.9507874016,
"line_max": 109,
"alpha_frac": 0.577383592,
"autogenerated": false,
"ratio": 4.502995340581318,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0006794785232588018,
"num_lines": 508
} |
from functools import update_wrapper
from django.contrib import admin
from django.db import models
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Action(models.Model):
name = models.CharField(max_length=50, primary_key=True)
description = models.CharField(max_length=70)
def __str__(self):
return self.name
class ActionAdmin(admin.ModelAdmin):
"""
A ModelAdmin for the Action model that changes the URL of the add_view
to '<app name>/<model name>/!add/'
The Action model has a CharField PK.
"""
list_display = ('name', 'description')
def remove_url(self, name):
"""
Remove all entries named 'name' from the ModelAdmin instance URL
patterns list
"""
return [url for url in super(ActionAdmin, self).get_urls() if url.name != name]
def get_urls(self):
# Add the URL of our custom 'add_view' view to the front of the URLs
# list. Remove the existing one(s) first
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
view_name = '%s_%s_add' % info
return [
url(r'^!add/$', wrap(self.add_view), name=view_name),
] + self.remove_url(view_name)
class Person(models.Model):
name = models.CharField(max_length=20)
class PersonAdmin(admin.ModelAdmin):
def response_post_save_add(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_history', args=[obj.pk]))
def response_post_save_change(self, request, obj):
return HttpResponseRedirect(
reverse('admin:admin_custom_urls_person_delete', args=[obj.pk]))
class Car(models.Model):
name = models.CharField(max_length=20)
class CarAdmin(admin.ModelAdmin):
def response_add(self, request, obj, post_url_continue=None):
return super(CarAdmin, self).response_add(
request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk]))
site = admin.AdminSite(name='admin_custom_urls')
site.register(Action, ActionAdmin)
site.register(Person, PersonAdmin)
site.register(Car, CarAdmin)
| {
"repo_name": "yephper/django",
"path": "tests/admin_custom_urls/models.py",
"copies": "1",
"size": "2583",
"license": "bsd-3-clause",
"hash": 4757473671694404000,
"line_mean": 29.1204819277,
"line_max": 106,
"alpha_frac": 0.6442121564,
"autogenerated": false,
"ratio": 3.8959276018099547,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002469302929570968,
"num_lines": 83
} |
from functools import update_wrapper, wraps
from django_pyres.conf import settings
from django import db
from .core import pyres
try:
# This is prefered in >1.6
close_connections = db.close_old_connections
except AttributeError:
# This is deprecated in 1.6 and removed in 1.8
close_connections = db.close_connection
def reset_db_connection(func):
def wrapper(*args, **kwargs):
""" Because forked processes using connection pool
can throw errors, close db to reinitialize inside
child process. """
if settings.PYRES_USE_QUEUE:
close_connections()
result = func(*args, **kwargs)
if settings.PYRES_USE_QUEUE:
close_connections()
return result
update_wrapper(wrapper, func)
return wrapper
class Job(object):
"""
Class that wraps a function to enqueue in pyres
"""
_resque_conn = pyres
def __init__(self, func, queue):
self.func = reset_db_connection(func)
#self.priority = priority
# Allow this class to be called by pyres
self.queue = str(queue)
self.perform = self.__call__
# Wrap func
update_wrapper(self, func)
# _resque wraps the underlying resque connection and delays initialization
# until needed
@property
def _resque(self):
return self._resque_conn
@_resque.setter # NOQA
def _resque(self, val):
self._resque_conn = val
def enqueue(self, *args, **kwargs):
if settings.PYRES_USE_QUEUE:
queue = kwargs.pop('queue', self.queue)
if kwargs:
raise Exception("Cannot pass kwargs to enqueued tasks")
class_str = '%s.%s' % (self.__module__, self.__name__)
self._resque.enqueue_from_string(class_str, queue, *args)
else:
return self(*args, **kwargs)
def enqueue_at(self, dt, *args, **kwargs):
queue = kwargs.pop('queue', self.queue)
if kwargs:
raise Exception('Cannot pass kwargs to enqueued tasks')
class_str = '%s.%s' % (self.__module__, self.__name__)
self._resque.enqueue_at_from_string(dt, class_str, queue, *args)
def __call__(self, *args, **kwargs):
try:
return self.func(*args, **kwargs)
except:
if hasattr(settings, 'RAVEN_CONFIG'):
from raven.contrib.django.models import client
client.captureException()
raise
def __repr__(self):
return 'Job(func=%s, queue=%s)' % (self.func, self.queue)
def job(queue, cls=Job):
def _task(f):
return cls(f, queue)
return _task
| {
"repo_name": "briandailey/django-pyres",
"path": "django_pyres/decorators.py",
"copies": "1",
"size": "2658",
"license": "bsd-3-clause",
"hash": 7859707732460116000,
"line_mean": 29.5517241379,
"line_max": 78,
"alpha_frac": 0.5981941309,
"autogenerated": false,
"ratio": 3.920353982300885,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5018548113200885,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, wraps
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.resources import ModelResource
class ModelResourceUtils(ModelResource):
@classmethod
def get_fields(cls, fields=None, excludes=None):
"""
This allows using a custom meta class option `list_exclude_fields` using
which you can exclude certains fields only from list view, but still
include them in detail view.
"""
final_fields = super(ModelResource, cls).get_fields(fields=fields,
excludes=excludes)
if getattr(cls._meta, 'list_exclude_fields', None):
for field_name in final_fields:
if field_name in cls._meta.list_exclude_fields:
final_fields[field_name].use_in = "detail"
return final_fields
def wrap_view(self, view):
"""
Ensure that the decorated function looks like the original view function
using update_wrapper from the functools package
"""
wrapper = super(ModelResourceUtils, self).wrap_view(view)
return update_wrapper(wrapper, getattr(self, view))
def dehydrate(self, bundle):
"""
You can restrict the api response to send only certain fields by
using include_fields/exclude_fields query parameters.
"""
include_fields = bundle.request.GET.get('include_fields', None)
exclude_fields = bundle.request.GET.get('exclude_fields', [])
if not exclude_fields and not include_fields:
return bundle
else:
if not include_fields:
exclude_fields = exclude_fields.split(",")
include_fields = set(bundle.data.keys())\
.difference(exclude_fields)
else:
include_fields = include_fields.split(",")
bundle.data = {k: bundle.data[k] for k in include_fields}
return bundle
def alter_list_data_to_serialize(self, request, data):
"""
Restrict the api response to only contain the metadata by using
querystring meta_only
"""
if request.GET.get('meta_only'):
return {'meta': data['meta']}
return data
@staticmethod
def get_view_name(request):
return request.resolver_match.url_name
def get_model_name(self):
return self._meta.queryset.model.__name__
def get_app_label(self):
return self._meta.queryset.model._meta.app_label
def get_filters(self, request, **kwargs):
filters = {}
kwargs = self.remove_api_resource_names(kwargs)
if hasattr(request, 'GET'):
# Grab a mutable copy.
filters = request.GET.copy()
filters.update(kwargs)
return self.build_filters(filters=filters)
def paginate(self, request, objects):
"""
Allow custom api's to use paginator defined for the resource
"""
paginator = self._meta.paginator_class(request.GET, objects,
resource_uri=self.get_resource_uri(),
limit=self._meta.limit,
max_limit=self._meta.max_limit,
collection_name=self._meta.collection_name)
to_be_serialized = paginator.page()
return to_be_serialized
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart/form-data'):
multipart_data = request.POST.copy()
multipart_data.update(request.FILES)
return multipart_data
return super(MultipartResource, self).deserialize(request, data, format)
def put_detail(self, request, **kwargs):
if request.META.get('CONTENT_TYPE', '').startswith('multipart/form-data') and not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).put_detail(request, **kwargs)
def patch_detail(self, request, **kwargs):
if request.META.get('CONTENT_TYPE', '').startswith('multipart/form-data') and not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).patch_detail(request, **kwargs)
def authorize_api(resource, allowed_methods, custom_auth=None):
"""
Decorator to be used with custom api views to perform method_check,
throttle check and authentication.
"""
def _decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
resource.method_check(request, allowed_methods)
resource.throttle_check(request)
resource_auth = resource._meta.authentication
if custom_auth:
resource._meta.authentication = custom_auth
try:
resource.is_authenticated(request)
except ImmediateHttpResponse, ex:
return ex.response
finally:
resource._meta.authentication = resource_auth
return view_func(request, *args, **kwargs)
return _wrapped_view
return _decorator | {
"repo_name": "kgritesh/tastypie-utils",
"path": "resources.py",
"copies": "1",
"size": "5489",
"license": "mit",
"hash": -9178467912291888000,
"line_mean": 34.1923076923,
"line_max": 116,
"alpha_frac": 0.5966478411,
"autogenerated": false,
"ratio": 4.593305439330544,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5689953280430544,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, wraps
from twisted.internet import defer
from lacli.log import getLogger
class login_async(object):
def __init__(self, f, obj=None):
self.f = f
self.obj = obj
update_wrapper(self, self.f)
def __get__(self, obj, cls):
return wraps(self.f)(login(self.f, obj))
def dologin(self, prefs):
return self.obj.registry.cmd.login.login_async(
prefs.get('user'), prefs.get('pass'))
@defer.inlineCallbacks
def loginfirst(self, prefs, *args, **kwargs):
try:
yield self.dologin(prefs)
r = yield self.f(self.obj, *args, **kwargs)
defer.returnValue(r)
except Exception:
getLogger().debug("unhandled error in login decorator",
exc_info=True)
raise
def __call__(self, *args, **kwargs):
if len(args) > 0:
if self.obj is None:
self.obj = args[0]
args = args[1:]
elif self.obj == args[0]:
args = args[1:]
prefs = None
if self.obj.registry.session:
prefs = self.obj.registry.session.prefs
if not prefs:
prefs = self.obj.registry.init_prefs()
if not self.obj.session or self.obj.registry.cmd.login.email is None:
return self.loginfirst(prefs, *args, **kwargs)
return self.f(self.obj, *args, **kwargs)
class login(login_async):
def __init__(self, *args, **kwargs):
super(login, self).__init__(*args, **kwargs)
def dologin(self, prefs):
if self.obj.batch:
self.obj.registry.cmd.login.login_batch(
prefs.get('user'), prefs.get('pass'))
else:
cmdline = [prefs[a] for a in ['user', 'pass']
if prefs.get(a)]
self.obj.registry.cmd.username = prefs['user']
self.obj.registry.cmd.password = prefs['pass']
self.obj.registry.cmd.do_login(" ".join(cmdline))
def loginfirst(self, prefs, *args, **kwargs):
self.dologin(prefs)
return self.f(self.obj, *args, **kwargs)
| {
"repo_name": "longaccess/longaccess-client",
"path": "lacli/loginutil.py",
"copies": "1",
"size": "2168",
"license": "apache-2.0",
"hash": 4437088003700212700,
"line_mean": 31.8484848485,
"line_max": 77,
"alpha_frac": 0.5498154982,
"autogenerated": false,
"ratio": 3.783595113438045,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9833410611638045,
"avg_score": 0,
"num_lines": 66
} |
from functools import update_wrapper, wraps
from unittest import TestCase
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test,
)
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
from django.middleware.clickjacking import XFrameOptionsMiddleware
from django.test import SimpleTestCase
from django.utils.decorators import method_decorator
from django.utils.functional import keep_lazy, keep_lazy_text, lazy
from django.utils.safestring import mark_safe
from django.views.decorators.cache import (
cache_control, cache_page, never_cache,
)
from django.views.decorators.clickjacking import (
xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin,
)
from django.views.decorators.http import (
condition, require_GET, require_http_methods, require_POST, require_safe,
)
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
def fully_decorated(request):
"""Expected __doc__"""
return HttpResponse('<html><body>dummy</body></html>')
fully_decorated.anything = "Expected __dict__"
def compose(*functions):
# compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs))
functions = list(reversed(functions))
def _inner(*args, **kwargs):
result = functions[0](*args, **kwargs)
for f in functions[1:]:
result = f(result)
return result
return _inner
full_decorator = compose(
# django.views.decorators.http
require_http_methods(["GET"]),
require_GET,
require_POST,
require_safe,
condition(lambda r: None, lambda r: None),
# django.views.decorators.vary
vary_on_headers('Accept-language'),
vary_on_cookie,
# django.views.decorators.cache
cache_page(60 * 15),
cache_control(private=True),
never_cache,
# django.contrib.auth.decorators
# Apply user_passes_test twice to check #9474
user_passes_test(lambda u: True),
login_required,
permission_required('change_world'),
# django.contrib.admin.views.decorators
staff_member_required,
# django.utils.functional
keep_lazy(HttpResponse),
keep_lazy_text,
lazy,
# django.utils.safestring
mark_safe,
)
fully_decorated = full_decorator(fully_decorated)
class DecoratorsTest(TestCase):
def test_attributes(self):
"""
Built-in decorators set certain attributes of the wrapped function.
"""
self.assertEqual(fully_decorated.__name__, 'fully_decorated')
self.assertEqual(fully_decorated.__doc__, 'Expected __doc__')
self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__')
def test_user_passes_test_composition(self):
"""
The user_passes_test decorator can be applied multiple times (#9474).
"""
def test1(user):
user.decorators_applied.append('test1')
return True
def test2(user):
user.decorators_applied.append('test2')
return True
def callback(request):
return request.user.decorators_applied
callback = user_passes_test(test1)(callback)
callback = user_passes_test(test2)(callback)
class DummyUser:
pass
class DummyRequest:
pass
request = DummyRequest()
request.user = DummyUser()
request.user.decorators_applied = []
response = callback(request)
self.assertEqual(response, ['test2', 'test1'])
def test_cache_page(self):
def my_view(request):
return "response"
my_view_cached = cache_page(123)(my_view)
self.assertEqual(my_view_cached(HttpRequest()), "response")
my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
self.assertEqual(my_view_cached2(HttpRequest()), "response")
def test_require_safe_accepts_only_safe_methods(self):
"""
Test for the require_safe decorator.
A view returns either a response or an exception.
Refs #15637.
"""
def my_view(request):
return HttpResponse("OK")
my_safe_view = require_safe(my_view)
request = HttpRequest()
request.method = 'GET'
self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = 'HEAD'
self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = 'POST'
self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = 'PUT'
self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = 'DELETE'
self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
# For testing method_decorator, a decorator that assumes a single argument.
# We will get type arguments if there is a mismatch in the number of arguments.
def simple_dec(func):
def wrapper(arg):
return func("test:" + arg)
return wraps(func)(wrapper)
simple_dec_m = method_decorator(simple_dec)
# For testing method_decorator, two decorators that add an attribute to the function
def myattr_dec(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.myattr = True
return wraps(func)(wrapper)
myattr_dec_m = method_decorator(myattr_dec)
def myattr2_dec(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.myattr2 = True
return wraps(func)(wrapper)
myattr2_dec_m = method_decorator(myattr2_dec)
class ClsDec:
def __init__(self, myattr):
self.myattr = myattr
def __call__(self, f):
def wrapped():
return f() and self.myattr
return update_wrapper(wrapped, f)
class MethodDecoratorTests(SimpleTestCase):
"""
Tests for method_decorator
"""
def test_preserve_signature(self):
class Test:
@simple_dec_m
def say(self, arg):
return arg
self.assertEqual("test:hello", Test().say("hello"))
def test_preserve_attributes(self):
# Sanity check myattr_dec and myattr2_dec
@myattr_dec
@myattr2_dec
def func():
pass
self.assertIs(getattr(func, 'myattr', False), True)
self.assertIs(getattr(func, 'myattr2', False), True)
# Decorate using method_decorator() on the method.
class TestPlain:
@myattr_dec_m
@myattr2_dec_m
def method(self):
"A method"
pass
# Decorate using method_decorator() on both the class and the method.
# The decorators applied to the methods are applied before the ones
# applied to the class.
@method_decorator(myattr_dec_m, "method")
class TestMethodAndClass:
@method_decorator(myattr2_dec_m)
def method(self):
"A method"
pass
# Decorate using an iterable of decorators.
decorators = (myattr_dec_m, myattr2_dec_m)
@method_decorator(decorators, "method")
class TestIterable:
def method(self):
"A method"
pass
for Test in (TestPlain, TestMethodAndClass, TestIterable):
self.assertIs(getattr(Test().method, 'myattr', False), True)
self.assertIs(getattr(Test().method, 'myattr2', False), True)
self.assertIs(getattr(Test.method, 'myattr', False), True)
self.assertIs(getattr(Test.method, 'myattr2', False), True)
self.assertEqual(Test.method.__doc__, 'A method')
self.assertEqual(Test.method.__name__, 'method')
def test_bad_iterable(self):
decorators = {myattr_dec_m, myattr2_dec_m}
msg = "'set' object is not subscriptable"
with self.assertRaisesMessage(TypeError, msg):
@method_decorator(decorators, "method")
class TestIterable:
def method(self):
"A method"
pass
# Test for argumented decorator
def test_argumented(self):
class Test:
@method_decorator(ClsDec(False))
def method(self):
return True
self.assertIs(Test().method(), False)
def test_descriptors(self):
def original_dec(wrapped):
def _wrapped(arg):
return wrapped(arg)
return _wrapped
method_dec = method_decorator(original_dec)
class bound_wrapper:
def __init__(self, wrapped):
self.wrapped = wrapped
self.__name__ = wrapped.__name__
def __call__(self, arg):
return self.wrapped(arg)
def __get__(self, instance, cls=None):
return self
class descriptor_wrapper:
def __init__(self, wrapped):
self.wrapped = wrapped
self.__name__ = wrapped.__name__
def __get__(self, instance, cls=None):
return bound_wrapper(self.wrapped.__get__(instance, cls))
class Test:
@method_dec
@descriptor_wrapper
def method(self, arg):
return arg
self.assertEqual(Test().method(1), 1)
def test_class_decoration(self):
"""
@method_decorator can be used to decorate a class and its methods.
"""
def deco(func):
def _wrapper(*args, **kwargs):
return True
return _wrapper
@method_decorator(deco, name="method")
class Test:
def method(self):
return False
self.assertTrue(Test().method())
def test_tuple_of_decorators(self):
"""
@method_decorator can accept a tuple of decorators.
"""
def add_question_mark(func):
def _wrapper(*args, **kwargs):
return func(*args, **kwargs) + "?"
return _wrapper
def add_exclamation_mark(func):
def _wrapper(*args, **kwargs):
return func(*args, **kwargs) + "!"
return _wrapper
# The order should be consistent with the usual order in which
# decorators are applied, e.g.
# @add_exclamation_mark
# @add_question_mark
# def func():
# ...
decorators = (add_exclamation_mark, add_question_mark)
@method_decorator(decorators, name="method")
class TestFirst:
def method(self):
return "hello world"
class TestSecond:
@method_decorator(decorators)
def method(self):
return "hello world"
self.assertEqual(TestFirst().method(), "hello world?!")
self.assertEqual(TestSecond().method(), "hello world?!")
def test_invalid_non_callable_attribute_decoration(self):
"""
@method_decorator on a non-callable attribute raises an error.
"""
msg = (
"Cannot decorate 'prop' as it isn't a callable attribute of "
"<class 'Test'> (1)"
)
with self.assertRaisesMessage(TypeError, msg):
@method_decorator(lambda: None, name="prop")
class Test:
prop = 1
@classmethod
def __module__(cls):
return "tests"
def test_invalid_method_name_to_decorate(self):
"""
@method_decorator on a nonexistent method raises an error.
"""
msg = (
"The keyword argument `name` must be the name of a method of the "
"decorated class: <class 'Test'>. Got 'non_existing_method' instead"
)
with self.assertRaisesMessage(ValueError, msg):
@method_decorator(lambda: None, name="non_existing_method")
class Test:
@classmethod
def __module__(cls):
return "tests"
class XFrameOptionsDecoratorsTests(TestCase):
"""
Tests for the X-Frame-Options decorators.
"""
def test_deny_decorator(self):
"""
Ensures @xframe_options_deny properly sets the X-Frame-Options header.
"""
@xframe_options_deny
def a_view(request):
return HttpResponse()
r = a_view(HttpRequest())
self.assertEqual(r['X-Frame-Options'], 'DENY')
def test_sameorigin_decorator(self):
"""
Ensures @xframe_options_sameorigin properly sets the X-Frame-Options
header.
"""
@xframe_options_sameorigin
def a_view(request):
return HttpResponse()
r = a_view(HttpRequest())
self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
def test_exempt_decorator(self):
"""
Ensures @xframe_options_exempt properly instructs the
XFrameOptionsMiddleware to NOT set the header.
"""
@xframe_options_exempt
def a_view(request):
return HttpResponse()
req = HttpRequest()
resp = a_view(req)
self.assertIsNone(resp.get('X-Frame-Options', None))
self.assertTrue(resp.xframe_options_exempt)
# Since the real purpose of the exempt decorator is to suppress
# the middleware's functionality, let's make sure it actually works...
r = XFrameOptionsMiddleware().process_response(req, resp)
self.assertIsNone(r.get('X-Frame-Options', None))
class NeverCacheDecoratorTest(TestCase):
def test_never_cache_decorator(self):
@never_cache
def a_view(request):
return HttpResponse()
r = a_view(HttpRequest())
self.assertEqual(
set(r['Cache-Control'].split(', ')),
{'max-age=0', 'no-cache', 'no-store', 'must-revalidate'},
)
| {
"repo_name": "auready/django",
"path": "tests/decorators/tests.py",
"copies": "3",
"size": "13943",
"license": "bsd-3-clause",
"hash": 5635459827285970000,
"line_mean": 29.9844444444,
"line_max": 84,
"alpha_frac": 0.5967151976,
"autogenerated": false,
"ratio": 4.230279126213592,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6326994323813592,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, wraps
from django.core.exceptions import ImproperlyConfigured
from actionviews.base import BaseView
def action_decorator(view_decorator):
def decorator(func):
def wrapper(self, *args, **kwargs):
@view_decorator
def view_func(request, *view_args, **view_kwargs):
return func(self, *view_args, **view_kwargs)
return view_func(self.request, *args, **kwargs)
# In case 'decorator' adds attributes to the function it decorates, we
# want to copy those. We don't have access to bound_func in this scope,
# but we can cheat by using it on a dummy function.
update_wrapper(wrapper, view_decorator(lambda *args, **kwargs: None))
# Need to preserve any existing attributes of 'func', including the
# name.
update_wrapper(wrapper, func)
return wrapper
return decorator
def require_method(methods):
if isinstance(methods, str):
methods = [methods]
def decorator(action):
action.allowed_methods = methods
return action
return decorator
def child_view(view_klass):
if not issubclass(view_klass, BaseView):
raise ImproperlyConfigured(
'`child_view` decorator receive BaseView subclass as its argument')
def decorator(func):
func.child_view = view_klass
return func
return decorator
def form(form_class, form_name='form', **form_kwargs):
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
request = self.request
if request.method == 'POST':
self.form = form_class(request.POST, **form_kwargs)
if self.form.is_valid():
return func(self, *args, **kwargs)
else:
self.form = form_class(**form_kwargs)
return {form_name: self.form}
return wrapper
return decorator
| {
"repo_name": "lig/django-actionviews",
"path": "actionviews/decorators.py",
"copies": "1",
"size": "1996",
"license": "bsd-3-clause",
"hash": 4224867699565359600,
"line_mean": 23.95,
"line_max": 79,
"alpha_frac": 0.6137274549,
"autogenerated": false,
"ratio": 4.36761487964989,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.548134233454989,
"avg_score": null,
"num_lines": null
} |
from functools import update_wrapper, wraps
import facebook
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import (HttpResponse, HttpResponseBadRequest,
HttpResponseRedirect)
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
import conf
from utils import is_fb_logged_in
def canvas_only(function=None):
"""
Decorator ensures that a page is only accessed from within a facebook
application.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# Make sure we're receiving a signed_request from facebook
if not request.POST.get('signed_request'):
return HttpResponseBadRequest('<h1>400 Bad Request</h1>'
'<p>Missing <em>signed_request</em>.</p>')
# Parse the request and ensure it's valid
signed_request = request.POST["signed_request"]
data = conf.auth.parse_signed_request(signed_request)
if data is False:
return HttpResponseBadRequest('<h1>400 Bad Request</h1>'
'<p>Malformed <em>signed_request</em>.</p>')
# If the user has not authorised redirect them
if not data.get('uid'):
scope = getattr(settings, 'FACEBOOK_PERMS', None)
auth_url = conf.auth.auth_url(conf.APP_ID,
conf.CANVAS_PAGE,
scope)
markup = ('<script type="text/javascript">'
'top.location.href="%s"</script>' % auth_url)
return HttpResponse(markup)
# Success so return the view
return view_func(request, *args, **kwargs)
return _view
return _dec(function)
def facebook_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
def _passes_test(test_func, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func, assigned=available_attrs(view_func))(
_wrapped_view)
return decorator
actual_decorator = _passes_test(
is_fb_logged_in,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
| {
"repo_name": "tino/django-facebook2",
"path": "django_facebook/decorators.py",
"copies": "1",
"size": "3096",
"license": "mit",
"hash": -4792371927216790000,
"line_mean": 37.2222222222,
"line_max": 78,
"alpha_frac": 0.572997416,
"autogenerated": false,
"ratio": 4.53294289897511,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003125488357555868,
"num_lines": 81
} |
from functools import update_wrapper, wraps, partial
import types
from .base import Unit
from .util import NOT_SET
from django import test
from django.http import HttpResponse
class UnitClient(test.Client):
def generic(self, method, path, **kw):
stop_after = kw.pop('unit', None)
repeat = partial(self.generic, method=method, path=path, **kw)
kw.update({'units.stop_after': stop_after})
response = super().generic(method, path, **kw)
return UnitsIterator(response._unit, repeat, stop_after)
class UnitsIterator:
def __init__(self, unit, repeat, current_unit):
self.unit = unit
self.repeat = repeat
if current_unit is not None:
self.current_unit = self.unit.all_units[current_unit]
else:
self.current_unit = self.unit
def go(self, unit):
try:
self.unit.run(stop_after=unit)
except StopIteration:
return self.repeat(unit=unit)
self.current_unit = self.all_units[unit]
return self
def __getattr__(self, name):
return getattr(self.current_unit, name)
def _repr_pretty_(self, p, cycle):
# black magic
from IPython.lib import pretty
if cycle:
p.text('UnitsIterator(..)')
return
max_length = max(len("%d %s" % (i, str(unit)))
for i, unit in enumerate(self.all_units))
def print_units(p, units_enum):
with p.group(2):
for i, unit in units_enum:
p.break_()
id_and_name = ("%d %s" % (i, str(unit))
).ljust(max_length + 1)
p.text(id_and_name)
with p.group(len(id_and_name)):
if unit.result is NOT_SET:
result = '-'
else:
result = pretty.pretty(unit.result)
if len(result) > 120:
result = '%s(...)' % unit.result.__class__.__name__
p.text(result)
all_units = enumerate(self.all_units)
current = self.all_units.index(self.current_unit)
def units_run():
for i, unit in all_units:
yield i, unit
if i == current:
break
p.text('Units run:')
print_units(p, list(units_run()))
units_to_run = list(all_units)
if units_to_run:
p.break_()
p.text('Units to run:')
print_units(p, units_to_run)
class UnitResponse(HttpResponse):
pass
class ViewUnit(Unit):
publish_attrs = ['request']
def prepare_run(self, request, *args, **kwargs):
self.request = request
self.view_args = args
self.view_kwargs = kwargs
@classmethod
def as_view(cls, *unit_args, view_func=None, **unit_kwargs):
def view(request, *args, **kwargs):
unit = cls(*unit_args, **unit_kwargs)
if view_func:
unit.view = view_func
if view_func and isinstance(view_func, types.MethodType):
# make unit accessible from view if it's class based
view_func.__self__._unit_ = unit
if not hasattr(unit, 'view'):
raise NotImplementedError('No "view" callable in %s' % unit)
is_test_client = 'units.stop_after' in request.META
if is_test_client:
kwargs.update(stop_after=request.META['units.stop_after'])
unit.run(request, *args, **kwargs)
if is_test_client:
# HttpResponse hasn't been got yet
empty = UnitResponse()
empty._unit = unit
return empty
return unit.result
# take name and docstring from class
update_wrapper(view, cls, updated=())
try:
view_function = view_func or cls.view
# and possible attributes from the view function
update_wrapper(view, view_function, assigned=())
except AttributeError:
pass
return view
def main(self):
return self.view(self.request, *self.view_args, **self.view_kwargs)
class unit_dispatch:
def __init__(self, unit_cls, *unit_args, **unit_kwargs):
self.unit_cls = unit_cls
self.unit_args = unit_args
self.unit_kwargs = unit_kwargs
def __get__(self, instance, owner):
if instance is None:
return self
decorated = getattr(self, '_decorated_func', None)
dispatch = decorated.__get__(instance) if decorated \
else super(owner, instance).dispatch
return self.unit_cls.as_view(*self.unit_args, view_func=dispatch,
**self.unit_kwargs)
def __call__(self, f):
self._decorated_func = f
return self | {
"repo_name": "abetkin/app-units",
"path": "appunits/dj.py",
"copies": "1",
"size": "4958",
"license": "mit",
"hash": 9064347982402827000,
"line_mean": 32.5067567568,
"line_max": 79,
"alpha_frac": 0.5340863251,
"autogenerated": false,
"ratio": 4.131666666666667,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5165752991766667,
"avg_score": null,
"num_lines": null
} |
from functools import WRAPPER_ASSIGNMENTS
from pynads.utils import decorators, update_wrapper
def generate_test_class():
class Test(object):
@decorators.method_optional_kwargs
def instm(self, f, **notes):
"""Instance Method"""
f.notes = notes
return f
@decorators.method_optional_kwargs
@classmethod
def clsm(cls, f, **notes):
"""Class Method"""
f.notes = notes
return f
@decorators.method_optional_kwargs
@staticmethod
def statm(f, **notes):
"""Static Method"""
f.notes = notes
return f
return Test
def test_kwargs_deco_looks_like_wrapped():
def my_deco(func, thing):
"a doc string"
return func
wrapped = decorators.optional_kwargs(my_deco)
assert wrapped.__wrapped__ is my_deco
assert all(getattr(my_deco, attr) == getattr(wrapped, attr)
for attr in WRAPPER_ASSIGNMENTS)
def test_kwargs_deco_actually_works():
@decorators.optional_kwargs
def my_deco(func, thing):
func.thing = thing
return func
@my_deco(thing=True)
def tester():
pass
assert tester.thing
def test_optional_kwargs_on_class():
@decorators.optional_kwargs
class W(object):
def __init__(self, f, thing):
update_wrapper(self, f)
self.thing = thing
self.f = f
def __call__(self, *a, **k):
return self.f(*a, **k)
wrapped_w = decorators.optional_kwargs(W)
@wrapped_w(thing=True)
def tester(x):
"a doc string"
return x
assert wrapped_w.__wrapped__ is W
assert all(getattr(W, attr) == getattr(wrapped_w, attr)
for attr in WRAPPER_ASSIGNMENTS)
assert tester.thing
assert tester.__doc__ == "a doc string"
assert tester.__name__ == 'tester'
def test_optional_kwargs_with_defaults():
@decorators.optional_kwargs
def test_deco(f, thing=True):
f.thing = thing
return f
@test_deco
def test():
pass
assert test.thing
def test_annotate():
@decorators.annotate(type="(a -> b) -> [a] -> [b]")
def my_map(f, xs):
pass
assert "my_map :: (a -> b) -> [a] -> [b]" in my_map.__doc__
def test_method_optional_kwargs_wraps_descriptors():
Test = generate_test_class()
assert "Instance Method" == Test.instm.__doc__
assert "Class Method" == Test.clsm.__doc__
assert "Static Method" == Test.statm.__doc__
def test_method_optional_kwargs_works():
Test = generate_test_class()
t = Test()
@t.instm(test=True)
def test1(*args, **kwargs):
"""Wrapped by instance"""
return 1
@Test.clsm(test=True)
def test2(*args, **kwargs):
"""Wrapped by classmethod"""
return 2
@Test.statm(test=True)
def test3(*args, **kwargs):
"""Wrapped by staticmethod"""
return 3
assert all(f.notes['test'] for f in [test1, test2, test3])
assert "Wrapped by instance" == test1.__doc__
assert test1() == 1
assert "Wrapped by classmethod" == test2.__doc__
assert test2() == 2
assert "Wrapped by staticmethod" == test3.__doc__
assert test3() == 3
| {
"repo_name": "justanr/pynads",
"path": "tests/test_utils_decorator.py",
"copies": "1",
"size": "3275",
"license": "mit",
"hash": 8288134213786507000,
"line_mean": 23.6240601504,
"line_max": 63,
"alpha_frac": 0.5746564885,
"autogenerated": false,
"ratio": 3.67152466367713,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47461811521771297,
"avg_score": null,
"num_lines": null
} |
from functools import WRAPPER_ASSIGNMENTS, update_wrapper, wraps
import inspect
from textwrap import dedent, wrap
import warnings
from pandas._libs.properties import cache_readonly # noqa
from pandas.compat import PY2, callable, signature
def deprecate(name, alternative, version, alt_name=None,
klass=None, stacklevel=2, msg=None):
"""Return a new function that emits a deprecation warning on use.
To use this method for a deprecated function, another function
`alternative` with the same signature must exist. The deprecated
function will emit a deprecation warning, and in the docstring
it will contain the deprecation directive with the provided version
so it can be detected for future removal.
Parameters
----------
name : str
Name of function to deprecate.
alternative : func
Function to use instead.
version : str
Version of pandas in which the method has been deprecated.
alt_name : str, optional
Name to use in preference of alternative.__name__.
klass : Warning, default FutureWarning
stacklevel : int, default 2
msg : str
The message to display in the warning.
Default is '{name} is deprecated. Use {alt_name} instead.'
"""
alt_name = alt_name or alternative.__name__
klass = klass or FutureWarning
warning_msg = msg or '{} is deprecated, use {} instead'.format(name,
alt_name)
# adding deprecated directive to the docstring
msg = msg or 'Use `{alt_name}` instead.'.format(alt_name=alt_name)
msg = '\n '.join(wrap(msg, 70))
@Substitution(version=version, msg=msg)
@Appender(alternative.__doc__)
def wrapper(*args, **kwargs):
"""
.. deprecated:: %(version)s
%(msg)s
"""
warnings.warn(warning_msg, klass, stacklevel=stacklevel)
return alternative(*args, **kwargs)
# Since we are using Substitution to create the required docstring,
# remove that from the attributes that should be assigned to the wrapper
assignments = tuple(x for x in WRAPPER_ASSIGNMENTS if x != '__doc__')
update_wrapper(wrapper, alternative, assigned=assignments)
return wrapper
def deprecate_kwarg(old_arg_name, new_arg_name, mapping=None, stacklevel=2):
"""
Decorator to deprecate a keyword argument of a function.
Parameters
----------
old_arg_name : str
Name of argument in function to deprecate
new_arg_name : str or None
Name of preferred argument in function. Use None to raise warning that
``old_arg_name`` keyword is deprecated.
mapping : dict or callable
If mapping is present, use it to translate old arguments to
new arguments. A callable must do its own value checking;
values not found in a dict will be forwarded unchanged.
Examples
--------
The following deprecates 'cols', using 'columns' instead
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
... def f(columns=''):
... print(columns)
...
>>> f(columns='should work ok')
should work ok
>>> f(cols='should raise warning')
FutureWarning: cols is deprecated, use columns instead
warnings.warn(msg, FutureWarning)
should raise warning
>>> f(cols='should error', columns="can\'t pass do both")
TypeError: Can only specify 'cols' or 'columns', not both
>>> @deprecate_kwarg('old', 'new', {'yes': True, 'no': False})
... def f(new=False):
... print('yes!' if new else 'no!')
...
>>> f(old='yes')
FutureWarning: old='yes' is deprecated, use new=True instead
warnings.warn(msg, FutureWarning)
yes!
To raise a warning that a keyword will be removed entirely in the future
>>> @deprecate_kwarg(old_arg_name='cols', new_arg_name=None)
... def f(cols='', another_param=''):
... print(cols)
...
>>> f(cols='should raise warning')
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
>>> f(another_param='should not raise warning')
should not raise warning
>>> f(cols='should raise warning', another_param='')
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
"""
if mapping is not None and not hasattr(mapping, 'get') and \
not callable(mapping):
raise TypeError("mapping from old to new argument values "
"must be dict or callable!")
def _deprecate_kwarg(func):
@wraps(func)
def wrapper(*args, **kwargs):
old_arg_value = kwargs.pop(old_arg_name, None)
if new_arg_name is None and old_arg_value is not None:
msg = (
"the '{old_name}' keyword is deprecated and will be "
"removed in a future version. "
"Please take steps to stop the use of '{old_name}'"
).format(old_name=old_arg_name)
warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
kwargs[old_arg_name] = old_arg_value
return func(*args, **kwargs)
if old_arg_value is not None:
if mapping is not None:
if hasattr(mapping, 'get'):
new_arg_value = mapping.get(old_arg_value,
old_arg_value)
else:
new_arg_value = mapping(old_arg_value)
msg = ("the {old_name}={old_val!r} keyword is deprecated, "
"use {new_name}={new_val!r} instead"
).format(old_name=old_arg_name,
old_val=old_arg_value,
new_name=new_arg_name,
new_val=new_arg_value)
else:
new_arg_value = old_arg_value
msg = ("the '{old_name}' keyword is deprecated, "
"use '{new_name}' instead"
).format(old_name=old_arg_name,
new_name=new_arg_name)
warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
if kwargs.get(new_arg_name, None) is not None:
msg = ("Can only specify '{old_name}' or '{new_name}', "
"not both").format(old_name=old_arg_name,
new_name=new_arg_name)
raise TypeError(msg)
else:
kwargs[new_arg_name] = new_arg_value
return func(*args, **kwargs)
return wrapper
return _deprecate_kwarg
def rewrite_axis_style_signature(name, extra_params):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
if not PY2:
kind = inspect.Parameter.POSITIONAL_OR_KEYWORD
params = [
inspect.Parameter('self', kind),
inspect.Parameter(name, kind, default=None),
inspect.Parameter('index', kind, default=None),
inspect.Parameter('columns', kind, default=None),
inspect.Parameter('axis', kind, default=None),
]
for pname, default in extra_params:
params.append(inspect.Parameter(pname, kind, default=default))
sig = inspect.Signature(params)
func.__signature__ = sig
return wrapper
return decorate
# Substitution and Appender are derived from matplotlib.docstring (1.1.0)
# module http://matplotlib.org/users/license.html
class Substitution(object):
"""
A decorator to take a function's docstring and perform string
substitution on it.
This decorator should be robust even if func.__doc__ is None
(for example, if -OO was passed to the interpreter)
Usage: construct a docstring.Substitution with a sequence or
dictionary suitable for performing substitution; then
decorate a suitable function with the constructed object. e.g.
sub_author_name = Substitution(author='Jason')
@sub_author_name
def some_function(x):
"%(author)s wrote this function"
# note that some_function.__doc__ is now "Jason wrote this function"
One can also use positional arguments.
sub_first_last_names = Substitution('Edgar Allen', 'Poe')
@sub_first_last_names
def some_function(x):
"%s %s wrote the Raven"
"""
def __init__(self, *args, **kwargs):
if (args and kwargs):
raise AssertionError("Only positional or keyword args are allowed")
self.params = args or kwargs
def __call__(self, func):
func.__doc__ = func.__doc__ and func.__doc__ % self.params
return func
def update(self, *args, **kwargs):
"""
Update self.params with supplied args.
If called, we assume self.params is a dict.
"""
self.params.update(*args, **kwargs)
@classmethod
def from_params(cls, params):
"""
In the case where the params is a mutable sequence (list or dictionary)
and it may change before this class is called, one may explicitly use a
reference to the params rather than using *args or **kwargs which will
copy the values and not reference them.
"""
result = cls()
result.params = params
return result
class Appender(object):
"""
A function decorator that will append an addendum to the docstring
of the target function.
This decorator should be robust even if func.__doc__ is None
(for example, if -OO was passed to the interpreter).
Usage: construct a docstring.Appender with a string to be joined to
the original docstring. An optional 'join' parameter may be supplied
which will be used to join the docstring and addendum. e.g.
add_copyright = Appender("Copyright (c) 2009", join='\n')
@add_copyright
def my_dog(has='fleas'):
"This docstring will have a copyright below"
pass
"""
def __init__(self, addendum, join='', indents=0):
if indents > 0:
self.addendum = indent(addendum, indents=indents)
else:
self.addendum = addendum
self.join = join
def __call__(self, func):
func.__doc__ = func.__doc__ if func.__doc__ else ''
self.addendum = self.addendum if self.addendum else ''
docitems = [func.__doc__, self.addendum]
func.__doc__ = dedent(self.join.join(docitems))
return func
def indent(text, indents=1):
if not text or not isinstance(text, str):
return ''
jointext = ''.join(['\n'] + [' '] * indents)
return jointext.join(text.split('\n'))
def make_signature(func):
"""
Returns a string repr of the arg list of a func call, with any defaults.
Examples
--------
>>> def f(a,b,c=2) :
>>> return a*b*c
>>> print(_make_signature(f))
a,b,c=2
"""
spec = signature(func)
if spec.defaults is None:
n_wo_defaults = len(spec.args)
defaults = ('',) * n_wo_defaults
else:
n_wo_defaults = len(spec.args) - len(spec.defaults)
defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
args = []
for i, (var, default) in enumerate(zip(spec.args, defaults)):
args.append(var if default == '' else var + '=' + repr(default))
if spec.varargs:
args.append('*' + spec.varargs)
if spec.keywords:
args.append('**' + spec.keywords)
return args, spec.args
| {
"repo_name": "harisbal/pandas",
"path": "pandas/util/_decorators.py",
"copies": "2",
"size": "11932",
"license": "bsd-3-clause",
"hash": 7212091244741181000,
"line_mean": 33.991202346,
"line_max": 79,
"alpha_frac": 0.5888367415,
"autogenerated": false,
"ratio": 4.256867641812344,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5845704383312343,
"avg_score": null,
"num_lines": null
} |
from functools import WRAPPER_ASSIGNMENTS, wraps
from inspect import Parameter, Signature, signature
from microcosm_pubsub.chain.decorators import BINDS, EXTRACTS
from microcosm_pubsub.chain.exceptions import ContextKeyNotFound
DEFAULT_ASSIGNED = (EXTRACTS, BINDS)
EXTRACT_PREFIX = "extract_"
def get_positional_args(func):
"""
Returns all the POSITIONAL argument names of a function
* If func is a method, do not return "self" argument
* Handle wrapped functions too
"""
return [
(arg, parameter.default)
for arg, parameter
in signature(func).parameters.items()
if parameter.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD)
]
def get_from_context(context, func, assigned=DEFAULT_ASSIGNED):
"""
Decorate a function - pass to the function the relevant arguments
from a context (dictionary) - based on the function arg names
"""
positional_args = get_positional_args(func)
@wraps(func, assigned=assigned + WRAPPER_ASSIGNMENTS)
def decorate(*args, **kwargs):
try:
context_kwargs = {
arg_name: (context[arg_name] if default is Signature.empty else context.get(arg_name, default))
for arg_name, default in positional_args[len(args):]
if arg_name not in kwargs
}
except KeyError as error:
raise ContextKeyNotFound(error, func)
return func(*args, **kwargs, **context_kwargs)
return decorate
def save_to_context(context, func, assigned=DEFAULT_ASSIGNED):
"""
Decorate a function - save to a context (dictionary) the function return value
if the function is marked by @extracts decorator
"""
extracts = getattr(func, EXTRACTS, None)
if not extracts:
return func
extracts_one_value = len(extracts) == 1
@wraps(func, assigned=assigned + WRAPPER_ASSIGNMENTS)
def decorate(*args, **kwargs):
value = func(*args, **kwargs)
if extracts_one_value:
value = [value]
for index, name in enumerate(extracts):
context[name] = value[index]
return value
return decorate
def save_to_context_by_func_name(context, func, assigned=DEFAULT_ASSIGNED):
"""
Decorate a function - save to a context (dictionary) the function return value
if the function is not signed by EXTRACTS and it's name starts with "extract_"
"""
if (
hasattr(func, EXTRACTS) or
not hasattr(func, "__name__") or
not func.__name__.startswith(EXTRACT_PREFIX)
):
return func
name = func.__name__[len(EXTRACT_PREFIX):]
@wraps(func, assigned=assigned + WRAPPER_ASSIGNMENTS)
def decorate(*args, **kwargs):
value = func(*args, **kwargs)
context[name] = value
return value
return decorate
def temporarily_replace_context_keys(context, func, assigned=DEFAULT_ASSIGNED):
"""
Decorate a function - temporarily updates the context keys while running the function
Updates the context if the function is marked by @binds decorator.
"""
binds = getattr(func, BINDS, None)
if not binds:
return func
@wraps(func, assigned=assigned + WRAPPER_ASSIGNMENTS)
def decorate(*args, **kwargs):
for old_key, new_key in binds.items():
if old_key not in context:
raise KeyError(f"Variable '{old_key}'' not set")
if new_key in context:
raise ValueError(f"Variable '{new_key}'' already set")
try:
for old_key, new_key in binds.items():
context[new_key] = context.pop(old_key)
return func(*args, **kwargs)
finally:
for old_key, new_key in binds.items():
context[old_key] = context.pop(new_key)
return decorate
| {
"repo_name": "globality-corp/microcosm-pubsub",
"path": "microcosm_pubsub/chain/context_decorators.py",
"copies": "1",
"size": "3853",
"license": "apache-2.0",
"hash": -7281353704936620000,
"line_mean": 31.6525423729,
"line_max": 111,
"alpha_frac": 0.6384635349,
"autogenerated": false,
"ratio": 4.055789473684211,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5194253008584211,
"avg_score": null,
"num_lines": null
} |
from functools import WRAPPER_ASSIGNMENTS, wraps
from django.http import Http404
from django.shortcuts import get_object_or_404
from account.decorators import login_required
from .models import Membership, Team
def team_required(func=None):
"""
Decorator for views that require a team be supplied wither via a slug in the
url pattern or already set on the request object from the TeamMiddleware
"""
def decorator(view_func):
@wraps(view_func, assigned=WRAPPER_ASSIGNMENTS)
def _wrapped_view(request, *args, **kwargs):
slug = kwargs.pop("slug", None)
if not getattr(request, "team", None):
request.team = get_object_or_404(Team, slug=slug)
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator
def manager_required(func=None):
"""
Decorator for views that require not only a team but also that a user be
logged in and be the manager or owner of that team.
"""
def decorator(view_func):
@team_required
@login_required
@wraps(view_func, assigned=WRAPPER_ASSIGNMENTS)
def _wrapped_view(request, *args, **kwargs):
role = request.team.role_for(request.user)
if role not in [Membership.ROLE_MANAGER, Membership.ROLE_OWNER]:
raise Http404()
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator
| {
"repo_name": "pinax/pinax-teams",
"path": "pinax/teams/decorators.py",
"copies": "1",
"size": "1552",
"license": "mit",
"hash": 5161380170534152000,
"line_mean": 32.7391304348,
"line_max": 80,
"alpha_frac": 0.6507731959,
"autogenerated": false,
"ratio": 4.116710875331565,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5267484071231565,
"avg_score": null,
"num_lines": null
} |
from functools import WRAPPER_ASSIGNMENTS, wraps
from .jobs import FunctionJob
def cacheback(
lifetime=None,
fetch_on_miss=None,
cache_alias=None,
job_class=None,
task_options=None,
**job_class_kwargs
):
"""
Decorate function to cache its return value.
:lifetime: How long to cache items for
:fetch_on_miss: Whether to perform a synchronous fetch when no cached
result is found
:cache_alias: The Django cache alias to store the result into.
:job_class: The class to use for running the cache refresh job. Defaults
using the FunctionJob.
:job_class_kwargs: Any extra kwargs to pass to job_class constructor.
Useful with custom job_class implementations.
"""
if job_class is None:
job_class = FunctionJob
job = job_class(
lifetime=lifetime,
fetch_on_miss=fetch_on_miss,
cache_alias=cache_alias,
task_options=task_options,
**job_class_kwargs
)
def _wrapper(fn):
# using available_attrs to work around http://bugs.python.org/issue3445
@wraps(fn, assigned=WRAPPER_ASSIGNMENTS)
def __wrapper(*args, **kwargs):
return job.get(fn, *args, **kwargs)
# Assign reference to unwrapped function so that we can access it
# later without descending into infinite regress.
__wrapper.fn = fn
# Assign reference to job so we can use the full Job API
__wrapper.job = job
return __wrapper
return _wrapper
| {
"repo_name": "codeinthehole/django-cacheback",
"path": "cacheback/decorators.py",
"copies": "1",
"size": "1559",
"license": "mit",
"hash": 6278901049166546000,
"line_mean": 30.8163265306,
"line_max": 79,
"alpha_frac": 0.6343810135,
"autogenerated": false,
"ratio": 4.135278514588859,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5269659528088859,
"avg_score": null,
"num_lines": null
} |
from functools import wraps as copydoc
import kudu
import pandas as pd
import ibis.expr.datatypes as dt
from ibis.backends.base_sql.ddl import (
CreateTable,
format_schema,
format_tblproperties,
)
from ibis.common.exceptions import IbisError
from ibis.expr.api import schema
_kudu_type_to_ibis_typeclass = {
'int8': dt.Int8,
'int16': dt.Int16,
'int32': dt.Int32,
'int64': dt.Int64,
'float': dt.Float,
'double': dt.Double,
'bool': dt.Boolean,
'string': dt.String,
'timestamp': dt.Timestamp,
}
class KuduImpalaInterface:
"""User-facing wrapper layer for the ImpalaClient."""
def __init__(self, impala_client):
self.impala_client = impala_client
self.client = None
@copydoc(kudu.client.Client.list_tables)
def list_tables(self, filter=''):
return self.client.list_tables(filter)
@copydoc(kudu.client.Client.table_exists)
def table_exists(self, name):
return self.client.table_exists(name)
def connect(
self,
host_or_hosts,
port_or_ports=7051,
rpc_timeout=None,
admin_timeout=None,
):
"""
Pass-through connection interface to the Kudu client
Parameters
----------
host_or_hosts : string or list of strings
If you have multiple Kudu masters for HA, pass a list
port_or_ports : int or list of int, default 7051
If you pass multiple host names, pass multiple ports
rpc_timeout : kudu.TimeDelta
See Kudu client documentation for details
admin_timeout : kudu.TimeDelta
See Kudu client documentation for details
Returns
-------
None
"""
self.client = kudu.connect(
host_or_hosts,
port_or_ports,
rpc_timeout_ms=rpc_timeout,
admin_timeout_ms=admin_timeout,
)
def _check_connected(self):
if not self.is_connected:
raise IbisError(
'Please first connect to a Kudu cluster '
'with client.kudu.connect'
)
@property
def is_connected(self):
# crude check for now
return self.client is not None
def create_table(
self,
impala_name,
kudu_name,
primary_keys=None,
obj=None,
schema=None,
database=None,
external=False,
force=False,
):
"""
Create an Kudu-backed table in the connected Impala cluster. For
non-external tables, this will create a Kudu table with a compatible
storage schema.
This function is patterned after the ImpalaClient.create_table function
designed for physical filesystems (like HDFS).
Parameters
----------
impala_name : string
Name of the created Impala table
kudu_name : string
Name of hte backing Kudu table. Will be created if external=False
primary_keys : list of column names
List of
obj : TableExpr or pandas.DataFrame, optional
If passed, creates table from select statement results
schema : ibis.Schema, optional
Mutually exclusive with expr, creates an empty table with a
particular schema
database : string, default None (optional)
external : boolean, default False
If False, a new Kudu table will be created. Otherwise, the Kudu table
must already exist.
"""
self._check_connected()
if not external and (primary_keys is None or len(primary_keys) == 0):
raise ValueError(
'Must specify primary keys when DDL creates a '
'new Kudu table'
)
if obj is not None:
if external:
raise ValueError(
'Cannot create an external Kudu-Impala table '
'from an expression or DataFrame'
)
if isinstance(obj, pd.DataFrame):
from .pandas_interop import write_temp_dataframe
writer, to_insert = write_temp_dataframe(
self.impala_client, obj
)
else:
to_insert = obj
# XXX: exposing a lot of internals
ast = self.impala_client._build_ast(to_insert)
select = ast.queries[0]
stmt = CTASKudu(
impala_name,
kudu_name,
self.client.master_addrs,
select,
primary_keys,
database=database,
)
else:
if external:
ktable = self.client.table(kudu_name)
kschema = ktable.schema
schema = schema_kudu_to_ibis(kschema)
primary_keys = kschema.primary_keys()
elif schema is None:
raise ValueError(
'Must specify schema for new empty ' 'Kudu-backed table'
)
stmt = CreateTableKudu(
impala_name,
kudu_name,
self.client.master_addrs,
schema,
primary_keys,
external=external,
database=database,
can_exist=False,
)
self.impala_client._execute(stmt)
def table(
self, kudu_name, name=None, database=None, persist=False, external=True
):
"""
Convenience to expose an existing Kudu table (using CREATE TABLE) as an
Impala table. To create a new table both in the Hive Metastore with
storage in Kudu, use create_table.
Note: all tables created are EXTERNAL for now. Creates a temporary
table (like parquet_file and others) unless persist=True.
If you create a persistent table you can thereafter use it like any
other Impala table.
Parameters
----------
kudu_name : string
The name of the table in the Kudu cluster
name : string, optional
Name of the created table in Impala / Hive Metastore. Randomly
generated if not specified.
database : string, optional
Database to create the table in. Uses the temp db if not provided
persist : boolean, default False
If True, do not drop the table upon Ibis garbage collection /
interpreter shutdown. Be careful using this in conjunction with the
`external` option.
external : boolean, default True
If True, create the Impala table as EXTERNAL so the Kudu data is not
deleted when the Impala table is dropped
Returns
-------
parquet_table : ImpalaTable
"""
# Law of demeter, but OK for now because internal class coupling
name, database = self.impala_client._get_concrete_table_path(
name, database, persist=persist
)
self.create_table(name, kudu_name, database=database, external=True)
return self.impala_client._wrap_new_table(name, database, persist)
class CreateTableKudu(CreateTable):
"""
Creates an Impala table that scans from a Kudu table
"""
# TODO
# - DISTRIBUTE BY HASH
# - DISTRIBUTE BY RANGE`
# - multi master test
def __init__(
self,
table_name,
kudu_table_name,
master_addrs,
schema,
key_columns,
external=True,
**kwargs,
):
self.kudu_table_name = kudu_table_name
self.master_addrs = master_addrs
self.schema = schema
self.key_columns = key_columns
CreateTable.__init__(self, table_name, external=external, **kwargs)
self._validate()
def _validate(self):
pass
def compile(self):
return '{}\n{}\n{}'.format(
self._create_line(),
format_schema(self.schema),
format_tblproperties(self._get_table_properties()),
)
_table_props_base = {
'storage_handler': 'com.cloudera.kudu.hive.KuduStorageHandler'
}
def _get_table_properties(self):
tbl_props = self._table_props_base.copy()
addr_string = ', '.join(self.master_addrs)
keys_string = ', '.join(self.key_columns)
tbl_props.update(
{
'kudu.table_name': self.kudu_table_name,
'kudu.master_addresses': addr_string,
'kudu.key_columns': keys_string,
}
)
return tbl_props
class CTASKudu(CreateTableKudu):
def __init__(
self,
table_name,
kudu_name,
master_addrs,
select,
key_columns,
database=None,
external=False,
can_exist=False,
):
self.select = select
CreateTableKudu.__init__(
self,
table_name,
kudu_name,
master_addrs,
None,
key_columns,
database=database,
external=external,
can_exist=can_exist,
)
def compile(self):
return '{}\n{} AS\n{}'.format(
self._create_line(),
format_tblproperties(self._get_table_properties()),
self.select.compile(),
)
def schema_kudu_to_ibis(kschema, drop_nn=False):
ibis_types = []
for i in range(len(kschema)):
col = kschema[i]
typeclass = _kudu_type_to_ibis_typeclass[col.type.name]
if drop_nn:
# For testing, because Impala does not have nullable types
itype = typeclass(True)
else:
itype = typeclass(col.nullable)
ibis_types.append((col.name, itype))
return schema(ibis_types)
| {
"repo_name": "cloudera/ibis",
"path": "ibis/backends/impala/kudu_support.py",
"copies": "1",
"size": "9811",
"license": "apache-2.0",
"hash": 7186343577822855000,
"line_mean": 28.374251497,
"line_max": 79,
"alpha_frac": 0.56202222,
"autogenerated": false,
"ratio": 4.155442609063956,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 334
} |
from functools import wraps as copydoc
import kudu
import pandas as pd
import ibis.expr.datatypes as dt
from ibis.backends.base.sql.ddl import (
CreateTable,
format_schema,
format_tblproperties,
)
from ibis.common.exceptions import IbisError
from ibis.expr.api import schema
_kudu_type_to_ibis_typeclass = {
'int8': dt.Int8,
'int16': dt.Int16,
'int32': dt.Int32,
'int64': dt.Int64,
'float': dt.Float,
'double': dt.Double,
'bool': dt.Boolean,
'string': dt.String,
'timestamp': dt.Timestamp,
}
class KuduImpalaInterface:
"""User-facing wrapper layer for the ImpalaClient."""
def __init__(self, impala_client):
self.impala_client = impala_client
self.client = None
@copydoc(kudu.client.Client.list_tables)
def list_tables(self, filter=''):
return self.client.list_tables(filter)
@copydoc(kudu.client.Client.table_exists)
def table_exists(self, name):
return self.client.table_exists(name)
def connect(
self,
host_or_hosts,
port_or_ports=7051,
rpc_timeout=None,
admin_timeout=None,
):
"""
Pass-through connection interface to the Kudu client
Parameters
----------
host_or_hosts : string or list of strings
If you have multiple Kudu masters for HA, pass a list
port_or_ports : int or list of int, default 7051
If you pass multiple host names, pass multiple ports
rpc_timeout : kudu.TimeDelta
See Kudu client documentation for details
admin_timeout : kudu.TimeDelta
See Kudu client documentation for details
Returns
-------
None
"""
self.client = kudu.connect(
host_or_hosts,
port_or_ports,
rpc_timeout_ms=rpc_timeout,
admin_timeout_ms=admin_timeout,
)
def _check_connected(self):
if not self.is_connected:
raise IbisError(
'Please first connect to a Kudu cluster '
'with client.kudu.connect'
)
@property
def is_connected(self):
# crude check for now
return self.client is not None
def create_table(
self,
impala_name,
kudu_name,
primary_keys=None,
obj=None,
schema=None,
database=None,
external=False,
force=False,
):
"""
Create an Kudu-backed table in the connected Impala cluster. For
non-external tables, this will create a Kudu table with a compatible
storage schema.
This function is patterned after the ImpalaClient.create_table function
designed for physical filesystems (like HDFS).
Parameters
----------
impala_name : string
Name of the created Impala table
kudu_name : string
Name of hte backing Kudu table. Will be created if external=False
primary_keys : list of column names
List of
obj : TableExpr or pandas.DataFrame, optional
If passed, creates table from select statement results
schema : ibis.Schema, optional
Mutually exclusive with expr, creates an empty table with a
particular schema
database : string, default None (optional)
external : boolean, default False
If False, a new Kudu table will be created. Otherwise, the Kudu table
must already exist.
"""
self._check_connected()
if not external and (primary_keys is None or len(primary_keys) == 0):
raise ValueError(
'Must specify primary keys when DDL creates a '
'new Kudu table'
)
if obj is not None:
if external:
raise ValueError(
'Cannot create an external Kudu-Impala table '
'from an expression or DataFrame'
)
if isinstance(obj, pd.DataFrame):
from .pandas_interop import write_temp_dataframe
writer, to_insert = write_temp_dataframe(
self.impala_client, obj
)
else:
to_insert = obj
# XXX: exposing a lot of internals
ast = self.impala_client.compiler.to_ast(to_insert)
select = ast.queries[0]
stmt = CTASKudu(
impala_name,
kudu_name,
self.client.master_addrs,
select,
primary_keys,
database=database,
)
else:
if external:
ktable = self.client.table(kudu_name)
kschema = ktable.schema
schema = schema_kudu_to_ibis(kschema)
primary_keys = kschema.primary_keys()
elif schema is None:
raise ValueError(
'Must specify schema for new empty ' 'Kudu-backed table'
)
stmt = CreateTableKudu(
impala_name,
kudu_name,
self.client.master_addrs,
schema,
primary_keys,
external=external,
database=database,
can_exist=False,
)
self.impala_client._execute(stmt)
def table(
self, kudu_name, name=None, database=None, persist=False, external=True
):
"""
Convenience to expose an existing Kudu table (using CREATE TABLE) as an
Impala table. To create a new table both in the Hive Metastore with
storage in Kudu, use create_table.
Note: all tables created are EXTERNAL for now. Creates a temporary
table (like parquet_file and others) unless persist=True.
If you create a persistent table you can thereafter use it like any
other Impala table.
Parameters
----------
kudu_name : string
The name of the table in the Kudu cluster
name : string, optional
Name of the created table in Impala / Hive Metastore. Randomly
generated if not specified.
database : string, optional
Database to create the table in. Uses the temp db if not provided
persist : boolean, default False
If True, do not drop the table upon Ibis garbage collection /
interpreter shutdown. Be careful using this in conjunction with the
`external` option.
external : boolean, default True
If True, create the Impala table as EXTERNAL so the Kudu data is not
deleted when the Impala table is dropped
Returns
-------
parquet_table : ImpalaTable
"""
# Law of demeter, but OK for now because internal class coupling
name, database = self.impala_client._get_concrete_table_path(
name, database, persist=persist
)
self.create_table(name, kudu_name, database=database, external=True)
return self.impala_client._wrap_new_table(name, database, persist)
class CreateTableKudu(CreateTable):
"""
Creates an Impala table that scans from a Kudu table
"""
# TODO
# - DISTRIBUTE BY HASH
# - DISTRIBUTE BY RANGE`
# - multi master test
def __init__(
self,
table_name,
kudu_table_name,
master_addrs,
schema,
key_columns,
external=True,
**kwargs,
):
self.kudu_table_name = kudu_table_name
self.master_addrs = master_addrs
self.schema = schema
self.key_columns = key_columns
CreateTable.__init__(self, table_name, external=external, **kwargs)
self._validate()
def _validate(self):
pass
def compile(self):
return '{}\n{}\n{}'.format(
self._create_line(),
format_schema(self.schema),
format_tblproperties(self._get_table_properties()),
)
_table_props_base = {
'storage_handler': 'com.cloudera.kudu.hive.KuduStorageHandler'
}
def _get_table_properties(self):
tbl_props = self._table_props_base.copy()
addr_string = ', '.join(self.master_addrs)
keys_string = ', '.join(self.key_columns)
tbl_props.update(
{
'kudu.table_name': self.kudu_table_name,
'kudu.master_addresses': addr_string,
'kudu.key_columns': keys_string,
}
)
return tbl_props
class CTASKudu(CreateTableKudu):
def __init__(
self,
table_name,
kudu_name,
master_addrs,
select,
key_columns,
database=None,
external=False,
can_exist=False,
):
self.select = select
CreateTableKudu.__init__(
self,
table_name,
kudu_name,
master_addrs,
None,
key_columns,
database=database,
external=external,
can_exist=can_exist,
)
def compile(self):
return '{}\n{} AS\n{}'.format(
self._create_line(),
format_tblproperties(self._get_table_properties()),
self.select.compile(),
)
def schema_kudu_to_ibis(kschema, drop_nn=False):
ibis_types = []
for i in range(len(kschema)):
col = kschema[i]
typeclass = _kudu_type_to_ibis_typeclass[col.type.name]
if drop_nn:
# For testing, because Impala does not have nullable types
itype = typeclass(True)
else:
itype = typeclass(col.nullable)
ibis_types.append((col.name, itype))
return schema(ibis_types)
| {
"repo_name": "ibis-project/ibis",
"path": "ibis/backends/impala/kudu_support.py",
"copies": "1",
"size": "9816",
"license": "apache-2.0",
"hash": -4115556706137091600,
"line_mean": 28.3892215569,
"line_max": 79,
"alpha_frac": 0.5622453138,
"autogenerated": false,
"ratio": 4.15404147270419,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.521628678650419,
"avg_score": null,
"num_lines": null
} |
from functools import wraps as copydoc
import kudu
import pandas as pd
import ibis.expr.datatypes as dt
from ibis.common.exceptions import IbisError
from ibis.expr.api import schema
from ibis.impala import ddl
_kudu_type_to_ibis_typeclass = {
'int8': dt.Int8,
'int16': dt.Int16,
'int32': dt.Int32,
'int64': dt.Int64,
'float': dt.Float,
'double': dt.Double,
'bool': dt.Boolean,
'string': dt.String,
'timestamp': dt.Timestamp,
}
class KuduImpalaInterface:
"""User-facing wrapper layer for the ImpalaClient."""
def __init__(self, impala_client):
self.impala_client = impala_client
self.client = None
@copydoc(kudu.client.Client.list_tables)
def list_tables(self, filter=''):
return self.client.list_tables(filter)
@copydoc(kudu.client.Client.table_exists)
def table_exists(self, name):
return self.client.table_exists(name)
def connect(
self,
host_or_hosts,
port_or_ports=7051,
rpc_timeout=None,
admin_timeout=None,
):
"""
Pass-through connection interface to the Kudu client
Parameters
----------
host_or_hosts : string or list of strings
If you have multiple Kudu masters for HA, pass a list
port_or_ports : int or list of int, default 7051
If you pass multiple host names, pass multiple ports
rpc_timeout : kudu.TimeDelta
See Kudu client documentation for details
admin_timeout : kudu.TimeDelta
See Kudu client documentation for details
Returns
-------
None
"""
self.client = kudu.connect(
host_or_hosts,
port_or_ports,
rpc_timeout_ms=rpc_timeout,
admin_timeout_ms=admin_timeout,
)
def _check_connected(self):
if not self.is_connected:
raise IbisError(
'Please first connect to a Kudu cluster '
'with client.kudu.connect'
)
@property
def is_connected(self):
# crude check for now
return self.client is not None
def create_table(
self,
impala_name,
kudu_name,
primary_keys=None,
obj=None,
schema=None,
database=None,
external=False,
force=False,
):
"""
Create an Kudu-backed table in the connected Impala cluster. For
non-external tables, this will create a Kudu table with a compatible
storage schema.
This function is patterned after the ImpalaClient.create_table function
designed for physical filesystems (like HDFS).
Parameters
----------
impala_name : string
Name of the created Impala table
kudu_name : string
Name of hte backing Kudu table. Will be created if external=False
primary_keys : list of column names
List of
obj : TableExpr or pandas.DataFrame, optional
If passed, creates table from select statement results
schema : ibis.Schema, optional
Mutually exclusive with expr, creates an empty table with a
particular schema
database : string, default None (optional)
external : boolean, default False
If False, a new Kudu table will be created. Otherwise, the Kudu table
must already exist.
"""
self._check_connected()
if not external and (primary_keys is None or len(primary_keys) == 0):
raise ValueError(
'Must specify primary keys when DDL creates a '
'new Kudu table'
)
if obj is not None:
if external:
raise ValueError(
'Cannot create an external Kudu-Impala table '
'from an expression or DataFrame'
)
if isinstance(obj, pd.DataFrame):
from ibis.impala.pandas_interop import write_temp_dataframe
writer, to_insert = write_temp_dataframe(
self.impala_client, obj
)
else:
to_insert = obj
# XXX: exposing a lot of internals
ast = self.impala_client._build_ast(to_insert)
select = ast.queries[0]
stmt = CTASKudu(
impala_name,
kudu_name,
self.client.master_addrs,
select,
primary_keys,
database=database,
)
else:
if external:
ktable = self.client.table(kudu_name)
kschema = ktable.schema
schema = schema_kudu_to_ibis(kschema)
primary_keys = kschema.primary_keys()
elif schema is None:
raise ValueError(
'Must specify schema for new empty ' 'Kudu-backed table'
)
stmt = CreateTableKudu(
impala_name,
kudu_name,
self.client.master_addrs,
schema,
primary_keys,
external=external,
database=database,
can_exist=False,
)
self.impala_client._execute(stmt)
def table(
self, kudu_name, name=None, database=None, persist=False, external=True
):
"""
Convenience to expose an existing Kudu table (using CREATE TABLE) as an
Impala table. To create a new table both in the Hive Metastore with
storage in Kudu, use create_table.
Note: all tables created are EXTERNAL for now. Creates a temporary
table (like parquet_file and others) unless persist=True.
If you create a persistent table you can thereafter use it like any
other Impala table.
Parameters
----------
kudu_name : string
The name of the table in the Kudu cluster
name : string, optional
Name of the created table in Impala / Hive Metastore. Randomly
generated if not specified.
database : string, optional
Database to create the table in. Uses the temp db if not provided
persist : boolean, default False
If True, do not drop the table upon Ibis garbage collection /
interpreter shutdown. Be careful using this in conjunction with the
`external` option.
external : boolean, default True
If True, create the Impala table as EXTERNAL so the Kudu data is not
deleted when the Impala table is dropped
Returns
-------
parquet_table : ImpalaTable
"""
# Law of demeter, but OK for now because internal class coupling
name, database = self.impala_client._get_concrete_table_path(
name, database, persist=persist
)
self.create_table(name, kudu_name, database=database, external=True)
return self.impala_client._wrap_new_table(name, database, persist)
class CreateTableKudu(ddl.CreateTable):
"""
Creates an Impala table that scans from a Kudu table
"""
# TODO
# - DISTRIBUTE BY HASH
# - DISTRIBUTE BY RANGE`
# - multi master test
def __init__(
self,
table_name,
kudu_table_name,
master_addrs,
schema,
key_columns,
external=True,
**kwargs
):
self.kudu_table_name = kudu_table_name
self.master_addrs = master_addrs
self.schema = schema
self.key_columns = key_columns
ddl.CreateTable.__init__(self, table_name, external=external, **kwargs)
self._validate()
def _validate(self):
pass
def compile(self):
return '{}\n{}\n{}'.format(
self._create_line(),
ddl.format_schema(self.schema),
ddl.format_tblproperties(self._get_table_properties()),
)
_table_props_base = {
'storage_handler': 'com.cloudera.kudu.hive.KuduStorageHandler'
}
def _get_table_properties(self):
tbl_props = self._table_props_base.copy()
addr_string = ', '.join(self.master_addrs)
keys_string = ', '.join(self.key_columns)
tbl_props.update(
{
'kudu.table_name': self.kudu_table_name,
'kudu.master_addresses': addr_string,
'kudu.key_columns': keys_string,
}
)
return tbl_props
class CTASKudu(CreateTableKudu):
def __init__(
self,
table_name,
kudu_name,
master_addrs,
select,
key_columns,
database=None,
external=False,
can_exist=False,
):
self.select = select
CreateTableKudu.__init__(
self,
table_name,
kudu_name,
master_addrs,
None,
key_columns,
database=database,
external=external,
can_exist=can_exist,
)
def compile(self):
return '{}\n{} AS\n{}'.format(
self._create_line(),
ddl.format_tblproperties(self._get_table_properties()),
self.select.compile(),
)
def schema_kudu_to_ibis(kschema, drop_nn=False):
ibis_types = []
for i in range(len(kschema)):
col = kschema[i]
typeclass = _kudu_type_to_ibis_typeclass[col.type.name]
if drop_nn:
# For testing, because Impala does not have nullable types
itype = typeclass(True)
else:
itype = typeclass(col.nullable)
ibis_types.append((col.name, itype))
return schema(ibis_types)
| {
"repo_name": "cpcloud/ibis",
"path": "ibis/impala/kudu_support.py",
"copies": "1",
"size": "9764",
"license": "apache-2.0",
"hash": 6596849757862764000,
"line_mean": 28.5878787879,
"line_max": 79,
"alpha_frac": 0.5620647276,
"autogenerated": false,
"ratio": 4.140797285835454,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5202862013435454,
"avg_score": null,
"num_lines": null
} |
from functools import wraps as DECORATOR
import language
def memoize(obj):
'''
A simple method decorator for memoization
Usage
------
@memoize
def myfunction(arg1, arg2):
return 2 * arg2 + arg1
Internals:
----------
This decorator hashes a string representation of the args+kwargs
passed to cache preci
'''
# -- initialize memoization cache
cache = obj.cache = {}
# -- create wrapper around general object function calls
@DECORATOR(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
def normalize_sos(sq, sz=30, filler=0, prepend=True):
'''
Take a list of lists and ensure that they are all of length `sz`
Args:
-----
e: a non-generator iterable of lists
sz: integer, the size that each sublist should be normalized to
filler: obj -- what should be added to fill out the size?
prepend: should `filler` be added to the front or the back of the list?
'''
if not prepend:
def _normalize(e, sz):
return e[:sz] if len(e) >= sz else e + [filler] * (sz - len(e))
return [_normalize(e, sz) for e in sq]
else:
def _normalize(e, sz):
return e[-sz:] if len(e) >= sz else [filler] * (sz - len(e)) + e
return [_normalize(e, sz) for e in sq]
def to_glove_vectors(text, glovebox):
tokens = language.tokenize_text(text)
wvs = []
for token in tokens:
wvs.append(glovebox[token])
return wvs | {
"repo_name": "textclf/fancy-cnn",
"path": "textclf/util/misc.py",
"copies": "2",
"size": "1658",
"license": "mit",
"hash": 522634098790682900,
"line_mean": 25.3333333333,
"line_max": 79,
"alpha_frac": 0.5856453559,
"autogenerated": false,
"ratio": 3.7426636568848757,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5328309012784875,
"avg_score": null,
"num_lines": null
} |
from functools import wraps as _wraps
from itertools import chain as _chain
import json
from .utils import convert_to, Logger, dec_con
from decimal import Decimal
import pandas as pd
from time import sleep
from datetime import datetime, timezone, timedelta
import zmq
import threading
from multiprocessing import Process
from .exceptions import *
from cryptotrader.utils import send_email
debug = True
# Base classes
class ExchangeConnection(object):
# Feed methods
@property
def balance(self):
return NotImplementedError("This class is not intended to be used directly.")
def returnBalances(self):
return NotImplementedError("This class is not intended to be used directly.")
def returnFeeInfo(self):
return NotImplementedError("This class is not intended to be used directly.")
def returnCurrencies(self):
return NotImplementedError("This class is not intended to be used directly.")
def returnChartData(self, currencyPair, period, start=None, end=None):
return NotImplementedError("This class is not intended to be used directly.")
# Trade execution methods
def sell(self, currencyPair, rate, amount, orderType=False):
return NotImplementedError("This class is not intended to be used directly.")
def buy(self, currencyPair, rate, amount, orderType=False):
return NotImplementedError("This class is not intended to be used directly.")
def pair_reciprocal(self, df):
df[['open', 'high', 'low', 'close']] = df.apply(
{col: lambda x: str((Decimal('1') / convert_to.decimal(x)).quantize(Decimal('0E-8')))
for col in ['open', 'low', 'high', 'close']}, raw=True).rename(columns={'low': 'high',
'high': 'low'}
)
return df.rename(columns={'quoteVolume': 'volume', 'volume': 'quoteVolume'})
## Feed daemon
# Server
class FeedDaemon(Process):
"""
Data Feed server
"""
def __init__(self, api={}, addr='ipc:///tmp/feed.ipc', n_workers=8, email={}):
"""
:param api: dict: exchange name: api instance
:param addr: str: client side address
:param n_workers: int: n threads
"""
super(FeedDaemon, self).__init__()
self.api = api
self.email = email
self.context = zmq.Context()
self.n_workers = n_workers
self.addr = addr
self.MINUTE, self.HOUR, self.DAY = 60, 60 * 60, 60 * 60 * 24
self.WEEK, self.MONTH = self.DAY * 7, self.DAY * 30
self.YEAR = self.DAY * 365
self._nonce = int("{:.6f}".format(datetime.utcnow().timestamp()).replace('.', ''))
@property
def nonce(self):
""" Increments the nonce"""
self._nonce += 33
return self._nonce
def handle_req(self, req):
req = req.split(' ')
if req[0] == '' or len(req) == 1:
return False
elif len(req) == 2:
return req[0], req[1]
else:
# Candle data
if req[1] == 'returnChartData':
if req[4] == 'None':
req[4] = datetime.utcnow().timestamp() - self.DAY
if req[5] == 'None':
req[5] = datetime.utcnow().timestamp()
call = (
req[0],
req[1],
{
'currencyPair': str(req[2]).upper(),
'period': str(req[3]),
'start': str(req[4]),
'end': str(req[5])
}
)
return call
if req[1] == 'returnTradeHistory':
args = {'currencyPair': str(req[2]).upper()}
if req[3] != 'None':
args['start'] = req[3]
if req[4] != 'None':
args['end'] = req[4]
return req[0], req[1], args
# Buy and sell orders
if req[1] == 'buy' or req[1] == 'sell':
args = {
'currencyPair': str(req[2]).upper(),
'rate': str(req[3]),
'amount': str(req[4]),
}
# order type specified?
try:
possTypes = ['fillOrKill', 'immediateOrCancel', 'postOnly']
# check type
if not req[5] in possTypes:
raise ExchangeError('Invalid orderType')
args[req[5]] = 1
except IndexError:
pass
return req[0], req[1], args
if req[1] == 'returnDepositsWithdrawals':
args = {}
if req[2] != 'None':
args['start'] = req[2]
if req[3] != 'None':
args['end'] = req[3]
return req[0], req[1], args
def worker(self):
# Init socket
sock = self.context.socket(zmq.REP)
sock.connect("inproc://workers.inproc")
while True:
try:
# Wait for request
req = sock.recv_string()
Logger.info(FeedDaemon.worker, req)
# Handle request
call = self.handle_req(req)
# Send request to api
if call:
try:
self.api[call[0]].nonce = self.nonce
rep = self.api[call[0]].__call__(*call[1:])
except ExchangeError as e:
rep = e.__str__()
Logger.error(FeedDaemon.worker, "Exchange error: %s\n%s" % (req, rep))
except DataFeedException as e:
rep = e.__str__()
Logger.error(FeedDaemon.worker, "DataFeedException: %s\n%s" % (req, rep))
if debug:
Logger.debug(FeedDaemon.worker, "Debug: %s" % req)
# send reply back to client
sock.send_json(rep)
else:
raise TypeError("Bad call format.")
except Exception as e:
send_email(self.email, "FeedDaemon Error", e)
sock.close()
raise e
def run(self):
try:
Logger.info(FeedDaemon, "Starting Feed Daemon...")
# Socket to talk to clients
clients = self.context.socket(zmq.ROUTER)
clients.bind(self.addr)
# Socket to talk to workers
workers = self.context.socket(zmq.DEALER)
workers.bind("inproc://workers.inproc")
# Launch pool of worker threads
for i in range(self.n_workers):
thread = threading.Thread(target=self.worker, args=())
thread.start()
Logger.info(FeedDaemon.run, "Feed Daemon running. Serving on %s" % self.addr)
zmq.proxy(clients, workers)
except KeyboardInterrupt:
clients.close()
workers.close()
self.context.term()
# Client
class DataFeed(ExchangeConnection):
"""
Data feeder for backtesting with TradingEnvironment.
"""
# TODO WRITE TESTS
retryDelays = [2 ** i for i in range(8)]
def __init__(self, exchange='', addr='ipc:///tmp/feed.ipc', timeout=30):
"""
:param period: int: Data sampling period
:param pairs: list: Pair symbols to trade
:param exchange: str: FeedDaemon exchange to query
:param addr: str: Client socked address
:param timeout: int:
"""
super(DataFeed, self).__init__()
# Sock objects
self.context = zmq.Context()
self.addr = addr
self.exchange = exchange
self.timeout = timeout * 1000
self.sock = self.context.socket(zmq.REQ)
self.sock.connect(addr)
self.poll = zmq.Poller()
self.poll.register(self.sock, zmq.POLLIN)
def __del__(self):
self.sock.close()
# Retry decorator
def retry(func):
""" Retry decorator """
@_wraps(func)
def retrying(*args, **kwargs):
problems = []
for delay in _chain(DataFeed.retryDelays, [None]):
try:
# attempt call
return func(*args, **kwargs)
# we need to try again
except DataFeedException as problem:
problems.append(problem)
if delay is None:
Logger.debug(DataFeed, problems)
raise MaxRetriesException('retryDelays exhausted ' + str(problem))
else:
# log exception and wait
Logger.debug(DataFeed, problem)
Logger.error(DataFeed, "No reply... -- delaying for %ds" % delay)
sleep(delay)
return retrying
def get_response(self, req):
req = self.exchange + ' ' + req
# Send request
try:
self.sock.send_string(req)
except zmq.ZMQError as e:
if 'Operation cannot be accomplished in current state' == e.__str__():
# If request timeout, restart socket
Logger.error(DataFeed.get_response, "%s request timeout." % req)
# Socket is confused. Close and remove it.
self.sock.setsockopt(zmq.LINGER, 0)
self.sock.close()
self.poll.unregister(self.sock)
# Create new connection
self.sock = self.context.socket(zmq.REQ)
self.sock.connect(self.addr)
self.poll.register(self.sock, zmq.POLLIN)
raise DataFeedException("Socket error. Restarting connection...")
# Get response
socks = dict(self.poll.poll(self.timeout))
if socks.get(self.sock) == zmq.POLLIN:
# If response, return
return self.sock.recv_json()
else:
# If request timeout, restart socket
Logger.error(DataFeed.get_response, "%s request timeout." % req)
# Socket is confused. Close and remove it.
self.sock.setsockopt(zmq.LINGER, 0)
self.sock.close()
self.poll.unregister(self.sock)
# Create new connection
self.sock = self.context.socket(zmq.REQ)
self.sock.connect(self.addr)
self.poll.register(self.sock, zmq.POLLIN)
raise RequestTimeoutException("%s request timedout" % req)
@retry
def returnTicker(self):
try:
rep = self.get_response('returnTicker')
assert isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnTicker")
@retry
def returnBalances(self):
"""
Return balance from exchange. API KEYS NEEDED!
:return: list:
"""
try:
rep = self.get_response('returnBalances')
assert isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnBalances")
@retry
def returnFeeInfo(self):
"""
Returns exchange fee informartion
:return:
"""
try:
rep = self.get_response('returnFeeInfo')
assert isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnFeeInfo")
@retry
def returnCurrencies(self):
"""
Return exchange currency pairs
:return: list:
"""
try:
rep = self.get_response('returnCurrencies')
assert isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnCurrencies")
@retry
def returnChartData(self, currencyPair, period, start=None, end=None):
"""
Return pair OHLC data
:param currencyPair: str: Desired pair str
:param period: int: Candle period. Must be in [300, 900, 1800, 7200, 14400, 86400]
:param start: str: UNIX timestamp to start from
:param end: str: UNIX timestamp to end returned data
:return: list: List containing desired asset data in "records" format
"""
try:
call = "returnChartData %s %s %s %s" % (str(currencyPair),
str(period),
str(start),
str(end))
rep = self.get_response(call)
if 'Invalid currency pair.' in rep:
try:
symbols = currencyPair.split('_')
pair = symbols[1] + '_' + symbols[0]
call = "returnChartData %s %s %s %s" % (str(pair),
str(period),
str(start),
str(end))
rep = json.loads(
self.pair_reciprocal(pd.DataFrame.from_records(self.get_response(call))).to_json(
orient='records'))
except Exception as e:
raise e
assert isinstance(rep, list), "returnChartData reply is not list"
assert int(rep[-1]['date']), "Bad returnChartData reply data"
assert float(rep[-1]['open']), "Bad returnChartData reply data"
assert float(rep[-1]['close']), "Bad returnChartData reply data"
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnChartData")
@retry
def returnTradeHistory(self, currencyPair='all', start=None, end=None):
try:
call = "returnTradeHistory %s %s %s" % (str(currencyPair),
str(start),
str(end))
rep = self.get_response(call)
assert isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnTradeHistory")
@retry
def returnDepositsWithdrawals(self, start=False, end=False):
try:
call = "returnDepositsWithdrawals %s %s" % (
str(start),
str(end)
)
rep = self.get_response(call)
assert isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnDepositsWithdrawals")
@retry
def sell(self, currencyPair, rate, amount, orderType=False):
try:
call = "sell %s %s %s %s" % (str(currencyPair),
str(rate),
str(amount),
str(orderType))
rep = self.get_response(call)
if 'Invalid currency pair.' in rep:
try:
symbols = currencyPair.split('_')
pair = symbols[1] + '_' + symbols[0]
call = "sell %s %s %s %s" % (str(pair),
str(rate),
str(amount),
str(orderType))
rep = self.get_response(call)
except Exception as e:
raise e
assert isinstance(rep, str) or isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.sell")
@retry
def buy(self, currencyPair, rate, amount, orderType=False):
try:
call = "buy %s %s %s %s" % (str(currencyPair),
str(rate),
str(amount),
str(orderType))
rep = self.get_response(call)
if 'Invalid currency pair.' in rep:
try:
symbols = currencyPair.split('_')
pair = symbols[1] + '_' + symbols[0]
call = "buy %s %s %s %s" % (str(pair),
str(rate),
str(amount),
str(orderType))
rep = self.get_response(call)
except Exception as e:
raise e
assert isinstance(rep, str) or isinstance(rep, dict)
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.buy")
# Test datafeeds
class BacktestDataFeed(ExchangeConnection):
"""
Data feeder for backtesting with TradingEnvironment.
"""
# TODO WRITE TESTS
def __init__(self, tapi, period, pairs=[], balance={}, load_dir=None):
super().__init__()
self.tapi = tapi
self.ohlc_data = {}
self._balance = balance
self.data_length = 0
self.load_dir = load_dir
self.tax = {'makerFee': '0.00150000',
'nextTier': '600.00000000',
'takerFee': '0.00250000',
'thirtyDayVolume': '0.00000000'}
self.pairs = pairs
self.period = period
def returnBalances(self):
return self._balance
def set_tax(self, tax):
"""
{'makerFee': '0.00150000',
'nextTier': '600.00000000',
'takerFee': '0.00250000',
'thirtyDayVolume': '0.00000000'}
:param dict:
:return:
"""
self.tax.update(tax)
def returnFeeInfo(self):
return self.tax
def returnCurrencies(self):
if self.load_dir:
try:
with open(self.load_dir + '/currencies.json') as file:
return json.load(file)
except Exception as e:
Logger.error(BacktestDataFeed.returnCurrencies, str(e.__cause__) + str(e))
return self.tapi.returnCurrencies()
else:
return self.tapi.returnCurrencies()
def download_data(self, start=None, end=None):
# TODO WRITE TEST
self.ohlc_data = {}
self.data_length = None
index = pd.date_range(start=start,
end=end,
freq="%dT" % self.period).ceil("%dT" % self.period)
for pair in self.pairs:
ohlc_df = pd.DataFrame.from_records(
self.tapi.returnChartData(
pair,
period=self.period * 60,
start=start,
end=end
),
nrows=index.shape[0]
)
i = -1
last_close = ohlc_df.at[ohlc_df.index[i], 'close']
while not dec_con.create_decimal(last_close).is_finite():
i -= 1
last_close = ohlc_df.at[ohlc_df.index[i], 'close']
# Replace missing values with last close
fill_dict = {col: last_close for col in ['open', 'high', 'low', 'close']}
fill_dict.update({'volume': '0E-16'})
self.ohlc_data[pair] = ohlc_df.fillna(fill_dict).ffill()
for key in self.ohlc_data:
if not self.data_length or self.ohlc_data[key].shape[0] < self.data_length:
self.data_length = self.ohlc_data[key].shape[0]
for key in self.ohlc_data:
if self.ohlc_data[key].shape[0] != self.data_length:
# self.ohlc_data[key] = pd.DataFrame.from_records(
# self.tapi.returnChartData(key, period=self.period * 60,
# start=self.ohlc_data[key].date.iloc[-self.data_length],
# end=end
# ),
# nrows=index.shape[0]
# )
self.ohlc_data[key] = self.ohlc_data[key].iloc[:self.data_length]
self.ohlc_data[key].set_index('date', inplace=True, drop=False)
print("%d intervals, or %d days of data at %d minutes period downloaded." % (self.data_length, (self.data_length * self.period) /\
(24 * 60), self.period))
def save_data(self, dir=None):
"""
Save data to disk
:param dir: str: directory relative to ./; eg './data/train
:return:
"""
for item in self.ohlc_data:
self.ohlc_data[item].to_json(dir+'/'+str(item)+'_'+str(self.period)+'min.json', orient='records')
def load_data(self, dir):
"""
Load data form disk.
JSON like data expected.
:param dir: str: directory relative to self.load_dir; eg: './self.load_dir/dir'
:return: None
"""
self.ohlc_data = {}
self.data_length = None
for key in self.pairs:
self.ohlc_data[key] = pd.read_json(self.load_dir + dir +'/'+str(key)+'_'+str(self.period)+'min.json', convert_dates=False,
orient='records', date_unit='s', keep_default_dates=False, dtype=False)
self.ohlc_data[key].set_index('date', inplace=True, drop=False)
if not self.data_length:
self.data_length = self.ohlc_data[key].shape[0]
else:
assert self.data_length == self.ohlc_data[key].shape[0]
def returnChartData(self, currencyPair, period, start=None, end=None):
try:
data = json.loads(self.ohlc_data[currencyPair].loc[start:end, :].to_json(orient='records'))
return data
except json.JSONDecodeError:
print("Bad exchange response.")
except AssertionError as e:
if "Invalid period" == e:
raise ExchangeError("%d invalid candle period" % period)
elif "Invalid pair" == e:
raise ExchangeError("Invalid currency pair.")
def reverse_data(self):
for df in self.ohlc_data:
self.ohlc_data.update({df:self.ohlc_data[df].reindex(index=self.ohlc_data[df].index[::-1])})
self.ohlc_data[df]['date'] = self.ohlc_data[df].index[::-1]
self.ohlc_data[df].index = self.ohlc_data[df].index[::-1]
self.ohlc_data[df] = self.ohlc_data[df].rename(columns={'close': 'open', 'open': 'close'})
class PaperTradingDataFeed(ExchangeConnection):
"""
Data feeder for paper trading with TradingEnvironment.
"""
# TODO WRITE TESTS
def __init__(self, tapi, period, pairs=[], balance={}):
super().__init__()
self.tapi = tapi
self._balance = balance
self.pairs = pairs
self.period = period
def returnBalances(self):
return self._balance
def returnFeeInfo(self):
return {'makerFee': '0.00150000',
'nextTier': '600.00000000',
'takerFee': '0.00250000',
'thirtyDayVolume': '0.00000000'}
def returnTicker(self):
return self.tapi.returnTicker()
def returnCurrencies(self):
"""
Return exchange currency pairs
:return: list:
"""
return self.tapi.returnCurrencies()
def returnChartData(self, currencyPair, period, start=None, end=None):
"""
Return pair OHLC data
:param currencyPair: str: Desired pair str
:param period: int: Candle period. Must be in [300, 900, 1800, 7200, 14400, 86400]
:param start: str: UNIX timestamp to start from
:param end: str: UNIX timestamp to end returned data
:return: list: List containing desired asset data in "records" format
"""
try:
return self.tapi.returnChartData(currencyPair, period, start=start, end=end)
except ExchangeError as error:
if 'Invalid currency pair.' == error.__str__():
try:
symbols = currencyPair.split('_')
pair = symbols[1] + '_' + symbols[0]
return json.loads(
self.pair_reciprocal(pd.DataFrame.from_records(self.tapi.returnChartData(pair, period,
start=start,
end=end
))).to_json(
orient='records'))
except Exception as e:
raise e
else:
raise error
# Live datafeeds
class PoloniexConnection(DataFeed):
def __init__(self, period, pairs=[], exchange='', addr='ipc:///tmp/feed.ipc', timeout=20):
"""
:param tapi: exchange api instance: Exchange api instance
:param period: int: Data period
:param pairs: list: Pairs to trade
"""
super().__init__(exchange, addr, timeout)
self.pairs = pairs
self.period = period
@DataFeed.retry
def returnChartData(self, currencyPair, period, start=None, end=None):
"""
Return pair OHLC data
:param currencyPair: str: Desired pair str
:param period: int: Candle period. Must be in [300, 900, 1800, 7200, 14400, 86400]
:param start: str: UNIX timestamp to start from
:param end: str: UNIX timestamp to end returned data
:return: list: List containing desired asset data in "records" format
"""
try:
call = "returnChartData %s %s %s %s" % (str(currencyPair),
str(period),
str(start),
str(end))
rep = self.get_response(call)
if 'Invalid currency pair.' in rep:
try:
symbols = currencyPair.split('_')
pair = symbols[1] + '_' + symbols[0]
call = "returnChartData %s %s %s %s" % (str(pair),
str(period),
str(start),
str(end))
rep = json.loads(
self.pair_reciprocal(
pd.DataFrame.from_records(
self.get_response(call)
)
).to_json(orient='records'))
except Exception as e:
raise e
assert isinstance(rep, list), "returnChartData reply is not list: %s" % str(rep)
assert int(rep[-1]['date']), "Bad returnChartData reply data"
assert float(rep[-1]['open']), "Bad returnChartData reply data"
assert float(rep[-1]['close']), "Bad returnChartData reply data"
return rep
except AssertionError:
raise UnexpectedResponseException("Unexpected response from DataFeed.returnChartData")
| {
"repo_name": "naripok/cryptotrader",
"path": "cryptotrader/datafeed.py",
"copies": "1",
"size": "28137",
"license": "mit",
"hash": -2446921661670587000,
"line_mean": 35.4941634241,
"line_max": 138,
"alpha_frac": 0.4970323773,
"autogenerated": false,
"ratio": 4.52,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.55170323773,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
__author__ = 'sekely'
def parse_single_arg(arg_name, args, arg_type=None, default_val=None):
arg = args.get(arg_name, default_val)
if isinstance(arg, list):
arg = arg[0]
if arg_type:
return arg_type(arg)
return arg
class ServerStopped(Exception):
pass
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def parse_args(**k):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
pv = {}
for key, val in k.iteritems():
arg_type, default_val = val
pv[key] = parse_single_arg(key, kwargs, arg_type, default_val)
kwargs.update(pv)
return func(*args, **kwargs)
return wrapper
return decorator
def safe(wrapped):
@wraps(wrapped)
def wrapper(*args, **kwargs):
try:
wrapped(*args, **kwargs)
except ServerStopped as e:
raise e
except Exception as e:
print e
return wrapper
| {
"repo_name": "idosekely/toll_road",
"path": "model/infra.py",
"copies": "1",
"size": "1220",
"license": "mit",
"hash": 1656815673323332900,
"line_mean": 22.9215686275,
"line_max": 81,
"alpha_frac": 0.5590163934,
"autogenerated": false,
"ratio": 3.8485804416403786,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9803202060442477,
"avg_score": 0.020878954919580153,
"num_lines": 51
} |
from functools import wraps
from advanced_reports import get_report_or_404
try:
from django.utils.timezone import now
except:
import datetime
now = datetime.datetime.now
def conditional_delegation(condition_func):
"""
Delegate a view depending on a certain condition.
"""
def decorator(view_func):
@wraps(view_func)
def delegated_view(request, *args, **kwargs):
# Only do the actual delegation if the django-delegation library is installed.
try:
from django_delegation.decorators import delegate
from django_delegation.utils import SimpleHTTPRequest
except ImportError:
return view_func(request, *args, **kwargs)
if not isinstance(request, SimpleHTTPRequest) and condition_func(request):
return delegate(view_func)(request, *args, **kwargs)
return view_func(request, *args, **kwargs)
return delegated_view
return decorator
def report_view(view_func):
"""
Encapsulates a view which deals with a report and applies a custom decorator
defined in the report, if it has ``decorate_views = True``.
"""
@wraps(view_func)
def decorated(request, slug, *args, **kwargs):
report = get_report_or_404(slug)
report.set_request(request)
inner = view_func
if report.decorate_views:
inner = report.get_decorator()(inner)
return inner(request, report, *args, **kwargs)
return decorated
| {
"repo_name": "vikingco/django-advanced-reports",
"path": "advanced_reports/decorators.py",
"copies": "1",
"size": "1534",
"license": "bsd-3-clause",
"hash": 9192711458579853000,
"line_mean": 33.0888888889,
"line_max": 90,
"alpha_frac": 0.6440677966,
"autogenerated": false,
"ratio": 4.3456090651558075,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5489676861755808,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from .aggregation import AggregationGroupParser, AggregationParser
from .matching import (SchemaFreeParser, SchemaAwareParser, ParseError,
StringField, IntField, BoolField, IdField,
ListField, DictField, DateTimeField)
def find(expression, schema=None):
'''
Gets an <expression> and optional <schema>.
<expression> should be a string of python code.
<schema> should be a dictionary mapping field names to types.
'''
parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema)
return parser.parse(expression)
class pipe_element(list):
def __or__(self, other):
return pipe_element(self + other)
def pipe(func):
@wraps(func)
def decorated(*a, **k):
return pipe_element([func(*a, **k)])
return decorated
def _parse_value(parser, value):
if isinstance(value, str):
return parser.parse(value)
elif isinstance(value, int):
return value
else:
raise ValueError('Unexpected type: {}'.format(value.__class__))
def _parse_dict(parser, dct):
return dict([(k, _parse_value(parser, v)) for k, v in dct.items()])
@pipe
def group(_id, **kwargs):
group = _parse_dict(parser=AggregationGroupParser(), dct=kwargs)
if isinstance(_id, pipe_element):
_id = _id[0]['$project']
else:
_id = AggregationParser().parse(_id)
group['_id'] = _id
return {'$group': group}
@pipe
def project(**kwargs):
return {'$project': _parse_dict(parser=AggregationParser(), dct=kwargs)}
@pipe
def match(expression, schema=None):
return {'$match': find(expression, schema)}
@pipe
def limit(number):
if not isinstance(number, int):
raise ValueError("aggregation 'limit' must be a number")
return {'$limit': number}
@pipe
def skip(number):
if not isinstance(number, int):
raise ValueError("aggregation 'skip' must be a number")
return {'$skip': number}
@pipe
def unwind(list_name):
if not isinstance(list_name, str):
raise ValueError("aggregation 'unwind' must be a str")
return {'$unwind': '$' + list_name}
@pipe
def sort(fields):
'''
Gets a list of <fields> to sort by.
Also supports getting a single string for sorting by one field.
Reverse sort is supported by appending '-' to the field name.
Example: sort(['age', '-height']) will sort by ascending age and descending height.
'''
from pymongo import ASCENDING, DESCENDING
from bson import SON
if isinstance(fields, str):
fields = [fields]
if not hasattr(fields, '__iter__'):
raise ValueError("expected a list of strings or a string. not a {}".format(type(fields)))
sort = []
for field in fields:
if field.startswith('-'):
field = field[1:]
sort.append((field, DESCENDING))
continue
elif field.startswith('+'):
field = field[1:]
sort.append((field, ASCENDING))
return {'$sort': SON(sort)}
| {
"repo_name": "rsmoorthy/docker",
"path": "pythontools/pql/__init__.py",
"copies": "1",
"size": "3036",
"license": "mit",
"hash": -5539292521703946000,
"line_mean": 30.2989690722,
"line_max": 97,
"alpha_frac": 0.6360342556,
"autogenerated": false,
"ratio": 4.005277044854881,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.016430406127264253,
"num_lines": 97
} |
from functools import wraps
from aiohttp.web import HTTPException
from transmute_core.exceptions import APIException, NoSerializerFound
from transmute_core.function.signature import NoDefault
from transmute_core import ParamExtractor, NoArgument
from aiohttp import web
def create_handler(transmute_func, context):
@wraps(transmute_func.raw_func)
async def handler(request):
exc, result = None, None
try:
args, kwargs = await extract_params(request, context,
transmute_func)
result = await transmute_func.raw_func(*args, **kwargs)
except HTTPException as hpe:
code = hpe.status_code or 400
exc = APIException(code=code, message=str(hpe))
except Exception as e:
exc = e
if isinstance(result, web.Response):
return result
else:
response = transmute_func.process_result(
context, result, exc, request.content_type
)
return web.Response(
body=response["body"], status=response["code"],
content_type=response["content-type"],
headers=response["headers"]
)
handler.transmute_func = transmute_func
return handler
async def extract_params(request, context, transmute_func):
body = await request.content.read()
content_type = request.content_type
extractor = ParamExtractorAIOHTTP(request, body)
return extractor.extract_params(
context, transmute_func, content_type
)
class ParamExtractorAIOHTTP(ParamExtractor):
def __init__(self, request, body):
self._request = request
self._body = body
def _get_framework_args(self):
return {"request": self._request}
@property
def body(self):
return self._body
def _query_argument(self, key, is_list):
if key not in self._request.query:
return NoArgument
if is_list:
return self._request.query.getall(key)
else:
return self._request.query[key]
def _header_argument(self, key):
return self._request.headers.get(key, NoArgument)
def _path_argument(self, key):
return self._request.match_info.get(key, NoArgument)
| {
"repo_name": "toumorokoshi/transmute-core",
"path": "transmute_core/frameworks/aiohttp/handler.py",
"copies": "3",
"size": "2315",
"license": "mit",
"hash": -7293684880658659000,
"line_mean": 30.7123287671,
"line_max": 69,
"alpha_frac": 0.6233261339,
"autogenerated": false,
"ratio": 4.31098696461825,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.643431309851825,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from annoying.decorators import ajax_request, render_to
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render_to_response
from models import *
from reduction import *
from exceptions import GameException
def game_request(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
if 'game_id' not in kwargs:
raise Exception("game_id expected")
game_id = kwargs['game_id']
game = Game.objects(id=game_id)[0]
request.game = game
request.slots = Slot.objects(game_id=game_id)
if request.user is not None:
user_id = request.user.id
is_first_user = game.first_user_id == user_id
request.proponent_id = user_id
request.opponent_id = game.second_user_id if is_first_user else game.first_user_id
request.my_slots = request.slots.filter(user_id=user_id)
request.opponent_slots = request.slots.filter(user_id=request.opponent_id)
del kwargs['game_id']
return func(request, *args, **kwargs)
return wrapper
@login_required
def create_game(request):
Slot.drop_collection()
Game.drop_collection()
game = Game(first_user_id=1)
game.save()
game.accept_opponent(2)
return redirect_to_room(game.id)
@ajax_request
@login_required
@game_request
def game_state(request):
return {'data': request.game.as_dict(request.user.id) }
CARDS = {
'id': create_identity,
'zero': create_zero,
'scomb': create_s_comb,
'kcomb': create_k_comb,
'succ': Succ,
'dbl': Dbl,
'get': Get,
'inc': Inc,
'dec': Dec,
'copy': Copy,
'attack': Attack,
}
@ajax_request
def available_cards(request):
return {'cards': CARDS.keys()}
def game_assert(expr, message="Error"):
if not expr:
raise GameException(message)
def apply_term_to_slot(request, slot_id, term, from_right):
try:
game_assert(request.game.is_active(), "Game is not active")
game_assert(request.game.is_user_turn(request.user.id), "It's not your turn")
slot = request.my_slots.filter(slot_id=slot_id)[0]
game_assert(slot.is_alive(), "Slot is not active")
if int(from_right) == 1:
application = Application(first_term=slot.term, second_term=term)
else:
application = Application(second_term=slot.term, first_term=term)
new_slot_term = Reducer(request).make_reduction(application)
except Exception as e:
return {'error': str(e)}
slot.term = new_slot_term
slot.save()
request.game.flip_turn()
request.game.save()
return {'data': request.game.as_dict(request.user.id)}
@ajax_request
@login_required
@game_request
def apply_card(request, slot_id, card, from_right):
term = CARDS[card](does_prefer_combinators(request.user.id))
return apply_term_to_slot(request, slot_id, term, from_right)
@ajax_request
@login_required
@game_request
def apply_slot(request, slot_id, second_slot_id, from_right):
game_assert(slot_id != second_slot_id, "Don't apply to the same slot")
second_slot = request.my_slots.filter(slot_id=second_slot_id)[0]
game_assert(second_slot.is_alive(), "Slot is not alive")
return apply_term_to_slot(request, slot_id, second_slot.term, from_right)
@login_required
@render_to('games/my_games.html')
def my_games(request):
games = list(Game.\
objects(Q(first_user_id=request.user.id) | Q (second_user_id=request.user.id)).\
filter(second_user_id__exists=True).all())
for game in games:
opponent_user_id = game.second_user_id if game.first_user_id == request.user.id else game.first_user_id
game.opponent = User.objects.filter(id=opponent_user_id).first()
return {'games': games}
def redirect_to_room(game_id):
return HttpResponseRedirect(reverse('frontend.views.room', kwargs={'game_id': game_id}))
@login_required
def new_game(request):
game = Game.objects(second_user_id__exists=False).filter(first_user_id__ne=request.user.id).first()
my_game = Game.objects(second_user_id__exists=False).filter(first_user_id=request.user.id).first()
if game is None or my_game is not None:
game = my_game if my_game is not None else Game(first_user_id=request.user.id).save()
return HttpResponseRedirect(reverse('games.views.wait_opponent', kwargs={'game_id': game.id}))
else:
game.accept_opponent(request.user.id)
return redirect_to_room(game.id)
@login_required
def wait_opponent(request, game_id):
game = Game.objects(id=game_id)[0]
if game.second_user_id is None:
return render_to_response('games/wait.html')
else:
return redirect_to_room(game.id)
| {
"repo_name": "tsvtkv/lgt",
"path": "games/views.py",
"copies": "2",
"size": "4923",
"license": "mit",
"hash": 514923028070477300,
"line_mean": 28.656626506,
"line_max": 111,
"alpha_frac": 0.6668697948,
"autogenerated": false,
"ratio": 3.299597855227882,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49664676500278826,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from app import app
from flask import (session,render_template, redirect,
request, url_for)
from models import db, login_data, post_data
@app.route("/")
def home():
username=None
if 'username' in session:
username = session['username']
return redirect(url_for('user',username=username))
return render_template("base.html")
def login_required(f):
@wraps(f)
def temp(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
return redirect(url_for('login'))
return temp
@app.route("/login", methods=['POST','GET'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = login_data.query.filter_by(username=username).first()
if user and user.password == password:
session['logged_in']=username
session['user_id']=user.user_id
session['username']=user.username
return redirect(url_for('user',username=user.username))
else:
pass
return redirect(url_for('home'))
@app.route("/user/<username>")
@login_required
def user(username):
all_posts =None
if username == session['logged_in']:
all_posts = show_post()
return render_template('user.html',all_posts=all_posts, username = username)
return redirect(url_for('error404'))
@app.route('/signup', methods=['POST','GET'])
def signup():
error = None
if request.method == 'POST':
user = login_data(request.form['username'], request.form['password'])
if login_data.query.filter_by(username=user.username).first():
error="Username Already exists"
else:
db.session.add(user)
db.session.commit()
return render_template("base.html",error=error)
# return redirect(url_for('home',error=error))
@app.route('/logout')
@login_required
def logout():
session.pop('logged_in', None)
session.pop('user_id', None)
session.pop('username', None)
return redirect(url_for('home'))
@app.route('/404')
def error404():
return render_template('404.html')
@app.route('/post-new', methods = ['POST','GET'])
@login_required
def postnew():
if request.method == 'POST':
post = request.form['post']
title = request.form['title']
tags = request.form['tags']
date = request.form['date']
time = request.form['time']
user_id = session['user_id']
save = post_data(post,title,tags,date+' '+time,user_id)
db.session.add(save)
db.session.commit()
return redirect(url_for('home'))
def show_post():
all_posts = post_data.query.filter_by(user_id= session['user_id']).order_by('-date')
return all_posts
@app.route('/search', methods = ['POST','GET'])
@login_required
def search():
results=None
if request.method == 'POST':
keyword = request.form['search']
results = post_data.query.filter_by(tags = keyword, user_id = session['user_id'])
return render_template('user.html',all_posts=results, username = session['username'])
| {
"repo_name": "gauravkulkarni96/MicroBlog",
"path": "app/views.py",
"copies": "1",
"size": "3174",
"license": "mit",
"hash": 7337272907820650000,
"line_mean": 31.0606060606,
"line_max": 89,
"alpha_frac": 0.6194076875,
"autogenerated": false,
"ratio": 3.699300699300699,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4818708386800699,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from application.models.user import User
from flask import request, jsonify
from application.helper.jwt.jwt_helper import jwt_decode
def required_token(f):
@wraps(f)
def decorated_function(*args, **kwargs):
error_response = jsonify(
userMessage="Authorization required"
), 401
try:
token_string = request.headers.get('Authorization')
except:
return error_response
try:
decoded_user = jwt_decode(token_string)
decoded_user_id = decoded_user['id']
except:
return error_response #TODO invalide token data
# print 2
# if User.query.filter(
# User.id == decoded_user_id).count() == 0:
# return error_response #TODO not found user
# print 3
return f(*args, **kwargs)
return decorated_function
def get_user_data_from_request(request):
"""
:param request:
:return: user data dic { "id": , "email", }
"""
token_string = request.headers.get('Authorization')
return jwt_decode(token_string) | {
"repo_name": "taewookimfardark/woohwa",
"path": "application/helper/rest/auth_helpler.py",
"copies": "1",
"size": "1138",
"license": "apache-2.0",
"hash": 2226574589516550400,
"line_mean": 27.475,
"line_max": 67,
"alpha_frac": 0.6001757469,
"autogenerated": false,
"ratio": 4.168498168498169,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5268673915398169,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from app.models.tokens import Tokens
from app.models.users import Users
from flask import Blueprint, request, jsonify, make_response
from flask.views import MethodView
from .base import BaseController
login = Blueprint('login', __name__, url_prefix='/api/login')
class TokenAPI(MethodView, BaseController):
def post(self):
"""
Create a Token for a valid User, providing e-mail and password
:return: JSON response
"""
validate = ['email', 'password']
try:
self.validate_fields(validate, request.form)
except ValueError:
return self.response(400, 'Required fields: ' + ' '.join(validate))
params = self.get_form_values(validate, request.form)
user = Users.query.filter_by(email=params['email']).first()
if user is None:
return self.response(400, 'Invalid user')
if not user.check_password(params['password']):
return self.response(401)
old_token = Tokens.query.filter_by(user_id=user.id).first()
if old_token is not None:
old_token.delete()
token = Tokens(user_id=user.id)
token.save()
json_response = {
'access_key': token.key,
'user': {
'name': token.user.name,
'e-mail': token.user.email,
},
'expiration': token.readable_expiration
}
return self.response(200, json_response)
def delete(self):
token = Tokens.query.filter(Tokens.key == request.headers['Authorization']).first()
if token:
token.delete()
return self.response(200)
token_view = TokenAPI.as_view('token_api')
login.add_url_rule('/', view_func=token_view, methods=['POST', 'DELETE'])
def login_required():
"""
Decorator for validate the Token provided in the HTTP Headers
:return: JSON response on error
"""
def decorator(f):
@wraps(f)
def validate_token(*args, **kwargs):
token = None
if request.headers.get('Authorization'):
token = Tokens.query.filter_by(key=request.headers['Authorization']).first()
error = None
response = {
'status': {
'code': 401,
'message': None
},
'success': False
}
if token is None:
error = 'Unauthorized Access'
if token:
if token.expired():
error = 'Login Expired'
if error:
response['status']['message'] = error
return make_response(jsonify(response), 401)
return f(*args, **kwargs)
return validate_token
return decorator
| {
"repo_name": "xeBuz/Ordbogen",
"path": "app/controllers/login.py",
"copies": "1",
"size": "2841",
"license": "mpl-2.0",
"hash": 3040053398513722000,
"line_mean": 27.1287128713,
"line_max": 92,
"alpha_frac": 0.5568461809,
"autogenerated": false,
"ratio": 4.3707692307692305,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.542761541166923,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from BinaryTreeExceptions import *
from Node import Node
def NotEmpty(function):
@wraps(function)
def wrapper(self, *args, **kwargs):
if self.isEmpty():
raise EmptyTree()
else:
return function(self, *args, **kwargs)
return wrapper
class BinaryTree(object):
def __init__(self, *args):
self.root = None
if len(args) is 0:
#===================================================================
# Default, empty, constructor.
# >>> tree = BinaryTree()
#===================================================================
pass
elif isinstance(args[0], Node):
#===================================================================
# Use the given node as the root of this tree.
#===================================================================
self.root = args[0]
elif '__iter__' in dir(args[0]):
#===================================================================
# Construct the binary tree using the given iterable.
# >>> evens = BinaryTree(number for number in range(101) if number % 2 is 0)
#===================================================================
for element in args[0]:
self.insert(element)
else:
#===================================================================
# Construct the binary tree using all given elements.
# >>> random = BinaryTree(56,7,2,5,8,23)
#===================================================================
for element in args:
self.insert(element)
def __contains__(self, element):
return element in self.root
def __str__(self):
return str(self.inOrder())
def isEmpty(self):
return self.root is None
def insert(self, element):
if self.isEmpty():
self.root = Node(element)
else:
self.root.insert(element)
return self
def inOrder(self):
return tuple(item for item in self.root.inOrder())
def preOrder(self):
return tuple(item for item in self.root.preOrder())
def postOrder(self):
return tuple(item for item in self.root.postOrder())
@NotEmpty
def decendantsOf(self, element):
return self.root.descendants(element)
@NotEmpty
def ancestorsOf(self, element):
return tuple(ancestor for ancestor in self.root.ancestors(element))
@NotEmpty
def isAncestorOf(self, targetAncestor, targetDescendant):
return self.root.isAncestorOf(targetAncestor, targetDescendant)
@NotEmpty
def isDescendantOf(self, targetDescendant, targetAncestor):
return self.root.isAncestorOf(targetAncestor, targetDescendant)
@NotEmpty
def min(self):
return self.root.min()
@NotEmpty
def max(self):
return self.root.max()
@NotEmpty
def root(self):
return self.root.element
@NotEmpty
def detachAt(self, element):
return BinaryTree(self.root.detachAt(element))
@NotEmpty
def levelOf(self, element):
return self.root.levelOf(element)
@NotEmpty
def height(self):
return max(self.root.height())
def attach(self, tree):
if not isinstance(tree, BinaryTree):
raise TypeError('Expected a Node. Received a {CLASS}'.format(CLASS=tree.__class__))
if self.root is None:
self.root = tree
else:
self.root.attach(tree.root)
return self | {
"repo_name": "christopher-henderson/Experiments",
"path": "structures/BinaryTree/binaryTree.py",
"copies": "2",
"size": "3711",
"license": "mit",
"hash": 2420535050707175000,
"line_mean": 31,
"line_max": 95,
"alpha_frac": 0.4896254379,
"autogenerated": false,
"ratio": 4.800776196636481,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6290401634536481,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from bson import json_util, datetime
import time
import api
# import timestamp
from api.exceptions import *
no_cache = False
fast_cache = {}
_mongo_index = None
def clear_all():
db = api.common.db_conn()
db.cache.remove()
fast_cache.clear()
def get_mongo_key(f, *args, **kwargs):
min_kwargs = dict(filter(lambda pair: pair[1] is not None, kwargs.items()))
return {
"function": "{}.{}".format(f.__module__, f.__name__),
"args": args,
"kwargs": min_kwargs
}
def get_key(f, *args, **kwargs):
if len(args) > 0:
kwargs["#args"] = ",".join(map(str, args))
sorted_keys = sorted(kwargs)
arg_key = "&".join(["{}:{}".format(key, kwargs[key]) for key in sorted_keys])
key = "{}.{}${}".format(f.__module__, f.__name__, arg_key).replace(" ", "~")
return key
def get(key, fast=False):
if fast:
return fast_cache.get(key, None)
db = api.common.db_conn()
cached_result = db.cache.find_one(key)
if cached_result is None:
return None
if int(time.time()) > cached_result["expireAt"].timestamp():
return None
if cached_result:
return cached_result["value"]
# raise WebException("Something screwed up.")
def set(key, value, timeout=120, fast=False):
if fast:
fast_cache[key] = {
"result": value,
"timeout": timeout,
"set_time": time.time()
}
return
db = api.common.db_conn()
update = key.copy()
update.update({ "value": value })
if timeout is not None:
expireAt = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
update.update({ "expireAt": expireAt })
db.cache.update(key, update, upsert=True)
def timed_out(info):
return int(time.time()) - info["set_time"] > info["timeout"]
def memoize(timeout=120, fast=False):
assert(not fast or (fast and timeout is not None)), "You can't set fast cache without a timeout!"
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not kwargs.get("cache", True):
kwargs.pop("cache", None)
return f(*args, **kwargs)
key = get_key(f, *args **kwargs) if fast else get_mongo_key(f, *args, **kwargs)
cached_result = get(key, fast=fast)
if cached_result is None or no_cache or (fast and timed_out(cached_result)):
function_result = f(*args, **kwargs)
set(key, function_result, timeout=timeout, fast=fast)
return function_result
return cached_result["result"] if fast else cached_result
return wrapper
return decorator
def invalid_memoization(f, args):
db = api.common.db_conn()
search = { "function": "{}.{}".format(f.__module__, f.__name__) }
search["args"] = list(args)
print(search)
# search.update({ "$or": list(keys) })
db.cache.remove(search) | {
"repo_name": "EasyCTF/easyctf-2015",
"path": "api/api/cache.py",
"copies": "1",
"size": "2660",
"license": "mit",
"hash": -999324910148613800,
"line_mean": 24.3428571429,
"line_max": 98,
"alpha_frac": 0.6496240602,
"autogenerated": false,
"ratio": 2.9588431590656286,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4108467219265628,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from collections import defaultdict
from prompt_toolkit.keys import Keys
import statinfo
class StatConstraintState:
# Selection states
NONE_SELECTED = 0x0 # Nothing selected
SINGLE_SELECTED = 0x1 # Single number selected (enter pressed once and not moved)
RANGE_SELECTED = 0x2 # Range selected (enter, move, enter)
RANGE_SELECTED_PENDING = 0x3 # Range partially selected (enter, move)
_default_state = {'state': NONE_SELECTED, 'low': 0, 'high': 0, 'start': 0}
def __init__(self):
self._state = defaultdict(self._default_state.copy)
def for_buffer(self, buffer):
if buffer not in statinfo.names:
raise NameError("No such stat")
return {k:v for k,v in self._state[buffer].items() if k != 'state'}
def get_cursor_bounds(self, buffer):
stats1, stats2, numeric, phys = statinfo.groups
stats = stats1 + stats2
if buffer in stats:
return range(18, 35+1)
# These next two may need some sort of alternate entry method
# like some slider bar at the bottom
elif buffer in numeric:
return range(15, 15+1) # TODO: allow alt entry (f'in")
elif buffer in phys:
return range(23, 31+1, 2)
def listen(self, func):
@wraps(func)
def wrapped(event):
current_buffer = event.current_buffer
current_buffer_name = event.cli.current_buffer_name
self._process_event_before(event)
x = func(event)
event.previous_buffer = current_buffer
event.previous_buffer_name = current_buffer_name
self._process_event_after(event)
return x
return wrapped
def _process_event_before(self, event):
buffer_name = event.current_buffer.text.split(':')[0]
key = event.key_sequence[0].key.name # non-character keys are key objects in events
cursor_pos = event.current_buffer.cursor_position - 17
full_state = self._state[buffer_name]
state = full_state['state']
low, high = sorted((cursor_pos, full_state['start']))
if key in (Keys.Up.name, Keys.Down.name):
# Reset selection to single, other option was to set to range
if state == self.RANGE_SELECTED_PENDING:
full_state.update(state=self.SINGLE_SELECTED, low=cursor_pos, high=cursor_pos, start=cursor_pos)
elif key in (Keys.Left.name, Keys.Right.name):
if state == self.RANGE_SELECTED_PENDING:
full_state.update(low=low, high=high)
elif state == self.SINGLE_SELECTED:
full_state.update(state=self.RANGE_SELECTED_PENDING, low=low, high=high)
elif key == Keys.Enter.name:
if state in (self.NONE_SELECTED, self.RANGE_SELECTED):
full_state.update(state=self.SINGLE_SELECTED, low=cursor_pos, high=cursor_pos, start=cursor_pos)
elif state == self.RANGE_SELECTED_PENDING:
if low == high:
full_state.update(state=self.SINGLE_SELECTED, low=low, high=high)
else:
full_state.update(state=self.RANGE_SELECTED, low=low, high=high)
def _process_event_after(self, event):
last_buffer_name = event.previous_buffer.text.split(':')[0]
key = event.key_sequence[0].key.name # non-character keys are key objects in events
last_cursor_pos = event.previous_buffer.cursor_position - 17
full_state = self._state[last_buffer_name]
state = full_state['state']
if key in (Keys.Up.name, Keys.Down.name):
if state == self.RANGE_SELECTED_PENDING:
full_state.update(state=self.SINGLE_SELECTED)
class StatConstraint:
def __init__(self, stat, *, lower, upper, min, max, value=None):
if upper > max:
raise ValueError(f"Upper bound cannot be greater than max value ({upper} > {max})")
if lower < min:
raise ValueError(f"Lower bound cannot be less than than min value ({lower} > {min})")
if upper < lower:
raise ValueError(f"Upper bound cannot be lower than lower bound ({upper} < {lower}")
self.stat = stat
self.lower = lower
self.upper = upper
self.min = min
self.max = max
self.value = None
self.low_token = self.high_token = ' '
self.mid_token = '-'
self.mid_low_bound_token = '>'
self.mid_high_bound_token = '<'
self.mid_same_bound_token = 'O'
self.valid_token = '@'
self.invalid_token = 'x'
def set(self, value):
self.value = min(self.upper, max(self.lower, value))
return self.value
def is_in_bounds(self, value):
return self.lower <= value <= self.upper
def is_valid(self, value):
return self.min <= value <= self.max
def visualize(self, value=None):
if value is not None:
if not self.is_valid(value):
raise ValueError(f"Value not within bounds ({self.min} <= {value} <= {self.max})")
elif not self.is_in_bounds(value) and self.invalid_token is None:
value = None
total_range = self.max - self.min
ok_range = self.upper - self.lower
low = self.low_token * (self.lower - 1)
high = self.high_token * (total_range - ok_range - len(low))
if self.lower == self.upper:
mid = self.mid_same_bound_token
else:
mid = (self.mid_token * (self.upper - self.lower - 1)).join(
self.mid_low_bound_token + self.mid_high_bound_token)
if value is not None:
chars = list(f"[{low}{mid}{high}]")
t = self.valid_token if self.is_in_bounds(value) else self.invalid_token
chars[value - self.min + 1] = t
return ''.join(chars)
else:
return f"[{low}{mid}{high}]"
class InteractiveStatSetup:
"""
Will post instructions and guide through stat selection process.
Clear stats and constraints
Select first buffer
(if we have race data, place cursor on top of bell curve value)
(need to consider the no data/dont care button (space?))
(stat info will be posted as usual)
Constraints will be entered by the user
(need to thing about how to do weight/height)
focus will move to some "start button"
press enter to begin etc
"""
def __init__(self, ui):
self.ui = ui
self.process_events = True
def on_event(self, event):
if not self.process_events:
return
def start(self):
...
| {
"repo_name": "imayhaveborkedit/urw-stat-roller",
"path": "interactions.py",
"copies": "1",
"size": "6725",
"license": "mit",
"hash": 9107168874637084000,
"line_mean": 33.3112244898,
"line_max": 112,
"alpha_frac": 0.5943494424,
"autogenerated": false,
"ratio": 3.873847926267281,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4968197368667281,
"avg_score": null,
"num_lines": null
} |
from functools import wraps
from collections import defaultdict
import asyncio
import atexit
import os
from asyncio import coroutine, Task
from pyadds.annotate import cached, delayed
from pyadds.logging import log
from pyadds.forkbug import maybug
from . import resolve
from . import rpc
from . import idd
@log
class Process:
def __init__(self, tracker):
self.tracker = tracker
self.receiver = resolve.Receiver.defaults(tracker=tracker)
self.deliver = resolve.Deliver.defaults(tracker=tracker)
self.outs = defaultdict(list)
self.units = {}
@coroutine
def setup(self):
self.__log.debug('setting up %s', self)
self.trloop = yield from self.tracker.setup()
@coroutine
def register(self, unit, outs, ins):
self.__log.debug('register %r/%x', unit, id(unit))
try:
unit = self.units[unit.id.idd]
except KeyError:
with maybug():
yield from unit.__setup__()
self.units[unit.id.idd] = unit
for l in outs:
chan = yield from self.deliver[l.endpoint].register(unit, l)
outs = self.outs[l.source.pid]
out = (l.target.pid, chan)
if out not in outs:
outs.append(out)
l.source.of(unit).handle = self.handler(l.source.pid)
for l in ins:
yield from self.receiver[l.endpoint].register(unit, l)
@coroutine
def activate(self, outs, ins):
for l in outs:
yield from self.deliver[l.endpoint].activate(l)
for l in ins:
yield from self.receiver[l.endpoint].activate(l)
@coroutine
def info(self):
return Task.all_tasks()
def handler(self, src):
outs = self.outs[src]
aquire = self.tracker.aquire
@coroutine
def handle(self, packet):
aq = asyncio.gather(*(aquire(tgt) for tgt,_ in outs))
dl = asyncio.gather(*(chan.deliver((tgt, packet))
for tgt,chan in outs))
yield from asyncio.gather(aq, dl)
return handle
@coroutine
def close(self, uid):
...
@coroutine
def shutdown(self):
@coroutine
def down():
try:
self.__log.debug('shutdown closes all channels')
yield from asyncio.gather(*(
chan.close() for outs in self.outs.values() for _,chan in outs))
self.__log.debug('tearing down units')
yield from asyncio.gather(*(
unit.__teardown__() for unit in self.units.values()))
if self.trloop:
self.trloop.cancel()
yield from asyncio.gather(trloop)
if self.trloop.exception():
self.__log.warning('%s in tr-loop', self.trloop.exception())
else:
self.__log.warning('tr-loop returned', self.trloop.result())
self.trloop = None
except Exception as e:
self.__log.error('%s occured when shutting down', e, exc_info=True)
yield from asyncio.sleep(.5)
self.__log.debug('exiting')
asyncio.get_event_loop().stop()
asyncio.async(down())
@log
class Control:
def __init__(self, *, ctx, tp):
self.tp = tp
self.path = str(self.tp.path)
self.spawner = ctx.spawner
self.procs = {}
self.remotes = {}
self.units = {}
self.queued = []
atexit.register(self.shutdown)
def queue(self, coro):
self.queued.append(coro)
def replay(self):
@coroutine
def replay():
while self.queued:
coro = self.queued.pop()
yield from coro
yield from replay()
#return asyncio.async(replay())
@cached
def local(self):
return None
@cached
def tracker(self):
return rpc.Tracker(self.tp.path)
def register(self, unit):
self.units[unit.id] = unit
@coroutine
def ensure(self, space):
if not space.bound:
if not self.local:
proc = self.local = Process(tracker=rpc.Master(self.tp.path))
yield from proc.setup()
else:
proc = self.local
self.__log.debug('{!r} is local'.format(space))
return self.local
try:
return self.remotes[space]
except KeyError:
self.__log.debug('spawning for {!r}'.format(space))
@coroutine
def init_rpc(i=None):
path = space.path
if i is not None:
path += idd.Named('replicate', 'rep-'+str(i))
remote = rpc.Remote(Process(tracker=self.tracker), endpoint=path)
proc = yield from self.spawner.cospawn(remote.__remote__, __name__=str(space))
with open(path.namespace()+'/pids', 'a') as f:
f.write('{}\n'.format(proc.pid))
yield from remote.__setup__()
yield from remote.setup()
return remote,proc
if space.replicate:
rpcs = yield from asyncio.gather(*(
init_rpc(i) for i in range(space.replicate)))
remotes = [r for r,_ in rpcs]
procs = [p for _,p in rpcs]
remote = rpc.Multi(remotes)
else:
remote,proc = yield from init_rpc()
procs = [proc]
self.remotes[space] = remote
self.procs[space] = procs
return remote
def shutdown(self):
atexit.unregister(self.shutdown)
if self.procs:
self.__log.info('shuting down all processes')
@coroutine
def shutdown(remote, procs):
try:
yield from asyncio.wait_for(remote.shutdown(), timeout=5)
except asyncio.TimeoutError:
self.__log.warn("can't shutdown %s properly, killing it", set(procs))
for p in procs:
p.terminate()
future = asyncio.gather(*[shutdown(remote, proc)
for remote,proc in zip(self.remotes.values(), self.procs.values())],
return_exceptions=True)
asyncio.get_event_loop().run_until_complete(future)
for r in future:
if r:
self.__log.warn('%r when shuting down', r)
self.procs.clear()
self.remotes.clear()
os.system("rm -rf {!r}".format(self.path))
def __del__(self):
self.shutdown()
@coroutine
def activate(self, unit, actives=set()):
u = self.tp.lookup(unit)
self.__log.debug('activate {!r} on {!r}'.format(u, u.space))
chan = yield from self.ensure(u.space)
self.__log.debug('using {!r}'.format(chan))
yield from chan.register(unit, self.tp.links_from(u), self.tp.links_to(u))
self.__log.debug('registered')
yield from chan.activate(self.tp.links_from(u), self.tp.links_to(u))
self.__log.debug('activated')
u.active = True
for l in self.tp.links_from(u):
tgt = l.target.unit
if tgt in actives:
continue
yield from self.activate(self.units[tgt.id], actives|{tgt})
@coroutine
def await(self, unit):
yield from self.replay()
deps = self.tp.dependencies(unit, kind='target')
self.__log.debug('%s depends on %s', unit, deps)
deps = [p.pid for p in deps]
self.__log.debug('%s depends on %s', unit, ['%x' % p for p in deps])
yield from self.local.tracker.await(*deps)
@coroutine
def close(self, unit):
chan = yield from self.ensure(self.tp[unit].space)
yield from chan.close(unit.id.idd)
| {
"repo_name": "wabu/zeroflo",
"path": "zeroflo/core/control.py",
"copies": "1",
"size": "8034",
"license": "mit",
"hash": -150892309565086050,
"line_mean": 30.2607003891,
"line_max": 94,
"alpha_frac": 0.5296240976,
"autogenerated": false,
"ratio": 4.12,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5149624097600001,
"avg_score": null,
"num_lines": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.