Beispiel #1
0
def get_data(data):
    return HttpResponse(renderers.JSONRenderer().render(data))
Beispiel #2
0
def get_role():
    roles = Role.objects.all()
    return HttpResponse(renderers.JSONRenderer().render(roles.values()))
Beispiel #3
0
 def get_renderers(self):
     if self.action == 'status':
         return [renderers.JSONRenderer()]
     else:
         return super(RunViewSet, self).get_renderers()
Beispiel #4
0
    def list(self, request, *args, **kwargs):
        """
        We support multiple arguments for listing semantic fields.

        Exact fields
        ============

        You can use one of:

        * ``paths`` with a semi-colon separated list of paths to retrieve.

        * ``ids`` with a semi-colon separated list of ids to retreive.

        Searching
        =========

        Searching is mutually exclusive with returning exact
        fields. You must use ``search``, ``aspect``, ``scope``, ``root``:

        * ``search`` is the search text

        * ``aspect`` is where to search:

          + ``sf`` the semantic field headings

          + ``lexemes`` the lexemes

        * ``scope`` is the scope of the search:

          + ``all`: all semantic fields

          + ``hte`: only the fields from the HTE

          + ``btw``: only the fields created for BTW

        * ``root`` is the root of the search:

          + ``all``: all semantic fields

          + ``01``, ``02``, ``03``: all fields that have a path
          starting with this number.

        Pagination
        ==========

        When using ``search``, pagination is turned on. You can set
        pagination parameters with ``limit`` and ``offset``. ``limit``
        indicates how many records to return, ``offset`` indicates
        where to start in the set of results.  When paging is turned
        on, the results are returned as a dictionary containing:

        * ``count``: the number of matching results,

        * ``next`` and ``previous``: URLs to the next and previous set
          of results,

        * ``results`` an array of results.

        * ``unfiltered_count``: the total count of records that exist,
          ignoring filtering.

        When paging is off (not searching), the results are just an
        array of matching records.

        Selecting Fields
        ================

        You can reduce or expand the set of returned fields by using
        the ``fields`` parameter, which is a comma separated list of
        field names or field sets. The field sets exist:

        * The default: ``url``, ``path``, ``heading``, ``is_subcat``,
          ``verbose_pos``

        * The ``@search`` field set: ``parent``, ``related_by_pos``

        * The ``@details`` field set: ``parent``, ``related_by_pos``,
          ``lexemes``, ``children``

        See
        `:class:semantic_fields.serializers.SemanticFieldSerializer`
        for the full syntax.

        Depths of Relations
        ===================

        Using ``depths.<fieldname>`` allows to set a depth of
        expansion when following relationships. For instance without
        any specified ``depth``, the ``parent`` relation would be
        serialized as a URL to the parent. With ``depths.parent=1`` it
        would be realized as a serialization of the parent and the
        parent would itself contain a URL to its own
        parent. ``depths.parent=-1`` makes the depth infinite.

        ..warning:: Be careful when setting an infinite depth, as it
                    could cause an enormous amount of queries.
        """
        saved_method = request.method
        request.method = "POST"
        request.csrf_processing_done = False
        reason = CsrfViewMiddleware().process_view(request, None, (), {})
        request.method = saved_method

        if reason:
            return reason

        # If not specified, we use the JSON renderer.
        if request.META.get("HTTP_ACCEPT", None) is None:
            request.accepted_renderer = renderers.JSONRenderer()

        # And we can return only JSON.
        if request.accepted_renderer.media_type != "application/json":
            raise NotAcceptable

        # We have to check that these are set *here* because there's
        # nowhere else to check for them. The filter cannot do it.
        paths = request.GET.get('paths', None)
        ids = request.GET.get('ids', None)
        search = request.GET.get('search', None)

        if paths is None and ids is None and search is None:
            return HttpResponseBadRequest(
                "paths or ids or search must be specified")

        complex_paths = set()
        if paths is not None:
            # This interface accepts queries on semantic field
            # *expressions*. To perform such search, we split any
            # expression in its constituent parts and pass that to the
            # search. We then build "fake" semantic fields that we
            # return.
            paths = set(paths.split(";"))
            cleaned = set()
            for path in paths:
                try:
                    refs = parse_local_references(path)
                except FailedParse:
                    continue

                cleaned |= set(str(ref) for ref in refs)
                if len(refs) > 1:
                    complex_paths.add(path)

            if len(complex_paths) > 0:
                request.GET = request.GET.copy()  # Make it mutable.
                request.GET["paths"] = ";".join(cleaned)

        ret = super(SemanticFieldViewSet, self).list(request, *args, **kwargs)

        if len(complex_paths) > 0:
            # The return value is a response to the modified `paths`
            # we created. We need to modify it:
            #
            # a) to remove those semantic fields that are *only* the
            # result of breaking down a complex expression, and
            #
            # b) to add the result of complex expressions.

            # First, we add.
            sf_by_path = {sf["path"]: sf for sf in ret.data}
            for path in complex_paths:
                try:
                    refs = parse_local_references(path)
                except FailedParse:
                    continue
                combined = self.get_serializer(
                    make_specified_sf([sf_by_path[str(ref)] for ref in refs]))
                sf_by_path[path] = combined.data

            # This filters out what we need to remove.
            ret.data = [sf for path, sf in sf_by_path.items() if path in paths]

        return ret
 def __init__(self):
     self.accepted_renderer = renderers.JSONRenderer()
     self.GET = {}
Beispiel #6
0
class YueLiBaoRefund(APIView):
    """
    http请求方式: POST  投资到期回款.
    http://xxxxxx.com/php/yue/refund/
    refundId 还款记录ID 月利宝还款计划表id
    userId 用户ID
    productId 产品ID
    principal 本金
    interest 利息
    increase 加息额
    plusInterest 平台加息
    t0Interest t+0 利息
    amount 本次还款金额
    tradeType 产品类型 0月利宝 1债转
    remark 备注
    # args = [{'refundId': 1, 'userId': 2, 'productId': 4, 'tradeType': 0, 'remark': 'string',
    #          'amount': 1018, 'principal': 1000, 'interest': 10, 'increase': 5, 'plusInterest': 3, 'add_interest': 6},
    #         {'refundId': 2, 'userId': 2, 'amount': 4, 'tradeType': 0, 'remark': 'string',
    #          'amount': 1018, 'principal': 1000, 'interest': 10, 'increase': 5, 'plusInterest': 3, 'add_interest': 6},
    #         ...]
    返回数据格式:json
    :return:
    """
    permission_classes = (IPValidPermissions, )

    @csrf_exempt
    def post(self, request):

        msg_list = list()
        ret = dict()

        args = request.POST.get('args')
        logger.info('in YueLiBaoRefund!')

        try:
            with transaction.atomic(savepoint=True):
                for arg in eval(args):
                    user = User.objects.filter(pk=arg['userId']).first()

                    # TODO: 此处用marginrecord流水来确定是否还款,容易出问题,最好是用中间表,并建立唯一索引,查询时将表记录锁定
                    margin_record = MarginRecord.objects.filter(
                        # # (Q(catalog=u'月利宝本金入账') | Q(catalog=u'债转本金入账')) &
                        # (Q(catalog=u'\u6708\u5229\u5b9d\u672c\u91d1\u5165\u8d26') |
                        #  Q(catalog=u'\u503a\u8f6c\u672c\u91d1\u5165\u8d26')) &

                        # u'月利宝本金入账' 和 u'债转本金入账'  ---> u'回款本金'
                        # Q(catalog=u'回款本金') &
                        Q(catalog=u'\u56de\u6b3e\u672c\u91d1')
                        & Q(order_id=arg['refundId']) & Q(user=user)).first()

                    if margin_record:
                        logger.info(
                            'refund_ID = {} has been refunded already!!! '.
                            format(arg['refundId']))
                        msg_list.append({
                            'refundId': arg['refundId'],
                            'status': 1
                        })

                    else:
                        buyer_keeper = PhpMarginKeeper(user, arg['refundId'])

                        try:
                            buyer_keeper.php_amortize_detail(
                                arg['tradeType'], arg['principal'],
                                arg['interest'], arg['add_interest'],
                                arg['increase'], arg['plusInterest'],
                                arg['refundId'])
                            msg_list.append({
                                'refundId': arg['refundId'],
                                'status': 1
                            })

                        except Exception, e:
                            ret.update(status=0, msg=e.message)
                            logger.debug(
                                'in YueLiBaoRefund, refund_id = {}, userId = {}, error = {}\n'
                                .format(arg['refundId'], arg['userId'],
                                        e.message))
                            return HttpResponse(
                                renderers.JSONRenderer().render(
                                    ret, 'application/json'))

                ret.update(status=1, msg=msg_list)

        except Exception, e:
            logger.exception('in YueLiBaoRefund, error = {}\n'.format(
                e.message))
            ret.update(status=0, msg=e.message)
        logger.info('refund processed, return = {}\n'.format(ret))
        return HttpResponse(renderers.JSONRenderer().render(
            ret, 'application/json'))
Beispiel #7
0
class AssignmentBuyFail(APIView):
    """
    http请求方式: POST  当主站扣款成功, 新平台没接收到, 调用该接口说明购买失败
    http://xxxxxx.com/php/assignment/fail/
    :return: status = 1  成功, status = 0 失败 .
    """
    permission_classes = (IPValidPermissions, )

    @csrf_exempt
    def post(self, request):

        ret = dict()

        buyer_id = request.POST.get('buyerId')
        seller_id = request.POST.get('sellerId')
        buy_token = request.POST.get('buyToken')
        sell_token = request.POST.get('sellToken')

        assignment = AssignmentOfClaims.objects.filter(buyer_id=buyer_id,
                                                       seller_id=seller_id,
                                                       buyer_token=buy_token,
                                                       seller_token=sell_token,
                                                       status=True).first()

        if not assignment:
            assignment = AssignmentOfClaims.objects.filter(
                buyer_id=buyer_id,
                seller_id=seller_id,
                buyer_token=buy_token,
                seller_token=sell_token).first()
            if assignment:
                ret.update(status=1, msg='success')
                return HttpResponse(renderers.JSONRenderer().render(
                    ret, 'application/json'))
            ret.update(status=2, msg='success')
            return HttpResponse(renderers.JSONRenderer().render(
                ret, 'application/json'))

        try:
            with transaction.atomic(savepoint=True):

                buyer = assignment.buyer
                seller = assignment.seller
                product_id = assignment.product_id
                buyer_keeper = PhpMarginKeeper(buyer, product_id)
                seller_keeper = PhpMarginKeeper(seller, product_id)

                a = buyer_keeper.margin_process(buyer, 0, assignment.buy_price,
                                                u'买家债转退款', u'债转购买失败回滚')
                b = seller_keeper.margin_process(seller, 1,
                                                 assignment.sell_price,
                                                 u'卖家债转退款', u'债转购买失败回滚')
                if a and b:
                    assignment.status = False
                    assignment.save()

                ret.update(status=1, msg='success')
        except Exception, e:
            ret.update(status=0, msg=e.message)
        return HttpResponse(renderers.JSONRenderer().render(
            ret, 'application/json'))
Beispiel #8
0
    def get(self, request):
        result = {
            "result_code": "-1",
            "result_msg": u"未授权的访问!",
            "page_count": "0",
            "page_index": "0",
            "loans": "null"
        }
        try:
            id = int(request.GET.get('id'))
            id_query = Q(id=id)
        except:
            result.update(result_code=-2, result_msg=u'id参数不存在或者格式错误')
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        # 验证日期
        time_from, result = validate_date(request, result, 'time_from')
        time_to, result = validate_date(request, result, 'time_to')

        # 构造日期查询语句
        if time_from and time_to:
            publish_query = Q(publish_time__range=(time_from, time_to))
            try:
                p2pproduct = P2PProduct.objects.filter(hide=False).filter(status__in=[
                    u'正在招标', u'已完成', u'满标待打款', u'满标已打款', u'满标待审核', u'满标已审核', u'还款中'
                ]).filter(publish_query).get(id_query)
            except:
                return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))
        else:
            try:
                p2pproduct = P2PProduct.objects.filter(hide=False).filter(status__in=[
                    u'正在招标', u'已完成', u'满标待打款', u'满标已打款', u'满标待审核', u'满标已审核', u'还款中'
                ]).get(id_query)
            except:
                return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        p2pequities = p2pproduct.equities.all()

        if not p2pequities:
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        # 分页处理
        equities, paginator = handler_paginator(request, p2pequities)
        if not equities:
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        loans = []
        for eq in equities:
            obj = {
                "id": str(p2pproduct.id),
                "link": "https://{}/p2p/detail/{}?promo_token=da57ku".format(request.get_host(), p2pproduct.id),
                "useraddress": "null",
                "username": eq.user.username,
                "userid": str(eq.user.id),
                "type": u"手动",
                "money": Decimal.from_float(eq.equity).quantize(Decimal('0.00')),#str(eq.equity),
                "account": Decimal.from_float(eq.equity).quantize(Decimal('0.00')),#str(eq.equity),
                "status": u"成功",
                "add_time": timezone.localtime(eq.created_at).strftime("%Y-%m-%d %H:%M:%S"),
            }
            loans.append(obj)
        result.update(loans=loans, page_count=str(paginator.num_pages), page_index=str(equities.number),
                      result_code="1",
                      result_msg=u'获取数据成功!')
        return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))
Beispiel #9
0
 def layout_list(self, request, *args, **kwargs):
     self.renderers_classes = [renderers.JSONRenderer()]
     queryset = self.filter_queryset(self.get_queryset())
     serializer = self.get_serializer(queryset, many=True)
     return Response(serializer.data)
Beispiel #10
0
    def get(self, request):

        date_args = request.GET.get('date', '')
        if not date_args:
            return HttpResponse(
                renderers.JSONRenderer().render({'message': u'date必传', 'code': -2}, 'application/json'))
        try:
            start_time = dateparse.parse_date(date_args)

            if not start_time:
                return HttpResponse(
                    renderers.JSONRenderer().render({'message': u'错误的date', 'code': -1}, 'application/json'))
        except:
            return HttpResponse(
                renderers.JSONRenderer().render({'message': u'错误的date', 'code': -1}, 'application/json'))

        p2pproducts = P2PProduct.objects.filter(hide=False) \
            .filter(status=u'正在招标').filter(publish_time__gte=start_time)

        p2p_list = []
        for p2p in p2pproducts:
            amount = Decimal.from_float(p2p.total_amount).quantize(Decimal('0.00'))
            percent = p2p.ordered_amount / amount * 100
            fld_lend_progress = percent.quantize(Decimal('0.0'), 'ROUND_DOWN')

            fld_awards = 0
            fld_interest_year = Decimal.from_float(p2p.expected_earning_rate)
            if p2p.activity:
                fld_awards = 1
                fld_interest_year += p2p.activity.rule.rule_amount * 100

            p2pequity_count = p2p.equities.all().count()

            temp_p2p = {
                'fld_proid': p2p.id,
                "fld_proname": p2p.name,
                "fld_name": u'网利宝',
                "fld_finstarttime": timezone.localtime(p2p.publish_time).strftime("%Y-%m-%d %H:%M:%S"),
                "fld_finendtime": timezone.localtime(p2p.end_time).strftime("%Y-%m-%d %H:%M:%S"),
                "fld_total_finance": p2p.total_amount,
                "fld_lend_period": p2p.period * 30,
                "fld_interest_year": float(fld_interest_year.quantize(Decimal('0.0'))),
                "fld_refundmode": p2p.pay_method,
                "fld_loantype_name": u'第三方担保',
                "fld_guarantee_org": p2p.warrant_company.name,
                "fld_securitymode_name": u'本息保障',
                "fld_mininvest": 100.0,
                "fld_awards": fld_awards,
                "fld_lend_progress": fld_lend_progress,
                "fld_invest_number": p2pequity_count,
                "fld_finance_left": p2p.total_amount - p2p.ordered_amount,
                "fld_lendname": p2p.borrower_name,
                "fld_lendway": p2p.short_usage,
                "fld_netaddress": 'https://{}/p2p/detail/{}?promo_token=hexunw'.format(request.get_host(), p2p.id),
                "fld_status": 1,
                "fld_status_name": u'筹款中'
            }
            p2p_list.append(temp_p2p)
        result = {
            "data": {
                "list": p2p_list,
                "version": "",
                "status": "",
                "msg": ""
            }
        }
        return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))
Beispiel #11
0
    def get(self, request):

        result = {
            "result_code": "-1",
            "result_msg": u"未授权的访问!",
            "page_count": "0",
            "page_index": "0",
            "loans": "null"
        }

        # 验证状态
        status_query, status, result = validate_status(request, result, 'status')
        if not status_query:
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        # 验证日期
        time_from, result = validate_date(request, result, 'time_from')
        if not time_from:
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        time_to, result = validate_date(request, result, 'time_to')
        if not time_to:
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        # 构造日期查询语句
        publish_query = Q(publish_time__range=(time_from, time_to))

        p2pproducts = P2PProduct.objects.select_related('activity').filter(hide=False).filter(status_query).filter(
            publish_query)

        # 分页处理
        p2pproducts, paginator = handler_paginator(request, p2pproducts)
        if not p2pproducts:
            return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))

        if p2pproducts:
            loans = []
            for p2pproduct in p2pproducts:
                status = 0 if p2pproduct.status == u'正在招标' else 1
                # 进度
                amount = Decimal.from_float(p2pproduct.total_amount).quantize(Decimal('0.00'))
                percent = p2pproduct.ordered_amount / amount
                process = percent.quantize(Decimal('0.00'), 'ROUND_DOWN')

                reward = Decimal.from_float(0).quantize(Decimal('0.0000'), 'ROUND_DOWN')
                if p2pproduct.activity:
                    reward = p2pproduct.activity.rule.rule_amount.quantize(Decimal('0.0000'), 'ROUND_DOWN')

                rate = p2pproduct.expected_earning_rate + float(reward * 100)

                rate = Decimal.from_float(rate / 100).quantize(Decimal('0.0000'))

                matches = re.search(u'日计息', p2pproduct.pay_method)
                if matches and matches.group():
                    p_type = 0
                else:
                    p_type = 1

                obj = {
                    "id": str(p2pproduct.id),
                    "platform_name": u"网利宝",
                    "url": "https://{}/p2p/detail/{}?promo_token=da57ku".format(request.get_host(), p2pproduct.id),
                    "title": p2pproduct.name,
                    "username": md5(p2pproduct.borrower_name.encode('utf-8')).hexdigest(),
                    "status": status,
                    "userid": md5(p2pproduct.borrower_name.encode('utf-8')).hexdigest(),
                    # "c_type": u"抵押标" if p2pproduct.category == u'证大速贷' else u"信用标",
                    "c_type": 2 if p2pproduct.category == u'证大速贷' else 0,
                    "amount": amount,
                    "rate": rate,
                    # "period": u'{}个月'.format(p2pproduct.period),
                    "period": p2pproduct.period,
                    "p_type": p_type,#期限类型,0 代表天,1 代表月
                    # "pay_way": str(P2PEYE_PAY_WAY.get(p2pproduct.pay_method, 6)),
                    "pay_way": P2PEYE_PAY_WAY.get(p2pproduct.pay_method, 0),
                    "process": process,
                    "reward": reward,
                    # "guarantee": "null",
                    "guarantee": 0,
                    "start_time": timezone.localtime(p2pproduct.publish_time).strftime(
                        "%Y-%m-%d %H:%M:%S"),
                    "end_time": timezone.localtime(p2pproduct.soldout_time).strftime(
                        "%Y-%m-%d %H:%M:%S") if p2pproduct.soldout_time else 'null',
                    "invest_num": str(p2pproduct.equities.count()),
                    # "c_reward": "null"
                    "c_reward": 0
                }
                loans.append(obj)
            result.update(loans=loans, page_count=str(paginator.num_pages), page_index=str(p2pproducts.number),
                          result_code="1",
                          result_msg=u'获取数据成功!')
        else:
            result.update(result_code='-1', result_msg=u'未授权的访问!')
        return HttpResponse(renderers.JSONRenderer().render(result, 'application/json'))
Beispiel #12
0
    def get(self, request):

        date = request.GET.get('date', '')
        self.date = date
        self.token = request.GET.get('token', '')
        self.page = request.GET.get('page', '')
        self.pageSize = request.GET.get('pageSize', '')
        self.timestamp = request.GET.get('timestamp', '')
        if not date or not self.page or not self.pageSize or not self.timestamp or not self.token:
            return HttpResponse(renderers.JSONRenderer().render({'message': u'错误的参数'}, 'application/json'))
        self.message = self._check_token()
        if self.message:
            return HttpResponse(renderers.JSONRenderer().render({'message': self.message}, 'application/json'))

        date = [int(i) for i in date.split('-')]
        start_time = timezone.datetime(*date)
        end_time = start_time + timezone.timedelta(days=1)

        p2pproducts = P2PProduct.objects.filter(hide=False).filter(status__in=[
            u'满标待打款', u'满标已打款', u'满标待审核', u'满标已审核', u'还款中', u'已完成'
        ]).filter(soldout_time__range=(start_time, end_time))
        count = p2pproducts.count()
        p2p_data = {"totalCount": count}
        if count == 0:
            p2p_data['totalPage'] = 0
        else:
            n = count / int(self.pageSize)
            if count % int(self.pageSize) != 0:
                n = n + 1
            p2p_data['totalPage'] = n
        p2p_list = []
        repaymentType = ''
        for p2p in p2pproducts:

            amount = Decimal.from_float(p2p.total_amount).quantize(Decimal('0.00'))
            percent = p2p.ordered_amount / amount * 100
            schedule = '{}%'.format(percent.quantize(Decimal('0.0'), 'ROUND_DOWN'))

            for pay_method, value in PAY_METHOD_CHOICES:
                if pay_method == p2p.pay_method:
                    repaymentType = value
                    break

            p2pequities = p2p.equities.all()
            subscribes = [{
                    "subscribeUserName": eq.user.username,
                    "amount": Decimal.from_float(eq.equity).quantize(Decimal('0.00')),
                    "validAmount": Decimal.from_float(eq.equity).quantize(Decimal('0.00')),
                    "addDate": timezone.localtime(eq.created_at).strftime("%Y-%m-%d %H:%M:%S"),
                    "status": "1",
                    "type": "0"
                } for eq in p2pequities]

            reward = p2p.activity.rule.rule_amount * 100 if p2p.activity else 0

            matches = re.search(u'日计息', p2p.pay_method)
            if matches and matches.group():
                deadlineUnit = u"天"
            else:
                deadlineUnit = u"月"

            temp_p2p = {
                "projectId": str(p2p.pk),
                "title": p2p.name,
                "amount": amount,
                "schedule": schedule,
                "interestRate": '{}%'.format(Decimal.from_float(p2p.expected_earning_rate).quantize(Decimal('0.0'))+reward),
                "deadline": str(p2p.period),
                "deadlineUnit": deadlineUnit,
                "reward": '{}'.format(reward),
                "type": u"信用标" if p2p.category == u'证大速贷'else u"抵押标",
                "repaymentType": str(repaymentType),
                "subscribes": subscribes,
                #"userName": md5(p2p.borrower_bankcard_bank_name.encode('utf-8')).hexdigest(),
                "userName": md5(p2p.brief.encode('utf-8')).hexdigest(),
                #"amountUsedDesc": strip_tags(p2p.short_usage),
                "loanUrl": "https://{}/p2p/detail/{}".format(request.get_host(), p2p.id),
                "warrantcom": p2p.warrant_company.name,
                #"successTime": timezone.localtime(p2p.soldout_time).strftime("%Y-%m-%d %H:%M:%S"),
                #"publishTime": timezone.localtime(p2p.publish_time).strftime("%Y-%m-%d %H:%M:%S")
            }
            p2p_list.append(temp_p2p)
        p2p_data["borrowList"] = p2p_list
        return HttpResponse(renderers.JSONRenderer().render(p2p_data, 'application/json'))
Beispiel #13
0
def start_applying_task(task):
    task_data = renderers.JSONRenderer().render(EvalTaskSerializer(task, task_type=APPLYING).data)
    logger.info('start_applying_task %s', task_data)
    return start_task(task.id, task_data)
Beispiel #14
0
def start_learning_task(task):
    task_data = renderers.JSONRenderer().render(TrainingTaskSerializer(task, task_type=LEARNING).data)
    logger.info('start_learning_task %s', task_data)
    return start_task(task.id, task_data)
Beispiel #15
0
class YueLiBaoCheck(APIView):
    """
    http请求方式: POST  满标审核完毕, 减去冻结资金
    http://xxxxxx.com/php/yue/check/
    返回数据格式:json
    :return:
    """
    permission_classes = (IPValidPermissions, )

    @csrf_exempt
    def post(self, request):

        logger.info('in YueLiBaoCheck!!!!!!')

        ret = dict()

        product_id = request.POST.get('productId')
        period = int(request.POST.get('period'))

        try:
            with transaction.atomic(savepoint=True):
                # 字段没有索引, 应该会锁表?
                # 会锁, 已验证
                month_products = MonthProduct.objects.filter(
                    product_id=product_id,
                    cancel_status=False,
                    trade_status='PAID')

                for product in month_products:
                    # 这是对应商城直接购买的还款, 如果有这种还款忽略.
                    if product.red_packet == -1:
                        product.red_packet = 0
                        product.save()
                        continue
                    if product.settle_status:
                        logger.info(
                            u'该条记录已审核: product = {}, 这是重复请求, product_id = {}'.
                            format(product.id, product_id))
                        continue
                    product.settle_status = True
                    product.save()
                    # 已支付, 直接返回成功
                    user = product.user
                    product_id = product.product_id
                    buyer_keeper = PhpMarginKeeper(user, product_id)
                    buyer_keeper.php_settle(product.amount_source,
                                            description=u'月利宝满标审核')

                # 进行全民淘金数据写入
                try:
                    calc_php_commission(product_id, period)
                    logger.info(u'period = {}, 全民淘金数据写入: {}\n'.format(
                        period, product_id))
                except Exception, ex:
                    logger.exception(
                        u'period = {}, 全民淘金数据写入: {}, except: {}\n'.format(
                            period, product_id, ex))

                ret.update(status=1, msg='success')
        except Exception, e:
            logger.debug(u'月利宝id: {} 满标审核失败: {}\n'.format(
                product_id, e.message))
            ret.update(status=0, msg=e.message)
        return HttpResponse(renderers.JSONRenderer().render(
            ret, 'application/json'))
Beispiel #16
0
import snippets.serializers as ser


snippet1 = models.Snippet()
snippet1.code = """
de fukkin():
    print(';laksdjf')
"""
snippet1.save()

serializer1 = ser.SnippetSerializer(instance=snippet1)

print(serializer1.data)
print(serializer1.data['code'])

bin_data = renderers.JSONRenderer().render(serializer1.data)

print(bin_data)

stream = io.BytesIO(bin_data)

print(stream)

decoded_data = parsers.JSONParser().parse(stream)

print(decoded_data)



snippet1_restored = ser.SnippetSerializer(data=decoded_data)
Beispiel #17
0
class YueLiBaoCancel(APIView):
    """
    http请求方式: POST  流标, 钱原路返回
    http://xxxxxx.com/php/yue/cancel/
    返回数据格式:json 外层 status = 1 API 成功, 里层status = 1 当个订单返回成功.
    :return:
    """
    permission_classes = (IPValidPermissions, )

    @csrf_exempt
    def post(self, request):

        msg_list = []
        ret = dict()

        tokens = request.POST.get('tokens')
        tokens = tokens.split('|')
        logger.info(u'流标 tokens = {}'.format(tokens))

        try:
            with transaction.atomic(savepoint=True):
                month_products = MonthProduct.objects.select_for_update(
                ).filter(token__in=tokens)
                for product in month_products:
                    user = product.user
                    product_id = product.product_id
                    buyer_keeper = PhpMarginKeeper(user, product_id)
                    record = buyer_keeper.php_unfreeze(product.amount_source,
                                                       description=u'月利宝流标')

                    # 状态置为已退款, 这个记录丢弃
                    product.cancel_status = True
                    product.save()
                    logger.info(
                        'cancel_status saved as true! month_product_id = {}'.
                        format(product_id))

                    # 增加回退红包接口
                    result = php_redpack_restore(product.id, product_id,
                                                 product.amount_source, user)
                    logger.info(
                        u'判断是否有红包, month_product_id = {}'.format(product_id))
                    # 用户红包金额退回
                    if result['ret_code'] != -1:
                        logger.info(
                            u'使用过红包. result = {}, result["ret_code"] = {}'.
                            format(result, result['ret_code']))
                        buyer_keeper.redpack_return(
                            result['deduct'],
                            description=u"月利宝id=%s流标 红包退回%s元" %
                            (product_id, result['deduct']))

                    status = 1 if record else 0
                    msg_list.append({'token': product.token, 'status': status})

            ret.update(status=1, msg=msg_list)
            logger.info(u'tokens = {}, 流标成功\n'.format(tokens))
        except Exception, e:
            logger.debug(u'tokens = {}, 流标失败: {}\n'.format(tokens, e.message))
            ret.update(status=0, msg=e.message)
        return HttpResponse(renderers.JSONRenderer().render(
            ret, 'application/json'))
Beispiel #18
0
 def get_default_renderer(self, view):
     return renderers.JSONRenderer()
Beispiel #19
0
    def post(self, request):

        msg_list = list()
        ret = dict()

        args = request.POST.get('args')
        logger.info('in YueLiBaoRefund!')

        try:
            with transaction.atomic(savepoint=True):
                for arg in eval(args):
                    user = User.objects.filter(pk=arg['userId']).first()

                    # TODO: 此处用marginrecord流水来确定是否还款,容易出问题,最好是用中间表,并建立唯一索引,查询时将表记录锁定
                    margin_record = MarginRecord.objects.filter(
                        # # (Q(catalog=u'月利宝本金入账') | Q(catalog=u'债转本金入账')) &
                        # (Q(catalog=u'\u6708\u5229\u5b9d\u672c\u91d1\u5165\u8d26') |
                        #  Q(catalog=u'\u503a\u8f6c\u672c\u91d1\u5165\u8d26')) &

                        # u'月利宝本金入账' 和 u'债转本金入账'  ---> u'回款本金'
                        # Q(catalog=u'回款本金') &
                        Q(catalog=u'\u56de\u6b3e\u672c\u91d1')
                        & Q(order_id=arg['refundId']) & Q(user=user)).first()

                    if margin_record:
                        logger.info(
                            'refund_ID = {} has been refunded already!!! '.
                            format(arg['refundId']))
                        msg_list.append({
                            'refundId': arg['refundId'],
                            'status': 1
                        })

                    else:
                        buyer_keeper = PhpMarginKeeper(user, arg['refundId'])

                        try:
                            buyer_keeper.php_amortize_detail(
                                arg['tradeType'], arg['principal'],
                                arg['interest'], arg['add_interest'],
                                arg['increase'], arg['plusInterest'],
                                arg['refundId'])
                            msg_list.append({
                                'refundId': arg['refundId'],
                                'status': 1
                            })

                        except Exception, e:
                            ret.update(status=0, msg=e.message)
                            logger.debug(
                                'in YueLiBaoRefund, refund_id = {}, userId = {}, error = {}\n'
                                .format(arg['refundId'], arg['userId'],
                                        e.message))
                            return HttpResponse(
                                renderers.JSONRenderer().render(
                                    ret, 'application/json'))

                ret.update(status=1, msg=msg_list)

        except Exception, e:
            logger.exception('in YueLiBaoRefund, error = {}\n'.format(
                e.message))
            ret.update(status=0, msg=e.message)
Beispiel #20
0
        self.country = country
        self.capital_city = capital_city
        self.capital_population = capital_population
        self.author = user


author_obj = User('test_user')  # Создаём запись об автора
# Создаём 4 отдельные записи
capital_1 = Capital('Norway', 'Oslo', 693500, author_obj)
capital_2 = Capital('Sweden ', 'Stockholm', 961600, author_obj)
capital_3 = Capital('Finland', 'Helsinki', 655300, author_obj)
capital_4 = Capital('Iceland', 'Reykjavik', 128800, author_obj)
# Объединяем записи в набор - аналог Capital.objects.all()
queryset = [capital_1, capital_2, capital_3, capital_4]


# Объявляем класс сериалайзера
class CapitalSerializer(serializers.Serializer):
    capital_city = serializers.CharField(max_length=200)
    capital_population = serializers.IntegerField()
    author = serializers.CharField(source='author.username', max_length=200)


# instance - набор записей, many=True - сериализовать нужно
# именно несколько записей, а не одну
serializer_obj = CapitalSerializer(instance=queryset, many=True)
# Рендерим данные в json
json_render_for_our_data = renderers.JSONRenderer()
data_in_json = json_render_for_our_data.render(serializer_obj.data)
print(data_in_json)
Beispiel #21
0
 def get_default_renderer(self, view):
     renderer = super(BrowsableAPIRenderer, self).get_default_renderer(view)
     # Always use JSON renderer for browsable OPTIONS response.
     if view.request.method == 'OPTIONS' and not isinstance(renderer, renderers.JSONRenderer):
         return renderers.JSONRenderer()
     return renderer
Beispiel #22
0
    print("Generating data")
    for i in range(0, 10000):
        MyModel.create(i)
# The serializers


class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel


print("Test plain serializer:")
samples = []
for i in range(0, 10):
    start = datetime.now()
    data = renderers.JSONRenderer().render(
        MySerializer(MyModel.objects.all(), many=True).data)
    samples.append(datetime.now() - start)
print("Avg: %s" % (sum(samples, timedelta()) / 10))

print("Test obj_to_representation:")


class ToReprSerializer(fast_serializer.Mixin, serializers.ModelSerializer):
    to_representation = fast_serializer.obj_to_representation

    class Meta:
        model = MyModel


samples = []
for i in range(0, 10):
Beispiel #23
0
 def render(self, data, media_type=None, renderer_context=None):
     if isinstance(data, dict):
         return renderers.JSONRenderer().render(data, media_type,
                                                renderer_context)
     return data
 def render(self, data, media_type=None, renderer_context=None):
     return str(renderers.JSONRenderer().render(
         data, media_type, renderer_context)).encode(self.charset)
Beispiel #25
0
 def render(self, data, media_type=None, renderer_context=None):
     model_name = self.get_model_name(renderer_context)
     json_str = renderers.JSONRenderer().render(data, media_type, renderer_context)
     return 'define("{0}",function(){{return {1};}});'.format(model_name, json_str)
Beispiel #26
0
def getWorkers(data):
    if (data['id'] == '*'):
        worker = Workers.objects.all().values()
    else:
        worker = Workers.objects.filter(id=data['id'])
    return HttpResponse(renderers.JSONRenderer().render(worker.values()))
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if not isinstance(data, etl.Engine):
            return renderers.JSONRenderer().render(data, accepted_media_type,
                                                   renderer_context)

        return data.to_csv().encode()
Beispiel #28
0
    def get(self, request):
        user = self.request.user
        ret = get_mall_locked_amount(user)

        return HttpResponse(renderers.JSONRenderer().render(
            ret, 'application/json'))
Beispiel #29
0
 def __init__(self, data, **kwargs):
     content = renderers.JSONRenderer().render(data)
     kwargs['content_type'] = 'application/json'
     super(JSONResponse, self).__init__(content, **kwargs)
Beispiel #30
0
    def __init__(self, data, *args, **kwargs):
        data = renderers.JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'

        super().__init__(data, **kwargs)