Upload csv file in Anvil with uplink

1.8k Views Asked by At

I have an error like this:

TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given at <ipython-input 4-66c1c8f89515>, line 8 called from Form1, line 18

this my code in anvil:

class Form1(Form1Template):
def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

  def file_loader_1_change(self, file, **event_args):
    """This method is called when a new file is loaded into this FileLoader"""
    anvil.server.call('import_csv_data',file)

and this code in jupyter notebook for upload the data to anvil data table:

import pandas as pd
import anvil.tables as tables
from anvil.tables import app_tables
import anvil.media

@anvil.server.callable
def import_csv_data(file):
  with anvil.media.TempFile(file, "r") as f:
    df = pd.read_csv(f)
    for d in df.to_dict(orient="records"):
      # d is now a dict of {columnname -> value} for this row
      # We use Python's **kwargs syntax to pass the whole dict as
      # keyword arguments
      app_tables.NilaiTukar.add_row(**d)
1

There are 1 best solutions below

1
RaspberryCheesecake On

I think the error you saw is because you are giving two arguments to anvil.media.TempFile and it is only designed to take one. I replicated your error with a simpler example:

import anvil.media

@anvil.server.callable
def import_csv_data(file):
  with anvil.media.TempFile(file, "r") as f:
    pass

if __name__ == "__main__":
  import_csv_data("fname.txt")

According to the docs you don't need the "r" argument. You should just call:

@anvil.server.callable
def import_csv_data(file):
  with anvil.media.TempFile(file) as f:
    ...

Then it should work for you.