0

I have this project where I have to display the date time on my website using Python and HTML by using PyScript. I have two files;

File source.py

import datetime as dt

pyscript.write('date',dt.datetime.today())

File index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hi</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
    <div id="date"></div>
    <py-script src="source.py"></py-script>
</body>
</html>

But when I reload my website the page displays this: JsException (TypeError: Failed to fetch). How do I fix this error and what is the explanation behind this occurrence?

2

2 Answers 2

0

The reason that you are getting this error is because py-script needs a server to pull the contents from. You can simply navigate to your projects directory and open a new terminal window, or simply cd into that folder path. Next, once you are in the directory run this command

$ python -m http.server 8080

This will run a localhost server displaying all contents from that directory. On your browser now you should be able to access it by entering in the address bar:

localhost:8080

Lastly, you must define the python script in the head tag. e.g.

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

code example:

index.html

<html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
        - paths:
          - ./pytest.py
      </py-env>
    </head>
  <body>
    <h1>Update HTML from PYTHON</h1>
    <b> <label id="output"></label></b>
    <py-script>
      from pytest import function
      pyscript.write('output', function())
    </py-script>
  </body>
</html>

pytest.py

def function():

    output = 'CONGRATS!'


    return ('Your Data has been extracted from a python script: '+''.join(output))
Sign up to request clarification or add additional context in comments.

Comments

-1

Was your URL look like this and said failed after pressing the reload button in Chrome:

Error screenshot

Use the Live Server extension in Visual Studio Code to solve this error. Because you need a server for PyScript to work.

Live Server extension

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.