自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一個 Python 和 JavaScript 交換數(shù)據(jù)的庫

開發(fā) 后端
telepath是一個Django庫,用于在Python和JavaScript之間交換數(shù)據(jù),使您可以構(gòu)建具有豐富客戶端接口的應用程序,同時將業(yè)務邏輯保留在服務器端代碼中。

[[400553]]

本文轉(zhuǎn)載自微信公眾號「Python中文社區(qū)」,作者telepath。轉(zhuǎn)載本文請聯(lián)系Python中文社區(qū)公眾號。

 telepath是一個Django庫,用于在Python和JavaScript之間交換數(shù)據(jù),使您可以構(gòu)建具有豐富客戶端接口的應用程序,同時將業(yè)務邏輯保留在服務器端代碼中。

它有什么作用?

它提供了一種將包括Python對象在內(nèi)的結(jié)構(gòu)化數(shù)據(jù)打包為JSON可序列化格式的機制。通過向相應的JavaScript實現(xiàn)注冊該機制,可以擴展該機制以支持任何Python類。然后,打包的數(shù)據(jù)可以包含在HTTP響應中,并在JavaScript中解壓縮以獲得與原始數(shù)據(jù)等效的數(shù)據(jù)結(jié)構(gòu)。

安裝方法

  1. pip install telepath 

并將'telepath'添加到項目的INSTALLED_APPS。

簡介

假設(shè)我們正在構(gòu)建一個用于玩跳棋的Django應用。我們已經(jīng)花費了數(shù)天或數(shù)周的時間,構(gòu)建了游戲規(guī)則的Python實現(xiàn),并提供了代表當前游戲狀態(tài)和各個部分的類。但是,我們還希望為播放器提供一個適當友好的用戶界面,這意味著該是我們編寫JavaScript前端的時候了。我們的UI代碼不可避免地將擁有自己的對象,這些對象代表不同的角色,鏡像我們正在服務器上跟蹤的數(shù)據(jù)結(jié)構(gòu)——但我們無法發(fā)送Python對象,因此將這些數(shù)據(jù)發(fā)送到客戶端通常將意味著設(shè)計游戲狀態(tài)的JSON表示形式,并在兩端分別設(shè)計大量樣式代碼,遍歷數(shù)據(jù)結(jié)構(gòu)以在本機對象之間來回轉(zhuǎn)換。讓我們看看telepath如何簡化該過程。

一個完整的跳棋游戲?qū)τ诒窘坛虂碚f有點太多了,所以我們只選擇渲染這一步...

在Python環(huán)境中,創(chuàng)建一個新的Django項目:

  1. pip install "Django>=3.1,<3.2" 
  2. django-admin startproject draughts 
  3. cd draughts 
  4. ./manage.py startapp games 

在draughts / settings.py的INSTALLED_APPS列表中添加'games'。

為簡單起見,在本示例中,我們將不涉及數(shù)據(jù)庫,而是將游戲狀態(tài)表示為普通的Python類而不是Django模型。修改games/views.py,如下所示:

  1. from django.shortcuts import render 
  2.  
  3.  
  4. class Piece: 
  5.     def __init__(self, color, position): 
  6.         self.color = color 
  7.         self.position = position 
  8.  
  9.  
  10. class GameState: 
  11.     def __init__(self, pieces): 
  12.         self.pieces = pieces 
  13.  
  14.     @staticmethod 
  15.     def new_game(): 
  16.         black_pieces = [ 
  17.             Piece('black', (x, y)) 
  18.             for y in range(0, 3) 
  19.             for x in range((y + 1) % 2, 8, 2) 
  20.         ] 
  21.         white_pieces = [ 
  22.             Piece('white', (x, y)) 
  23.             for y in range(5, 8) 
  24.             for x in range((y + 1) % 2, 8, 2) 
  25.         ] 
  26.         return GameState(black_pieces + white_pieces) 
  27.  
  28.  
  29. def game(request): 
  30.     game_state = GameState.new_game() 
  31.  
  32.     return render(request, 'game.html', {}) 

如下所示創(chuàng)建games/templates/game.html:

  1. <!doctype html> 
  2. <html> 
  3.     <head> 
  4.         <title>Draughts</title> 
  5.         <script> 
  6.             document.addEventListener('DOMContentLoaded', event => { 
  7.                 const gameElement = document.getElementById('game'); 
  8.                 gameElement.innerHTML = 'TODO: render the board here' 
  9.             }); 
  10.         </script> 
  11.     </head> 
  12.     <body> 
  13.         <h1>Draughts</h1> 
  14.         <div id="game"
  15.         </div> 
  16.     </body> 
  17. </html> 

 

 

 

 

 

 

 

將新視圖添加到draughts/urls.py:

  1. from django.contrib import admin 
  2. from django.urls import path 
  3.  
  4. from games.views import game 
  5.  
  6. urlpatterns = [ 
  7.     path('', game), 
  8.     path('admin/', admin.site.urls), 

現(xiàn)在,使用./manage.py runserver啟動服務器,并訪問http:// localhost:8000 /。

到目前為止,我們已經(jīng)創(chuàng)建了一個代表新游戲的GameState對象——現(xiàn)在是時候引入telepath,以便我們可以將該對象傳輸?shù)娇蛻舳?。?zhí)行下面命令:

  1. pip install telepath 

并將'telepath'添加到draughts / settings.py中的INSTALLED_APPS列表中?,F(xiàn)在編輯games/views.py文件:

  1. import json 
  2. from django.shortcuts import render 
  3. from telepath import JSContext 
  4.  
  5. # ... 
  6.  
  7. def game(request): 
  8.     game_state = GameState.new_game() 
  9.  
  10.     js_context = JSContext() 
  11.     packed_game_state = js_context.pack(game_state) 
  12.     game_state_json = json.dumps(packed_game_state) 
  13.  
  14.     return render(request, 'game.html', { 
  15.         'game_state_json': game_state_json, 
  16.     }) 

這里JSContext是一個幫助工具,用于管理游戲狀態(tài)對象到我們可以在Javascript中使用的表示形式的轉(zhuǎn)換。js_context.pack接受該對象并將其轉(zhuǎn)換為可以JSON序列化并傳遞到我們的模板的值。但是,現(xiàn)在重新加載頁面失敗,并出現(xiàn)以下形式的錯誤:don't know how to pack object:

這是因為GameState是Telepath尚不知道如何處理的自定義Python類型。傳遞給pack的任何自定義類型必須鏈接到相應的JavaScript實現(xiàn);這是通過定義Adapter對象并將其注冊到telepath來完成的。如下更新game / views.py:

  1. import json 
  2. from django.shortcuts import render 
  3. from telepath import Adapter, JSContext, register 
  4.  
  5. # ... 
  6.  
  7. class GameState: 
  8.     # keep definition as before 
  9.  
  10.  
  11. class GameStateAdapter(Adapter): 
  12.     js_constructor = 'draughts.GameState' 
  13.  
  14.     def js_args(self, game_state): 
  15.         return [game_state.pieces] 
  16.  
  17.     class Media: 
  18.         js = ['draughts.js'
  19.  
  20.  
  21. register(GameStateAdapter(), GameState) 

此處js_constructor是JavaScript構(gòu)造函數(shù)的標識符,該標識符將用于在客戶端上構(gòu)建GameState實例,并且js_args定義了將傳遞給此構(gòu)造函數(shù)的參數(shù)列表,以重新創(chuàng)建給定game_state對象的JavaScript對應對象 。Media類指示文件,該文件遵循Django對格式媒體的約定,可在其中找到GameState的JavaScript實現(xiàn)。稍后我們將看到此JavaScript實現(xiàn)的外觀,現(xiàn)在,我們需要為Piece類定義一個類似的適配器,因為我們對GameStateAdapter的定義取決于是否能夠打包Piece實例。將以下定義添加到games/views.py:

  1. class Piece: 
  2.     # keep definition as before 
  3.  
  4.  
  5. class PieceAdapter(Adapter): 
  6.     js_constructor = 'draughts.Piece' 
  7.  
  8.     def js_args(self, piece): 
  9.         return [piece.color, piece.position] 
  10.  
  11.     class Media: 
  12.         js = ['draughts.js'
  13.  
  14.  
  15. register(PieceAdapter(), Piece) 

重新加載頁面,您將看到錯誤提示消失了,這表明我們已成功將GameState對象序列化為JSON并將其傳遞給模板?,F(xiàn)在,我們可以將其包含在模板中-編輯games/templates/game.html:

  1. <body> 
  2.        <h1>Draughts</h1> 
  3.        <div id="game" data-game-state="{{ game_state_json }}"
  4.        </div> 
  5.    </body> 

 

 

 

 

 

 

再次重新加載頁面,并在瀏覽器的開發(fā)人員工具中檢查游戲元素(在Chrome和Firefox中,右鍵單擊TODO注釋,然后選擇Inspect或Inspect Element),您將看到GameState對象的JSON表示,準備好 解壓成完整的JavaScript對象。

除了將數(shù)據(jù)打包成JSON可序列化的格式外,JSContext對象還跟蹤將數(shù)據(jù)解壓縮所需的JavaScript媒體定義,作為其媒體屬性。讓我們更新游戲視圖,以將其也傳遞給模板-在games/views.py中:

  1. def game(request): 
  2.     game_state = GameState.new_game() 
  3.  
  4.     js_context = JSContext() 
  5.     packed_game_state = js_context.pack(game_state) 
  6.     game_state_json = json.dumps(packed_game_state) 
  7.  
  8.     return render(request, 'game.html', { 
  9.         'game_state_json': game_state_json, 
  10.         'media': js_context.media, 
  11.     }) 

將下面代碼添加到games / templates / game.html中的HTML頭文件中:

  1. <head> 
  2.         <title>Draughts</title> 
  3.         {{ media }} 
  4.         <script> 
  5.             document.addEventListener('DOMContentLoaded', event => { 
  6.                 const gameElement = document.getElementById('game'); 
  7.                 gameElement.innerHTML = 'TODO: render the board here' 
  8.             }); 
  9.         </script> 
  10.     </head> 

 

 

重新加載頁面并查看源代碼,您將看到這帶來了兩個JavaScript包括 —— telepath.js(客戶端telepath庫,提供解包機制)和我們在適配器定義中指定的draughts.js文件。后者尚不存在,所以讓我們在games / static / draughts.js中創(chuàng)建它:

  1. class Piece { 
  2.     constructor(color, position) { 
  3.         this.color = color; 
  4.         this.position = position; 
  5.     } 
  6. window.telepath.register('draughts.Piece', Piece); 
  7.  
  8.  
  9. class GameState { 
  10.     constructor(pieces) { 
  11.         this.pieces = pieces; 
  12.     } 
  13. window.telepath.register('draughts.GameState', GameState); 

這兩個類定義實現(xiàn)了我們先前在適配器對象中聲明的構(gòu)造函數(shù)-構(gòu)造函數(shù)接收的參數(shù)是js_args定義的參數(shù)。window.telepath.register行將這些類定義附加到通過js_constructor指定的相應標識符?,F(xiàn)在,這為我們提供了解壓縮JSON所需的一切-回到games / templates / game.html中,更新JS代碼,如下所示:

  1. <script> 
  2.            document.addEventListener('DOMContentLoaded', event => { 
  3.                const gameElement = document.getElementById('game'); 
  4.                const gameStateJson = gameElement.dataset.gameState; 
  5.                const packedGameState = JSON.parse(gameStateJson); 
  6.                const gameState = window.telepath.unpack(packedGameState); 
  7.                console.log(gameState); 
  8.            }) 
  9.        </script> 

 

您可能需要重新啟動服務器以獲取新的games/static文件夾。重新加載頁面,然后在瀏覽器控制臺中,您現(xiàn)在應該看到填充了Piece對象的GameState對象?,F(xiàn)在,我們可以繼續(xù)在games/static/draughts.js中填寫渲染代碼:

  1. class Piece { 
  2.     constructor(color, position) { 
  3.         this.color = color; 
  4.         this.position = position; 
  5.     } 
  6.  
  7.     render(container) { 
  8.         const element = document.createElement('div'); 
  9.         container.appendChild(element); 
  10.         element.style.width = element.style.height = '24px'
  11.         element.style.border = '2px solid grey'
  12.         element.style.borderRadius = '14px'
  13.         element.style.backgroundColor = this.color; 
  14.     } 
  15. window.telepath.register('draughts.Piece', Piece) 
  16.  
  17.  
  18. class GameState { 
  19.     constructor(pieces) { 
  20.         this.pieces = pieces; 
  21.     } 
  22.  
  23.     render(container) { 
  24.         const table = document.createElement('table'); 
  25.         container.appendChild(table); 
  26.         const cells = []; 
  27.         for (let y = 0; y < 8; y++) { 
  28.             let row = document.createElement('tr'); 
  29.             table.appendChild(row); 
  30.             cells[y] = []; 
  31.             for (let x = 0; x < 8; x++) { 
  32.                 let cell = document.createElement('td'); 
  33.                 row.appendChild(cell); 
  34.                 cells[y][x] = cell; 
  35.                 cell.style.width = cell.style.height = '32px'
  36.                 cell.style.backgroundColor = (x + y) % 2 ? 'silver''white'
  37.             } 
  38.         } 
  39.  
  40.         this.pieces.forEach(piece => { 
  41.             const [x, y] = piece.position; 
  42.             const cell = cells[y][x]; 
  43.             piece.render(cell); 
  44.         }); 
  45.     } 
  46. window.telepath.register('draughts.GameState', GameState) 

在games/templates/game.html中添加對render方法的調(diào)用:

  1. <script> 
  2.             document.addEventListener('DOMContentLoaded', event => { 
  3.                 const gameElement = document.getElementById('game'); 
  4.                 const gameStateJson = gameElement.dataset.gameState; 
  5.                 const packedGameState = JSON.parse(gameStateJson); 
  6.                 const gameState = window.telepath.unpack(packedGameState); 
  7.                 gameState.render(gameElement); 
  8.             }) 
  9.         </script> 

 

重新加載頁面,您將看到我們的跳棋程序已準備就緒,可以開始游戲了。

  • 讓我們快速回顧一下我們已經(jīng)取得的成果:
  • 我們已經(jīng)打包和解包了自定義Python / JavaScript類型的數(shù)據(jù)結(jié)構(gòu),而無需編寫代碼來遞歸該結(jié)構(gòu)。如果我們的GameState對象變得更復雜(例如,“棋子”列表可能變成棋子和國王對象的混合列表,或者狀態(tài)可能包括游戲歷史),則無需重構(gòu)任何數(shù)據(jù)打包/拆包邏輯,除了為每個使用的類提供一個適配器對象。
  • 僅提供了解壓縮頁面數(shù)據(jù)所需的JS文件-如果我們的游戲應用程序擴展到包括Chess,Go和Othello,并且所有生成的類都已通過Telepath注冊,則我們?nèi)匀恢恍枰峁┡c跳棋知識相關(guān)的代碼。

即使我們使用任意對象,也不需要動態(tài)內(nèi)聯(lián)JavaScript —— 所有動態(tài)數(shù)據(jù)都以JSON形式傳遞,并且所有JavaScript代碼在部署時都是固定的(如果我們的網(wǎng)站強制執(zhí)行CSP,這一點很重要)。

責任編輯:武曉燕 來源: Python中文社區(qū)
相關(guān)推薦

2014-02-14 09:37:01

JavascriptDOM

2012-07-17 17:05:55

JavaScript

2012-12-12 09:47:56

JavaScript

2021-05-14 10:45:21

PythonNoSQL數(shù)據(jù)庫

2017-05-18 12:16:03

LinuxPythonNoSql

2011-07-20 14:57:47

SQLite數(shù)據(jù)庫ORDER BYGROUP BY

2022-07-21 09:50:20

Python日期庫pendulum

2024-07-02 11:29:28

Typer庫Python命令

2024-04-01 05:00:00

GUIpythonDearPyGui

2023-11-28 14:22:54

Python音頻

2011-07-20 13:18:01

SQLite數(shù)據(jù)庫修改和刪除數(shù)據(jù)

2012-01-04 13:55:23

Canvas

2024-04-10 12:39:08

機器學習python

2021-07-29 10:46:56

Python內(nèi)置庫代碼

2021-08-27 09:48:18

Pythonitertools代碼

2018-02-25 17:30:18

2011-10-13 09:38:27

JavaScript

2011-07-20 13:40:00

SQLite數(shù)據(jù)庫查詢數(shù)據(jù)

2017-04-10 10:35:02

JavaScript框架

2022-08-31 12:48:48

TinyDBPython數(shù)據(jù)庫
點贊
收藏

51CTO技術(shù)棧公眾號