This solution is to create a docker network using Docker supported APIs. For achieving this, I am using Python and Django framework for providing RESTful APIs.
cat network.py
from django.http import JsonResponse
import requests
import json
HEADERS = {"Content-Type" : "application/json", "Accept" : "application/json"}
def network_details():
response = requests.get("http://127.0.0.1:6000/networks")
#table = [[Name, Id, Driver, Subnet, Gateway]]
table = []
details = {}
for network in response.json():
details["Name"] = network["Name"].encode("utf-8")
details["Id"] = network["Id"].encode("utf-8")[:12]
details["Driver"] = network["Driver"].encode("utf-8")
#to check if dict is Null
if network["IPAM"]["Config"].__len__() == 0:
details["Subnet"] = "none"
details["Gateway"] = "none"
else:
ip_config = network["IPAM"]["Config"][0]
details["Subnet"] = ip_config["Subnet"]
details["Gateway"] = ip_config["Gateway"]
table.append(details)
#intializing to dict to None as scope is outside the for loop as well
details = {}
return table
def network_info(request):
if request.method == "GET":
return JsonResponse(network_details(), safe=False)
def create_nw(content):
response = requests.post("http://127.0.0.1:6000/networks/create",
content, headers = HEADERS )
return response.json()
def create_network(request):
if request.method == "POST":
try:
response = create_nw(request.body)
#explicitly looking for Warning or message to know the status
if "Warning" in response:
return JsonResponse("Success, Network created with ID: {}".
format(response['Id'].encode('utf-8')[:12]),safe=False)
elif "message" in response:
return JsonResponse("Error : {}".
format(response.values()[0]),safe=False)
except ValueError:
return JsonResponse("Error : Improper JSON format provided", safe=False)
URLs information:
cat urls.py
from django.conf.urls import url
from . import views, images, containers, network
urlpatterns = [
url(r'images', images.images_info),
url(r'containers', containers.active_containers),
url(r'network/create', network.create_network),
url(r'network', network.network_info),
url(r'^$', views.index, name='index'),
]
RESTful API to the solution:
curl -X POST <****>/network/create -d @create_network.json --header "Content-Type: application/json" | jq
Can someone suggest if this the right way to build an application using Django framework?
I am not looking for the appropriate/optimized solution for the idea I want to work on. I am looking for your suggestions how can I improve in my coding skills. The reason for selecting Django is to get hands on the framework.