docassemble

Access file processed by a module in DocAssemble interview


I've written a python module which generates an image from a bunch of values as plot. The module uses matplotlib and pandas for the generation of the image. Now I'm a bit in trouble accessing the image from inside DocAssemble to put the image into a docx template. Therefore I've some questions:

  1. The image will be saved within the module in /usr/share/docassemble/files/image.png. I don't think that this is the proper path to save files in DA. Where can I save such files to be accessed in the later interview?
plt.savefig("/usr/share/docassemble/files/image.png")
  1. What is the right way to implement the image from such a path into a docx document using DA YAML?

extract from da yml file

---
modules:
  - .plot_file
[...]
---
code: |
 plot_file(datapoints)

Solution

  • You can initialize a DAFile object in your YAML and then pass that object to your plot_file() function. Your plot_file() function can write data to the path indicated by .path() and then run .commit(). This will ensure that your code works properly even if the server keeps its files on S3.

    modules:
      - .plot_file
    ---
    objects:
      - myfile: DAFile
    ---
    code: |
      plot_file(datapoints, myfile)
    

    Then in your module you could do something like:

    def plot_file(datapoints, the_file):
      the_file.initialize(filename="plot.png")
      ...
      with open(the_file.path(), 'rb') as file_pointer:
        file_pointer.write(data)
      the_file.commit()
    

    See the first example in this section for an example.

    Docassemble is designed to be a cloud-based application, so you can't assume that the machine that processes a request at time 1 will be the same machine that processes a request at time 2. That is why files are abstracted as DAFile objects; the DAFile code takes care of storing the file on S3 and retrieving it from S3. The DAFile class also provides a permissions system so that other users on the server can't access your file unless you have specifically called .set_attributes() or .user_access() in order to grant permission.