def process_exception(self, request, exception): '''异常处理''' if isinstance(exception, errors.LogicError): return render_json(error=exception) else: # TODO: 向开发者发送异常告警邮件 error_info = format_exception(*exc_info()) err_log.error(''.join(error_info)) # 输出错误日志 return render_json(error=errors.InternalError)
def get_code(request): if request.method == 'GET': # 获取查询参数 phonenum print(request.GET) phonenum = request.GET.get('phonenum', None) if phonenum is None: return render_json(201, '请求参数phonenum是必填项') sms.new_code(phonenum) return render_json(200, '获取验证码成功!') return render_json(100, '只允许GET请求')
def upload_avatar(request): # 上传用户头像 if request.method == 'POST': avatar_file: InMemoryUploadedFile = request.FILES.get( 'avatar') # 要求:前端上传头像的字段为avatar # 将上传的图片文件写入到临时文件中 filedir = os.path.join(settings.BASE_DIR, 'static/images') filename = uuid.uuid4().hex + os.path.splitext(avatar_file.name)[-1] with open(os.path.join(filedir, filename), 'wb') as f: for chunk in avatar_file.chunks(): f.write(chunk) return render_json(200, {'path': '/static/images/%s' % filename}) return render_json(300, '只允许POST请求')
def process_request(self, request): # 排除白名单里的路径 if self.is_ignored_path(request.path): return # 检查 uid 是否存在于 session 中 if 'uid' not in request.session: return render_json(error=errors.LoginRequired) # 为 request 动态添加 user 属性 uid = request.session['uid'] try: user = User.get(pk=uid) request.user = user except User.DoesNotExist: return render_json(error=errors.UserNotExist)
def process_response(self, request, response): '''对结果进行封装''' if isinstance(response, HttpResponse): return response elif isinstance(response, dict): return render_json(response) else: err_log.error('Unknow type of the result: %s' % response) return response
def update_avatar(request): if request.method == 'GET': filename = request.GET.get('filename') key = oss.upload_file(settings.BASE_DIR + filename) login_user = request.session['login_user'] login_user['avatar'] = oss.get_small_url(key) user = User.objects.get(pk=login_user.get('uid')) user.avatar = key user.save() # 更新头像的oss的key # 删除临时文件 os.remove(settings.BASE_DIR + filename) return render_json(200, {'url': login_user['avatar'], 'msg': '更新头像成功'}) return render_json(100, '只允许GET请求')
def user_info(request): uid = request.session['uid'] user = User.objects.get(pk=uid) return render_json(user.to_dict())