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

pip install telepath
'telepath'添加到項目的INSTALLED_APPS。pip install "Django>=3.1,<3.2"
django-admin startproject draughts
cd draughts
./manage.py startapp games
draughts / settings.py的INSTALLED_APPS列表中添加'games'。games/views.py,如下所示:from django.shortcuts import render
class Piece:
def __init__(self, color, position):
self.color = color
self.position = position
class GameState:
def __init__(self, pieces):
self.pieces = pieces
@staticmethod
def new_game():
black_pieces = [
Piece('black', (x, y))
for y in range(0, 3)
for x in range((y + 1) % 2, 8, 2)
]
white_pieces = [
Piece('white', (x, y))
for y in range(5, 8)
for x in range((y + 1) % 2, 8, 2)
]
return GameState(black_pieces + white_pieces)
def game(request):
game_state = GameState.new_game()
return render(request, 'game.html', {})
games/templates/game.html:<!doctype html>
<html>
<head>
<title>Draughts</title>
<script>
document.addEventListener('DOMContentLoaded', event => {
const gameElement = document.getElementById('game');
gameElement.innerHTML = 'TODO: render the board here'
});
</script>
</head>
<body>
<h1>Draughts</h1>
<div id="game">
</div>
</body>
</html>
draughts/urls.py:from django.contrib import admin
from django.urls import path
from games.views import game
urlpatterns = [
path('', game),
path('admin/', admin.site.urls),
]
./manage.py runserver啟動服務器,并訪問http:// localhost:8000 /。GameState對象——現(xiàn)在是時候引入telepath,以便我們可以將該對象傳輸?shù)娇蛻舳?。?zhí)行下面命令:pip install telepath
'telepath'添加到draughts / settings.py中的INSTALLED_APPS列表中?,F(xiàn)在編輯games/views.py文件:import json
from django.shortcuts import render
from telepath import JSContext
# ...
def game(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)
return render(request, 'game.html', {
'game_state_json': game_state_json,
})
JSContext是一個幫助工具,用于管理游戲狀態(tài)對象到我們可以在Javascript中使用的表示形式的轉換。js_context.pack接受該對象并將其轉換為可以JSON序列化并傳遞到我們的模板的值。但是,現(xiàn)在重新加載頁面失敗,并出現(xiàn)以下形式的錯誤:don't know how to pack object: <games.views.GameState object at 0x10f3f2490>GameState是Telepath尚不知道如何處理的自定義Python類型。傳遞給pack的任何自定義類型必須鏈接到相應的JavaScript實現(xiàn);這是通過定義Adapter對象并將其注冊到telepath來完成的。如下更新game / views.py:import json
from django.shortcuts import render
from telepath import Adapter, JSContext, register
# ...
class GameState:
# keep definition as before
class GameStateAdapter(Adapter):
js_constructor = 'draughts.GameState'
def js_args(self, game_state):
return [game_state.pieces]
class Media:
js = ['draughts.js']
register(GameStateAdapter(), GameState)
js_constructor是JavaScript構造函數(shù)的標識符,該標識符將用于在客戶端上構建GameState實例,并且js_args定義了將傳遞給此構造函數(shù)的參數(shù)列表,以重新創(chuàng)建給定game_state對象的JavaScript對應對象 。Media類指示文件,該文件遵循Django對格式媒體的約定,可在其中找到GameState的JavaScript實現(xiàn)。稍后我們將看到此JavaScript實現(xiàn)的外觀,現(xiàn)在,我們需要為Piece類定義一個類似的適配器,因為我們對GameStateAdapter的定義取決于是否能夠打包Piece實例。將以下定義添加到games/views.py:class Piece:
# keep definition as before
class PieceAdapter(Adapter):
js_constructor = 'draughts.Piece'
def js_args(self, piece):
return [piece.color, piece.position]
class Media:
js = ['draughts.js']
register(PieceAdapter(), Piece)
games/templates/game.html: <body>
<h1>Draughts</h1>
<div id="game" data-game-state="{{ game_state_json }}">
</div>
</body>
games/views.py中:def game(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)
return render(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 => {
const gameElement = document.getElementById('game');
gameElement.innerHTML = 'TODO: render the board here'
});
</script>
</head>
telepath.js(客戶端telepath庫,提供解包機制)和我們在適配器定義中指定的draughts.js文件。后者尚不存在,所以讓我們在games / static / draughts.js中創(chuàng)建它:class Piece {
constructor(color, position) {
this.color = color;
this.position = position;
}
}
window.telepath.register('draughts.Piece', Piece);
class GameState {
constructor(pieces) {
this.pieces = pieces;
}
}
window.telepath.register('draughts.GameState', GameState);
js_args定義的參數(shù)。window.telepath.register行將這些類定義附加到通過js_constructor指定的相應標識符?,F(xiàn)在,這為我們提供了解壓縮JSON所需的一切-回到games / templates / game.html中,更新JS代碼,如下所示: <script>
document.addEventListener('DOMContentLoaded', event => {
const gameElement = document.getElementById('game');
const gameStateJson = gameElement.dataset.gameState;
const packedGameState = JSON.parse(gameStateJson);
const gameState = window.telepath.unpack(packedGameState);
console.log(gameState);
})
</script>
games/static文件夾。重新加載頁面,然后在瀏覽器控制臺中,您現(xiàn)在應該看到填充了Piece對象的GameState對象?,F(xiàn)在,我們可以繼續(xù)在games/static/draughts.js中填寫渲染代碼:class Piece {
constructor(color, position) {
this.color = color;
this.position = position;
}
render(container) {
const element = document.createElement('div');
container.appendChild(element);
element.style.width = element.style.height = '24px';
element.style.border = '2px solid grey';
element.style.borderRadius = '14px';
element.style.backgroundColor = this.color;
}
}
window.telepath.register('draughts.Piece', Piece)
class GameState {
constructor(pieces) {
this.pieces = pieces;
}
render(container) {
const table = document.createElement('table');
container.appendChild(table);
const cells = [];
for (let y = 0; y < 8; y++) {
let row = document.createElement('tr');
table.appendChild(row);
cells[y] = [];
for (let x = 0; x < 8; x++) {
let cell = 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;
const cell = cells[y][x];
piece.render(cell);
});
}
}
window.telepath.register('draughts.GameState', GameState)
games/templates/game.html中添加對render方法的調用: <script>
document.addEventListener('DOMContentLoaded', event => {
const gameElement = document.getElementById('game');
const gameStateJson = gameElement.dataset.gameState;
const packedGameState = JSON.parse(gameStateJson);
const gameState = window.telepath.unpack(packedGameState);
gameState.render(gameElement);
})
</script>
我們已經(jīng)打包和解包了自定義Python / JavaScript類型的數(shù)據(jù)結構,而無需編寫代碼來遞歸該結構。如果我們的GameState對象變得更復雜(例如,“棋子”列表可能變成棋子和國王對象的混合列表,或者狀態(tài)可能包括游戲歷史),則無需重構任何數(shù)據(jù)打包/拆包邏輯,除了為每個使用的類提供一個適配器對象。 僅提供了解壓縮頁面數(shù)據(jù)所需的JS文件-如果我們的游戲應用程序擴展到包括Chess,Go和Othello,并且所有生成的類都已通過Telepath注冊,則我們仍然只需要提供與跳棋知識相關的代碼。 即使我們使用任意對象,也不需要動態(tài)內聯(lián)JavaScript —— 所有動態(tài)數(shù)據(jù)都以JSON形式傳遞,并且所有JavaScript代碼在部署時都是固定的(如果我們的網(wǎng)站強制執(zhí)行CSP,這一點很重要)。
更多閱讀
特別推薦

點擊下方閱讀原文加入社區(qū)會員
評論
圖片
表情
