Python文件嵌入html(vue)中,在瀏覽器中跑起來
近期有個需求,之前項目是用python寫的,需要包一層html,在瀏覽器中跑起來。
推薦框架PyScript https://pyscript.net/

文檔中有一些在線的example

在本地試了試
<!doctype html> <html> <head> <!-- Recommended meta tags --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <!-- PyScript CSS --> <link rel="stylesheet" > <!-- This script tag bootstraps PyScript --> <script type="module" src="https://pyscript.net/releases/2024.1.1/core.js"></script> <style> #loading { outline: none; border: none; background: transparent } body { margin: 0; } .pyscript { margin: 0.5rem; } html { font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; line-height: 1.5; } py-terminal { display: none !important; } nav { position: sticky; width: 100%; top: 0; left: 0; z-index: 9999; } .logo { padding-right: 10px; font-size: 28px; height: 30px; max-width: inherit; } .title { text-decoration: none; text-decoration-line: none; text-decoration-style: initial; text-decoration-color: initial; font-weight: 400; font-size: 1.5em; line-height: 2em; white-space: nowrap; } .app-header { display: flex; align-items: center; padding: 0.5rem 1rem; } </style> </head> <body> <div id="#app"> <dialog id="loading"> <h1>Loading...</h1> </dialog> <nav class="navbar" style="background-color: hsl(0, 0%, 0%)"> <div class="app-header"> <a class="title" href="" style="color: #f0ab3c">Hello World</a> </div> </nav> <section class="pyscript"> <script type="py" src="./main.py" async terminal></script> <script type="py"> from pyscript import display from datetime import datetime now = datetime.now() display(now.strftime("%m/%d/%Y, %H:%M:%S")) </script> </section> </div> <script src="js/vue.min.js"></script> <script> var vm = new Vue({ el: '#app', data: { }, methods: { off: function () { }, off() { }, }, created() { } }); </script> </body> </html>
在本地文件夾中
python直接寫在代碼里可以跑起來,但是外部引入的報錯
發現,不能在文件夾中直接打開,需要起一個本地服務地址,類似http://127.0.0.1:8848/
也是可以正常跑起來
但是,我需要將他放到vue項目里面,而examples中的PyScript的js是外鏈,且js的type是type="module",不知道如何引入
更難過的是在淘寶鏡像中沒有對應的模塊
接下來就需要另一個集成框架pyscript-vue-starter出場了
github 地址 https://github.com/FabioRosado/pyscript-vue-starter
pyscript-vue-starter中用到 Vue 3, Vite, TypeScript, Tailwind CSS, Jest 和 Playwright。
使用此模板,可以快速開始使用Pyscript和Vue 3。Pyscript使能夠在Vue組件中編寫Python代碼,并且它還提供了在Vue組件中使用Python庫的方法。
在index.html文件的頭文件中添加并加載Pyscript。這將允許在Vue組件和頁面中使用Pyscript。

代碼運行及打包,依然是vue的一套。
至此,對于前端來說就容易了。

浙公網安備 33010602011771號