コード例 #1
0
ファイル: base.py プロジェクト: hakutyou/django_api
    def request(self,
                interface: str,
                data: Union[dict, list] = None,
                headers=None,
                method=None):
        url = f'{self.base_url}{interface}'

        if isinstance(data, list) or isinstance(data, dict):
            pretty_data = json.dumps(protect_dict_or_list(data),
                                     indent=2,
                                     sort_keys=True,
                                     ensure_ascii=False)
        else:
            pretty_data = str(data)

        logger.info('request_send',
                    extra={
                        'uri': url,
                        'method': 'POST',
                        'request': pretty_data,
                    })
        time_begin = xtime.now()
        if isinstance(data, list):
            if method == 'POST':
                response = requests.post(url, json=data, headers=headers)
            else:
                response = requests.get(url, json=data, headers=headers)
        else:
            if method == 'POST':
                response = requests.post(url, data=data, headers=headers)
            else:
                response = requests.get(url, data=data, headers=headers)
        time_cost = xtime.now() - time_begin
        # 检查返回值
        if response.status_code >= 400:
            raise ClientError('服务器连接错误,请稍后再试')
        try:
            result = json.loads(response.text)
        except AttributeError:
            result = response

        if isinstance(result, dict):
            pretty_result = json.dumps(protect_dict_or_list(result),
                                       indent=2,
                                       sort_keys=True,
                                       ensure_ascii=False)
        else:
            pretty_result = str(result)
        logger.info('request_receive',
                    extra={
                        'uri': url,
                        'duration': str(time_cost.total_seconds()),
                        'response': pretty_result,
                    })
        return response
コード例 #2
0
    def __call__(self, request):
        # Request
        request.time_begin = xtime.now()
        request_post = request.POST or request.body

        # 接收到请求
        if isinstance(request_post, dict):
            request_post = json.dumps(protect_dict_or_list(request_post),
                                      indent=2,
                                      sort_keys=True,
                                      ensure_ascii=False)
        logger.info(
            'response_accept',
            extra={
                'uri':
                f'{request.scheme}://{request.get_host()}{request.get_full_path()}',
                'remote_ip': request.META.get('REMOTE_ADDR'),
                'authorization': request.META.get('HTTP_AUTHORIZATION'),
                # postman 需要传入 header 参数为 internal-token(去掉前面的 HTTP- 并且使用减号代替下划线)
                'internal_token': request.META.get('HTTP_INTERNAL_TOKEN'),
                'method': request.method,
                'data': request_post,
            })
        request.do_request = Session()
        response = self.get_response(request)
        # 返回请求的日志在 shortcuts.py 中
        return response
コード例 #3
0
ファイル: celery.py プロジェクト: hakutyou/django_api
def append_celery(_type, func, *args, **kwargs):
    ic = xtime.to_strtime(xtime.now(), time_format='%Y%m%d%H%M%S') + xrandom.random_string(length=6)
    celery_stage(ic, _type, 0)
    celery_id = func.delay(ic, _type, *args, **kwargs)
    celery_queue = CeleryQueueModels.objects.get(ic=ic)
    celery_queue.celery_id = celery_id
    celery_queue.save(update_fields=['celery_id'])
    return ic
コード例 #4
0
ファイル: score.py プロジェクト: hakutyou/django_api
def score_set(request):
    dict_kanji = DictKanjiItem.objects.get(id=request.post.get('kanji_id'))
    try:
        dict_score = dict_kanji.score.get(account=request.user)
    except DictScore.DoesNotExist:
        dict_score = DictScore.objects.create(
            next_date=to_date(now()),
            score=0,
            account=request.user,
            kanji=dict_kanji,
        )
    # 更新分数
    score = str(int(dict_score.score) * 6 + int(request.post.get('score')))
    dict_score.score = score
    dict_score.next_date = to_date(now() + datetime.timedelta(days=supermemo_2(score)))
    dict_score.save(update_fields=('score', 'next_date'))
    data = {
        'id': dict_score.id,
        'score': dict_score.score,
        'next_date': str(dict_score.next_date),
    }
    return Response(request, 0, data=data)
コード例 #5
0
 def sign(self, headers: dict) -> None:
     headers['date'] = str(xtime.to_timestamp(xtime.now()))
     headers['nonce'] = xrandom.random_string()
     # 签名
     encrypt_header_str = ''
     joint_str = ''
     for i in headers:
         encrypt_header_str += i + ' '
         joint_str += f'{i}: {headers[i]}\n'
     h = hmac.new(self.secret_key.encode(encoding='utf-8'), joint_str[:-1].encode(encoding='utf-8'), hashlib.sha1)
     signature = base64.b64encode(h.digest()).decode()
     headers['Authorization'] = f'hmac id="{self.secret_id}", algorithm="hmac-sha1", ' \
                                f'headers="{encrypt_header_str[:-1]}", signature="{signature}"'
コード例 #6
0
ファイル: score.py プロジェクト: hakutyou/django_api
def score_review(request):
    today = to_date(now())
    dict_score = DictScore.objects.filter(account=request.user, next_date=today).select_related('kanji',
                                                                                                'kanji__kana').first()
    if not dict_score:
        raise ClientError('没有新的项目', code=100)
    data = {
        'id': dict_score.id,
        'kanji_id': dict_score.kanji.id,
        'kana': dict_score.kanji.kana.kana,
        'kanji': dict_score.kanji.kanji,
        'imi': dict_score.kanji.imi,
        'hinnsi': dict_score.kanji.hinnsi,
        'rei': dict_score.kanji.rei,
    }
    return Response(request, 0, data=data)
コード例 #7
0
 def login(user):
     user.last_login = xtime.now()
     user.save(update_fields=['last_login'])
     return
コード例 #8
0
ファイル: shortcuts.py プロジェクト: hakutyou/django_api
def Response(request, code=0, _type='dict', **kwargs):
    """
    code == 0 表示正常的返回
    code > 0 表示错误的 request
        code == 401 表示认证错误(401)
    code < 0 表示外部错误
    """
    _status_mapper = {
        0: 200,
        204: 204,  # 删除成功
        400: 400,  # 参数有误
        401: 401,  # 认证失败
        500: 500,  # 未曾预料的请求
    }
    _type_mapper = {
        'dict': JsonResponse,
    }
    _content_type = {
        'gif': 'image/gif',
        'str': 'text/plain',
    }
    if _type == 'dict':
        if code < 1000:
            ret = kwargs
        else:
            ret = {}
        ret['code'] = code
        content_type = 'application/json'
    else:
        ret = kwargs.get('data', '')
        content_type = kwargs.get('content_type',
                                  _content_type.get(_type, 'text/plain'))
    status = _status_mapper.get(code, 400)
    # logger
    time_cost = xtime.now() - request.time_begin

    if isinstance(ret, dict):
        pretty_ret = json.dumps(protect_dict_or_list(ret),
                                indent=2,
                                sort_keys=True,
                                ensure_ascii=False)
    else:
        pretty_ret = str(ret)

    if code == 0:
        logger.info(
            'response_return',
            extra={
                'uri':
                f'{request.scheme}://{request.get_host()}{request.get_full_path()}',
                'duration': str(time_cost.total_seconds()),
                'method': request.method,
                'response': pretty_ret,
            })
    elif code >= 1000:
        logger.error(
            'response_error',
            extra={
                'uri':
                f'{request.scheme}://{request.get_host()}{request.get_full_path()}',
                'level': 'error',
                'duration': str(time_cost.total_seconds()),
                'method': request.method,
                'response': f'{kwargs["exception"]}\n{kwargs["traceback"]}',
            })
    else:
        logger.warning(
            'response_warning',
            extra={
                'uri':
                f'{request.scheme}://{request.get_host()}{request.get_full_path()}',
                'level': 'warning',
                'duration': str(time_cost.total_seconds()),
                'method': request.method,
                'response': pretty_ret,
            })
    _response = _type_mapper.get(_type, HttpResponse)
    return _response(ret, status=status, content_type=content_type)