def update_password(request): token = get_token_data(request) username = token['username'] post_data = json.loads(request.body.decode('utf-8')) new_password = post_data['password'] old_password = post_data['oldPassword'] try: validate_password(new_password) except ValidationError as e: return JsonResponse({'status': 'fail', 'message': str(e)}, status=500) # check old password and get user object u = authenticate(username=username, password=old_password) if u is not None: u.set_password(new_password) try: u.save() except: return JsonResponse( { 'status': 'fail', 'message': 'There was an error while updating the password' }, status=500) return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'fail'}, status=401)
def comment(request): if request.method == 'POST': post_data = json.loads(request.body.decode('utf-8')) video_id = post_data['id'] body = post_data['body'] try: username = post_data['username'] except KeyError: token = get_token_data(request) username = token['username'] # 获取视频模型对象 m, created = VideoItem.objects.get_or_create(pk=video_id, defaults={'title': ''}) # comment c = Comment(video=m, username=username, body=body) try: c.save() except: return JsonResponse( { 'status': 'fail', 'data': { 'message': 'Error while saving comment' } }, status=500) return JsonResponse({'status': 'success', 'data': {'id': c.id}}) elif request.method == 'DELETE': id = request.GET.get('id', '') username = request.GET.get('u', '') try: c = Comment.objects.get(id=id, username=username) except Comment.DoesNotExist: return JsonResponse( { 'status': 'fail', 'data': { 'message': 'This comment does not exist' } }, status=500) try: c.delete() except: return JsonResponse( { 'status': 'fail', 'data': { 'message': 'Error while deleting comment' } }, status=500) return JsonResponse({'status': 'success'})
def update_data(request): ''' 更新用户信息, 根据用户登录时的token进行更新 :param request: :return: ''' if request.method != 'POST': return JsonResponse({'status': 'fail', 'message': '本接口只支持post'}) token = get_token_data(request) username = token['username'] u = UserProfile.objects.get(username=username) if username is None or len(username) == 0 or u is None: return JsonResponse({'status': 'fail', 'message': '没有权限,用户未登录'}) new_email = request.POST.get('email') new_nickname = request.POST.get('nickname') new_gender = request.POST.get('gender') new_birday = request.POST.get('birday') new_address = request.POST.get('address') new_summary = request.POST.get('summary') new_avatar = u.avatar new_cover = u.cover if 'avatar' in request.FILES: new_avatar = request.FILES.get('avatar', None) if 'cover' in request.FILES: new_cover = request.FILES.get('cover', None) try: if new_email is not None: validate_email(new_email) except ValidationError as e: return JsonResponse({'status': 'fail', 'message': str(e)}, status=500) if new_email is not None: # email is not none u.email = new_email u.nickname = new_nickname u.gender = new_gender u.address = new_address u.cover = new_cover u.avatar = new_avatar u.birday = new_birday u.summary = new_summary try: u.save() except Exception as e: return JsonResponse({'status': 'fail', 'message': str(e)}, status=500) token = create_login_token({'username': u.username, 'email': u.email}) res = JsonResponse({ 'status': 'success', 'user': u.to_dict(), }) res.set_cookie('token', value=token['token'], expires=token['exp']) return res
def get_user_data(request): token = get_token_data(request) username = token['username'] try: u = UserProfile.objects.get(username=username).values( 'username', 'email') except UserProfile.DoesNotExist: return JsonResponse( { 'status': 'fail', 'message': 'The username does not exist' }, status=500) return JsonResponse({'status': 'success', 'data': u})
def delete_account(request): if request.method != 'DELETE': pass token = get_token_data(request) username = token['username'] u = UserProfile.objects.get(username=username) try: u.delete() except: return JsonResponse( { 'status': 'fail', 'message': 'There was an error while deleting user account' }, status=500) # need to delete jwt cookie on client side return JsonResponse({'status': 'success'})
def new_video(request): # 上传文件必须是post请求 if request.method != 'POST': return JsonResponse({ 'status': 'fail', 'message': '上傳視頻必須使用POST', }) token = get_token_data(request) username = token['username'] try: u = UserProfile.objects.get( username=username) #.values('username', 'email') except UserProfile.DoesNotExist: return JsonResponse({ 'status': 'fail', 'message': '用戶名不存在', }, status=500) user_id = u.pk # 用户必须登录 if user_id == None: return JsonResponse({'status': 'fail', 'message': '上傳視頻,用戶必須登錄'}) # 动图的类型 # animted_type = request.POST.get('animted_type', 'gif') # 获取视频数据 title = request.POST.get('title', '') describe = request.POST.get('describe', '') # save video = request.FILES.get('video', None) if len(video.name) > 20: # 解决上传的文件名太长问题 nameExtension = os.path.splitext(video.name)[1] try: import md5 hash = md5.new(video.name).hexdigest() except ImportError as e: from hashlib import md5 hash = md5(video.name.encode()).hexdigest() # startswith中拥有多个参数必须是元组形式,只需满足一个条件,返回True if nameExtension.startswith((".", )): file_name = hash + nameExtension else: file_name = hash + '.' + nameExtension video.name = file_name if video: m = VideoItem(title=title, describe=describe, video=video, user_id=user_id) try: m.save() except Exception as e: return JsonResponse( { 'status': 'fail', 'message': str(e) if type(e) == ValueError else '保存視頻出錯' }, status=500) # 重新查詢一遍視頻,返回給客戶端 return getVideoDetailByVideoId(m.pk) return JsonResponse({'status': 'fail', 'message': "未知錯誤"})
def rate(request): # if POST, save or update rating if request.method == 'POST': body = json.loads(request.body.decode('utf-8')) video_id = body['id'] rating = int(body['rating']) try: username = body['username'] except KeyError: token = get_token_data(request) username = token['username'] # get the video object with id video_id, or create it m, created = VideoItem.objects.get_or_create(pk=video_id, defaults={'title': ''}) # save or update rating try: r, created = Rating.objects.update_or_create( username=username, video=m, defaults={'rating': rating}) except Exception as e: print(e) return JsonResponse( { 'status': 'fail', 'data': { 'message': 'Error while saving rating' } }, status=500) return JsonResponse({ 'status': 'success', 'data': { 'title': m.title, 'rating': r.rating, 'is_new': created } }) elif request.method == 'DELETE': username = request.GET.get('u', '') video_id = request.GET.get('m_id', '') # find movie object m = VideoItem.objects.filter(pk=video_id).first() r = Rating.objects.filter(video=m, username=username) # delete rating try: r.delete() except: return JsonResponse( { 'status': 'fail', 'data': { 'message': 'Error while deleting rating' } }, status=500) return JsonResponse({'status': 'success'})
def new_video(request): # 上传文件必须是post请求 if request.method != 'POST': return JsonResponse({ 'status': 'fail', 'message': '上傳視頻必須使用POST', }) token = get_token_data(request) username = token['username'] try: u = UserProfile.objects.get(username=username)#.values('username', 'email') except UserProfile.DoesNotExist: return JsonResponse({ 'status': 'fail', 'message': '用戶名不存在', }, status=500) user_id = u.pk # 用户必须登录 if user_id == None: return JsonResponse({ 'status': 'fail', 'message': '上傳視頻,用戶必須登錄' }) # 动图的类型 # animted_type = request.POST.get('animted_type', 'gif') # 获取视频数据 title = request.POST.get('title', '') describe = request.POST.get('describe', '') # 播放封面的时间戳, coverDuration = request.POST.get('coverDuration', 5) # 封面起始的时间戳 coverStartTime = request.POST.get('coverStartTime', 0) # save video = request.FILES.get('video', None) if len(video.name) > 20: # 解决上传的文件名太长问题 nameExtension = os.path.splitext(video.name)[1] try: import md5 hash = md5.new(video.name).hexdigest() except ImportError as e: from hashlib import md5 hash = md5(video.name.encode()).hexdigest() # startswith中拥有多个参数必须是元组形式,只需满足一个条件,返回True if nameExtension.startswith((".",)): file_name = hash + nameExtension else: file_name = hash + '.' + nameExtension video.name = file_name if video: # 经度 longitude = request.POST.get('longitude') # 纬度 latitude = request.POST.get('latitude') name = request.POST.get('poi_name') address = request.POST.get('poi_address') # 根据地址经纬度查询poi,如果没有这个poi就保存数据库 location = None if longitude and latitude and name and address: location = LocationItem.objects.filter(longitude=longitude, latitude=latitude, name=name, address=address).first() if not location: location = LocationItem(longitude=longitude, latitude=latitude, name=name, address=address) location.save() # 重新查询下,为了获取主键 location = LocationItem.objects.filter(longitude=longitude, latitude=latitude, name=name, address=address).first() if not location: # 没有有地址 m = VideoItem( title=title, describe=describe, video=video, user_id=user_id, cover_duration=coverDuration, cover_start_second=coverStartTime ) else: # 有地址 关联地址 m = VideoItem( title=title, describe=describe, video=video, user_id=user_id, location_id=location.pk, cover_duration=coverDuration, cover_start_second=coverStartTime ) try: m.save() except Exception as e: m.rollback_resource() return JsonResponse({ 'status': 'fail', 'message': str(e) if type(e) == ValueError else '保存視頻出錯' }, status=500) # 保存失败 清空视频 # 重新查詢一遍視頻,返回給客戶端 return getVideoDetailByVideoId(m.pk) return JsonResponse({ 'status': 'fail', 'message': "未知錯誤" })