佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 基于telepath庫實現(xiàn)Python和JavaScript之間交換數(shù)據(jù)

基于telepath庫實現(xiàn)Python和JavaScript之間交換數(shù)據(jù)

熱門標(biāo)簽:客戶服務(wù) 百度AI接口 語音系統(tǒng) Win7旗艦版 呼叫中心市場需求 硅谷的囚徒呼叫中心 電話運營中心 企業(yè)做大做強

它有什么作用?

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

安裝方法

pip install telepath

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

簡介

假設(shè)我們正在構(gòu)建一個用于玩跳棋的Django應(yīng)用。我們已經(jīng)花費了數(shù)天或數(shù)周的時間,構(gòu)建了游戲規(guī)則的Python實現(xiàn),并提供了代表當(dāng)前游戲狀態(tài)和各個部分的類。但是,我們還希望為播放器提供一個適當(dāng)友好的用戶界面,這意味著該是我們編寫JavaScript前端的時候了。我們的UI代碼不可避免地將擁有自己的對象,這些對象代表不同的角色,鏡像我們正在服務(wù)器上跟蹤的數(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項目:

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

在draughts / settings.py的INSTALLED_APPS列表中添加'games'。
為簡單起見,在本示例中,我們將不涉及數(shù)據(jù)庫,而是將游戲狀態(tài)表示為普通的Python類而不是Django模型。修改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', {})

如下所示創(chuàng)建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),
]

現(xiàn)在,使用./manage.py runserver啟動服務(wù)器,并訪問http:// localhost:8000 /。
到目前為止,我們已經(jīng)創(chuàng)建了一個代表新游戲的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中使用的表示形式的轉(zhuǎn)換。js_context.pack接受該對象并將其轉(zhuǎn)換為可以JSON序列化并傳遞到我們的模板的值。但是,現(xiàn)在重新加載頁面失敗,并出現(xiàn)以下形式的錯誤:don't know how to pack object: games.views.GameState object at 0x10f3f2490>
這是因為GameState是Telepath尚不知道如何處理的自定義Python類型。傳遞給pack的任何自定義類型必須鏈接到相應(yīng)的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構(gòu)造函數(shù)的標(biāo)識符,該標(biāo)識符將用于在客戶端上構(gòu)建GameState實例,并且js_args定義了將傳遞給此構(gòu)造函數(shù)的參數(shù)列表,以重新創(chuàng)建給定game_state對象的JavaScript對應(yīng)對象 。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)

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

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

再次重新加載頁面,并在瀏覽器的開發(fā)人員工具中檢查游戲元素(在Chrome和Firefox中,右鍵單擊TODO注釋,然后選擇Inspect或Inspect Element),您將看到GameState對象的JSON表示,準(zhǔn)備好 解壓成完整的JavaScript對象。
除了將數(shù)據(jù)打包成JSON可序列化的格式外,JSContext對象還跟蹤將數(shù)據(jù)解壓縮所需的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中創(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);

這兩個類定義實現(xiàn)了我們先前在適配器對象中聲明的構(gòu)造函數(shù)-構(gòu)造函數(shù)接收的參數(shù)是js_args定義的參數(shù)。window.telepath.register行將這些類定義附加到通過js_constructor指定的相應(yīng)標(biāo)識符?,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>

您可能需要重新啟動服務(wù)器以獲取新的games/static文件夾。重新加載頁面,然后在瀏覽器控制臺中,您現(xiàn)在應(yīng)該看到填充了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方法的調(diào)用:

        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>

重新加載頁面,您將看到我們的跳棋程序已準(zhǔn)備就緒,可以開始游戲了。
讓我們快速回顧一下我們已經(jīng)取得的成果:

  • 我們已經(jīng)打包和解包了自定義Python / JavaScript類型的數(shù)據(jù)結(jié)構(gòu),而無需編寫代碼來遞歸該結(jié)構(gòu)。如果我們的GameState對象變得更復(fù)雜(例如,“棋子”列表可能變成棋子和國王對象的混合列表,或者狀態(tài)可能包括游戲歷史),則無需重構(gòu)任何數(shù)據(jù)打包/拆包邏輯,除了為每個使用的類提供一個適配器對象。
  • 僅提供了解壓縮頁面數(shù)據(jù)所需的JS文件-如果我們的游戲應(yīng)用程序擴展到包括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,這一點很重要)。

以上就是基于telepath庫實現(xiàn)Python和JavaScript之間交換數(shù)據(jù)的詳細內(nèi)容,更多關(guān)于Python和JavaScript之間交換數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!

您可能感興趣的文章:
  • python中requests庫+xpath+lxml簡單使用
  • python 網(wǎng)頁解析器掌握第三方 lxml 擴展庫與 xpath 的使用方法
  • Python json解析庫jsonpath原理及使用示例
  • Python 解析庫json及jsonpath pickle的實現(xiàn)
  • python3 pathlib庫Path類方法總結(jié)
  • 對python3中pathlib庫的Path類的使用詳解
  • Python爬蟲基礎(chǔ)之XPath語法與lxml庫的用法詳解
  • Python標(biāo)準(zhǔn)庫os.path包、glob包使用實例
  • 教你使用Python pypinyin庫實現(xiàn)漢字轉(zhuǎn)拼音
  • 讓文件路徑提取變得更簡單的Python Path庫

標(biāo)簽:崇左 喀什 安康 長沙 山西 濟南 海南 山西

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《基于telepath庫實現(xiàn)Python和JavaScript之間交換數(shù)據(jù)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    九寨沟县| 南通市| 会昌县| 青州市| 永城市| 海盐县| 铁岭县| 庆阳市| 百色市| 梅河口市| 丰原市| 嘉鱼县| 三河市| 泰宁县| 兴文县| 胶州市| 丰宁| 沛县| 龙游县| 聊城市| 和顺县| 萝北县| 通河县| 开化县| 湘潭市| 蓝田县| 鹤山市| 津市市| 开封县| 济宁市| 光泽县| 屯门区| 鲁山县| 霍林郭勒市| 宁国市| 祁连县| 伊川县| 武定县| 称多县| 玉树县| 西吉县|