<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ryan Febriansyah on Medium]]></title>
        <description><![CDATA[Stories by Ryan Febriansyah on Medium]]></description>
        <link>https://medium.com/@EnterGodMode__?source=rss-96e4ed575306------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9ApKKpUTesg7ZKC2.jpg</url>
            <title>Stories by Ryan Febriansyah on Medium</title>
            <link>https://medium.com/@EnterGodMode__?source=rss-96e4ed575306------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 00:12:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@EnterGodMode__/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Running Django Project with Bash Script]]></title>
            <link>https://medium.com/@EnterGodMode__/running-django-project-with-bash-script-8563a1c7bcc0?source=rss-96e4ed575306------2</link>
            <guid isPermaLink="false">https://medium.com/p/8563a1c7bcc0</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Ryan Febriansyah]]></dc:creator>
            <pubDate>Thu, 26 Mar 2020 14:24:24 GMT</pubDate>
            <atom:updated>2020-03-26T14:24:24.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDBtwOLcErbDn67VSF5zhg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@judebeck?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jude Beck</a> on <a href="https://unsplash.com/t/textures-patterns?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Recently i found out that when i will run the django project with default command like python manage.py runserver, it&#39;s a bit “difficult” for me cause the first time when we run django, we need to set up the virtual environment and also cause too much typing in keyboard (lol). I initially explored for whether there is some way or django packages such as auto-completion to run the django project without typing python manage.py runserver, and I got an idea after reading nginx configuration for host django server to make a kind of bash script so I could run django (entirely) and automatically activate the virtual environment.</p><p>Basically, the thing is it will run or host the django project using gunicorn (WSGI server).</p><p><strong>First of all</strong>, you need to install gunicorn on your machine and i’m assuming you have a django project. You can also try whether the gunicorn that has been installed on your machine can run the django project by trying to bind the django localhost like this :</p><p>gunicorn &lt;your_project&gt;.wsgi:application --bind localhost:8000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*QlkzWfmYrjLTmL4MVDvgyA.png" /><figcaption>It work</figcaption></figure><p>If binding django localhost with gunicorn is succeed, you can see the log in your terminal as shown in the image. The next step, you can create a bash file by writing kind of a script like this (To be noted, you can create a new file in outside django project or create a new folder and then place the file in that folder as long a you can configure it correctly) :</p><pre>#!/bin/bash</pre><pre>NAME=&quot;your_project_name&quot;<br>DJANGODIR=/path/to/your_project_name<br>SOCKFILE=/path/to/your_project_name/run/gunicorn.sock<br>USER=your_name<br>GROUP=your_group<br>NUM_WORKERS=3<br>DJANGO_SETTINGS_MODULE=your_project.settings<br>DJANGO_WSGI_MODULE=project.wsgi</pre><pre>echo &quot;Starting $NAME as `whoami`&quot;</pre><pre>cd $DJANGODIR<br>source ../Env/bin/activate <br>export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE<br>export PYTHONPATH=$DJANGODIR:$PYTHONPATH</pre><pre>RUNDIR=$(dirname $SOCKFILE)<br>test -d $RUNDIR || mkdir -p $RUNDIR</pre><pre>exec /Env/bin/activate/gunicorn ${DJANGO_WSGI_MODULE}:application \<br>  --name $NAME \<br>  --workers $NUM_WORKERS \<br>  --user=$USER --group=$GROUP \<br>  --bind=$SOCKFILE \<br>  --log-level=debug \<br>  --log-file=-</pre><p>As a concern, you can adjust the virtual environment to your own, and normally gunicorn will be saved in bin folder in python virtualenv. The sockfile in that script function to make communication between django application with gunicorn socket and will do binding through directory named /run, and make sure the user that you configure in script has permission to run this service or you can give the permission outside the script with chmod +x your_file.sh .</p><p>After all, you can run django entirely with activate virtual environment by simply typing name of your bash file, (for mine it look like this) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*1BEAS23lNyF5wf08dpZAEg.png" /><figcaption>It work again</figcaption></figure><h3>Bonus</h3><p>You can also use a supervisor (and of course you also need to install the supervisor first) to monitor your django project processes, with simple configuration like this (create new file with .conf extension) :</p><pre>[program:nginx_service]</pre><pre>command = /path/to/your_project/and/bash_file<br>user = your_name<br>stdout_logfile = /path/to/your_project/logs/gunicorn_supervisor.log<br>redirect_stderr = true<br>environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8</pre><p>This supervisor will act to monitor and control a number of processes on UNIX-like operating systems, for example when you run your django project, and an error appears like a port that has been used the information will be saved into a log and you can also see the information in your log directory. And also, make sure you create a directory for the log and update the process on the supersivor and reload the supervisor, you just simply run the command sudo supervisorctl update and sudo supervisorctl reload . If all processes have been completed, you can check it out if your django project service is running or not using ps aux | grep gunicorn and it will appear like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLMeTFU14g0yx2dPwg2huA.png" /><figcaption>Voila</figcaption></figure><p>And that’s that.… you can explore yourself and be creative as possible to run a django project with a bash script, thank you for reading :D</p><p>Some nice references you can read here :</p><ol><li><a href="https://kuttler.eu/code/simple-bash-deployment-script-django/">https://kuttler.eu/code/simple-bash-deployment-script-django/</a></li><li><a href="https://github.com/harikvpy/deploy-django">https://github.com/harikvpy/deploy-django</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8563a1c7bcc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Django Rest Framework]]></title>
            <link>https://medium.com/@EnterGodMode__/optimizing-django-rest-framework-b014e62eb932?source=rss-96e4ed575306------2</link>
            <guid isPermaLink="false">https://medium.com/p/b014e62eb932</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ryan Febriansyah]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 06:07:30 GMT</pubDate>
            <atom:updated>2019-04-02T06:07:30.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WamGu7mpG8hivfbQt_2g-g.jpeg" /></figure><p>Django Rest Framework is a very powerful and flexible toolkit for building Web APIs. It is allow us to build a simple yet robust standards based on REST APIs for web applications. However, a simple and straightforward usage of Django Rest Framework sometimes can kill performance of our APIs especially in the database. As database queries are relatively slow, <br>there are several ways to deal with this like Tom Christie wrote on his article named <em>Web API performance: profiling Django REST framework, </em>the benefits might will accelerate the process and responsiveness of web application rather we change the code structure of the program on a large scale, we only need to use of select_related and prefetch_related methods based on Django ORM.</p><p>When you build a Django Rest Framework view, you often want the return to include data from more than one related table or maybe you want to use nested relationship in your serializer that could be crushing the APIs performance. This happens cause Django ORM only fetches the minimum amount of data needed to respond to the current query. So, the basic code for models is like a simple blog post. You have 3 different classes such asUser, Comment and BlogPost itself. for comment classes and the blog post itself will have a foreign key relationship with the user class, with additional comments classes also having a relationship with the blog post class. And here the serializers for our models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*0d1-bVyi7mr0dwiSgrgf5A.png" /></figure><p>then, in this case we will try to insert two data into our serializers produces the following in the console like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*mcxy83hZieUQ-CrEQIV9_Q.png" /></figure><p>As you can see, inserting two data into the serializer requires at least 10 database queries and if this happens in a real cases with several hundred data, of course it will be very troublesome. To displaying the number of database queries that happened we can override the dispatch() method, and it is very important before starting optimization because we first need profiling the django views. Actually, there are many different ways to profile django views <br>but I prefer this method. The code like here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*mzURMpNHluikiysbaWJzrw.png" /></figure><p>Besides the code above, you also need to import the connection from the django database.</p><p>Now we can see that BlogPost models has a foreign key relationship author to User, and it has been included in the serializer. By default, django will make a database query each time an author needs to be serialized. To avoid this, we can use select_related() on the viewset queryset to tell django to merge this extra query with the primary BlogPost query. Now we try to sending another request of the two data that we have entered before and produces like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*HhFXhBBYeOkzXyk_nlS5aQ.png" /></figure><p>for the number of queries alone it decreases to 8 and that is still a lot queries, so let’s take a look onBlogPostSerializer .BlogPostSerializer will serializes a list of comments from the reverse relationship to Comment. Without optimization, this will cause a database query to occur for each blog post. to handle this things we can use prefetch_related() method on the viewsets to reduce this to just one extra query. But, the things is this only reduced our total numbers of queries down by one, but there are still a lot of queries happening. To improve this we need use prefetch_related() also inComment , because Comment has a foreign key relationship author to User that it is serializing, the following code like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*rB06sJ7w6zGBEM2N6dkN9g.png" /></figure><p>Now we try to sending another request of the two data that we have entered before and produces like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*MfA6Nn171LXck9YCdbCA1Q.png" /></figure><p>As you can see the number of queries now goes down to just 3 queries. This approach can have a big effect on our web APIs, like Scott Stafford said that if using this method the return function for the API can drop below 1 second than we don’t do an optimization that allows it to process around 5–10 seconds and our API performance will usually much better.</p><p>So, is it just this only way to optimize the Django Rest Framework queries? <strong>No. </strong>You can also do this by normalizing the serializer and become more effective with the Django ORM. One way that I found was to change some of the code structure in our serializer into PrimaryKeyRelatedField or using HyperLinkedRelatedField , this function may be used to represent the target of the relationship using its primary key or represent the target of the relationship using a hyperlink and it also decreases the number of queries, but that only decreases to around 5–6 queries counted. The other ways is use Prefetch objects to control prefetch_related() at a deeper level, using Prefetch allows us to define the queryset for the prefetch. This means we can use select_related() to merge the comments and comments__author queries into one.</p><p>Other ways, you can also optimize it by writing more simple code and it minimizes the total from the queries itself.</p><p><strong>References</strong></p><ul><li><a href="http://www.django-rest-framework.org/">Django REST Framework</a> documentation</li><li>Scott Stafford, the author of <em>Optimizing slow Django REST Framework performance</em></li><li>Tom Christie, the author of <em>Web API performance: profiling Django REST framework</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b014e62eb932" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Nested API Using Django Rest Framework]]></title>
            <link>https://medium.com/@EnterGodMode__/simple-nested-api-using-django-rest-framework-d2dd9f0ff093?source=rss-96e4ed575306------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2dd9f0ff093</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Ryan Febriansyah]]></dc:creator>
            <pubDate>Fri, 18 Jan 2019 12:26:12 GMT</pubDate>
            <atom:updated>2019-01-18T12:26:12.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzJ0zqItik6y-XlG9p5ASg.jpeg" /></figure><p>In this article, you will learn how to build a REST API using Django Rest Framework. Prerequisites, Python version 3.6, Django 2.1.4, and Django Rest Framework version 3.6 were used to build the API that contained here. In this case, it’s assumed that all every command will be run in the virtual environment.</p><p>Let’s get an anology a popular library approach. Example, your API allows you to post data such as the name of the books and also the authors. Mostly, endpoints for authors will look like this:</p><blockquote><strong>books/?author={author_id}</strong></blockquote><p>However, we want the query from the endpoint to be logically structured which allows it to be like:</p><blockquote><strong>authors/{author_id}/books</strong></blockquote><p>How we will implement it? for that, we can use <em>nested relationships</em> on the django rest framework. Nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field. By default nested serializers are read only. If you want to support write operations to a nested serializer field, you’ll need to create create() and update() methods in order to explicitly specify how the child relationships should be saved.</p><p>Now, let’s take a look to build nested relationships in Django Rest Framework:</p><p>First of all, we need some interconnected models to wrap our API around. You can get this by create an application. For this case, i’ll create a new application called shelf, and then add our app to settings.py. After that, create a simple models in shelf like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*inWf3Abw45Da1xxwlaw4xA.png" /></figure><p>And don’t forget to make migrations and apply them by following command py manage.py makemigrations and py manage.py migrate.</p><p>For serializers, we need to create some serializers to handle our data interchange. For Django Rest Framework, uses JSON by default but you can change that to XML or YAML. To make the serializer on this API it wasn’t all that hard, we only need a new class which defines the model we have created before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*yCfEyL7_pKGrg6lN3w9kSA.png" /></figure><p>For note, you can actually replace the values in the attributes of fields using magic values __all__ but i think listing specific fields is highly recommended, it makes your API much safer.</p><p>For viewsets, i’ll write using basic viewsets in views.py. You also can separate that API files by create a new files like api.py , and then remember to update imports in other files accordingly. The final step is to create a basic routing for the API and connect the viewsets and then test the API behavior by using py manage.py runserver , then go to <a href="http://127.0.0.1:8000/api/">http://127.0.0.1:8000/api/</a> and create some entries. if your API run wells, it will display a page containing data entries. This API has an API feature in general, we can post a data and then we can also edit the data.</p><p>Now it’s time for the main subject of this article, how to make a nested relationship API using Django REST Framework. There are a couple packages that handle nesting logic. Such as DRF Nested Routers and DRF-Extensions. To understand it more deeply, you can check it in the django rest framework documentation. For now, we will use DRF-Extensions as it is the most feature rich package that we can use and also it quite simple. First thing to do, install the drf-extensions using pip install drf-extensions and add a mixin to our viewsets. It will ensure that the url params are correctly handled and the queryset filtered properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*4oIlIUjg7XaRlSAoIOmzpg.png" /></figure><p>Also don’t forget to to extend our DefaultRouter . To do this, we will create a new file called routing.py in our main directory, and then we can start nesting our routes. This routes allow us to create subrouters to register nested endpoints. It’s almost as simple as registering normal routers, for exception for this case we only need to add two extra params so that the automation will know how to connect everything together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*3qK0j3iR8xVyAYscxoE0eQ.png" /></figure><p>After these changes we can get a list of all books by a certain author, and reload the server and go to this <a href="http://127.0.0.1:8000/api/authors/1/books/">http://127.0.0.1:8000/api/authors/1/books/</a>. if your API is successful then the display will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLnKKRCxFo9NgeJTzybqZA.png" /></figure><p>if you look at the navigation section, there is a new link that you can click on and allow you to see the previous section up to API endpoints. If you go through to Author Instance, you will see who the authors of the book, and you can also delete it. For the Author List, it will show a list of authors.</p><p>Important to note, base_name in router eneeds to be unique across your API. It’s the name that will be the root for url names used by reverse() function. Now you should be able to build a nested relationship API using Django REST Framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2dd9f0ff093" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>