柚子快報激活碼778899分享:關(guān)于我的Django學(xué)習(xí)筆記
柚子快報激活碼778899分享:關(guān)于我的Django學(xué)習(xí)筆記
dgango創(chuàng)建應(yīng)用
(django開發(fā)中一個功能模塊用一個應(yīng)用來實現(xiàn))
每一個應(yīng)用完成一個特定的功能
django項目創(chuàng)建命令: django-admin startproject Django 創(chuàng)建一個應(yīng)用命令: python manege.py startapp 應(yīng)用名
各個模塊的功能
1.models.py:MVC中的M,寫和數(shù)據(jù)庫相關(guān)的內(nèi)容 2.views.py:MVC中的V,接受請求,進行處理,與M和T進行交互,返回應(yīng)答 定義處理函數(shù) 3.test.py:寫測試代碼的文件 4.admin.py:網(wǎng)站后臺管理相關(guān)文件
實操
1.創(chuàng)建項目 2.開發(fā)某一功能時創(chuàng)建對應(yīng)應(yīng)用 3.建立應(yīng)用和項目之間的關(guān)系:修改settings.py文件 INSTALLED_APPS中進行應(yīng)用的注冊在后面添加應(yīng)用的名字 4.運行項目(檢查項目是否創(chuàng)建成功) 項目運行命令:python manage.py runserver
Django框架
1.ORM框架 (django自帶)
object:對象、類
Relation:關(guān)系,關(guān)系數(shù)據(jù)庫中的表
Mapping:映射
舉例:
‘’'type
class Bookinfo:
btitle 圖書名稱
tbpub_data 出版日期
‘’’ ‘圖書類’(object)
idbtitlebpub_data(Relations)\將類與關(guān)系表一一對應(yīng)\== 通過類操作對應(yīng)的表 ==(不需要寫sql語句了)
2.mvc框架 M:Model ,模型,和數(shù)據(jù)庫進行交互 V:View視圖,產(chǎn)生html頁面 C:Controller,控制器,接受請求,進行處理,與M和V進行交互,
== (分工思想) ==
怎樣在modles.py中設(shè)計模型類
后臺管理(更改數(shù)據(jù)表)
admin.py (后臺管理相關(guān)文件)
class BookInfo(models.Model):
btitle = models.CharField(max_length=20)
bpub_date = models.DateField()
def __str__(self):
#返回書名
return self.btitle
#自定義模型類管理(包括要顯示內(nèi)容等)
class BookInfoAdmin(admin.ModelAdmin):
list_display = ['id','btitle','bpub_date']
#注冊模型類
admin.site.register(BookInfo, BookInfoAdmin)
連接url與視圖
(值得注意的是,在django并不是用過濾器) view.py中設(shè)計好頁面要返回什么樣的內(nèi)容,然后用urls.py與view.py進行連接(路由配置) 用正則表達(dá)式進行匹配,之后返回views中的函數(shù)中的HttpResponse對象 從上到下匹配每一個path,一匹配到就輸出—>所以要嚴(yán)格匹配開頭和結(jié)尾,防止匹配到其他
path(r'^index&', views.index, name = 'index'),
path(r'^index2&',views.index2, name = 'index2')
用模板顯示html內(nèi)容
-----模板文件
使用模板文件
加載模板文件 去模板目錄下面獲取html文件的內(nèi)容,得到一個模板對象 定義模板上下文 向模版?zhèn)鬟f數(shù)據(jù) 模板渲染 得到一個標(biāo)準(zhǔn)的html文件 (渲染:把變量替換成對應(yīng)的值) 返回給瀏覽器
(可向模板文件中傳變量)
連接ChatGlm
調(diào)取chatAPI接口
import requests
from django.http import JsonResponse
def chat_with_glm(request):
if 'GET' == request.method:
return JsonResponse({'error': 'Please use POST method.'}, status=405)
data = json.loads(request.body)
user_input = data['input']
# 調(diào)用ChatGLM的API
response = requests.post('http://localhost:8000/v1/chat', json={'content': user_input}, timeout=10).json()
glm_response = response['data']['answer']
return JsonResponse({'response': glm_response})
配置Django以允許跨域請求
(可能是django接入chatglm API的必要步驟)(如果兩者運行在不同的域中) 所需庫:django-cors-headers
pip install django-cors-headers
將corsheaders添加到你的Django項目的INSTALLED_APPS設(shè)置中,位于列表的最頂部:
INSTALLED_APPS = [
'corsheaders',
# ...其他應(yīng)用...
]
在中間件MIDDLEWARE設(shè)置中添加corsheaders.middleware.CorsMiddleware,確保它被添加在CommonMiddleware之前:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
# ...其他中間件...
]
在settings.py中配置跨域設(shè)置,允許所有源(注意:在生產(chǎn)環(huán)境中應(yīng)該只允許信任的源):
CORS_ORIGIN_ALLOW_ALL = True
或者,更詳細(xì)地控制哪些源被允許:
CORS_ORIGIN_WHITELIST = (
'http://example.com',
'https://sub.example.com',
'http://localhost:8000',
'http://127.0.0.1:9000'
)
確保你的CORS_ORIGIN_WHITELIST和CORS_ORIGIN_ALLOW_ALL設(shè)置不能同時為True。
完成以上步驟后,你的Django項目就應(yīng)該能夠接受并響應(yīng)跨域請求了。
調(diào)用zhipuai的API接口
def send_message_to_chatglm(request,):
if request.method == 'POST':
value = request.POST.get('my_input', '') # 獲取輸入框的值
client = ZhipuAI(api_key="27b93707a8b9cbe24195275ad6539b7f.ZgPgA5DDAf8pVBLQ") # 填寫您自己的APIKey
response = client.chat.completions.create(
model="glm-4", # 填寫需要調(diào)用的模型名稱
messages=[
# {"role": "user", "content": "作為一名營銷專家,請為我的產(chǎn)品創(chuàng)作一個吸引人的slogan"},
# {"role": "assistant", "content": "當(dāng)然,為了創(chuàng)作一個吸引人的slogan,請告訴我一些關(guān)于您產(chǎn)品的信息"},
# {"role": "user", "content": "智譜AI開放平臺"},
# {"role": "assistant", "content": "智啟未來,譜繪無限一智譜AI,讓創(chuàng)新觸手可及!"},
{"role": "user", "content": str(value)}
],
)
# return render(request, 'chat/chatt.html', {'mess': str(response.choices[0].message)})
# 處理value,例如存儲到數(shù)據(jù)庫或進行其他操作
# return HttpResponse(f"You entered: {value}")
return render(request, 'chat/en.html',{'v':str(response.choices[0].message)})
return render(request, 'chat/en.html',)
響應(yīng)和請求
基本參數(shù)
例:
def show_books(request, ):
'''顯示圖書信息'''
# 1.通過M查找圖書表中的數(shù)據(jù)
# 2.進行url配置,建立url地址和試圖的對應(yīng)關(guān)系
Books = BookInfo.objects.all()
return render(request, 'book/show_books.html',{'books':Books})
1.request
一個對象對象,封裝了用戶發(fā)過來的所有數(shù)據(jù)
2.return HttpResponse
返回一個請求
3.request.GET
在URL上傳遞值
4.request.POST
在請求體中提交數(shù)據(jù)
5.return redirect()
讓瀏覽器重定向到其他頁面 例:
return redirect("https://www.baidu.com")
創(chuàng)建表單(前端)
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。