From pyscript, how can I access the file that I load from html?

Viewed 140

This is the html input from which I load my file

<input type="file" id="fasta_1" accept=".fasta" class="form-control-file">

And this is the block of code from which I try to access the file but it doesn't work for me.

fasta_1 = Element("fasta_1")

document = fasta_1.element.files[0]
    print(document)
    #document = evt.target.files[0]
    #with open(document, "r") as f:
        #txtread = f.read()
        #print(document)
1 Answers

For security reasons you should create a file listener and use pyodide's create_proxy to load a local file and then process the file asynchronously. It looks like this
index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href=pyscript.css" />
        <script defer src="pyscript.js"></script>       
        
<!--    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
        <script defer src="https://pyscript.net/alpha/pyscript.js" onerror=scriptLoadFailure('pyscr ipt.js')></script>      -->

<py-env>
paths:
    ./main.py
</py-env>
    </head>

    <body>
<py-script id="main" src="./main.py"></py-script>

    <input type="file" id="fasta_1" accept=".fasta" class="form-control-file">
    <div  id="outMsg"></div>
    </body>
</html>

And your main.py script (I put it in src attribute of py-script node of index.html) creating a proxy and processing the file that you choose.
main.py

import asyncio
from pyodide import create_proxy
#
#
def Setup_File_Listener():
    file_event = create_proxy(Process_File)
    e = document.getElementById("fasta_1")
    e.addEventListener("change", file_event, False)
#
#
async def Process_File(event):
    fileList = event.target.files.to_py()

    for f in fileList:
        data = await f.text()
        show_data(data)     #  OR do something else with the data
#
#        
def show_data(data):
    document.getElementById("outMsg").innerHTML = data

#   -----------------------------------------------------
Setup_File_Listener()

This way browser waits for a change event to happen on your input file element and then the file event defined in listener (Process_File()) activates asynchronous processing the file. More about it at: https://www.jhanley.com/pyscript-javascript-callbacks/

Related