This is an old revision of the document!
Django API
General Information
Interacting with the Django Python API.
Checklist
Imports
Imports and settings to add to your Python script in order to use your Django App's built in API.
Import and Settings
#!/usr/bin/python # Required module for sys.path.append import sys # Required module for os.environ import os # Import Django WSGI App Loading capabilities from django.core.wsgi import get_wsgi_application ##- Configure Django Settings to point to your App -## # sys.path = where manage.py is sys.path.append('/home/django/myprojecthere') # Settings Module = projectname.settings os.environ["DJANGO_SETTINGS_MODULE"] = 'myprojecthere.settings' application = get_wsgi_application() # Import Django App Model (from 'myapphere' app) from myapphere.models import AssetEntry
Using Your Apps API
Different ways to get your app data.
Load Objects
Objects can now be retrieved just like in views.py.
# Load all assets (just like in views.py) asset_list = AssetEntry.objects.order_by('asset_type', 'asset_env', 'asset_name') # Print all names (see your models.py for available fields) for node in asset_list: print(node.asset_name)
Add New Objects
Create a new object and then save it to the database.
# Set variables that will be used to create a new object new_name = "server99" new_type = "Servers" new_description = "API Added Server" new_env = "Prod" new_os = "CentOS 7" new_hardware = "Virtual" # Create the new object new_entry = AssetEntry(asset_name = new_name, asset_type = new_type, asset_description = new_description, asset_env = new_env, asset_os = new_os, asset_hardware = new_hardware) # Attempt to add new object to the database try: new_entry.save() print("--> Entry added successfully.") except: print("---> ERROR adding entry!")
Change Existing Objects
Changing an existing object in the database.
# Load all assets (just like in views.py) asset_list = AssetEntry.objects.order_by('asset_type', 'asset_env', 'asset_name') # Change server99's OS to Ubuntu 18.04 for node in asset_list: if node.asset_name == "server99": node.asset_os = "Ubuntu 18.04" # Attempt to save object change to the database try: node.save() print("--> Change saved successfully.") except: print("---> ERROR saving change!")
Delete Objects
- Fill out how to delete an object.