def _get_view_func(view): if _is_callback(view): mod, func = get_mod_func(view) try: # Separate the module and function, e.g. # 'mymodule.views.myview' -> 'mymodule.views', 'myview'). return getattr(import_module(mod), func) except ImportError: # Import may fail because view contains a class name, e.g. # 'mymodule.views.ViewContainer.my_view', so mod takes the form # 'mymodule.views.ViewContainer'. Parse it again to separate # the module and class. mod, klass = get_mod_func(mod) return getattr(getattr(import_module(mod), klass), func)
def _get_view_func(view): urlconf = get_urlconf() if get_resolver(urlconf)._is_callback(view): mod, func = get_mod_func(view) try: # Separate the module and function, e.g. # 'mymodule.views.myview' -> 'mymodule.views', 'myview'). return getattr(import_module(mod), func) except ImportError: # Import may fail because view contains a class name, e.g. # 'mymodule.views.ViewContainer.my_view', so mod takes the form # 'mymodule.views.ViewContainer'. Parse it again to separate # the module and class. mod, klass = get_mod_func(mod) return getattr(getattr(import_module(mod), klass), func)
def get_data_fixture(default='sequential'): # It must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass' try: INTERNAL_DATA_FIXTURES = { 'sequential': SequentialDataFixture(), 'static_sequential': StaticSequentialDataFixture(), 'global_sequential': GlobalSequentialDataFixture(), 'random': RandomDataFixture() } if hasattr(settings, 'DDF_DEFAULT_DATA_FIXTURE'): if settings.DDF_DEFAULT_DATA_FIXTURE in INTERNAL_DATA_FIXTURES.keys( ): return INTERNAL_DATA_FIXTURES[ settings.DDF_DEFAULT_DATA_FIXTURE] else: # path.to.CustomDataFixtureClass mod_name, obj_name = get_mod_func( settings.DDF_DEFAULT_DATA_FIXTURE) module = import_module(mod_name) custom_data_fixture = getattr(module, obj_name) return custom_data_fixture() else: return INTERNAL_DATA_FIXTURES[default] except: six.reraise( DDFImproperlyConfigured, DDFImproperlyConfigured( "DDF_DEFAULT_DATA_FIXTURE (%s) must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass'." % settings.DDF_DEFAULT_DATA_FIXTURE), sys.exc_info()[2])
def callback(self): if self._callback is not None: return self._callback elif self._callback_str is None: return lambda *args, **kwargs: None try: self._callback = get_callable(self._callback_str) except ImportError as exc: mod_name, _ = get_mod_func(self._callback_str) raise ImproperlyConfigured("Could not import '%s'. " "Error was: %s" % (mod_name, str(exc))) except AttributeError as exc: mod_name, func_name = get_mod_func(self._callback_str) raise ImproperlyConfigured("Tried importing '%s' from module " "'%s' but failed. Error was: %s" % (func_name, mod_name, str(exc))) return self._callback
def _get_view_func(view): urlconf = get_urlconf() if get_resolver(urlconf)._is_callback(view): mod, func = get_mod_func(view) try: # Separate the module and function, e.g. # 'mymodule.views.myview' -> 'mymodule.views', 'myview'). return getattr(import_module(mod), func) except ImportError: # Import may fail because view contains a class name, e.g. # 'mymodule.views.ViewContainer.my_view', so mod takes the form # 'mymodule.views.ViewContainer'. Parse it again to separate # the module and class. mod, klass = get_mod_func(mod) return getattr(getattr(import_module(mod), klass), func) except AttributeError: # PY2 generates incorrect paths for views that are methods, # e.g. 'mymodule.views.ViewContainer.my_view' will be # listed as 'mymodule.views.my_view' because the class name # can't be detected. This causes an AttributeError when # trying to resolve the view. return None
def get_context_data(self, **kwargs): view = self.kwargs['view'] urlconf = get_urlconf() if get_resolver(urlconf)._is_callback(view): mod, func = get_mod_func(view) view_func = getattr(import_module(mod), func) else: raise Http404 title, body, metadata = utils.parse_docstring(view_func.__doc__) if title: title = utils.parse_rst(title, 'view', _('view:') + view) if body: body = utils.parse_rst(body, 'view', _('view:') + view) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view) kwargs.update({ 'name': view, 'summary': title, 'body': body, 'meta': metadata, }) return super(ViewDetailView, self).get_context_data(**kwargs)
six.reraise(DDFImproperlyConfigured, DDFImproperlyConfigured("%s (%s) must be True or False." % (config_name, getattr(settings, config_name))), sys.exc_info()[2]) # DDF_DEFAULT_DATA_FIXTURE default = 'sequential' # It must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass' try: INTERNAL_DATA_FIXTURES = {'sequential': SequentialDataFixture(), 'static_sequential': StaticSequentialDataFixture(), 'global_sequential': GlobalSequentialDataFixture(), 'random': RandomDataFixture()} if hasattr(settings, 'DDF_DEFAULT_DATA_FIXTURE'): if settings.DDF_DEFAULT_DATA_FIXTURE in INTERNAL_DATA_FIXTURES.keys(): DDF_DEFAULT_DATA_FIXTURE = INTERNAL_DATA_FIXTURES[settings.DDF_DEFAULT_DATA_FIXTURE] else: # path.to.CustomDataFixtureClass mod_name, obj_name = get_mod_func(settings.DDF_DEFAULT_DATA_FIXTURE) module = import_module(mod_name) custom_data_fixture = getattr(module, obj_name) DDF_DEFAULT_DATA_FIXTURE = custom_data_fixture() else: DDF_DEFAULT_DATA_FIXTURE = INTERNAL_DATA_FIXTURES['sequential'] except: six.reraise(DDFImproperlyConfigured, DDFImproperlyConfigured("DDF_DEFAULT_DATA_FIXTURE (%s) must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass'." % settings.DDF_DEFAULT_DATA_FIXTURE), sys.exc_info()[2]) # DDF_IGNORE_FIELDS default = [] try: DDF_IGNORE_FIELDS = list(settings.DDF_IGNORE_FIELDS) if hasattr(settings, 'DDF_IGNORE_FIELDS') else [] except Exception as e: six.reraise(DDFImproperlyConfigured, DDFImproperlyConfigured("DDF_IGNORE_FIELDS (%s) must be a list of strings" % settings.DDF_IGNORE_FIELDS), sys.exc_info()[2])
def _form_handler(request, form_cls, require_login=False, block_get=False, ajax=False, next=None, template=None, login_url=None, pass_request=True, validate_only=False, **kwargs): """ Some ajax heavy apps require a lot of views that are merely a wrapper around the form. This generic view can be used for them. """ RESULT_KEY = getattr(settings, "RESULT_KEY", "response") request.REQUEST = request.GET.copy() request.REQUEST.update(request.POST) if "next" in request.REQUEST: next = request.REQUEST["next"] is_ajax = request.is_ajax() or ajax or request.REQUEST.get( "json") == "true" if isinstance(form_cls, basestring): # can take form_cls of the form: "project.app.forms.FormName" mod_name, form_name = get_mod_func(form_cls) form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name) validate_only = (validate_only or request.REQUEST.get("validate_only") == "true") if login_url is None: login_url = getattr(settings, "LOGIN_URL", "/login/") if callable(require_login): require_login = require_login(request) elif require_login: require_login = not request.user.is_authenticated() if require_login: redirect_url = "%s?next=%s" % ( login_url, urlquote(request.get_full_path())) # FIXME if is_ajax: return JSONResponse({'success': False, 'redirect': redirect_url}) return HttpResponseRedirect(redirect_url) if block_get and request.method != "POST": raise Http404("only post allowed") if next: assert template, "template required when next provided" def get_form(with_data=False): _form = form_cls(request) if pass_request else form_cls() _form.next = next if with_data: _form.data = request.REQUEST _form.files = request.FILES _form.is_bound = True if hasattr(_form, "init"): res = _form.init(**kwargs) if res: raise ResponseReady(res) return _form if is_ajax and request.method == "GET": return JSONResponse(get_form_representation(get_form())) if template and request.method == "GET": return render(request, template, {"form": get_form()}) form = get_form(with_data=True) if form.is_valid(): if validate_only: return JSONResponse({"valid": True, "errors": {}}) r = form.save() if is_ajax: return JSONResponse({ 'success': True, RESULT_KEY: (form.get_json(r) if hasattr(form, "get_json") else r) }) if isinstance(r, HttpResponse): return r if next: return HttpResponseRedirect(next) if template: return HttpResponseRedirect(r) return JSONResponse({ 'success': True, RESULT_KEY: (form.get_json(r) if hasattr(form, "get_json") else r) }) if validate_only: if "field" in request.REQUEST: errors = form.errors.get(request.REQUEST["field"], "") if errors: errors = "".join(errors) else: errors = form.errors return JSONResponse({"errors": errors, "valid": not errors}) if is_ajax: return JSONResponse({'success': False, 'errors': form.errors}) if template: return render(request, template, {"form": form}) return JSONResponse({'success': False, 'errors': form.errors})
False) RESTRICT_OOTB_AUTH = getattr(settings, 'RPC4DJANGO_RESTRICT_OOTB_AUTH', True) JSON_ENCODER = getattr(settings, 'RPC4DJANGO_JSON_ENCODER', 'django.core.serializers.json.DjangoJSONEncoder') try: # Python2 basestring except NameError: # Python3 basestring = str # resolve JSON_ENCODER to class if it's a string if isinstance(JSON_ENCODER, basestring): mod_name, cls_name = get_mod_func(JSON_ENCODER) json_encoder = getattr(import_module(mod_name), cls_name) else: json_encoder = JSON_ENCODER # instantiate the rpcdispatcher -- this examines the INSTALLED_APPS # for any @rpcmethod decorators and adds them to the callable methods dispatcher = RPCDispatcher(RESTRICT_INTROSPECTION, RESTRICT_OOTB_AUTH, json_encoder) def rpcmethod(**kwargs): ''' Accepts keyword based arguments that describe the method's rpc aspects **Parameters**
from django.conf import settings try: from django.urls import get_mod_func except ImportError: # For Django <2.0 from django.core.urlresolvers import get_mod_func REGISTRY = {} loggers = getattr(settings, 'DJTRIGGERS_LOGGERS', ()) for entry in loggers: module_name, class_name = get_mod_func(entry) logger_class = getattr(__import__(module_name, {}, {}, ['']), class_name) instance = logger_class() REGISTRY[class_name] = instance def get_logger(slug): return REGISTRY.get(slug, None)
def _form_handler( request, form_cls, require_login=False, block_get=False, ajax=False, next=None, template=None, login_url=None, pass_request=True, validate_only=False, **kwargs ): """ Some ajax heavy apps require a lot of views that are merely a wrapper around the form. This generic view can be used for them. """ RESULT_KEY = getattr(settings, "RESULT_KEY", "response") request.REQUEST = request.GET.copy() request.REQUEST.update(request.POST) if "next" in request.REQUEST: next = request.REQUEST["next"] is_ajax = request.is_ajax() or ajax or request.REQUEST.get("json") == "true" if isinstance(form_cls, basestring): # can take form_cls of the form: "project.app.forms.FormName" mod_name, form_name = get_mod_func(form_cls) form_cls = getattr(__import__(mod_name, {}, {}, ['']), form_name) validate_only = ( validate_only or request.REQUEST.get("validate_only") == "true" ) if login_url is None: login_url = getattr(settings, "LOGIN_URL", "/login/") if callable(require_login): require_login = require_login(request) elif require_login: require_login = not request.user.is_authenticated() if require_login: redirect_url = "%s?next=%s" % ( login_url, urlquote(request.get_full_path()) ) # FIXME if is_ajax: return JSONResponse({'success': False, 'redirect': redirect_url}) return HttpResponseRedirect(redirect_url) if block_get and request.method != "POST": raise Http404("only post allowed") if next: assert template, "template required when next provided" def get_form(with_data=False): _form = form_cls(request) if pass_request else form_cls() _form.next = next if with_data: _form.data = request.REQUEST _form.files = request.FILES _form.is_bound = True if hasattr(_form, "init"): res = _form.init(**kwargs) if res: raise ResponseReady(res) return _form if is_ajax and request.method == "GET": return JSONResponse(get_form_representation(get_form())) if template and request.method == "GET": return render(request, template, {"form": get_form()}) form = get_form(with_data=True) if form.is_valid(): if validate_only: return JSONResponse({"valid": True, "errors": {}}) r = form.save() if is_ajax: return JSONResponse( { 'success': True, RESULT_KEY: ( form.get_json(r) if hasattr(form, "get_json") else r ) } ) if isinstance(r, HttpResponse): return r if next: return HttpResponseRedirect(next) if template: return HttpResponseRedirect(r) return JSONResponse( { 'success': True, RESULT_KEY: ( form.get_json(r) if hasattr(form, "get_json") else r ) } ) if validate_only: if "field" in request.REQUEST: errors = form.errors.get(request.REQUEST["field"], "") if errors: errors = "".join(errors) else: errors = form.errors return JSONResponse({"errors": errors, "valid": not errors}) if is_ajax: return JSONResponse({'success': False, 'errors': form.errors}) if template: return render(request, template, {"form": form}) return JSONResponse({'success': False, 'errors': form.errors})