Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python for frontend !
#1
Heart 
Hi,

While I was looking how to use Python for the front-end
I discover a great suggestion on the Mozilla "ideas box" aka connect, so I'll share it with you.

https://connect.mozilla.org/t5/ideas/gec...di-p/20158

I'll make an account and up vote this ideas !

Cheers.
[Image: NfRQr9R.jpg]
Reply
#2
We need more voters!
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
I don't think that this idea/requests will gain any traction or replies that are positive.
JavaScript is to deep into the browser HTML DOM implementations

Brython ok try,but i don't thin that is the right way forward.
I think the PyScript is a step forward in right direction.
So can run Python code in html example with a Python function.
Need no server,just run as eg joke.html .
<head>
  <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head> 
    
<py-script>
import random

def joke() -> str:
    """Return a random joke"""
    lst = [
        "I've got a really good UDP joke to tell you but I don’t know if you'll get it.",
        "Debugging: Removing the needles from the haystack.",
        "# This line dos nothing,but the code stops working when I delete it.",
    ]
    return random.choice(lst)

print(joke())
</py-script>
So one of the problem now is that runtime load time is to high,
saw that they did test with MicroPython which will give much lower runtime.
MicroPython + Pyscript: Is this finally Python on the Frontend?

htmx is for me one the best new tool out there for simplify web-development.
To give a simple example all in one file,
so this dos call(AJAX call no page reload) when push button to get new joke,see that no JavaScript is used all is done in HTML.
from flask import Flask, render_template
import random

app = Flask(__name__)
@app.route("/")
def index():
    return """\
    <head>
      <title>Some title</title>
      <script src="https://unpkg.com/[email protected]"></script>
    </head>
    <body>
      <h1>Get a random joke</h1>
      <button hx-get="/joke" hx-target="#output">Get a Joke</button>
      <p id="output"></p>
    </body>"""

@app.route("/joke")
def joke() -> str:
    """Return a random joke"""
    lst = [
        "If Bill Gates had a dime for every time Windows crashed ... Oh wait, he does.",
        "Debugging: Removing the needles from the haystack.",
        "# This line doesn't actually do anything, but the code stops working when I delete it.",
    ]
    return random.choice(lst)

if __name__ == "__main__":
    app.run(debug=False)

One more with PyScript,so can use many libraries they build in.
<head>
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>  
</head>  
<py-env>
  - numpy
  - matplotlib
  - pandas
</py-env> 
     
<py-script>
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
 
df = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
fig, ax = plt.subplots()
df.plot.area(ax=ax)
plt
</py-script>
[Image: naMD1O.png]
Larz60+ and rob101 like this post
Reply
#4
(Dec-09-2022, 06:07 PM)snippsat Wrote: I don't think that this idea/requests will gain any traction or replies that are positive.
JavaScript is to deep into the browser HTML DOM implementations
Exactly ! That why it's has to evolve !
If your look the definition of the HTML DOM in Wikipedia-->
wikipedia Wrote:... is a cross-platform and language-independent interface ...
But indeed as you point out, the current internet Browsers only focus on Javascript, letting all the other languages on the side. So let vote to change this !

(Dec-09-2022, 06:07 PM)snippsat Wrote: Brython ok try,but i don't thin that is the right way forward.
I've tried, and also developed a neat front-end tool with and the loading time is way faster than PyScript.
The documentation could be improved, (but that's the case for a lot of project)

I took a look at htmx whooo Shocked that look very efficient !! Thanks ! Thumbs Up
I will test it asap !
[Image: NfRQr9R.jpg]
Reply
#5
Question 
(Dec-09-2022, 06:07 PM)snippsat Wrote: htmx is for me one the best new tool out there for simplify web-development.
To give a simple example all in one file,
so this dos call(AJAX call no page reload) when push button to get new joke,see that no JavaScript is used all is done in HTML.
from flask import Flask, render_template
import random

app = Flask(__name__)
@app.route("/")
def index():
    return """\
    <head>
      <title>Some title</title>
      <script src="https://unpkg.com/[email protected]"></script>
    </head>
    <body>
      <h1>Get a random joke</h1>
      <button hx-get="/joke" hx-target="#output">Get a Joke</button>
      <p id="output"></p>
    </body>"""

@app.route("/joke")
def joke() -> str:
    """Return a random joke"""
    lst = [
        "If Bill Gates had a dime for every time Windows crashed ... Oh wait, he does.",
        "Debugging: Removing the needles from the haystack.",
        "# This line doesn't actually do anything, but the code stops working when I delete it.",
    ]
    return random.choice(lst)

if __name__ == "__main__":
    app.run(debug=False)

@snippsat (or anyone) what does the -> str: in line 19 ?

Thanks.
[Image: NfRQr9R.jpg]
Reply
#6
It's called a type hint: https://docs.python.org/3/library/typing.html.
SpongeB0B likes this post
Reply
#7
(Dec-24-2022, 10:36 AM)ndc85430 Wrote: It's called a type hint: https://docs.python.org/3/library/typing.html.

so if I understand well -> str: mean that the output of the function has to be a String ? right ?
[Image: NfRQr9R.jpg]
Reply
#8
Yes. I don't know how much the implementation enforces that, but the documentation should say I assume.
Reply
#9
To make a more realistic joke app bye using two Api's.
Using Flask, Bulma and htmx
So look like this,htmx doing all call(Ajax) in HTLM this simplify stuff a lot,and not one line of JavaScript is needed.
[Image: xYzoD9.png]

Folder setup.
joke
  |-- app.py
  templates\
    |-- index.html
app.py:
from flask import Flask, render_template, jsonify, request
import requests
import random

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/chuck")
def chuck():
    url = "https://api.chucknorris.io/jokes/random"
    response = requests.get(url)
    chuck_joke = response.json()["value"]
    return chuck_joke

if __name__ == "__main__":
    app.run(debug=False)
index.html:
<!DOCTYPE html>
<html class="has-background-link-light">
<head>
  <title>Joke of the day</title>
  <script src="https://unpkg.com/[email protected]"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
  <link href="https://fonts.googleapis.com/css?family=Delius Swash Caps" rel="stylesheet" type="text/css">
</head>

<style>
  h2,
  #info {
    font-family: 'Delius Swash Caps', sans-serif;
    font-weight: regular;
    text-shadow: none;
    text-decoration: none;
    text-transform: capitalize;
  }
</style>

<body>
  <section class="section">
    <div class="container">
      <div class="columns is-multiline is-centered">
        <div class="column is-6 has-text-centered">
          <h2 class="mt-2 mb-4 is-size-1 is-size-3-mobile has-text-weight-bold has-text-info-dark">Get a Joke of the
            day</h2>
          <p id='info' class="subtitle has-text-grey mb-5 is-size-4">Joke from Api or Local from disk</p>
          <div class="buttons is-centered">
            <a class="button is-primary has-text-link-dark"
              hx-get="https://v2.jokeapi.dev/joke/Any?format=txt&safe-mode" hx-target="#output_api">Joke from API</a>
            <a class="button is-warning ml-4 has-text-dark" hx-get="/chuck" hx-target="#output_api">Chuck Norris Joke</a>
            <a class="button is-danger ml-4 has-text-warning" hx-get="/chuck" hx-target="#output_api"
              hx-trigger="mouseenter">Mouse over Chuck Joke  </a>
            <figure class="image is-128x128 mt-5">
              <img class="is-rounded" src="https://cdn-icons-png.flaticon.com/512/235/235916.png">
            </figure> 
          </div>
          <p id="output_api" class="subtitle is-size-4 has-text-warning-dark mt-6"></p>
        </div>
      </div>
    </div>
  </section>
</body>
</html>
Reply
#10
(Dec-09-2022, 06:07 PM)snippsat Wrote: ....
htmx is for me one the best new tool out there for simplify web-development.
To give a simple example all in one file,
so this dos call(AJAX call no page reload) when push button to get new joke,see that no JavaScript is used all is done in HTML.

Hi everyone, one year have passed !
during that time I have developed with htmx (Thanks @snippsat).
Meanwhile I've discovered that Bryton can also do XMLHttpRequest (aka Ajax) and OMG Heart when you're a Python developer this is so fitting so well and way more powerful than htmx ! So if you're using Brython, no need anymore to load and use htmx :D

I hope my experience can benefit the community.

Cheers
[Image: NfRQr9R.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python frontend workout plan karateobituary 1 3,221 Aug-31-2020, 12:41 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020