Esempio n. 1
0
 def get_tag_by_id(cls, tag_id):
     try:
         o_tag = cls.objects.get(pk=tag_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_TAG)
     return Ret(o_tag)
Esempio n. 2
0
 def get_user_by_str_id(cls, str_id):
     try:
         o_user = cls.objects.get(str_id=str_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Esempio n. 3
0
 def get_photo_by_id(cls, photo_id):
     try:
         o_photo = cls.objects.get(photo_id=photo_id)
     except Photo.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.PHOTO_NOT_FOUND)
     return Ret(Error.OK, o_photo)
Esempio n. 4
0
def require_login_func(request):
    """需要登录

    并根据传入的token获取user
    """
    jwt_str = request.META.get('HTTP_TOKEN')
    if jwt_str is None:
        return Ret(Error.REQUIRE_LOGIN)
    from Base.jtoken import jwt_d

    ret = jwt_d(jwt_str)
    if ret.error is not Error.OK:
        return ret
    dict_ = ret.body

    try:
        user_id = dict_["user_id"]
    except KeyError as err:
        deprint(str(err))
        return Ret(Error.STRANGE)

    from User.models import User
    ret = User.get_user_by_id(user_id)
    if ret.error is not Error.OK:
        return ret
    o_user = ret.body
    if not isinstance(o_user, User):
        return Ret(Error.STRANGE)

    request.user = o_user
    return Ret()
Esempio n. 5
0
    def create(cls, qt_user_app_id, token):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        ret = cls.get_user_by_qt_user_app_id(qt_user_app_id)
        if ret.error is Error.OK:
            o_user = ret.body
            o_user.qtb_token = token
            o_user.save()
            return Ret(o_user)
        try:
            o_user = cls(
                qt_user_app_id=qt_user_app_id,
                qtb_token=token,
                port=cls.get_unique_port(),
                ss_pwd=get_random_string(length=8),
                ss_on=False,
                ss_change_time=0,
            )
            o_user.save()
        except Exception as err:
            deprint(str(err))
            return Ret(Error.ERROR_CREATE_USER)

        o_user.do_ss_on()

        return Ret(o_user)
Esempio n. 6
0
 def wrapper(request, *args, **kwargs):
     """wrapper"""
     if not isinstance(request, HttpRequest):
         return error_response(Error.STRANGE)
     if request.method != method:
         return error_response(Error.ERROR_METHOD, append_msg=',需要%s请求' % method)
     if request.method == "GET":
         request.DICT = request.GET.dict()
     else:
         try:
             request.DICT = json.loads(request.body.decode())
         except json.JSONDecodeError as err:
             deprint(str(err))
             request.DICT = {}
     if decode:
         for k in request.DICT.keys():
             import binascii
             try:
                 base64.decodebytes(bytes(request.DICT[k], encoding='utf8')).decode()
             except binascii.Error as err:
                 deprint(str(err))
                 return error_response(Error.REQUIRE_BASE64)
     ret = validate_params(r_params, request.DICT)
     if ret.error is not Error.OK:
         return error_response(ret)
     request.d = Param(ret.body)
     return func(request, *args, **kwargs)
Esempio n. 7
0
    def create(cls, name, singer, cover, total_comment, netease_id, o_user):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        ret = cls.get_music_by_netease_id(netease_id)
        if ret.error is Error.OK:
            return ret

        crt_time = datetime.datetime.now().timestamp()

        try:
            o_music = cls(
                name=name,
                singer=singer,
                cover=cover,
                total_comment=total_comment,
                netease_id=netease_id,
                re_user=o_user,
                create_time=crt_time,
                status=cls.STATUS_CONSIDER,
                last_update_time=crt_time,
                updated_total_comment=total_comment,
            )
            o_music.save()
        except Exception as err:
            deprint(str(err))
            return Ret(Error.ERROR_CREATE_MUSIC)

        return Ret(o_music)
Esempio n. 8
0
 def get_msg_by_id(cls, msg_id):
     try:
         o_msg = cls.objects.get(pk=msg_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_MESSAGE)
     return Ret(o_msg)
Esempio n. 9
0
 def get_dr_by_date(cls, date_):
     try:
         o_dr = cls.objects.get(dat_e=date_)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_DAILYRECOMMEND)
     return Ret(o_dr)
Esempio n. 10
0
 def get_music_by_netease_id(cls, netease_id):
     try:
         o_music = cls.objects.get(netease_id=netease_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_MUSIC)
     return Ret(o_music)
Esempio n. 11
0
 def get_unique_port(cls):
     while True:
         port = random.randint(60000, 65500)
         ret = cls.get_user_by_port(port)
         if ret.error == Error.NOT_FOUND_USER:
             return port
         deprint('generate port: %s, conflict.' % port)
Esempio n. 12
0
 def get_unique_str_id(cls):
     while True:
         str_id = get_random_string(length=cls.L['str_id'])
         ret = cls.get_user_by_str_id(str_id)
         if ret.error == Error.NOT_FOUND_USER:
             return str_id
         deprint('generate res_str_id: %s, conflict.' % str_id)
Esempio n. 13
0
def field_validator(dict_, cls, allow_none=False):
    """
    针对model的验证函数
    事先需要FIELD_LIST存放需要验证的属性
    需要L字典存放CharField类型字段的最大长度
    可选MIN_L字典存放CharField字段最小长度
    可选创建_valid_<param>函数进行自校验
    """
    field_list = getattr(cls, 'FIELD_LIST', None)
    if field_list is None:
        return Ret(Error.ERROR_VALIDATION_FUNC, append_msg=',不存在FIELD_LIST')
    _meta = getattr(cls, '_meta', None)
    if _meta is None:
        return Ret(Error.ERROR_VALIDATION_FUNC, append_msg=',不是Django的models类')
    len_list = getattr(cls, 'L', None)
    if len_list is None:
        return Ret(Error.ERROR_VALIDATION_FUNC, append_msg=',不存在长度字典L')
    min_len_list = getattr(cls, 'MIN_L', None)

    for k in dict_.keys():
        if k in getattr(cls, 'FIELD_LIST'):
            if allow_none and dict_[k] is None:
                continue
            if isinstance(_meta.get_field(k), models.CharField):
                try:
                    if len(dict_[k]) > len_list[k]:
                        return Ret(Error.ERROR_PARAM_FORMAT,
                                   append_msg=',%s的长度不应超过%s个字符' %
                                   (k, len_list[k]))
                    if min_len_list and k in min_len_list and len(
                            dict_[k]) < min_len_list[k]:
                        return Ret(Error.ERROR_PARAM_FORMAT,
                                   append_msg=',%s的长度不应少于%s个字符' %
                                   (k, min_len_list[k]))
                except TypeError as err:
                    deprint(str(err))
                    return Ret(Error.ERROR_PARAM_FORMAT,
                               append_msg=",%s不是字符串" % k)

        tuple_name = '%s_TUPLE' % k.upper()
        tuple_ = getattr(cls, tuple_name, None)
        if tuple_ is not None and isinstance(tuple_, tuple):
            flag = False
            for item in tuple_:
                if not isinstance(item, tuple):
                    return Ret(Error.ERROR_TUPLE_FORMAT,
                               append_msg='(%s)' % tuple_name)
                if dict_[k] == item[0]:
                    flag = True
            if not flag:
                return Ret(Error.ERROR_PARAM_FORMAT,
                           append_msg=',%s的值应该在%s之中' % (k, tuple_name))
        valid_func = getattr(cls, '_valid_%s' % k, None)
        if valid_func is not None and callable(valid_func):
            # print('_valid_', k)
            ret = valid_func(dict_[k])
            if ret.error is not Error.OK:
                return ret
    return Ret()
Esempio n. 14
0
 def get_user_by_qt_user_app_id(qt_user_app_id):
     """根据齐天用户-应用ID获取用户对象"""
     try:
         o_user = User.objects.get(qt_user_app_id=qt_user_app_id)
     except User.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Esempio n. 15
0
 def get_user_by_port(cls, port):
     """根据用户分配的port获取用户对象"""
     try:
         o_user = cls.objects.get(port=port)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Esempio n. 16
0
 def get_user_by_id(cls, user_id):
     """根据用户ID获取用户对象"""
     try:
         o_user = cls.objects.get(pk=user_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Esempio n. 17
0
 def wrapper(request, *args, **kwargs):
     """wrapper"""
     if request.body:
         try:
             request.DICT = json.loads(request.body.decode())
         except json.JSONDecodeError as err:
             deprint(str(err))
         return func(request, *args, **kwargs)
     return error_response(Error.REQUIRE_JSON)
Esempio n. 18
0
 def remove_port(cls, port):
     # deprint('remove port debug')
     # return
     data = {
         'server_port': port,
     }
     data_str = json.dumps(data)
     deprint(data_str)
     cls._send('remove: %s' % data_str)
Esempio n. 19
0
    def get_comment(cls, netease_id):
        comment_url = cls.COMMENT_URL % netease_id

        try:
            data = abstract_grab(comment_url)
            total_comment = json.loads(data)['total']
        except Exception as err:
            deprint(str(err))
            return Ret(Error.ERROR_GRAB_MUSIC, append_msg=',评论获取错误')
        return Ret(total_comment)
Esempio n. 20
0
def auth_callback(request):
    code = request.d.code
    deprint('CODE -- ', code)
    access_token = get_access_token(code)
    if access_token is None:
        return error_response(Error.ERROR_CODE)
    rtn = User.create(access_token)
    if rtn.error is not Error.OK:
        return error_response(rtn.error)
    return HttpResponseRedirect('/random')
Esempio n. 21
0
 def add_port(cls, port, password):
     # deprint('add port debug')
     # return
     data = {
         'server_port': port,
         'password': password,
     }
     data_str = json.dumps(data)
     deprint(data_str)
     cls._send('add: %s' % data_str)
Esempio n. 22
0
    def get_config_by_key(cls, key):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        try:
            o_config = cls.objects.get(key=key)
        except Exception as err:
            deprint(str(err))
            return Ret(Error.NOT_FOUND_CONFIG)
        return Ret(o_config)
Esempio n. 23
0
    def get_phrase_by_phrase(cls, phrase):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        try:
            o_phrase = cls.objects.get(phrase=phrase)
        except cls.DoesNotExist as err:
            deprint(str(err))
            return Ret(Error.NOT_FOUND_PHRASE)
        return Ret(o_phrase)
Esempio n. 24
0
def aes_encrypt(data):
    try:
        key = SECRET_KEY[:16]
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(key, AES.MODE_CFB, iv)
        encrypted_data = iv + cipher.encrypt(data)
        encrypted_data = base64.b64encode(encrypted_data).decode()
    except Exception as err:
        deprint(str(err))
        return Ret(Error.AES_ENCRYPT_ERROR)
    return Ret(encrypted_data)
Esempio n. 25
0
def error_response(e, append_msg=""):
    """
    回复一个错误
    171216 当error_id为Ret类时,自动转换
    """
    if isinstance(e, Ret):
        append_msg = e.append_msg
        e = e.error
    if not isinstance(e, E):
        deprint(str(e))
        return error_response(Error.STRANGE, append_msg='error_response error_id not E')
    return response(e=e, msg=e.msg + append_msg)
Esempio n. 26
0
def aes_decrypt(encrypted_data):
    try:
        encrypted_data = base64.b64decode(encrypted_data)
        key = SECRET_KEY[:16]
        iv = encrypted_data[:16]
        encrypted_data = encrypted_data[16:]
        cipher = AES.new(key, AES.MODE_CFB, iv)
        data = cipher.decrypt(encrypted_data).decode()
    except Exception as err:
        deprint(str(err))
        return Ret(Error.AES_DECRYPT_ERROR)
    return Ret(data)
Esempio n. 27
0
 def get_value_by_key(cls, key, default=__ConfigNone()):
     ret = cls._validate(locals())
     if ret.error is not Error.OK:
         return ret
     try:
         o_config = cls.objects.get(key=key)
     except Exception as err:
         deprint(str(err))
         if isinstance(default, cls.__ConfigNone):
             return Ret(Error.NOT_FOUND_CONFIG)
         else:
             return Ret(default)
     return Ret(o_config.value)
Esempio n. 28
0
    def create(cls, key):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        try:
            o_image = cls(
                key=key,
            )
            o_image.save()
        except Exception as err:
            deprint('Image-create', str(err))
            return Ret(Error.ERROR_CREATE_IMAGE, append_msg=str(err))
        return Ret(o_image)
Esempio n. 29
0
def error_response(error_id, append_msg=""):
    """
    回复一个错误
    171216 当error_id为Ret类时,自动转换
    """
    # deprint('error_id', error_id)
    if isinstance(error_id, Ret):
        append_msg = error_id.append_msg
        error_id = error_id.error
    for error in Error.ERROR_DICT:
        if error_id == error[0]:
            return response(code=error_id, msg=error[1] + append_msg)
    deprint('Error Not Found: ', error_id)
    return error_response(Error.ERROR_NOT_FOUND)
Esempio n. 30
0
def update_user_info(token):
    update_info_uri = '%s/api/user/' % QTB_HOST
    req = requests.get(update_info_uri, headers=dict(token=token, ), timeout=3)
    if req.status_code != requests.codes.ok:
        return Ret(Error.QTB_GET_INFO_FAIL)

    try:
        res = req.json()
    except Exception as err:
        deprint(str(err))
        return Ret(Error.QTB_GET_INFO_FAIL)

    if res['code'] != Error.OK.eid:
        return Ret(Error.QTB_GET_INFO_FAIL, append_msg=',%s' % res['msg'])

    return Ret(res['body'])