Ejemplo n.º 1
0
 def test_render_json_jsonp_bad_name(self):
   # Bad names
   for x in [r"%evil-name", "3vil", "", "evil%"]:
     assert_raises(django_util.IllegalJsonpCallbackNameException,
       django_util.render_json, "whatever-value", x)
   # Fine names
   for x in ["a", "$", "_", "a9", "a9$"]:
     django_util.render_json("whatever-value", x)
Ejemplo n.º 2
0
 def test_render_json_jsonp_bad_name(self):
   # Bad names
   for x in [r"%evil-name", "3vil", "", "evil%"]:
     assert_raises(django_util.IllegalJsonpCallbackNameException,
       django_util.render_json, "whatever-value", x)
   # Fine names
   for x in ["a", "$", "_", "a9", "a9$"]:
     django_util.render_json("whatever-value", x)
Ejemplo n.º 3
0
def login_ajax(request):
    username = request.POST.get("username")
    user = authenticate(username=username, password=request.POST.get("password"))
    if user:
        access_warn(request, '"%s" login ok' % (user.username,))
        login(request, user)
        return render_json(dict(success=True))
    else:
        access_warn(request, 'Failed login for user "%s"' % (username,))
        return render_json(dict(success=False))
Ejemplo n.º 4
0
def login_ajax(request):
    username = request.POST.get('username')
    user = authenticate(username=username,
                        password=request.POST.get('password'))
    if user:
        access_warn(request, '"%s" login ok' % (user.username, ))
        login(request, user)
        return render_json(dict(success=True))
    else:
        access_warn(request, 'Failed login for user "%s"' % (username, ))
        return render_json(dict(success=False))
Ejemplo n.º 5
0
Archivo: views.py Proyecto: atm/hue
def login_ajax(request):
  username = request.POST.get('username')
  user = authenticate(username=username,
                      password=request.POST.get('password'))
  if user:
    access_warn(request, '"%s" login ok' % (user.username,))
    login(request, user)
    _add_to_current_users(user, AccessInfo(request))

    return render_json(dict(success=True))
  else:
    access_warn(request, 'Failed login for user "%s"' % (username,))
    return render_json(dict(success=False))
Ejemplo n.º 6
0
def delete_design(request, design_id):
    if request.method != 'POST':
        raise StructuredException(code="METHOD_NOT_ALLOWED_ERROR",
                                  message=_('Must be POST request.'),
                                  error_code=405)

    skip_trash = 'skip_trash' in request.GET

    try:
        workflow = _get_design(design_id)
        _check_permission(request,
                          workflow.owner.username,
                          _("Access denied: delete design %(id)s.") %
                          {'id': design_id},
                          allow_root=True)
        if skip_trash:
            Workflow.objects.destroy(workflow, request.fs)
        else:
            workflow.delete(skip_trash=False)

    except Workflow.DoesNotExist:
        raise StructuredException(code="NOT_FOUND",
                                  message=_('Could not find design %s.') %
                                  design_id,
                                  error_code=404)

    return render_json({'status': 0})
Ejemplo n.º 7
0
def view(request, path):
    """Dispatches viewing of a path to either index() or fileview(), depending on type."""

    # default_to_home is set in bootstrap.js
    if 'default_to_home' in request.GET:
        home_dir_path = request.user.get_home_directory()
        if request.fs.isdir(home_dir_path):
            return format_preserving_redirect(request, reverse(view, kwargs=dict(path=home_dir_path)))

    # default_to_home is set in bootstrap.js
    if 'default_to_trash' in request.GET:
        home_trash = request.fs.join(request.fs.trash_path, 'Current', request.user.get_home_directory()[1:])
        if request.fs.isdir(home_trash):
            return format_preserving_redirect(request, reverse(view, kwargs=dict(path=home_trash)))
        if request.fs.isdir(request.fs.trash_path):
            return format_preserving_redirect(request, reverse(view, kwargs=dict(path=request.fs.trash_path)))

    try:
        stats = request.fs.stats(path)
        if stats.isDir:
            return listdir_paged(request, path)
        else:
            return display(request, path)
    except (IOError, WebHdfsException), e:
        msg = _("Cannot access: %(path)s.") % {'path': escape(path)}
        if request.user.is_superuser and not request.user == request.fs.superuser:
            msg += _(' Note: You are a Hue admin but not a HDFS superuser (which is "%(superuser)s").') % {'superuser': request.fs.superuser}
        if request.is_ajax():
          exception = {
            'error': msg
          }
          return render_json(exception)
        else:
          raise PopupException(msg , detail=e)
Ejemplo n.º 8
0
Archivo: views.py Proyecto: ronwxy/hue
def kill_task_attempt(request, attemptid):
  """
  We get here from /jobs/jobid/tasks/taskid/attempts/attemptid/kill
  TODO: security
  """
  ret = request.jt.kill_task_attempt(request.jt.thriftattemptid_from_string(attemptid))
  return render_json({})
Ejemplo n.º 9
0
def kill_task_attempt(request, attemptid):
  """
  We get here from /jobs/jobid/tasks/taskid/attempts/attemptid/kill
  TODO: security
  """
  ret = request.jt.kill_task_attempt(request.jt.thriftattemptid_from_string(attemptid))
  return render_json({})
Ejemplo n.º 10
0
  def process_exception(self, request, exception):
    import traceback
    tb = traceback.format_exc()
    logging.info("Processing exception: %s: %s" % (i18n.smart_unicode(exception),
                                                   i18n.smart_unicode(tb)))

    if hasattr(exception, "response"):
      return exception.response(request)

    if hasattr(exception, "response_data"):
      if request.ajax:
        response = render_json(exception.response_data)
        response[MIDDLEWARE_HEADER] = 'EXCEPTION'
        return response
      else:
        return render("error.mako", request,
                      dict(error=exception.response_data.get("message")))

    # We didn't handle it as a special exception, but if we're ajax we still
    # need to do some kind of nicer handling than the built-in page
    # Note that exception may actually be an Http404 or similar.
    if request.ajax:
      err = _("An error occurred: %(error)s") % {'error': exception}
      logging.exception("Middleware caught an exception")
      return PopupException(err, detail=None).response(request)

    return None
Ejemplo n.º 11
0
Archivo: views.py Proyecto: dizhu/hue
def save_design(request, design_id):
  workflow = _get_design(design_id)
  _check_permission(request, workflow.owner.username, _("Access denied: edit design %(id)s.") % {'id': workflow.id})

  ActionForm = design_form_by_type(request.POST.get('node_type', None), request.user, workflow)
  form = ActionForm(request.POST)

  if not form.is_valid():
    raise StructuredException(code="INVALID_REQUEST_ERROR", message=_('Error saving design'), data={'errors': form.errors}, error_code=400)

  data = format_dict_field_values(request.POST.copy())
  sanitize_node_dict(data)
  workflow.name = data['name']
  workflow.description = data['description']
  node = workflow.start.get_child('to').get_full_node()
  node_id = node.id
  for key in data:
    setattr(node, key, data[key])
  node.id = node_id
  node.pk = node_id
  node.save()
  workflow.save()

  data['id'] = workflow.id
  return render_json(data);
Ejemplo n.º 12
0
Archivo: views.py Proyecto: dizhu/hue
def new_design(request, node_type):
  """
  Designs are the interpolation of Workflows and a single action.
  Save ``name`` and ``description`` of workflows.
  Also, use ``id`` of workflows.
  """
  if request.method != 'POST':
    raise StructuredException(code="METHOD_NOT_ALLOWED_ERROR", message=_('Must be POST request.'), error_code=405)

  workflow = Workflow.objects.new_workflow(request.user)
  ActionForm = design_form_by_type(node_type, request.user, workflow)
  form = ActionForm(request.POST)

  if not form.is_valid():
    raise StructuredException(code="INVALID_REQUEST_ERROR", message=_('Error saving design'), data={'errors': form.errors}, error_code=400)

  workflow.managed = False
  # Every one should be able to execute and clone a design.
  workflow.is_shared = True
  workflow.save()
  Workflow.objects.initialize(workflow, request.fs)
  action = form.save(commit=False)
  action.workflow = workflow
  action.node_type = node_type
  action.save()
  workflow.start.add_node(action)
  action.add_node(workflow.end)
  workflow.name = request.POST.get('name')
  workflow.description = request.POST.get('description')
  workflow.save()

  data = format_dict_field_values(request.POST.copy())
  data['id'] = workflow.id
  return render_json(data)
Ejemplo n.º 13
0
    def process_exception(self, request, exception):
        import traceback
        tb = traceback.format_exc()
        logging.info("Processing exception: %s: %s" %
                     (i18n.smart_unicode(exception), i18n.smart_unicode(tb)))

        if isinstance(exception, PopupException):
            return exception.response(request)

        if isinstance(exception, StructuredException):
            if request.ajax:
                response = render_json(exception.response_data)
                response[MIDDLEWARE_HEADER] = 'EXCEPTION'
                response.status_code = getattr(exception, 'error_code', 500)
                return response
            else:
                response = render(
                    "error.mako", request, {
                        'error': exception.response_data.get("message"),
                        'is_embeddable': request.GET.get(
                            'is_embeddable', False),
                    })
                response.status_code = getattr(exception, 'error_code', 500)
                return response

        return None
Ejemplo n.º 14
0
    def process_exception(self, request, exception):
        import traceback
        logging.info("Processing exception: %s: %s" %
                     (exception, traceback.format_exc()))

        if hasattr(exception, "response"):
            return exception.response(request)

        if hasattr(exception, "response_data"):
            if request.ajax:
                response = render_json(exception.response_data)
                response[MIDDLEWARE_HEADER] = 'EXCEPTION'
                return response
            else:
                return render_to_response(
                    "error.html",
                    dict(error=exception.response_data.get("message")))

        # We didn't handle it as a special exception, but if we're ajax we still
        # need to do some kind of nicer handling than the built-in page
        # Note that exception may actually be an Http404 or similar.
        if request.ajax:
            err = "An error occurred: %s" % (exception, )
            logging.exception("Middleware caught an exception")
            return PopupException(err, detail=None).response(request)

        return None
Ejemplo n.º 15
0
def list_designs(request):
    """
  List all workflow designs. Result sorted by last modification time.
  Query params:
    owner       - Substring filter by owner field
    name        - Substring filter by design name field
  """
    data = Workflow.objects.filter(managed=False)
    owner = request.GET.get("owner", "")
    name = request.GET.get("name", "")
    if owner:
        data = data.filter(owner__username__icontains=owner)
    if name:
        data = data.filter(name__icontains=name)
    data = data.order_by("-last_modified")

    designs = []
    for design in data:
        ko_design = {
            "id": design.id,
            "owner": design.owner.username,
            # Design name is validated by workflow and node forms.
            "name": design.name,
            "description": design.description,
            "node_type": design.start.get_child("to").node_type,
            "last_modified": py_time.mktime(design.last_modified.timetuple()),
            "editable": design.owner.id == request.user.id,
            "is_shared": design.is_shared,
        }
        designs.append(ko_design)

    if request.is_ajax():
        return render_json(designs, js_safe=True)
    else:
        return render("designs.mako", request, {"currentuser": request.user, "owner": owner, "name": name})
Ejemplo n.º 16
0
def set_job_priority(request, jobid):
  """
  We get here from /jobs/jobid/setpriority?priority=PRIORITY
  """
  priority = request.GET.get("priority")
  jid = request.jt.thriftjobid_from_string(jobid)
  request.jt.set_job_priority(jid, ThriftJobPriority._NAMES_TO_VALUES[priority])
  return render_json({})
Ejemplo n.º 17
0
def set_job_priority(request, job):
  """
  We get here from /jobs/job/setpriority?priority=PRIORITY
  """
  priority = request.GET.get("priority")
  jid = request.jt.thriftjobid_from_string(job.jobId)
  request.jt.set_job_priority(jid, ThriftJobPriority._NAMES_TO_VALUES[priority])
  return render_json({})
Ejemplo n.º 18
0
def get_design(request, design_id):
    workflow = _get_design(design_id)
    node = workflow.start.get_child('to')
    node_dict = model_to_dict(node)
    node_dict['id'] = design_id
    node_dict['is_shared'] = workflow.is_shared
    node_dict['editable'] = workflow.owner.id == request.user.id
    node_dict['parameters'] = workflow.parameters
    return render_json(node_dict, js_safe=True)
Ejemplo n.º 19
0
def get_design(request, design_id):
  workflow = _get_design(design_id)
  node = workflow.start.get_child('to')
  node_dict = model_to_dict(node)
  node_dict['id'] = design_id
  node_dict['is_shared'] = workflow.is_shared
  node_dict['editable'] = workflow.owner.id == request.user.id
  node_dict['parameters'] = workflow.parameters
  return render_json(node_dict, js_safe=True);
Ejemplo n.º 20
0
def get_design(request, design_id):
    workflow = _get_design(design_id)
    node = workflow.start.get_child("to")
    node_dict = model_to_dict(node)
    node_dict["id"] = design_id
    node_dict["is_shared"] = workflow.is_shared
    node_dict["editable"] = workflow.owner.id == request.user.id
    node_dict["parameters"] = workflow.parameters
    return render_json(node_dict, js_safe=True)
Ejemplo n.º 21
0
Archivo: views.py Proyecto: dizhu/hue
def get_design(request, design_id):
  workflow = _get_design(design_id)
  node = workflow.start.get_child('to')
  node_dict = model_to_dict(node)
  node_dict['id'] = design_id
  for key in node_dict:
    if key not in JSON_FIELDS:
      if key not in SKIP_ESCAPE:
        node_dict[key] = escapejs(node_dict[key])
  node_dict['editable'] = workflow.owner.id == request.user.id
  return render_json(node_dict);
Ejemplo n.º 22
0
Archivo: views.py Proyecto: joey/hue
def get_design(request, design_id):
    workflow = _get_design(design_id)
    _check_permission(request, workflow.owner.username, _("Access denied: edit design %(id)s.") % {"id": design_id})
    node = workflow.start.get_child("to")
    node_dict = model_to_dict(node)
    node_dict["id"] = design_id
    for key in node_dict:
        if key not in JSON_FIELDS:
            node_dict[key] = escapejs(node_dict[key])
    node_dict["editable"] = True
    return render_json(node_dict)
Ejemplo n.º 23
0
def stat(request, path):
    """
    Returns just the generic stats of a file.

    Intended for use via AJAX (and hence doesn't provide
    an HTML view).
    """
    if not request.fs.exists(path):
        raise Http404(_("File not found: %(path)s") % {'path': escape(path)})
    stats = request.fs.stats(path)
    return render_json(_massage_stats(request, stats))
Ejemplo n.º 24
0
def prefs(request, key=None):
  """Get or set preferences."""
  if key is None:
    d = dict( (x.key, x.value) for x in UserPreferences.objects.filter(user=request.user))
    return render_json(d)
  else:
    if "set" in request.REQUEST:
      try:
        x = UserPreferences.objects.get(user=request.user, key=key)
      except UserPreferences.DoesNotExist:
        x = UserPreferences(user=request.user, key=key)
      x.value = request.REQUEST["set"]
      x.save()
      return render_json(True)
    if "delete" in request.REQUEST:
      try:
        x = UserPreferences.objects.get(user=request.user, key=key)
        x.delete()
        return render_json(True)
      except UserPreferences.DoesNotExist:
        return render_json(False)
    else:
      try:
        x = UserPreferences.objects.get(user=request.user, key=key)
        return render_json(x.value)
      except UserPreferences.DoesNotExist:
        return render_json(None)
Ejemplo n.º 25
0
def prefs(request, key=None):
  """Get or set preferences."""
  if key is None:
    d = dict( (x.key, x.value) for x in UserPreferences.objects.filter(user=request.user))
    return render_json(d)
  else:
    if "set" in request.REQUEST:
      try:
        x = UserPreferences.objects.get(user=request.user, key=key)
      except UserPreferences.DoesNotExist:
        x = UserPreferences(user=request.user, key=key)
      x.value = request.REQUEST["set"]
      x.save()
      return render_json(True)
    if "delete" in request.REQUEST:
      try:
        x = UserPreferences.objects.get(user=request.user, key=key)
        x.delete()
        return render_json(True)
      except UserPreferences.DoesNotExist:
        return render_json(False)
    else:
      try:
        x = UserPreferences.objects.get(user=request.user, key=key)
        return render_json(x.value)
      except UserPreferences.DoesNotExist:
        return render_json(None)
Ejemplo n.º 26
0
def list_designs(request):
    """
  List all workflow designs. Result sorted by last modification time.
  Query params:
    owner       - Substring filter by owner field
    name        - Substring filter by design name field
  """
    owner = request.GET.get("owner", "")
    name = request.GET.get("name", "")

    if request.is_ajax():
        return render_json({"designs": _list_designs(request, owner, name)}, js_safe=True)
    else:
        return render("designs.mako", request, {"currentuser": request.user, "owner": owner, "name": name})
Ejemplo n.º 27
0
def test_popup_injection():
  """Test that result injection works"""
  base = HttpResponse('<html><head></head><body>Hello</body></html>')
  resp = django_util.render_injected(base, ' Cookie monster')
  assert_true('Hello Cookie monster' in resp.content)

  redirect = HttpResponseRedirect('http://www.cnn.com')
  resp = django_util.render_injected(redirect, 'Cookie monster')
  assert_true('Cookie monster' not in resp.content)

  json = django_util.render_json('blah')
  resp = django_util.render_injected(json, 'Cookie monster')
  assert_true('Cookie monster' not in resp.content)

  assert_raises(AssertionError, django_util.render_injected, "foo", "bar")
Ejemplo n.º 28
0
def test_popup_injection():
  """Test that result injection works"""
  base = HttpResponse('<html><head></head><body>Hello</body></html>')
  resp = django_util.render_injected(base, ' Cookie monster')
  assert_true('Hello Cookie monster' in resp.content)

  redirect = HttpResponseRedirect('http://www.cnn.com')
  resp = django_util.render_injected(redirect, 'Cookie monster')
  assert_true('Cookie monster' not in resp.content)

  json = django_util.render_json('blah')
  resp = django_util.render_injected(json, 'Cookie monster')
  assert_true('Cookie monster' not in resp.content)

  assert_raises(AssertionError, django_util.render_injected, "foo", "bar")
Ejemplo n.º 29
0
Archivo: views.py Proyecto: dizhu/hue
def delete_design(request, design_id):
  if request.method != 'POST':
    raise StructuredException(code="METHOD_NOT_ALLOWED_ERROR", message=_('Must be POST request.'), error_code=405)

  try:
    workflow = _get_design(design_id)
    _check_permission(request, workflow.owner.username,
                      _("Access denied: delete workflow %(id)s.") % {'id': design_id},
                      allow_root=True)
    Workflow.objects.destroy(workflow, request.fs)

  except Workflow.DoesNotExist:
    LOG.error("Trying to delete non-existent workflow (id %s)" % (design_id,))
    raise StructuredException(code="NOT_FOUND", message=_('Could not find design.'), error_code=404)

  return render_json({})
Ejemplo n.º 30
0
def restore_design(request, design_id):
  if request.method != 'POST':
    raise StructuredException(code="METHOD_NOT_ALLOWED_ERROR", message=_('Must be POST request.'), error_code=405)

  try:
    workflow = _get_design(design_id)
    _check_permission(request, workflow.owner.username,
                      _("Access denied: delete design %(id)s.") % {'id': design_id},
                      allow_root=True)
    workflow.restore()

  except Workflow.DoesNotExist:
    LOG.error("Trying to restore non-existent workflow (id %s)" % (design_id,))
    raise StructuredException(code="NOT_FOUND", message=_('Could not find design %s.') % design_id, error_code=404)

  return render_json({
    'status': 0
  })
Ejemplo n.º 31
0
def restore_design(request, design_id):
    if request.method != "POST":
        raise StructuredException(code="METHOD_NOT_ALLOWED_ERROR", message=_("Must be POST request."), error_code=405)

    try:
        workflow = _get_design(design_id)
        _check_permission(
            request,
            workflow.owner.username,
            _("Access denied: delete design %(id)s.") % {"id": design_id},
            allow_root=True,
        )
        workflow.restore()

    except Workflow.DoesNotExist:
        LOG.error("Trying to restore non-existent workflow (id %s)" % (design_id,))
        raise StructuredException(code="NOT_FOUND", message=_("Could not find design %s.") % design_id, error_code=404)

    return render_json({"status": 0})
Ejemplo n.º 32
0
def list_designs(request):
    '''
  List all workflow designs. Result sorted by last modification time.
  Query params:
    owner       - Substring filter by owner field
    name        - Substring filter by design name field
  '''
    owner = request.GET.get('owner', '')
    name = request.GET.get('name', '')

    if request.is_ajax():
        return render_json({'designs': _list_designs(request, owner, name)},
                           js_safe=True)
    else:
        return render("designs.mako", request, {
            'currentuser': request.user,
            'owner': owner,
            'name': name
        })
Ejemplo n.º 33
0
Archivo: views.py Proyecto: Lt-Pone/hue
def list_designs(request):
  '''
  List all workflow designs. Result sorted by last modification time.
  Query params:
    owner       - Substring filter by owner field
    name        - Substring filter by design name field
  '''
  owner = request.GET.get('owner', '')
  name = request.GET.get('name', '')

  if request.is_ajax():
    return render_json({
      'designs': _list_designs(request, owner, name)
    }, js_safe=True)
  else:
    return render("designs.mako", request, {
      'currentuser': request.user,
      'owner': owner,
      'name': name
    })
Ejemplo n.º 34
0
def log_view(request):
  """
  We have a log handler that retains the last X characters of log messages.
  If it is attached to the root logger, this view will display that history,
  otherwise it will report that it can't be found.
  """
  if not request.user.is_superuser:
    return HttpResponse(_("You must be a superuser."))

  logs = dict(log=[_("No logs found!")])
  l = logging.getLogger()
  for h in l.handlers:
    if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
      logs = dict(log=[l for l in h.buf], query=request.GET.get("q", ""))

  if request.method == 'POST':
    try:
      return render_json(logs)
    except UnicodeDecodeError, e:
      LOG.warning("Failed to render logs to json")
      pass
Ejemplo n.º 35
0
def log_view(request):
    """
  We have a log handler that retains the last X characters of log messages.
  If it is attached to the root logger, this view will display that history,
  otherwise it will report that it can't be found.
  """
    if not request.user.is_superuser:
        return HttpResponse(_("You must be a superuser."))

    logs = dict(log=[_("No logs found!")])
    l = logging.getLogger()
    for h in l.handlers:
        if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
            logs = dict(log=[l for l in h.buf], query=request.GET.get("q", ""))

    if request.method == 'POST':
        try:
            return render_json(logs)
        except UnicodeDecodeError, e:
            LOG.warning("Failed to render logs to json")
            pass
Ejemplo n.º 36
0
    def process_exception(self, request, exception):
        import traceback

        tb = traceback.format_exc()
        logging.info("Processing exception: %s: %s" % (i18n.smart_unicode(exception), i18n.smart_unicode(tb)))

        if isinstance(exception, PopupException):
            return exception.response(request)

        if isinstance(exception, StructuredException):
            if request.ajax:
                response = render_json(exception.response_data)
                response[MIDDLEWARE_HEADER] = "EXCEPTION"
                response.status_code = getattr(exception, "error_code", 500)
                return response
            else:
                response = render("error.mako", request, dict(error=exception.response_data.get("message")))
                response.status_code = getattr(exception, "error_code", 500)
                return response

        return None
Ejemplo n.º 37
0
def list_designs(request):
  '''
  List all workflow designs. Result sorted by last modification time.
  Query params:
    owner       - Substring filter by owner field
    name        - Substring filter by design name field
  '''
  data = Workflow.objects.filter(managed=False)
  owner = request.GET.get('owner', '')
  name = request.GET.get('name', '')
  if owner:
      data = data.filter(owner__username__icontains=owner)
  if name:
      data = data.filter(name__icontains=name)
  data = data.order_by('-last_modified')

  designs = []
  for design in data:
      ko_design = {
        'id': design.id,
        'owner': design.owner.username,
        # Design name is validated by workflow and node forms.
        'name': design.name,
        'description': design.description,
        'node_type': design.start.get_child('to').node_type,
        'last_modified': py_time.mktime(design.last_modified.timetuple()),
        'editable': design.owner.id == request.user.id,
        'is_shared': design.is_shared
      }
      designs.append(ko_design)

  if request.is_ajax():
    return render_json(designs, js_safe=True)
  else:
    return render("designs.mako", request, {
      'currentuser': request.user,
      'owner': owner,
      'name': name
    })
Ejemplo n.º 38
0
def delete_design(request, design_id):
  if request.method != 'POST':
    raise StructuredException(code="METHOD_NOT_ALLOWED_ERROR", message=_('Must be POST request.'), error_code=405)

  skip_trash = 'skip_trash' in request.GET

  try:
    workflow = _get_design(design_id)
    _check_permission(request, workflow.owner.username,
                      _("Access denied: delete design %(id)s.") % {'id': design_id},
                      allow_root=True)
    if skip_trash:
      Workflow.objects.destroy(workflow, request.fs)
    else:
      workflow.delete(skip_trash=False)

  except Workflow.DoesNotExist:
    raise StructuredException(code="NOT_FOUND", message=_('Could not find design %s.') % design_id, error_code=404)

  return render_json({
    'status': 0
  })
Ejemplo n.º 39
0
Archivo: views.py Proyecto: yjkim/hue
def list_designs(request):
    '''
  List all workflow designs. Result sorted by last modification time.
  Query params:
    owner       - Substring filter by owner field
    name        - Substring filter by design name field
  '''
    data = Workflow.objects.filter(managed=False)
    owner = request.GET.get('owner', '')
    name = request.GET.get('name', '')
    if owner:
        data = data.filter(owner__username__icontains=owner)
    if name:
        data = data.filter(name__icontains=name)
    data = data.order_by('-last_modified')

    designs = []
    for design in data:
        ko_design = {
            'id': design.id,
            'owner': design.owner.username,
            # Design name is validated by workflow and node forms.
            'name': design.name,
            'description': design.description,
            'node_type': design.start.get_child('to').node_type,
            'last_modified': py_time.mktime(design.last_modified.timetuple()),
            'editable': design.owner.id == request.user.id,
            'is_shared': design.is_shared
        }
        designs.append(ko_design)

    if request.is_ajax():
        return render_json(designs, js_safe=True)
    else:
        return render("designs.mako", request, {
            'currentuser': request.user,
            'owner': owner,
            'name': name
        })
Ejemplo n.º 40
0
Archivo: views.py Proyecto: anutron/hue
def kill_job(request, jobid):
  """
  We get here from /jobs/jobid/kill
  """
  if request.method != "POST":
    raise Exception("kill_job may only be invoked with a POST (got a %s)" % request.method)
  job = Job.from_id(jt=request.jt, jobid=jobid)
  if job.user != request.user.username and not request.user.is_superuser:
    access_warn(request, 'Insufficient permission')
    raise MessageException("Permission denied.  User %s cannot delete user %s's job." %
                           (request.user.username, job.profile.user))

  job.kill()
  cur_time = time.time()
  while time.time() - cur_time < 15:
    job = Job.from_id(jt=request.jt, jobid=jobid)

    if job.status not in ["RUNNING", "QUEUED"]:
      return render_json({})
    time.sleep(1)
    job = Job.from_id(jt=request.jt, jobid=jobid)

  raise Exception("Job did not appear as killed within 15 seconds")
Ejemplo n.º 41
0
    def process_exception(self, request, exception):
        import traceback

        logging.info("Processing exception: %s: %s" % (str(exception), traceback.format_exc()))

        if hasattr(exception, "response"):
            return exception.response(request)

        if hasattr(exception, "response_data"):
            if request.ajax:
                response = render_json(exception.response_data)
                response[MIDDLEWARE_HEADER] = "EXCEPTION"
                return response
            else:
                return render_to_response("error.html", dict(error=exception.response_data.get("message")))

        # We didn't handle it as a special exception, but if we're ajax we still
        # need to do some kind of nicer handling than the built-in page
        # Note that exception may actually be an Http404 or similar.
        if request.ajax:
            err = "An error occurred: " + str(exception)
            return PopupException(err, detail=None).response(request)

        return None
Ejemplo n.º 42
0
 def test_render_json_jsonp(self):
   assert_equal("foo(3);", django_util.render_json(3, jsonp_callback="foo").content)
Ejemplo n.º 43
0
 def test_render_json_jsonp(self):
   assert_equal("foo(3);", django_util.render_json(3, jsonp_callback="foo").content)