Reading CSV file uploads

Example Python task to read a CSV file upload
Airplane makes it easy to allow users to upload a file as a parameter and read that from your script. In this guide, we'll walk through reading a CSV file in Python.
In short: Airplane provides user-uploaded files to your task as a temporary URL. Using your language of choice, you can download the file from the URL, pass it to a CSV parser of choice, and read the output of parsing. (File uploads support arbitrary data—once you've downloaded the data from the URL, you can do whatever you need with code.)

Set up a task

First, let's create a Python task. Visit the create task page and choose a Python task. Give it a name, description, and file parameter.
Click "Continue" to move through the next few pages and click "Create task." You'll see a page with CLI instructions:
Follow the instructions to init your task. Make sure --from upload_csv is replaced with whatever your task slug is, and replace your_task_file.py with where you'd like the new task file to be created:
bash
Copied
1
# Use the slug for your task, displayed in the UI
2
airplane tasks init --from upload_csv your_task_file.py

Write code to read the file

When a user runs your task, they'll be able to drag-and-drop a file into the UI. This file gets uploaded to Airplane, and a temporary URL for downloading the file is passed to your task.
We're going to use the built-in Python modules urllib.request and csv to download and read the file:
python
Copied
1
# YOUR_TASK_FILE.py
2
3
# Linked to https://app.airplane.dev/t/upload_csv [do not edit this line]
4
import csv
5
import io
6
import urllib.request
7
8
def main(params):
9
# The file is available in the params dict keyed by param slug. url is the string URL where the file lives.
10
url = params["file"]["url"]
11
# Download from URL into memory
12
response = urllib.request.urlopen(url)
13
# Open the file as a CSV
14
csv_file = csv.reader(io.TextIOWrapper(response))
15
for row in csv_file:
16
print(row)
And that's it! You can work with csv_file like you would any other file.
If you're already using the pandas library in your script, you can use pandas.read_csv to open the file and read it in one go:
python
Copied
1
pandas.read_csv(params["file"]["url"])

Deploy and run the task

Run deploy to finish creating the task:
bash
Copied
1
airplane deploy your_task_file.py
2
3
...
4
5
Build succeeded
6
7
⚡ To execute the task from the CLI:
8
airplane exec your_task_file.py
9
10
⚡ To execute the task from the UI:
11
https://app.airplane.dev/t/upload_csv
Visit your task from the UI, and you'll be able to drag-and-drop a CSV file in!