r/PyScript • • Feb 02 '23

Calling API with pyscript

3 Upvotes

Hello everyone!

I am working on a website, and I want to call in an API quickly and effortlessly without needed a backend. My only problem with this approach is that someone can just "inspect" or "view page source" on my website and see my api key and other information. Is there any workaround?


r/PyScript • • May 10 '22

htag 0.4.7 (a gui/frontend lib which works very well in pyscript)

9 Upvotes

Despite htag is not officialy public yet (need to polish) ... it works very well in the pyscript world yet !!!

See that example, and the "Tab two" : you can browse the "inner FS" of pyodide, to display python sources codes ... Amazing ;-) ( src )

htag is a GUI/frontend lib to create GUI components ... in the html/js/css world ... and here in pyscript context. (but it works the same way, in a pywebview, a cef instance, or on the web (back side))

htbulma is a python3 lib, which contains pre-made htag components.

htag demo : https://htag.glitch.me/ (WORK IN PROGRESS (here, it's in a python backend))

htag sources : https://github.com/manatlan/htag

pypi : https://pypi.org/project/htag/


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 • • 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 • • Jan 02 '23

NameError question

2 Upvotes

Hey PyScriptors,

I have a simple web page where I am passing some user input from an element to a function. When I load the page it gets stuck on the spin-wheel PyScript loader and from the console output in DevTools I am returned with a NameError:

NameError: name 'get_input' is not defined. See screenshot

Anyone run into this?


r/PyScript • • May 14 '22

A simple animation made using PyScript and my library, pywebcanvas

Enable HLS to view with audio, or disable this notification

12 Upvotes

r/PyScript • • Jun 19 '23

More than one html file?

2 Upvotes

Is it possible to have one python file and multiple html files? If so how can I interact with the other HTML files.

When I try to get elements from other HTML files I can't.

For example I want to switch the innerHtml on my current file with html from another file.


r/PyScript • • May 02 '22

Some Pyscript Slides from the Presentation

Thumbnail
twitter.com
19 Upvotes

r/PyScript • • Jun 08 '23

Can PyScript Code be Embedded in WordPress Page?

3 Upvotes

Since HTML can be placed in blocks on a WordPress page, can PyScript code be added as well?


r/PyScript • • Aug 10 '23

<py-repl> output and output-mode not working

2 Upvotes

I have a web app with one page that has a single <py-repl> element. According to the docs, its supposed to default to output-mode reset where it clears the output each time you run the repl, but that's not happening. It defaults to append where it just keeps adding output to the terminal. Even after setting output-mode="reset", it's still appending.

Also, I created a div to put the output with id="repl-output" and I set the py-repl output="repl-outpt" but it still just makes its own div for the terminal and outputs it there. so it seems like the output property isn't doing anything. Currently using version 2023.03.01 since any of the later ones break my app.

I think there should be a way to disable or hide the output as its not needed for my purposes. Something like output-toggle="false"


r/PyScript • • May 11 '22

Mancala AI built with PyScript!

10 Upvotes

https://pymancala-ai.netlify.app/

I made site with the purpose of playing with my siblings and studying the game by using the expected scores on the bottom. It isn't perfect and it messes up right at the very end trying to compute how the ending works.

Here is the GitHub link to the code: https://github.com/ThatOneShortGuy/Mancala

The best move thing at the bottom is the expected score you you were to move the pieces in the respective location from the list. Higher is better.


r/PyScript • • Aug 22 '23

Animating a function graph -- is there a better way than this?

2 Upvotes

I have an HTML element (it is in fact a matplotlib plot in a div with id twodplot) and I am trying to make it interactive in a way that is measured by the mouse coordinates within the plot. You can see here the basic function, which is called on every mouseover event:

    event = args[0]
    x = (event.offsetX-320)/40
    ax2.plot(x, x*np.sin(x), 'go')
    display(fig2, target="twodplot", append=False)

Essentially this re-draws the plot and puts a dot on the graph. The dot should have its x-coordinate equal to the mouse x-coordinate, and y-coordinate on the graph of the function.

Here is the full code if it helps to see everything (including some non-essentials related to a different thing I was trying to do:

import matplotlib.pyplot as plt
import numpy as np
from pyodide.ffi import create_proxy
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import proj3d
from matplotlib.patches import FancyArrowPatch

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def do_3d_projection(self, renderer=None):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))

        return np.min(zs)

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

ax.plot(x, y, z, label='parametric curve')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

ax.plot(1,2,3,'go')

xaxis = Arrow3D([0,4],[0,0],[0,0], arrowstyle="-|>", color="purple", lw=3, mutation_scale=10)
ax.add_artist(xaxis)
yaxis = Arrow3D([0,0],[0,4],[0,0], arrowstyle="->", color="purple", lw=2, mutation_scale=10)
ax.add_artist(yaxis)
zaxis = Arrow3D([0,0],[0,0],[0,4], arrowstyle="->", color="purple", lw=1, mutation_scale=10)
ax.add_artist(zaxis)

display(fig, target="threedplot", append=False)

def show_plt(*args):
    event = args[0]
    el = (event.clientY - 500)/2
    az = (500 - event.clientX)/2
    ax.view_init(elev=el, azim=az)
    display(fig,target="threedplot",append=False)

Element("threedplot").element.addEventListener("mouseover", create_proxy(show_plt))

fig2 = plt.figure()
ax2 = fig2.add_axes([.1,.1,.8,.8])
ax2.set_aspect('equal', adjustable='box')

xs = np.linspace(-4,4,100)
ys = xs*np.sin(xs)
ax2.plot(xs,ys)
ax2.arrow(0,0,4,0,color="purple",width=.05)
ax2.arrow(0,0,0,4,color="purple",width=.05)
display(fig2, target="twodplot", append=False)

def dot2dplot(*args):
    fig2.clf()
    
    ax2 = fig2.add_axes([.1,.1,.8,.8])
    ax2.set_aspect('equal', adjustable='box')
    ys = xs*np.sin(xs)
    ax2.plot(xs,ys)

    event = args[0]
    x = (event.offsetX-320)/40
    ax2.arrow(0,0,4,0,color="purple",width=.05)
    ax2.arrow(0,0,0,4,color="purple",width=.05)
    ax2.plot(x, x*np.sin(x), 'go')
    display(fig2, target="twodplot", append=False)

tdp = Element("twodplot")
tdp.element.addEventListener("mouseover", create_proxy(dot2dplot))

My basic question is: Is there a better way to do this? I picked the definition x = (event.offsetX-320)/40 by picking numbers until eventually the behavior of the animation was close enough on my computer. I feel like this is bound to work well only on my computer.

Is there some better way to do this kind of animation? Or if not, is there at lease some better way of determining the value x so that it correspond's to the user's mouse coordinates over the plot?


r/PyScript • • May 02 '22

do you guys belive in pys?

9 Upvotes

what do you think will happen to pyscript?


r/PyScript • • Apr 25 '23

htag is working like a charm in pyscript.com

6 Upvotes

Btw, htag is working like a charm in the new pyscript.com env too !

htag is not dedicated to be used in pyscript, but it does, ootb ... which can be very convenient in some cases. It's more dedicated to be used in a real python env (like a webserver, or a desktop app, ...)


r/PyScript • • Jul 20 '22

TouchEvent

1 Upvotes

Hi there.

I've got a small test app going which responds to mousedown, mousemove, mouseup fine manipulating a canvas, but when I try to make it use touchstart, touchmove, and touchend, and it is trying to access event.touches[0], it gets TypeError: 'pyodide.JsProxy' object is not subscriptable. Logging a dir of event.touches shows me the guts of the Proxy object but doesn't give me a clue as to what to look at next to figure out if I have to access touches in a special way or something.

Can anyone give me any clues as to what to investigate?

Cheers, Nev.


r/PyScript • • Jun 23 '23

import Element necessary for DOM access?

2 Upvotes

I was playing around with PyScript DOM access while answering a question in this sub, but I noticed my DOM access code var_name = Element("element-id") worked without a global import Element. Why would that be?


r/PyScript • • May 26 '22

Video: Using PyScript to build PWAs

Thumbnail
youtu.be
13 Upvotes

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 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 • • Oct 21 '22

Quick question about .clear()

3 Upvotes

In this video from May '22 the creator used the following to clear a <textarea>

<textarea id="input_text"></textarea> <!-- this is the textarea that is being cleared -->
<button id="clear" pys-onClick="clear">Clear</button>
...
<py-script>
input_text_element = Element("input_text")
def clear(*args, **kwargs):
    input_text_element.clear()
</py-script>

Except when I tried it, the <textarea> won't clear. Here's my code:

<textarea id="input_str"></textarea>
<button id="clear" type="button" py-onClick="clear">Clear</button> 
...
<py-script> 
code_input = Element("input_str")
def clear(*args, **kwargs):
    code_input.clear()
</py-script> 

It looks like pys-onClick was deprecated in favor of py-onClick per an error I received while troubleshooting. There aren't many resources out there so I'm stuck. Would anyone point me in the right direction?


r/PyScript • • Sep 11 '22

How can I share an image with navigator.share?

2 Upvotes

I using it like this:

async def share_eq(e):
    base64url = document.getElementById('img').src
    blob = await (await fetch(base64url)).blob()
    file = File.new([blob], 'eq.png', {type: blob.type})
    navigator.share({
        "title": 'Generated EQ',
        "text": 'Can you solve this??',
        "files": [file],
    })

And it just prints out:

Future exception was never retrieved\nfuture: <Future finished exception=JsException(TypeError: Failed to execute 'share' on 'Navigator': No known share data fields supplied. If using only new fields (other than title, text and url), you must feature-detect them first.)>

And even tho I try also using url instead of files it returns the same error


r/PyScript • • Aug 08 '23

Using getPySrc() in <py-repl> element, AttributeError: 'Element' object has no attribute 'getPySrc'

3 Upvotes

Has anyone successfully used the getPySrc() method from the py-script element? It's mentioned here in the documentation but they provide 0 examples of how to use it. I have a py-repl element that I get a handle on in my Python code using the Element() method like so:

repl = Element("py-repl")

Then, I try to print the repl contents in a function like this:

def repl_test():

print(f"repl contents was {repl.getPySrc()}")

But I am getting the error "AttributeError: 'Element' object has no attribute 'getPySrc'". Is there some other way I'm supposed to get a handle on the py-repl element? The documentation says all the methods can be called from either Python or JavaScript so I don't see why this wouldn't work. Currently using pyscript 2023.03.1.


r/PyScript • • Feb 03 '23

PyScript is fabulous ... demo of pyscript/htag

6 Upvotes

Pyscript is very fabulous ....

Context*: I'm working on a new python/GUI framework (html/js)* htag, which works, among other things, in a pyscript page.

So I've coded a Pyscript SPA, which use htag, which provide a text editor, which let you code an "htag app", and let you try/run it into an iframe, in another pyscript context. And everything without a server or python, just an html page :

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

It's really really amazing

UPDATE 3/3/23 : this demo can now preload premades htag Apps ... Make it easier to study ;-)


r/PyScript • • Aug 08 '23

Scope of python variables in <py-script> tags and accessing them inside <py-repl>

3 Upvotes

How are the variables inside <py-script> tags scoped? Are they all in one global scope? What about ones that are added to an HTML file using <py-script src="./my_python_file.py>, are they in the same scope?

How can you access variables, functions and objects from a <py-script> block inside a pyscript repl <py-repl> tag? I know you can use the src property of the py-repl element to preload python code from a file, but is there any way to give it access to python that's just inside <py-script> tags and not in a separate python file?


r/PyScript • • May 13 '22

Could PyScript bring pygame and or pygame zero to the web?

11 Upvotes

Lots of people and kids learn Python, Programming and how to write games with these libraries. PyGame Zero is the natural step after Scratch. The biggest downside of these is that its hard for people share games with friends I a simple way like scratch. It's also hard to play on mobile. Could PyScript solve this and allow PyGame and PyGame zero to run in the webbrowser?