Exemplo n.º 1
0
 def post(self, request):
     # 4.获取前端传过来的参数
     try:
         json_data = request.body
         if not json_data:
             return json_response(errno=Code.PARAMERR, errmsg="参数为空,请重新输入!")
         dict_data = json.loads(json_data.decode('utf8'))
     except Exception as e:
         logger.info('错误信息:\n{}'.format(e))
         return json_response(errno=Code.UNKOWNERR, errmsg=error_map[Code.UNKOWNERR] + e)
     form = RegisterForm(dict_data)
     # 5.校验参数
     if form.is_valid():
         username = form.cleaned_data.get('username')
         password = form.cleaned_data.get('password')
         mobile = form.cleaned_data.get('mobile')
         # 6.将用户信息保存到数据库
         user = Users.objects.create_user(username=username, password=password, mobile=mobile)
         login(request, user)
         # 7.将结果返回前端
         return json_response(errmsg='恭喜你,注册成功!')
     else:
         # 定义一个错误信息列表
         err_msg_list = []
         for item in form.errors.values():
             err_msg_list.append(item[0])
         err_msg_str = '/'.join(err_msg_list)
         return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)
Exemplo n.º 2
0
    def post(self, request):
        image_file = request.FILES.get('image_file')
        if not image_file:
            logger.info("从前端获取图片失败")
            return json_response(errno=Code.NODATA, errmsg="长前端获取图片失败")
        if image_file.content_type not in ('images/jped', 'image/png',
                                           'image/gif'):
            return json_response(errno=Code.DATAERR, errmsg='不能上传非图片文件')
        try:
            image_ext_name = image_file.name.split('.')[-1]
        except Exception as e:
            logger.info('图片扩展名异常:{}'.format(e))
            image_ext_name = 'fpg'

        try:
            upload_res = FDFS_Client.upload_by_buffer(
                image_file.read(), file_ext_name=image_ext_name)
        except Exception as e:
            logger.error('图片上传出现异常,{}'.format(e))
        else:
            if upload_res.get('Status') != 'Upload successed':
                logger.info('图片上传到FastDFS服务器失败')
                return json_response(errno=Code.UNKOWNERR,
                                     errmsg='图片上传到FastDFS服务器失败')
            else:
                image_name = upload_res.get('Remote file_id')
                image_url = settings.FASTDFS_SERVER_DOMAIN + image_name
                return json_response(data={'image_url': image_url},
                                     errmsg="图片上传成功")
Exemplo n.º 3
0
 def delete(self, request, tag_id):
     tag = Tag.objects.only('id').filter(is_delete=False, id=tag_id).first()
     if tag:
         tag.is_delete = True
         tag.save(update_fields=['is_delete'])
         return json_response(errmsg="标签删除成功")
     else:
         return json_response(errno=Code.PARAMERR, errmsg="需要删除的标签不存在")
Exemplo n.º 4
0
 def delete(self, request, news_id):
     news = News.objects.only('id').filter(id=news_id).first()
     if news:
         news.is_delete = True
         # news.save()
         news.save(update_fields=['is_delete'])
         return json_response(errmsg="文章删除成功")
     else:
         return json_response(errno=Code.PARAMERR, errmsg="需要删除的文章不存在")
Exemplo n.º 5
0
 def post(self, request):
     json_data = request.body
     if not json_data:
         return json_response(errno=Code.PARAMERR,
                              errmsg=error_map[Code.PARAMERR])
     dict_data = json.loads(json_data.decode('utf8'))
     tag_name = dict_data.get('name')
     if tag_name:
         tag_name = tag_name.strip()
         tag_tuple = Tag.objects.get_or_create(name=tag_name)
         tag_instance, tag_created_bool = tag_tuple
         new_tag_dict = {"id": tag_instance.id, "name": tag_instance.name}
         return json_response(errmsg="标签添加成功", data=new_tag_dict) if tag_created_bool else\
             json_response(errno=Code.DATAEXIST, errmsg="标签名已存在")
     else:
         return json_response(errno=Code.PARAMERR, errmsg="标签名为空")
Exemplo n.º 6
0
 def post(self, request):
     # 2.接收参数
     try:
         json_data = request.body
         if not json_data:
             return json_response(errno=Code.PARAMERR, errmsg="参数为空,请重新输入!")
         dict_data = json.loads(json_data.decode('utf8'))
     except Exception as e:
         logger.info('错误信息:\n{}'.format(e))
         return json_response(errno=Code.UNKOWNERR, errmsg=error_map[Code.UNKOWNERR] + e)
     # 3.校验参数
     form = LoginForm(data=dict_data, request=request)
     if form.is_valid():
         return json_response(errmsg='恭喜登录成功!')
     else:
         err_msg_list = []
         for item in form.errors.values():
             err_msg_list.append(item[0])
         err_msg_str = '/'.join(err_msg_list)
         return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)
Exemplo n.º 7
0
 def put(self, request, tag_id):
     json_data = request.body
     if not json_data:
         return json_response(errno=Code.PARAMERR,
                              errmsg=error_map[Code.PARAMERR])
     dict_data = json.loads(json_data.decode('utf8'))
     tag_name = dict_data.get('name')
     tag = Tag.objects.only('id').filter(id=tag_id).first()
     if tag:
         if tag_name:
             tag_name = tag_name.strip()
             if not Tag.objects.only('id').filter(name=tag_name).exits():
                 tag.name = tag_name
                 tag.save(updata_fields=['name'])
                 return json_response(errmsg="标签更新成功")
             else:
                 return json_response(errno=Code.PARAMERR, errmsg="标签名已存在")
         else:
             return json_response(errno=Code.PARAMERR, errmsg="标签名不能为空")
     else:
         return json_response(errno=Code.PARAMERR, errmsg="需要更新的标签不存在")
Exemplo n.º 8
0
def check_mobile_view(request, mobile):
    """
    校验手机号是否存在
    url:/moblie/(?P<moblie>1[3-9]\d{9})/
    :param request:
    :param mobile:
    :return:
    """
    data = {
        'mobile': mobile,
        'count': Users.objects.filter(mobile=mobile).count()
    }
    return json_response(data=data)
Exemplo n.º 9
0
 def get(self, request):
     # 1.拿到所有文档
     docs = Doc.objects.values('file_url', 'file_name', 'title', 'desc',
                               'image_url').filter(is_delete=False)
     # 2.分页
     paginator = Paginator(docs, constants.PER_PAGE_DOC_COUNT)
     try:
         page = paginator.get_page(int(request.GET.get('page')))
     except Exception as e:
         logger.error('错误:\n{}'.format(e))
         page = paginator.get_page(1)
     data = {'total_page': paginator.num_pages, 'docs': list(page)}
     return json_response(data=data)
Exemplo n.º 10
0
    def post(self, request):
        json_data = request.body
        if not json_data:
            return json_response(errno=Code.PARAMERR,
                                 errmsg=error_map[Code.PARAMERR])
        dict_data = json.loads(json_data.decode('utf8'))

        form = NewsPubForm(data=dict_data)
        if form.is_valid():
            # n = News(**form.cleaned_data)
            # n.title = form.cleaned_data.get('title')
            # 整个表单保存
            # 等插入用户信息再提交
            news_instance = form.save(commit=False)
            news_instance.author_id = request.user.id
            news_instance.save()
            return json_response(errmsg="文章创建成功!")
        else:
            # 定义一个错误信息列表
            err_msg_list = []
            for item in form.errors.values():
                err_msg_list.append(item[0])
            err_msg_str = '/'.join(err_msg_list)
            return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)
Exemplo n.º 11
0
 def get(self, request, username):
     # 3.查询数据库是否有同名
     # user = Users.objects.filter(username=username)
     # 4.返回校验的结果
     # if user:
     #     return HttpResponse('可以注册')
     # else:
     #     return HttpResponse('不能注册')
     # 无则0 有则1
     count = Users.objects.filter(username=username).count()
     # try:
     #     count = Users.objects.get(username=username).count()
     # except ObjectDoesNotExist:
     #     return json_response(errno=Code.NODATA, errmsg=error_map[Code.NODATA])
     data = {'username': username, 'count': count}
     return json_response(data=data)
Exemplo n.º 12
0
 def handle_no_permission(self):
     return json_response(errno=Code.ROLEERR, errmsg="没有操作权限")
Exemplo n.º 13
0
 def handle_no_permission(self):
     if self.request.method.lower() != 'get':
         return json_response(errno=Code.ROLEERR, errmsg="没有操作权限")
     else:
         return super(TagManageView, self).handle_no_permission()
Exemplo n.º 14
0
    def post(self, request):
        # 2.获取前端参数
        json_data = request.body
        if not json_data:
            return json_response(errno=Code.PARAMERR, errmsg="参数为空,请重新输入")
        dict_data = json.loads(json_data.decode('utf8'))
        # 3.校验参数
        # mobile = dict_data.get('mobile')
        # text = dict_data.get('text')
        # image_code_id = dict_data.get('image_code_id')
        form = forms.CheckImagForm(dict_data, request=request)
        if form.is_valid():
            # 2.获取手机
            mobile = form.cleaned_data.get('mobile')
            # 3.生成手机验证码
            sms_code = ''.join([
                random.choice('0123456789')
                for _ in range(constants.SMS_CODE_LENGTH)
            ])
            # 4.发送手机验证码
            # ccp = CCP()
            # try:
            #     res = ccp.send_template_sms(mobile,
            #                                 [sms_code, constants.SMS_CODE_YUNTX_EXPIRES],
            #                                 constants.SMS_CODE_TEMP_ID)
            #     if res == 0:
            #         logger.info('发送短信验证码[正常][mobile: %s sms_code: %s]' % (mobile, sms_code))
            #     else:
            #         logger.error('发送短信验证码[失败][moblie: %s sms_code: %s]' % (mobile, sms_code))
            #         return json_response(errno=Code.SMSFAIL, errmsg=error_map[Code.SMSFAIL])
            # except Exception as e:
            #     logger.error('发送短信验证码[异常][mobile: %s message: %s]' % (mobile, e))
            #     return json_response(errno=Code.SMSERROR, errmsg=error_map[Code.SMSERROR])
            logger.info('发送短信验证码[正常][mobile: %s sms_code: %s]' %
                        (mobile, sms_code))

            # 5.保存到redis数据库
            # 创建短信验证码发送记录
            sms_flag_key = 'sms_flag_{}'.format(mobile).encode('utf8')
            # 创建短信验证码内容记录
            sms_text_key = 'sms_text_{}'.format(mobile).encode('utf8')
            redis_conn = get_redis_connection(alias='verify_codes')
            # 实例一个管道
            pl = redis_conn.pipeline()

            try:
                # 设置过期时间setex(key, seconds, value)
                pl.setex(sms_flag_key, constants.SMS_CODE_INTERVAL, 1)
                pl.setex(sms_text_key, constants.SMS_CODE_EXPIRES, sms_code)
                # 让管道通知redis执行命令
                pl.execute()
                return json_response(errmsg="短信验证码发送成功!")
            except Exception as e:
                logger.error('redis 执行异常:{}'.format(e))
                return json_response(errno=Code.UNKOWNERR,
                                     errmsg=error_map[Code.UNKOWNERR])

        else:
            # 将表单的报错信息进行拼接
            err_msg_list = []
            # 获取表单错误信息
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
                # print(item[0].get('message'))   # for test
            err_msg_str = '/'.join(err_msg_list)  # 拼接错误信息为一个字符串

            return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)