class ArticleSearch(APIView): res = BaseResponse() def post(self, request): # 先根据标签找出所有的文章,再使用模糊查询找出所有包含关键字的文章 article_list_obj = [] search_field = request.data['search'] if not search_field: return try: tag_obj = Tag.objects.filter(name=search_field).first() if not tag_obj: article_list = Article.objects.filter(title__contains=search_field) else: # 如果可以通过标签找到对应的文章 article_list = tag_obj.article_set.all() for article in article_list: article_obj = dict({"id": "", "title": "", "create_time": "", "user": "", "views": ""}) article_obj['id'] = article.id article_obj['title'] = article.title article_obj['user'] = article.user.username article_obj['create_time'] = article.create_time.strftime("%Y-%m-%d %H:%M:%S") article_obj['views'] = article.total_views article_list_obj.append(article_obj) self.res.data = article_list_obj except Exception as e: self.res.code = 201 self.res.data = str(e) return Response(self.res.dict)
class HotArticle(APIView): res = BaseResponse() md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ] ) def get(self, request): my_articles = Article.objects.all().order_by('-total_views') my_article_list = [] for article in my_articles: every_article = dict({ "id": "", "title": "", "create_time": "", "user": "", "views": "" }) every_article["id"] = article.pk every_article["title"] = article.title every_article["user"] = article.user.username every_article["views"] = article.total_views every_article["create_time"] = article.create_time.strftime("%Y-%m-%d %H:%M:%S") my_article_list.append(every_article) self.res.data = my_article_list return Response(self.res.dict)
class TimeFilter(APIView): res = BaseResponse() def time_stamp(self, article_time): article_time = time.mktime(article_time.timetuple()) article_time = int(article_time) return article_time def post(self, request): my_articles = Article.objects.all().order_by('-create_time') click_time = int(request.data.get('time') / 1000) article_list = [] timestamp = 86400 for article in my_articles: format_time = article.create_time.strftime("%Y-%m-%d %H:%M:%S") article.create_time = self.time_stamp(article.create_time) if click_time <= article.create_time <= click_time + timestamp: every_article = dict({"id": "", "title": "", "create_time": "", "user": "", "views": ""}) every_article['id'] = article.id every_article['title'] = article.title every_article['create_time'] = format_time every_article['user'] = article.user.username every_article['views'] = article.total_views article_list.append(every_article) self.res.data = article_list return Response(self.res.dict)
def get(self, request, *args, **kwargs): """ 查看购物车中所有的商品 :param request: :param args: :param kwargs: :return: """ ret = BaseResponse() try: key_match = settings.SHOPPING_CAR_KEY % (request.auth.user_id, "*") course_list = [] for key in self.conn.scan_iter(key_match, count=10): info = { "title": self.conn.hget(key, 'title').decode('utf-8'), "img": self.conn.hget(key, 'img').decode('utf-8'), "policy": json.loads(self.conn.hget(key, 'policy').decode('utf-8')), "default_policy": self.conn.hget(key, 'default_policy').decode('utf-8') } course_list.append(info) ret.data = course_list except Exception as e: ret.code = 1002 ret.error = "获取失败" return Response(ret.dict)
class CommentView(APIView): res = BaseResponse() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) def get(self, request): all_comment = [] comment_list = Comment.objects.order_by("-created_time")[:3] for comment in comment_list: every_commend = { "id": "", "text": "", "created_time": "", "article": "", "excerpt": "", "article_id": "" } excerpt = strip_tags(self.md.convert(comment.text))[:40] every_commend["id"] = comment.id every_commend["text"] = comment.text # every_commend["created_time"] = comment.created_time every_commend["article"] = comment.article.title every_commend["article_id"] = comment.article.id every_commend["excerpt"] = excerpt all_comment.append(every_commend) self.res.data = all_comment return Response(self.res.dict)
class Recommend(APIView): res = BaseResponse() md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ] ) def get(self, request): recommend = [] recommend_article = Article.objects.order_by('-total_views')[0:5] for article in recommend_article: every_recommend = { "id": "", "title": "", "user": "", "create_time": "", "total_views": "", "excerpt": "", } excerpt = strip_tags(self.md.convert(article.content))[:30] every_recommend["id"] = article.pk every_recommend["title"] = article.title every_recommend["user"] = article.user.username every_recommend["create_time"] = article.create_time.strftime("%Y-%m-%d %H:%M:%S") every_recommend["total_views"] = article.total_views every_recommend["excerpt"] = excerpt recommend.append(every_recommend) self.res.data = recommend return Response(self.res.dict)
class RegView(APIView): res = BaseResponse() def post(self, request): try: reg_username = request.data.get("reg_username") reg_password = request.data.get("reg_password") reg_email = request.data.get("reg_email") user = UserInfo.objects.filter(username=reg_username) if user: self.res.code = 201 return Response(self.res.dict) user = UserInfo.objects.create_user(username=reg_username, password=reg_password, email=reg_email) user.pwd = reg_password user.save() if user: self.res.code = 200 else: self.res.code = 202 except Exception as e: self.res.code = 203 self.res.msg = str(e) return Response(self.res.dict)
class LoginView(APIView): res = BaseResponse() def post(self, request): try: username = request.data.get("username") password = request.data.get("password") user = UserInfo.objects.filter(username=username).first() if not user: self.res.code = 201 self.res.msg = "用户不存在" else: user_obj = auth.authenticate(username=username, password=password) if user_obj: self.res.code = 200 self.res.data["username"] = username self.res.data["user_id"] = user.pk else: self.res.code = 202 self.res.msg = "用户名或密码错误" except Exception as e: self.res.msg = str(e) return Response(self.res.dict)
class NewPublish(APIView): res = BaseResponse() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) def get(self, request): new_publish_article_list = [] new_publish_article = Article.objects.order_by("-create_time")[:4] for article in new_publish_article: every_article = { "id": "", "title": "", "create_time": "", "excerpt": "", "user": "" } excerpt = strip_tags(self.md.convert(article.content))[:90] every_article["id"] = article.id every_article["title"] = article.title every_article["create_time"] = article.create_time.strftime( "%Y-%m-%d %H:%M:%S") every_article["user"] = article.user.username every_article["excerpt"] = excerpt new_publish_article_list.append(every_article) self.res.data = new_publish_article_list return Response(self.res.dict)
class ArticleUpdate(APIView): res = BaseResponse() md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ] ) def post(self, request): list1 = [] tags = request.data["tag"] tag_list = tags.strip("").split(",") # 前端传过来的标签列表 for tag in tag_list: article = Tag.objects.filter(name=tag).first() if not article: Tag.objects.create(name=tag) else: continue for j in tag_list: tag = Tag.objects.filter(name=j).first() list1.append(tag) article_id = request.data['id'] title = request.data['title'] markdown_content = request.data['markdown'] article = Article.objects.filter(id=article_id).first() article.title = title article.content = markdown_content article.tags.set(list1) article.save() return Response(self.res.dict)
class TagArticle(APIView): res = BaseResponse() def post(self, request): articles = [] tag_id = request.data.get('id') article_list = Article.objects.filter(tags__id=tag_id) for article in article_list: every_article = dict({ "id": "", "title": "", "create_time": "", "user": "", "views": "" }) every_article["id"] = article.pk every_article["title"] = article.title every_article["user"] = article.user.username every_article["views"] = article.total_views every_article["create_time"] = article.create_time.strftime( "%Y-%m-%d %H:%M:%S") articles.append(every_article) self.res.data = articles return Response(self.res.dict)
def post(self, request, *args, **kwargs): """ 将课程添加到购物车 :param request: :param args: :param kwargs: :return: """ ret = BaseResponse() try: # 1. 获取用户提交的课程ID和价格策略ID course_id = int(request.data.get('courseid')) policy_id = int(request.data.get('policyid')) # 2. 获取专题课信息 course = models.Course.objects.get(id=course_id) # 3. 获取该课程相关的所有价格策略 price_policy_list = course.price_policy.all() price_policy_dict = {} for item in price_policy_list: price_policy_dict[item.id] = { "period": item.valid_period, "period_display": item.get_valid_period_display(), "price": item.price, } # 4. 判断用户提交的价格策略是否合法 if policy_id not in price_policy_dict: # 价格策略不合法 raise PricePolicyInvalid('价格策略不合法') # 5. 将购物信息添加到redis中 # self.conn # car_key = "luffy_shopping_car_%s_%s" car_key = settings.SHOPPING_CAR_KEY % ( request.auth.user_id, course_id, ) car_dict = { 'title': course.name, 'img': course.course_img, 'default_policy': policy_id, 'policy': json.dumps(price_policy_dict) } # conn = get_redis_connection("default") self.conn.hmset(car_key, car_dict) ret.data = '添加成功' except PricePolicyInvalid as e: ret.code = 2001 ret.error = e.msg except ObjectDoesNotExist as e: ret.code = 2001 ret.error = '课程不存在' except Exception as e: ret.code = 1001 ret.error = '获取购物车失败' return Response(ret.dict)
class UserDelete(APIView): res = BaseResponse() def post(self, request): user_id = request.data.get('id') UserInfo.objects.filter(id=user_id).delete() return Response(self.res.dict)
def get(self, request, *args, **kwargs): ret = BaseResponse() try: course_detail_list = models.CourseDetail.objects.all() p = PageNumberPagination() page_list = p.paginate_queryset(course_detail_list, request, self) obj = appo1serializer.CourseDetail(course_detail_list, many=True) ret.data = obj.data except Exception as e: ret.code = 1 ret.error = '获取数据失败' return Response(ret.dict)
class AddComment(APIView): res = BaseResponse() def post(self, request): article_id = request.data.get('article_id') user_id = request.data.get('user_id') comment = request.data.get('comment') comment_obj = Comment.objects.create(article_id=article_id, user_id=user_id, text=comment) if comment_obj: return Response(self.res.dict) self.res.msg = "评论失败" return Response(self.res.dict)
class HotTags(APIView): res = BaseResponse() def get(self, request): tag_list = [] tags = Tag.objects.all()[:9] for tag in tags: every_tag = {"id": "", "title": ""} every_tag["id"] = tag.id every_tag["title"] = tag.name tag_list.append(every_tag) self.res.data = tag_list return Response(self.res.dict)
class ChangeEmail(APIView): res = BaseResponse() def post(self, request): print(request.data) user_id = request.data.get('id') change_email = request.data.get('change_email') user = UserInfo.objects.filter(id=user_id).update(email=change_email) if user: pass else: self.res.code = 201 self.res.msg = "邮箱修改失败" return Response(self.res.dict)
class ChangeUser(APIView): res = BaseResponse() def post(self, request): user_id = request.data.get("id") change_username = request.data.get("change_username") user = UserInfo.objects.filter(id=user_id).update(username=change_username) if user: pass else: self.res.code = 201 self.res.msg = "用户名修改失败" return Response(self.res.dict)
class ChangePassword(APIView): res = BaseResponse() def post(self, request): user_id = request.data.get("id") old_password = request.data.get("data").get("old_password") change_password = request.data.get("data").get("change_password") user = UserInfo.objects.filter(id=user_id).first() if user.check_password(old_password): user.set_password(change_password) user.save() else: self.res.code = 201 self.res.msg = "输入的原密码不正确" return Response(self.res.dict)
class TodayRecommend(APIView): res = BaseResponse() md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) def get(self, request): recommend = [] today_recommend = Article.objects.all().order_by('-total_views')[0:4] for article in today_recommend: every_recommend = {"id": "", "title": "", "excerpt": ""} excerpt = strip_tags(self.md.convert(article.content))[:30] every_recommend["id"] = article.pk every_recommend["title"] = article.title every_recommend["excerpt"] = excerpt recommend.append(every_recommend) self.res.data = recommend return Response(self.res.dict)
def get(self, request, *args, **kwargs): """ 结算中心展示页面(用户访问) :param request: :param args: :param kwargs: :return: """ ret = BaseResponse() try: # luffy_payment_1_* redis_payment_key = settings.PAYMENT_KEY % (request.auth.user_id, "*",) # luffy_payment_coupon_1 redis_global_coupon_key = settings.PAYMENT_COUPON_KEY % (request.auth.user_id,) # 1. 获取绑定课程信息 course_list = [] for key in self.conn.scan_iter(redis_payment_key): info = {} data = self.conn.hgetall(key) for k, v in data.items(): kk = k.decode('utf-8') if kk == "coupon": info[kk] = json.loads(v.decode('utf-8')) else: info[kk] = v.decode('utf-8') course_list.append(info) # 2.全站优惠券 global_coupon_dict = { 'coupon': json.loads(self.conn.hget(redis_global_coupon_key, 'coupon').decode('utf-8')), 'default_coupon': self.conn.hget(redis_global_coupon_key, 'default_coupon').decode('utf-8') } ret.data = { "course_list": course_list, "global_coupon_dict": global_coupon_dict } except Exception as e: ret.code = 1001 ret.error = "获取失败" return Response(ret.dict)
def patch(self, request, *args, **kwargs): """ 修改课程的价格策略 :param request: :param args: :param kwargs: :return: """ ret = BaseResponse() try: # 1. 获取价格策略ID和课程ID course_id = int(request.data.get('courseid')) policy_id = str(request.data.get('policyid')) # 2. 拼接课程的key key = settings.SHOPPING_CAR_KEY % ( request.auth.user_id, course_id, ) if not self.conn.exists(key): ret.code = 1002 ret.error = "购物车中不存在此课程" return Response(ret.dict) # 3. redis中获取所有的价格策略 policy_dict = json.loads( str(self.conn.hget(key, 'policy'), encoding='utf-8')) if policy_id not in policy_dict: ret.code = 1003 ret.error = "价格策略不合法" return Response(ret.dict) # 4. 在购物车中修改该课程的默认价格策略 self.conn.hset(key, 'default_policy', policy_id) ret.data = "修改成功" except Exception as e: ret.code = 1004 ret.error = "修改失败" return Response(ret.dict)
class ArticleAdd(APIView): res = BaseResponse() md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ] ) def post(self, request): user_id = request.data.get("user_id") title = request.data.get('title') tag = request.data.get('tag') context = request.data.get('context') if ',' in tag: tag_list = [tag for tag in tag.split(',') if tag != ''] else: tag_list = list(tag) try: # 先添加文章 article_obj = Article.objects.create( title=title, content=context, user_id=user_id, ) query_list = [] for i in tag_list: query_list.append(Tag(name=i)) Tag.objects.bulk_create(query_list) # 批量添加标签对象 # 多对多添加标签??????????????????? li = [] for q in tag_list: q_obj = Tag.objects.filter(name=q).first() li.append(q_obj.id) article_obj.tags.add(*li) # 通过id添加每个标签 return Response(self.res.dict) except Exception as e: self.res.data = str(e) return Response(self.res.dict)
class ArticleDetail(APIView): res = BaseResponse() def get(self, request, id): article = Article.objects.filter(id=id).first() article.total_views += 1 article.save() md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ] ) tag = "" data = { "id": "", "title": "", "content": "", "create_time": "", "modify_time": "", "user": "", "tag": "", "total_views": "" } tag_query = article.tags.all().values("name") for t in tag_query: tag += "," tag += t["name"] tag = tag.strip(",") data["id"] = article.id data["title"] = article.title data["content"] = md.convert(article.content) data["create_time"] = article.create_time data["modify_time"] = article.modify_time data["user"] = article.user.username data['tag'] = tag data["total_views"] = article.total_views self.res.data = data return Response(self.res.dict)
class UserEdit(APIView): res = BaseResponse() def post(self, request): user_id = request.data.get('id') username = request.data.get('username') password = request.data.get('password') email = request.data.get('email') user = UserInfo.objects.filter(id=user_id).update(username=username, email=email, pwd=password) if user: user_obj = UserInfo.objects.filter(id=user_id).first() user_obj.set_password(password) user_obj.save() self.res.msg = "修改成功" else: self.res.code = 201 self.res.msg = "修改失败" return Response(self.res.dict)
class ArticleComment(APIView): res = BaseResponse() def post(self, request, id): article = Article.objects.get(id=id) comment_list = article.comment.all() response = [] for comment in comment_list: if comment: every_comment = dict({ 'comment_id': comment.id, 'created_time': (comment.created_time + datetime.timedelta(hours=8) ).strftime("%Y-%m-%d %H:%M:%S"), 'username': comment.user.username, 'text': comment.text, }) response.append(every_comment) self.res.data = response return Response(self.res.dict)
def delete(self, request, *args, **kwargs): """ 购物车中删除课程 :param request: :param args: :param kwargs: :return: """ ret = BaseResponse() try: course_id_list = request.data.get('courseids') key_list = [ settings.SHOPPING_CAR_KEY % ( request.auth.user_id, course_id, ) for course_id in course_id_list ] self.conn.delete(*key_list) except Exception as e: ret.code = 1002 ret.error = "删除失败" return Response(ret.dict)
class UserManage(APIView): res = BaseResponse() def get(self, request): user_list = [] users = UserInfo.objects.all() for user in users: if user.username == 'root': pass else: user_obj = dict({ 'id': '', 'username': '', 'password': '', 'email': '' }) user_obj['id'] = user.id user_obj['username'] = user.username user_obj['password'] = user.pwd user_obj['email'] = user.email user_list.append(user_obj) self.res.data = user_list return Response(self.res.dict)
def post(self, request, *args, **kwargs): """ 用户认证 :param request: 请求相关的数据 :param args: URL传参 :param kwargs: URL关键字传参 :return: """ # 实例化一个减少字典使用的类 ret = BaseResponse() try: user = request.data.get('user') pwd = request.data.get('pwd') user = Account.objects.filter(username=user, password=pwd).first() if not user: ret.code = 1001 ret.error = '用户名或密码错误' return Response(ret) uid = str(uuid.uuid4()) UserAuthToken.objects.update_or_create(user=user, defaults={'token': uid}) ret.data = uid except Exception as e: ret.code = 1003 return Response(ret.dict)
class ArticleDelete(APIView): res = BaseResponse() def post(self, request, id): Article.objects.filter(id=id).delete() return Response(self.res.dict)