<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aravinda S Holla</title>
    <description>The latest articles on DEV Community by Aravinda S Holla (@aravindas4).</description>
    <link>https://dev.to/aravindas4</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F522666%2Feba83139-f7ce-4f96-af30-cb552d4725f6.png</url>
      <title>DEV Community: Aravinda S Holla</title>
      <link>https://dev.to/aravindas4</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/aravindas4"/>
    <language>en</language>
    <item>
      <title>Django: Decouple Excerpt</title>
      <dc:creator>Aravinda S Holla</dc:creator>
      <pubDate>Sat, 05 Dec 2020 04:28:06 +0000</pubDate>
      <link>https://dev.to/aravindas4/django-decouple-excerpt-4c9j</link>
      <guid>https://dev.to/aravindas4/django-decouple-excerpt-4c9j</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In the Court of Judiciary, the loser is the one who has won, dead is the one who has lost.  - Boothayyana Maga Ayyu, Kannada Cinema.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In real-world projects, sensitive and important data such as server IP address, credentials, etc,  must be kept secret as much as possible. &lt;/p&gt;

&lt;p&gt;For doing so, we have lots of tools, utilities, packages, etc. But while using such a facility, there may be problems of another kind.&lt;/p&gt;

&lt;p&gt;Let's have an illustration.&lt;/p&gt;

&lt;h4&gt;
  
  
  Django Twangy:
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;cookie-cutter&lt;/code&gt; tool is a commonly used project template starter. And provides us with a clean folder structure, &lt;code&gt;.envs&lt;/code&gt;, for storing the data.&lt;/p&gt;

&lt;p&gt;These data are supplied to python code via environment variables, something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'ecommerce-portal',
        'USER': 'postgres',
        'PASSWORD': os.environ.get('DATABASE_PASSWORD'),,
        'HOST': os.environ.get('DATABASE_HOST', default='localhost'),
        'PORT': '5432',
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here secrets such as &lt;code&gt;DATABASE_PASSWORD&lt;/code&gt;, &lt;code&gt;DATABASE_HOST&lt;/code&gt; can be stored at &lt;code&gt;.envs&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  The Case:
&lt;/h4&gt;

&lt;p&gt;In the above scenario, if &lt;code&gt;Supervisor&lt;/code&gt; (a process control system) is used: While restarting sub-processes,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sudo supervisorctl restart ecommerce_celery
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the result maybe something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ecommerce_celery: ERROR (not running)
ecommerce_celery: ERROR (spawn error)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If subprocess worker log is checked:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django.db.utils.OperationalError: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;supervisor&lt;/code&gt; runs outside the context of the virtual environment, detached from environment variables&lt;/li&gt;
&lt;li&gt;In the above error case, the &lt;code&gt;supervisor&lt;/code&gt; has not received the database name to connect.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A possible try is to pass the database name in the config file as an environment variable, like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;environment = DATABASE_HOST="255.254.253.252", .....
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;at &lt;code&gt;/etc/supervisor/conf.d/ecommerce_celery.conf&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This does not seem to work but continues to persist with the same error.&lt;/p&gt;

&lt;h4&gt;
  
  
  Saviour:
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;python-decouple&lt;/code&gt; is a smart and simple solution that solves the above problem in a painless manner.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from decouple import config

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'ecommerce-portal',
        'USER': 'postgres',
        'PASSWORD': config('DATABASE_PASSWORD'),,
        'HOST': config('DATABASE_HOST', default='localhost'),
        'PORT': '5432',
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The restart does not produce the errors but runs successfully. &lt;/p&gt;

&lt;h3&gt;
  
  
  Links:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;  &lt;a href="https://pypi.org/project/python-decouple/"&gt;Python Decouple&lt;/a&gt; &lt;/li&gt;
&lt;li&gt; &lt;a href="https://cookiecutter-django.readthedocs.io/en/latest/"&gt;Cookie Cutter&lt;/a&gt; &lt;/li&gt;
&lt;li&gt; &lt;a href="http://supervisord.org/"&gt;Supervisor&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>django</category>
      <category>python</category>
      <category>original</category>
    </item>
    <item>
      <title>Django REST Framework: The powers of a Serializer (1)</title>
      <dc:creator>Aravinda S Holla</dc:creator>
      <pubDate>Sun, 29 Nov 2020 12:26:46 +0000</pubDate>
      <link>https://dev.to/aravindas4/django-rest-framework-the-powers-of-a-serializer-1-1igj</link>
      <guid>https://dev.to/aravindas4/django-rest-framework-the-powers-of-a-serializer-1-1igj</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Water has been taken for granted. - Jan Eliasson&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;DRF's Serializer has been proved to be a killing feature. &lt;/p&gt;

&lt;p&gt;Here I am going to share details of updating a Foreign key object data while updating a reverse relation object using serializer.&lt;/p&gt;

&lt;p&gt;The point here is that, while we usually use foreign key fields in the serializer for reading operation, we can also use them to write operations.&lt;/p&gt;

&lt;h3&gt;
  
  
  Update FK object data:
&lt;/h3&gt;

&lt;p&gt;Let's consider a scenario.&lt;/p&gt;

&lt;p&gt;Where we have an account, to which loan applications can be submitted. While approving an application, we need to collect the &lt;code&gt;approved_amount&lt;/code&gt; and &lt;code&gt;reason&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Account(models.Model):
    account_number = models.CharField(max_length=255)
    approved_amount = models.PositiveIntegerField(default=0)
    reason = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
        return self.account_number


class LoanApplication(models.Model):

    class Status(models.TextChoices):
        SUBMITTED = 'SUBMITTED', 'Submitted',
        REJECTED = 'REJECTED', 'Rejected'
        APPROVED = 'APPROVED', 'Approved'

    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    status = models.CharField(
        max_length=255, choices=Status.choices, default=Status.SUBMITTED)

    def __str__(self):
        return str(self.account)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above requirement shall be done using only one API call.&lt;/p&gt;

&lt;p&gt;As shown in the above code shots, we have &lt;code&gt;approved_amount&lt;/code&gt; and &lt;code&gt;reason&lt;/code&gt; in the &lt;code&gt;Account&lt;/code&gt; model, whereas approval shall be done to the &lt;code&gt;LoanApplication&lt;/code&gt; object. &lt;/p&gt;

&lt;p&gt;Let's see how the serializer tackles the above problem.&lt;/p&gt;

&lt;p&gt;As in the below shots, while approval, we collect the amount and reason in the same API. In serializer, just before updating &lt;code&gt;LoanApplication&lt;/code&gt;, we separate &lt;code&gt;Account&lt;/code&gt; data and update to the appropriate account, then proceed to update the loan application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AccountSerializer(serializers.ModelSerializer):

    class Meta:
        model = Account
        fields = '__all__'


class LoanApplicationSerializer(serializers.ModelSerializer):
    approved_amount = serializers.IntegerField(
        source='account.approved_amount')
    reason = serializers.CharField(source='account.reason')

    class Meta:
        model = LoanApplication
        exclude = ('account',)

    def update(self, instance, validated_data):
        account_data = validated_data.pop('account', None)
        if account_data:
            account_serializer = AccountSerializer(
                instance.account, data=account_data, partial=True)
            account_serializer.is_valid(raise_exception=True)
            account_serializer.save()

        return super().update(instance, validated_data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Links:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt; &lt;a href="https://github.com/aravindas4/django-shots1/tree/master/app1"&gt;Github code&lt;/a&gt; &lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>django</category>
      <category>original</category>
      <category>serializer</category>
      <category>rest</category>
    </item>
  </channel>
</rss>
