Trying to import libraries on brython but the site sees them as .py files and not as folders with .py files

56 Views Asked by At

I have a site on GitHub pages, and I'm trying to import libraries on Brython.

I have the project settled like this:

Project
   -index.html
   -brython.js
   -library1
       -__init__.py
       -file1.py
       -file2.py
       -...
    -library2
       -__init__.py
       -file1.py
       -file2.py
       -...
    -library3
       -__init__.py
       -file1.py
       -file2.py
       -..

I want to import all modules from the libraries, but if I use import when I go to the site console, it tells me it can't find the init.py file and that it can't find library1.py like it's trying to import a single module and not all of them.

I tried looking on internet but didn't find anything that could help me, I even used ChatGPT but it's useless.

I see that some says that it's impossible to import local libraries, but the official Brython site says, that I can, so I don't know, I'm really confused by the answers on the other questions.

1

There are 1 best solutions below

1
Jasmijn On

According to Brython documentation:

The HTML files stored in a computer can be loaded in the browser in two different ways:

  • by the File / Open browser menu: in this case the browser uses the "file" protocol (the address in the address bar starts with file://)
  • by launching a local web server (for instance the one provided by Python standard distribution: python -m http.server) and entering the file address in the browser address bar (for instance localhost:8000//app.html). The protocol is "http" (or "https")

These options are mostly the same, but the "file" protocol comes with a few limitations:

  • external scripts cannot be loaded with the syntax <script type="text/python" src="test.py">
  • it is not possible to import modules or packages located in the same directory as the application files cannot be opened and read with open()

The reason is that these features rely on Ajax calls to get the modules / packages source code, or the file contents; and browsers do not allow making Ajax calls when the protocol is "file".

(Emphasis mine.)

I recommend you try running something like python -m http.server in the Projects directory, and then opening http://localhost:8000/index.html in your browser`.

If that doesn't help, please edit your question to include additional information like error tracebacks, and how your code imports your library modules exactly.