您的位置:首页技术文章
文章详情页

基于telepath库实现Python和JavaScript之间交换数据

【字号: 日期:2022-06-19 09:03:44浏览:7作者:猪猪
目录它有什么作用?安装方法简介它有什么作用?

它提供了一种将包括Python对象在内的结构化数据打包为JSON可序列化格式的机制。通过向相应的JavaScript实现注册该机制,可以扩展该机制以支持任何Python类。然后,打包的数据可以包含在HTTP响应中,并在JavaScript中解压缩以获得与原始数据等效的数据结构。

安装方法

pip install telepath

并将’telepath’添加到项目的INSTALLED_APPS。

简介

假设我们正在构建一个用于玩跳棋的Django应用。我们已经花费了数天或数周的时间,构建了游戏规则的Python实现,并提供了代表当前游戏状态和各个部分的类。但是,我们还希望为播放器提供一个适当友好的用户界面,这意味着该是我们编写JavaScript前端的时候了。我们的UI代码不可避免地将拥有自己的对象,这些对象代表不同的角色,镜像我们正在服务器上跟踪的数据结构——但我们无法发送Python对象,因此将这些数据发送到客户端通常将意味着设计游戏状态的JSON表示形式,并在两端分别设计大量样式代码,遍历数据结构以在本机对象之间来回转换。让我们看看telepath如何简化该过程。一个完整的跳棋游戏对于本教程来说有点太多了,所以我们只选择渲染这一步...在Python环境中,创建一个新的Django项目:

pip install 'Django>=3.1,<3.2'django-admin startproject draughtscd draughts./manage.py startapp games

在draughts / settings.py的INSTALLED_APPS列表中添加’games’。为简单起见,在本示例中,我们将不涉及数据库,而是将游戏状态表示为普通的Python类而不是Django模型。修改games/views.py,如下所示:

from django.shortcuts import renderclass Piece: def __init__(self, color, position):self.color = colorself.position = positionclass 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 adminfrom django.urls import pathfrom games.views import gameurlpatterns = [ 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 jsonfrom django.shortcuts import renderfrom 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 jsonfrom django.shortcuts import renderfrom telepath import Adapter, JSContext, register# ...class GameState: # keep definition as beforeclass 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 beforeclass PieceAdapter(Adapter): js_constructor = ’draughts.Piece’ def js_args(self, piece):return [piece.color, piece.position] class Media:js = [’draughts.js’]register(PieceAdapter(), Piece)

重新加载页面,您将看到错误提示消失了,这表明我们已成功将GameState对象序列化为JSON并将其传递给模板。现在,我们可以将其包含在模板中-编辑games/templates/game.html:

<body><h1>Draughts</h1><div id='game' data-game-state='{{ game_state_json }}'></div> </body>

再次重新加载页面,并在浏览器的开发人员工具中检查游戏元素(在Chrome和Firefox中,右键单击TODO注释,然后选择Inspect或Inspect Element),您将看到GameState对象的JSON表示,准备好 解压成完整的JavaScript对象。除了将数据打包成JSON可序列化的格式外,JSContext对象还跟踪将数据解压缩所需的JavaScript媒体定义,作为其媒体属性。让我们更新游戏视图,以将其也传递给模板-在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>

重新加载页面并查看源代码,您将看到这带来了两个JavaScript包括 —— 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,这一点很重要)。

以上就是基于telepath库实现Python和JavaScript之间交换数据的详细内容,更多关于Python和JavaScript之间交换数据的资料请关注好吧啦网其它相关文章!

标签: Python 编程
相关文章: