Exemple #1
0
    def get(self, request, pk):
        instance = self.get_object(request, pk)
        data = serialize(instance, **self.template)

        for i in range(len(data['results'])):
            data['results'][i]['variant'] = VariantResource.get(
                request, data['results'][i]['variant_id'])
            data['results'][i].pop('variant_id')

            result_id = data['results'][i]['id']
            data['results'][i]['num_assessments'] = Assessment.objects.filter(
                sample_result__id=result_id,
                sample_result__resultset__id=pk).count()

            try:
                assessment = Assessment.objects.get(
                    sample_result__id=result_id,
                    sample_result__resultset__id=pk,
                    user=request.user.id)
                data['results'][i]['assessment'] = \
                    serialize(assessment, **api.templates.ResultAssessment)
            except Assessment.DoesNotExist:
                data['results'][i]['assessment'] = {}

        return data
Exemple #2
0
    def get(self, request, pk):
        related = ['type', 'chr']
        try:
            variant = self.model.objects.select_related(*related).get(pk=pk)
        except self.model.DoesNotExist:
            raise Http404
        data = serialize(variant, **self.template)

        # Roll up unique set of genes and effects for this variant since
        # this is quite important
        genes = set()
        effects = set()
        for eff in data['effects']:
            effects.add(eff['type'])
            if eff.get('transcript') and eff['transcript'].get('gene'):
                if eff['transcript']['gene']:
                    genes.add(eff['transcript']['gene']['symbol'])

        data['unique_genes'] = sorted(genes)
        data['unique_effects'] = sorted(effects)

        # Augment resource with cohort-related details (e.g. allele frequencies)
        perms = Q(cohort__user=None, cohort__published=True) | \
            Q(cohort__user=request.user)
        cohort_variants = CohortVariant.objects.filter(
            perms, variant=variant).order_by('-cohort__order',
                                             'cohort__name').distinct()
        data['cohorts'] = serialize(cohort_variants,
                                    **api.templates.CohortVariant)

        return data
Exemple #3
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(),
                                 '')

        kwargs['application'] = serialize(application,
                                          posthook=format_application)

        kwargs['assessments'] = serialize(
            Assessment.objects.filter(application=application),
            posthook=format_assessment)

        kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get(
            payment_utils.get_application_payment_status(application))

        kwargs['log_entry_form'] = ApplicationLogEntryForm(
            to=get_log_entry_to(application),
            fromm=self.request.user.get_full_name())

        return super(ViewReadonlyOfficerView, self).get_context_data(**kwargs)
Exemple #4
0
    def get_context_data(self, **kwargs):
        ctx = super(CurateReturnView, self).get_context_data(**kwargs)
        ret = ctx['return']
        ctx['return'] = serialize(
            ret,
            posthook=format_return,
            exclude=['application', 'applicationrequest_ptr', 'licence'])

        if ret.proxy_customer is None:
            to = ret.licence.holder
        else:
            to = ret.proxy_customer

        ctx['log_entry_form'] = ReturnsLogEntryForm(
            to=to.get_full_name(),
            fromm=self.request.user.get_full_name(),
        )

        ctx['amendment_request_form'] = ReturnAmendmentRequestForm(
            ret=ret, officer=self.request.user)

        amendment_requests = ReturnAmendmentRequest.objects.filter(ret=ret)
        ctx['amendment_requests'] = serialize(amendment_requests,
                                              fields=['status', 'reason'])
        return ctx
Exemple #5
0
def format_application(instance, attrs):
    attrs['processing_status'] = PROCESSING_STATUSES[
        attrs['processing_status']]
    attrs['id_check_status'] = ID_CHECK_STATUSES[attrs['id_check_status']]
    attrs['returns_check_status'] = RETURNS_CHECK_STATUSES[
        attrs['returns_check_status']]
    attrs['character_check_status'] = CHARACTER_CHECK_STATUSES[
        attrs['character_check_status']]
    attrs['review_status'] = REVIEW_STATUSES[attrs['review_status']]
    attrs['licence_type']['default_conditions'] = serialize([
        ap.condition
        for ap in instance.licence_type.defaultcondition_set.order_by('order')
    ])
    attrs['conditions'] = serialize([
        ap.condition
        for ap in instance.applicationcondition_set.order_by('order')
    ])

    attrs['applicant_profile']['user'] = serialize(
        instance.applicant_profile.user,
        exclude=['postal_address', 'residential_address', 'billing_address'])
    attrs['applicant_profile']['postal_address'] = serialize(
        instance.applicant_profile.postal_address,
        exclude=['user', 'oscar_address'])
    if instance.applicant.identification is not None and instance.applicant.identification.file is not None:
        attrs['applicant']['identification'][
            'url'] = instance.applicant.identification.file.url
    if instance.applicant.senior_card is not None and instance.applicant.senior_card.file is not None:
        attrs['applicant']['senior_card'][
            'url'] = instance.applicant.senior_card.file.url

    return attrs
Exemple #6
0
    def get(self, request, pk):
        related = ['type', 'chr']
        try:
            variant = self.model.objects.select_related(*related).get(pk=pk)
        except self.model.DoesNotExist:
            raise Http404
        data = serialize(variant, **self.template)

        # Roll up unique set of genes and effects for this variant since
        # this is quite important
        genes = set()
        effects = set()
        for eff in data['effects']:
            effects.add(eff['type'])
            if eff.get('transcript') and eff['transcript'].get('gene'):
                if eff['transcript']['gene']:
                    genes.add(eff['transcript']['gene']['symbol'])

        data['unique_genes'] = sorted(genes)
        data['unique_effects'] = sorted(effects)

        # Augment resource with cohort-related details (e.g. allele frequencies)
        perms = Q(cohort__user=None, cohort__published=True) | \
            Q(cohort__user=request.user)
        cohort_variants = CohortVariant.objects.filter(perms,
            variant=variant).order_by('-cohort__order', 'cohort__name').distinct()
        data['cohorts'] = serialize(cohort_variants,
            **api.templates.CohortVariant)

        return data
Exemple #7
0
    def serialize_to_python(self, data):
        """
        Invoked by ``postprocess``.
        Serializes ``data`` to python data structures, according to the
        handler's ``template`` attribute, or request-level field selection
        defined by querystring parameter ``field``.

        Args:
            data: Result of the handler's operation
        Returns:
            Serialized data.
        """
        # NOTE: The request level field selection doesn not work if the
        # handler's ``template`` attribute uses ``django-preserialize``'s
        # pseudo selectors
        # See
        # <https://github.com/bruth/django-preserialize#my-model-has-a-ton-of-fields-and-i-dont-want-to-type-them-all-out-what-do-i-do>
        # It only works when the ``fields`` are defined one by one in a list.
        field_selection = set(self.request.GET.getlist('field'))
        if field_selection:
            intersection = field_selection.intersection(
                set(self.template['fields']))
            template = {key: value for key, value in self.template.items()}
            template['fields'] = intersection
            return preserializer.serialize(data, **template)

        return preserializer.serialize(data, **self.template)
Exemple #8
0
    def _build_data(self, request, application):
        with open('%s/json/%s.json' % (APPLICATION_SCHEMA_PATH, application.licence_type.code)) as data_file:
            form_structure = json.load(data_file)

        officers = [{'id': officer.id, 'text': render_user_name(officer)} for officer in get_all_officers()]
        officers.insert(0, {'id': 0, 'text': 'Unassigned'})

        current_ass_groups = [ass_request.assessor_group for ass_request in Assessment.objects.filter(application=application)]
        ass_groups = [{'id': ass_group.id, 'text': ass_group.name} for ass_group in
                     AssessorGroup.objects.all().exclude(id__in=[ass_group.pk for ass_group in current_ass_groups])]

        previous_application_data = []
        for revision in revisions.get_for_object(application).filter(revision__comment='Details Modified').order_by('-revision__date_created'):
            previous_application_data.append({'lodgement_number': revision.object_version.object.lodgement_number +
                                              '-' + str(revision.object_version.object.lodgement_sequence),
                                              'date': formats.date_format(revision.revision.date_created, 'd/m/Y', True),
                                              'data': revision.object_version.object.data})

        data = {
            'user': serialize(request.user),
            'application': serialize(application, posthook=format_application),
            'form_structure': form_structure,
            'officers': officers,
            'amendment_requests': serialize(AmendmentRequest.objects.filter(application=application), posthook=format_amendment_request),
            'assessor_groups': ass_groups,
            'assessments': serialize(Assessment.objects.filter(application=application),
                                     posthook=format_assessment),
            'previous_application_data': serialize(previous_application_data),
            'csrf_token': str(csrf(request).get('csrf_token'))
        }

        return data
Exemple #9
0
    def get(self, request, pk):
        instance = self.get_object(request, pk)
        data = serialize(instance, **self.template)

        for i in range(len(data['results'])):
            data['results'][i]['variant'] = VariantResource.get(
                request, data['results'][i]['variant_id'])
            data['results'][i].pop('variant_id')

            result_id = data['results'][i]['id']
            data['results'][i]['num_assessments'] = Assessment.objects.filter(
                sample_result__id=result_id,
                sample_result__resultset__id=pk).count()

            try:
                assessment = Assessment.objects.get(
                    sample_result__id=result_id,
                    sample_result__resultset__id=pk,
                    user=request.user.id)
                data['results'][i]['assessment'] = \
                    serialize(assessment, **api.templates.ResultAssessment)
            except Assessment.DoesNotExist:
                data['results'][i]['assessment'] = {}

        return data
    def serialize_to_python(self, data):
        """
        Invoked by ``postprocess``.
        Serializes ``data`` to python data structures, according to the
        handler's ``template`` attribute, or request-level field selection
        defined by querystring parameter ``field``.

        Args:
            data: Result of the handler's operation
        Returns:
            Serialized data.
        """
        # NOTE: The request level field selection doesn not work if the
        # handler's ``template`` attribute uses ``django-preserialize``'s
        # pseudo selectors
        # See
        # <https://github.com/bruth/django-preserialize#my-model-has-a-ton-of-fields-and-i-dont-want-to-type-them-all-out-what-do-i-do>
        # It only works when the ``fields`` are defined one by one in a list.
        field_selection = set(self.request.GET.getlist("field"))
        if field_selection:
            intersection = field_selection.intersection(set(self.template["fields"]))
            template = {key: value for key, value in self.template.items()}
            template["fields"] = intersection
            return preserializer.serialize(data, **template)

        return preserializer.serialize(data, **self.template)
Exemple #11
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(), '')

        kwargs['application'] = serialize(application, posthook=format_application)
        kwargs['form_structure'] = application.licence_type.application_schema

        assessment = get_object_or_404(Assessment, pk=self.args[1])

        kwargs['assessment'] = serialize(assessment, post_hook=format_assessment,exclude=['application','applicationrequest_ptr'])

        kwargs['other_assessments'] = serialize(Assessment.objects.filter(application=application).
                                                exclude(id=assessment.id).order_by('id'), posthook=format_assessment,exclude=['application','applicationrequest_ptr'])

        kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application),
                                                           fromm=self.request.user.get_full_name())

        if application.processing_status == 'declined':
            message = "This application has been declined."
            details = ApplicationDeclinedDetails.objects.filter(application=application).first()
            if details and details.reason:
                message += "<br/>Reason:<br/>{}".format(details.reason.replace('\n', '<br/>'))
                kwargs['application']['declined_reason'] = details.reason
            messages.error(self.request, message)

        return super(ViewReadonlyAssessorView, self).get_context_data(**kwargs)
Exemple #12
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])
        assessment = get_object_or_404(Assessment, pk=self.args[1])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(), '')

        kwargs['application'] = serialize(application, posthook=format_application)
        kwargs['form_structure'] = application.licence_type.application_schema

        kwargs['assessment'] = serialize(assessment, post_hook=format_assessment)

        kwargs['other_assessments'] = serialize(Assessment.objects.filter(application=application).
                                                exclude(id=assessment.id).order_by('id'), posthook=format_assessment)

        assessors = [{'id': assessor.id, 'text': assessor.get_full_name()} for assessor in
                     assessment.assessor_group.members.all().order_by('first_name')]
        assessors.insert(0, {'id': 0, 'text': 'Unassigned'})

        kwargs['assessors'] = assessors

        kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application),
                                                           fromm=self.request.user.get_full_name())

        return super(EnterConditionsAssessorView, self).get_context_data(**kwargs)
Exemple #13
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(),
                                 '')

        kwargs['application'] = serialize(application,
                                          posthook=format_application)
        kwargs['form_structure'] = application.licence_type.application_schema

        assessment = get_object_or_404(Assessment, pk=self.args[1])

        kwargs['assessment'] = serialize(assessment,
                                         post_hook=format_assessment)

        kwargs['other_assessments'] = serialize(Assessment.objects.filter(
            application=application).exclude(id=assessment.id).order_by('id'),
                                                posthook=format_assessment)

        kwargs['log_entry_form'] = ApplicationLogEntryForm(
            to=get_log_entry_to(application),
            fromm=self.request.user.get_full_name())

        return super(ViewReadonlyAssessorView, self).get_context_data(**kwargs)
Exemple #14
0
    def _build_data(self, request, application):
        officers = [{'id': officer.id, 'text': render_user_name(officer)} for officer in get_all_officers()]
        officers.insert(0, {'id': 0, 'text': 'Unassigned'})

        current_ass_groups = [ass_request.assessor_group for ass_request in
                              Assessment.objects.filter(application=application)]

        ass_groups = [{'id': ass_group.id, 'text': ass_group.name} for ass_group in
                      AssessorGroup.objects.all().exclude(id__in=[ass_group.pk for ass_group in current_ass_groups])]

        # extract and format the previous lodgements of the application
        previous_lodgements = []
        for revision in revisions.get_for_object(application).filter(revision__comment='Details Modified').order_by(
                '-revision__date_created'):
            previous_lodgement = revision.object_version.object

            if previous_lodgement.hard_copy is not None:
                previous_lodgement.licence_type.application_schema, previous_lodgement.data = \
                    append_app_document_to_schema_data(previous_lodgement.licence_type.application_schema, previous_lodgement.data,
                                                       previous_lodgement.hard_copy.file.url)

            # reversion won't reference the previous many-to-many sets, only the latest one, so need to get documents as per below
            previous_lodgement_documents = Document.objects.filter(pk__in=revision.field_dict['documents'])

            convert_documents_to_url(previous_lodgement.licence_type.application_schema, previous_lodgement.data,
                                     previous_lodgement_documents)
            previous_lodgements.append({'lodgement_number': '{}-{}'.format(previous_lodgement.lodgement_number,
                                                                           previous_lodgement.lodgement_sequence),
                                        'date': formats.date_format(revision.revision.date_created, 'd/m/Y', True),
                                        'data': previous_lodgement.data})

        previous_application_returns_outstanding = False
        if application.previous_application is not None:
            previous_application_returns_outstanding = Return.objects.filter(licence=application.previous_application.licence).\
                exclude(status='accepted').exclude(status='submitted').exists()

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.licence_type.application_schema, application.data, application.documents.all())

        data = {
            'user': serialize(request.user),
            'application': serialize(application, posthook=format_application),
            'form_structure': application.licence_type.application_schema,
            'officers': officers,
            'amendment_requests': serialize(AmendmentRequest.objects.filter(application=application),
                                            posthook=format_amendment_request),
            'assessor_groups': ass_groups,
            'assessments': serialize(Assessment.objects.filter(application=application),
                                     posthook=format_assessment),
            'previous_versions': serialize(previous_lodgements),
            'returns_outstanding': previous_application_returns_outstanding,
            'csrf_token': str(csrf(request).get('csrf_token'))
        }

        return data
def epSuccessPayment(request):
    KEYS = [settings.MERCHANT_KEY, request.POST['txnid'], request.POST['amount'],request.POST['productinfo'], request.POST['firstname'], request.POST['email'],'', '', '', '', '','', '', '', '', '']
    status = request.POST['status']
    result={}
    if verify_hash(KEYS, status) == request.POST['hash']:
        return JsonResponse({'status':'200','success':serialize(request)})
    else :
        return JsonResponse({'status':'404','error':serialize(request)})
Exemple #16
0
def transform_player_stats(audit_date, stat_recs, clv_recs, 
                           stats_time='1 month', clv_time='12 month'):
    s_recs = []
    stat_df = pd.DataFrame.from_records(stat_recs, index='player_id')
    clv_summary = calc_clv(clv_recs, audit_date)
    combine_df = pd.concat([clv_summary, stat_df], axis=1)
    combine_dict = combine_df.to_dict(orient='index')
    player_ids = combine_dict.keys()
    for player_id in player_ids:
        try:
            rec = clean_stat_dict_values(combine_dict[player_id])
            rec['player_id'] = int(player_id)
            rec['start_date'] = parse(audit_date)
            date_dim = DateDimension.objects.get(full_date=rec['start_date'])
            #convert dates to UTC
            date_dim.full_date = local_to_utc(date_dim.full_date)
            date_dim.week_begin_date = local_to_utc(date_dim.week_begin_date)
            
            player = get_player_rec(rec)
            player_age = calculate_age(audit_date, player.birth_date)
            full_name = player.first_name + " " + player.last_name
            player_tier = get_player_tier(audit_date, player.player_id)
            
            #geo_point for player
            geo_point = create_geo_point(player)
            
            date_s = serialize(date_dim)
            
            player_s = serialize(player)
            # clean up field the user does not need to see
            player_s.pop('effective_date', None)
            player_s.pop('expiration_date', None)
            player_s.pop('addr_lon', None)
            player_s.pop('addr_lat', None)
            player_s.pop('current', None)
            
            player_s['home_geo_point'] = serialize(geo_point)
            player_s['age'] = player_age
            player_s['full_name'] = full_name
            player_s['grc_rank'] = player_tier
                
            rec['player']=player_s
            rec['gaming_date']=date_s
            rec['clv_T']=rec.pop('T')
            rec['clv_frequency']=rec.pop('frequency')
            rec['clv_monetary_value']=rec.pop('monetary_value')
            rec['clv_recency']=rec.pop('recency')
            rec['stats_timeframe']=stats_time
            rec['clv_timeframe']=clv_time
            rec.pop('player_id', None)
            rec.pop('start_date', None)
            
            
            s_recs.append(rec)
        except Exception, e:
                print e
Exemple #17
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        with open('%s/json/%s.json' % (APPLICATION_SCHEMA_PATH, application.licence_type.code)) as data_file:
            form_structure = json.load(data_file)

        kwargs['application'] = serialize(application, posthook=format_application)
        kwargs['form_structure'] = form_structure
        kwargs['assessments'] = serialize(Assessment.objects.filter(application=application), posthook=format_assessment)
        kwargs['action_url'] = reverse('applications:submit_conditions', args=[application.pk])

        return super(EnterConditionsView, self).get_context_data(**kwargs)
def epSuccessPayment(request):
    KEYS = [
        settings.MERCHANT_KEY, request.POST['txnid'], request.POST['amount'],
        request.POST['productinfo'], request.POST['firstname'],
        request.POST['email'], '', '', '', '', '', '', '', '', '', ''
    ]
    status = request.POST['status']
    result = {}
    if verify_hash(KEYS, status) == request.POST['hash']:
        return JsonResponse({'status': '200', 'success': serialize(request)})
    else:
        return JsonResponse({'status': '404', 'error': serialize(request)})
Exemple #19
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(), '')

        kwargs['application'] = serialize(application,posthook=format_application,
                                            related={
                                                'applicant': {'exclude': ['residential_address','postal_address','billing_address']},
                                                'applicant_profile':{'fields':['email','id','institution','name']},
                                                'previous_application':{'exclude':['applicant','applicant_profile','previous_application','licence']},
                                                'licence':{'related':{
                                                   'holder':{'exclude': ['residential_address','postal_address','billing_address']},
                                                   'issuer':{'exclude': ['residential_address','postal_address','billing_address']},
                                                   'profile':{'related': {'user': {'exclude': ['residential_address','postal_address','billing_address']}},
						       'exclude': ['postal_address']}
                                                   },'exclude':['holder','issuer','profile','licence_ptr']}
                                            })
        kwargs['form_structure'] = application.licence_type.application_schema

        assessment = get_object_or_404(Assessment, pk=self.args[1])

        kwargs['assessment'] = serialize(assessment, post_hook=format_assessment,exclude=['application','applicationrequest_ptr'],
                                                related={'assessor_group':{'related':{'members':{'exclude':['residential_address']}}},
                                                    'officer':{'exclude':['residential_address']},
                                                    'assigned_assessor':{'exclude':['residential_address']}})


        kwargs['other_assessments'] = serialize(Assessment.objects.filter(application=application).exclude(id=assessment.id).order_by('id'),
                                                posthook=format_assessment,exclude=['application','applicationrequest_ptr'],
                                                related={'assessor_group':{'related':{'members':{'exclude':['residential_address']}}},
                                                    'officer':{'exclude':['residential_address']},
                                                    'assigned_assessor':{'exclude':['residential_address']}})


        kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application),
                                                           fromm=self.request.user.get_full_name())

        if application.processing_status == 'declined':
            message = "This application has been declined."
            details = ApplicationDeclinedDetails.objects.filter(application=application).first()
            if details and details.reason:
                message += "<br/>Reason:<br/>{}".format(details.reason.replace('\n', '<br/>'))
                kwargs['application']['declined_reason'] = details.reason
            messages.error(self.request, message)

        return super(ViewReadonlyAssessorView, self).get_context_data(**kwargs)
Exemple #20
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])
        assessment = get_object_or_404(Assessment, pk=self.args[1])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(), '')

        #kwargs['application'] = serialize(application, posthook=format_application)
        kwargs['application'] = serialize(application,posthook=format_application,
                                            related={
                                                'applicant': {'exclude': ['residential_address','postal_address','billing_address']},
                                                'applicant_profile':{'fields':['email','id','institution','name']},
                                                'previous_application':{'exclude':['applicant','applicant_profile','previous_application','licence']},
                                                'licence':{'related':{
                                                   'holder':{'exclude': ['residential_address','postal_address','billing_address']},
                                                   'issuer':{'exclude': ['residential_address','postal_address','billing_address']},
                                                   'profile':{'related': {'user': {'exclude': ['residential_address','postal_address','billing_address']}},
						       'exclude': ['postal_address']}
                                                   },'exclude':['holder','issuer','profile','licence_ptr']}
                                            })
        kwargs['form_structure'] = application.licence_type.application_schema

        kwargs['assessment'] = serialize(assessment, post_hook=format_assessment,
                                            exclude=['application','applicationrequest_ptr'],
                                            related={'assessor_group':{'related':{'members':{'exclude':['residential_address']}}},
                                                'officer':{'exclude':['residential_address']},
                                                'assigned_assessor':{'exclude':['residential_address']}})

        kwargs['other_assessments'] = serialize(Assessment.objects.filter(application=application).
						exclude(id=assessment.id).order_by('id'),
                                                posthook=format_assessment,exclude=['application','applicationrequest_ptr'],
                                                related={'assessor_group':{'related':{'members':{'exclude':['residential_address']}}},
                                                    'officer':{'exclude':['residential_address']},
                                                    'assigned_assessor':{'exclude':['residential_address']}})

        assessors = [{'id': assessor.id, 'text': assessor.get_full_name()} for assessor in
                     assessment.assessor_group.members.all().order_by('first_name')]
        assessors.insert(0, {'id': 0, 'text': 'Unassigned'})

        kwargs['assessors'] = assessors

        kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application),
                                                           fromm=self.request.user.get_full_name())

        return super(EnterConditionsAssessorView, self).get_context_data(**kwargs)
Exemple #21
0
 def get(self, request, poll_pk):
     poll = m.Poll.objects.get(pk=poll_pk)
     data = serialize(poll, fields=['subject', 'content'])
     data['options'] = {}
     data['total'] = 0
     for option in poll.options.all():
         o = serialize(option, fields=['text', 'index', 'count'])
         data['options'][unicode(option.index)] = o
         data['count'] += o['count']
     if request.user.is_authenticated():
         try:
             data['vote'] = q.votes.get(user=request.user).option.index
         except m.Vote.DoesNotExist:
             data['vote'] = None
     return data
Exemple #22
0
    def prepare(self, instance):
        obj = serialize(instance, **self.template)

        # Augment the links
        obj['_links'] = {
            'self': {
                'rel': 'self',
                'href': reverse('serrano:datafield', args=[instance.pk]),
            },
            'values': {
                'rel': 'data',
                'href': reverse('serrano:datafield-values',
                                args=[instance.pk]),
            },
        }

        if stats_capable(instance):
            obj['_links']['stats'] = {
                'rel': 'data',
                'href': reverse('serrano:datafield-stats', args=[instance.pk]),
            }
            # Add distribution link only if the relevent dependencies are
            # installed.
            if OPTIONAL_DEPS['scipy']:
                obj['_links']['distribution'] = {
                    'rel':
                    'data',
                    'href':
                    reverse('serrano:datafield-distribution',
                            args=[instance.pk]),
                }

        return obj
Exemple #23
0
def serialize_sc_channel(sc_channel, exclude_fields=None):
    """JSON serializer
    Serializes the given spacecraft channel.
    :param sc_channel: The Spacecraft channel object to be serialized
    :param exclude_fields: List of fields to be excluded from the object
    :return: JSON serialization
    """
    if not exclude_fields:
        exclude_fields = ['id', 'spacecraft']

    return serialize(sc_channel,
                     camelcase=True,
                     exclude=exclude_fields,
                     related={
                         'modulation': {
                             'fields': ['modulation']
                         },
                         'bandwidth': {
                             'fields': ['bandwidth']
                         },
                         'bitrate': {
                             'fields': ['bitrate']
                         },
                         'polarization': {
                             'fields': ['polarization']
                         }
                     })
Exemple #24
0
    def post(self, request, *args, **kwargs):
        application = get_object_or_404(Application, pk=request.POST['applicationID'])

        ass_group = get_object_or_404(AssessorGroup, pk=request.POST['assGroupID'])
        assessment = Assessment.objects.get_or_create(
            application=application,
            assessor_group=ass_group,
            defaults={
                'officer': self.request.user
            }
        )[0]

        assessment.status = 'awaiting_assessment'

        assessment.save()

        application.processing_status = determine_processing_status(application)
        application.save()
        application.log_user_action(
            ApplicationUserAction.ACTION_SEND_FOR_ASSESSMENT_TO_.format(ass_group),
            request)

        send_assessment_requested_email(assessment, request)

        # need to only set and save this after the email was sent in case the email fails whereby it should remain null
        assessment.date_last_reminded = date.today()

        assessment.save()

        return JsonResponse({'assessment': serialize(assessment, posthook=format_assessment),
                             'processing_status': PROCESSING_STATUSES[application.processing_status]},
                            safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #25
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        kwargs['application'] = serialize(application, posthook=format_application)

        # if reissue
        if application.licence:
            kwargs['issue_licence_form'] = IssueLicenceForm(instance=application.licence)
        else:
            purposes = '\n\n'.join(Assessment.objects.filter(application=application).values_list('purpose', flat=True))

            if hasattr(application.licence_type, 'returntype'):
                return_frequency = application.licence_type.returntype.month_frequency
            else:
                return_frequency = -1

            kwargs['issue_licence_form'] = IssueLicenceForm(purpose=purposes, is_renewable=application.licence_type.is_renewable,
                                                            return_frequency=return_frequency)

        if application.proxy_applicant is None:
            to = application.applicant_profile.user
        else:
            to = application.proxy_applicant

        kwargs['log_entry_form'] = CommunicationsLogEntryForm(to=to.get_full_name(), fromm=self.request.user.get_full_name())

        return super(IssueLicenceView, self).get_context_data(**kwargs)
Exemple #26
0
 def get(self, request, namespace=None):
     params = {}
     if namespace:
         params['app'] = request.app.clients[namespace]
     else:
         params['app__in'] = request.app.clients.values_list('child__pk', flat=True)
     return serialize(m.Rule.objects.request(request, **params))
def epFailPayment(request):
    KEYS = [settings.MERCHANT_KEY, request.POST['txnid'], request.POST['amount'],request.POST['productinfo'], request.POST['firstname'], request.POST['email'],'', '', '', '', '','', '', '', '', '']
    status = request.POST['status']
    if verify_hash(KEYS, status) == request.POST['hash']:
        return  JsonResponse({'status':'false','cancelreason':serialize(request)})
    else:
       return JsonResponse({'status':'false','reason':'unethical activity detected, transaction stands cancelled'})
Exemple #28
0
def player_stats_etl(audit_date):
    es = Elasticsearch([es_host])
    batch_chunks = []
    iterator = 0
    stats_ext = player_stats_extract(audit_date, 30)  #30
    clv_data_ext = player_clv_data(audit_date, 360)  #360
    stats_trans = transform_player_stats(audit_date, stats_ext, clv_data_ext)
    for rec in stats_trans:
        s = serialize(rec)
        data_dict = {
            "_index":
            "slot_player_stats",
            "_type":
            "stats",
            "_id":
            str(s['player']['player_id']) + '_' +
            str(s['gaming_date']['datekey']),
            "_source":
            s
        }

        batch_chunks.append(data_dict)
        if iterator % 100 == 0:
            try:
                helpers.bulk(es, batch_chunks, request_timeout=60)
            except:
                pass
            del batch_chunks[:]
        iterator = iterator + 1

    if len(batch_chunks) != 0:
        helpers.bulk(es, batch_chunks)
Exemple #29
0
 def get(self, request, *args, **kwargs):
     application = get_object_or_404(Application, pk=args[0])
     data = serialize(
         ApplicationUserAction.objects.filter(application=application),
         **self.serial_template
     )
     return JsonResponse({'data': data}, safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #30
0
 def get(self, request, *args, **kwargs):
     application = get_object_or_404(Application, pk=args[0])
     data = serialize(
         ApplicationUserAction.objects.filter(application=application),
         **self.serial_template
     )
     return JsonResponse({'data': data}, safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #31
0
    def post(self, request, *args, **kwargs):
        amendment_request_form = AmendmentRequestForm(request.POST)
        if amendment_request_form.is_valid():
            amendment_request = amendment_request_form.save()

            application = amendment_request.application
            application.review_status = 'awaiting_amendments'
            application.customer_status = determine_customer_status(
                application)
            application.processing_status = determine_processing_status(
                application)
            application.save()

            send_amendment_requested_email(amendment_request, request=request)

            response = {
                'review_status':
                REVIEW_STATUSES[application.review_status],
                'processing_status':
                PROCESSING_STATUSES[application.processing_status],
                'amendment_request':
                serialize(amendment_request, posthook=format_amendment_request)
            }

            return JsonResponse(response,
                                safe=False,
                                encoder=WildlifeLicensingJSONEncoder)
        else:
            return JsonResponse(amendment_request_form.errors,
                                safe=False,
                                encoder=WildlifeLicensingJSONEncoder)
Exemple #32
0
    def get(self, request, *args, **kwargs):
        ret = get_object_or_404(Return, pk=args[0])
        data = serialize(ReturnLogEntry.objects.filter(ret=ret),
                         posthook=format_communications_log_entry,
                         exclude=['ret', 'communicationslogentry_ptr', 'customer', 'officer']),

        return JsonResponse({'data': data[0]}, safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #33
0
    def _cache_data(self, request, pk, key):
        related = ['sample', 'variant', 'genotype']

        try:
            result = self.model.objects.select_related(*related).get(pk=pk)
        except self.model.DoesNotExist:
            raise Http404

        data = serialize(result, **self.template)

        data['_links'] = {
            'self': {
                'rel': 'self',
                'href': reverse('api:samples:variant',
                    kwargs={'pk': data['id']})
            },
            'sample': {
                'rel': 'related',
                'href': reverse('api:samples:sample',
                    kwargs={'pk': data['sample']['id']})
            },
            'variant': {
                'rel': 'related',
                'href': reverse('api:variants:variant',
                    kwargs={'pk': data['variant_id']}),
            }
        }

        # Integrate the Variant resource data
        data['variant'] = VariantResource.get(request, data['variant_id'])
        data.pop('variant_id')

        cache.set(key, data, timeout=api.CACHE_TIMEOUT)
        return data
Exemple #34
0
 def get(self, request, namespace=None):
     params = {}
     if namespace:
         params['user'] = request.user.accounts[namespace]
     else:
         params['user__in'] = request.user.accounts.values_list('child__pk', flat=True)
     return serialize(m.Trigger.objects.request(request, **params))
Exemple #35
0
 def test_fields(self):
     obj = serialize(self.hackers, fields=['website'], values_list=True)
     self.assertEqual(obj, [
         'http://ejohn.org',
         'https://github.com/jashkenas',
         'http://holovaty.com',
     ])
Exemple #36
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        kwargs['application'] = serialize(application, posthook=format_application)

        # if reissue
        if application.licence:
            kwargs['issue_licence_form'] = IssueLicenceForm(instance=application.licence)

            kwargs['extracted_fields'] = application.licence.extracted_fields
        else:
            purposes = '\n\n'.join(Assessment.objects.filter(application=application).values_list('purpose', flat=True))

            if hasattr(application.licence_type, 'returntype'):
                return_frequency = application.licence_type.returntype.month_frequency
            else:
                return_frequency = -1

            kwargs['issue_licence_form'] = IssueLicenceForm(purpose=purposes, is_renewable=application.licence_type.is_renewable,
                                                            return_frequency=return_frequency)

            kwargs['extracted_fields'] = extract_licence_fields(application.licence_type.application_schema, application.data)

        if application.proxy_applicant is None:
            to = application.applicant
        else:
            to = application.proxy_applicant

        kwargs['log_entry_form'] = ApplicationLogEntryForm(to=to.get_full_name(), fromm=self.request.user.get_full_name())

        kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get(payment_utils.
                                                                      get_application_payment_status(application))

        return super(IssueLicenceView, self).get_context_data(**kwargs)
Exemple #37
0
    def test_prehook_shorthand(self):
        obj = serialize(self.hackers, prehook={'user__first_name': 'John'},
            fields=['user'], related={'user': {'fields': ['first_name']}})

        self.assertEqual(obj, [{
            'user': '******',
        }])
Exemple #38
0
    def get_context_data(self, **kwargs):
        application = get_object_or_404(Application, pk=self.args[0])

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(), '')

        kwargs['application'] = serialize(application, posthook=format_application)

        if is_officer(self.request.user):
            kwargs['customer'] = application.applicant

            kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application),
                                                               fromm=self.request.user.get_full_name())
        else:
            kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get(payment_utils.
                                                                          get_application_payment_status(application))
        if application.processing_status == 'declined':
            message = "This application has been declined."
            details = ApplicationDeclinedDetails.objects.filter(application=application).first()
            if details and details.reason:
                message += "<br/>Reason:<br/>{}".format(details.reason.replace('\n', '<br/>'))
                kwargs['application']['declined_reason'] = details.reason
            messages.error(self.request, message)

        return super(ViewReadonlyView, self).get_context_data(**kwargs)
def player_stats_etl(audit_date):
    es = Elasticsearch([es_host])
    batch_chunks = []
    iterator = 0
    stats_ext = player_stats_extract(audit_date, 30) #30
    clv_data_ext = player_clv_data(audit_date, 360) #360
    stats_trans = transform_player_stats(audit_date, stats_ext, clv_data_ext)
    for rec in stats_trans:
        s = serialize(rec)
        data_dict = {
                "_index": "slot_player_stats", 
                "_type": "stats",
                "_id": str(s['player']['player_id']) + '_' + str(s['gaming_date']['datekey']),
                "_source": s
        }
        
        batch_chunks.append(data_dict)
        if iterator % 100 == 0:
            try:
                helpers.bulk(es, batch_chunks, request_timeout=60)
            except:
                pass
            del batch_chunks[:]
        iterator = iterator + 1
    
    if len(batch_chunks) != 0:
        helpers.bulk(es, batch_chunks)
def budget_etl():
    es = Elasticsearch([es_host])
    batch_chunks = []
    iterator = 0
    budget_ext = DailyBudgetDimension.objects.all().values()
    budget_trans = transform_daily_budget(budget_ext)
    for rec in budget_trans:
        s = serialize(rec)
        id_ = str(s['location']['casino']) + '_' + str(
            s['gaming_date']['datekey'])
        data_dict = {
            "_index": "daily_budget",
            "_type": "daily_budget",
            "_id": id_,
            "_source": s
        }

        batch_chunks.append(data_dict)
        if iterator % 100 == 0:
            helpers.bulk(es, batch_chunks, request_timeout=60)
            del batch_chunks[:]
        iterator = iterator + 1

    if len(batch_chunks) != 0:
        helpers.bulk(es, batch_chunks)
Exemple #41
0
    def post(self, request, *args, **kwargs):
        application = get_object_or_404(Application, pk=request.POST['applicationID'])

        ass_group = get_object_or_404(AssessorGroup, pk=request.POST['assGroupID'])
        assessment = Assessment.objects.get_or_create(application=application, assessor_group=ass_group)[0]

        assessment.status = 'awaiting_assessment'

        assessment.save()

        application.processing_status = determine_processing_status(application)
        application.save()
        application.log_user_action(
            ApplicationUserAction.ACTION_SEND_FOR_ASSESSMENT_TO_.format(ass_group),
            request)

        send_assessment_requested_email(assessment, request)

        # need to only set and save this after the email was sent in case the email fails whereby it should remain null
        assessment.date_last_reminded = date.today()

        assessment.save()

        return JsonResponse({'assessment': serialize(assessment, posthook=format_assessment),
                             'processing_status': PROCESSING_STATUSES[application.processing_status]},
                            safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #42
0
    def get_context_data(self, **kwargs):
        ret = get_object_or_404(Return, pk=self.args[0])

        kwargs['return'] = serialize(ret, posthook=format_return)

        kwargs['tables'] = []

        for resource in ret.return_type.resources:
            resource_name = resource.get('name')
            schema = Schema(resource.get('schema'))
            table = {'name': resource_name, 'title': resource.get('title', resource.get('name')),
                     'headers': schema.headers}

            try:
                return_table = ret.returntable_set.get(name=resource_name)
                rows = [return_row.data for return_row in return_table.returnrow_set.all()]
                validated_rows = list(schema.rows_validator(rows))
                table['data'] = validated_rows
            except ReturnTable.DoesNotExist:
                pass

            kwargs['tables'].append(table)

        kwargs['upload_spreadsheet_form'] = UploadSpreadsheetForm()

        if ret.proxy_customer is None:
            to = ret.licence.holder
        else:
            to = ret.proxy_customer

        kwargs['log_entry_form'] = CommunicationsLogEntryForm(to=to.get_full_name(), fromm=self.request.user.get_full_name())

        return super(CurateReturnView, self).get_context_data(**kwargs)
Exemple #43
0
def get_weblog_history(request):
    try:
        if request.method == 'GET':
            # current_user = request.user
            weblog_id = str(request.GET.get('weblog_id', ''))
            webh_query_set = WeblogHistory.objects.filter(
                weblog_id=weblog_id).order_by('-created_at')
            # webh_json = serializers.serialize("json", webh_query_set)
            webh_json = serialize(webh_query_set,
                                  fields=[
                                      'id', 'weblog_id', 'version',
                                      'created_at', 'verdict', 'old_verdict',
                                      'author_name'
                                  ],
                                  exclude=['weblog'],
                                  aliases={
                                      'author_name': 'get_author_name',
                                      'created_at': 'created_at_txt'
                                  })
            return JsonResponse(
                dict(data=json.dumps(webh_json),
                     msg='WeblogHistory Consulst DONE'))
        else:
            return HttpResponseServerError("Only POST request")
    except Exception as e:
        print_exception()
        return HttpResponseServerError("There was a error in the Server")
Exemple #44
0
    def get(self, request, *args, **kwargs):
        ret = get_object_or_404(Return, pk=args[0])
        data = serialize(ReturnLogEntry.objects.filter(ret=ret),
                         posthook=format_communications_log_entry,
                         exclude=['ret', 'communicationslogentry_ptr', 'customer', 'officer']),

        return JsonResponse({'data': data[0]}, safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #45
0
def slot_revenue_etl(audit_date):
    es = Elasticsearch([es_host])
    batch_chunks = []
    iterator = 0
    revenue_ext = slot_revenue_extract(audit_date)
    revenue_trans = transform_slot_revenue(audit_date, revenue_ext)
    for rec in revenue_trans:
        s = serialize(rec)
        id_ = str(s['slotgame']['slot_number']) + '_' + str(
            s['gaming_date']['datekey'])
        data_dict = {
            "_index": "slot_revenue",
            "_type": "slot_revenue",
            "_id": id_,
            "_source": s
        }

        batch_chunks.append(data_dict)
        if iterator % 100 == 0:
            helpers.bulk(es, batch_chunks, request_timeout=60)
            del batch_chunks[:]
        iterator = iterator + 1

    if len(batch_chunks) != 0:
        helpers.bulk(es, batch_chunks)
Exemple #46
0
    def _create_from_context(self, request, instance):
        context = self.get_context(request)
        results = context.apply()
        instance.bulk(results)

        content = serialize(instance, **self.template)
        return self.render(request, content=content, status=codes.created)
Exemple #47
0
    def post(self, request, **kwargs):
        instance = self.get_object(request, **kwargs)

        if self._requestor_can_fork(request, instance):
            fork = DataQuery(name=instance.name,
                             description=instance.description,
                             view_json=instance.view_json,
                             context_json=instance.context_json,
                             parent=instance)

            if getattr(request, 'user', None):
                fork.user = request.user
            elif request.session.session_key:
                fork.session_key = request.session.session_key

            fork.save()
            request.session.modified = True

            posthook = functools.partial(query_posthook, request=request)
            data = serialize(fork, posthook=posthook, **templates.Query)

            return self.render(request, data, status=codes.created)

        data = {
            'message': 'Cannot fork query',
        }
        return self.render(request, data, status=codes.unauthorized)
Exemple #48
0
    def post(self, request, **kwargs):
        instance = self.get_object(request, **kwargs)

        if self._requestor_can_fork(request, instance):
            fork = DataQuery(name=instance.name,
                             description=instance.description,
                             view_json=instance.view_json,
                             context_json=instance.context_json,
                             parent=instance)

            if getattr(request, 'user', None):
                fork.user = request.user
            elif request.session.session_key:
                fork.session_key = request.session.session_key

            fork.save()
            request.session.modified = True

            posthook = functools.partial(query_posthook, request=request)
            data = serialize(fork, posthook=posthook, **templates.Query)

            return self.render(request, data, status=codes.created)

        data = {
            'message': 'Cannot fork query',
        }
        return self.render(request, data, status=codes.unauthorized)
Exemple #49
0
    def _create_from_context(self, request, instance):
        context = self.get_context(request)
        results = context.apply()
        instance.bulk(results)

        content = serialize(instance, **self.template)
        return self.render(request, content=content, status=codes.created)
Exemple #50
0
 def test_fields(self):
     obj = serialize(self.hackers, fields=['website'], values_list=True)
     self.assertEqual(obj, [
         'http://ejohn.org',
         'https://github.com/jashkenas',
         'http://holovaty.com',
     ])
Exemple #51
0
 def get(self, request, poll_pk, option_idx=None):
     if option_idx is None:
         options = m.Option.objects.filter(poll_pk=poll_pk)
     else:
         options = m.Option.objects.get(poll_pk=poll_pk, index=option_idx)
     return serialize(options, fields=['text', 'index', 'count', 'poll'],
             related={'poll': ['subject', 'content']})
Exemple #52
0
    def get(self, request, pk):
        page = request.GET.get('page', 1)

        related = ['sample', 'variant', 'variant__chr', 'genotype']
        results = self.model.objects.select_related(*related)\
            .filter(sample__pk=pk)

        # Paginate the results
        paginator = Paginator(results, api.PAGE_SIZE)

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

        resp = {
            'result_count': paginator.count,
            'results': serialize(page.object_list, **self.template),
        }

        # Augment the links
        for obj in resp['results']:
            obj['_links'] = {
                'self': {
                    'rel': 'self',
                    'href': reverse('api:samples:variant',
                        kwargs={'pk': obj['id']})
                },
                'sample': {
                    'rel': 'related',
                    'href': reverse('api:samples:sample',
                        kwargs={'pk': obj['sample']['id']})
                },
                'variant': {
                    'rel': 'related',
                    'href': reverse('api:variants:variant',
                        kwargs={'pk': obj['variant_id']}),
                }
            }
            obj.pop('variant_id')

        links = {}
        if page.number != 1:
            links['prev'] = {
                'rel': 'prev',
                'href': reverse('api:samples:variants',
                    kwargs={'pk': pk}) + '?page=' + str(page.number - 1)
            }
        if page.number < paginator.num_pages - 1:
            links['next'] = {
                'rel': 'next',
                'href': reverse('api:samples:variants',
                    kwargs={'pk': pk}) + '?page=' + str(page.number + 1)
            }
        if links:
            resp['_links'] = links
        return resp
Exemple #53
0
 def prepare(self, request, instance, template=None, embed=False):
     if template is None:
         template = self.template
     posthook = functools.partial(
         revision_posthook, request=request,
         object_uri=self.object_model_base_uri,
         object_template=self.object_model_template, embed=embed)
     return serialize(instance, posthook=posthook, **template)
Exemple #54
0
def concept_posthook(instance, data, request, embed, brief, categories=None):
    """Concept serialization post-hook for augmenting per-instance data.

    The only two arguments the post-hook takes is instance and data. The
    remaining arguments must be partially applied using `functools.partial`
    during the request/response cycle.
    """
    uri = request.build_absolute_uri

    if categories is None:
        categories = {}

    if 'category_id' in data:
        # This relies on categories being passed in as a dict with the key
        # being the primary key. This makes it must faster since the
        # categories are pre-cached.
        category = categories.get(data.pop('category_id'))
        data['category'] = serialize(category, **templates.Category)

        if data['category']:
            parent = categories.get(data['category'].pop('parent_id'))
            data['category']['parent'] = serialize(parent,
                                                   **templates.Category)

            # Embed first parent as well, but no others since this is the
            # bound in Avocado's DataCategory parent field.
            if data['category']['parent']:
                data['category']['parent'].pop('parent_id')

    if not brief:
        data['_links'] = {
            'self': {
                'href': uri(reverse('serrano:concept', args=[instance.pk])),
            },
            'fields': {
                'href':
                uri(reverse('serrano:concept-fields', args=[instance.pk])),
            }
        }

    # Embeds the related fields directly in the concept output
    if not brief and embed:
        resource = ConceptFieldsResource()
        data['fields'] = resource.prepare(request, instance)

    return data
Exemple #55
0
    def get(self, request, *args, **kwargs):
        query = request.GET.get('q')

        q = Q(code__icontains=query) | Q(text__icontains=query) & Q(one_off=False)

        conditions = serialize(Condition.objects.filter(q))

        return JsonResponse(conditions, safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #56
0
    def post(self, request, *args, **kwargs):
        try:
            response = serialize(Condition.objects.create(code=request.POST.get('code'), text=request.POST.get('text'),
                                                          one_off=not request.POST.get('addToGeneralList', False)))
        except IntegrityError:
            response = 'This code has already been used. Please enter a unique code.'

        return JsonResponse(response, safe=False, encoder=WildlifeLicensingJSONEncoder)
Exemple #57
0
def format_assessment(instance, attrs):
    attrs['conditions'] = serialize(
        instance.assessmentcondition_set.all().order_by('order'),
        fields=['acceptance_status', 'id', 'condition'],
        posthook=format_assessment_condition)
    attrs['status'] = ASSESSMENT_STATUSES[attrs['status']]

    return attrs
Exemple #58
0
    def prepare(self, request, instance, tree, template=None):
        if template is None:
            template = self.template

        tree = trees[tree]
        posthook = functools.partial(
            context_posthook, request=request, tree=tree)
        return serialize(instance, posthook=posthook, **template)
def proceedToPayment(request, txnId):
    uname = request.POST['payer'].strip()
    amount = request.POST['amount'].strip()
    uemail = request.POST['email'].strip()
    uphone = request.POST['phone'].strip()
    KEYS = [
        settings.MERCHANT_KEY, txnId, amount, 'anyText', uname, uemail, '', '',
        '', '', '', '', '', '', '', ''
    ]
    hash = generate_hash(KEYS)
    item = {
        "key": settings.MERCHANT_KEY,
        "txnid": txnId,
        "amount": amount,
        "productinfo": "anyText",
        "firstname": uname,
        "phone": uphone,
        "email": uemail,
        "surl": request.build_absolute_uri(reverse('epSuccessPayment')),
        "furl": request.build_absolute_uri(reverse('epFailPayment')),
        "hash": hash,
        "udf1": "",
        "udf2": "",
        "udf3": "",
        "udf4": "",
        "udf5": ""
    }
    resp = get_redirect_url(item)
    r = serialize(resp.content)
    r = json.loads(r)
    if r['status'] == 0:
        return JsonResponse({'status': '201', 'error': r['data']})
    elif r['status'] == 1:
        link_id = r['data']
        url = settings.URL_PAY + link_id
        print url
        return HttpResponse("""
                        <html>
                        <head><title>Redirecting...</title></head>
                        <body>
                        <form action='%s' method='post' name="paywitheasebuzz">
                            redirecting to pay.easebuzz.in ....
                        </form>
                        </body>
                        <script language='javascript'>
                            window.onload = function(){
                            document.forms['paywitheasebuzz'].submit()
                            }
                        </script>
                        </html>
                    """ % url)
    else:
        return JsonResponse({
            'status':
            '202',
            'error':
            'Due To security concerns we reject this transaction'
        })
Exemple #60
0
 def test_related(self):
     template = {
         'fields': [':pk', 'website', 'user', 'libraries'],
         'related': {
             'user': {
                 'exclude': ['groups', 'password', 'user_permissions'],
                 'merge': True,
                 'prefix': '%(accessor)s_',
             },
             'libraries': {
                 'fields': ['name'],
                 'values_list': True,
             }
         },
     }
     obj = serialize(self.hackers, **template)
     self.assertEqual(
         obj,
         [{
             'user_is_superuser': True,
             'website': 'http://ejohn.org',
             'user_id': 1,
             'user_is_active': True,
             'user_is_staff': True,
             'user_first_name': 'John',
             'user_last_name': 'Resig',
             'user_username': '******',
             'libraries': ['jQuery'],
             'user_date_joined': datetime.datetime(2009, 5, 16, 15, 52, 40),
             'user_last_login': datetime.datetime(2010, 3, 3, 17, 40, 41),
             'user_email': ''
         }, {
             'user_is_superuser': False,
             'website': 'https://github.com/jashkenas',
             'user_id': 2,
             'user_is_active': True,
             'user_is_staff': True,
             'user_first_name': 'Jeremy',
             'user_last_name': 'Ashkenas',
             'user_username': '******',
             'libraries': ['Backbone', 'CoffeeScript'],
             'user_date_joined': datetime.datetime(2009, 5, 16, 15, 52, 40),
             'user_last_login': datetime.datetime(2010, 3, 3, 17, 40, 41),
             'user_email': ''
         }, {
             'user_is_superuser': True,
             'website': 'http://holovaty.com',
             'user_id': 3,
             'user_is_active': False,
             'user_is_staff': True,
             'user_first_name': 'Adrian',
             'user_last_name': 'Holovaty',
             'user_username': '******',
             'libraries': ['Django'],
             'user_date_joined': datetime.datetime(2009, 5, 16, 15, 52, 40),
             'user_last_login': datetime.datetime(2010, 3, 3, 17, 40, 41),
             'user_email': ''
         }])