評論系統后端代碼實作
- 一. django創建
- 二. 資料庫連接與創建
- 三. settings檔案配置基本資訊
- 四. 創建一個小的后端系統
前言:
作者:神的孩子在歌唱
大家好,我叫陳運智,大家可以叫我智
教學視頻:
3. django基本配置——評論功能
4. 獲取資料庫資訊——評論功能
一. django創建
- 創建專案

- 運行測驗
python3 manage.py runserver

二. 資料庫連接與創建
連接資料庫


然后創建contents資料庫
create database contents
如果出現以下錯誤
Server returns invalid timezone. Need to set ‘serverTimezone’ property.
設定時間
將UTC設定成上海

完成資料庫創建

三. settings檔案配置基本資訊
(1)資料庫基本配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',#引擎
'HOST': 'localhost', # 資料庫主機
'PORT': 3306, # 資料庫埠
'USER': 'root', # 資料庫用戶名
'PASSWORD': 'chenyunzhi', # 資料庫用戶密碼
'NAME': 'contents' # 資料庫名字
}
}
如果出現以下錯誤說明資料庫服務沒打開
django.db.utils.OperationalError: (2002, “Can’t connect to MySQL server on ‘localhost’ (10061)”)
在cmd中輸入services.msc

(2)配置日期
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
四. 創建一個小的后端系統
- 創建app子應用
python manager.py startapp content_app

- 注冊安裝子應用
(1)設定根路徑

將content_app添加到工程中

- 在model.py中創建一個保存評論的資料庫

- 模型遷移(建表)
生成遷移檔案:根據模型類生成創建表的陳述句
python manage.py makemigrations

執行遷移:根據第一步生成的陳述句在資料庫中創建表
python manage.py migrate

完成

遷移時發生錯誤:沒有指定長度
django.db.utils.OperationalError: (1170, “BLOB/TEXT column ‘content’ used in key specification without a key length”)
- 在views.py檔案撰寫代碼,獲取content資料表里面的資訊
我們先手動給資料表添加幾個資料

匯入兩個模塊
#引入student的類
from content_app.models import Content
#引入JsonResponse模塊
from django.http import JsonResponse
撰寫獲取代碼
'''
獲取資料庫里所有評論
'''
def get_students(request):
'''獲取所有評論資訊'''
try:
#使用ORM獲取所有評論資訊
obj_content=Content.objects.all().values()
#把結果轉為list
contents=list(obj_content)
#回傳
return JsonResponse({'code':1,'data':contents})
except Exception as e:
#如果出現例外,回傳
return JsonResponse({'code': 0, 'msg': "獲取評論資訊例外"+str(e)})
pass
在url.py中配置路由
匯入類
from content_app import views
path('contents/',views.get_contents)
運行專案,輸入路由,就可以獲得他回傳的json格式的資料

目前后端獲取資料庫已經完成,接下來可以和前端聯通試試
本人博客:https://blog.csdn.net/weixin_46654114
轉載說明:跟我說明,務必注明來源,附帶本人博客連接,
請給我點個贊鼓勵我吧

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/287163.html
標籤:其他
