Вдохновлен этим постом:
Создайте автономную страницу dev с (крошечным) и webassembly 🦄💡✨
Sendil Kumar N · JUL 6 ’19 · 4 мин прочитаны
Я решил попробовать использовать Python.
Это первый раз, когда я пишу webassembly, которую я хотел сделать долгое время. Так что для этого я использую Пирога .
Давай началось
Первый Скачать pyodide Извлеките его и скопируйте pyodide.js
Файл в вашем текущем каталоге.
Теперь давайте напишем сервер в Server.py
Отказ
from http.server import BaseHTTPRequestHandler, HTTPServer class HTTPRequestHandler(BaseHTTPRequestHandler): """Request handler class""" def do_GET(self): """Handler for GET requests.""" # Send response status code self.send_response(200) # Send headers self.send_header("Cache-Control", "no-cache") if self.path.endswith(".wasm"): # Header to serve .wasm file self.send_header("Content-Type", "application/wasm") else: self.send_header("Content-Type", "text/html") self.end_headers() # Serve the file contents urlpath = self.path if urlpath == "/": urlpath = "/index.html" with open(f".{urlpath}", "rb") as f: content = f.read() self.wfile.write(content) def main(): print("starting server...") # Server settings server_address = ("localhost", 8080) httpd = HTTPServer(server_address, HTTPRequestHandler) print("running server...") httpd.serve_forever() if __name__ == "__main__": main()
Так что у нас есть pyodide.js
, Server.py
Отказ
Давайте напишем index.html.
Python wasm Initializing Python...
Теперь давайте напишем код Python для холста.
from js import document as doc # Make the "Initializing Python" status disappear doc.getElementById("status").innerHTML = "" canvas = doc.getElementById("draw-here") canvas.setAttribute("width", doc.body.clientWidth) canvas.setAttribute("height", 300) ctx = canvas.getContext("2d") ctx.strokeStyle = "#F4908E" ctx.lineJoin = "round" ctx.lineWidth = 5 # Global variables pen = False lastPoint = (0, 0) def onmousemove(e): global lastPoint if pen: newPoint = (e.offsetX, e.offsetY) ctx.beginPath() ctx.moveTo(lastPoint[0], lastPoint[1]) ctx.lineTo(newPoint[0], newPoint[1]) ctx.closePath() ctx.stroke() lastPoint = newPoint def onmousedown(e): global pen, lastPoint pen = True lastPoint = (e.offsetX, e.offsetY) def onmouseup(e): global pen pen = False canvas.addEventListener("mousemove", onmousemove) canvas.addEventListener("mousedown", onmousedown) canvas.addEventListener("mouseup", onmouseup) # Colors div = doc.getElementById("colors") colors = ["#F4908E", "#F2F097", "#88B0DC", "#F7B5D1", "#53C4AF", "#FDE38C"] for c in colors: node = doc.createElement("div") node.setAttribute("class", "color") node.setAttribute("id", c) node.setAttribute("style", f"background-color: {c}") def setColor(e): ctx.strokeStyle = e.target.id node.addEventListener("click", setColor) div.appendChild(node)
Теперь мы можем получить этот код как текст через AJAX и выполнить с помощью Pyodide.runpython (код)
.
Но для простоты мы будем напрямую вставить код в index.html
Отказ
Так что окончательная версия выглядит так:
Python wasm Initializing Python...
Теперь нам нужно только запустить веб-сервер с Python Server.py
и открыть http://localhost: 8080
Если у вас возникли проблемы, Вот полный проект Отказ
Оригинал: “https://dev.to/sayanarijit/create-dev-s-offline-page-with-python-pyodide-and-webassembly-241h”