Ejemplo n.º 1
0
    def process_exception(self, request, exception):
        _exception_code = {
            redis.exceptions.ConnectionError: lambda: {
                'code': -1,
                'msg': 'Redis Error',
            },
            ClientError: lambda: {
                'code': exception.code,
                'msg': exception.response,
            },
            ServiceError: lambda: {
                'code': exception.code,
                'msg': exception.response,
            },
        }

        error_info = _exception_code.get(type(exception))
        if error_info:
            error_info = error_info()
            return Response(request,
                            code=error_info['code'],
                            msg=error_info['msg'])

        if settings.DEBUG or (time.time() - self.mail_time < 60):
            code = 1000
        else:
            code = 1001
            # 加入 celery 队列
            append_celery('mail', send_mail_celery, exception,
                          traceback.format_exc(), settings.EMAIL_RECEIVER)
            self.mail_time = time.time()
        return Response(request,
                        code=code,
                        exception=exception,
                        traceback=traceback.format_exc())
Ejemplo n.º 2
0
def user_remove(request):
    user_id = request.post.get('user_id')
    try:
        result = face_service.user_remove(user_id)
    except FaceUser.DoesNotExist:
        return Response(request, 1, msg='不存在该用户')
    return Response(request, 0, data=result)
Ejemplo n.º 3
0
def get_video_check(request):
    """
    获取异步下载的视频
    """
    ic = request.post.get('ic')
    state, result = celery_check(ic)
    if state < 0:
        return Response(request, 1, msg='failed')
    if state != 2:
        return Response(request, 2, msg='loading')
    return Response(request, 0, data=result)
Ejemplo n.º 4
0
def show_streams(request):
    """
    查看多媒体文件的流信息(list)
    index           序号
    codec_name      编码名
    codec_long_name
    profile
    level
    width           视频画面大小
    height          视频画面大小
    has_b_frame
    r_frame_rate    能够准确表示所有时间戳的最低帧速率, 整个视频帧率的最小公倍数
    例如 第一秒为 2帧/秒 第三秒为 3帧/秒, 该值为 6(6帧/秒 才可以表示所有帧的时间戳)
    avg_frame_rate  平均帧率(帧/s)
    bit_rate        码率(bps)
    codec_type      video/audio/subtitle
    time_base       时间戳计算基础单位
    duration_ts     duration_ts * time_base = duration  视频时间长度
    codec_time_base 编码的时间戳计算基础单位
    """
    try:
        data = ffmpeg.probe(request.post.get('url'),
                            show_streams=None).get('streams')
    except ffmpeg.Error:
        raise ClientError('多媒体文件错误')
    return Response(request, 0, data=data)
Ejemplo n.º 5
0
def scf_common(request, path):
    """
    转 SCF 调用,仅 demo 测试
    """
    data = request.POST.dict()
    result = scf_service.post(path, data=data)
    return Response(request, 0, msg=result)
Ejemplo n.º 6
0
def general_recognition(request):
    url = request.post.get('url')
    try:
        result = vision_service.image_detect(url)
    except KeyError:
        raise ClientError('图片格式错误')
    return Response(request, 0, data=result)
Ejemplo n.º 7
0
def get_file_info(request, path):
    try:
        response = tencent_cos_service.file(path=path)
    except CosClientError as e:
        raise ServiceError(str(e), code=-1)
    except CosServiceError as e:
        raise ServiceError(e.get_error_msg(), code=-2)

    content_type = response['Content-Type']
    if request.post.get('detail') is None:
        data = {'type': content_type, 'length': response['Content-Length']}
        return Response(request, 0, data=data)
    else:
        with response['Body'].get_raw_stream() as fp:
            content = fp.read()
            return Response(request, 0, _type='str', data=content, content_type=content_type)
Ejemplo n.º 8
0
def modify_password(request):
    password = request.post.get('password')
    new_password = request.post.get('new_password')
    if not request.user.check_password(password):
        raise ClientError('原密码错误', code=401)

    request.user.set_password(new_password)
    request.user.save(update_fields=['password'])
    return Response(request, 0)
Ejemplo n.º 9
0
def get_captcha(request):
    """
    最简单的图片验证码
    """
    b64 = request.post.get('b64', 0)
    # 通过签名区分不同客户端请求
    sign = request.post.get('sign')

    # 防止混淆
    exclude = '0129'  # 0:O, 1:l, 2:z, 9:g
    code = random_string(length=4, exclude=exclude)
    print(code)
    cache.set(f'captcha:{sign}', code.lower(), 60 + 10)
    if b64 == 0:
        response_text = captcha.get_captcha_base64(code)
        return Response(request, 0, _type='gif', data=response_text)
    response_text = f'data:image/png;base64,{captcha.get_captcha_base64("1234", b64=True).decode()}'
    return Response(request, 0, _type='str', data=response_text)
Ejemplo n.º 10
0
def get_video_info(request):
    """
    获得视频信息
    """
    av = request.post.get('av')
    bv = request.post.get('bv')
    if not av and not bv:
        raise ServiceError('Argument Error', code=400)

    response = bilibili_api.get_video_info(bv, av)
    return Response(request, 0, data=response.get('data'))
Ejemplo n.º 11
0
def upload_file(request):
    path = request.post.get('path')
    bucket = request.post.get('bucket')
    try:
        content = tencent_cos_service.upload(request.byte_stream, path=path, bucket=bucket)
    except CosClientError as e:
        raise ServiceError(str(e), code=-1)
    except CosServiceError as e:
        raise ServiceError(e.get_error_msg(), code=-2)

    return Response(request, 0, _type='str', data=content)
Ejemplo n.º 12
0
 def get(self, request):
     """
     获得用户信息
     """
     # 登录校验
     if request.user.is_anonymous:
         raise ClientError('未登录', code=401)
     data = {
         'username': request.user.username,
         'last_login': xtime.to_strtime(request.user.last_login),
     }
     return Response(request, 0, data=data)
Ejemplo n.º 13
0
 def post(self, request, *args, **kwargs):
     try:
         serializer = self.serializer_class(
             data=request.data, context=self.get_serializer_context())
         serializer.is_valid(raise_exception=True)
     except exceptions.AuthenticationFailed:
         raise ClientError('用户名或密码错误', code=401)
     token = csrf.get_token(request)
     serializer.validated_data['csrf_token'] = token
     UserSerializer.login(serializer.user)
     # 内部调用使用 request.do_request 代替 requests 以保持 rid 一致
     # request.do_request.get('http://127.0.0.1:8000/account/user/')
     return Response(request, 0, **serializer.validated_data)
Ejemplo n.º 14
0
def score_get(request):
    dict_kanji = DictKanjiItem.objects.exclude(score__account=request.user).select_related('kana').first()
    if not dict_kanji:
        raise ClientError('没有新的项目', code=100)
    data = {
        'kanji_id': dict_kanji.id,
        'kana': dict_kanji.kana.kana,
        'kanji': dict_kanji.kanji,
        'imi': dict_kanji.imi,
        'hinnsi': dict_kanji.hinnsi,
        'rei': dict_kanji.rei,
    }
    return Response(request, 0, data=data)
Ejemplo n.º 15
0
def general_ocr(request):
    url = request.post.get('url')
    lang = request.post.get('lang')
    try:
        result = ocr_service.ocr_general(url, lang)
    except KeyError:
        raise ClientError('图片格式错误', code=401)
        # return Response(request, 0, data='图片格式错误')

    data = ''
    # for i in result:
    #     data += f'{i["words"]}\n'
    return Response(request, 0, data=result)
Ejemplo n.º 16
0
def check_captcha(request):
    """
    验证验证码正确性,单独调用可能会通过修改 html 跳过这个步骤
    应该放在 login 内,如果验证码错误就不返回 access_token
    """
    sign = request.post.get('sign')
    code = request.post.get('code').lower()
    right_code = cache.get(f'captcha:{sign}')
    if right_code is None:
        raise ClientError('验证码超时,请刷新重试')
    if right_code != code:
        cache.delete(f'captcha:{sign}')
        raise ClientError('验证码错误')
    return Response(request, 0)
Ejemplo n.º 17
0
def get_file_list(request, path):
    response = tencent_cos_service.list(path=path)
    files = []
    directories = []
    for file in response.get('Contents', []):
        filename = file['Key']
        if filename[-1] == '/':
            continue
        files.append(filename)

    for directory in response.get('CommonPrefixes', []):
        directories.append(directory['Prefix'])

    data = {'file': files,
            'directory': directories}
    return Response(request, 0, data=data)
Ejemplo n.º 18
0
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)
Ejemplo n.º 19
0
def reset_password(request):
    username = request.post.get('username')
    mobile = request.post.get('mobile')
    new_password = request.post.get('new_password')
    code = request.post.get('code')
    try:
        user = UserModel.objects.get(username=username, mobile=mobile, is_active=1)
    except UserModel.DoesNotExist:
        raise ClientError('账号不存在或手机错误', code=401)

    if not tencent_sms_service.check_sms('reset_password', mobile, code):
        raise ClientError('验证码错误', code=401)

    user.set_password(new_password)
    user.save(update_fields=['password'])
    return Response(request, 0)
Ejemplo n.º 20
0
def show_format(request):
    """
    查看多媒体的封装格式
    nb_stream       包含的流的个数 (show_streams)
    nb_programs     节目数
    format_name     使用的封装模块的名称
    format_long_name
    start_time      媒体文件的起始时间
    duration        媒体文件的总时间长度
    size            媒体文件的大小
    bit_rate        媒体文件的码率
    """
    try:
        data = ffmpeg.probe(request.post.get('url'),
                            show_format=None).get('format')
    except ffmpeg.Error:
        raise ClientError('多媒体文件错误')
    return Response(request, 0, data=data)
Ejemplo n.º 21
0
def proxy_common(request):
    """
    转外网调用,私有网络(SCF)访问外网时使用
    """
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \
    Chrome/55.0.2883.87 Safari/537.36'
    }
    url = request.post.get('url')
    json_ = request.post.get('json')
    if json_:
        json_ = json.loads(json_)
    method = request.post.get('method')
    if method == 'get':
        response = requests.get(url, json=json_, headers=headers)
    else:
        response = requests.post(url, json=json_, headers=headers)
    return Response(request, 0, _type='str', data=response.text)
Ejemplo n.º 22
0
 def post(self, request, *args, **kwargs):
     data = request.data.dict()
     kana = data.get('kana')
     kanji = data.get('kanji')
     if not kana or not kanji:
         raise ServiceError('Argument Error', code=400)
     # kana_query
     try:
         kana_query = self.queryset.get(kana=kana)
     except DictKanaItem.DoesNotExist:
         kana_query = self.queryset.create(kana=kana)
     # kanji_query
     try:
         kanji_query = kana_query.kanji.get(kanji=kanji)
     except DictKanjiItem.DoesNotExist:
         kanji_query = kana_query.kanji.create(kanji=data.get('kanji'), )
     kanji_query.theta = data.get('theta', 0.2)
     kanji_query.hinnsi = data.get('hinnsi', '')
     kanji_query.rei = data.get('rei', '')
     kanji_query.save(update_fields=['theta', 'hinnsi', 'rei'])
     return Response(request, 0)
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
def get_video(request):
    """
    下载视频(异步)
    """
    av = request.post.get('av')
    bv = request.post.get('bv')
    # 视频品质, 80 表示 1080P
    quality = request.post.get('quality', 80)
    if not av and not bv:
        raise ServiceError('Argument Error', code=400)

    response = bilibili_api.get_video_info(bv, av)
    referer = response.get('Referer')
    data = response.get('data')
    bvid = data.get('bvid')
    title = data.get('title').replace(' ', '-')
    desc = data.get('desc')  # 简介
    pic = data.get('pic')  # 封面

    ic_list = []
    for item in data['pages']:
        cid = str(item['cid'])
        page = str(item['page'])
        part_title = item['part'].replace(' ', '-')  # 分 P 的标题
        video_list = []
        for d_url in bilibili_api.get_play_list(referer, cid, quality)['durl']:
            video_list.append(d_url['url'])
        # 加入 celery 队列
        ic = append_celery('download', download_video_celery, referer, video_list,
                           filename=f'{title}_{part_title}',
                           codename=f'{bvid}_{page}')
        ic_list.append(ic)
    # 返回 celery 队列中的 ID
    return Response(request, 0, data={
        'title': title,
        'desc': desc,
        'pic': pic,
        'ic_list': ic_list,
    })
Ejemplo n.º 25
0
 def _sms_sender(request):
     mobile = request.POST.get('mobile')
     if (not mobile) or (action not in ACTION_RANGE):
         return ClientError('请输入手机号码', code=400)
     tencent_sms_service.send_sms(action, mobile)
     return Response(request, 0)
Ejemplo n.º 26
0
def face_compare(request):
    url_1 = request.post.get('url_1')
    url_2 = request.post.get('url_2')
    result = face_service.face_compare(url_1, url_2)
    return Response(request, 0, data=result)
Ejemplo n.º 27
0
def user_add(request):
    url = request.post.get('url')
    user_name = request.post.get('user_name')
    # 录入
    result = face_service.user_add(url=url, user_name=user_name)
    return Response(request, 0, data=result)
Ejemplo n.º 28
0
def user_search(request):
    url = request.post.get('url')
    result = face_service.user_search(url=url)
    return Response(request, 0, data=result)
Ejemplo n.º 29
0
def user_list(request):
    result = face_service.user_list()
    return Response(request, 0, data=result)
Ejemplo n.º 30
0
def face_detect(request):
    url = request.post.get('url')
    # field = request.post.get('field', '')
    result = face_service.face_detect(url)
    return Response(request, 0, data=result)