Dive into Code

Discover code snippets, tutorials, and programming insights

Postgresql

Optimize postgresql in debian server

<p>Optimizing PostgreSQL in a Debian server involves several steps, including tuning PostgreSQL configuration, optimizing server hardware resources, and optimizing queries. Here are some general steps that you can follow:&nbsp; &nbsp;&nbsp;</p> …

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Optimizing PostgreSQL in a Debian server involves several steps, including tuning PostgreSQL configuration, optimizing server hardware resources, and optimizing queries. Here are some general steps that you can follow:

Tune PostgreSQL configuration:
a. Locate the PostgreSQL configuration file. By default, it is located at /etc/postgresql/<version>/main/postgresql.conf
b. Adjust the following parameters according to your hardware configuration and workload:

shared_buffers: This parameter controls the amount of memory that PostgreSQL uses for caching data in memory. It should be set to a reasonable value based on the available system memory.
work_mem: This parameter controls the amount of memory that PostgreSQL uses for sorting and other temporary operations. It should be set to a reasonable value based on the size of your largest tables and the available system memory.
effective_cache_size: This parameter tells PostgreSQL how much memory is available for caching data. It should be set to a value that reflects the amount of available system memory.
maintenance_work_mem: This parameter controls the amount of memory that PostgreSQL uses for performing maintenance tasks, such as vacuuming. It should be set to a reasonable value based on the size of your database and the available system memory.
checkpoint_completion_target: This parameter controls how much time is allowed for checkpoint completion. It should be set to a value that balances checkpoint overhead with performance.
Optimize server hardware resources:
a. Make sure that your server has enough memory and CPU resources to support your PostgreSQL workload.
b. Use a high-performance storage device such as an SSD to improve disk I/O performance.
c. Consider using RAID to improve data availability and performance.

Optimize queries:
a. Use EXPLAIN to analyze query performance and identify slow queries.
b. Rewrite slow queries to use indexes, if possible.
c. Avoid using SELECT * in queries and instead specify the required columns explicitly.
d. Use LIMIT and OFFSET to limit the amount of data returned by a query.
e. Use prepared statements to avoid repeated parsing of SQL statements.

Monitor PostgreSQL performance:
a. Use a tool such as pgAdmin to monitor PostgreSQL performance metrics, such as CPU usage, memory usage, and disk I/O.
b. Use a tool such as Nagios to monitor PostgreSQL availability and performance.

These are just general steps that you can follow to optimize PostgreSQL in a Debian server. The exact steps may vary depending on your specific hardware and workload. It is always a good idea to consult PostgreSQL documentation and seek expert advice when optimizing PostgreSQL for production environments.
Django

Django model self many-to-many relation

<p>The provided code defines two classes: <code>Folder</code> and <code>FolderParent</code>. Let&#39;s go through each class and understand their functionalities:</p> <ol> <li> <p><code>Folder</code> class:</p> <ul> <li>It inherits from the <code>Timestamped</code> class (not …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Folder(Timestamped):
    name = models.CharField(max_length=50)
    depth = models.PositiveIntegerField(default=0)
    parents = models.ManyToManyField("self", through='FolderParent',
                                      through_fields=('source', 'target'),
                                      symmetrical=False, blank=True)



    class Meta:
        default_related_name = 'folders'
        verbose_name = 'folder'
        verbose_name_plural = 'folders'

    def __str__(self):
        return f"{self.name}"

    def get_depth(self):
        """
        Recursively calculates the depth of the folder in the tree structure.
        """
        depth = 0
        # Traverse up the tree to the root node
        parent_folders = self.parents.all()
        while parent_folders:
            depth += 1
            parent_folder = parent_folders.first()
            parent_folders = parent_folder.parents.all()
        if depth != self.depth:
            self.depth = depth
            self.save()
        return depth

    def get_ancestors(self):
        """
        Recursively gets a list of ancestor folders in the tree structure.
        """
        ancestors = []
        parent_folders = self.parents.all()
        while parent_folders:
            parent_folder = parent_folders.first()
            ancestors.append(parent_folder)
            parent_folders = parent_folder.parents.all()
        return reversed(ancestors)

    def get_breadcrumb(self):
        """
        Returns a list of ancestor folders and the current folder, 
        representing the breadcrumb for the current folder.
        """
        breadcrumb = list(self.get_ancestors())
        breadcrumb.append(self)
        return breadcrumb


class FolderParent(Timestamped):
    source = models.ForeignKey(Folder, on_delete=models.CASCADE,
                               related_name='folder_parent')
    target = models.ForeignKey(Folder, on_delete=models.CASCADE,
                               related_name='folder_child')

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['source', 'target'], name="folderparent")
        ]
        indexes = [
            models.Index(fields=['source', 'target']),
        ]
Django

django delete model function

<p>This Django view function is designed to handle DELETE requests and delete an item from a database based on the provided parameters. Let&#39;s go through the code step by step …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django.http import JsonResponse, HttpResponseBadRequest, Http404
from django.apps import apps
from django.views.decorators.http import require_http_methods

@require_http_methods(["DELETE"])
def delete_item(request):
    item_id = request.GET.get('id')
    if not item_id:
        return JsonResponse({'error': 'Missing ID parameter.'}, status=400)

    model_name = request.GET.get('model')
    app_name = request.GET.get('app')

    if not model_name or not app_name:
        return JsonResponse({'error': 'Missing model or app parameter.'}, status=400)

    try:
        model_obj = apps.get_model(app_label=app_name, model_name=model_name)
    except LookupError:
        return JsonResponse({'error': 'Invalid model or app parameter.'}, status=400)

    try:
        item = model_obj.objects.get(id=item_id)
        item.delete()
        return JsonResponse({'message': 'Item deleted successfully.'}, status=200)
    except model_obj.DoesNotExist:
        raise Http404("Item does not exist.")
Django

Django settings for vscode

django settings for vscode

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from vscode market place install  python,django,beautify

in your python virtual environment install packages

autopep8
pylint
pylint-django


in vscode  settings.json add 

{
    "emmet.includeLanguages": {
        "django-html": "html"
    },
    "python.PythonPath": ".venv\\scripts\\python.exe",
    "editor.formatOnSave": true,
    "python.formatting.provider": "autopep8",
    "python.linting.enabled": true,
    "python.linting.lintOnSave": true,
    "files.associations": {
        "**/templates/*.html": "django-html",
        "**/templates/*": "django-txt",
        "**/requirements{/**,*}.{txt,in}": "pip-requirements",
        "*.html": "html"
    },
}