put data from docker api to database

iam working on a django-project. And my goal is to receive data from the docker deamon and pass the information to a simple integrated Django-Database like sqlite3. I made it already to put the information output to the template. But how i can pass the data to this database. I tried it for month and i didnt get it.i hope some of you can help me. Some Code:

docker_api.py where the information comes in:

from json.decoder import JSONDecodeError
from requests_unixsocket import Session
from requests import RequestException
from config.settings import DOCKER_API


def docker_requester(func):
    def wrapper(*args, **kwargs):
        method, endpoint, data = func(*args, **kwargs)
        session = Session()
        call = getattr(session, method)
        resp = call(DOCKER_API + endpoint, json=data, timeout=30)

        if resp.status_code == 204:
            return True
        if resp.status_code == 201 or resp.status_code == 200:
            try:
                return resp.json()
            except JSONDecodeError:
                return True
        return False

    return wrapper


@docker_requester
def list_image():
    return "get", "images/json", None

This already works

images.py (acting like a view):

from dockerInspector.forms import ImageForm
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from dockerInspector.docker_api import list_image, pull_image, delete_image


def list_images_view(request):
    resp = list_image()

    images = []
    for res in resp:
        try:
            img_id = res["Id"].split(":")
            repo_tags = (
                res["RepoTags"] if res["RepoTags"] is not None else ["no_name:untagged"]
            )
        except KeyError:
            return render(
                request, "dockerInspector/list_image.html", {"images": images}
            )

        for r in repo_tags:
            name, tag = r.split(":")
            image = {"repo": name, "tag": tag, "id": img_id[1][:12], "full_name": r}
            images.append(image)

    return render(request, "dockerInspector/list_image.html", {"images": images})

list_image.html This handles the incoming informations and send it to the template like this:

{% extends "dockerInspector/base.html" %}
{% block content%}
<table class="table table-light">
    <thead class="thead-dark">
        <div class="section-image_pulling">
            <div class="input-group mb-3">
                <input type="text" id="image_txt" class="form-control" placeholder="Image von Docker-Hub beziehen..."
                    aria-label="Recipient's username" aria-describedby="button-addon2" />
                <div class="input-group-append">
                    <button class="btn btn-secondary pull" type="button" id="pull_bt">
                        Pull
                    </button>
                </div>
            </div>
        </div>
        <tr>
            <th scope="col">Image-Name</th>
            <th scope="col">Image-Tag</th>
            <th scope="col">Image-ID</th>
            <th scope="col">Image löschen</th>
            <th scope="col">Container starten</th>
            <th scope="col">Submit</th>
        </tr>
    </thead>

    <tbody>
        {% for image in images %}

        <tr>
            <td><a class="detail-link" href="#">{{image.repo}}</a></td>
            <td>{{image.tag}}</td>
            <td>{{image.id}}</td>
            <td>
                <button type="button" value={{image.full_name}} class="btn btn-danger delete">Image löschen</button>
            </td>
            <td>
                <button type="button" class="btn btn-success">Container starten</button>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

And the data is displaying. So far so good. For my project i need to save this ouput to a database. Do anyone has an idea, how i can do it? Im working so long on this project and i didnt get it.

You would save this to the database just like any other data. Create your models, create instances of the model for the data, and save the instance.

See the Models page of the docs for some examples.

Thanks for your answer, but i already tried your solution. Whenever i create a model with the fields. The model do not connect with the incomming information in the image.py file. The database stays empty.
I do not know how to connect model with the incomming information.

Please post the code that you’ve tried to use. Include both your Model and the changes you made to your view to save the data in the model.

Image.py:

from dockerInspector.forms import ImageForm
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from dockerInspector.models import Image
from dockerInspector.docker_api import list_image, pull_image, delete_image

def list_images_view(request):
resp = list_image()

images = []
for res in resp:
    try:
        img_id = res["Id"].split(":")
        repo_tags = (
            res["RepoTags"] if res["RepoTags"] is not None else ["no_name:untagged"]
        )
    except KeyError:
        return render(
            request, "dockerInspector/list_image.html", {"images": images}
        )

    for r in repo_tags:
        name, tag = r.split(":")
        image = {"repo": name, "tag": tag, "id": img_id[1][:12], "full_name": r}
        images.append(image)

return render(request, "dockerInspector/list_image.html", {"images": images})

Models.py:
from django.db import models
from dockerInspector.docker_api import list_image

class Image(models.Model):
img_id = models.CharField(max_length=50)
tag = models.CharField(max_length=50)
name = models.CharField(max_length=50)
r = models.CharField(max_length=50)

def save_image(self):
    resp = list_image()
    images = []
    for res in resp:
        self.img_id = res["Id"].split(":")
        self.repo_tags = (
            res["RepoTags"] if res["RepoTags"] is not None else ["no_name:untagged"]
        )

        for r in self.repo_tags:
            name, tag = r.split(":")
            image = {
                "repo": self.name,
                "tag": self.tag,
                "id": self.img_id[1][:12],
                "full_name": r,
            }
            images.append(image)

Not in database yet, but the output displaying:

Your view needs to create the instance of the model with the data to be saved, and then save that instance.

In Django, how do you create an instance of a Model? If you’re unsure of the answer, then you need to review the documentation on Models. If that doesn’t clear it up, then my next recommendation would be to work your way through the official Django tutorial for even more detailed examples.

Hey,
thanks for your help. I really struggled with it, but in fact, it was so easy to do. I had a missunderstanding of the way model, view, template works together. This was a hard lesson, but now i got it.
Thank you!

1 Like