基于telepath庫實現Python和JavaScript之間交換數據
它有什么作用?
它提供了一種將包括Python對象在內的結構化數據打包為JSON可序列化格式的機制。通過向相應的JavaScript實現注冊該機制,可以擴展該機制以支持任何Python類。然后,打包的數據可以包含在HTTP響應中,并在JavaScript中解壓縮以獲得與原始數據等效的數據結構。
安裝方法
pipinstalltelepath
并將'telepath'添加到項目的INSTALLED_APPS。
簡介
假設我們正在構建一個用于玩跳棋的Django應用。我們已經花費了數天或數周的時間,構建了游戲規(guī)則的Python實現,并提供了代表當前游戲狀態(tài)和各個部分的類。但是,我們還希望為播放器提供一個適當友好的用戶界面,這意味著該是我們編寫JavaScript前端的時候了。我們的UI代碼不可避免地將擁有自己的對象,這些對象代表不同的角色,鏡像我們正在服務器上跟蹤的數據結構——但我們無法發(fā)送Python對象,因此將這些數據發(fā)送到客戶端通常將意味著設計游戲狀態(tài)的JSON表示形式,并在兩端分別設計大量樣式代碼,遍歷數據結構以在本機對象之間來回轉換。讓我們看看telepath如何簡化該過程。
一個完整的跳棋游戲對于本教程來說有點太多了,所以我們只選擇渲染這一步...
在Python環(huán)境中,創(chuàng)建一個新的Django項目:
pipinstall"Django>=3.1,<3.2" django-adminstartprojectdraughts cddraughts ./manage.pystartappgames
在draughts / settings.py的INSTALLED_APPS列表中添加'games'。
為簡單起見,在本示例中,我們將不涉及數據庫,而是將游戲狀態(tài)表示為普通的Python類而不是Django模型。修改games/views.py,如下所示:
fromdjango.shortcutsimportrender classPiece: def__init__(self,color,position): self.color=color self.position=position classGameState: def__init__(self,pieces): self.pieces=pieces @staticmethod defnew_game(): black_pieces=[ Piece('black',(x,y)) foryinrange(0,3) forxinrange((y+1)%2,8,2) ] white_pieces=[ Piece('white',(x,y)) foryinrange(5,8) forxinrange((y+1)%2,8,2) ] returnGameState(black_pieces+white_pieces) defgame(request): game_state=GameState.new_game() returnrender(request,'game.html',{})
如下所示創(chuàng)建games/templates/game.html:
<!doctypehtml> <html> <head> <title>Draughts</title> <script> document.addEventListener('DOMContentLoaded',event=>{ constgameElement=document.getElementById('game'); gameElement.innerHTML='TODO:rendertheboardhere' }); </script> </head> <body> <h1>Draughts</h1> <divid="game"> </div> </body> </html>
將新視圖添加到draughts/urls.py:
fromdjango.contribimportadmin fromdjango.urlsimportpath fromgames.viewsimportgame urlpatterns=[ path('',game), path('admin/',admin.site.urls), ]
現在,使用./manage.py runserver啟動服務器,并訪問http:// localhost:8000 /。
到目前為止,我們已經創(chuàng)建了一個代表新游戲的GameState對象——現在是時候引入telepath,以便我們可以將該對象傳輸到客戶端。執(zhí)行下面命令:
pipinstalltelepath
并將'telepath'添加到draughts / settings.py中的INSTALLED_APPS列表中?,F在編輯games/views.py文件:
importjson fromdjango.shortcutsimportrender fromtelepathimportJSContext #... defgame(request): game_state=GameState.new_game() js_context=JSContext() packed_game_state=js_context.pack(game_state) game_state_json=json.dumps(packed_game_state) returnrender(request,'game.html',{ 'game_state_json':game_state_json, })
這里JSContext是一個幫助工具,用于管理游戲狀態(tài)對象到我們可以在Javascript中使用的表示形式的轉換。js_context.pack接受該對象并將其轉換為可以JSON序列化并傳遞到我們的模板的值。但是,現在重新加載頁面失敗,并出現以下形式的錯誤:don't know how to pack object: <games.views.GameState object at 0x10f3f2490>
這是因為GameState是Telepath尚不知道如何處理的自定義Python類型。傳遞給pack的任何自定義類型必須鏈接到相應的JavaScript實現;這是通過定義Adapter對象并將其注冊到telepath來完成的。如下更新game / views.py:
importjson fromdjango.shortcutsimportrender fromtelepathimportAdapter,JSContext,register #... classGameState: #keepdefinitionasbefore classGameStateAdapter(Adapter): js_constructor='draughts.GameState' defjs_args(self,game_state): return[game_state.pieces] classMedia: js=['draughts.js'] register(GameStateAdapter(),GameState)
此處js_constructor是JavaScript構造函數的標識符,該標識符將用于在客戶端上構建GameState實例,并且js_args定義了將傳遞給此構造函數的參數列表,以重新創(chuàng)建給定game_state對象的JavaScript對應對象 。Media類指示文件,該文件遵循Django對格式媒體的約定,可在其中找到GameState的JavaScript實現。稍后我們將看到此JavaScript實現的外觀,現在,我們需要為Piece類定義一個類似的適配器,因為我們對GameStateAdapter的定義取決于是否能夠打包Piece實例。將以下定義添加到games/views.py:
classPiece: #keepdefinitionasbefore classPieceAdapter(Adapter): js_constructor='draughts.Piece' defjs_args(self,piece): return[piece.color,piece.position] classMedia: js=['draughts.js'] register(PieceAdapter(),Piece)
重新加載頁面,您將看到錯誤提示消失了,這表明我們已成功將GameState對象序列化為JSON并將其傳遞給模板?,F在,我們可以將其包含在模板中-編輯games/templates/game.html:
<body> <h1>Draughts</h1> <divid="game"data-game-state="{{game_state_json}}"> </div> </body>
再次重新加載頁面,并在瀏覽器的開發(fā)人員工具中檢查游戲元素(在Chrome和Firefox中,右鍵單擊TODO注釋,然后選擇Inspect或Inspect Element),您將看到GameState對象的JSON表示,準備好 解壓成完整的JavaScript對象。
除了將數據打包成JSON可序列化的格式外,JSContext對象還跟蹤將數據解壓縮所需的JavaScript媒體定義,作為其媒體屬性。讓我們更新游戲視圖,以將其也傳遞給模板-在games/views.py中:
defgame(request): game_state=GameState.new_game() js_context=JSContext() packed_game_state=js_context.pack(game_state) game_state_json=json.dumps(packed_game_state) returnrender(request,'game.html',{ 'game_state_json':game_state_json, 'media':js_context.media, })
將下面代碼添加到games / templates / game.html中的HTML頭文件中:
<head> <title>Draughts</title> {{media}} <script> document.addEventListener('DOMContentLoaded',event=>{ constgameElement=document.getElementById('game'); gameElement.innerHTML='TODO:rendertheboardhere' }); </script> </head>
重新加載頁面并查看源代碼,您將看到這帶來了兩個JavaScript包括 —— telepath.js(客戶端telepath庫,提供解包機制)和我們在適配器定義中指定的draughts.js文件。后者尚不存在,所以讓我們在games / static / draughts.js中創(chuàng)建它:
classPiece{ constructor(color,position){ this.color=color; this.position=position; } } window.telepath.register('draughts.Piece',Piece); classGameState{ constructor(pieces){ this.pieces=pieces; } } window.telepath.register('draughts.GameState',GameState);
這兩個類定義實現了我們先前在適配器對象中聲明的構造函數-構造函數接收的參數是js_args定義的參數。window.telepath.register行將這些類定義附加到通過js_constructor指定的相應標識符?,F在,這為我們提供了解壓縮JSON所需的一切-回到games / templates / game.html中,更新JS代碼,如下所示:
<script> document.addEventListener('DOMContentLoaded',event=>{ constgameElement=document.getElementById('game'); constgameStateJson=gameElement.dataset.gameState; constpackedGameState=JSON.parse(gameStateJson); constgameState=window.telepath.unpack(packedGameState); console.log(gameState); }) </script>
您可能需要重新啟動服務器以獲取新的games/static文件夾。重新加載頁面,然后在瀏覽器控制臺中,您現在應該看到填充了Piece對象的GameState對象?,F在,我們可以繼續(xù)在games/static/draughts.js中填寫渲染代碼:
classPiece{ constructor(color,position){ this.color=color; this.position=position; } render(container){ constelement=document.createElement('div'); container.appendChild(element); element.style.width=element.style.height='24px'; element.style.border='2pxsolidgrey'; element.style.borderRadius='14px'; element.style.backgroundColor=this.color; } } window.telepath.register('draughts.Piece',Piece) classGameState{ constructor(pieces){ this.pieces=pieces; } render(container){ consttable=document.createElement('table'); container.appendChild(table); constcells=[]; for(lety=0;y<8;y++){ letrow=document.createElement('tr'); table.appendChild(row); cells[y]=[]; for(letx=0;x<8;x++){ letcell=document.createElement('td'); row.appendChild(cell); cells[y][x]=cell; cell.style.width=cell.style.height='32px'; cell.style.backgroundColor=(x+y)%2?'silver':'white'; } } this.pieces.forEach(piece=>{ const[x,y]=piece.position; constcell=cells[y][x]; piece.render(cell); }); } } window.telepath.register('draughts.GameState',GameState)
在games/templates/game.html中添加對render方法的調用:
<script> document.addEventListener('DOMContentLoaded',event=>{ constgameElement=document.getElementById('game'); constgameStateJson=gameElement.dataset.gameState; constpackedGameState=JSON.parse(gameStateJson); constgameState=window.telepath.unpack(packedGameState); gameState.render(gameElement); }) </script>
重新加載頁面,您將看到我們的跳棋程序已準備就緒,可以開始游戲了。
讓我們快速回顧一下我們已經取得的成果:
- 我們已經打包和解包了自定義Python / JavaScript類型的數據結構,而無需編寫代碼來遞歸該結構。如果我們的GameState對象變得更復雜(例如,“棋子”列表可能變成棋子和國王對象的混合列表,或者狀態(tài)可能包括游戲歷史),則無需重構任何數據打包/拆包邏輯,除了為每個使用的類提供一個適配器對象。
- 僅提供了解壓縮頁面數據所需的JS文件-如果我們的游戲應用程序擴展到包括Chess,Go和Othello,并且所有生成的類都已通過Telepath注冊,則我們仍然只需要提供與跳棋知識相關的代碼。
- 即使我們使用任意對象,也不需要動態(tài)內聯JavaScript —— 所有動態(tài)數據都以JSON形式傳遞,并且所有JavaScript代碼在部署時都是固定的(如果我們的網站強制執(zhí)行CSP,這一點很重要)。
以上就是基于telepath庫實現Python和JavaScript之間交換數據的詳細內容,更多關于Python和JavaScript之間交換數據的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網友推薦、互聯網收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯系alex-e#qq.com處理。