Beispiel #1
0
 def put(self, request, uuid):
     try:
         data = request.data
         data = self.parse_data(data)
         facility = Locality.objects.get(uuid=uuid)
         try:
             facility.update_data(data, request.user)
             return Response('OK')
         except KeyError as e:
             return HttpResponseBadRequest('%s is required' % e)
         except ValueError as e:
             return HttpResponseBadRequest('%s' % e)
         except TypeError as e:
             return HttpResponseBadRequest('%s' % e)
     except Locality.DoesNotExist:
         raise Http404()
Beispiel #2
0
    def post(self, request, *args, **kwargs):
        if request.version != 'v5':
            raise Http404()

        file_name = None
        file_content = None

        # Check whether AJAX or a standard encoded form was used
        if request.is_ajax():

            # File name must be provided by an HTTP header
            if 'HTTP_X_FILE_NAME' not in request.META:
                return Response('Missing HTTP header for file name.',
                                status=status.HTTP_400_BAD_REQUEST)
            file_name = request.META['HTTP_X_FILE_NAME']
            file_content = request
        else:

            # File content must be already processed by the request
            if len(request.data) != 1:
                return Response('Missing embedded file content.',
                                status=status.HTTP_400_BAD_REQUEST)
            file_handle = request.data.values()[0]
            file_name = file_handle.name
            file_content = file_handle

        # Make sure the file type is supported
        if not file_name or not file_content:
            return Response('Missing file attachment.',
                            status=status.HTTP_400_BAD_REQUEST)
        if os.path.splitext(file_name)[1] not in ['.json']:
            return Response('Unsupported file type.',
                            status=status.HTTP_400_BAD_REQUEST)

        # Attempt to parse the file content
        # TODO: Add buffer overflow protection
        import_dict = json.loads(file_content.read())

        # Attempt to apply the configuration
        try:
            warnings = importer.import_config(import_dict)
        except InvalidConfiguration as ex:
            logger.exception('Unable to import configuration.')
            raise BadParameter(unicode(ex))

        results = [{'id': w.key, 'details': w.details} for w in warnings]
        return Response({'warnings': results})
Beispiel #3
0
def __workflowObject(request):
    _site_url = get_site_url_id(request)

    _p = PortalCatalog.objects.filter(site__url=_site_url)
    _url = reescrever_url(request)
    _workflow = request.GET['workflow_action']
    if _workflow in WORKFLOW_ACTION:

        _p = _p.get(path_url=_url)

        if _p.tipo == 'ATPagina':
            paginas.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATLink':
            links.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATImagem':
            imagens.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATPasta':
            pastas.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATBanner':
            banners.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATNoticia':
            noticias.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATArquivo':
            arquivos.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATEvento':
            eventos.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATAgenda':
            agendas.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATInforme':
            informes.workflow(request, _p, WORKFLOW[_workflow])

        if _p.tipo == 'ATServico':
            servicos.workflow(request, _p, WORKFLOW[_workflow])

    else:
        raise Http404('Operação não permitida.')

    return redirect(_url)
def apply(request, jid):

    if request.method == "POST":
        form = Application_form(request.POST)
        job = Job.objects.get(id=jid)
        seekerProfile = SeekerProfile.objects.get(seeker=request.user)
        if form.is_valid():
            cv = form.cleaned_data['cv']
            cover_letter = form.cleaned_data['cover_letter']

            score = macthing_score(request, job, seekerProfile)

            application_id = Application.objects.create(
                cv=cv,
                cover_letter=cover_letter,
                status='A',
                seeker=seekerProfile,
                matching_score=score,
                job=job,
                seeker_name=seekerProfile.first_name)

            application_id.save()

            job_application = Application.objects.get(id=application_id.id)

            Message.objects.create(
                application=job_application,
                recruiter=job.recruiter,
                seeker=seekerProfile,
                message_type='A',
            ).save()

            messages.success(request,
                             "You have sucessfully applied for this position")
            args = {'form': form, 'job': job}
            return render(request, 'ojss_app/job_details.html', args)

        else:
            messages.warning(
                request,
                "Your application form had errors in it. Please re submit application"
            )
            args = {'form': form, 'job': job, 'status': "T"}
            return render(request, 'ojss_app/job_details.html', args)

    else:
        raise Http404("This is an invalid request")
Beispiel #5
0
def detail(request, tracker_id):
    # Count of applications(similar to getting count of one report per application)
    reports_number = Application.objects.distinct('handle').count()
    try:
        tracker = Tracker.objects.get(pk=tracker_id)
        # Add spaces aroung pipes for better rendering of signatures
        tracker.network_signature = tracker.network_signature.replace("|", " | ")
        tracker.code_signature = tracker.code_signature.replace("|", " | ")

        # Returns reports in reverse chronological order
        app_tuples = Application.objects.values('handle').annotate(recent_id=Max('id'))
        application_ids = [i['recent_id'] for i in app_tuples]
        report_ids = Application.objects.filter(id__in=application_ids).values_list('report_id', flat=True)
        # List of only latest report for an application
        reports_list = Report.objects.filter(id__in=report_ids, found_trackers=tracker_id)

    except Tracker.DoesNotExist:

        raise Http404(_("Tracker does not exist"))

    paginator = Paginator(reports_list, settings.EX_PAGINATOR_COUNT)
    page = request.GET.get('page')

    try:
        reports = paginator.page(page)
    except PageNotAnInteger:
        reports = paginator.page(1)
    except EmptyPage:
        reports = paginator.page(paginator.num_pages)

    count = len(reports_list)
    score = int(100. * count / reports_number)
    if score >= 50:
        tracker_class = "danger"
    elif score >= 33:
        tracker_class = "warning"
    else:
        tracker_class = "info"

    data_to_render = {
        'tracker': tracker,
        'reports': reports,
        'count': count,
        'score': score,
        'tracker_class': tracker_class
    }
    return render(request, 'tracker_details.html', data_to_render)
Beispiel #6
0
def deleteUnit(request, unit_id=None):
    # STEP1.0.0: Set template and create an empty context object.
    t = 'systemAdmin/extensions/mono_page.html'
    context = {}
    # STEP1.1: Test for session, to determine currently logged in user.
    try:
        if request.session['user_admin']:
            # if user is logged in, build the required page.
            # create new user instance
            user = request.session['user_admin']
            # Set session data for the new user
            set_session_data(request, user)
            unit = get_object_or_404(ServiceUnit, unit_id=unit_id)

            # Set admin panel options
            context.update(
                {'options': admin_panel_options(active='dashboard')})

            if unit:
                unit.delete()

                # Turn on flags to enable loading unit update form
                unit_delete_success = True
                context.update({'unit_delete_success': True})
                if unit_delete_success:
                    # Create a unit object to be sent to the client together with the form
                    context.update({'unit': unit})
                    return redirect('systemAdmin:serviceUnits',
                                    deleted='deleted')
                    #return render(request, t, context)
                else:
                    return HttpResponse(
                        "<font color = 'red'><b>Error Encountered while Deleting the Service Unit</b></font>"
                    )
            else:
                # If no Service unit matches the given query,
                # Just Load the standard HTTP 404 page.
                return Http404()

            return render(request, t, context)
        else:
            # if no user is logged in, try Logging in.
            return redirect('systemAdmin:login')
        # End of if request.session['user_admin']:
    except KeyError:
        # Just try logging in.
        return redirect('systemAdmin:login')
Beispiel #7
0
def index(request):
    try:
        # TODO: Use a Django Form instead ?
        filter_name = request.GET.get('tracker_name', '')
        only_collisions = request.GET.get('only_collisions', False)
        approve_select = request.GET.get('approve_select', '')
        trackers_select = request.GET.get('trackers_select', '')
        if filter_name:
            trackers = Tracker.objects.filter(name__startswith=filter_name)
        else:
            trackers = Tracker.objects

        trackers = trackers.order_by('name')

        if trackers_select == "exodus":
            trackers = trackers.filter(is_in_exodus=True)
        elif trackers_select == "etip":
            trackers = trackers.filter(is_in_exodus=False)

        if only_collisions:
            trackers = list(t for t in trackers
                            if t.has_any_signature_collision())

        if approve_select == "approved":
            trackers = list(t for t in trackers if t.approvals.count() >= 2)
        elif approve_select == "need_review":
            trackers = list(t for t in trackers if t.approvals.count() == 1)
        elif approve_select == "no_approvals":
            trackers = list(t for t in trackers if t.approvals.count() == 0)

        count = len(trackers)

        paginator = Paginator(trackers, 20)
        page = request.GET.get('page', 1)
        trackers = paginator.get_page(page)
    except Tracker.DoesNotExist:
        raise Http404("trackers does not exist")

    return render(
        request, 'tracker_list.html', {
            'trackers': trackers,
            'count': count,
            'filter_name': filter_name,
            'only_collisions': 'checked' if only_collisions else '',
            'approve_select': approve_select,
            'trackers_select': trackers_select
        })
Beispiel #8
0
    def post(self, request, scan_id=None):
        """Launches a scan to ingest from an existing scan model instance

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :param scan_id: ID for Scan record to pull configuration from
        :type scan_id: int
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._post_v6(request, scan_id)
        elif request.version == 'v7':
            return self._post_v6(request, scan_id)

        raise Http404()
Beispiel #9
0
    def create(self, request):
        """Determine api version and call specific method

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v4':
            return self.create_impl(request)
        elif request.version == 'v5':
            return self.create_impl(request)
        elif request.version == 'v6':
            return self.create_impl_v6(request)

        raise Http404()
Beispiel #10
0
    def retrieve(self, request, batch_id):
        """Retrieves the details for a batch and returns them in JSON form

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param batch_id: The batch ID
        :type batch_id: int
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._retrieve_v6(batch_id)
        elif request.version == 'v7':
            return self._retrieve_v6(batch_id)

        raise Http404()
Beispiel #11
0
    def get(self, request, root_batch_id):
        """Validates a new batch

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param root_batch_id: The root batch ID
        :type root_batch_id: int
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._get_v6(request, root_batch_id)
        elif request.version == 'v7':
            return self._get_v6(request, root_batch_id)

        raise Http404()
Beispiel #12
0
    def retrieve(self, request, recipe_id):
        """Retrieves the details for a recipe and returns it in JSON form

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param recipe_id: The id of the recipe
        :type recipe_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._retrieve_v6(request, recipe_id)
        elif request.version == 'v7':
            return self._retrieve_v6(request, recipe_id)

        raise Http404()
Beispiel #13
0
    def post(self, request, recipe_id):
        """Schedules a recipe for reprocessing and returns it in JSON form

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param recipe_id: The id of the recipe
        :type recipe_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._post_v6(request, recipe_id)
        elif request.version == 'v7':
            return self._post_v6(request, recipe_id)

        raise Http404()
Beispiel #14
0
def registeruer(request, dealer_code=None):
    customer_factory = CustomerServicesFactory()
    cuser = customer_factory.get_instance("user")
    if request.GET.get("profile_id"):
        profile = cuser.get_user_profile(request.GET.get("profile_id"))
        if profile:
            initial_user_form = {"profile": profile.id}
            usercreateform = CreateUserForm(initial=initial_user_form)
            return render(
                request, "customer/registeruser.html", {
                    "usercreationform": usercreateform,
                    "profile": profile,
                    "done_disable": True,
                    "request": request
                })
        else:
            raise Http404("Profile not found")
Beispiel #15
0
 def get_resource_objects(self):
     super().get_resource_objects()
     MANAGERS = {
         "category": CategoryManager,
         "module": ModuleManager,
         "exercise": ExerciseManager,
     }
     self.model = self._get_kwarg(self.model_kw)
     if not self.model in MANAGERS:
         raise Http404()
     self.manager = MANAGERS[self.model]()
     self.model_name = self.manager.name
     # FIXME: model is passed from kwargs in View.dispatch and from
     # BaseMixin/BaseTemplateMixin to template context. As the value is
     # same, this should break anything, but is still a problematic thing.
     # Should be fixed one day.
     self.note("model", "model_name")
Beispiel #16
0
    def retrieve(self, request, ingest_id=None, file_name=None):
        """Determine api version and call specific method

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param ingest_id: The id of the ingest
        :type ingest_id: int encoded as a str
        :param file_name: The name of the ingest
        :type file_name: string
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6' or request.version == 'v7':
            return self.retrieve_v6(request, ingest_id)

        raise Http404()
Beispiel #17
0
    def retrieve(self, request, file_id):
        """Determine api version and call specific method

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :param file_id: The id of the file
        :type file_id: int encoded as a string
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self.retrieve_impl(request, file_id)
        elif request.version == 'v7':
            return self.retrieve_impl(request, file_id)

        raise Http404()
Beispiel #18
0
def finance(request, id=None):
    if id is None:
        ad_list = Advertisement.objects.filter(Q(location='0')
                                               | Q(location='4'),
                                               is_hidden=False)[0:8]
        strategy_list = Press.objects.filter(type='2')[0:10]
        context = {'ad_list': ad_list, 'strategy_list': strategy_list}
        rank_users = MyUser.objects.order_by('-accu_income')[0:6]
        for i in range(len(rank_users)):
            key = 'rank' + str(i + 1)
            username = rank_users[i].username
            if len(username) > 4:
                username = username[0:4] + '****'
            else:
                username = username + '****'
            income = rank_users[i].accu_income
            context.update(
                {key: {
                    'username': username,
                    'income': str(income)
                }})
        return render(request, 'finance.html', context)
    else:
        id = int(id)
        news = None
        try:
            news = Finance.objects.get(id=id)
        except Finance.DoesNotExist:
            raise Http404(u"该页面不存在")
        update_view_count(news)
        scheme = news.scheme
        table = []
        str_rows = scheme.split('|')
        for str_row in str_rows:
            row = str_row.split('#')
            table.append(row)
        other_wel_list = Finance.objects.filter(
            state='1', level__in=['normal',
                                  'all']).order_by('-view_count')[0:10]
        context = {
            'news': news,
            'type': 'Finance',
            'other_wel_list': other_wel_list,
            'table': table,
        }
        return render(request, 'detail-finance.html', context)
Beispiel #19
0
def handle_instance_action(request, action):
    form = request.form.clean()

    if action not in actions_for_instance:
        raise Http404()

    instance_id = form.get('instance_id')

    if action == 'start':
        return start_pipeline(instance_id, request.user.username)

    try:
        result = actions_for_instance[action](instance_id)
    except Exception as e:
        logger.exception(traceback.format_exc(e))
        return action_result(False, 'An error occurred, please contact developer.', status=500)
    return action_result(result.result, result.message)
Beispiel #20
0
    def get(self, request, scan_id):
        """Retrieves the details for a Scan process and return them in JSON form

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param scan_id: The ID of the Scan process
        :type scan_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._get_v6(request, scan_id)
        elif request.version == 'v7':
            return self._get_v6(request, scan_id)

        raise Http404()
Beispiel #21
0
 def wrap(request, *args, **kwargs):
         appservice  = appointmentservices.AppointmentService()
         appointment_id = None
         
         if request.method =="POST":
             appointment_id = request.POST.get("appointment_id")
               
         if appointment_id == None:
             appointment_id =request.GET.get("appointment_id")   
         
         appointment = appservice.get_valid_appointment(appointment_id)
         #this check the session if userid key exist, if not it will redirect to login page
         if appointment == None:
                 raise Http404("Appointment does not exist")
         else:
             request.session["appointment_id"] = appointment_id
         return f(request, appointment,*args, **kwargs)
Beispiel #22
0
    def patch(self, request, scan_id):
        """Edits an existing Scan process and returns the updated details

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param scan_id: The ID of the Scan process
        :type scan_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._patch_v6(request, scan_id)
        elif request.version == 'v7':
            return self._patch_v6(request, scan_id)

        raise Http404()
Beispiel #23
0
    def get(self, request, recipe_id):
        """Retrieve detailed information about the input files for a recipe

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :param recipe_id: The ID for the recipe.
        :type recipe_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._get_v6(request, recipe_id)
        elif request.version == 'v7':
            return self._get_v6(request, recipe_id)

        raise Http404()
Beispiel #24
0
    def patch(self, request, strike_id):
        """Determine api version and call specific method

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :param strike_id: The ID of the Strike process
        :type strike_id: int encoded as a str
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self.patch_impl_v6(request, strike_id)
        elif request.version == 'v7':
            return self.patch_impl_v6(request, strike_id)

        raise Http404()
Beispiel #25
0
def like_post(request, post_id):
    post = Post.objects.get(pk=post_id)
    is_liked = False
    user = request.user.profile
    try:
        profile = Profile.objects.get(user=user.user)
        print(profile)

    except Profile.DoesNotExist:
        raise Http404()
    if post.likes.filter(id=user.user.id).exists():
        post.likes.remove(user.user)
        is_liked = False
    else:
        post.likes.add(user.user)
        is_liked = True
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Beispiel #26
0
    def create(self, request):
        """Creates a new Workspace and returns it in JSON form

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._create_v6(request)
        elif request.version == 'v5':
            return self._create_v5(request)
        elif request.version == 'v4':
            return self._create_v5(request)

        raise Http404()
Beispiel #27
0
    def update(self, request, batch_id, **kwargs):
        """Updates the given batch

        :param request: the HTTP PATCH request
        :type request: :class:`rest_framework.request.Request`
        :param batch_id: the batch id
        :type batch_id: int
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._update_v6(request, batch_id)
        elif request.version == 'v7':
            return self._update_v6(request, batch_id)

        raise Http404()
Beispiel #28
0
    def list(self, request):
        """Retrieves the batches and returns them in JSON form

        :param request: the HTTP GET request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._list_v6(request)
        elif request.version == 'v5':
            return self._list_v5(request)
        elif request.version == 'v4':
            return self._list_v5(request)

        raise Http404()
Beispiel #29
0
    def create_result_response(self, service, result, service_path):
        for nested in service_path:
            result = result.get(nested, None)
            if result is None:
                break

        if result is None:
            raise Http404()

        if result in (True, False):
            status_code = 200 if result else _get_err_status_code()
            return HttpResponse(str(result).lower(), status=status_code)
        elif isinstance(result, six.string_types) or isinstance(result, bytes):
            return HttpResponse(result)
        else:
            # Django requires safe=False for non-dict values.
            return JsonResponse(result, safe=False)
Beispiel #30
0
    def post(self, request):
        """Validates a new workspace and returns any warnings discovered

        :param request: the HTTP POST request
        :type request: :class:`rest_framework.request.Request`
        :rtype: :class:`rest_framework.response.Response`
        :returns: the HTTP response to send back to the user
        """

        if request.version == 'v6':
            return self._post_v6(request)
        elif request.version == 'v5':
            return self._post_v5(request)
        elif request.version == 'v4':
            return self._post_v5(request)

        raise Http404()