Working with Django
Airplane works with Django! You can write Python tasks like you normally would, plus a few additional lines of code to configure Django.
Add the following code to the beginning of your Airplane task:
pythonCopied1import os2import sys3# Assumes this task is run from the parent directory4# Airplane will use the directory that requirements.txt is in5sys.path.insert(0, os.getcwd())6# Importing from myproject.wsgi configures Django7# Replace myproject with your Django project name8from myproject.wsgi import application
This configures your Python path to allow importing from the root directory, then initializes Django so you Django models, etc. are properly set up.
In this guide, we'll use the following example layout (replace
myproject with the name of your
myapp is an example Django application you might want to import from):
You might have something like the following if you ran
airplane init --slug my_airplane_task:
pythonCopied1# Linked to https://app.airplane.dev/t/my_airplane_task [do not edit this line]23def main(params):4print("parameters:", params)
To import from Django, add the following code to the top of your file:
pythonCopied1# Linked to https://app.airplane.dev/t/my_airplane_task [do not edit this line]23# DJANGO SETUP4import os5import sys6# Assumes this task is run from the parent directory7# Airplane will use the directory that requirements.txt is in8sys.path.insert(0, os.getcwd())9# Importing from myproject.wsgi configures Django10from myproject.wsgi import application11# END DJANGO SETUP1213# You can now import e.g. models from myapp14from myapp.models import MyModel1516def main(params):17print(MyModel.objects.all())
In lines 4-10, we've added the current directory to the Python path, which allows us to import from
myapp. This code assumes your working directory is your project root—Airplane will find
requirements.txt to determine the project root and uses that as the working directory when running
In line 14, you can see an example of importing a model—without the setup code, this normally fails.
Finally, in line 17 you can use your model like you would in a normal Django handler.