from pyspark.sql import SparkSessionfrom django.http import JsonResponsefrom .models import Article, Comment, User, Tagimport jsondef get_hot_articles_view(request): spark = SparkSession.builder.appName("BlogHotAnalysis").getOrCreate() article_data = [(a.id, a.title, a.view_count, a.comment_set.count()) for a in Article.objects.all()] columns = ["id", "title", "views", "comments"] df = spark.createDataFrame(article_data, columns) df.createOrReplaceTempView("articles") hot_df = spark.sql("SELECT id, title, views, comments, (views * 0.7 + comments * 0.3) as hot_score FROM articles ORDER BY hot_score DESC LIMIT 10") hot_articles = hot_df.collect() spark.stop() result = [{"id": row.id, "title": row.title, "hot_score": row.hot_score} for row in hot_articles] return JsonResponse({"status": "success", "data": result})def publish_article_view(request): if request.method == 'POST' and request.user.is_authenticated: data = json.loads(request.body) title = data.get('title', '').strip() content = data.get('content', '').strip() tag_names = data.get('tags', []) if not title or not content: return JsonResponse({"status": "error", "message": "标题和内容不能为空"}) article = Article.objects.create(title=title, content=content, author=request.user) for tag_name in tag_names: tag, created = Tag.objects.get_or_create(name=tag_name.strip()) article.tags.add(tag) article.save() return JsonResponse({"status": "success", "message": "文章发布成功", "article_id": article.id}) return JsonResponse({"status": "error", "message": "请求无效或用户未登录"})def add_comment_view(request): if request.method == 'POST' and request.user.is_authenticated: data = json.loads(request.body) article_id = data.get('article_id') content = data.get('content', '').strip() try: article = Article.objects.get(id=article_id) except Article.DoesNotExist: return JsonResponse({"status": "error", "message": "文章不存在"}) if not content: return JsonResponse({"status": "error", "message": "评论内容不能为空"}) comment = Comment.objects.create(article=article, content=content, user=request.user) article.comment_count += 1 article.save() return JsonResponse({"status": "success", "message": "评论成功", "comment_id": comment.id, "user": request.user.username, "content": content, "created_time": comment.created_time.strftime("%Y-%m-%d %H:%M:%S")}) return JsonResponse({"status": "error", "message": "请求无效或用户未登录"})