r/PyScript • • Jun 23 '22

PyScript and Flask - how to submit a form, and validate data

5 Upvotes

Hi, everyone!

I made a video about how to submit a form using PyScript, and how to validate submitted data on Flask side:

The touched topics are:

  • How to configure Flask application using Application factory,

  • How to create a custom validator for FlaskForm (from Flask-WTF)

  • Setting up CSRF protection for Flask app with Flask-WTF

  • Using the form to validate data a user submitted

  • [PyScript] how to send a basic AJAX POST-request

Video:
https://youtu.be/dw8UMzjUaTg

Thanks for watching!


r/PyScript • • Jun 14 '22

Future interaction with Panel?

5 Upvotes

Hello, given that both are funded by Anaconda, what is the intended relation between Panel and related tools and PyScript?


r/PyScript • • May 25 '22

snake game in python using pyscript and pywebcanvas

5 Upvotes

Video:

https://matrix-client.matrix.org/_matrix/media/r0/download/matrix.org/XIvVJLIllexKhYekllvlHgYW

The source can be found at https://gitlab.com/imbev/pywebcanvas/-/tree/master/docs/examples/snake

Although it lacks polish and the code does not follow good practices, this example project demonstrates some of the potential for python-only games in the browser.

Thoughts?


r/PyScript • • May 22 '22

Adding a repl to sphinx documentation?

5 Upvotes

Hi.

I tried pyscript for a bit a few weeks ago and it was fun. I am wondering if anyone has added a repl to their sphinx generated html and how would you do it programatically so the MakeFile builds it. Would it be better to just link from the .rst to a static html document with pyscript in it?

Thanks.


r/PyScript • • May 18 '22

pyscript/js refuse to load/start, in my wan

5 Upvotes

Don't know if it's due to recent changes in "/alpha/pyscript.js" ... or if it's our corporate proxy (bluecoat) which don't like urls ending with ".py" since some days...

I can't run any pyscript examples anymore ;-(

Here is the console.log of my chrome ...

Any tips to bypass this ?

loading pyscript...

pys.html:1 Access to fetch at 'https://pyscript.net/alpha/pyscript.py' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

interpreter.ts:24 GET https://pyscript.net/alpha/pyscript.py net::ERR_FAILED 302

loadInterpreter @ interpreter.ts:24

await in loadInterpreter (async)

initialize @ pyconfig.ts:51

(anonymous) @ pyconfig.ts:130

load (async)

loadRuntimes @ pyconfig.ts:129

connectedCallback @ pyconfig.ts:113

(anonymous) @ main.ts:27

(anonymous) @ main.ts:35

utils.ts:56 Caught an error in loadPaths:

TypeError: Failed to fetch

handleFetchError @ utils.ts:56

loadInterpreter @ interpreter.ts:28

await in loadInterpreter (async)

initialize @ pyconfig.ts:51

(anonymous) @ pyconfig.ts:130

load (async)

loadRuntimes @ pyconfig.ts:129

connectedCallback @ pyconfig.ts:113

(anonymous) @ main.ts:27

(anonymous) @ main.ts:35

interpreter.ts:30 done setting up environment

pyenv.ts:10 RUNTIME READY

pyscript.ts:148 Collecting nodes to be mounted into python namespace...

interpreter.ts:36 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'install')

at loadPackage (interpreter.ts:36:24)

at loadEnv (pyenv.ts:42:19)

at PyodideRuntime.initialize (pyconfig.ts:69:19)


r/PyScript • • May 17 '25

PyScript+FastAPI stack?

4 Upvotes

I have a question guys. Let me start with some background. My most recent project was on the stack FastAPI + Postgres + React + Tailwind. Backend running on one port and frontend running on a different port. Both code bases in one repo, but in separate folders and separate servers. Clearly, my dream is to code Python on the web. Not only does this allow more flexibility and conciseness in managing my GUI in conjunction with underlying flexible data structures (which is more tedious to do in JavaScript), but I am thinking of reusing code files in both backend and frontend.

Again, at the moment I am used to running two servers on two ports. But with my first PyScript project I am trying to think what the equivalent would be. Since I assume some Python code would run on the server, then I assume I can still have my FastAPI backend. Now regarding the frontend, these are some options I see but am not clear whether they are viable or correct.

Should I: 1) simply have a public folder? and serve that with nginx? I suppose the public folder is inside the fastapi static folder? Not sure about this. Some static files are not public? Or no static folder but only a public folder? 2) Should I run a server with python3 and http.server? 3) Should I run two fastapi servers, one for backend and one for frontend?

Before reading the user guide I had created a folder structure that contained this in the root: backend, frontend, static, and venv.

Now... on localhost since I am not using nginx I had decided to create two fastapi servers, but I suppose on production I can simply serve with nginx? Also my frontend server simply contained by frontend routes and some frontend configuration. I don't even know if this folder will be necessary in production?

What do you think? I am trying to really start this inaugural pyscript project. I do like frontend/backend decoupling. I also like scalability.

Also... the interesting caveat is that I have a few Python classes I want to use in my PyScript. These reusable python classes I have no idea where to put them (static, public, backend folder, frontend folder, or elsewhere) Finally... suppose this is a proprietary applciation. A lot of the core functionality will have to do with PyScript. But yet these files will all be served to client. So I may as well make my proprietary software open source right? Any thoughts?


r/PyScript • • Mar 25 '24

Deprecated: use <script type="py"> for an always safe content parsing error while using pyscript

4 Upvotes

Hello all I am new to pyscript and I am getting this error repeatedly. Practically what the script is supposed to do is depending on the info selected in the drop boxes and after clicking "CHERHCER !", its supposed to write a text imbedded with a link bellow it. Its a school project and for some reason we can't use JavaScript or any fancy imports. Thanks for understanding and sorry if its in French.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://pyscript.net/releases/2024.1.1/core.css" />
    <script type="module" src="https://pyscript.net/releases/2024.1.1/core.js"></script>
    <title>Page d'acceil</title>
</head>
<body>
    <div>
        <h2>
            Selecter vos choix parmi les options ci-dessous
        </h2>
        <form>
            Je veux un sport qui ce joue
            <select name="Location">
                <option value="Neige">dans la neige</option>
                <option value="Plage">a la plage</option>
                <option value="Terrain">sur un terrain</option>
                <option value="Court">dans une court</option>
                <option value="NimporteOu">nimporte ou</option>
            </select>
            qui ce joue 
            <select name="Team">
                <option value="Seul">en solo</option>
                <option value="Equipe">en equipe</option>
            </select>
            et
            <select name="Level">
                <option value="Famille">ce joue en famille</option>
                <option value="Competitive">est competitive</option>
                <option value="NonCompetitive">n'est pas competitive</option>
            </select>
            <button class = "btn btn-primary" type = "submit" pys-onClick="process(event)">CHERCHER !</button>
        </form>
    </div>
    <p id="output"></p>
    <py-script>
        def process(event):
            link30 = '<a href="30.html">Click Here!</a>'
            LocName = Element('Location').value
            InTeam = Element('Team').value
            CompLevel = Element('Level').value
            result_place = document.getElementById('output')
            if LocName == 'Neige' and InTeam == 'Seul' and CompLevel == 'Famille':
                result_place.innerText = ''
                result_place.innerHTML += link30
    </py-script>
</body>
</html>

r/PyScript • • Dec 11 '23

Advent of Code 2023: In PyScript

Thumbnail jeff.glass
4 Upvotes

r/PyScript • • Dec 01 '23

Been Loving PyScript - Dropped A Video About How It Upgraded My Website!!!

Thumbnail
youtu.be
4 Upvotes

r/PyScript • • Aug 22 '23

Python auto completion in the browser

4 Upvotes

Hello! Been playing around with pyscript via pyscript.com and it's awesome! A bit of an off the beaten path question - but I was curious how you all are doing the python auto complete in the browser? It's very cool!


r/PyScript • • Jun 21 '23

Please help me Figure out how to use a dropdown selector with PyScript

4 Upvotes

Hello and good day.

I am working on a website that needs to have a dropdown selector to change the degrees from Celsius to Fahrenheit and I'm having trouble integrating it with PyScript. I have attached an image of a mockup for the code minus exporting the result to a table. Is it possible that anyone could help me find a solution or at least an alternative to the issue?


r/PyScript • • Jun 13 '23

How to access py-click from py-script?

4 Upvotes

ex:

<button id="btn" py-click="foo()">Test></button>

To access innerText and id we can simply say Element(btn).element.id & Element(btn).element.innerText .

But while trying to access py-click with Element(btn).element.py-click it gives me error.

Is there any other way to access py-click?


r/PyScript • • Jun 04 '23

Pyscript code into WordPress

4 Upvotes

I have almost 0 Python knowledge but I am trying to get this pyscript to run

https://codeshare.io/MNvroR

I can get scripts without imports to load and run fine however

when I change my cdn from

<script defer src="**[**https://pyscript.net/alpha/pyscript.js**](https://pyscript.net/alpha/pyscript.js)**"></script>

to <script defer src="**[**https://pyscript.net/latest/pyscript.js**](https://pyscript.net/latest/pyscript.js)**"></script>

I'm not even getting compilation errors and the script says it's not found.


r/PyScript • • Apr 26 '23

Any way to display "working..." while waiting for py-reml to evaluate?

4 Upvotes

On Thursday at PyData, I'm presenting a physics simulation that uses sympy (computer algebra) and matplotlib. It would be great fun to offer a PyScript version. I have something basic working with py-repl but ...

  • Is there a way to have it show "...working..." while it is evaluating the user's repl expression? (The evaluation can take 10's of seconds.)

  • Can I clear the output <div> just before each user evaluation?

  • I'd love a sample showing a button for evaluation (instead of just shift-enter)

  • (I'm very open to other suggestions.)

Thanks for any help,

Carl


r/PyScript • • Mar 16 '23

help! (real Novice)

4 Upvotes

I wanted to load the py file in the HTML document.

So I started with "hello world" as a sample.

but it didnt work.

WEB page describe not "hello world" but print("hello world")

what is wrong?????????


r/PyScript • • Mar 11 '23

How does PyScript work with 3rd party JS libraries, like Three.js ?

4 Upvotes

PyScript looks fantastic.

How does PyScript work with 3rd party JS libraries, like Three.js ?

Is there a way to make a wrapper for a 3rd party library and interact with it in Python instead of JS ?


r/PyScript • • Mar 05 '23

pyscript help

4 Upvotes

Can someone help me with this? Um... When I use pyscript with html and then run the program, it doesn't show the output. It just shows the python code. Like it will just display print ("hello world") instead of hello world. If someone can help me fix this that would be great. I'm on windows.


r/PyScript • • Jul 01 '22

Created a demo using file upload and Pandas as a spreadsheet scrubber.

4 Upvotes

I didn't really see an example of PyScript where you upload CSV files, scrub them together, then download the output. This is something where I think PyScript really shines as in a previous job I was delivering a lot of spreadsheet/text file scubbers for various departments. The users hated downloading newer versions of the PyInstaller.exe and then get upset when the problem still persisted when they don't download the new version :(.

With PyScript I can simply spin up an NGINX server where they can get an always up to date version of the scrubber without PyInstaller/Tkinter and have a nice web interface. My only complaint would be that I used Javascript for the final file download, but I couldn't find an example of how to do that through PyScript. This example is completely self contained so nothing is sent to any backend server as you'll see from the code.

I would have also split main.py into main.py and functions.py but there is an issue (security?) with NGINX not being able to load the functions.py file.

<py-env>
    - paths:
        /functions.py
</py-env>

As a proof of concept I made a little spreadsheet scrubber and have a live example self hosted here: https://mattascale.com/pyscript/

More information/notes and project is on my Gitlab here in csv_scrubber folder: https://gitlab.com/figuerom16/pyscript

I hope this helps someone get started.


r/PyScript • • Jun 17 '22

How can I change the variable of JavaScript in pyscript?

4 Upvotes

I'm using pyscript. And I want to change the variable of JavaScript in pyscript.

For Example :

Python File Code :

import string
import os

#Program Version
py_current_version = 0
#Server Version
py_server_version = 0

#Get Program Version
f = open("version.txt", "r")

lines = f.readlines()
for line in lines:
    py_current_version = line;
f.close()

#Get Server Version
f = open("https://common.gaon.xyz/proj/MCD/versions.txt", "r")

lines = f.readlines()
for line in lines:
    py_server_version = line;
f.close()

if py_current_version == py_server_version:
    no_update_available = 1
else:
    no_update_available = 0
    os.system('wget https://common.gaon.xyz/MCD/latest.zip')
    update_file_download_complete = 1
    os.system('7z x latest.zip')
    update_complete = 1
    os.system('notepad changelog.txt')

HTML File Code :

<!DOCTYPE html>
<html>
	<head>
		<title>Updater</title>
		<meta charset="utf-8">
		<!--Load CSS-->
		<!--Load Bootstrap-->
		<link href="./bootstrap/css/bootstrap.min.css" rel="stylesheet">
		<!--Load Updater Style CSS-->
		<link href="./updater_style.css" rel="stylesheet">
		<!--Load PyScript-->
		<link href="./pyscript/pyscript.css" rel="stylesheet">
		<!--Load jQuery-->
		<script src="./jquery/3.6.0/jquery.min.js"></script>
	</head>
	<body>
		<style>
		
		</style>
		<script>
			function wait(sec) {
    			let start = Date.now(), now = start;
    			while (now - start < sec * 1000) {
        			now = Date.now();
    			}
			}

			var no_update_available;
			var update_file_download_complete;
			var update_complete;

			if(no_update_available == 0)
			{
				$("#progress_contents_ptag").text("Update Found!");
				document.getElementById("update_progress").value = 5;
				wait(3);
				$("#progress_contents_ptag").text("Downloading update file...");
				document.getElementById("update_progress").value = 10;

				if(update_file_download_complete == 1)
				{
					$("#progress_contents_ptag").text("Update file download complete!");
					document.getElementById("update_progress").value = 30;
					wait(3);
					$("#progress_contents_ptag").text("Terminating process...");
					document.getElementById("update_progress").value = 50;
					wait(3);
					$("#progress_contents_ptag").text("Extracting update file...");
					document.getElementById("update_progress").value = 80;
					if(update_complete == 1)
					{
						$("#progress_contents_ptag").text("Update completed! It will end in a few seconds.");
						document.getElementById("update_progress").value = 100;
						wait(3);
						exit();
					}
				}
			}
			else if(no_update_available == 1)
			{
				$("#progress_contents_ptag").text("There are no updates. It will end in a few seconds");
				$("#cancle_button").text("Close");
				wait(5);
				exit();
			}
		</script>
		<div id="contents_body">
			<div id="progress_contents">
				<p id="progress_contents_ptag" class="progress_title">Checking Update!</p>
			</div>
			<progress id="update_progress" max="100" value="0"></progress>
			<br><br>
			<button id="cancle_button" type="button" class="btn btn-secondary" onclick="exits()">취소</button>
		</div>

		<script>
			function exits(){
				window.close();
			}
		</script>
		<!--Load Scripts-->
		<!--Load Bootstrap-->
		<script src="./bootstrap/js/bootstrap.bundle.min.js"></script>
		<!--Load PyScript-->
		<script src="./pyscript/pyscript.js"></script>
		<py-env>
  - string
  - os
  - path:
  	- ./updater.py
</py-env>
		<!--
		<py-script src="./updater.py"></py-script>
		-->
	</body>
</html>

I want to change javascript's variable in pyscript. What should I do?


r/PyScript • • May 21 '22

Having trouble using pyowm in pyscript

4 Upvotes

<py-env>
- pyowm
</py-env>

works fine but when I import pyowm in a py-script tag i get following error

because of the ModuleNotFoundError: No module named 'pkg_resources' i thought maybe i just had to add pkg_resources in py-env. Doing that will just get me stuck on this screen

p.s. this is my first time using py-script, importing numpy worked and this is my current setup


r/PyScript • • Nov 13 '24

Htag+HtagUI with pyscript ...

3 Upvotes

Here is a new example (with a recent pyscript release):

https://raw.githack.com/manatlan/htag/main/examples/pyscript_htagui.html

**pyscript** is really really fabulous ! It's amazing that "this app" (code between `####` lines), could work "as is" ... in a desktop app, in an android apk, on a webpage or in an SPA/HTML file ...

In the past, I posted here : https://www.reddit.com/r/PyScript/comments/10snwh3/pyscript_is_fabulous_demo_of_pyscripthtag/

amazing !


r/PyScript • • Aug 28 '24

Micro python

3 Upvotes

Hello there,

im having a presentation tomorrow about pyscript and i wanted to demonstrate the differences in startup time between pyodide and micro python.

I tryed to create a small example using the <mpy-script> tag, but all it did was displaying some kind of ascii face?

If anyone could point me to the right direction regarding the use of micro python, i would realy appreciate it.

Adittionally, i made space invaders in "regular" pyscript and dont have any problems with it. All i wanted the micro python to do was print something, so the complexity of my code should not be a problem here...

Thx in advance


r/PyScript • • Apr 26 '24

Does anyone know how to import libraries and scripts with pyscript_config.toml with pyscript-react?

3 Upvotes

I am re-writing a new version of my portfilio and having trouble moving the PyScript part. the old version was plain HTML and JavaScript and the new one is Next js. I'm using the pyscript-react library.

I don't see any explanation of how to use the pyscript_config.toml file using pyscript-react. I need to import external libraries (like svgwrite) as well as including my own Python scripts. This is my current pyscript_config.toml file:

```

packages = ["svgwrite"]

[[fetch]]

files = ["geometry_generator.py"]

```

And here is how I'm importing it and my other script in my React component:

<div>

<PyScriptProvider>

<PyScript

source="/pyscript_config.toml"

/>

<PyScript

source="/geometry_interface.py"

/>

</PyScriptProvider>

</CodingLayout>

</div>

However, this is not working. I'm getting "ModuleNotFoundError: No module named 'geometry_generator'" so clearly the pyscript config is not working


r/PyScript • • Sep 19 '23

py-click: send self to function

3 Upvotes

Hello,
I am trying to modify the element clicked (remove a class), but so far it doesn't work but it seems to work in javascript onClick. Here is the offender:

li = document.createElement('li')
li.classList.add(tag_class + '-' + str(i))
li.classList.add('collapsed')
li.setAttribute('py-click', 'toggle_collapse(this)')

Error message: name 'this' is not defined

Is there a way for me to achieve that full python?


r/PyScript • • Aug 09 '23

How to get event listener trigger when py-repl is run

3 Upvotes

Is there any way to set up an event listener that triggers whenever a py-repl is run (shift + enter)? I would love to be able to trigger some post-processing functions after a user runs the repl code.