<?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: Roshan Chokshi</title>
    <description>The latest articles on DEV Community by Roshan Chokshi (@chokshiroshan).</description>
    <link>https://dev.to/chokshiroshan</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%2F680588%2F77b38535-94d1-4ec4-9c04-1865d0ce0a21.jpeg</url>
      <title>DEV Community: Roshan Chokshi</title>
      <link>https://dev.to/chokshiroshan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/chokshiroshan"/>
    <language>en</language>
    <item>
      <title>Using OpenMPI for Parallel Processing of Text Files</title>
      <dc:creator>Roshan Chokshi</dc:creator>
      <pubDate>Sat, 17 Dec 2022 04:18:00 +0000</pubDate>
      <link>https://dev.to/chokshiroshan/using-openmpi-for-parallel-processing-of-text-files-2jhj</link>
      <guid>https://dev.to/chokshiroshan/using-openmpi-for-parallel-processing-of-text-files-2jhj</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is this about?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This article provides a clear overview of OpenMPI and how it can be used to improve the performance of distributed computing tasks. It also provides a detailed code example that demonstrates how to use OpenMPI to calculate the frequency of each letter in a text file. The article also mentions the drawbacks of the code example, which is useful to consider when deciding if OpenMPI is a good solution for a particular problem. Overall, this is a article that provides a good understanding of OpenMPI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is OpenMPI?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;OpenMPI is an open source implementation of the Message Passing Interface (MPI) standard. It is a library that provides high-performance communication among computers in a distributed system. The OpenMPI library includes a set of routines for point-to-point communication, collective communication, and remote memory operations.&lt;/p&gt;

&lt;p&gt;Point-to-point communication allows two processes to communicate directly with each other. This is useful for exchanging data between two processes, such as a client and a server. Collective communication allows multiple processes to communicate at once. This is useful for tasks that require multiple processes to cooperate, such as sorting an array. Remote memory operations provide a way for processes to access data stored in memory on another process. This is useful for tasks that require sharing data between processes, such as a distributed search algorithm.&lt;/p&gt;

&lt;p&gt;The main functionality of the OpenMPI library is to provide communication between processes. This communication is done through message passing. In message passing, each process sends a message to another process, which then receives the message and processes it. Message passing is an important part of distributed computing, as it allows processes to exchange data and coordinate their activities. It also allows for synchronization between processes, which is critical for distributed systems.&lt;/p&gt;

&lt;p&gt;The OpenMPI library also provides support for other features, such as parallel programming, process management, and resource management. Parallel programming is a way of writing code that allows multiple processes to run concurrently. This can significantly speed up the execution of tasks. Process management allows processes to be created, managed, and monitored. Resource management allows processes to acquire and release resources, such as memory, in a distributed system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are we doing?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a program that uses MPI (Message Passing Interface) to perform different operations on a given text file in parallel. It first reads the text file, removes punctuations and converts it to lower case, then partitions the text into four groups based on their colors (Blue, Yellow, Green, Red). Each group performs a specific operation on the text:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Blue group removes unwanted words from the text.&lt;/li&gt;
&lt;li&gt;Yellow group sets each word to a separate line.&lt;/li&gt;
&lt;li&gt;Green group counts the frequency of each word in the text.&lt;/li&gt;
&lt;li&gt;Red group sorts the words by their frequency.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8lv06y9ft3rsy75uymer.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8lv06y9ft3rsy75uymer.png" alt="System Architecture"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The program uses MPI_Intercomm_create function to create an intercommunicator from two intracommunicators. The intercommunicator allows the groups to communicate and pass data to each other. The program then outputs the results to a file named "out.txt".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This code is a C++ implementation of a program that partitions a number of processes into four groups (Blue, Yellow, Green, Red) and calculates the frequency of each letter in a text file. The program takes in two arguments, the input filename and the output filename, and uses MPI to split the text file into four parts. After processing each part, the results are combined and written to the output file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;mpi.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;

#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
#include &amp;lt;chrono&amp;gt;

using namespace std;

typedef std::chrono::high_resolution_clock::time_point TimeVar;

#define duration(a) std::chrono::duration_cast&amp;lt;std::chrono::nanoseconds&amp;gt;(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The program begins by including the mpi.h header, followed by the iostream and string library for string manipulation, and the chrono library for timing. The removePunctuation() method removes all punctuation from a string, the convertToLower() method converts all uppercase letters to lowercase, the calculateFrequency() method calculates the frequency of each letter in a string, and the create_Intercommunicator() method creates an intercommunicator between two groups of processes. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Methods:&lt;/strong&gt;&lt;br&gt;
removePunctuation():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* remove the unwanted character*/
void removePunctuation(char *chunk)
{
    int count = 0;
    int i = 0, j = 0;
    for (i = 0; chunk[i] != '\0'; i++)
    {
        if ((chunk[i] &amp;gt;= 'a' &amp;amp;&amp;amp; chunk[i] &amp;lt;= 'z') || (chunk[i] &amp;gt;= 'A' &amp;amp;&amp;amp; chunk[i] &amp;lt;= 'Z'))
        {
            chunk[j] = chunk[i];
            j++;
        }
    }

    // add null character at the end of the string
    chunk[j] = '\0';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;convertToLower():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* convert the string to lower case*/
void convertToLower(char *chunk)
{
    int i = 0;
    while (chunk[i] != '\0')
    {
        if (chunk[i] &amp;gt;= 'A' &amp;amp;&amp;amp; chunk[i] &amp;lt;= 'Z')
        {
            chunk[i] = chunk[i] + 32;
        }
        i++;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;calculateFrequency():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* calculate character frequency*/
int calculateFrequency(char *chunk, int *freq)
{
    int i = 0;
    while (chunk[i] != '\0')
    {
        if (chunk[i] &amp;gt;= 'a' &amp;amp;&amp;amp; chunk[i] &amp;lt;= 'z')
        {
            freq[chunk[i] - 'a']++;
        }
        i++;
    }

    return *freq;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;create_Intercommunicator():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void create_Intercommunicator(MPI_Comm &amp;amp;comm, int color, MPI_Comm &amp;amp;a, MPI_Comm &amp;amp;b, MPI_Comm &amp;amp;c, MPI_Comm &amp;amp;d)
{
    if (color == 0)
    { // Blue: remove the unwanted word in text file
        /* Creates an intercommunicator from two intracommunicators. */
        MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, 1, 1, &amp;amp;a);
    }
    else if (color == 1)
    { // Yellow
        // set to one word each line
        MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, 0, 1, &amp;amp;a);
        MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, 2, 12, &amp;amp;b);
    }
    else if (color == 2)
    { // Green
        // count the word frequency
        MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, 1, 12, &amp;amp;b);
        MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, 3, 123, &amp;amp;c);
    }
    else if (color == 3)
    { // Red
        // sort by the word frequency
        MPI_Intercomm_create(comm, 0, MPI_COMM_WORLD, 2, 123, &amp;amp;c);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The main() method begins by initializing the MPI environment and declaring the colors, communicators, and file variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int main(int argc, char const *argv[])
{
    TimeVar t1 = timeNow();
    string colors[4] = {"Blue", "Yellow", "Green", "Red"};
    MPI_Comm group_comm, BY_comm, YG_comm, GR_comm, RD_comm;
    MPI_File in, out;
    MPI_Offset filesize; /*  integer type of size sufficient to represent the size (in bytes) */
    MPI_Status status;   /* Status returned from read */
    int world_rank, world_size, group_rank, group_size;
    int initialized, finalized;
    int ierr;
    int bufsize;
    int freqsum[26] = {0};

    MPI_Initialized(&amp;amp;initialized);
    if (!initialized)
        MPI_Init(NULL, NULL);

    MPI_Comm_rank(MPI_COMM_WORLD, &amp;amp;world_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &amp;amp;world_size);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It then checks the number of arguments and exits with an error message if there are not enough. The code then opens the input and output files and gets their sizes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
    /* Check the arguments */
    if (argc != 3)
    {
        if (world_rank == 0)
            fprintf(stderr, "Usage: %s infilename outfilename\n", argv[0]);
        MPI_Finalize();
        exit(1);
    }

    /* Read the input file */
    ierr = MPI_File_open(MPI_COMM_WORLD, argv[1], MPI_MODE_RDONLY, MPI_INFO_NULL, &amp;amp;in);
    if (ierr)
    {
        if (world_rank == 0)
            fprintf(stderr, "%s: Couldn't open file %s\n", argv[0], argv[1]);
        MPI_Finalize();
        exit(2);
    }

    /* Get the size of the file */
    ierr = MPI_File_get_size(in, &amp;amp;filesize);
    if (ierr)
    {
        if (world_rank == 0)
            fprintf(stderr, "%s: Couldn't read file size of %s\n", argv[0], argv[1]);
        MPI_Finalize();
        exit(3);
    }

    /* Open the output file */
    ierr = MPI_File_open(MPI_COMM_WORLD, argv[2], MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &amp;amp;out);
    if (ierr)
    {
        if (world_rank == 0)
            fprintf(stderr, "%s: Couldn't open output file %s\n", argv[0], argv[2]);
        MPI_Finalize();
        exit(4);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code then splits the MPI_COMM_WORLD into four groups based on the rank of the process and creates an intercommunicator between each group. The process then sets the view for the input and output files.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
    /* split into groups*/
    int color = world_rank % 4;
    MPI_Comm_split(MPI_COMM_WORLD, color, world_rank, &amp;amp;group_comm);
    MPI_Comm_rank(group_comm, &amp;amp;group_rank);

    MPI_Comm_size(group_comm, &amp;amp;group_size);

    printf("Rank %d/%d in original comm, group [%s] %d/%d in new comm\n", world_rank, world_size, colors[color].c_str(), group_rank, group_size);

    /* Calculate how many elements that is */
    filesize = filesize / sizeof(char);
    /* Calculate how many elements each processor gets */
    bufsize = filesize / group_size;

    ierr = MPI_File_set_view(in, group_rank * bufsize, MPI_CHAR, MPI_CHAR, "native", MPI_INFO_NULL); // split the file for group members
    if (ierr)
    {
        if (group_rank == 0)
            fprintf(stderr, "%s: Couldn't set file view for %s", argv[0], argv[1]);
        MPI_Finalize();
        exit(5);
    }

    ierr = MPI_File_set_view(out, group_rank * bufsize, MPI_CHAR, MPI_CHAR, "native", MPI_INFO_NULL); // split the file for group members
    if (ierr)
    {
        if (group_rank == 0)
            fprintf(stderr, "%s: Couldn't set file view for %s", argv[0], argv[1]);
        MPI_Finalize();
        exit(6);
    }

    /* create intercommunicator for groups */
    create_Intercommunicator(group_comm, color, BY_comm, YG_comm, GR_comm, RD_comm);

    MPI_Barrier(MPI_COMM_WORLD);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reads the input file, removes punctuation, converts all letters to lowercase, calculates the frequency of each letter, and writes the results to the output file. Finally, the program closes the input and output files and exits with the total time taken.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (color == 0)
    { // Blue: remove the puctuations and spaces in text file
        int nrchar = 0;
        char *buf = new char[bufsize + 1];
        /* Reads a file starting at the location specified by the individual file pointer (blocking, noncollective) */
        ierr = MPI_File_read(in, buf, bufsize, MPI_CHAR, &amp;amp;status);
        if (ierr)
        {
            if (group_rank == 0)
                fprintf(stderr, "%s: Couldn't read from file %s", argv[0], argv[1]);
            MPI_Finalize();
            exit(7);
        }
        /* Gets the number of top-level elements received. */
        MPI_Get_count(&amp;amp;status, MPI_CHAR, &amp;amp;nrchar);
        /* Add a null character to the end of the buffer */
        buf[nrchar] = '\0';
        removePunctuation(buf);
        MPI_Send(buf, bufsize, MPI_CHAR, group_rank, 0, BY_comm);
    }
    else if (color == 1)
    { // Yellow: convert to lowercase
        char *buf = new char[bufsize + 1];
        /* receive the data from blue */
        MPI_Recv(buf, bufsize, MPI_CHAR, group_rank, 0, BY_comm, &amp;amp;status);
        convertToLower(buf);
        MPI_Send(buf, bufsize, MPI_CHAR, group_rank, 0, YG_comm);
    }
    else if (color == 2)
    { // Green: calculate the char frequency
        char *buf = new char[bufsize + 1];
        int freq[26] = {0};
        /* receive the data from yellow */
        MPI_Recv(buf, bufsize, MPI_CHAR, group_rank, 0, YG_comm, &amp;amp;status);
        calculateFrequency(buf, freq);
        MPI_Send(freq, 26, MPI_INT, group_rank, 0, GR_comm);
    }
    else if (color == 3)
    { // Red: write the result to file
        int freq[26] = {0};
        MPI_Recv(freq, 26, MPI_INT, group_rank, 0, GR_comm, &amp;amp;status);
        MPI_Reduce(freq, freqsum, 26, MPI_INT, MPI_SUM, 0, group_comm);
        if (group_rank == 0)
        {
            char outbuf[1000];
            int index = 0;
            for (int i = 0; i &amp;lt; 26; i++)
            {
                index += sprintf(outbuf + index, "%c: %d\n", 'a' + i, freqsum[i]);
            }

            ierr = MPI_File_write(out, outbuf, index, MPI_CHAR, &amp;amp;status);
            if (ierr)
            {
                if (group_rank == 0)
                    fprintf(stderr, "%s: Couldn't write to file %s", argv[0], argv[2]);
                MPI_Finalize();
                exit(8);
            }
        }
    }

    MPI_File_close(&amp;amp;in);
    MPI_File_close(&amp;amp;out);

    MPI_Finalized(&amp;amp;finalized);
    if (!finalized)
        MPI_Finalize();
    cout &amp;lt;&amp;lt; "Total Time: " &amp;lt;&amp;lt; duration(timeNow() - t1) &amp;lt;&amp;lt; " seconds";
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How to run?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To run this program, you need to have MPI installed on your system. You can then compile the program using &lt;br&gt;
&lt;code&gt;mpic++ main.cpp -o main.out&lt;/code&gt;&lt;br&gt;
 and run it using &lt;br&gt;
&lt;code&gt;mpirun --hostfile mpi.config -np 4 ./main.out test.txt out.txt&lt;/code&gt;&lt;br&gt;
Where &lt;code&gt;test.txt&lt;/code&gt; is the input file and &lt;code&gt;out.txt&lt;/code&gt; is the output file. The &lt;code&gt;--hostfile&lt;/code&gt; option specifies the host file that contains a list of hosts (computers) to be used in the MPI job, and &lt;code&gt;-np 4&lt;/code&gt; specifies the number of processes to run.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Results:&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqg844uhhfv9sm7dbb7ld.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqg844uhhfv9sm7dbb7ld.png" alt="Benchmark"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Drawbacks:&lt;/strong&gt;&lt;br&gt;
One of the drawbacks of this code is that it is limited in the number of processes it can use. This is due to the fact that the intercommunicator only supports four processes. This means that if more than four processes are available, the code will not be able to utilize them. Additionally, the code is limited in the size of the file that it can read. This is due to the fact that it splits the file into chunks that are equal in size. If the file is too large, the code will not be able to split it into chunks that are equal in size.&lt;/p&gt;

</description>
      <category>openmpi</category>
      <category>distributedsystems</category>
      <category>cpp</category>
      <category>programming</category>
    </item>
    <item>
      <title>What is an APIView?</title>
      <dc:creator>Roshan Chokshi</dc:creator>
      <pubDate>Thu, 12 Aug 2021 18:12:19 +0000</pubDate>
      <link>https://dev.to/chokshiroshan/what-is-an-apiview-2g8o</link>
      <guid>https://dev.to/chokshiroshan/what-is-an-apiview-2g8o</guid>
      <description>&lt;p&gt;The Django REST framework offers a couple of helper classes we can use to create our API endpoints.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;APIView&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ViewSet&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The &lt;code&gt;APIView&lt;/code&gt; and The &lt;code&gt;ViewSet&lt;/code&gt; both classes are slightly different and offer their own benefits in this post we will be diving in &lt;code&gt;APIView&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;APIView&lt;/code&gt; is the most basic type of view we can use to build our &lt;code&gt;API&lt;/code&gt;. It enables us to describe the logic which makes our &lt;code&gt;API&lt;/code&gt; endpoint.&lt;/p&gt;

&lt;p&gt;An &lt;code&gt;APIView&lt;/code&gt; allows us to define functions that match the standard &lt;code&gt;HTTP&lt;/code&gt; methods:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;POST&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, &lt;code&gt;PATCH&lt;/code&gt;, &lt;code&gt;DELETE&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  When to use APIViews?
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Need full control over logic.&lt;/li&gt;
&lt;li&gt;Processing files and rendering a synchronous response.&lt;/li&gt;
&lt;li&gt;Calling other APIs and Services.&lt;/li&gt;
&lt;li&gt;Accessing local files or data.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now let's create our first &lt;code&gt;APIView&lt;/code&gt;. First we are going to import some classes in our &lt;code&gt;views.py&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;from rest_framework.views import APIView
from rest_framework.response import Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Creating &lt;code&gt;FirstAPIView&lt;/code&gt; Class.
&lt;/h4&gt;

&lt;p&gt;Underneath the imports let's create a new class called &lt;code&gt;FirstAPIView&lt;/code&gt; and inherit from the &lt;code&gt;APIView&lt;/code&gt; which we imported from &lt;code&gt;rest_framework&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 FirstAPIView(APIView):
    """ Test API View """

    def get(self, request, format=None):
        """ Returns some random values """
        py_list = [
            "apples","bananas",2,5
            ]

        return Response({'message': 'Hello!', 'list': py_list})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We created a &lt;code&gt;get&lt;/code&gt; function which will return &lt;code&gt;message&lt;/code&gt; and &lt;code&gt;list&lt;/code&gt; as response if we receive &lt;code&gt;GET&lt;/code&gt; request on this path.&lt;/p&gt;

&lt;h4&gt;
  
  
  Wiring it to URl.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('APP_NAME.urls')),
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above code we have made changes over boilerplate code such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Importing &lt;code&gt;include&lt;/code&gt; function which helps us to include Urls from other apps.&lt;/li&gt;
&lt;li&gt;Created new path &lt;code&gt;api/&lt;/code&gt; and wire it up with urls file of app.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create new file in app folder as &lt;code&gt;urls.py&lt;/code&gt; and paste below lines of code in it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import path
from APP_NAME import views

urlpatterns = [
    path('first-view', views.FirstAPIView.as_view()),
    ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By adding above code we:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Imported &lt;code&gt;path&lt;/code&gt; from &lt;code&gt;django.urls&lt;/code&gt; and &lt;code&gt;views&lt;/code&gt; from our custom app. &lt;/li&gt;
&lt;li&gt;Created &lt;code&gt;urlpatterns&lt;/code&gt; which linked &lt;code&gt;first-view&lt;/code&gt; path to our &lt;code&gt;FirstAPIView&lt;/code&gt; class.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Testing our APIView.
&lt;/h4&gt;

&lt;p&gt;In terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py runserver 0.0.0.0:8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Visit below link using any browser:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;127.0.0.1:8080/api/first-view/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Demo
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sb2WIJOS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj4pl34ryjosx6hhd0xe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sb2WIJOS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj4pl34ryjosx6hhd0xe.png" alt="Screenshot 2021-08-12 at 11.38.12 PM"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>django</category>
      <category>python</category>
      <category>rest</category>
      <category>apiview</category>
    </item>
    <item>
      <title>How to Use Email as Username for Django Authentication.</title>
      <dc:creator>Roshan Chokshi</dc:creator>
      <pubDate>Thu, 05 Aug 2021 13:09:39 +0000</pubDate>
      <link>https://dev.to/chokshiroshan/how-to-use-email-as-username-for-django-authentication-8if</link>
      <guid>https://dev.to/chokshiroshan/how-to-use-email-as-username-for-django-authentication-8if</guid>
      <description>&lt;p&gt;Django comes with a default user model that's used for the standard authentication system. If you had worked on Django you probably have seen this authentication page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fptczfqlk38nuv2lyphpz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fptczfqlk38nuv2lyphpz.png" alt="Default Admin Log-in page"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We're going to override this model with our own custom model that allows us to use an &lt;code&gt;Email&lt;/code&gt; instead of the standard &lt;code&gt;Username&lt;/code&gt; that comes with the Django default model.&lt;/p&gt;

&lt;p&gt;We're gonna modify &lt;code&gt;models.py&lt;/code&gt; file to include our user profile model.&lt;br&gt;
The first thing we need to do is import some additional classes at the top.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AbstractBaseUser&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;According to Django documentation &lt;code&gt;AbstractBaseUser&lt;/code&gt; has the authentication functionality only , it has no actual fields, you will supply the fields to use when you subclass.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PermissionsMixin&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Django provides &lt;code&gt;PermissionsMixin&lt;/code&gt;. This is an abstract model you can include in the class hierarchy for your user model, giving you all the methods and database fields necessary to support Django’s permission model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BaseUserManager&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If your user model defines &lt;code&gt;username&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, &lt;code&gt;is_staff&lt;/code&gt;, &lt;code&gt;is_active&lt;/code&gt;, &lt;code&gt;is_superuser&lt;/code&gt;, &lt;code&gt;last_login&lt;/code&gt;, and &lt;code&gt;date_joined&lt;/code&gt; fields the same as Django’s default user, you can install Django’s &lt;code&gt;UserManager&lt;/code&gt;; however, if your user model defines different fields, you’ll need to define a custom manager that extends &lt;code&gt;BaseUserManager&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Add this lines at top of the file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Creating UserProfile Class.
&lt;/h3&gt;

&lt;p&gt;Underneath the imports let's create a new class called &lt;code&gt;UserProfile&lt;/code&gt; and inherit from the &lt;code&gt;AbstractBaseUser&lt;/code&gt; and &lt;code&gt;PermissionsMixin&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class UserProfile(AbstractBaseUser, PermissionsMixin):
    """ Database model for users in the system """
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)

    objects = UserProfileManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def __str__(self):
        """ Return string representation of our user """
        return self.email


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;By adding above code we:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Made the &lt;code&gt;email&lt;/code&gt; and &lt;code&gt;name&lt;/code&gt; field required and made &lt;code&gt;email&lt;/code&gt; unique&lt;/li&gt;
&lt;li&gt;Set the &lt;code&gt;USERNAME_FIELD&lt;/code&gt; which defines the unique identifier for the &lt;code&gt;username&lt;/code&gt; to &lt;code&gt;email&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Specified that all objects for the class come from the &lt;code&gt;UserProfileManager&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Creating UserProfileManager Class.
&lt;/h3&gt;

&lt;p&gt;Now that we have our custom user model we can go ahead and create a manager. Now because we've customized our model we need to tell Django how to interact with this user model in order to create users because by default when it creates a user it expects a user name field and password field but we replace the user name field with an email field.So we just need to create a custom manager that can handle creating users with an email field instead of a user name field.&lt;/p&gt;

&lt;p&gt;Let's create a new class called &lt;code&gt;UserProfileManager&lt;/code&gt; and inherit from the &lt;code&gt;BaseUserManager&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class UserProfileManager(BaseUserManager):
    """ Manager for user profiles """


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;UserProfileManager&lt;/code&gt; the way it manages work is you specify&lt;br&gt;
some functions within the manager that can be used to manipulate objects within the module that the manager is for.&lt;/p&gt;

&lt;p&gt;Below are two functions which we need to add in &lt;code&gt;UserProfileManager&lt;/code&gt; class.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

def create_user(self, email, name, password=None):
        """ Create a new user profile """
        if not email:
            raise ValueError('User must have an email address')

        email = self.normalize_email(email)
        user = self.model(email=email, name=name)

        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, name, password):
        """ Create a new superuser profile """
        user = self.create_user(email,name, password)
        user.is_superuser = True
        user.is_staff = True

        user.save(using=self._db)

        return user


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Above code sets logic for when one creates users and superusers using Django CLI.&lt;/p&gt;

&lt;h3&gt;
  
  
  Update Settings to use Custom Model.
&lt;/h3&gt;

&lt;p&gt;We need add below line in &lt;code&gt;settings.py&lt;/code&gt; to use this model over default one.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;AUTH_USER_MODEL = 'App_name.UserProfile'&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Make changes in Database.&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;Create new migrations and migrate them which will create a new database that uses our custom User Model:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;$ python manage.py makemigrations&lt;br&gt;
$ python manage.py migrate&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Create superuser&lt;br&gt;
&lt;/h3&gt;
&lt;br&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;$ python manage.py createsuperuser&lt;br&gt;
Email address: &lt;a href="mailto:chokshiroshan@gmail.com"&gt;chokshiroshan@gmail.com&lt;/a&gt;&lt;br&gt;
Password:&lt;br&gt;
Password (again):&lt;br&gt;
Superuser created successfully.&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Test&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;As you can see instead of asking for &lt;code&gt;Username&lt;/code&gt; it is prompting for &lt;code&gt;Email&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firs014xrigrw9zfxyxyy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Firs014xrigrw9zfxyxyy.png" alt="Screenshot 2021-08-05 at 6.34.30 PM"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>django</category>
      <category>python</category>
    </item>
  </channel>
</rss>
