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
inityour task. Make sure
--from upload_csvis replaced with whatever your task slug is, and replace
your_task_file.pywith where you'd like the new task file to be created:
bashCopied1# Use the slug for your task, displayed in the UI2airplane 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
csvto download and read the file:
pythonCopied1# YOUR_TASK_FILE.py23# Linked to https://app.airplane.dev/t/upload_csv [do not edit this line]4import csv5import io6import urllib.request78def main(params):9# The file is available in the params dict keyed by param slug. url is the string URL where the file lives.10url = params["file"]["url"]11# Download from URL into memory12response = urllib.request.urlopen(url)13# Open the file as a CSV14csv_file = csv.reader(io.TextIOWrapper(response))15for row in csv_file:16print(row)
And that's it! You can work with
csv_filelike you would any other file.
If you're already using the
pandaslibrary in your script, you can use
pandas.read_csvto open the file and read it in one go:
Deploy and run the task
deployto finish creating the task:
bashCopied1airplane deploy your_task_file.py23...45Build succeeded67⚡ To execute the task from the CLI:8airplane exec your_task_file.py910⚡ To execute the task from the UI:11https://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!