一个 Python 和 JavaScript 交换数据的库
Python中文社区
共 16521字,需浏览 34分钟
·
2021-05-21 02:36
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
对象——现在是时候引入telepath,以便我们可以将该对象传输到客户端。执行下面命令:pip install telepath
'telepath'
添加到draughts / settings.py
中的INSTALLED_APPS
列表中。现在编辑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
是一个帮助工具,用于管理游戏状态对象到我们可以在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
: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构造函数的标识符,该标识符将用于在客户端上构建GameState
实例,并且js_args
定义了将传递给此构造函数的参数列表,以重新创建给定game_state
对象的JavaScript对应对象 。Media类指示文件,该文件遵循Django对格式媒体的约定,可在其中找到GameState的JavaScript实现。稍后我们将看到此JavaScript实现的外观,现在,我们需要为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
中创建它: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
定义的参数。window.telepath.register
行将这些类定义附加到通过js_constructor
指定的相应标识符。现在,这为我们提供了解压缩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
文件夹。重新加载页面,然后在浏览器控制台中,您现在应该看到填充了Piece对象的GameState对象。现在,我们可以继续在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>
我们已经打包和解包了自定义Python / JavaScript类型的数据结构,而无需编写代码来递归该结构。如果我们的GameState对象变得更复杂(例如,“棋子”列表可能变成棋子和国王对象的混合列表,或者状态可能包括游戏历史),则无需重构任何数据打包/拆包逻辑,除了为每个使用的类提供一个适配器对象。 仅提供了解压缩页面数据所需的JS文件-如果我们的游戏应用程序扩展到包括Chess,Go和Othello,并且所有生成的类都已通过Telepath注册,则我们仍然只需要提供与跳棋知识相关的代码。 即使我们使用任意对象,也不需要动态内联JavaScript —— 所有动态数据都以JSON形式传递,并且所有JavaScript代码在部署时都是固定的(如果我们的网站强制执行CSP,这一点很重要)。
更多阅读
特别推荐
点击下方阅读原文加入社区会员
评论