基于 Vue + Django + MySQL 實現個人博客/CMS系統

目錄

1. 環境搭建與項目初始化

后端 (Django)

2. 數據庫模型設計

用戶認證模型 (Django Auth)

文章模型 (models.py)

全文索引優化

3. 后端API開發 (Django REST Framework)

用戶注冊/登錄

文章發布與搜索

4. 前端實現 (Vue 3)

項目初始化

核心功能實現

5. 訪問統計實現

后端中間件記錄PV/UV

6. 部署與優化

關鍵問題解決


1. 環境搭建與項目初始化

后端 (Django)

  1. 創建Django項目

    django-admin startproject blog_backend
    cd blog_backend
    python manage.py startapp blog
  2. 安裝依賴

    pip install django djangorestframework django-cors-headers djangorestframework-simplejwt mysqlclient
  3. 配置MySQL數據庫
    修改?settings.py

    DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'blog_db','USER': 'root','PASSWORD': 'your_password','HOST': 'localhost','PORT': '3306',}
    }
  4. 配置DRF和JWT
    修改?settings.py

INSTALLED_APPS = [# ...'rest_framework','corsheaders','blog',
]MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',# ...
]CORS_ALLOW_ALL_ORIGINS = True  # 開發階段允許所有跨域REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',)
}

    2. 數據庫模型設計

    用戶認證模型 (Django Auth)

    直接使用Django內置的?User?模型,無需額外設計。

    文章模型 (models.py)

    from django.db import models
    from django.contrib.auth.models import Userclass Article(models.Model):title = models.CharField(max_length=200)content = models.TextField()  # 存儲Markdown或HTML內容author = models.ForeignKey(User, on_delete=models.CASCADE)category = models.CharField(max_length=50)tags = models.CharField(max_length=100)  # 逗號分隔的標簽,如 "Python,Web"created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)def __str__(self):return self.titleclass Comment(models.Model):article = models.ForeignKey(Article, on_delete=models.CASCADE)user = models.ForeignKey(User, on_delete=models.CASCADE)content = models.TextField()parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)  # 樹形評論created_at = models.DateTimeField(auto_now_add=True)

    全文索引優化

    在MySQL中為?Article?表添加全文索引:

    ALTER TABLE blog_article ADD FULLTEXT(title, content);

    3. 后端API開發 (Django REST Framework)

    用戶注冊/登錄

    1. 序列化器 (serializers.py)

      from rest_framework import serializers
      from django.contrib.auth.models import Userclass UserSerializer(serializers.ModelSerializer):class Meta:model = Userfields = ('id', 'username', 'email', 'password')extra_kwargs = {'password': {'write_only': True}}def create(self, validated_data):user = User.objects.create_user(**validated_data)return user
    2. 視圖 (views.py)

      from rest_framework.views import APIView
      from rest_framework.response import Response
      from rest_framework_simplejwt.tokens import RefreshTokenclass RegisterView(APIView):def post(self, request):serializer = UserSerializer(data=request.data)if serializer.is_valid():user = serializer.save()refresh = RefreshToken.for_user(user)return Response({'refresh': str(refresh),'access': str(refresh.access_token),})return Response(serializer.errors, status=400)

    文章發布與搜索

    1. 文章序列化器

      class ArticleSerializer(serializers.ModelSerializer):class Meta:model = Articlefields = '__all__'
    2. 文章搜索接口
      使用Django ORM的全文搜索:

      class ArticleSearchView(APIView):def get(self, request):query = request.query_params.get('q', '')# MySQL全文搜索語法articles = Article.objects.raw("SELECT * FROM blog_article WHERE MATCH(title, content) AGAINST (%s)",[query])serializer = ArticleSerializer(articles, many=True)return Response(serializer.data)

    4. 前端實現 (Vue 3)

    項目初始化

    npm create vue@latest blog_frontend
    cd blog_frontend
    npm install axios vue-router vuex quill @vueuse/core

    核心功能實現

    1. Markdown渲染
      使用?marked?或?vue-markdown?庫:

      <template><div v-html="compiledMarkdown"></div>
      </template><script setup>
      import { marked } from 'marked'
      const compiledMarkdown = marked(props.content)
      </script>
    2. 富文本編輯器集成 (Quill)

      <template><div ref="editor"></div>
      </template><script setup>
      import Quill from 'quill'
      import 'quill/dist/quill.snow.css'const editor = ref(null)
      onMounted(() => {const quill = new Quill(editor.value, {theme: 'snow',modules: { toolbar: true }})
      })
      </script>
    3. 動態路由SEO優化
      使用?vue-router?和預渲染插件?prerender-spa-plugin

      // vue.config.js
      const PrerenderSPAPlugin = require('prerender-spa-plugin')module.exports = {configureWebpack: {plugins: [new PrerenderSPAPlugin({staticDir: path.join(__dirname, 'dist'),routes: ['/', '/articles', '/about'],  // 預渲染的路由})]}
      }

    5. 訪問統計實現

    后端中間件記錄PV/UV

    1. 創建訪問記錄模型

      class AccessLog(models.Model):ip = models.CharField(max_length=50)path = models.CharField(max_length=200)user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)created_at = models.DateTimeField(auto_now_add=True)
    2. 中間件統計訪問量

      class AccessLogMiddleware:def __init__(self, get_response):self.get_response = get_responsedef __call__(self, request):response = self.get_response(request)AccessLog.objects.create(ip=request.META.get('REMOTE_ADDR'),path=request.path,user=request.user if request.user.is_authenticated else None)return response

    6. 部署與優化

    1. MySQL全文索引查詢優化
      確保MySQL版本 >= 5.6,并配置索引:

      CREATE FULLTEXT INDEX ft_idx ON blog_article(title, content);
    2. Nginx配置反向代理

      server {listen 80;server_name your_domain.com;location /api {proxy_pass http://localhost:8000;proxy_set_header Host $host;}location / {root /path/to/vue/dist;try_files $uri $uri/ /index.html;}
      }
    3. 性能優化

      • 使用?django-debug-toolbar?分析查詢

      • Vue路由懶加載:

        const routes = [{ path: '/article/:id', component: () => import('./views/ArticleDetail.vue') }
        ]

    關鍵問題解決

    1. 跨域配置
      使用?django-cors-headers,確保前端能訪問后端API。

    2. 樹形評論渲染
      前端遞歸組件實現:

      <template><div v-for="comment in comments" :key="comment.id"><div>{{ comment.content }}</div><CommentTree v-if="comment.replies" :comments="comment.replies"/></div>
      </template>
    3. JWT Token自動刷新
      使用Axios攔截器:

      axios.interceptors.response.use(response => response, error => {if (error.response.status === 401) {return refreshToken().then(() => {return axios(error.config)})}return Promise.reject(error)
      })

    通過以上步驟,你可以逐步搭建一個功能完整的博客系統。建議先從基礎功能(如文章發布)開始,逐步迭代添加評論、搜索等模塊。

    本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
    如若轉載,請注明出處:http://www.pswp.cn/bicheng/75706.shtml
    繁體地址,請注明出處:http://hk.pswp.cn/bicheng/75706.shtml
    英文地址,請注明出處:http://en.pswp.cn/bicheng/75706.shtml

    如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

    相關文章

    從全球首發到獨家量產,遠峰科技持續領跑數字鑰匙賽道

    數字車鑰匙「新紀元」即將開啟&#xff0c;星閃數字鑰匙正式進入量產周期。 隨著汽車智能化快速普及&#xff0c;數字鑰匙的搭載量正在快速提升。根據高工智能汽車研究院的數據&#xff0c;2024年中國市場乘用車前裝標配搭載數字鑰匙的新車交付量超過1000萬輛&#xff0c;同比…

    C#高級:利用LINQ進行實體列表的集合運算

    問題引入&#xff1a; Teacher實體的唯一標識符是Name和Classes字段&#xff08;或者說這兩個字段唯一確定一條數據&#xff09;&#xff0c;如何對兩個實體列表做交集、差集運算呢&#xff1f;&#xff08;并集直接調用AddRange方法即可&#xff09; 一、重寫方法實現 1.原…

    C++\MFC鎖lock從專家到小白

    C mutex # include <mutex> std::mutex m_lock; void CMainWnd::function() {std::lock_guard<std::mutex> lock(m_lock);... }僅限同一進程內。阻塞等待&#xff1a;當線程 A 持有鎖時&#xff0c;線程 B 嘗試獲取同一互斥鎖時&#xff0c;會進入阻塞狀態&#x…

    COBOL語言的數據庫交互

    COBOL語言的數據庫交互 引言 隨著信息技術的不斷發展&#xff0c;數據庫管理系統&#xff08;DBMS&#xff09;已經成為現代應用程序中不可或缺的組成部分。在眾多編程語言中&#xff0c;COBOL&#xff08;Common Business-Oriented Language&#xff09;以其在商業應用中的穩…

    黑馬點評_知識點

    將手機驗證碼保存到HttpSession中進行驗證&#xff08;感覺已經過時&#xff09; Controller中的參數有HttpSession&#xff0c;存驗證碼session.setAttribute(SystemConstants.VERIFY_CODE, code); 其他的都是邏輯代碼 Cookie的缺點 什么是Session集群共享問題&#xff1f; …

    CSS語言的硬件驅動

    CSS語言的硬件驅動探討 引言 隨著信息技術的迅猛發展&#xff0c;硬件和軟件之間的交互愈發復雜&#xff0c;特別是在嵌入式系統、物聯網設備等領域&#xff0c;硬件驅動程序的開發變得至關重要。而在眾多編程語言中&#xff0c;CSS&#xff08;層疊樣式表&#xff09;作為一…

    K8s中CPU和Memory的資源管理

    資源類型 在 Kubernetes 中&#xff0c;Pod 作為最小的原子調度單位&#xff0c;所有跟調度和資源管理相關的屬性都屬于 Pod。其中最常用的資源就是 CPU 和 Memory。 CPU 資源 在 Kubernetes 中&#xff0c;一個 CPU 等于 1 個物理 CPU 核或者一個虛擬核&#xff0c;取決于節…

    解鎖 DeepSeek 與 Matlab:攻克科研難題的技術利刃

    技術點目錄 第一章、MATLAB 2024b深度學習工具箱新特性簡介第二章、卷積神經網絡&#xff08;Convolutional Neural Network, CNN&#xff09;第三章、模型可解釋性與特征可視化Model Explanation and Feature Visualization第四章、遷移學習算法&#xff08;Transfer Learning…

    藍橋杯_PCF8591

    目錄 一 前言 二 引言 三 PCF8591介紹 &#xff08;1&#xff09;I2C通信 &#xff08;2&#xff09;原理圖中的8591 四 代碼層面 &#xff08;1&#xff09;根據題目所給的示范代碼&#xff0c;實現ADC 1 為什么需要返回值&#xff0c;同時返回值是unsigned char&#x…

    Dify案例-接入飛書云文檔實現需求質量評估

    dify接入飛書云文檔實現需求質量評估 1. 背景與目標2. 系統架構與流程2.1 整體架構圖2.2 核心流程2.3 dify工作流概覽 3. 實現細節3.1 文檔提取3.2 需求評估3.3 參數提取3.4 創建飛書云文檔 4. 難點總結4.1 提示詞編寫4.2 關聯飛書云文檔4.2.1 安裝飛書云文檔插件并關聯到飛書自…

    機器視覺工程師的專業精度決定職業高度,而專注密度決定成長速度。低質量的合群,不如高質量獨處

    在機器視覺行業&#xff0c;真正的技術突破往往誕生于深度思考與有效碰撞的辯證統一。建議采用「70%高質量獨處30%精準社交」的鉆石結構&#xff0c;構建可驗證的技術能力護城河。記住&#xff1a;你的專業精度決定職業高度&#xff0c;而專注密度決定成長速度。 作為機器視覺工…

    字符串移位包含問題

    字符串移位包含問題 #include <iostream> #include <algorithm> using namespace std; int main(){string a,b;cin>>a>>b;//誰長遍歷誰if(a.size()<b.size()) swap(a,b);//1-對整個字符串進行移位for(int i0; i<a.size(); i){//每次循環都將第一…

    SQL 查詢執行順序

    SQL 查詢的邏輯處理順序&#xff08;即 SQL 引擎解析和執行查詢的順序&#xff09;與書寫順序不同。以下是 SQL 查詢的完整執行順序&#xff1a; 1. 邏輯執行順序 FROM 和 JOIN - 確定數據來源表并執行連接操作 WHERE - 對行進行篩選 GROUP BY - 將數據分組 HAVING - 對分組…

    核心知識——Spark核心數據結構:RDD

    引入 通過前面的學習&#xff0c;我們對于Spark已經有一個基本的認識&#xff0c;并且搭建了一個本地的練習環境&#xff0c;因為本專欄的主要對象是數倉和數分&#xff0c;所以就不花大篇幅去寫環境搭建等內容&#xff0c;當然&#xff0c;如果感興趣的小伙伴可以留言&#x…

    Spring Boot 嵌入式容器性能對決:Tomcat vs Undertow!

    文章目錄 引言理論基礎嵌入式容器TomcatUndertow 實戰性能測試配置 Tomcat 和 Undertow創建測試控制器使用Jmeter壓測 總結 引言 在現代應用開發中&#xff0c;選擇合適的嵌入式容器對于提升應用的性能和響應性至關重要。Spring Boot 提供了多種嵌入式容器選項&#xff0c;其中…

    計算機系統---GPU

    硬件架構 核心處理器&#xff1a; 流處理器&#xff08;SP&#xff09;&#xff1a;是GPU進行計算的核心單元&#xff0c;數量眾多。例如&#xff0c;NVIDIA的高端GPU可能擁有數千個流處理器。它們可以并行執行大量的計算任務&#xff0c;如在圖形渲染中對每個頂點或像素進行獨…

    【GPT寫代碼】動作視頻切截圖研究器

    目錄 背景源代碼 end 背景 用python寫一個windows環境運行的動作視頻切截圖研究器&#xff0c;用路徑瀏覽的方式指定待處理的視頻文件&#xff0c;然后點擊分析按鈕&#xff0c;再預覽區域顯示視頻預覽畫面&#xff0c;然后拖動時間軸&#xff0c;可以在預覽區域刷新顯示相應的…

    在 .NET 8 中使用自定義令牌身份驗證掌握 SignalR Hub 安全性

    最近在練習做一個 Web 開發項目&#xff0c;需要使用 WebSockets 傳輸數據&#xff0c;實現實時通信。這是一個 React.js 項目&#xff0c;后端是 .NET。 雖然 MSDN 提供了出色的頂級文檔&#xff0c;但它通常缺少高級用例所需的低級細節。 一種這樣的場景是使用自定義令牌對…

    [2018][note]用于超快偏振開關和動態光束分裂的all-optical有源THz超表——

    前言 類型 太赫茲 + 超表面 太赫茲 + 超表面 太赫茲+超表面 期刊 O p e n A c c e s s Open Access Open

    家里網絡訪問Github有時候打不開,解決辦法

    1、修改Hosts文件修改法 通過DNS查詢工具&#xff08;如&#xff09;獲取最新GitHub域名解析IP修改系統hosts文件&#xff08;路徑&#xff1a;C:\Windows\System32\drivers\etc\hosts&#xff09;&#xff0c;添加&#xff1a;20.205.243.166 github.com 20.27.177.113 github…