41.django 中如何實現 websocket?
django實現websocket大致上有兩種方式,一種channels,一種是dwebsocket。channels依賴於redis,twisted等,相比之下使用dwebsocket要更為方便一些。
安裝
# pip install dwebsocket
配置:
# setting.py
INSTALLED_APPS = [
.....
.....
'dwebsocket',
]
MIDDLEWARE_CLASSES = [
......
......
'dwebsocket.middleware.WebSocketMiddleware' # 為所有的URL提供websocket,如果只是單獨的視圖需要可以不選
]
WEBSOCKET_ACCEPT_ALL=True # 可以允許每一個單獨的視圖實用websockets
簡單使用:
模擬文件下載的簡單示例
from dwebsocket.decorators import accept_websocket
@accept_websocket
def test(request):
if not request.is_websocket(): # 判斷是不是websocket連接
return render(request, 'websocket.html')
else:
download = Haproxy()
t = threading.Thread(target=download.run)
t.start()
sent = []
while download.status:
if len(download.res_dict) > len(sent):
for i in download.res_dict.keys():
if i not in sent:
sent.append(i)
request.websocket.send(str(sent[-1]+str(download.res_dict[sent[-1]])).encode('utf-8')) # 發送消息到客戶端
if not download.status:
request.websocket.send('下載完成'.encode('utf-8'))
dwebsocket有兩種裝飾器:require_websocket和accept_websocekt,使用require_websocket裝飾器會導致視圖函數無法接收導致正常的http請求,一般情況使用accept_websocket方式就可以了,
dwebsocket的一些內置方法:
request.is_websocket():判斷請求是否是websocket方式,是返回true,否則返回false
request.websocket: 當請求為websocket的時候,會在request中增加一個websocket屬性,
WebSocket.wait() 返回客戶端發送的一條消息,沒有收到消息則會導致阻塞
WebSocket.read() 和wait一樣可以接受返回的消息,只是這種是非阻塞的,沒有消息返回None
WebSocket.count_messages()返回消息的數量
WebSocket.has_messages()返回是否有新的消息過來
WebSocket.send(message)像客戶端發送消息,message為byte類型
42.Python web 開發中, 跨域問題的解決思路是?
# 方案1.安裝django-cors-headers
pip install django-cors-header
配置settings.py文件
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware', # 注意順序
...
)
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'*'
)
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
# 方案2.使用JSONP
使用Ajax獲取json數據時,存在跨域的限制。不過,在Web頁面上調用js的script腳本文件時卻不受跨域的影響,JSONP就是利用這個來實現跨域的傳輸。因此,我們需要將Ajax調用中的dataType從JSON改為JSONP(相應的API也需要支持JSONP)格式。
JSONP只能用於GET請求。
# 方案3.直接修改Django中的views.py文件
修改views.py中對應API的實現函數,允許其他域通過Ajax請求數據:
def myview(_request):
response = HttpResponse(json.dumps({“key”: “value”, “key2”: “value”}))
response[“Access-Control-Allow-Origin”] = “*”
response[“Access-Control-Allow-Methods”] = “POST, GET, OPTIONS”
response[“Access-Control-Max-Age”] = “1000”
response[“Access-Control-Allow-Headers”] = “*”
return response
43.什么是wsgi?
WSGI的全稱是Web Server Gateway Interface,翻譯過來就是Web服務器網關接口。具體的來說,WSGI是一個規范,定義了Web服務器如何與Python應用程序進行交互,使得使用Python寫的Web應用程序可以和Web服務器對接起來。
44.列舉django的內置組件?
.Admin是對model中對應的數據表進行增刪改查提供的組件
.model組件:負責操作數據庫
.form組件:1.生成HTML代碼2.數據有效性校驗3校驗信息返回並展示
.ModelForm組件即用於數據庫操作,也可用於用戶請求的驗證
45.django 中 model 的 SlugField 類型字段有什么用途
SlugField 本質上相當於存放字符串,但是在意義上,主要用於把某些字段形成語義化的,可以訪問的短網址(slug)字符串。