Skip to content

Commit

Permalink
更新用户关注取消关注功能
Browse files Browse the repository at this point in the history
  • Loading branch information
xishandong committed Jul 11, 2023
1 parent 574db20 commit 24e4cc3
Show file tree
Hide file tree
Showing 15 changed files with 118 additions and 40 deletions.
Binary file modified Server01/__pycache__/models.cpython-39.pyc
Binary file not shown.
17 changes: 17 additions & 0 deletions Server01/migrations/0011_remove_user_followed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.1 on 2023-07-11 08:21

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
("Server01", "0010_remove_post_images_alter_image_post"),
]

operations = [
migrations.RemoveField(
model_name="user",
name="followed",
),
]
Binary file not shown.
11 changes: 9 additions & 2 deletions Server01/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from django.db import models
from webServer.settings import SYSTEM_PATH
from Server01.util.auxiliaryFuction import check_and_delete


class User(models.Model):
Expand All @@ -9,14 +11,17 @@ class User(models.Model):
avatar = models.CharField(max_length=256, verbose_name='头像', null=False,
default='http://localhost:8000/static/img/avatar/defaultAvatar.jpg')
signature = models.CharField(max_length=64, verbose_name='个性签名', default='暂时没有个性签名~', null=True)
# 用户关注,related_name获取用户的粉丝
following = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='beFocusOn')
followed = models.ManyToManyField('self', symmetrical=False, blank=True, related_name='focusOn')
# 用户喜爱的帖子
favorites = models.ManyToManyField('Post', blank=True, related_name='favoritePosts')
# 用户收藏的帖子
collected = models.ManyToManyField('Post', blank=True, related_name='collectedPosts')


class Post(models.Model):
""" 帖子表 """
# 用户通过related_name获取ta发的帖子
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
title = models.CharField(max_length=64, verbose_name='标题', null=False)
content = models.TextField(max_length=3000, verbose_name='内容', null=True)
Expand All @@ -25,7 +30,9 @@ class Post(models.Model):
def delete(self, *args, **kwargs):
# 删除关联的帖子图片
self.imgs.all().delete()

# 删除帖子的图片的存储
path = SYSTEM_PATH + '/webServer/Server01/static/img/post/'
check_and_delete(path, self.id)
# 删除帖子本身
super().delete(*args, **kwargs)

Expand Down
Binary file added Server01/static/img/post/29-avatar.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified Server01/util/__pycache__/auxiliaryFuction.cpython-39.pyc
Binary file not shown.
38 changes: 38 additions & 0 deletions Server01/util/auxiliaryFuction.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
import os

import pytz

import Server01.models as models


# 更换时区
def convert_to_timezone(datetime_obj, timezone_str):
target_timezone = pytz.timezone(timezone_str)
converted_datetime = datetime_obj.astimezone(target_timezone)
return converted_datetime.strftime('%Y-%m-%d %H:%M')


# 检查邮箱
def check_email(email):
return models.User.objects.filter(email=email).exists()


# 整合主页帖子的信息
def combine_index_post(posts):
for post in posts:
imgs = post.imgs.all()
info = {
'title': post.title,
'id': post.id,
'img': imgs[0].imagePath,
'user': {
'id': post.user.id,
'username': post.user.username,
'avatar': post.user.avatar
}
}
yield info


# 检查和删除图片,用于删除帖子时删除文件,以及删除用户上一次上传的头像
def check_and_delete(id, mainPath):
# 获取目录下的文件
file_list = os.listdir(mainPath)
# 遍历文件列表,检查是否有对应的文件,如果有就删除
for file_name in file_list:
if file_name.startswith(f'{id}-'):
file_path = os.path.join(mainPath, file_name)
os.remove(file_path)
Binary file modified Server01/views/__pycache__/post.cpython-39.pyc
Binary file not shown.
Binary file modified Server01/views/__pycache__/user.cpython-39.pyc
Binary file not shown.
26 changes: 7 additions & 19 deletions Server01/views/post.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import json

from django.http import JsonResponse
from webServer.settings import TIME_ZONE
from webServer.settings import TIME_ZONE, SYSTEM_PATH
import Server01.models as models
from Server01.util.verifyJWT import authenticate_request
from Server01.util.auxiliaryFuction import convert_to_timezone
from Server01.util.auxiliaryFuction import convert_to_timezone, combine_index_post


system = 'D:/vue'


def upload_post(request):
file = request.FILES['file']
id = request.POST.get('id')
file_path = system + '/webServer/Server01/static/img/post/' + str(id) + '-' + file.name
file_path = SYSTEM_PATH + '/webServer/Server01/static/img/post/' + str(id) + '-' + file.name
with open(file_path, 'wb') as destination:
for chunk in file.chunks():
destination.write(chunk)
Expand All @@ -27,6 +27,7 @@ def upload_post(request):
return JsonResponse({'error': '错误的操作'}, status=401)


# 用户上传帖子
@authenticate_request
def upload_post_info(request, payload):
data = json.loads(request.body)
Expand All @@ -38,6 +39,7 @@ def upload_post_info(request, payload):
return JsonResponse({'data': 'success', 'info': post.id}, status=200)


# 获取帖子详情,整合信息
def get_post_detail(request):
data = json.loads(request.body)
id = data.get('id')
Expand Down Expand Up @@ -72,6 +74,7 @@ def get_post_detail(request):
return JsonResponse({'error': '错误的访问'}, status=401)


# 主页推送帖子
def query_post_index(request):
data = json.loads(request.body)
offset = data['offset']
Expand All @@ -87,18 +90,3 @@ def query_post_index(request):

return JsonResponse({'info': []}, status=200)


def combine_index_post(posts):
for post in posts:
imgs = post.imgs.all()
info = {
'title': post.title,
'id': post.id,
'img': imgs[0].imagePath,
'user': {
'id': post.user.id,
'username': post.user.username,
'avatar': post.user.avatar
}
}
yield info
57 changes: 39 additions & 18 deletions Server01/views/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from django.http import JsonResponse

import Server01.models as models
from Server01.util.verifyJWT import create_token
from Server01.util.auxiliaryFuction import check_email, combine_index_post
from Server01.util.verifyJWT import create_token, authenticate_request


# 用户登录
Expand Down Expand Up @@ -38,6 +39,7 @@ def register(request):
return JsonResponse({'error': '创建用户失败'}, status=401)


# 获取用户主页信息
def query_user_index(request):
data = json.loads(request.body)
if data.get('id'):
Expand All @@ -49,7 +51,7 @@ def query_user_index(request):
'avatar': user.avatar,
'signature': user.signature,
'fans': user.beFocusOn.count(),
'focusOn': user.focusOn.count(),
'focusOn': user.following.count(),
'postsCount': user.posts.count(),
}
info = {
Expand All @@ -63,21 +65,40 @@ def query_user_index(request):
return JsonResponse({'error': '非法访问'}, status=401)


def combine_index_post(posts):
for post in posts:
imgs = post.imgs.all()
info = {
'title': post.title,
'id': post.id,
'img': imgs[0].imagePath,
'user': {
'id': post.user.id,
'username': post.user.username,
'avatar': post.user.avatar
}
}
yield info
# 获取用户关注用户id
@authenticate_request
def get_user_focus(request, payload):
user_id = payload['user_id']
user = models.User.objects.filter(id=user_id).first()
following = user.following.all()
ids = [u.id for u in following]
return JsonResponse({'info': ids}, status=200)


# 用户关注
@authenticate_request
def focusOn(request, payload):
# 做关注操作的用户id
id1 = payload['user_id']
user1 = models.User.objects.filter(id=id1).first()
# 被关注的用户id
id2 = json.loads(request.body)['id']
user2 = models.User.objects.filter(id=id2).first()
if user1 and user2:
user1.following.add(user2)
return JsonResponse({'info': '成功关注'}, status=200)
return JsonResponse({'error': '非法的操作'}, status=401)


def check_email(email):
return models.User.objects.filter(email=email).exists()
@authenticate_request
def unfollow(request, payload):
# 取消关注操作的用户id
user_id = payload['user_id']
user = models.User.objects.filter(id=user_id).first()
# 被取消关注的用户id
unfollow_id = json.loads(request.body)['id']
unfollow_user = models.User.objects.filter(id=unfollow_id).first()
if user and unfollow_user:
user.following.remove(unfollow_user)
return JsonResponse({'info': '成功取消关注'}, status=200)
return JsonResponse({'error': '非法的操作'}, status=401)
Binary file modified webServer/__pycache__/settings.cpython-39.pyc
Binary file not shown.
Binary file modified webServer/__pycache__/urls.cpython-39.pyc
Binary file not shown.
3 changes: 2 additions & 1 deletion webServer/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@
# 启用 CSRF 保护
CSRF_COOKIE_HTTPONLY = True


# 配置保存文件路径
SYSTEM_PATH = 'D:/vue'



6 changes: 6 additions & 0 deletions webServer/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@

urlpatterns = [
path("admin/", admin.site.urls),
# 用户相关
path("login/", user.login),
path('register/', user.register),
path('index/', user.query_user_index),
path('focus/', user.focusOn),
path('user/focus/', user.get_user_focus),
path('user/unfollow/', user.unfollow),
# 帖子相关
path('upload/', post.upload_post),
path('upload/info/', post.upload_post_info),
path('post/detail/', post.get_post_detail),
path('post/', post.query_post_index),
# 评论相关
path('comment/', comment.do_comment)
]

0 comments on commit 24e4cc3

Please sign in to comment.