### Install and Configure PostgreSQL Server
Source: https://docassemble.org/docs/scalability.html
Commands to install, initialize, start PostgreSQL, and create a user and database for Docassemble. Ensure you set a strong password when prompted.
```bash
sudo yum install postgresql-server
sudo service postgresql initdb
sudo service postgresql start
sudo -u postgres createuser --login --pwprompt docassemble
sudo -u postgres createdb --owner=docassemble docassemble
```
--------------------------------
### Start Docker Service on Linux
Source: https://docassemble.org/docs/docker.html
Commands to start the Docker service if it does not start automatically after installation.
```bash
sudo systemctl start docker
```
```bash
sudo service docker start
```
```bash
sudo /etc/init.d/docker start
```
--------------------------------
### Configure Example Interview Metadata
Source: https://docassemble.org/docs/config.html
Use `metadata` headers within example interview YAML files to control titles, documentation links, and which blocks are displayed in the Playground. `example start` and `example end` specify the visible blocks.
```yaml
metadata:
title: Test Slack Posting
short title: Test Slack
documentation: "https://michigan.example.com/docs/using_slack.html"
example start: 1
example end: 2
---
question: |
What do you want to post on Slack?
fields:
- Message: the_message
---
code: |
post_to_slack(the_message)
message_posted
```
--------------------------------
### Install Docker
Source: https://docassemble.org/docs/docker.html
Instructions for installing Docker on various operating systems. Ensure Docker is installed before proceeding.
```bash
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
```
--------------------------------
### Organizer Introduction
Source: https://docassemble.org/docs/roles.html
Presents an introductory question for the organizer role, guiding them to the start of the multi-user process.
```text
field: introduction_made
question: |
Welcome to a test of the multi-user system!
subquestion:
This is the start of a test of the multi-user system.
You are the organizer. To continue, press **Continue**.
---
```
--------------------------------
### Interview Menu Example
Source: https://docassemble.org/docs/config.html
An example interview that mimics the standard start page by using the `interview_menu()` function to list available interviews. It displays interviews as a list with titles and links.
```yaml
code: |
available_interviews = interview_menu()
---
prevent going back: True
mandatory: True
question: |
Available interviews
subquestion: |
% if len(available_interviews) > 0:
% for interview in available_interviews:
* [${ interview['title'] }](${ interview['link'] })
% endfor
% else:
There are no available interviews.
% endif
```
--------------------------------
### Install Package and Wait for Restart
Source: https://docassemble.org/docs/api.html
Installs a PyPI package and then uses the `wait_for` function to monitor the server's restart process after the installation.
```python
r = requests.post('http://localhost/api/package', json={'pip': 'jsmin'}, headers=headers)
if r.status_code != 200:
sys.exit(r.text)
info = r.json()
wait_for(info['task_id'])
```
--------------------------------
### Database Configuration Example
Source: https://docassemble.org/docs/objects.html
Example of a database configuration block for 'demo db' using alchemy_url().
```yaml
demo db:
name: demo
user: jsmith
password: supersecret
```
--------------------------------
### Install Behave and Dependencies
Source: https://docassemble.org/docs/development.html
Install Behave, Selenium, and webdriver-manager using pip. Ensure Google Chrome is installed beforehand.
```bash
pip install behave selenium webdriver-manager
```
--------------------------------
### Package Installation and Status Polling
Source: https://docassemble.org/docs/api.html
Shows how to install a package and then poll the server status to determine when the installation is complete.
```APIDOC
## POST /api/package and GET /api/package_update_status
### Description
Installs a package via the API and provides a mechanism to poll for the completion status of the installation task.
### Method
POST (for /api/package), GET (for /api/package_update_status)
### Endpoint
/api/package
/api/package_update_status
### Parameters
#### Request Body (/api/package)
- **pip** (string) - Required - The name of the pip package to install.
#### Query Parameters (/api/package_update_status)
- **task_id** (string) - Required - The ID of the task to check the status for.
### Request Example
```python
import sys
import time
import requests
from requests.exceptions import Timeout
headers = {'X-API-Key': 'H3PLMKJKIVATLDPWHJH3AGWEJPFU5GRT'}
def wait_for(task_id):
while True:
try:
r = requests.get('http://localhost/api/package_update_status',
params={'task_id': task_id},
headers=headers,
timeout=7)
except Timeout:
continue
if r.status_code != 200:
sys.exit(r.text)
info = r.json()
if info['status'] == 'completed':
break
time.sleep(2)
r = requests.post('http://localhost/api/package', json={'pip': 'jsmin'}, headers=headers)
if r.status_code != 200:
sys.exit(r.text)
info = r.json()
wait_for(info['task_id'])
```
### Response
#### Success Response (200) (/api/package)
- **task_id** (string) - The ID of the initiated task.
#### Success Response (200) (/api/package_update_status)
- **status** (string) - The current status of the task (e.g., 'completed', 'running').
```
--------------------------------
### Install Let's Encrypt
Source: https://docassemble.org/docs/installation.html
Clones the Let's Encrypt repository into the docassemble installation directory.
```bash
cd /usr/share/docassemble
git clone https://github.com/letsencrypt/letsencrypt
```
--------------------------------
### Configure Supervisor to Start After Services
Source: https://docassemble.org/docs/installation.html
Sets up systemd to ensure the supervisor service starts only after PostgreSQL, Redis, and RabbitMQ have started.
```bash
sudo systemctl edit supervisor.service
[Unit]
After=rabbitmq-server.target postgresql.target redis-server.target
```
--------------------------------
### Example: Navigating Interview Flow
Source: https://docassemble.org/docs/functions.html
Demonstrates a sequence of setting sections to guide the user through different parts of the interview, including contact, demographics, preferences, and conclusion.
```python
sees_nav_bar
nav.set_section('about')
intro_to_about_you
nav.set_section('contact')
first_name
email_address
nav.set_section('demographic')
gender
belly_button
nav.set_section('prefs')
favorite_fruit
favorite_vegetable
nav.set_section('conclusion')
final_screen
```
--------------------------------
### Install a docassemble package without restarting
Source: https://docassemble.org/docs/development.html
Install a package without restarting the server. This is faster but only works on single-machine servers.
```bash
dainstall --norestart docassemble-custody
```
--------------------------------
### Build Google API Service with DAGoogleAPI
Source: https://docassemble.org/docs/objects.html
This example demonstrates how to create a Google API service client, specifically for the 'translate' API, using the DAGoogleAPI object in Docassemble. Ensure the 'apiclient' library is installed.
```python
import apiclient
import docassemble.base.util
api = docassemble.base.util.DAGoogleAPI()
http = api.http('https://www.googleapis.com/auth/cloud-translation')
service = apiclient.discovery.build('translate', 'v2', http=http)
```
--------------------------------
### Redis Process Example
Source: https://docassemble.org/docs/installation.html
This is an example of how the Redis processes might appear in the output of 'ps ax'.
```bash
855 ? S 0:00 bash /usr/share/docassemble/webapp/run-redis.sh
863 ? Sl 0:13 redis-server 0.0.0.0:6379
```
--------------------------------
### Install Docker on Ubuntu
Source: https://docassemble.org/docs/docker.html
Installs Docker and adds the current user to the docker group for non-root access. Log out and back in for changes to take effect.
```bash
sudo apt -y update
sudo apt -y install docker.io
sudo usermod -a -G docker ubuntu
```
--------------------------------
### RabbitMQ Process Example
Source: https://docassemble.org/docs/installation.html
This is an example of how the RabbitMQ processes might appear in the output of 'ps ax'.
```bash
573 ? S 0:00 /bin/sh -e /usr/lib/rabbitmq/bin/rabbitmq-server
808 ? Sl 0:06 /usr/lib/erlang/erts-10.2.4/bin/beam.smp -W w -A 64 -MBas ageffcbf -MHas ageffcbf -MBlmbcs 512 -MHlmbcs 512 -MMmcs 30 -P 1048576 -t 5000000 -stbt db -zdbbl 128000 -K true -B i -- -root /usr/lib/erlang -progname erl -- -home /var/lib/rabbitmq -- etc. etc.
```
--------------------------------
### PostgreSQL Process Example
Source: https://docassemble.org/docs/installation.html
This is an example of how the PostgreSQL processes might appear in the output of 'ps ax'.
```bash
741 ? S 0:00 su postgres -c /usr/lib/postgresql/11/bin/postgres -D /var/lib/postgresql/11/main -c config_file=/etc/postgresql/11/main/postgresql.conf
742 ? Ss 0:00 /usr/lib/postgresql/11/bin/postgres -D /var/lib/postgresql/11/main -c config_file=/etc/postgresql/11/main/postgresql.conf
745 ? Ss 0:00 postgres: 11/main: checkpointer
746 ? Ss 0:00 postgres: 11/main: background writer
747 ? Ss 0:00 postgres: 11/main: walwriter
```
--------------------------------
### Install a docassemble package
Source: https://docassemble.org/docs/development.html
Use this command to install a docassemble package on the server. Ensure the package name is correct.
```bash
dainstall docassemble-custody
```
--------------------------------
### Install Apache Modules for Docassemble
Source: https://docassemble.org/docs/docker.html
Installs necessary Apache modules for proxying and WebSocket tunneling. Ensure Apache is installed before running these commands.
```bash
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel
sudo a2enmod headers
```
--------------------------------
### Install a docassemble package into the Playground
Source: https://docassemble.org/docs/development.html
Install a package directly into the Playground environment on the server. This makes interview files available almost immediately.
```bash
dainstall --norestart --playground docassemble-custody
```
--------------------------------
### Cron Process Example
Source: https://docassemble.org/docs/installation.html
This is an example of how the cron process might appear in the output of 'ps ax'.
```bash
518 ? Ss 0:00 /usr/sbin/cron -f
```
--------------------------------
### Specify Playground Examples
Source: https://docassemble.org/docs/config.html
Define custom example interviews for the Playground by setting `playground examples` to a single YAML file path or a list of paths. This replaces or extends the default examples.
```yaml
playground examples: docassemble.michigan:data/questions/examples.yml
```
```yaml
playground examples:
- docassemble.base:data/questions/example-list.yml
- docassemble.michigan:data/questions/examples.yml
```
--------------------------------
### Install System Dependencies
Source: https://docassemble.org/docs/installation.html
Installs a comprehensive list of system dependencies required for docassemble. Adjust the list based on your specific distribution and version.
```bash
sudo apt-get install \
apt-utils \
tzdata \
python \
python-dev \
wget \
unzip \
git \
locales \
nginx \
postgresql \
gcc \
supervisor \
s4cmd \
make \
perl \
libinline-perl \
libparallel-forkmanager-perl \
autoconf \
automake \
libjpeg-dev \
libpq-dev \
logrotate \
nodejs \
npm \
cron \
libxml2 \
libxslt1.1 \
libxml2-dev \
libxslt1-dev \
libcurl4-openssl-dev \
libssl-dev \
redis-server \
rabbitmq-server \
libtool \
libtool-bin \
syslog-ng \
rsync \
curl \
dnsutils \
build-essential \
libsvm3 \
libsvm-dev \
liblinear3 \
liblinear-dev \
libzbar-dev \
libzbar0 \
libgs-dev \
default-libmysqlclient-dev \
libgmp-dev \
python-passlib \
libsasl2-dev \
libldap2-dev \
python3 \
exim4-daemon-heavy \
python3-venv \
python3-dev \
imagemagick \
pdftk \
pacpl \
pandoc \
texlive \
texlive-luatex \
texlive-latex-recommended \
texlive-latex-extra \
texlive-font-utils \
texlive-lang-cyrillic \
texlive-lang-french \
texlive-lang-italian \
texlive-lang-portuguese \
texlive-lang-german \
texlive-lang-european \
texlive-lang-spanish \
texlive-extra-utils \
poppler-utils \
libaudio-flac-header-perl \
libaudio-musepack-perl \
libmp3-tag-perl \
libogg-vorbis-header-pureperl-perl \
libvorbis-dev \
clibcddb-perl \
clibcddb-get-perl \
libmp3-tag-perl \
libaudio-scan-perl \
libaudio-flac-header-perl \
ffmpeg \
tesseract-ocr-all \
libtesseract-dev \
ttf-mscorefonts-installer \
fonts-ebgaramond-extra \
ghostscript \
fonts-liberation \
cm-super \
qpdf \
wamerican \
libreoffice \
zlib1g-dev \
ncurses5-dev \
ncursesw5-dev \
libreadline-dev \
libsqlite3-dev
```
--------------------------------
### Install boto3 library
Source: https://docassemble.org/docs/scalability.html
Installs the boto3 library, which is a dependency for the `da-cli` utility. This command may require administrator privileges.
```bash
sudo pip install boto3
```
--------------------------------
### Install Python 3.12 from Source
Source: https://docassemble.org/docs/installation.html
Instructions for compiling and installing Python 3.12 from source if it's not available in your Linux distribution's repositories.
```bash
# See https://python.org for detailed instructions on compiling from source.
```
--------------------------------
### Install Azure Storage CLI
Source: https://docassemble.org/docs/installation.html
Installs the 'azure-storage-cmd' globally using npm, enabling the use of Azure blob storage.
```bash
sudo npm install -g azure-storage-cmd
```
--------------------------------
### Install Alembic
Source: https://docassemble.org/docs/objects.html
Install the Alembic version control system using pip. This is a prerequisite for managing database revisions.
```bash
pip install alembic
```
--------------------------------
### List API Example (Python)
Source: https://docassemble.org/docs/api.html
Python example using the requests library to call the list API, authenticating with the API key in the request headers.
```APIDOC
## GET /api/list (Python Example)
### Description
Python code snippet to call the list API, demonstrating authentication via the `X-API-Key` header.
### Method
GET
### Endpoint
/api/list
### Parameters
#### Request Headers
- **X-API-Key** (string) - Required - Your API key for authentication.
### Request Example
```python
import sys
import requests
api_key = 'H3PLMKJKIVATLDPWHJH3AGWEJPFU5GRT'
headers = {'X-API-Key': api_key}
url = 'http://localhost/api/list'
try:
r = requests.get(url, headers=headers)
r.raise_for_status() # Raise an exception for bad status codes
info = r.json()
print(info)
except requests.exceptions.RequestException as e:
print(f"Error calling API: {e}")
sys.exit(1)
```
### Response
#### Success Response (200)
Returns a JSON array of objects, each representing an available resource.
#### Response Example
```json
[
{
"filename": "docassemble.base:data/questions/examples/combobox.yml",
"link": "http://localhost/interview?i=docassemble.base%3Adata%2Fquestions%2Fexamples%2Fcombobox.yml",
"metadata": {
"title": "Combobox"
},
"package": "docassemble.base",
"status_class": null,
"subtitle": null,
"subtitle_class": null,
"tags": [],
"title": "Combobox"
}
]
```
```
--------------------------------
### Set up Python Virtual Environment and Install Dependencies
Source: https://docassemble.org/docs/installation.html
Creates a Python 3.12 virtual environment, activates it, upgrades pip, and installs core docassemble dependencies and packages from the cloned repository.
```bash
sudo su www-data
cd /tmp
python3.12 -m venv --copies /usr/share/docassemble/local3.12
source /usr/share/docassemble/local3.12/bin/activate
pip3 install --upgrade pip
pip3 install --upgrade \
3to2 \
bcrypt \
flask \
flask-login \
flask-mail \
flask-sqlalchemy \
flask-wtf \
s4cmd \
uwsgi \
passlib \
pycryptodome \
pycryptodomex \
six \
setuptools
pip3 install --upgrade \
./docassemble/docassemble_base \
./docassemble/docassemble_demo \
./docassemble/docassemble_webapp
cp ./docassemble/Docker/pip.conf /usr/share/docassemble/local3.12/
```
--------------------------------
### Get Locale Characteristic
Source: https://docassemble.org/docs/functions.html
Retrieves a specific characteristic of the current locale. For example, to get the currency symbol, call get_locale('currency_symbol').
```python
get_locale('currency_symbol')
```
--------------------------------
### Example Startup Process Log Messages
Source: https://docassemble.org/docs/config.html
This is an example of the log output generated when `debug startup process` is enabled. It shows the timing of various stages of the web application's startup, aiding in performance analysis.
```log
0.000s server: starting
0.071s config: load complete
4.179s backend: starting
4.179s backend: getting email configuration
4.179s backend: finished getting email configuration
4.179s backend: configuring common functions
4.179s backend: finished configuring common functions
4.179s backend: processing translations
4.840s backend: finished processing translations
4.840s backend: obtaining cloud object
4.840s backend: finished obtaining cloud object
4.840s backend: completed
4.892s server: done importing modules
4.896s server: creating session store
4.896s server: setting up Flask
4.903s server: finished setting up Flask
4.903s server: setting up logging
4.903s server: finished setting up logging
4.903s server: getting page parts from configuration
4.903s server: finished getting page parts from configuration
5.776s server: making directories that do not already exist
5.776s server: finished making directories that do not already exist
5.776s server: building documentation
6.218s server: finished building documentation
6.218s server: entering app context
6.218s server: entering request context
6.235s server: loading preloaded interviews
6.458s server: finished loading preloaded interviews
6.458s server: copying playground modules
6.504s server: finished copying playground modules
6.504s server: deleting LibreOffice macro file if necessary
6.504s server: fixing API keys
6.504s server: starting importing add-on modules
7.490s server: finished importing add-on modules
7.490s server: running app
```
--------------------------------
### Install Python Packages in Docker
Source: https://docassemble.org/docs/config.html
Use this directive within the `jhpyle/docassemble` Docker image to specify Python packages that should be installed when the container starts.
```yaml
python packages:
- stripe
- slackclient
```
--------------------------------
### Add a Flask GET Endpoint
Source: https://docassemble.org/docs/recipes.html
Example of a Python module that adds a '/hello' GET endpoint to a Docassemble server by using the Flask 'route' decorator.
```python
# Example Python module to add a Flask endpoint
# from flask import Flask
# app = Flask(__name__)
#
# @app.route('/hello')
# def hello_world():
# return '
Hello, World!
'
```
--------------------------------
### Start up Docassemble services
Source: https://docassemble.org/docs/scalability.html
Initiates two 'app' services and one 'backend' service, provisions EC2 instances via the 'docassembleAsg' Auto Scaling Group, and registers instances for the 'websocket' Target Group.
```bash
./da-cli start_up 2
```
--------------------------------
### Get Interview Start Time
Source: https://docassemble.org/docs/functions.html
Retrieves a `DADateTime` object for the interview session's start time in UTC. An optional `timezone` parameter can localize the output.
```python
docassemble.base.util.start_time()
```
```python
docassemble.base.util.start_time(timezone='America/New_York')
```
--------------------------------
### Assemble Document and Refresh Screen
Source: https://docassemble.org/docs/background.html
This example demonstrates assembling a document in the background and then refreshing the user's screen using 'refresh' once the document is ready. It uses `need()` to ensure a variable is available and checks `the_task.ready()` to determine when to display the final screen.
```python
need(sweetheart)
if the_task.ready():
final_screen
else:
waiting_screen
```
```python
the_task = background_action('assembly_task', 'refresh')
```
```python
background_response_action('assembly_done', document=the_document)
```
--------------------------------
### Install Ubuntu Packages in Docker Image
Source: https://docassemble.org/docs/config.html
Specify a list of Ubuntu packages to be installed when the `jhpyle/docassemble` Docker container starts. The `debian packages` directive is an alias for backward compatibility.
```yaml
ubuntu packages:
- r-base
- r-cran-effects
```
--------------------------------
### Sample Docassemble Configuration File
Source: https://docassemble.org/docs/config.html
This is a comprehensive example of a docassemble configuration file, illustrating various directives for system settings, database, mail, cloud storage, and more.
```yaml
debug: True
exitpage: https://docassemble.org
db:
prefix: postgresql+psycopg2://
name: docassemble
user: docassemble
password: abc123
host: localhost
port: null
table prefix: null
secretkey: 28asflwjeifwlfjsd2fejfiefw3g4o87
default title: docassemble
default short title: doc
mail:
username: null
password: null
server: localhost
default sender: '"Administrator" '
default interview: docassemble.demo:data/questions/default-interview.yml
language: en
locale: en_US.utf8
default admin account:
nickname: admin
email: admin@example.com
password: password
voicerss:
enable: False
key: ae8734983948ebc98239e9898f998432
dialects:
en: us
es: mx
fr: fr
voices:
en: Amy
es: Juana
fr: Axel
s3:
enable: False
access key id: FWIEJFIJIDGISEJFWOEF
secret access key: RGERG34eeeg3agwetTR0+wewWAWEFererNRERERG
bucket: yourbucketname
region: us-west-2
azure:
enable: False
account name: example-com
account key: 1TGSCr2P2uSw9/CLoucfNIAEFcqakAC7kiVwJsKLX65X3yugWwnNFRgQRfRHtenGVcc5KujusYUNnXXGXruDCA==
container: yourcontainername
ec2: False
words:
- docassemble.base:data/sources/us-words.yml
```
--------------------------------
### Add menu items with arguments using action_menu_item
Source: https://docassemble.org/docs/functions.html
Pass keyword arguments to action_menu_item to include arguments in the triggered action. This example shows adding 'Get more' and 'Get less' options to the 'change_count' action with different 'increment' values.
```python
menu_items = [ action_menu_item('Get more', 'change_count', increment=1),
action_menu_item('Get less', 'change_count', increment=-1) ]
```
--------------------------------
### Run the Docassemble Docker Image
Source: https://docassemble.org/docs/docker.html
This command initiates the Docassemble Docker container. Docker will download the `jhpyle/docassemble` image if it's not already present locally and then create and start a new container from that image.
```bash
docker run jhpyle/docassemble
```
--------------------------------
### Get Singular Noun Form of List Variable
Source: https://docassemble.org/docs/objects.html
Convert a list's variable name into its singular noun form. For example, if the variable is `case.plaintiff`, this method returns `plaintiff`.
```python
case.plaintiff.as_singular_noun()
```
--------------------------------
### Background OCR with Flash Message Notification
Source: https://docassemble.org/docs/functions.html
This example shows how to start a background OCR task and use 'flash' for notification. A message will be flashed at the top of the screen once the OCR process is complete.
```python
ocr_file_in_background(the_file, 'flash', message='All done')
```
--------------------------------
### Start a New Interview Session
Source: https://docassemble.org/docs/api.html
Initiates a new interview session by making a GET request to the /api/session/new endpoint. This provides the necessary session ID and encryption key for subsequent interactions.
```APIDOC
## GET /api/session/new
### Description
Starts a new interview session and returns session credentials.
### Method
GET
### Endpoint
/api/session/new
### Query Parameters
- **i** (string) - Required - The interview to start, specified in the format 'package:path/to/file.yml'.
### Response
#### Success Response (200)
- **session** (string) - The unique session identifier.
- **secret** (string) - The encryption key for the session.
- **i** (string) - The interview identifier used.
- **encrypted** (boolean) - Indicates if the session is encrypted.
### Response Example
```json
{
"encrypted": true,
"i": "docassemble.base:data/questions/examples/questionless.yml",
"secret": "aZLbSszVzfVpnOfK",
"session": "YOwLSycrtezLXEWhIUheRSpLNLEfRMxP"
}
```
```
--------------------------------
### AIHelper Class Interview Example
Source: https://docassemble.org/docs/recipes.html
This is a complete Docassemble interview demonstrating the use of the AIHelper class. It includes setup, user questions, and code execution for interacting with an LLM to gather information.
```yaml
include:
- aihelper.yml
---
objects:
- ai: AIHelper
- user: Individual
---
question: |
What is your name?
fields:
- First name: user.name.first
- Last name: user.name.last
---
mandatory: true
question: |
Download your affidavit
attachment:
name: Favorite fruit affidavit
filename: affidavit
content: |
[CENTER]Affidavit of Favorite Fruit
${ life_story }
${ favorite_fruit_explanation }
---
code: |
life_story = ai['life'].interact()
---
question: |
What is your life story?
subquestion: |
${ ai['life'].output }
fields:
- no label: ai['life'].input
input type: area
---
template: ai['life'].initial_output
content: |
Please cover such details as where you were born, where you grew up,
where you went to school, and who you live with currently.
---
template: ai['life'].prompt
content: |
You are a helpful assistant who is having a conversation with
${ user } about ${ user.possessive('life story') }. You need to find
out from ${ user } where they were born, where they grew up, where
they went to school, and how they came to live with the people they
currently live with. When you have gathered this information, call
the conversation_complete tool with a 2 to 5 paragraph summary of
${ user.possessive('life story') } written in first-person as
${ user }, that includes all of these elements.
---
code: |
favorite_fruit_explanation = ai['fruit'].interact()
---
question: |
What is your favorite fruit and why?
subquestion: |
${ ai['fruit'].output }
fields:
- no label: ai['fruit'].input
input type: area
---
template: ai['fruit'].initial_output
content: |
Please explain your reasoning.
---
template: ai['fruit'].prompt
content: |
You are a helpful assistant who is having a conversation with ${ user } about ${ user.possessive('favorite fruit') }. Your job is to
elicit from ${ user } what their favorite fruit is and specifically
why they like the fruit so much, compared with other fruits. When
you have gathered this information, call the conversation_complete
tool with a 2 to 3 sentence testimonial, written in first-person as
${ user }, saying what their favorite fruit is and why.
```
--------------------------------
### Get Referring URL for User Navigation
Source: https://docassemble.org/docs/functions.html
Retrieves the URL the user was visiting before starting the interview. If unavailable, it uses a default URL or the 'exitpage' configuration. Useful for returning users to their previous location.
```python
question: |
We have finished our quest.
buttons:
- Return: exit
url: |
${ referring_url() }
need:
- continue_with_quest
mandatory: True
```
```python
question: |
How did you hear about us?
fields:
no label: how_user_heard_of_us
---
code: |
if referring_url(default=False) is not False:
how_user_heard_of_us = referring_url()
```
--------------------------------
### Create Directories and Set Permissions
Source: https://docassemble.org/docs/installation.html
Creates essential directories for docassemble and its dependencies, and sets ownership to the web server user (www-data).
```bash
sudo mkdir -p /etc/ssl/docassemble \
/usr/share/docassemble/local3.12 \
/usr/share/docassemble/certs \
/usr/share/docassemble/backup \
/usr/share/docassemble/config \
/usr/share/docassemble/webapp \
/usr/share/docassemble/files \
/var/www/.pip \
/var/www/.cache \
/var/run/uwsgi \
/usr/share/docassemble/log \
/tmp/docassemble \
/var/www/html/log
sudo chown -R www-data.www-data /var/www
sudo chown www-data.www-data /var/run/uwsgi
sudo chown -R www-data.www-data \
/tmp/docassemble \
/usr/share/docassemble/local3.12 \
/usr/share/docassemble/log \
/usr/share/docassemble/files
```
--------------------------------
### Run Background Task and Get Result
Source: https://docassemble.org/docs/background.html
Initiates a background task and waits for its completion, returning the result. Use when user input is needed to start the task and the result is required to continue the interview.
```yaml
objects:
bg: BackgroundAction
---
code: |
answer = bg.run('bg_task', additional=value_to_add)
---
question: |
How much shall I add to 553?
fields:
- Number: value_to_add
datatype: integer
---
event: bg_task
code: |
background_response(553 + action_argument('additional'))
---
mandatory: True
question: |
The answer is ${ answer }.
```
--------------------------------
### Start Background OCR with 'refresh' Notification
Source: https://docassemble.org/docs/functions.html
This example initiates an OCR process in the background and uses the 'refresh' notification method. This method automatically refreshes the screen when the task is complete, displaying the OCR results.
```python
the_task = ocr_file_in_background(the_files, 'refresh')
```
```python
the_task.get()
```
--------------------------------
### Run Docassemble with Web and Celery Services
Source: https://docassemble.org/docs/docker.html
This command starts a Docassemble container for web and Celery services. Ports 80, 443, and 9001 must be open on the host machine.
```bash
docker run \
--env CONTAINERROLE=web:celery \
...
-d -p 80:80 -p 443:443 -p 9001:9001 \
--restart always --stop-timeout 600 jhpyle/docassemble
```
--------------------------------
### Initializing Docassemble Objects
Source: https://docassemble.org/docs/objects.html
Set up initial object configurations using the `set_info` function. This is typically done early in the interview to define user and other relevant objects.
```python
set_info(user=user)
```
--------------------------------
### Using RoleChangeTracker in Docassemble Interviews
Source: https://docassemble.org/docs/objects.html
This example demonstrates the setup and usage of the RoleChangeTracker within a Docassemble interview. It defines roles, sets default roles, and uses the tracker to send emails based on role requirements.
```yaml
objects:
- client: Individual
- advocate: Individual
- role_change: RoleChangeTracker
---
default role: client
code: |
if user_logged_in() and \
advocate.attribute_defined('email') and \
advocate.email == user_info().email:
user = advocate
role = 'advocate'
else:
user = client
role = 'client'
set_info(user=user, role=role)
---
event: role_event
question: You are done for now.
subquestion: |
% if 'advocate' in role_needed:
An advocate needs to review your answers before you can proceed.
Please remember the following link and come back to it when you
receive notice to do so:
[${ interview_url() }](${ interview_url() })
% else:
Thanks, the client needs to resume the interview now.
% endif
% if role_change.send_email(role_needed, advocate={'to': advocate, 'email': role_event_email_to_advocate}, client={'to': client, 'email': role_event_email_to_client}):
An e-mail has been sent.
% endif
decoration: exit
buttons:
- Exit: leave
---
template: role_event_email_to_advocate
subject: |
Client interview waiting for your attention: ${ client }
content: |
A client, ${ client }, has partly finished an interview.
Please go to [the interview](${ interview_url() }) as soon as
possible to review the client's answers.
---
template: role_event_email_to_client
subject: |
Your interview answers have been reviewed
content: |
An advocate has finished reviewing your answers.
Please go to [${ interview_url() }](${ interview_url() })
to resume the interview.
```
--------------------------------
### Customize Administrative Page CSS
Source: https://docassemble.org/docs/config.html
Apply custom CSS to administrative pages like the start page and interviews page by including a CSS file with the 'global css' directive. This example shows how to style headings, lists, and table elements.
```css
h1.dastartpage {
font-size: 15px;
}
ul.dastartpage {
background-color: red;
}
ul.dastartpage li {
font-weight: bold;
}
h3.dainterviewpage {
font-decoration: underline;
}
p.dainterviewpage {
color: #aaaaaa;
}
table.dainterviewpage td {
border-style: solid;
border-width: 1px;
}
```
--------------------------------
### Automate Docassemble Interview Testing with Behave
Source: https://docassemble.org/docs/development.html
Use Behave scripts to simulate user interactions with a Docassemble interview for testing purposes. This approach allows for quick setup of test scenarios by specifying login credentials, interview start, and user selections.
```gherkin
Scenario: Test the interview "Debt collection advice"
Given I log in with "jsmith@example.com" and "sUper@sEcr3t_pAssWd"
And I start the interview "docassemble.massachusetts:data/questions/debt.yml"
Then I should see the phrase "Which scenario do you want to test?"
And I click the "Scenario One" option
And I click the button "Continue"
```
--------------------------------
### Start Docassemble Container with Custom Certificates
Source: https://docassemble.org/docs/docker.html
Command to launch the Docassemble Docker container, mounting the 'dacerts' volume to '/usr/share/docassemble/certs' and using the specified environment file.
```bash
docker run \
--restart always \
--stop-timeout 600 \
--env-file=env.list \
-v dabackup:/usr/share/docassemble/backup \
-v dacerts:/usr/share/docassemble/certs \
-d -p 80:80 -p 443:443 jhpyle/docassemble
```
--------------------------------
### Headless Document Assembly with Docassemble API
Source: https://docassemble.org/docs/recipes.html
This recipe demonstrates how to perform document assembly using the Docassemble API without a user interface. It includes example Python code for interacting with the API to start a session, provide variables, and retrieve the assembled document.
```yaml
mandatory: True
code: |
json_response(the_document.pdf.number)
---
attachment:
variable name: the_document
content: |
Your favorite fruit is ${ favorite_fruit }.
```
```python
root = 'https://docassemble.myhostname.com/api'
headers = {'X-API-Key': 'XXXSECRETAPIKEYXXX'}
username = 'jsmith'
password = 'xxxsecretpasswordxxx'
i = 'docassemble.mypackage:data/questions/headless.yml'
r = requests.get(root + '/secret', params={'username': username, 'password': password}, headers=headers)
if r.status_code != 200:
sys.exit(r.text)
secret = r.json()
r = requests.get(root + '/session/new', params={'secret': secret, 'i': i}, headers=headers)
if r.status_code != 200:
sys.exit(r.text)
session = r.json()['session']
r = requests.post(root + '/session', json={'secret': secret, 'i': i, 'session': session, 'variables': {'favorite_fruit': 'apple'}}, headers=headers)
if r.status_code != 200:
sys.exit(r.text)
file_number = r.json()
r = requests.get(root + '/file/' + str(file_number), params={'i': i, 'session': session, 'secret': secret}, headers=headers)
if r.status_code != 200:
sys.exit(r.text)
with open('the_file.pdf', 'wb') as fp:
fp.write(r.content)
```
--------------------------------
### Get Current Time from World Clock API (Python)
Source: https://docassemble.org/docs/external.html
This Python function uses the 'requests' library to fetch the current date and time from the World Clock API. It handles potential HTTP errors and returns the 'currentDateTime' from the JSON response. Ensure the 'requests' library is installed.
```python
import requests
def get_time():
r = requests.get('http://worldclockapi.com/api/json/est/now')
if r.status_code != 200:
raise Exception("Could not obtain the time")
return r.json()['currentDateTime']
```
--------------------------------
### Ajax Combobox with Dictionary Data Source
Source: https://docassemble.org/docs/fields.html
This example demonstrates an Ajax combobox where the server-side action returns a JSON list of lists, mapping underlying values to user-visible labels. The action must handle both initial values and user input. Remember to include 'set_save_status(\'ignore\')' at the start and 'json_response()' at the end of the action code.
```yaml
question: |
What is your favorite fruit?
fields:
- Word: favorite_fruit
input type: ajax
action: fruitlist
---
event: fruitlist
code: |
set_save_status('ignore')
original = action_argument('wordstart')
wordstart = original.lower()
results = []
for key, val in {'x234': 'Apple', 'y432': 'Orange', 'h293': 'Peach'}.items():
if key == original:
json_response([[key, val]])
if val.lower().startswith(wordstart):
results.append([key, val])
json_response(results)
```
--------------------------------
### Install Latest Pandoc
Source: https://docassemble.org/docs/installation.html
Installs the latest version of Pandoc by downloading and installing a .deb package.
```bash
cd /tmp \
&& wget -q https://github.com/jgm/pandoc/releases/download/2.7.3/pandoc-2.7.3-1-amd64.deb \
&& sudo dpkg -i pandoc-2.7.3-1-amd64.deb \
&& rm pandoc-2.7.3-1-amd64.deb
```
--------------------------------
### Initialize DAStore and DAObject
Source: https://docassemble.org/docs/objects.html
Initializes a DAStore for user data and a DAObject for preferences. Retrieves existing preferences from DAStore if available, otherwise creates a new DAObject.
```yaml
objects:
- userdata: DAStore
- preferences: DAObject
---
code: |
if userdata.defined("prefs"):
preferences = userdata.get("prefs")
```
--------------------------------
### Install pip
Source: https://docassemble.org/docs/installation.html
Downloads and installs the latest version of pip using a Python script. This ensures you have the most up-to-date package installer.
```bash
wget https://bootstrap.pypa.io/get-pip.py
sudo -H python get-pip.py
```
--------------------------------
### Docassemble Interview Logic with Task Management
Source: https://docassemble.org/docs/logic.html
This docassemble example demonstrates managing interview flow with tasks. It stores data and marks a task as performed, then conditionally asks a question. Refreshing the screen after the task is performed skips the conditional logic.
```yaml
mandatory: True
code: |
user.name.first
user.email
if not task_performed('data_stored'):
store_data(user)
mark_task_as_performed('data_stored')
user.wants_email
if user.wants_email:
send_email(to=user, template=confirmation_email)
user.birthdate
final_screen
---
question: |
Do you want a confirmation e-mail?
yesno: user.wants_email
```
--------------------------------
### Content of hello.md
Source: https://docassemble.org/docs/documents.html
This is the content of the `hello.md` file referenced in the previous example.
```markdown
Hello, world!
```
--------------------------------
### Install NGINX, Certbot, and Docker on Ubuntu
Source: https://docassemble.org/docs/docker.html
Installs necessary packages for web serving, SSL, and containerization. The user 'ubuntu' is added to the 'docker' group for privileges. Log out and back in for changes to take effect.
```bash
sudo apt -y update
sudo apt -y install snapd nginx docker.io
sudo snap install --classic certbot
sudo usermod -a -G docker ubuntu
```
--------------------------------
### Initialize DACloudStorage with Default Configuration
Source: https://docassemble.org/docs/objects.html
Include this in your interview to enable DACloudStorage with default S3 or Azure settings from your configuration.
```yaml
objects:
- cloud: DACloudStorage
```
--------------------------------
### Install or update a package
Source: https://docassemble.org/docs/api.html
Installs or updates a package and returns a task ID for status inspection. Supports installation from GitHub, PyPI, or uploaded ZIP files.
```APIDOC
## Install or update a package
### Description
Installs or updates a package and returns a task ID that can be used to inspect the status of the package update process.
### Method
POST
### Endpoint
`/api/package`
### Parameters
#### Request Body
- **key** (string) - Optional - the API key (optional if the API key is passed in an `X-API-Key` header or cookie or as a bearer token).
- **update** (string) - Optional - the name of an already-installed Python package that you want to update. (This is not useful if the package was installed from an uploaded ZIP file.)
- **github_url** (string) - Optional - the URL of a GitHub package to install.
- **branch** (string) - Optional - if a `github_url` is provided and you want to install from a non-standard branch, set `branch` to the name of the branch you want to install.
- **pip** (string) - Optional - the name of Python package to install from PyPI.
- **restart** (string) - Optional - set this to `0` if you want to skip the process of restarting the server after installing the package. By default, the server is restarted.
#### File Data
- **zip** (file) - a file upload of a ZIP file containing a package.
### Response
#### Success Response (200)
- **task_id** (string) - a code that can be passed to `/api/package_update_status` to check on the status and result of the package update process. The `task_id` expires after one hour.
#### Response Example
```json
{
"task_id": "your_task_id_here"
}
```
```
--------------------------------
### Start an interview
Source: https://docassemble.org/docs/api.html
API function to start a new interview session.
```APIDOC
## Start an interview
### Description
Initiates a new interview session.
### Method
POST
### Endpoint
/interviews/{interview_name}/start
### Parameters
#### Path Parameters
- **interview_name** (string) - Required - The name of the interview to start.
#### Request Body
- **user_data** (object) - Optional - Initial data for the interview.
```
--------------------------------
### List the packages installed
Source: https://docassemble.org/docs/api.html
API function to list all installed packages on the system.
```APIDOC
## List the packages installed
### Description
Retrieves a list of all packages that are currently installed on the system.
### Method
GET
### Endpoint
/packages
```
--------------------------------
### Install Mermaid CLI
Source: https://docassemble.org/docs/installation.html
Installs the 'mmdc' application for generating mermaid diagrams. This involves switching to the 'www-data' user, setting up Node.js and nvm, installing mermaid.cli, and then creating a symbolic link for the 'mmdc' command.
```bash
sudo su www-data
mkdir -p /var/www/node_modules/.bin
cd /tmp
echo '{ "args": ["--no-sandbox"] }' > ~/puppeteer-config.json
touch ~/.profile
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
source ~/.profile
nvm install 12.6.0
npm install mermaid.cli
rm ~/.profile
```
```bash
sudo ln -s /var/www/node_modules/.bin/mmdc /usr/local/bin/mmdc
```
--------------------------------
### Create Docassemble Database Tables
Source: https://docassemble.org/docs/installation.html
Initialize the Docassemble database tables using the create_tables script. This command must be run with the www-data user and requires the virtual environment to be activated.
```bash
sudo -H -u www-data bash -c "source /usr/share/docassemble/local3.12/bin/activate && python -m docassemble.webapp.create_tables"
```
--------------------------------
### Install Docassemble Packages and Reset Server
Source: https://docassemble.org/docs/development.html
This script activates the Python virtual environment, installs docassemble packages, and updates the web server configuration. It also populates shell history for easy re-execution.
```bash
#! /bin/bash
source /etc/profile
source /usr/share/docassemble/local3.12/bin/activate
pip install --no-deps --force-reinstall --upgrade ./docassemble_base ./docassemble_webapp ./docassemble_demo && touch /usr/share/docassemble/webapp/docassemble.wsgi
history -s "source /usr/share/docassemble/local3.12/bin/activate"
history -s "pip install --no-deps --force-reinstall --upgrade ./docassemble_base ./docassemble_webapp ./docassemble_demo && touch /usr/share/docassemble/webapp/docassemble.wsgi"
```
--------------------------------
### Control Software Updates on Container Start
Source: https://docassemble.org/docs/config.html
Manage whether Python packages are updated when the Docker container starts. Setting to 'false' prevents updates on any start, while 'initial' allows updates only on the first 'docker run'.
```yaml
update on start: false
```
```yaml
update on start: initial
```
--------------------------------
### Install or update a package
Source: https://docassemble.org/docs/api.html
API function to install a new package or update an existing one.
```APIDOC
## Install or update a package
### Description
Installs a new package or updates an existing package on the system.
### Method
POST
### Endpoint
/packages
### Parameters
#### Request Body
- **package_name** (string) - Required - The name of the package to install or update.
```