<?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 Ozgur Yarikkas on Medium]]></title>
        <description><![CDATA[Stories by Ozgur Yarikkas on Medium]]></description>
        <link>https://medium.com/@ozguryarikkas?source=rss-6a7cb9396941------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s8googiBn8QF9zcUGux2rg.jpeg</url>
            <title>Stories by Ozgur Yarikkas on Medium</title>
            <link>https://medium.com/@ozguryarikkas?source=rss-6a7cb9396941------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 20:24:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ozguryarikkas/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[LFCS — Linux Foundation System Administrator exam Study Guide with Exercises Part-1]]></title>
            <link>https://ozguryarikkas.medium.com/lfcs-linux-foundation-system-administrator-exam-study-guide-with-exercises-part-1-d9ddc9efc39f?source=rss-6a7cb9396941------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ddc9efc39f</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[debian]]></category>
            <category><![CDATA[redhat-linux]]></category>
            <category><![CDATA[lfcs-exam-questions]]></category>
            <category><![CDATA[linux-foundation]]></category>
            <dc:creator><![CDATA[Ozgur Yarikkas]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 13:56:40 GMT</pubDate>
            <atom:updated>2021-11-10T18:15:30.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>LFCS — Linux Foundation System Administrator exam Study Guide with Exercises</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*683aohVd6CPBulctZDX63w.png" /></figure><p>I recently took LFCS exam and was able to get my certificate in my first attempt. I know that it is a real struggle to have an achievement in this exam, especially in the first attempt, so I wanted to share my experience and prepare a study guide with a few exercises that you would most probably stumble upon very similar challenges in LFCS exam.</p><p>This post is intended to give you the understanding of what kind of tasks you might expect to get in the exam. As the time being, you can expect 24 tasks with multiple sub-tasks to solve in 2 hours time span. Key point to success will be the time management for most of you, and we know that practice makes perfect.</p><p>Distribution of tasks in exam are given from Linux Foundation as follows:</p><ul><li>Essential Commands — 25%</li><li>Operation of Running Systems — 20%</li><li>User and Group Management — 10%</li><li>Networking — 12%</li><li>Service Configuration — 20%</li><li>Storage Management — 13%</li></ul><p>You may even find a task with a few sub-tasks, coming from different subjects.</p><blockquote>Don’t forget! using man -k &lt;command&gt; can be very useful to list all the related commands with a short description. Use it wisely..</blockquote><p>There is an exercise questions sheet provided originally by Linux foundation that I am adding the link below:</p><p><a href="https://training.linuxfoundation.org/wp-content/uploads/2019/04/LFCS-Practice-Questions-v1.0.pdf">https://training.linuxfoundation.org/wp-content/uploads/2019/04/LFCS-Practice-Questions-v1.0.pdf</a></p><p>I encourage you to solve each task first in your practice environment. I will give the most practical solutions to a few of those tasks for each subject. Not only that, but I will also give some tips with a mention ‘good to know’ to give some alternative solutions for similar tasks. Let’s begin.</p><h3>Domain — Essential Commands</h3><p><strong>Q1</strong> — <strong>Open the file under home/student/textreferences/editme.txt and complete the following tasks:</strong></p><pre>1. Move line 777 to line 1</pre><pre>2. Remove line 7000. </pre><pre>3. Replace every occurrence of the word &quot;Earth&quot; shown with an uppercase E, with the word &quot;Globe&quot;</pre><pre>4. Add a new line at the very end of the document that contains &quot;Auctores Varii&quot;</pre><p><strong>Solution:</strong></p><p>Since I don’t have a practice edit.txt file for this case, I will create one first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca3583b194cb38b8867bc3997388f8ee/href">https://medium.com/media/ca3583b194cb38b8867bc3997388f8ee/href</a></iframe><p>The best practice is to use ed or sedfor any move and replace operation in Linux:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74c3ebc737d9001b570b2d8cc15ac2e6/href">https://medium.com/media/74c3ebc737d9001b570b2d8cc15ac2e6/href</a></iframe><p><strong>Q2</strong> — <strong>Working with archives and compressed files is an integral part of the System Administrator’s job. Perform the following tasks to demonstrate your ability to work with archives and compressed files:</strong></p><pre> 1. Extract all files from archive file /opt/SAMPLE001.zip into target directory /opt/SAMPLE001</pre><pre>2. Create a tar archive file /opt/SAMPLE0001.tar containing all files in the directory /opt/SAMPLE001 </pre><pre>3. Compress the tar archive file /opt/SAMPLE0001.tar using the bzip2 compression algorithm </pre><pre>4. Compress the tar archive file /opt/SAMPLE0001.tar using the xz compression algorithm </pre><pre>Make sure that the uncompressed archive file /opt/SAMPLE0001.tar is not removed after creating the compressed versions of the archive file!</pre><p><strong>Solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/056c49d482558a212b9ddf112320b94c/href">https://medium.com/media/056c49d482558a212b9ddf112320b94c/href</a></iframe><h3>Domain — Operation of Running Systems</h3><p><strong>Q1</strong> — <strong>Create a bash shell script named </strong><a href="http://certscript.sh/"><strong>certscript.sh</strong></a><strong> under /home/student/apps/</strong></p><pre>1. Make sure the script can be invoked as ./certscript.sh</pre><pre>2. The first line of output from the script should consist of the name of the user who invoked it.</pre><pre>3. The second line of output should contain the IP address of the default gateway.</pre><p><strong>Solution:</strong></p><p>We will test it out first with a few examples and after that create our script and update the permissions to make it executable</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/976b00e90fb007660d80cae32bf98167/href">https://medium.com/media/976b00e90fb007660d80cae32bf98167/href</a></iframe><p>Let’s create certscript.sh with these findings in mind:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74705b04f73fda2523f3c953c063a865/href">https://medium.com/media/74705b04f73fda2523f3c953c063a865/href</a></iframe><p>Make it executable by changing permissions and run it for testing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5465d3e10de8230b46454e402ef1a9fa/href">https://medium.com/media/5465d3e10de8230b46454e402ef1a9fa/href</a></iframe><p><strong>Q2</strong> — <strong>Create a cron job that kills all processes named </strong><strong>scan_filesystemwhich is owned by root, every minute.</strong></p><p><strong>Solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76928b3c93c6c538f5492c83231d0fb4/href">https://medium.com/media/76928b3c93c6c538f5492c83231d0fb4/href</a></iframe><p>To check your cron job logs, enter:</p><pre>tail -f /var/log/syslog</pre><blockquote>man crontab gives you a detailed information on how to use the command but it doesn’t provide any useful examples. using man 5 crontab documentation manual can definitely save you day with a lot of useful examples and use cases.</blockquote><h3>Domain — User &amp; Group Management</h3><p><strong>Q1</strong> — <strong>Create a candidate user account with the password cert456. Modify the sudo configuration to let the candidate account access root privileges with no password prompt.</strong></p><p><strong>Solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8527d2f2d4453d030d4f2a98bbde801/href">https://medium.com/media/c8527d2f2d4453d030d4f2a98bbde801/href</a></iframe><p><strong>Q2</strong> — <strong>Configure the system so that an empty NEWS file is automatically created in the home directory of any new user.</strong></p><p><strong>Solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc4c03b32ce655ec4eda5011a926c4d4/href">https://medium.com/media/dc4c03b32ce655ec4eda5011a926c4d4/href</a></iframe><p><strong>Q3</strong> — <strong>Create a new user account with the following attributes:</strong></p><pre>- Username is harry. <br>- Password is magic. <br>- This user’s home directory is defined as /home/school/harry/<br>- This new user is a member of the existing students group<br>- The /home/school/harry/binaries/ directory is part of the PATH variable.</pre><p><strong>Solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b119ff2a80ed933dfb8a765c6d14258/href">https://medium.com/media/0b119ff2a80ed933dfb8a765c6d14258/href</a></iframe><h3>Domain — Networking</h3><p><strong>Q1</strong> — <strong>Find ports under /etc/services</strong></p><pre>1. Find the name of the service which uses TCP port 2605, as documented in /etc/services, and write the service name to the file /home/student/port-2605.txt.</pre><pre>2. Find all the ports used for TCP services IMAP3 and IMAPS, again as documented in /etc/services, and write those port numbers to the file /home/student/imap-ports.txt</pre><p><strong>Solution:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/113cfd8015821087a44e686a5333754b/href">https://medium.com/media/113cfd8015821087a44e686a5333754b/href</a></iframe><h3>Conclusion</h3><p>Service Configuration and Storage Management domains are also very important as you may expect around 30–35% of the tasks from these two, but this post is already long enough to cover all the tasks with detailed solutions of the practice questions. I will cover the other questions in the pdf in part-2 of this study guide. Please feel free to ask me any questions and follow me for getting part-2 of this post when it is released.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ddc9efc39f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to creating an API Endpoint with Django Rest Framework and Django Filters with PostgreSQL]]></title>
            <link>https://ozguryarikkas.medium.com/a-guide-to-creating-an-api-endpoint-with-django-rest-framework-and-django-filters-with-postgresql-563a12b3accb?source=rss-6a7cb9396941------2</link>
            <guid isPermaLink="false">https://medium.com/p/563a12b3accb</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Ozgur Yarikkas]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 12:34:31 GMT</pubDate>
            <atom:updated>2019-09-07T11:07:28.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Comprehensive Guide to creating an API Endpoint with Django Rest Framework and Advanced Django Filters with PostgreSQL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6onebwzFcvaJjw77fyu-fQ.png" /></figure><p>This guide will give you hints on how to create an API endpoint with django rest framework. We are also going to use django filters package on top of DRF to apply sorting, search, filter by name like filtering capabilities for our API by URL parameters like:</p><pre>http://localhost:8000/api/sales?region=Europe&amp;groupby=country&amp;date_from=01.01.2015&amp;date_to=31.12.2015&amp;ordering=-revenue</pre><p>cool, right! in this URL, we filtered our dataset for this query:</p><p>Show revenue, earned in 2015 in Europe region, broken down by country and sorted by revenue in descending order.</p><p>and SQL statement for the query would be:</p><pre>SELECT country, SUM(quantity), SUM(price), SUM(cost), SUM(revenue), SUM(profit)<br>FROM public.app_sales <br>WHERE region=&#39;Europe&#39;<br>AND date &gt;= &#39;01.01.2015&#39;<br>AND date &lt;= &#39;12.31.2015&#39;<br>GROUP BY country<br>ORDER BY SUM(revenue) DESC;</pre><p>anyways, I am sure you got the point. We will design and build our API in order to query our database with complex filters.</p><p>I assume that you have a basic understanding of Django and preparing a python application virtual environment with python virtualenv module. So, I will skip these steps in this tutorial. Please refer <a href="https://medium.com/js-dojo/how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-e89a83318e9c">one of my older posts with Django</a> to setup a virtual environment.</p><p>I have this project in github but it is a dockerized version with docker-compose. For the sake of simplicity, I will cover this tutorial as it is inside of a virtual environment. If you want to have a look at the complete solution, check my github repository:</p><p><a href="https://github.com/talented/Sales-Records-API">talented/Sales-Records-API</a></p><p>If you are still here, let’s continue. I assume that you installed Django and DRF, also install Django filters with the following command:</p><pre>pip install django-filter</pre><p>After that start a Django project inside your environment and run the commands below:</p><pre>django-admin startproject apitest<br>django-admin startapp app</pre><p>Open settings.py and update Installed_Apps as shown below:</p><pre>INSTALLED_APPS = [</pre><pre>&#39;django.contrib.admin&#39;,<br>&#39;django.contrib.auth&#39;,<br>&#39;django.contrib.contenttypes&#39;,<br>&#39;django.contrib.sessions&#39;,<br>&#39;django.contrib.messages&#39;,<br>&#39;django.contrib.staticfiles&#39;,<br>&#39;app&#39;,<br>&#39;rest_framework&#39;,<br>&#39;django_filters&#39;,</pre><pre>]</pre><p>We are going to use PostgreSQL as our database system. You can install pgAdmin4 for administration of your postgreSQL database.</p><p>Again in settings.py, update as below:</p><pre>DATABASES = {</pre><pre>&#39;default&#39;: {<br>&#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>&#39;HOST&#39;: &#39;&#39;,<br>&#39;NAME&#39;: &#39;name of your database&#39;,<br>&#39;USER&#39;: &#39;your postgresql username&#39;,<br>&#39;PASSWORD&#39;: &#39;your postgresql password&#39;,<br>&#39;PORT&#39;: 5432,</pre><pre>}<br>}</pre><p>We have to install psycopg2 python library in order to connect with postgreSQL. It is a postgresql adapter for python. I had some incompatibilities with django’s current version when I installed 2.8 version so I suggest you to install an older version not to have any problem. Run command below:</p><pre>pip install psycopg2==2.7.0</pre><p>Basic setups are done. Let’s create our database model. But before, I would like to give some information for the data source to be used.</p><p>We are going to use an open dataset for 2000 Sales records of 12 product types. First 10 records from the dataset is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6onebwzFcvaJjw77fyu-fQ.png" /></figure><p>You can find it in my <a href="https://github.com/talented/Sales-Records-API">github repository</a> under pgdata folder as ‘2000_Sales_Records.csv’. We will populate our postgreSQL database after we created our model in Django and migrate it so our fields will be ready.</p><p>let’s start creating our Django model with these field names. Update models.py as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359844a2d59e22498080833be3a6a285/href">https://medium.com/media/359844a2d59e22498080833be3a6a285/href</a></iframe><p>our model is ready, it is time to migrate our fields into postgreSQL database, a table with a name app_sales will be created along with the fields we defined. Run commands below:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>Now our database is ready, but we need to import the data from ‘2000_Sales_Records.csv’ into postgreSQL. If you already downloaded it, put in under your main project folder apitest with the same level of manage.py and run sql command below inside of pgadmin4 (easier) or from the command line (by reaching out to postgreSQL db with psql command). I will go with pgadmin4.</p><p>After you start postgreSQL server, open pgadmin4 and reach out to “postgres” database as we used it as a name for our db. Open schemas and then Tables, right click to app_sales table and open Query Tool. Paste the following SQL command and click Execute (or F5):</p><pre>COPY app_sales(region,country,ptype,channel,date,quantity,price,cost,revenue,profit)<br>FROM<br> &#39;{exact location of your project folder}/2000_Sales_Records.csv&#39; DELIMITER &#39;;&#39; CSV HEADER;</pre><p>you can find the exact location of your project folder by typing pwd from command line.</p><p>Now it is time to test with Django interactive console that you have successfully populated the db. Enter commands below to activate the shell:</p><pre>python manage.py shell</pre><p>Query your db as below inside the shell:</p><pre>from app.models import Sales<br>Sales.objects.all().count()</pre><p>If it returns a count other than 0, it means that your data is successfully imported.</p><p>We can continue with designing our application system structure. We are going to use DRF and we will deliver and API, so it is a good practice to collect all the related api files under the same folder. Create a folder called ‘api’ under ‘app’ folder and create the files inside that folder as shown below. I will explain each in detail when we are writing our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*BgS5IzZAV6VHo2rjhRNbUA.png" /></figure><p>let’s start with serializers.py, open and update it with code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca12a352afb7f49f79e305eb056e1cba/href">https://medium.com/media/ca12a352afb7f49f79e305eb056e1cba/href</a></iframe><p>Even we used a ModelSerializer to create our SalesSerializer we need to define our models because when our api is filtered, some of the fields will not be visible so we need to set to default required value to False otherwise we get errors.</p><p>As you may notice, I have also added a calculated field called profit_percentage as a serialised field. We will need to extend our model to use this field. How can we achieve it?</p><p>Django managers come to the help when we need an extended queryset with aggregated and calculated fields. First add the following code inside of models.py</p><pre># models.py</pre><pre>from django.db import models<br>from app.managers import SalesQuerySet   <strong><em># &lt;-- Add This</em></strong></pre><pre>.<br>.. <br>...</pre><pre>objects = SalesQuerySet.as_manager()     <strong><em># &lt;-- Add This</em></strong></pre><p>and update managers.py as given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65afd775061f6f4bfa94b40db408c3a1/href">https://medium.com/media/65afd775061f6f4bfa94b40db408c3a1/href</a></iframe><p>We are able to kind of overwrite our objects attribute of our Sales model and we set SalesQuerySet class as our manager. Our models Manager’s default get_queryset method will return this class and let us call calculated_quantity method with our model’s object attribute.</p><p>We use django annotate filter in order to calculate the percentage of profit with profit and revenue fields. ExpressionWrapper helper class lets us output the result in a new field → DecimalField() in our case. we will call our extended queryset by Sales.objects.calculated_quantity()</p><p>let’s continue with views.py under api folder. Update it as given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc177cd228d86117e840a2a661bbc50e/href">https://medium.com/media/dc177cd228d86117e840a2a661bbc50e/href</a></iframe><p>We need to make an update for url routing so our api will be ready. Open urls.py inside apitest folder and update it as given below:</p><pre># /apitest/urls.py</pre><pre>from django.contrib import admin<br>from django.urls import path, include</pre><pre>urlpatterns = [<br>path(&#39;admin/&#39;, admin.site.urls),<br>path(&#39;&#39;, include(&#39;app.api.urls&#39;))<br>]</pre><p>and open urls.py inside of app/api folder that you created and update as given below:</p><pre># /app/api/urls.py</pre><pre>from django.urls import path<br>from .views import SalesListAPIView</pre><pre>urlpatterns = [<br>path(&#39;api/sales&#39;, SalesListAPIView.as_view())<br>]</pre><p>we define the url path for our API endpoint and we tell that we will use SalesListAPIView as our view. Now, our application is half-ready but we can test it out in the browser. Run python manage.py runserver and open your browser and type localhost:8000/api/sales</p><p>You should be seeing DRF generic API list view screen with your data listed ascending. Let’s add some settings for DRF in settings.py. Add the given code to the end:</p><pre>REST_FRAMEWORK = {<br>&#39;DEFAULT_RENDERER_CLASSES&#39;: (<br>&#39;rest_framework.renderers.JSONRenderer&#39;,<br>&#39;rest_framework.renderers.BrowsableAPIRenderer&#39;,<br>),<br>&#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.LimitOffsetPagination&#39;,<br>&#39;PAGE_SIZE&#39;: 20<br>}</pre><p>Now, we have pagination as well. Refresh the page to see the changes. If you comment out rest_framework.renderers.BrowsableAPIRenderer and reload the page you will see that API is just available only in JSON format. You may use like that if you don’t need an interface. In most cases, you won’t need because your API endpoint will be used by a request from client side and required data format will be most likely JSON.</p><h3>Applying Filters</h3><p>So far we have worked to prepare our API endpoint to get a complete list of the sales records. The crucial thing is how to filter these records. Open filters.py under api folder and add the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/351a06428996ae7acc45fab470b903a9/href">https://medium.com/media/351a06428996ae7acc45fab470b903a9/href</a></iframe><p>We have defined a filter class as a Filterset and added all of the model fields and our pre-calculated profit field. Just to use ‘is_less_than_or_equal_to’ and ‘is_greater_than_or_equal_to’ filter lookups by using lte and gte respectively, we have defined a number filter for each field which has numeric values.</p><p>For filtering by date, we have defined method filters so we can parse the date first and apply django’s queryset filtering by lte and gte lookup expressions.</p><p>For more complex filters like groupby, we have also defined a custom method. We are not able to use numeric or date fields with this filter because it doesn’t make sense. We first get the given query params defined in self.request and use annotate function and get the total value of numeric fields in our database by using Sum expression. We use the same calculation for profit_percentage field but this time by using the total profit and revenue values.</p><p>So far, we have a fully functional API endpoint with some advanced filtering capabilities and you can even add more filters as I hope you have learned a lot from this post.</p><p>There will be issues like performance optimisation etc. to be taken care of when we are dealing with a large database. We should be implementing effective caching methodologies and try to optimise our queries and database for speed and lower memory, maintainability and scalability. So, This will be a topic of another post.</p><p>You can find the source code <a href="https://github.com/talented/Sales-Records-API">here</a> on Github.</p><p>Thanks for reading! Please let me know if you have any questions and give me a Star on github if you find it useful for your projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=563a12b3accb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 — How to build a File Manager Storage web app with Django Rest Framework and Vue.js]]></title>
            <link>https://medium.com/js-dojo/part-2-how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-852e30e52aa5?source=rss-6a7cb9396941------2</link>
            <guid isPermaLink="false">https://medium.com/p/852e30e52aa5</guid>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[ag-grid]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ozgur Yarikkas]]></dc:creator>
            <pubDate>Sat, 04 May 2019 13:58:46 GMT</pubDate>
            <atom:updated>2019-07-20T15:46:42.369Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2 — How to build a File Manager Storage web app with Django Rest Framework and Vue.js with Vuex and Ag-grid integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75xHI2SIbtL38I7UgcO3NA.png" /></figure><p>This article is Part 2 of “How to build a File Manager Storage web app series”. In <a href="https://medium.com/js-dojo/how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-e89a83318e9c">Part 1</a>, we completed the setup of Django rest framework and Vue.js and connected them by the help of Django webpack loader. In the second part, we will go deep in vue and create our application for uploading, listing and deleting any files with an eye-catching ui. 💎</p><p>I will guide you step by step to create a File Manager storage web application. we will have a tech stack as Django with DRF, vue.js with webpack and vuex and libraries such as ag-grid, bootstrap, axios etc. 🎬</p><p>In the second part of this tutorial we are going to:</p><ul><li><a href="#eef4">Configure DRF to upload and delete files</a></li><li><a href="#1921">Configure main.js and install vue libraries to be used</a></li><li><a href="#66f2">Create Vue components and Configure Ag-Grid settings</a></li><li><a href="#7d37">Configure vuex settings for CRUD with Axios</a></li></ul><p>Let’s start coding! ☕️</p><h4>Configure DRF to upload and delete files</h4><p>in Part 1, we created an API endpoint with Django rest framework. We will update only <strong>viewsets.py</strong> that we created under filemanager. This will be the only update that we need to do in server side.</p><p>update viewsets.py as given the final code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ecfd6802c6a63a94cd8decae51e75d/href">https://medium.com/media/e9ecfd6802c6a63a94cd8decae51e75d/href</a></iframe><p>We provide a queryset for all objects in our database. This queryset is passed automatically when we call our DataViewSet class. We already registered ‘files’ url extension in <strong>routers.py</strong> that we created under djvuetut. This queryset will be used here to list all files that we have in our database.</p><p>Additionally, We have to handle the post and delete requests in server side and update our database accordingly. We are doing it with post and destroy methods respectively.</p><h4>Configure main.js and install vue libraries to be used</h4><p>we are going to use the following vue libraries:</p><p><a href="https://vuex.vuejs.org/">Vuex</a> → a state management pattern + library for Vue.js applications. We will deep dive in it when we create our API requests.</p><p><a href="https://github.com/axios/axios">Axios</a> → a node.js HTTP client in order to create API requests.</p><p><a href="https://bootstrap-vue.js.org/">Bootstrap-vue</a> → Bootstrap V4 components and grid system available for Vue.js</p><p><a href="https://www.ag-grid.com/vue-getting-started/">Ag-Grid</a> → a data grid javascript library. It supports Vue through a wrapper component.</p><p><a href="https://github.com/FortAwesome/vue-fontawesome">Fortawesome</a> → a font and icon toolkit based on CSS and LESS.</p><p><a href="https://momentjs.com/">Moment.js</a> → a Javascript library to parse and display dates and times.</p><p>Install all of these libraries with npm:</p><pre>npm i --save vuex axios bootstrap bootstrap-vue moment<br>npm i --save ag-grid-community ag-grid-vue vue-property-decorator <br>npm i --save @fortawesome/fontawesome-svg-core <br>npm i --save @fortawesome/free-solid-svg-icons <br>npm i --save @fortawesome/vue-fontawesome</pre><p>After installing our dependencies, we are ready to configure our main.js, the actual starting point of a vue app. We will need to tell vue which libraries we are going to use in our app.</p><p>Make sure that the final appearence of main.js is same as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f9c9dd825f4860d5392d898e4645c3e/href">https://medium.com/media/7f9c9dd825f4860d5392d898e4645c3e/href</a></iframe><h4>Create Vue components and Configure Ag-Grid settings</h4><p>We are going to create two components: one for header and one for main body. Create a folder called components under src folder. Inside it, create <strong>Header.vue</strong> and <strong>Home.vue</strong> as shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*qUdoEiPIZ2ZmVYSkvdlDGg.png" /></figure><p>Update <strong>App.vue</strong> as below. This is the starting point of our application’s front-end.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db2061bae093af070371e3087a175c7f/href">https://medium.com/media/db2061bae093af070371e3087a175c7f/href</a></iframe><p>Next, let’s continue by updating <strong>Header.vue</strong>: This is just a basic navigation bar actually. The good thing is that we have now bootstrap for vue installed. Bootstrap is a front-end component library and a toolkit for developing with HTML, CSS, and JS. It is much more easier to design a beautiful and professional looking front-end by using bootstrap.</p><p>Add the following code inside <strong>Header.vue:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9cb65af1461799bbb57c9b7137696fe/href">https://medium.com/media/a9cb65af1461799bbb57c9b7137696fe/href</a></iframe><p>Our header component is now ready. Let’s continue with our main component <strong>Home.vue</strong> but I have to stop here and think about how to continue because Home.vue contains a lot of code. I am just going to write here the full code and after that I will explain step by step the way I constructed it. I have added comments to html section and splitted it virtually as:</p><ul><li>Part-1 → List files</li><li>Part-2 → Upload a file</li><li>Part-3 → Delete file(s)</li></ul><p>Add the following code inside <strong>Home.vue</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39be15fc5d4a643b04e2f97c95f4f5bf/href">https://medium.com/media/39be15fc5d4a643b04e2f97c95f4f5bf/href</a></iframe><p>Let’s deep dive to understand what we did here.</p><p><strong>Part-1 → List files:</strong> we added an <strong>ag-grid-vue</strong> component. This is where we defined our grid configuration and data source we need. OnGridReady() is the method which is called when DOM is loaded. We defined our column headers and a few other settings for ag-grid in beforeMount(). To understand better the lifecycle hooks of vue, have a look at the article below:</p><p><a href="https://alligator.io/vuejs/component-lifecycle/">Understanding Vue.js Lifecycle Hooks</a></p><p>we also created onRowClicked() and onRowSelected() methods in which we implement our actions. onRowSelected() method, we calculate the size of selected files and add the total value to selectedDataTotal to be displayed when single or multiple rows selected. onRowClicked() method, we send the selected filename to vuex store to be prepared for downloading. More on this later in vuex section.</p><p>Where is our data coming from? rowData is the source of our file list that is asynchronously retrieved using <a href="https://github.com/axios/axios">Axios</a> for the API requests using <a href="https://vuex.vuejs.org/">Vuex</a> as a central data storage.</p><p>As you may notice we import a few helper methods from js files that we have to create under /src folder: filetypeCellRenderer.js and utils.js</p><p>We would like to render the type of files which are uploaded. So we can show the correspondent icon for each filetype in filetype column instead of showing the same icon for all. We use it as a Ag-grid framework component in cellRenderer parameter of filetype column definition.</p><p>Let’s create <strong>filetypeCellRenderer.js </strong>and add the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f72ab8e4510d25c6dac30b7754ee986c/href">https://medium.com/media/f72ab8e4510d25c6dac30b7754ee986c/href</a></iframe><p>Now, we are good to go! we would like to display in our list the file sizes in a beautiful format like 85.5KB, 3MB or 2GB etc. So, we will need to format it. In size column definition, we call sizeFormatter method as a valueFormatter parameter provided by Ag-grid. This will expect a formatted value that we will provide. Similarly, I would also like format the date and time for uploads. We are going to use a beautiful date and time parser library <strong>moment.js </strong>that we already installed. It is so straightforward to parse a date or datetime object with it as you can find more details on their <a href="https://momentjs.com/">website</a>.</p><p>we are going to display the date and time for uploaded files since their addition.</p><p>Create <strong>utils.js</strong> under /src and add the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/922d90a011b9eae4e64e234491e79653/href">https://medium.com/media/922d90a011b9eae4e64e234491e79653/href</a></iframe><h4><strong>Configure vuex settings for CRUD with Axios</strong></h4><p>I will continue <strong>Part-1 → List files </strong>under<strong> </strong>this header bacause we are going to use <strong>Vuex</strong> and <strong>Axios </strong>in order to fetch files from our backend as we delivered their information in JSON format from our API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zy3TjpKzbUJ53nY7RE_2w.png" /></figure><p><a href="https://vuex.vuejs.org/">Vuex</a> is a state management pattern + library for Vue.js applications. We will need the following methods as vuex actions:</p><ul><li><strong>loadFiles</strong> → fetch data from Database</li><li><strong>postFile</strong> → upload a file into Database</li><li><strong>deleteFile</strong> → delete a file from Database by a given ID</li><li><strong>downloadFile</strong> → enable to download a file from our media folder by given file name</li></ul><p>It is possible to create our application without vuex since we may think that we are going to use it standalone. But what if we would like to perform these actions from multiple locations in our appication. For scalability, it is a good practice to use a state management system, so we won’t need to write the same code for each component. Vuex gives us the opportunity to define a central store that we dispatch a request and get back a response from any Vue components conveniently.</p><p>Let’s create <strong>store.js</strong> file under /src and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b6a5bcb9c851ef9f256a32daa7c59ec/href">https://medium.com/media/2b6a5bcb9c851ef9f256a32daa7c59ec/href</a></iframe><p>now back to Home.vue and notice that we have a computed property that we call mapState inside which we imported from vuex.</p><blockquote>Computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.</blockquote><p>mapState method enables us to access store members easily. We have defined an empty rowData array under state in our store.js and we fetch this rowData to be used in our ag-grid list. Computed property will recall this array whenever it is changed. So we will always have up-to-date file list from our Database without any page refresh. That’s great!</p><p>So, the question is now, how is that rowData array populated? let’s check back our Home.vue and notice that we dispatch loadFiles method in our mounted method as below:</p><p>this.$store.dispatch(‘loadFiles’)</p><p>we then perform a commit to SET_FILES method under mutations. We fetch the file list with Axios get method and pass that data.</p><p><strong>Part-2 → Upload a file: </strong>we used a b-form-file bootstrap-vue component that also supports drag and drop functionality when opening a file browser window. Our @click action is set to submitFile() method which primarily makes a check for max. file size and then make a vuex call as below:</p><p>this.$store.dispatch(‘postfile’, fd)</p><p>by also passing the selected file as a form data. postFile() vuex action method performs a axios post request with passed data to be received by DRF. It is important in a post request to define the Content-Type of the data that we are sending. post() method that we have added in <strong>viewsets.py</strong> provided by DRF is able to handle a post request for a file type object with a definition. We defined it as ‘multipart/form-data’ because we designed our application to receive any time of file. We then perform a commit to POST_FILE method under mutations as we append the new added file to rowData array and lastly dispatch loadFiles() for a refresh in our list.</p><p><strong>Part-3 → Delete file(s): </strong>similarly our @click action is set to deleteFile() method. Ag-grid lets us to add a checkbox for each row and get their properties for selected rows by simply this.gridApi.getSelectedNodes() method. We can get an array of unique id’s of all selected files and pass these array to vuex after confirming the delete request with a modal window. This is triggered with handleOk() method and make a vuex call as below:</p><p>this.$store.dispatch(&#39;deleteFile&#39;, this.result_id)</p><p>deleteFile() vuex action method performs a axios delete request with provided result_id array. destroy() method in DRF viewsets.py handle this request and delete the file(s) with given ids.</p><h4><strong>Last but not least</strong></h4><p>Ag-grid also lets us to take an action when a specific row is clicked. We have pre-defined onRowClicked() method available for that. Within this method we make a vuex call to download the file when clicked as below:</p><p>this.$store.dispatch(&#39;downloadFile&#39;, filename)</p><p>downloadFile() vuex action method performs a get request to direct url of the file with the filename saved under ‘media’ folder and uses the response type ‘blob’ to prepare the file to be downloaded. All the files that we uploaded can also be viewed/accessed through the absolute URL path with filename as follows:</p><p><a href="http://localhost:8000/media/%7Bfilename%7D">http://localhost:8000/media/{filename</a>}</p><h4>Conclusion</h4><p>I encourage you to implement the tutorial and learn while you are building and before displaying your changes in browser, don’t forget to run:</p><p>npm run build</p><p>You can also clone the full project from Github repository and add to your project by making a few tweaks and adjustments. You can find the source code <a href="https://github.com/talented/FileManager">here</a> on Github.</p><p>Thanks for reading! Please let me know what you thought on twitter <a href="https://twitter.com/ozguryarikkas"><strong>@</strong>ozguryarikkas</a> Here’s a link to <a href="https://medium.com/js-dojo/how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-e89a83318e9c">Part 1</a> if you haven’t read it yet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852e30e52aa5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/part-2-how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-852e30e52aa5">Part 2 — How to build a File Manager Storage web app with Django Rest Framework and Vue.js</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a file manager storage web app with Django Rest Framework and Vue.js]]></title>
            <link>https://medium.com/js-dojo/how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-e89a83318e9c?source=rss-6a7cb9396941------2</link>
            <guid isPermaLink="false">https://medium.com/p/e89a83318e9c</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[ag-grid]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ozgur Yarikkas]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 23:31:00 GMT</pubDate>
            <atom:updated>2019-05-04T20:04:15.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1 — How to build a File Manager Storage web app with Django Rest Framework and Vue.js with Vuex and Ag-grid integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-WTYzR1Ytwe-zKs9h3lZg.png" /></figure><p>Since beginning of this year, I have been attending an online course. We have a platform that enables us to store and share files collaboratively. I wanted to clone it, so this web application idea was born ✍️</p><p>I will guide you step by step to create a File Manager storage web application. we will have a tech stack as Django with DRF, vue.js with webpack and vuex and libraries such as ag-grid, bootstrap, axios etc. 🎬</p><p>I broke up this tutorial into two parts. Part one focuses on setting up Django with DRF and Vue.js and making configurations and preparing our REST API in backend. Part two goes over frontend and finishing our application with vue.js, vuex and ag-grid. If you want to have a look at part 2 before diving in, follow the link below:</p><p><a href="https://medium.com/@ozguryarikkas/part-2-how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-852e30e52aa5">Part 2 — How to build a File Manager Storage web app with Django Rest Framework and Vue.js</a></p><p>In the <strong>first part </strong>of this tutorial we are going to:</p><ul><li>Install and setup Django with Django Rest Framework</li><li>Install Vue.js and webpack</li><li>Configure Django and vue to make them work together</li><li>Create a database model in Django</li><li>Create an API endpoint with Django Rest Framework</li></ul><p>Let’s start coding! I suppose that you have Python 3.6+ and Node.js installed.</p><p>We start with creating a new environment as following. We are going to use “virtualenv” module which comes with Pythton 3.6</p><pre><strong><em>(OSX)</em></strong><br>python3 -m venv .env</pre><pre><strong><em>(Linux and Windows)</em></strong><br>virtualenv .env</pre><pre><strong><em># Activate your environment</em></strong><br>. .env/bin/activate</pre><p>We are going to use:</p><p>Django — Vue.js 2.0 — Webpack</p><p>It is good practice to create and requirements.txt file to install our dependencies for Django.</p><pre>cat &gt; requirements.txt<br>Django<br>django-rest-framework<br>django-webpack-loader</pre><p>Press Control + D to save the file or install each library with pip manually.</p><p>Enter the following and run requirements.txt to install Django and DRF, also with webpack loader package which we will need to make django to talk to vue.</p><pre>pip3 install -r requirements.txt</pre><p>Next, create a Django project</p><pre>django-admin startproject djvuetut</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*LmdpwiGqPmm_Rft863JouQ.png" /></figure><p>Your current file tree should look like this for the moment. You may want to test it and see that it runs in your browser.</p><pre>cd djvuetut<br>python manage.py runserver  <strong><em># start your server in localhost:8000</em></strong></pre><p>Ignore any unapplied migrations warning for the moment and let’s check <a href="http://localhost:8000/">http://localhost:8000</a> and make sure you have a running django app!</p><p>click control + C to stop the server.</p><p>Now, we will continue with Vue.js installation and setup.</p><p>~ make sure that you are in the same directory with <a href="http://manage.py/">manage.py</a></p><p>enter the commands below to install vue-cli and webpack with simle configuration.</p><pre>npm install -g vue-cli<br>vue init webpack-simple</pre><pre>Generate project in current directory? Yes<br>Project name djvuetut<br>Project description A Vue.js project<br>Author talented &lt;ozguryarikkas@gmail.com&gt;<br>License MIT<br>Use sass? No</pre><pre>   vue-cli · Generated &quot;djvuetut&quot;.</pre><pre>   To get started:<br>   <br>     npm install<br>     npm run dev</pre><p>as stated:</p><p>enter npm install to install dependencies (npm modules) — This may take a while and npm run dev to start the server:</p><pre>npm install<br>npm run dev</pre><p>Default server port for Vue.js is 8080 so you can test that it runs at <a href="http://localhost:8080/">http://localhost:8080</a> if it doesn’t load automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9Kz3mfIiE4HiDW8UdQ5ag.png" /></figure><p>Just a quick introduction on how Vue is working in principal:</p><p>→ a vue.js instance is already created in main.js</p><p>→ the property el: binds the Vue instance to the HTML element with id=”app” and tell us that it is rendered in App.vue</p><p>→ in App.vue we have the Vue.js system to enable us to render data into DOM using double braces syntax.</p><h4>Configure Django and Vue to work together</h4><p>Now we need some Vue.js plugins to integrate vue with django. We already installed django-webpack-loader package for django. It requires just a few settings to work. First we need to install the following plugin.</p><p>Install the following by using npm</p><pre>npm install --save-dev webpack-bundle-tracker<br>npm install --save-dev write-file-webpack-plugin</pre><p>after installing these packages, it is time to make some configurations. Make the following changes in webpack.config.js</p><pre><br><strong><em># ./webpack.config.js</em></strong></pre><pre>var path = require(&#39;path&#39;);<br>var webpack = require(&#39;webpack&#39;);<br>var BundleTracker = require(&#39;webpack-bundle-tracker&#39;);  <strong><em>// add this</em></strong></pre><pre>module.exports = {  <br>  entry: &#39;./src/main.js&#39;,<br>  output: {<br>     path: path.resolve(__dirname, &#39;./dist&#39;),  <br>                                      // publicPath is deleted here<br>     filename: &#39;build.js&#39;<br>  },<br>  plugins: [                                       <strong><em>// add this</em></strong>    new BundleTracker({                                <strong><em>// add this</em></strong>   filename: &#39;./webpack-stats.json&#39;                   <strong><em>// add this</em></strong><br>  })                                               <strong><em>// add this</em></strong><br>],                                                 <strong><em>// add this</em></strong> module: {   <br>  rules: [<br>  ....</pre><p>in django settings, add the following:</p><pre><strong><em># ./djvuetut/settings.py</em></strong></pre><pre><strong><em># add &#39;webpack_loder&#39; to INSTALLED APPS</em></strong></pre><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;webpack_loader&#39;,                                 <strong><em># add this</em></strong><br>]</pre><pre>...</pre><pre><strong><em># Configure TEMPLATES DIRS and add BASE_DIR</em></strong></pre><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [BASE_DIR],                        <strong><em># update here</em></strong><br>        &#39;APP_DIRS&#39;: True,<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>                &#39;django.template.context_processors.debug&#39;,<br>                &#39;django.template.context_processors.request&#39;,<br>                &#39;django.contrib.auth.context_processors.auth&#39;,                              &#39;django.contrib.messages.context_processors.messages&#39;,<br>            ],<br>        },<br>    },<br>]</pre><pre><strong><em># Add this to the end of settings</em></strong></pre><pre># settings for django-webpack-loader<br>STATIC_ROOT = os.path.join(BASE_DIR, &#39;public&#39;)<br>STATICFILES_DIRS = (<br>    os.path.join(BASE_DIR, &#39;dist&#39;),<br>)<br>WEBPACK_LOADER = {<br>    &#39;DEFAULT&#39;: {<br>        &#39;CACHE&#39;: not DEBUG,<br>        &#39;BUNDLE_DIR_NAME&#39;: &#39;&#39;,<br>        &#39;STATS_FILE&#39;: os.path.join(BASE_DIR, &#39;webpack-stats.json&#39;),<br>        &#39;POLL_INTERVAL&#39;: 0.1,<br>        &#39;TIMEOUT&#39;: None,<br>        &#39;IGNORE&#39;: [&#39;.+\\.hot-update.js&#39;, &#39;.+\\.map&#39;]<br>    }<br>}</pre><p>Yes, now we are ready with our configuration. We will need to add our django tags to the main index.html to load the render-bundle from webpack-bundle. final look of index.html will look like below with added tags:</p><pre><strong><em># ./index.html</em></strong></pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;title&gt;djvuetut&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    {% load render_bundle from webpack_loader %}     <strong><em>// add this</em></strong> </pre><pre>&lt;div id=&quot;app&quot;&gt;<br>      &lt;django&gt;&lt;/django&gt;                              <strong><em>// add this</em></strong><br>    &lt;/div&gt;</pre><pre>{% render_bundle &#39;main&#39; %}                           <strong><em>// add this</em></strong><br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>We also need to update the urls.py in djvuetut folder as follows:</p><pre><strong><em># .djvuetut/urls.py</em></strong></pre><pre>from django.conf.urls import url<br>from django.contrib import admin<br>from django.views.generic import TemplateView</pre><pre>urlpatterns = [<br>     path(&#39;admin/&#39;, admin.site.urls),<br>     path(&#39;&#39;, TemplateView.as_view(template_name=&#39;index.html&#39;),  name=&#39;Home&#39;),<br>]</pre><p>and we need to add &lt;django&gt; tag as a component to our Vue instance in main.js under /src</p><pre><strong><em># ./src/main.js</em></strong></pre><pre>import Vue from &#39;vue&#39;<br>import App from &#39;./App.vue&#39;</pre><pre>new Vue({<br>  el: &#39;#app&#39;,<br>  components: {<br>    &#39;django&#39;: App                                    <strong><em>// add this</em></strong><br>  }<br>})</pre><p>we should be ready now. Run the latest commands below.</p><pre><strong><em># Compile VueJS App </em></strong><br>npm run build</pre><pre><strong><em>#collect static files in public folder</em></strong><br>python manage.py collectstatic</pre><pre><strong><em>#start django server in localhost</em></strong><br>python manage.py runserver</pre><p>Voila! 👏👏👏 when you route to <a href="http://localhost:8000/">http://localhost:8000</a> , you should be seeing your view in App.vue. Now you have a fully working vue.js app with a django backend.</p><h4>Create an API endpoint with Django rest framework</h4><p>the goal is to create and API endpoint to:</p><ul><li>upload and download files to the server</li><li>display a list of files in our database</li></ul><p>let’s start an django app and call it filemanager, so we create our models for our API</p><pre>django-admin startapp filemanager</pre><p>we need to add it under INSTALLED_APPS in settings.py</p><p>we have already installed DRF when we run our requirements.txt but we also need to add it to installed apps to let django know that we are going to use it.</p><pre><strong><em># ./djvuetut/settings.py</em></strong></pre><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;webpack_loader&#39;,<br>    &#39;filemanager&#39;                                     <strong><em># add this</em></strong><br>    &#39;rest_framework&#39;,                                 <strong><em># add this</em></strong></pre><pre>]</pre><p>actual file tree should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*vDh6MccR3qwJzhf5nLwmDA.png" /></figure><p>we will also create an admin user to manage our database from admin portal provided by django admin in case we need it. But first we have to migrate any changes before creating a super user:</p><pre>$ python manage.py migrate<br>$ python manage.py createsuperuser</pre><pre><strong><em># I think creating a super user is self explanatory. We will use it later.</em></strong></pre><p>What we have to do now:</p><ul><li>Create our model and fields to store file data in database</li><li>Create a folder in base project directory to store MEDIA data</li><li>Add media related settings (MEDIA_ROOT &amp; MEDIA_URL) to <a href="http://settings.py/">settings.py</a></li><li>Modify <a href="http://url.py/">url.py</a> to handle static media content</li></ul><p>let’s start with creating a model for our file manager in models.py:</p><pre><strong><em># ./filemanager/models.py</em></strong></pre><pre>from django.db import models<br>from django.utils import timezone</pre><pre>class Data(models.Model):<br>    file_id = models.AutoField(primary_key=True)<br>    file = models.FileField(null=True, max_length=255)<br>    date_created = models.DateTimeField(default = timezone.now)</pre><pre>    def __str__(self):<br>        return str(self.file.name)</pre><p>our model enables us to upload any file with any extension and size. We haven’t setup any validators yet, we will make the fine tuning later. We need to complete a few more configuration to make it work.</p><pre><strong><em># ./djvuetut/settings.py</em></strong></pre><pre>MEDIA_URL = &quot;/media/&quot;                                 <strong><em># add this</em></strong> <br>MEDIA_ROOT = os.path.join(BASE_DIR, &#39;media&#39;)          <strong><em># add this</em></strong></pre><p>we also need to configure our urls.py and define the new added folder as a static folder.</p><pre><strong><em># ./djvuetut/urls.py</em></strong></pre><pre>... <br>from django.conf import settings                      <strong><em># add this</em></strong> from django.conf.urls.static import static            <strong><em># add this</em></strong></pre><pre>urlpatterns = [<br>     ...<br>]  </pre><pre>if settings.DEBUG:     <br>    urlpatterns += static(                            <strong><em># add this</em></strong><br>            settings.STATIC_URL, <br>document_root=settings.STATIC_ROOT<br>          )   <br>    urlpatterns += static(                            <strong><em># add this</em></strong><br>            settings.MEDIA_URL,         document_root=settings.MEDIA_ROOT)</pre><h4>Django Rest Framework (DRF) Setup</h4><p>we will define a folder called “media” to keep our files. It will be automatically created in our first upload. now, it is time to create a setup to be able to use DRF.</p><p>There are more than one way and I wanted to create the most hassle free setup. It might not be so detailed or if we want to scale our app in the future, we may need to update our code accordingly. To maintain the correct business logic, we are going to create 3 files:</p><ul><li>viewsets.py</li><li>serializers.py</li><li>routers.py</li></ul><p>Let me add the required code for each. After that I will give an explanation what they do in general.</p><p>Create serializers.py under ./filemanager and add the following code:</p><pre><strong><em># ./filemanager/serializers.py</em></strong></pre><pre>from rest_framework import serializers<br>from .models import Data</pre><pre>class DataSerializer(serializers.ModelSerializer):</pre><pre>    size = serializers.SerializerMethodField()<br>    name = serializers.SerializerMethodField()<br>    filetype = serializers.SerializerMethodField()<br>    since_added = serializers.SerializerMethodField()</pre><pre>    class Meta:<br>        model = Data<br>        fields = (&#39;file_id&#39;, &#39;file&#39;, &#39;since_added&#39;, &#39;size&#39;, &#39;name&#39;, &#39;filetype&#39;)</pre><pre>    def get_size(self, obj):<br>        file_size = &#39;&#39;<br>        if obj.file and hasattr(obj.file, &#39;size&#39;):<br>            file_size = obj.file.size<br>        return file_size</pre><pre>    def get_name(self, obj):<br>        file_name = &#39;&#39;<br>        if obj.file and hasattr(obj.file, &#39;name&#39;):<br>            file_name = obj.file.name<br>        return file_name</pre><pre>    def get_filetype(self, obj):<br>      filename = obj.file.name<br>      return filename.split(&#39;.&#39;)[-1]</pre><pre>    def get_since_added(self, obj):<br>        date_added = obj.date_created<br>        return date_added<br></pre><p>Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types.</p><p>The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.</p><p>We have to use also SerializerMethodField to get the attributes of our file. we can just serialize file_name, file_size and filetype with this way. Get more info about serializers here in original documentation: <a href="http://www.django-rest-framework.org/api-guide/serializers/">http://www.django-rest-framework.org/api-guide/serializers/</a></p><p>create viewsets.py under ./filemanager and add the following code:</p><pre><strong><em># ./filemanager/viewsets.py</em></strong></pre><pre>from rest_framework import viewsets<br>from .models import Data<br>from .serializers import DataSerializer</pre><pre>class DataViewSet(viewsets.ModelViewSet):<br>    queryset = Data.objects.all()<br>    serializer_class = DataSerializer</pre><p>DRF allows you to combine the logic for a set of related views in a single class, called a ViewSet. A ViewSet class is simply a type of class-based View.</p><p>We have to provide a queryset and a serializer class that we already created in our serializers.py</p><p>Get more info about viewsets here in original documentation: <a href="http://www.django-rest-framework.org/api-guide/viewsets/">http://www.django-rest-framework.org/api-guide/viewsets/</a></p><p>create routers.py under ./djvuetut and add the following code:</p><pre><strong><em># ./djvuetut/routers.py</em></strong></pre><pre>from rest_framework import routers<br>from filemanager.viewsets import DataViewSet</pre><pre>router = routers.DefaultRouter()<br>router.register(r&#39;files&#39;, DataViewSet, base_name=&#39;data&#39;)</pre><p>With this piece of code, we created a router object and register ‘/files/’ url extension. We want to use it for our API endpoint with also providing our viewSet.</p><p>Get more info about routers here in original documentation: <a href="http://www.django-rest-framework.org/api-guide/routers/">http://www.django-rest-framework.org/api-guide/routers/</a></p><p>The important point is here that we need to tell django’s urls.py that we will use a router to manage our urls with DRF</p><pre><strong><em># ./djvuetut/urls.py</em></strong></pre><pre>from django.contrib import admin<br>from django.urls import path, include     <strong><em># import &quot;include&quot; here</em></strong><br>from .routers import router                            <strong><em># add this</em></strong></pre><pre>...</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, TemplateView.as_view(template_name=&#39;index.html&#39;),name=&#39;Home&#39;),<br>    path(&#39;api/&#39;, include(router.urls)),                <strong><em># add this</em></strong><br>]<br>...</pre><p>We are done for now with the DRF settings 🏹 let’s test it out! 😎</p><p>Enter the following in your browser and see what is available to us. By the help of DRF, we now have a fully usable rest framework for our model 💪🏻</p><pre>http://localhost:8000/api/</pre><p>click on ‘files’ viewset that we defined. Here you can upload a file to test it out. Just choose a file and click on POST. You will notice that a folder with a name “media” will be created in the root directory and the file is uploaded under it.</p><p>we will be able to reach the properties of that file through JSON. All we need to do is to parse this JSON query in our Vue views and that’s it. You can upload here more than one file and reach them individually by supplying their ids like that:</p><pre>http://localhost:8000/api/files/&lt;id&gt;</pre><p>In the <strong>second part</strong> of this series, we will create our front end in vue with bootstrap, integrate ag-grid to showcase our files, create CRUD operations with axios and much more.</p><p>click <a href="https://medium.com/@ozguryarikkas/part-2-how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-852e30e52aa5"><strong>here</strong></a> to read <strong>Part 2</strong> of the tutorial! ⚒⚒⚒</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e89a83318e9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/how-to-build-a-file-manager-storage-web-app-with-django-rest-framework-and-vue-js-e89a83318e9c">How to build a file manager storage web app with Django Rest Framework and Vue.js</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Conversion, Bitwise Operators and Practical Use of Binary in Programming]]></title>
            <link>https://ozguryarikkas.medium.com/binary-conversion-bitwise-operators-and-practical-use-of-binary-in-ruby-programming-da28dc5ef016?source=rss-6a7cb9396941------2</link>
            <guid isPermaLink="false">https://medium.com/p/da28dc5ef016</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[bitwise]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[bitwise-operator]]></category>
            <dc:creator><![CDATA[Ozgur Yarikkas]]></dc:creator>
            <pubDate>Tue, 10 Jan 2017 22:21:31 GMT</pubDate>
            <atom:updated>2019-03-12T09:57:04.964Z</atom:updated>
            <content:encoded><![CDATA[<p>I want to explain the programming solution to a form of Arithmetico-geometric sequence by using binary and bitwise operators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*Zy4KOPHlIUCONJwYu-nElw.gif" /><figcaption>a form of Arithmetico-geometric sequence</figcaption></figure><p>But first, let’s have a quick overview of:</p><p>▻ How to convert a decimal to binary and vice-versa</p><p>▻ How to perform bit by bit with Bitwise operators</p><p>I will also map the actual problem to a basic compound interest problem which, I believe, might be also interesting for finance people.</p><p>➥ <strong>Let’s start with decimal-binary conversion</strong></p><p>take number 83.</p><p>First, we find the closest number which is a power of 2 because we are now in the world of 2s. Then we continue by summing the power of 2 values in descending order until we reach to our number.</p><p>83 → 64 + 16 + 2 + 1</p><p>83 → 2⁶ + 2⁴ + 2¹ + 2⁰</p><p>Here we have the trick. We will now convert these 2s to 10s and add the values. Simple as that.</p><p>83 → 10⁶ + 10⁴ + 10¹ + 10⁰</p><p>83 → 1010011 — Voila!</p><p>What about fractions? Let’s have a look with an example:</p><p>57,625 — we use the same approach just with a simple trick:</p><p>57,625 → 32 + 16 + 8 + 1 + 0.5(1/2) + 0.125(1/8)</p><p>57,625 → 2⁵ + 2⁴ + 2³ + 2⁰ + (1/2¹) + (1/2³)</p><p>57,625 → 111001,101</p><p>Similarly, when we want to convert a binary to a number:</p><p>110100101 — first, we count the digits which is 9 in this case. Tip: 9–1 = 8 is the max. power of 2 in our number.</p><p>110100101 → 2⁸ + 2⁷ + 0 + 2⁵ + 0 + 0 + 2² + 0 + 1</p><p>110100101 → 256 + 128 + 32 + 4 + 1</p><p>110100101 → 421</p><p><strong>Using bitwise operators</strong></p><p>Every digit in binary numerals is called a bit so we have bitwise operators to deal with binaries. Let’s have a quick overview on how to perform bit by bit operation.</p><p>Let’s take two binary numbers as follows:</p><p>a = 011110</p><p>b = 001101</p><p>&amp; ⇢ Binary AND operator. Return the bit if it exists in<strong> both</strong> otherwise return 0.</p><p>a &amp; b → 001100</p><p>| ⇢ Binary OR operator. Return the bit if it exists in <strong>any</strong> otherwise return 0.</p><p>a | b → 011111</p><p>^ ⇢ Binary XOR operator. Return the bit if it exists in <strong>one but not both</strong> otherwise return 0.</p><p>a ^ b → 010011</p><p>~ ⇢ Binary complement operator. <strong>Flip</strong> all the bits.</p><p>~a → 100001</p><p>&lt;&lt; ⇢ Binary left shift operator. <strong>Shift the bits to the left</strong> by the number given.</p><p>a &lt;&lt; 2 → 111000</p><p>&gt;&gt; ⇢ Binary left shift operator. <strong>Shift the bits to the right</strong> by the number given.</p><p>a &gt;&gt; 2 → 000111</p><p><strong>Problem</strong></p><p>Now, if we are comfortable enough with binaries and bitwise operators, it is time to have a look at our solution to calculate the compound interest by year:</p><p>Initial investment → 1 dollar</p><p>Yearly investment → b =1 dollar</p><p>Yearly Interest rate = 100% → a = 2 (means ⇢ will be doubled)</p><p>What will be the total earning at the end of year 5?</p><p><strong>Solution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*Zy4KOPHlIUCONJwYu-nElw.gif" /></figure><p>where n: number of years</p><ul><li>year 1: 1*2+1 = 3</li><li>year 2: 3*2+1 = 7</li><li>year 3: 7*2+1 = 15</li><li>year 4: 15*2+1 = 31</li><li>year 5: 31*2+1 = 63</li></ul><p>and you can notice the value in binary is like this:</p><ul><li>year 1: 1*2+1 = 3 → 11</li><li>year 2: 3*2+1 = 7 → 111</li><li>year 3: 7*2+1 = 15 → 1111</li><li>year 4: 15*2+1 = 31 → 11111</li><li>year 5: 31*2+1 = 63 → 111111</li></ul><p>now, we are coming to a point where we can write our solution in Python by using bitwise operators as follows:</p><pre># we assume that yearly Interest rate is 100%</pre><pre>def earning(year, investment):<br>    return ~(~investment &lt;&lt; year)</pre><p>earning(4) ⇢ 31</p><p>earning(5) ⇢ 63</p><p>earning(20) ⇢ 2097151 — easiest way to be a millionaire with just investing 1 dollar per year 😉</p><p>You can see here the power of binary and bitwise operators in programming. I know, it is not that simple but once you get it, you can definitely distinguish yourself in the crowd!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da28dc5ef016" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>