2
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Just for this .. is this all necessary? You could use the flask application , or mapping the each route to a script..

Short answer : No , there are others ways to build what you want that django is not more appropriate.

Long answer

First point

In your methods you are handling the permited methods at hand , the django have the decorators that handle this:

Allowed http methods https://docs.djangoproject.com/en/1.11/topics/http/decorators/#allowed-http-methods

Some methods would:

@require_http_methods(["GET"])
def list_containers(request):
    pass

@require_http_methods(["GET"])    
def list_images(request):
    pass

@require_http_methods(["GET","POST"])
def networks(request):

    if request.method == "GET":
        # retrieve networks and return them

    if method.method == "POST":
        # create network

urls.py

url(r'container/s', network.list_containers),
url(r'images/', network.list_images),
url(r'networks/', network.networks)

P.s : The views isn't following your structure , but is easily changed.

Second point

The mainly problem with your code is the routes: network/ and network/create to REST definition , the correct would be the route /networks receive the GET and POST and perform different actions ( retrieve and create respectively )

You could use the Django Rest Framework[1] ( the main framework to build restful application in django )

The DRF handle all these: method , routes , views ( viewsets ).

But if django is the bigger to this , you could use the flask framework and use the your routes and the restful frameworks that solves your problem too.

[1] http://www.django-rest-framework.org/

[2] http://flask.pocoo.org/ ( Framework )

[3] https://flask-restful.readthedocs.io/en/0.3.5/ ( FlaskRestful )

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.