<?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 Rishi Banerjee on Medium]]></title>
        <description><![CDATA[Stories by Rishi Banerjee on Medium]]></description>
        <link>https://medium.com/@banerjeerishi?source=rss-757715c5ee6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pDyMV78GkCywH7T7iy8Gkw.jpeg</url>
            <title>Stories by Rishi Banerjee on Medium</title>
            <link>https://medium.com/@banerjeerishi?source=rss-757715c5ee6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:49:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@banerjeerishi/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[Deploy Rails 8 with Kamal 2 and DigitalOcean’s Managed Databases Like an Ape]]></title>
            <link>https://medium.com/@banerjeerishi/deploy-rails-8-with-kamal-2-and-digitaloceans-managed-databases-like-an-ape-a566e53c2d43?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a566e53c2d43</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[kamal]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 16:28:31 GMT</pubDate>
            <atom:updated>2025-01-18T16:28:31.523Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Kamal is Kamal (kamal means amazing in Hindi)</blockquote><p>Deploying Rails 8 with Kamal 2 on DigitalOcean sometimes feels like navigating a maze — especially when you’re juggling multiple databases, Docker images, and custom SSH configs.</p><p>It took me a fair bit of trial and error to piece everything together, and I found myself running one-off commands just to confirm each moving part was in place. This blog is an attempt to share everything I learned in a single, cohesive narrative, focusing on DigitalOcean’s Managed Databases and storing Docker images in the DigitalOcean Container Registry.</p><p>I’ll include every little gotcha that had me stuck for hours. <em>(I am not a smart cookie)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwhyCZrwHKk3xb9eWVL4wA.jpeg" /></figure><h3>Why Kamal 2?</h3><p>Rails 8 comes with Kamal (formerly <em>“MRSK”</em>) as an opinionated tool for deployment, but if you’re new to it — or to Docker-based Rails deployments in general — some details can sneak up on you. For example, Kamal automatically runs migrations but won’t seed your database, nor does it create it. Or maybe you need to tweak how multiple databases connect (production, queue, cache, cable). Throw in DigitalOcean’s registry and managed Postgres, and you have plenty of room for configuration mishaps.</p><p>I’ll walk through what I did, highlight the quirks, and show how to test each part so you’re never left guessing what went wrong.</p><blockquote>Note: This is not hardening any VPS, which I’ll cover in a later blog.</blockquote><h3>DigitalOcean Setup and Auth Steps</h3><p>Before even touching your Rails app, you should have your DigitalOcean account and CLI ready to go. If you’re using the DigitalOcean Container Registry and Managed Databases, these commands helped me get set up quickly:</p><pre>doctl auth init<br>docker login registry.digitalocean.com</pre><p>The doctl auth init command configures the DigitalOcean CLI, letting you create databases, droplets, etc., without logging in through the web interface. And docker login registry.digitalocean.com ensures you can push/pull images to your private registry on DigitalOcean. (I decided to store my container images there instead of Docker Hub.)</p><h3>Testing Rails in Production Locally</h3><p>Sometimes, you just want to sanity-check your Rails production environment without the overhead of a full container build. To poke around, I’d run:</p><p>rails c -e production</p><p>This command loads the production environment in your local Rails console. If there are issues with your production gems, environment variables, or configurations, you’ll likely see them here before deploying.</p><p>Another common pitfall is email configuration. If you haven’t set up a mail service, errors can cascade. You can silence those by adding these lines in config/environments/production.rb:</p><pre>config.action_mailer.raise_delivery_errors = false<br>config.action_mailer.perform_deliveries = false<br>config.action_mailer.delivery_method = :test</pre><p>Now you won’t get blocked by an unconfigured mailer when you just want to see if your app boots. Atleast you can have a live web app which you can play with.</p><p>DigitalOcean Managed Databases provide a hostname, port, username, and password. You plug all that into config/database.yml. If you have multiple databases (like for caching or background jobs), it might look something like:</p><pre># We are using PostgreSQL, but you can use Sqlite, Mysql or anything else<br>default: &amp;default<br>  adapter: postgresql<br>  encoding: unicode<br>  # For details on connection pooling, see Rails configuration guide<br>  # http://guides.rubyonrails.org/configuring.html#database-pooling<br>  pool: &lt;%= ENV[&quot;RAILS_MAX_THREADS&quot;] { 5 } %&gt;<br>  &lt;% if ENV[&quot;DB_HOST&quot;] %&gt;<br>  host: &lt;%= ENV[&quot;DB_HOST&quot;] %&gt;<br>  username: postgres<br>  password: postgres<br>  &lt;% end %&gt;<br><br>production:<br>  primary: &amp;primary_production<br>    &lt;&lt;: *default<br>    host: &lt;%= ENV[&quot;PRODUCTION_DB_HOST&quot;] %&gt;<br>    port: &lt;%= ENV[&quot;PRODUCTION_DB_PORT&quot;] %&gt;<br>    username: &lt;%= ENV[&quot;PRODUCTION_DB_USERNAME&quot;] %&gt;<br>    password: &lt;%= ENV[&quot;PRODUCTION_DB_PASSWORD&quot;] %&gt;<br>    database: prod <br>  cache:<br>    &lt;&lt;: *primary_production<br>    database: prod_cache<br>    migrations_paths: db/cache_migrate<br>  queue:<br>    &lt;&lt;: *primary_production<br>    database: prod_queue<br>    migrations_paths: db/queue_migrate<br><br>  cable:<br>    &lt;&lt;: *primary_production<br>    database: prod_cable<br>    migrations_paths: db/cable_migrate<br> </pre><p>ake sure you set the sslmode to require, as Managed Databases typically expect SSL connections. To confirm connectivity from your local machine, you can use the <strong>psql CLI</strong>:</p><p>psql -h DB_HOST -p DB_PORT -U DB_USERNAME -d DB_NAME</p><p>If you can log in, you know your credentials are fine. Don’t forget to close out connections when you’re done.</p><h3>The Dockerfile</h3><p>The Dockerfile you use with Kamal dictates how your Rails app is bundled, what system packages are included, and how assets get precompiled. Here’s a condensed version of the one I used (with some extra goodies like nano, htop, and vim — because debugging a production container without them can be painful). If you’re not using <a href="https://jumpstartrails.com/">Jumpstart Pro</a> or <a href="https://avohq.io/">Avo Pro</a>, you can comment out any lines referencing them:</p><pre># syntax=docker/dockerfile:1<br># check=error=true<br><br>ARG RUBY_VERSION=3.3.6<br>FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base<br><br>WORKDIR /rails<br><br>RUN apt-get update -qq &amp;&amp; \<br>    apt-get install --no-install-recommends -y curl libjemalloc2 libvips sqlite3 postgresql-client libz-dev libssl-dev libffi-dev &amp;&amp; \<br>    rm -rf /var/lib/apt/lists /var/cache/apt/archives<br><br>ENV RAILS_ENV=&quot;production&quot; \<br>    BUNDLE_DEPLOYMENT=&quot;1&quot; \<br>    BUNDLE_PATH=&quot;/usr/local/bundle&quot; \<br>    BUNDLE_WITHOUT=&quot;development&quot;<br><br>FROM base AS build<br><br>RUN apt-get update -qq &amp;&amp; \<br>    apt-get install --no-install-recommends -y build-essential git libpq-dev node-gyp pkg-config python-is-python3 \<br>      imagemagick libvips libvips-dev libvips-tools poppler-utils libyaml-dev nano htop iputils-ping vim &amp;&amp; \<br>    rm -rf /var/lib/apt/lists /var/cache/apt/archives<br><br># Learned it this the hardway, libyaml installation does not work directly, needs to<br># happen this way by using curl<br>RUN curl -LO https://github.com/yaml/libyaml/releases/download/0.2.5/yaml-0.2.5.tar.gz &amp;&amp; \<br>    tar -xzf yaml-0.2.5.tar.gz &amp;&amp; \<br>    cd yaml-0.2.5 &amp;&amp; \<br>    ./configure &amp;&amp; \<br>    make &amp;&amp; \<br>    make install &amp;&amp; \<br>    cd .. &amp;&amp; \<br>    rm -rf yaml-0.2.5 yaml-0.2.5.tar.gz<br><br>ARG NODE_VERSION=22.11.0<br>ARG YARN_VERSION=1.22.22<br>ENV PATH=/usr/local/node/bin:$PATH<br><br>RUN curl -sL https://github.com/nodenv/node-build/archive/master.tar.gz | tar xz -C /tmp/ &amp;&amp; \<br>    /tmp/node-build-master/bin/node-build &quot;${NODE_VERSION}&quot; /usr/local/node &amp;&amp; \<br>    npm install -g yarn@$YARN_VERSION &amp;&amp; \<br>    rm -rf /tmp/node-build-master<br><br>COPY Gemfile Gemfile.lock .ruby-version ./<br><br># If not using Avo Pro, comment out this line:<br>RUN bundle config set --global https://packager.dev/avo-hq/ AVO_GEM_KEY<br>RUN bundle install &amp;&amp; \<br>    rm -rf ~/.bundle/ &quot;${BUNDLE_PATH}&quot;/ruby/*/cache &quot;${BUNDLE_PATH}&quot;/ruby/*/bundler/gems/*/.git &amp;&amp; \<br>    bundle exec bootsnap precompile --gemfile<br><br>COPY package.json yarn.lock ./<br>RUN yarn install --frozen-lockfile<br><br>COPY . .<br><br>RUN bundle exec bootsnap precompile app/ lib/<br>RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile<br><br>FROM base<br><br>COPY --from=build &quot;${BUNDLE_PATH}&quot; &quot;${BUNDLE_PATH}&quot;<br>COPY --from=build /rails /rails<br><br>RUN groupadd --system --gid 1000 rails &amp;&amp; \<br>    useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash &amp;&amp; \<br>    chown -R rails:rails db log storage tmp<br>USER 1000:1000<br><br>ENTRYPOINT [&quot;/rails/bin/docker-entrypoint&quot;]<br><br># Exposing PORT 3000 did not work for me, had to do with 80<br>EXPOSE 80<br>CMD [&quot;./bin/thrust&quot;, &quot;./bin/rails&quot;, &quot;server&quot;]</pre><p>Notice how there’s a build stage and a final stage to keep the production image lean. Also, Kamal will rely on this Dockerfile to build images before shipping them to your DigitalOcean registry.</p><h3>The `deploy.yml` (Kamal Config)</h3><p>Kamal looks for a `deploy.yml` (by default in `config/deploy.yml`) to know how to handle servers, images, and environment variables. Here’s a sample that references a custom SSH config and uses the DigitalOcean registry:</p><pre><br>service: yourbusinessname<br>image: yourbusinessname<br>servers:<br>  web:<br>    - IP_ADDRESS<br>  <br>proxy:<br>  ssl: true<br>  hosts:<br>    - yourfirsthost.com<br>    - yoursecondhost.com<br><br>registry:<br><br>  server: registry.digitalocean.com/yourbusinessname<br>  username: YOUR_USER_NAME <br>  password:<br>    - KAMAL_REGISTRY_PASSWORD<br>env:<br>  secret:<br>    - KAMAL_REGISTRY_PASSWORD<br>    - RAILS_MASTER_KEY<br>    - PRODUCTION_DB_HOST<br>    - PRODUCTION_DB_NAME<br>    - PRODUCTION_DB_PORT<br>    - PRODUCTION_DB_USERNAME<br>    - PRODUCTION_DB_PASSWORD<br>  clear:<br>    SOLID_QUEUE_IN_PUMA: true<br>aliases:<br>  console: app exec --interactive --reuse &quot;bin/rails console&quot;<br>  shell: app exec --interactive --reuse &quot;bash&quot;<br>  logs: app logs -f<br>  dbc: app exec --interactive --reuse &quot;bin/rails dbconsole&quot;<br><br>volumes:<br>  - &quot;store_storage:/rails/storage&quot;<br><br>asset_path: /rails/public/assets<br><br><br>builder:<br>  arch: amd64<br>  secrets:<br><br>    - RAILS_MASTER_KEY<br><br># Use a different ssh user than root<br>ssh:<br>  user: root<br>  keys: [ &quot;~/.ssh/digital_ocean_dev_vm&quot; ]<br></pre><p>This config should work, I had to give KAMAL_REGISTRY_PASSWORD in both secret and in registry</p><p>In your ~/.ssh/config, you might have something like:</p><pre>Host quick_do<br>  HostName IP_ADRESS<br>  User root<br>  IdentityFile ~/.ssh/digital_ocean_dev_vm</pre><p>This way, you can alias your DigitalOcean server to something more memorable. Kamal will connect using this alias to run commands like setup, deploy, logs, etc.</p><h3>Kamal Commands and Testing</h3><p>After everything is configured, Kamal helps you manage your app lifecycle on the server:</p><p>- kamal setup (or kamal setup — verbose): Installs Docker and sets up the server.<br>- kamal deploy (or kamal deploy — verbose): Builds your image, pushes it to the registry, and deploys containers on the server.<br>- kamal app logs: Tails the logs so you can see what’s happening in real time.<br>- kamal remove: Removes your containers if you need a clean slate.</p><h3>Dealing with Local Docker Images</h3><p>When you’re testing locally, you might accumulate a bunch of leftover images or partial builds. If you’re using Buildx and you need to reset, use:</p><p>docker buildx rm kamal-local-docker-container</p><p>It’s a quick fix when you start running out of disk space or something seems stuck in Docker caching.</p><h3>Production Key</h3><p>Use rails credentials:edit –environment=production to generate the production credentials in config/credentials/. This command creates two files: production.key and production.yml.enc. Kamal often references these files in its secrets configuration, so keep them properly managed and stored securely.</p><p>Check the comment I’ve written in the below secrets sample file</p><pre>KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD<br>PRODUCTION_DB_HOST=$PRODUCTION_DB_HOST<br>PRODUCTION_DB_PORT=$PRODUCTION_DB_PORT<br>PRODUCTION_DB_NAME=$PRODUCTION_DB_NAME<br>PRODUCTION_DB_USERNAME=$PRODUCTION_DB_USERNAME<br>PRODUCTION_DB_PASSWORD=$PRODUCTION_DB_PASSWORD<br><br><br># Improve security by using a password manager. Never check config/master.key or config/credentials/*.key into git!<br># RAILS_MASTER_KEY=$(cat config/master.key)<br># But its gonna be<br>RAILS_MASTER_KEY=$(cat config/credentials/production.key)</pre><blockquote>I was writing master.key and then I was tearing off my hair why it was not working</blockquote><h3>Kamal Bash</h3><p>A highly useful command for debugging is:</p><pre>kamal app exec -i &quot;/bin/bash&quot;</pre><p>This command allows you to log into the deployed container and access an interactive Bash shell. Once inside, you can run debugging commands such as inspecting logs, checking installed packages, verifying environment variables, or even manually testing Rails commands.</p><h3>Wrapping Up the Gotchas</h3><p>- <strong>Suppressing emails</strong>: If no email service is set up, turn off deliveries in your production environment.<br>- <strong>Multiple DB connections</strong>: Confirm each one with `psql` using the credentials from DigitalOcean.<br>- <strong>SSH config</strong>: Keep your ~/.ssh/config neat so you don’t get confused about which server you’re deploying to.<br>- <strong>DigitalOcean registry</strong>: Login with docker login registry.digitalocean.com, and push images to the correct URL.<br>- <strong>Comment out lines</strong> referencing premium gems or private repositories if you’re not using them.</p><p>Once all these pieces are in place, you’ll have a reliable pipeline. The next time you push code, you can just run kamal deploy and watch your app gracefully update. If something fails, you know exactly which logs to inspect and which config to tweak.</p><p><strong>Please put in comments if any one of you faced problems, maybe I missed them. Will be glad to help :)</strong></p><p><strong><em>Kamal is infact, KAMAL</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a566e53c2d43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why should one learn more languages?]]></title>
            <link>https://medium.com/@banerjeerishi/why-should-one-learn-more-languages-6d9758320b3c?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d9758320b3c</guid>
            <category><![CDATA[polyglot]]></category>
            <category><![CDATA[culture]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[human-behavior]]></category>
            <category><![CDATA[language-learning]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 20:02:05 GMT</pubDate>
            <atom:updated>2024-11-07T21:00:18.042Z</atom:updated>
            <content:encoded><![CDATA[<p>I grew up in a <strong>Bengali-speaking</strong> home in West Bengal, surrounded by relatives and neighbors who treated Bengali like an unwritten rule of the household. But head outside, and it was a different story. In school, my classmates who weren’t Bengali always seemed to expect me to slip into Hindi, as if the outside world had a <em>“default”</em> language setting. I didn’t mind — Hindi was second nature to me too. But it’s funny how those assumptions work, how we all settle into these little language boxes based on what we think we know about each other.</p><p>Then one day, not so long ago, we had a family gathering, and our Punjabi Sikh neighbors showed up. For as long as I’d known them, we’d only ever spoken in Hindi. I’d assumed that was their comfort zone, as much as Bengali was mine.</p><p>So, you can imagine my surprise when the family matriarch leaned over to me and said, in flawless Bengali,</p><blockquote>“আর ঋষি কি খবর তোমার? কত দিন পরে দেখছি তোমায়” (<em>aar Rishi ki khobor tomar, koto din por dekchi tomai)</em></blockquote><p>“<strong>So Rishi, whats new? Seeing you after so long</strong>”</p><p>My heart practically burst. Here was someone who wasn’t supposed to know my language, suddenly speaking it as naturally as if she’d grown up with it. Hearing my mother tongue from someone else’s lips — someone who chose to speak it out of joy, not obligation — was like finding a part of myself in an unexpected place. I was teary-eyed, barely holding back the emotion.</p><p>Fast-forward to my first year in Bangalore. I was hustling hard, clocking nearly 18-hour days and barely finding time to learn Kannada, a language that didn’t overlap much with Hindi or Bengali. It was tough to squeeze in those extra words and phrases, but little by little, I tried. I’d throw in a <strong>“yeshtu”</strong> <em>(how much)</em> when buying bananas or <strong>“hogubartini” </strong><em>(I’m going)</em> with the vegetable vendors. You’d think those few words wouldn’t mean much, but every time I spoke even a tiny bit of Kannada, the vendor’s face would light up. Those simple exchanges felt like little bridges, where each smile and nod of approval was a reminder that language, no matter how basic, is about connection.</p><p>Later, while traveling through Rameshwaram and Madurai, I realized just how much a few words could open doors. I knew hardly any Tamil beyond a clumsy <strong>“nandri anna”</strong> <em>(thank you, brother) </em>and a couple of other basics, but the locals appreciated the effort like it was poetry.</p><p>In Madurai, a restaurant owner was so thrilled with my attempts at Tamil that he waved away my payment — on the house. In Rameshwaram, the same thing happened when I greeted a street vendor with a humble <strong>“vanakkam” </strong><em>(hello)</em> and a few more Tamil phrases. They smiled, laughed, and treated me not just as a visitor, but as a guest. Just those small efforts at their language brought out a warmth that transcended words.</p><p>These moments taught me something I hadn’t realized: human languages are more than words.</p><p>Imagine this, you’re in Amritsar, Punjab, lined up for langar at the <strong>Golden Temple</strong>, catching the hum of Punjabi around you. Or maybe you’re on a train from Mumbai to Chennai, hearing everything from Marathi to Tamil echo through the compartment. These aren’t just sounds — they’re slices of life. And there’s something in each of them waiting to be understood, right?</p><p>Each language here brings its own rhythm, its own sense of humor, its own way of describing life. Most of us already speak more than one language, but what about learning another? <br> <br> It’s more than just a skill or something to put on a résumé. It’s like saying,</p><blockquote><em>I want to understand you, not just at face value, but in a way that makes us feel like neighbors, no matter where we’re from.</em></blockquote><p>India is a blend that’s impossible to grasp through translations alone. Hindi may help you order a dosa in Kerala, but if you really want to understand why they drizzle everything with coconut oil or why the sambhar recipe is practically a family heirloom, you need Malayalam. Locals might chuckle when they call you <strong>“achayan” </strong>or <strong>“kochamma”</strong>, and those titles say more about community and respect than any English word could.</p><p>Or take Tamil Nadu, where ordering tea involves more than just saying “chai.” You ask for ‘<strong>kumbakonam degree coffee’</strong> with a certain reverence, knowing it’s brewed to perfection with frothy layers, and it’s almost its own genre of coffee!</p><p>And don’t get me started on Kannada: you’ll hear a cheerful <strong>“yenu samachara?”</strong> <em>(what’s the news?)</em> from your vendor, which sounds like they’re truly interested in your life, even if they’re just asking if you want more bananas.</p><p>Then there’s Maharashtra, where Marathi expressions like <strong>“kay zala!”</strong> <em>(what happened!)</em> carry a world of emotion — equal parts concern and sarcasm — that a simple “what’s wrong” could never capture.</p><p>And if you’re in Punjab, you’ll quickly learn that being called <strong>“puttar”</strong> <em>(child)</em> by a stranger isn’t an invasion of space; it’s an invitation to be family, to be part of the laughter, the warmth, and the endless rounds of tea and parathas.</p><p><strong>You get the flavor of the place, unfiltered, in a way you can’t if you’re relying on a Google translation.</strong></p><p>Look, we all know regional divides are real. Someone from the North assumes Malayalam sounds like “just sounds” (come on, you’ve heard it), and some folks from Chennai think Hindi’s just for “North Indians.” But picking up even a bit of another language lets you cut through that noise. It says, <strong><em>“Hey, I see you. I’m not here with my own assumptions — I’m actually interested.”</em></strong></p><p>Imagine you’re a Gujarati trying to talk to a Bengali in their language, or you’re a Rajasthani making an effort in Kannada. Those walls we all put up around <strong>“my state, my language!”</strong> start to crack a little. Learning someone’s language is like extending a hand and saying, <strong>“Show me your world.” And ten times out of ten, people open right up.</strong></p><p>If you’ve grown up juggling Hindi, English, maybe some Punjabi, or Marathi, you’re already a <strong>multilingual pro, a polygot</strong>. But when you dive into a totally new Indian language, you realize there’s more beneath the surface. Every language has its little treasures. In Tamil, for instance, there’s an entire vocabulary just for types of rain. In Urdu, you’ll find phrases for emotions so specific they could fill a book. Bengali, for example, has words that evoke a unique emotional depth. <strong>“Obhiman”</strong> <strong>(অভিমান) </strong>isn’t just about hurt feelings — it’s a type of sulking with dignity, often found in Bengali love stories or everyday relationships. And <strong>“adda”</strong> <strong>(আড্ডা)</strong>, an untranslatable gem, refers to a deep, unstructured conversation with friends that spans hours, topics, and endless cups of tea. It’s the heart of Bengali culture, as essential as the language itself.</p><p><strong>Assamese (Axomiya)</strong> also has its own distinctive terms rooted in the land. With Assam’s torrential monsoon rains, they have <strong>“boroxun”</strong>, which refers to the kind of heavy rain that fills rivers to the brim. Assam’s love for its heritage and land comes through in phrases like <strong>“joi aai Axom”</strong> <em>(“victory to mother Assam”)</em>, a proud rallying cry for the state’s identity.</p><p>Similarly, <strong>Manipuri “Meiteilon”</strong> gives voice to its rich natural landscapes, with words like “<strong>chingkhei”</strong> that refer to the refreshing mountain breeze. These languages carry a strong sense of place, with vocabulary that feels shaped by their regions.</p><p>Even Hindi, often seen as a “<em>common tongue</em>” across much of India, has layers that differ from region to region within the same state. In Uttar Pradesh alone, you’ll hear <strong>‘Bhojpuri’</strong> in the east, with phrases like <strong><em>“ka haal ba”</em></strong> for <em>“how are you?”</em> which brings a rustic warmth. In the Awadh region, there’s <strong>‘Awadhi’,</strong> where expressions like <strong>‘kahe ka humre ghare aawat ho’</strong> <em>(why are you coming to my place)</em> are used in friendly jest. Meanwhile, in western UP, <strong>‘Braj Bhasha’ </strong>is known for poetic references to Krishna, with phrases like<strong> ‘kunj bihari’</strong> that transport you to the lands of Vrindavan. Each of these dialects and languages offers its own flavor, one that’s impossible to fully understand through translations alone.</p><p>Across India, language is not only a means of communication but a way to understand each other’s worlds. From Odia’s classical words that capture monsoon rains and devotional poetry, to Kashmiri’s <strong>‘chandan wath’</strong> (pleasant weather after snowfall) and Himachali’s<strong> ‘jareyo’ </strong><em>(“how are you”)</em><strong>,</strong> these expressions are bridges into the daily lives, histories, and imaginations of people across the country.</p><p>These words and phrases expand your own understanding of what’s normal. You see how people from other regions interpret love, friendship, respect, and even humor. It’s like stepping outside your own brain for a bit and seeing things from a new, quirky, sometimes hilarious point of view.</p><p>Sure, speaking multiple languages is great for the resume. It’s practical, it’s useful, it’ll get you places — literally. But in India, it’s also just about being able to really talk to people. You travel up to Himachal and find yourself connecting with someone who doesn’t speak your language but gets a grin on their face when you manage a broken sentence in their tongue. It’s a real moment, not a transactional one.</p><p>Or maybe you’re at a wedding in Kerala, a fish-out-of-water Mumbaiite, but you make the effort to greet an elder in Malayalam.<strong> Suddenly, you’re not just a guest — you’re a part of it. </strong>Language here isn’t about “fluency” as much as<strong> it is about shared experience</strong>.</p><blockquote>You don’t have to be perfect; you just have to try!</blockquote><p>The thing about learning another Indian language is, strangely, it changes how you see your own. You start noticing things — like how Hindi borrowed a bunch of words from Farsi, or how Sanskrit pops up in places you didn’t expect. Sanskrit almost pops up everywhere. You get curious. Suddenly, your own language doesn’t feel as static, and you start seeing connections between languages you never thought had anything to do with each other.</p><p>I had my phase with language learning apps like Duolingo. I guess I still use it lot more than I should. I’d log in religiously every day, practicing phrases like <strong><em>“El gato está en la ventana</em></strong>”, fantasizing about becoming a hyperpolyglot one day. One of those rare people who can switch between languages like it’s nothing, holding conversations with ease whether they’re in a Parisian café or a crowded Tokyo subway.</p><p>That dream hasn’t exactly become reality yet, but here’s the thing: even my <em>broken</em> Spanish ended up surprising me with connections I never expected. It’s a quirky phenomenon — you’re at a party or in a café, and someone overhears you saying something in Spanish, then it turns out <em>they</em> spent time in Spain or love Latin American culture. Suddenly, you’re swapping stories and forming this weird little bond over Spanish phrases you probably both barely remember. Here in India, I even met a few new friends this way. It’s funny how just knowing a few words can spark a conversation and turn strangers into buddies.</p><p>And then there’s Chinese. The more I chipped away at it, the more I realized how the characters reveal layers of Chinese history, art, and philosophy. The writing isn’t just functional; it’s cultural. You start with basic radicals, and you realize these symbols aren’t random at all. They represent nature, family, emotions — everything that shapes human experience. I’m still far from fluent (and sometimes I feel like I’ll need a lifetime to even get close), but that tiny bit of progress has given me a whole new level of appreciation for Chinese culture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fsDXMzYWpGpq7UzU" /><figcaption>Something that I generated with DALL-E to server as this posts banner image ;(</figcaption></figure><p>So, yeah, learning a new language is work. It’s awkward, sometimes straight-up embarrassing. You’ll trip over words, <strong>say things that make locals chuckle</strong>, and sometimes feel like you’ll never get beyond the basics. But each stumble is like peeling back a layer of the world around you, revealing colors, sounds, and stories you didn’t even know were there.</p><p>In a place as wildly diverse as India, language is so much more than vocabulary and grammar. It’s a way of stepping into someone else’s world, even if just for a moment. It’s a gesture that says, <strong>“I see you, and I want to know what life looks like through your eyes.”</strong> Whether it’s ordering tea in Tamil or sharing a laugh in Kannada, each effort brings you a little closer, turning strangers into neighbors, and neighbors into friends.</p><p>And in that moment — when you see a smile break across a vendor’s face or hear laughter sparked by your clumsy attempts — you realize that language is a bridge, one that stretches across places, cultures, and hearts. Because really, there’s no other way to say it: language is a way of saying, <strong>“I get you”</strong> and finding that maybe, just maybe, you belong here too.</p><p><strong><em>Few interesting resources</em></strong><br>1. <a href="https://www.youtube.com/@LanguageSimp">Language Simp</a> — this guy is a hyperpolygot, truly an inspiration<br>2. <a href="https://www.youtube.com/@loic.suberville">Loic Suberville</a> — he shows how all languages have their own weird rules and exceptions<br>3. <a href="https://www.youtube.com/@lingualizer">Lingualizer</a> — shows the value in speaking languages by connecting with people in their languages<br>4. <a href="https://www.youtube.com/@xiaomanyc"><strong>Xiaomanyc 小马在纽约</strong></a><strong> — </strong>he goes around talking to people in their mother tongue.</p><p>Check more about me <a href="http://banerjeerishi.com/">here</a>! Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d9758320b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails really packs a Punch ]]></title>
            <link>https://medium.com/@banerjeerishi/rails-really-packs-a-punch-508591157224?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/508591157224</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 16:58:54 GMT</pubDate>
            <atom:updated>2024-10-05T16:58:54.106Z</atom:updated>
            <content:encoded><![CDATA[<p>After seven years with Django, I’ve become a bit of a Python zealot. It’s sleek, it’s flexible, and with Django, you have all the essentials neatly packed into a one-stop web framework. Yet, for the past couple of years, I’ve been dabbling with Ruby on Rails. And honestly? Rails 8 has made quite an impression on me, leaving me in a tug-of-war between these two worlds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTEXqo0ZuXyn3kpljHlvdw.jpeg" /><figcaption>The reward? the joy of programming!</figcaption></figure><p>Now, don’t get me wrong — I still love Django. It’s like that dependable partner who’s always there for you. But Rails, especially the upcoming latest 8.0 release, has an undeniable allure. It’s like discovering a <strong><em>new love that sweeps you off your feet while you’re still in a long-term relationship</em></strong>. Let’s dive into what makes Rails 8 so intriguing and where it might still stumble.</p><p>Rails 8 has introduced some game-changing features, particularly in how it tackles the problem of application deployment. Remember the headaches of managing deployments without the help of a platform-as-a-service (PaaS)? For many of us, this meant spending hours fine-tuning our infrastructure, only to be hit with eye-watering AWS bills at the end of the month. Or the pain of using Azure, but not through VSCode, the Microsoft UI. Hosting on PaaS platforms like Heroku, while convenient, can quickly become prohibitively expensive as your app scales. Rails 8 essentially shifts the focus <strong>back to building</strong>, rather than constantly fretting over where and how your app will run. It’s a change that’s hard to overstate for developers who have spent years wrestling with infrastructure and battling escalating cloud costs. I’ve found how stressful it was in early days of my life when I made a cute and solid django project, and had to hunt through websites on how to deploy for a client, knowing nothing about “DevOps”.</p><h4><strong>Kamal2 is huge!</strong></h4><p>It can be used with django as well but kudos to the rails team for bringing to us devs! It’s essentially Rails’ way of saying, <strong><em>“We’ve got your back, even when it comes to deployment.” </em></strong>You provide the IP addresses of your servers and your SSH key, and Kamal handles the rest. It automates the setup, turning a plain Linux box into a fully functional app server within minutes. You can even deploy it in a simple raspberry pi and have it served to someone in the Bahamas.</p><p>Another feature that caught my attention is Thruster, which acts as a built-in proxy for the Puma web server. Thruster eliminates the need for an external web server like Nginx, allowing the Rails app to handle internet traffic directly. In contrast, Django developers often find themselves wrangling with configurations for web servers to act as reverse proxies. A streamlined, built-in proxy layer for Django could save developers a lot of time and reduce the complexity of their deployment setups. All my projects run on Nginx, but surely I’ve been pained a lot in places where either nginx was part of the docker setup, or sometimes via the sites-enabled/nginx setup</p><blockquote><strong>”Thruster aims to be as zero-config as possible. It has no configuration file, and most features are automatically enabled with sensible defaults. The goal is that simply running your Puma server with Thruster should be enough to get a production-ready setup.” </strong>— <a href="https://github.com/basecamp/thruster">Thruster Readme</a></blockquote><h4>The Solid Series &amp; Less Reliance on Third-Party Services:</h4><p>Rails 8’s introduction of Solid Cable, Solid Cache, and Solid Queue is another area where it flexes its muscles. Traditionally, Rails apps have relied on services like Redis for caching, background jobs, and WebSockets. In Rails 8, this is now simplified, with SQLite being used for these tasks by default. This change brings Rails back to its <strong>“batteries-included”</strong> philosophy, removing the need for additional services to get started. For Django, adding features like real-time communication (Channels) or caching (Redis or Memcached) often requires setting up separate services, along with their own configurations and maintenance overhead. While Django does provide robust support for integrating with these services, a built-in, Rails-like approach to handling tasks with the default database would be a game-changer. Imagine a world where Django handles WebSockets, background jobs, and caching seamlessly with just the default SQLite or PostgreSQL setup.</p><p>While Rails embraces its “<strong>convention over configuration”</strong> philosophy, which often results in faster development and fewer decisions to make upfront, Django leans more towards explicit configuration. For example, Rails’ automatic setup for things like asset management or database connections means you can focus more on building your app rather than tweaking settings files. A GoLang developer will disagree with me on <strong>“Magic”</strong> but man oh man! I am a child, and I like magic via abstraction.</p><p>There’s a wishful part of me that longs for a Rails-like magic in some of Django’s more tedious setups, without sacrificing the explicitness that makes Django so versatile. A bit of Rails’ opinionated convenience in Django — while preserving Django’s flexibility — would make the development process even more enjoyable ❤</p><p><em>Disclaimer: The opinions expressed here are based on personal experience. Cloud services like AWS, Heroku, and others have their advantages, offering scalability, managed services, and convenience. However, they can also become costly depending on usage. Your mileage may vary, and the right choice always depends on the specific needs and context of your project.</em></p><p>You can find me writing more at <a href="http://banerjeerishi.com/">banerjeerishi.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=508591157224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a scheduler using Django, CeleryBeat & CronTab]]></title>
            <link>https://medium.com/django-unleashed/writing-a-scheduler-using-django-celerybeat-crontab-b3d5689abbe1?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3d5689abbe1</guid>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[celerybeat]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[scheduler]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 17:40:00 GMT</pubDate>
            <atom:updated>2024-09-10T17:40:00.418Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>To senior engineers, the code below might be subpar!</blockquote><p>Today we’re diving into something super practical — how to build a medicine reminder app using Django, Celery-Beat, and Docker. If you’ve been dabbling with Django and Celery, you know how crucial task scheduling can be. Sending payment reminders, scheduling notifications just like Jira, where you get bombarded by “overdue tickets” and much much more. And if you’re like me, you’ve probably been stuck in the weeds of setting up periodic tasks at some point. But, let’s simplify it with Celery-Beat and make it… almost fun.</p><p>Scheduling things are usually done via Crontabs. And if you’ve ever tried managing crontabs directly on Linux, you know it’s an absolute pain. You have to set them up using cryptic syntax, something like <strong>0 9 * * *, </strong>which basically means <strong><em>“run this at 9 AM every day.”</em></strong> But, oh boy, miss one asterisk or forget to restart your cron service and nothing works.</p><p>Setting up Celery and Celery-Beat as services with Systemd is another headache. You’ve got to configure <strong>celery.service</strong> and <strong>celery-beat.service</strong> files, ensuring they’re running smoothly with Redis as the broker. And let’s not forget, each time you make a small change, you have to restart services, check logs, and deal with errors like:</p><p>Failed to start celery.service: Unit celery.service not found</p><p>With Celery-Beat, we avoid the whole mess of manually writing and managing crontabs. The scheduling is baked into Django itself, and Celery-Beat takes care of the rest. Plus, it’s integrated with your database, so you can easily query schedules and update them without editing cryptic files. No more “SSHing” into your server and praying you didn’t mess up a cron job! 🙌</p><blockquote>I‘ve failed a million times almost, trying to setup systemmd services, and I’ve told myself “I aint no sys admin, I am a pythonista, I like to just pip my features”</blockquote><p>Well, hopefully this blog helps you set up an app for yourself, maybe its a calendar app, or a simple reminder app for anything.</p><p>We’re going to build a <strong>simple medicine reminder app.</strong> My grandma takes a lots of meds, and even though we take care of her, sometimes she forgets, or sometimes we do. It’s kinda messy. So with the help of this app, we are gonna send scheduled reminders. <em>(to my grandma, who does not use a phone :()</em></p><p>But first, lets summon Docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaFVKE76hRzEZtXxdswY9A.png" /></figure><p>We have a docker file which you can find <a href="https://gist.github.com/rshrc/389408f840712bce6c01ed3fc7873396">here</a></p><p>We are gonna have a docker compose file which is gonna look something like this</p><pre>version: &#39;3&#39;<br>services:<br>  redis:<br>    image: &quot;redis:alpine&quot;<br>    container_name: redis<br>    ports:<br>      - &quot;6379:6379&quot;<br><br>  django:<br>    build: .<br>    container_name: django<br>    command: gunicorn reminder_app.wsgi:application --bind 0.0.0.0:8000<br>    volumes:<br>      - .:/app<br>    ports:<br>      - &quot;8000:8000&quot;<br>    depends_on:<br>      - redis<br>    environment:<br>      - CELERY_BROKER_URL=redis://redis:6379/0<br>      - CELERY_RESULT_BACKEND=redis://redis:6379/0<br><br>  celery:<br>    build: .<br>    container_name: celery<br>    command: celery -A reminder_app worker --loglevel=info<br>    volumes:<br>      - .:/app<br>    depends_on:<br>      - redis<br>    environment:<br>      - CELERY_BROKER_URL=redis://redis:6379/0<br>      - CELERY_RESULT_BACKEND=redis://redis:6379/0<br><br>  celery-beat:<br>    build: .<br>    container_name: celery-beat<br>    command: celery -A reminder_app beat --loglevel=info<br>    volumes:<br>      - .:/app<br>    depends_on:<br>      - redis<br>    environment:<br>      - CELERY_BROKER_URL=redis://redis:6379/0<br>      - CELERY_RESULT_BACKEND=redis://redis:6379/0</pre><p>This you can put in a docker-compose.local.yml file and also pass in .env instead of putting details there. Usually in production we protect redis using password and all, but for the sake of this article, I am gonna assume no one is gonna hack stuff.</p><p>This sets us up with Redis as the broker, and both Celery and Celery-Beat containers, which handle task execution and scheduling respectively. I want to address one thing here, since I was a dummy most of my life, I am assuming someone might ask, <strong><em>why this redis?</em></strong></p><blockquote>Simply put, Redis acts as a message broker. When you schedule a task, Celery uses Redis to store the task and ensure that it gets executed at the right time. Without Redis (or another broker like RabbitMQ), Celery wouldn’t know what to do with all these tasks. It’s basically the <strong>“middleman” </strong>that holds tasks in a queue until they’re picked up by the Celery worker to be executed. So yeah, no Redis, no task execution.</blockquote><p>Lets build the Medicine Reminder Model</p><p>We’re building a reminder app, so we need a way to schedule when the reminders should go off. Enter the `Recurrence` model, which handles the schedule of your reminders. We’ll use the <a href="https://github.com/celery/django-celery-beat">django_celery_beat </a>library to manage periodic tasks (schedules).</p><p>Here is a simplified version of the Recurrencemodel that I use</p><pre>import calendar<br>import zoneinfo<br>from django.db import models<br>from django_celery_beat.models import CrontabSchedule, IntervalSchedule<br><br>TIMEZONE = zoneinfo.ZoneInfo(&#39;Asia/Kolkata&#39;)<br><br>class Recurrence(models.Model):<br>    repeat_choices = [<br>        (&#39;none&#39;, &#39;Does not repeat&#39;),<br>        (&#39;daily&#39;, &#39;Daily&#39;),<br>        (&#39;weekly&#39;, &#39;Weekly&#39;),<br>        (&#39;monthly&#39;, &#39;Monthly&#39;),<br>        (&#39;yearly&#39;, &#39;Yearly&#39;)<br>    ]<br>    repeat = models.CharField(max_length=10, choices=repeat_choices, default=&#39;none&#39;)<br>    repeat_every = models.PositiveIntegerField(blank=True, null=True)<br>    days_of_week = models.CharField(max_length=255, blank=True, null=True)<br>    day_of_month = models.PositiveIntegerField(blank=True, null=True)<br>    month_of_year = models.PositiveIntegerField(blank=True, null=True)<br>    minute = models.PositiveIntegerField(default=0)<br>    hour = models.PositiveIntegerField(default=9)  # default: 9AM<br>    <br>    def __str__(self):<br>        return f&quot;Reminder set for {self.description}&quot;<br><br>    @property<br>    def description(self):<br>        # Return a friendly string describing the schedule<br>        if self.repeat == &#39;daily&#39;:<br>            return &quot;Daily at {}:{}&quot;.format(self.hour, self.minute)<br>        elif self.repeat == &#39;weekly&#39;:<br>            days = self.days_of_week or &#39;every day&#39;<br>            return &quot;Weekly on {} at {}:{}&quot;.format(days, self.hour, self.minute)<br>        return &quot;Custom schedule&quot;</pre><p>This gives us the flexibility to schedule reminders daily, weekly, monthly, or even yearly. You can specify the time, day of the week, or day of the month when the reminder should be sent.</p><p>This model will include a <em>get_schedule()</em> function, which is gonna return the appropriate schedule. This is the part that tells Celery-Beat how to handle the recurrence schedule based on the user’s input. Without it, Celery wouldn’t know what the schedule looks like.</p><pre>def get_schedule(self):<br>    if self.repeat == &#39;daily&#39;:<br>        # Default to all days if not specified<br>        days = self.days_of_week or &#39;0,1,2,3,4,5,6&#39;<br>        return CrontabSchedule.objects.get_or_create(<br>            minute=self.minute,<br>            hour=self.hour,<br>            day_of_week=days,<br>            timezone=TIMEZONE<br>        )<br>    elif self.repeat == &#39;weekly&#39;:<br>        if not self.days_of_week:<br>            raise ValueError(&quot;Days of week must be provided for weekly recurrence&quot;)<br>        return CrontabSchedule.objects.get_or_create(<br>            minute=self.minute,<br>            hour=self.hour,<br>            day_of_week=self.days_of_week,<br>            timezone=TIMEZONE<br>        )<br>    elif self.repeat == &#39;monthly&#39;:<br>        day_of_month = self.day_of_month or 1<br>        return CrontabSchedule.objects.get_or_create(<br>            minute=self.minute,<br>            hour=self.hour,<br>            day_of_month=day_of_month,<br>            timezone=TIMEZONE<br>        )<br>    elif self.repeat == &#39;yearly&#39;:<br>        if not self.day_of_month or not self.month_of_year:<br>            raise ValueError(&quot;Both day of month and month of year must be provided for yearly recurrence&quot;)<br>        return CrontabSchedule.objects.get_or_create(<br>            minute=self.minute,<br>            hour=self.hour,<br>            day_of_month=self.day_of_month,<br>            month_of_year=self.month_of_year,<br>            timezone=TIMEZONE<br>        )<br>    elif self.repeat_type == &#39;interval&#39;:<br>        return IntervalSchedule.objects.get_or_create(<br>            every=self.interval,<br>            period=IntervalSchedule.HOURS,<br>        )<br><br>    return None</pre><p>Lets tie this django model to a Medicine model.</p><p>We need to associate this recurrence schedule with the medicine model itself. Here’s a simplified Medicine model that uses our Recurrence model:</p><pre>class Medicine(models.Model):<br>    name = models.CharField(max_length=255)<br>    dosage = models.CharField(max_length=255)<br>    recurrence = models.ForeignKey(Recurrence, on_delete=models.CASCADE, blank=True, null=True)<br><br>    def __str__(self):<br>        return f&quot;{self.name} - {self.dosage}&quot;</pre><p>We are gonna add a schedule_task function to the Medicine model which is gonna take care of scheduling the periodic task for us</p><pre>from django_celery_beat.models import PeriodicTask<br><br>@hook(AFTER_CREATE)<br>def schedule_task(self):<br>    if not self.recurrence or self.recurrence.repeat == &#39;none&#39;:<br>        PeriodicTask.objects.filter(name=f&#39;medicine-{self.id}&#39;).delete()<br>        return<br><br>    schedule, _ = self.recurrence.get_schedule()<br>    PeriodicTask.objects.update_or_create(<br>        name=f&#39;medicine-{self.id}&#39;,<br>        defaults={<br>            &#39;task&#39;: &#39;reminder.tasks.send_medicine_reminder&#39;,<br>            &#39;crontab&#39;: schedule,<br>            &#39;enabled&#39;: True,<br>            &#39;args&#39;: json.dumps([self.id]),<br>        }<br>    )</pre><p>What this does is, using the AFTER_CREATE <a href="https://medium.com/django-unleashed/django-lifecycle-hooks-ed731e4c829a">lifecycle hook</a>, as soon as it is created, it takes the recurrence object assigned and creates a Periodic task. We can pass in interval, and respectively get a interval schedule out of this task.</p><p>When a Medicine or its recurrence is deleted, we need to ensure that the corresponding Celery tasks get cleaned up too. This is where the unschedule_task function comes into play.</p><p>The purpose of this function is to remove any periodic tasks related to a Medicine instance when it’s no longer needed (e.g., if the user stops taking the medicine or deletes the reminder). Here’s how the unschedule_task method looks:</p><pre>@hook(AFTER_DELETE)<br>def unschedule_task(self):<br>    # Delete the associated Celery task<br>    PeriodicTask.objects.filter(name=f&#39;medicine-{self.id}&#39;).delete()</pre><p>Every time a Medicine instance is deleted, this function will look for any tasks scheduled under the name medicine-{self.id} and delete them from the periodic task table. Without this cleanup, you’d have zombie tasks running for reminders that no longer exist. Optimized!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpPjB-NBAWz3i-K-dV1adA.png" /><figcaption><em>Gonna make this app surely someday! Will be opensource.</em></figcaption></figure><p>This was just a sample app idea, I’ve taken the concepts from what I’ve learned over the years. This app does not exist yet, and I might make a open source version of it. Visit <a href="http://banerjeerishi.com/">banerjeerishi.com</a> for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3d5689abbe1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/writing-a-scheduler-using-django-celerybeat-crontab-b3d5689abbe1">Writing a scheduler using Django, CeleryBeat &amp; CronTab</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django & DRF Flexibility]]></title>
            <link>https://medium.com/django-unleashed/django-drf-flexibility-38c5e6b6435c?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c5e6b6435c</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 07:45:15 GMT</pubDate>
            <atom:updated>2024-04-19T07:45:15.134Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“Express.js is so damn flexible” </em>— Startup Intern</blockquote><p>Sure, it is, but did you know? What takes a week in Express.js, Django knocks out in a <strong>single afternoon</strong>!</p><p>With <a href="https://django-ninja.dev/">Django Ninja</a> showing so much promise, this blog might not be that relevant for senior Django engineers. This is a intro level blog to <a href="https://www.djangoproject.com/">Django</a> &amp; <a href="https://www.django-rest-framework.org/">Django Rest Framework</a> classes and how to modify sub classes to achieve custom behaviour.</p><p>Django is often pegged as being somewhat rigid by some developers.</p><blockquote>Its so hard to customize things Rishi!! Whenever I try to do something different, Django seems to suffocate me :(</blockquote><p>This view, however, doesn’t quite capture the entire picture. Django’s design philosophy —<strong> “batteries included”</strong> — does equip developers with a robust suite of ready-to-use tools, but it also provides ample room for customization. If someones says <em>“Django cannot be customized”</em>, it surely sounds like a skill issue to me</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*f6PIDdLlozFJaXHI.jpg" /></figure><p>In this post, we’ll explore the inherent flexibility of Django and its companion, Django Rest Framework (DRF), by delving into how overriding superclass methods can significantly tailor and enhance your applications.</p><p><strong>Before we dive right into Django classes, lets just first talk about Python.</strong></p><p>When we talk about method overriding in <a href="https://www.python.org/">Python</a>, we’re tapping into one of the fundamental principles of object-oriented programming (OOP): polymorphism. This concept allows us to alter or extend the default behavior of a program at a fundamental level. I had such a hard time findings its usecase 10 years ago. <strong><em>Why would I override the bark function of class Animal?</em></strong> It was a good example but I have a better one.</p><p>Imagine you buy a standard car model from a dealership. This car comes with a default set of features — <strong>engine</strong>, <strong>transmission</strong>, <strong>wheels</strong>, and so on. However, as the owner, you decide to customize this car. You might swap out the <strong>engine for a more powerful one, change the wheels for better performance, or even tweak the interior to better suit your taste.</strong></p><p>In programming, particularly in Python, overriding methods works similarly. You start with a standard, or Base class, which provides basic functionality. But when you need specific functionality not provided by the base class, you can create a subclass and modify (override) the methods to meet your requirements, just like customizing your car.</p><h4>Python Example: Enhancing a Notification System</h4><p>Let’s consider a notification system in a software application. The base class provides a simple way to send notifications, but we might need to customize the way notifications are sent depending on their type (e.g., email, SMS, push notification).</p><h4>Base Class — Notification</h4><p>The base class defines a simple method to send a notification, which includes just a basic message:</p><pre>class Notification:<br>   def send(self, message):<br>     print(f&quot;Sending notification: {message}&quot;)</pre><h4>Subclass — EmailNotification</h4><p>We want our email notifications to include a subject line and to format the message differently. We override the <strong>`send`</strong> method in a subclass to accommodate these additional details:</p><pre>class EmailNotification(Notification):<br>    def send(self, message, subject):<br>        formatted_message = f&quot;Subject: {subject}\n{message}&quot;<br>        print(f&quot;Sending email: {formatted_message}&quot;)</pre><h4>Subclass — SMSNotification</h4><p>For SMS notifications, we might want to ensure the message is within a certain character limit and does not include non-text elements like images or emojis:</p><pre>class SMSNotification(Notification):<br>    def send(self, message):<br>        if len(message) &gt; 160:<br>            message = message[:157] + &#39;...&#39;<br>        print(f&quot;Sending SMS: {message}&quot;)</pre><p><strong>Using the Subclasses</strong></p><p>With these subclasses, we can now tailor our notification system to handle different types of notifications appropriately, much like customizing different aspects of a car:</p><pre>email = EmailNotification()<br>email.send(&quot;Hello, your order has been shipped.&quot;, &quot;Order Update&quot;)<br><br>sms = SMSNotification()<br>sms.send(&quot;Your appointment is coming up soon!&quot;)</pre><p>Just as with car modifications, method overriding lets developers fine-tune their software’s functionality to deliver a more personalized and effective experience. This approach is a cornerstone of software development.</p><h3>The Essence of Django’s Design</h3><p>Django’s architecture encourages swift development with a clean, pragmatic approach. It’s not about enforcing a single way to solve problems but about offering a solid foundation that’s designed to be built upon.</p><p><strong>Using Django with OOP: Overriding Methods</strong></p><p>Object-oriented programming (OOP) lies at the heart of extending Django’s capabilities. Overriding methods, a core concept in OOP, is readily supported and can be a potent way to modify or extend Django’s built-in behavior.</p><h4>Customizing Model Save Method</h4><p>Take a simple blog post model in Django. By overriding the save method, developers can inject custom behavior into the model’s save operations, like ensuring all titles are saved in uppercase:</p><pre>from django.db import models<br><br>class BlogPost(models.Model):<br>    title = models.CharField(max_length=200)<br>    content = models.TextField()<br>    publish_date = models.DateTimeField(auto_now_add=True)<br><br>    def save(self, *args, **kwargs):<br>        self.title = self.title.upper()<br>        super().save(*args, **kwargs)</pre><p><em>Here, the </em><em>save method is an overridden version of the </em><em>save method from Django&#39;s </em><em>models.Model class.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*VbqUKg9h8Kpr1U0zu5oQTA.png" /><figcaption>A peek into the Django Model class in <strong>/django/db/models/base.py</strong></figcaption></figure><h4>Tailoring Form Validation</h4><p>Django forms also benefit from method overriding. Customizing validation logic by overriding methods like clean_email<strong> </strong>allows for specific checks, which can be crucial for maintaining data integrity and user experience:</p><pre>from django import forms<br>from django.core.exceptions import ValidationError<br><br>class ContactForm(forms.Form):<br>    name = forms.CharField(max_length=100)<br>    email = forms.EmailField()<br><br>    def clean_email(self):<br>        email = self.cleaned_data[&#39;email&#39;]<br>        if &quot;example.com&quot; in email:<br>            raise ValidationError(&quot;Registration using &#39;example.com&#39; is not allowed.&quot;)<br>        return email</pre><p>These were some basic override that you can do in Django, lets go to DRF, something modern django apps heavily use to create great API’s.</p><h3>Customizing DRF</h3><p>Building on Django, DRF enhances API development with similar extensibility. Overriding methods within DRF can tailor API behavior to fit even the most specific requirements.</p><h4>Enhancing Serializer Outputs</h4><p>In Django Rest Framework (DRF), serializers play a crucial role in how data is structured and presented to the user. They manage the conversion of complex data types, like Django models, into JSON for API responses and handle incoming data for storage in the database. By overriding methods like to_representation, developers gain significant control over this process, allowing for precise manipulation of the serialized data.</p><h4>The Necessity of Overriding to_representation</h4><p>While DRF is highly efficient and handles many tasks automatically, real-world applications frequently require specific adjustments that the default serializers don’t support out of the box. This necessity often leads to overriding methods like to_representation to ensure the data conforms to specific needs or client requirements.</p><p>For example, you might need to add additional fields that depend on complex logic or aggregate data from multiple sources. Similarly, adjusting the formatting of certain fields, such as dates or monetary values, to meet localization standards is another common requirement.</p><pre>from rest_framework import serializers<br>from django.contrib.auth.models import User<br><br>class UserSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = User<br>        fields = [&#39;id&#39;, &#39;username&#39;, &#39;email&#39;]<br><br>    def to_representation(self, instance):<br>        &quot;&quot;&quot;Modify the output format of the serializer.&quot;&quot;&quot;<br>        ret = super().to_representation(instance)<br>        # Add a custom field based on complex logic<br>        ret[&#39;is_vip&#39;] = instance.groups.filter(name=&#39;VIP&#39;).exists()<br>        # Format the email field to be lowercase<br>        ret[&#39;email&#39;] = instance.email.lower()<br>        return ret</pre><h4>Utilizing Different Serializers Based on Context</h4><p>Overriding get_serializer_class allows for dynamic selection of serializers based on the action being executed, providing enhanced flexibility and control over how data is presented. Typically, in a list view — used to display multiple items on a client application — you’d want to streamline the JSON response to improve performance and load times.</p><p>Conversely, in a detail view, where a single item’s comprehensive details are necessary, a more detailed JSON structure is preferable. This method enables tailored data representation to suit different use cases efficiently.</p><pre>from rest_framework import viewsets<br>from .models import User<br>from .serializers import UserDetailSerializer, UserListSerializer<br><br>class UserViewSet(viewsets.ModelViewSet):<br>    queryset = User.objects.all()<br><br>    def get_serializer_class(self):<br>        # we use the UserListSerializer which contains<br>        # lesser details than the UserDetailSerializer<br>        if self.action == &#39;list&#39;:<br>            return UserListSerializer<br>        else:<br>            return UserDetailSerializer</pre><h4>Adjusting the Serialization Process</h4><p>Customizing the serialization process can help you manipulate how data is saved or updated. Override create and update methods in serializers to include additional logic during these processes:</p><pre>from rest_framework import serializers<br><br>class UserSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = User<br>        fields = &#39;__all__&#39;<br><br>    def create(self, validated_data):<br>        # Custom logic before creating an object<br>        user = User.objects.create(**validated_data)<br>        send_welcome_email(user.email)  # For example, sending a welcome email<br>        return user<br><br>    def update(self, instance, validated_data):<br>        # Custom logic before updating an object<br>        instance.name = validated_data.get(&#39;name&#39;, instance.name)<br>        instance.save()<br>        notify_user(instance.email)  # Notify user about the update<br>        return instance</pre><p>Many of the send_welcom_email kind of features should achieved by signals with a mix of task queues in production, or use <a href="https://medium.com/django-unleashed/django-lifecycle-hooks-ed731e4c829a">Django Lifecycle Hooks</a> which we use way too much at our company</p><h4>Customizing Pagination Behavior</h4><p>Sometimes, the default pagination may not suit the specific needs of your API. You can override the get_paginated_response method in a custom paginator to change how pagination metadata is formatted or what additional data is included. Also in high-traffic applications, you might want users to have the ability to define their pagination sizes within certain limits:</p><pre>from rest_framework.pagination import PageNumberPagination<br>from rest_framework.response import Response<br><br>class CustomPagination(PageNumberPagination):<br>    def get_page_size(self, request):<br>        default_size = 10<br>        max_size = 100<br>        try:<br>            return max(<br>                min(int(request.query_params.get(&#39;page_size&#39;, default_size)), max_size),<br>                1<br>            )<br>        except (TypeError, ValueError):<br>            return default_size<br><br>    def get_paginated_response(self, data):<br>        return Response({<br>            &#39;next&#39;: self.get_next_link(),<br>            &#39;previous&#39;: self.get_previous_link(),<br>            &#39;page_size&#39;: self.get_page_size(self.request),<br>            &#39;data&#39;: data<br>        })</pre><p>This class inherits from DRF’s PageNumberPagination class, which is a pagination style that displays page numbers for navigating through the results. By subclassing PageNumberPagination, we can customize its behavior.</p><p>get_page_size method: This method determines the number of items to include on each page of the paginated response. If the client specifies a page_size query parameter in the request, it tries to convert it to an integer. If the conversion fails, it returns a default size of 10. Additionally, it ensures that the page size falls within a specified range (max_size).</p><p>The get_paginated_response method generates the paginated response data. It takes the data as input, representing the queryset or data to be paginated. It utilizes DRF’s Response class to construct the HTTP response. It includes links for navigating to the next and previous pages (‘next’ and ‘previous’), obtained using the get_next_link() and get_previous_link() methods provided by PageNumberPagination. The page size is obtained by calling the get_page_size method with self.request. It includes the actual data for the current page.</p><h4>Altering Permission Checks</h4><p>The get_permissions method is a part of DRF&#39;s view classes. It&#39;s called during the request handling process to determine the permissions that should be applied to the current request. By default, this method fetches the permission classes defined in the view&#39;s permission_classes attribute. However, overriding this method allows for more nuanced and conditional permission logic.</p><p><strong>When to Override </strong><strong>get_permissions ?</strong></p><p>Overriding get_permissions becomes essential when the access rules for your API need to change dynamically based on the context of the request. Here are a few scenarios where you might need to implement this method:</p><ul><li><strong>Different Permissions for Different Actions</strong>: You might want to allow read-only access to unauthenticated users but restrict write permissions to authenticated users.</li><li><strong>Role-Based Access Control (RBAC)</strong>: Access might depend on the user’s role within the system (e.g., admins can delete posts, but regular users cannot).</li><li><strong>Object-Level Permissions</strong>: Conditions where access depends on properties of the object being accessed or its relationship to the user.</li></ul><p>Let’s consider an API for a blogging platform where the permissions vary significantly between different actions:</p><pre>from rest_framework import viewsets<br>from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser<br>from .models import Post<br>from .serializers import PostSerializer<br><br>class PostViewSet(viewsets.ModelViewSet):<br>    queryset = Post.objects.all()<br>    serializer_class = PostSerializer<br><br>    def get_permissions(self):<br>        &quot;&quot;&quot;<br>        Instantiates and returns the list of permissions that this view requires.<br>        &quot;&quot;&quot;<br>        if self.action == &#39;list&#39;:<br>            permission_classes = [AllowAny]<br>        elif self.action in [&#39;create&#39;, &#39;update&#39;, &#39;partial_update&#39;]:<br>            permission_classes = [IsAuthenticated]<br>        elif self.action == &#39;destroy&#39;:<br>            permission_classes = [IsAdminUser]<br>        else:<br>            permission_classes = [AllowAny]  # Default Permission<br>        return [permission() for permission in permission_classes]</pre><h4>Dynamic Querysets</h4><p>In DRF, ViewSets generally require you to specify a static queryset. However, in <strong>multi-tenant applications </strong>where data access needs to be scoped to individual tenants, you must dynamically adjust the queryset based on the tenant context. This is particularly important to ensure that users only access data that belongs to their respective tenants. Here’s how you can modify the get_queryset method in your ViewSet to accommodate a multi-tenancy setup by using a tenant ID from the request headers.</p><pre>from rest_framework import viewsets<br>from django.db.models import Q<br>from .models import Item<br>from .serializers import ItemSerializer<br><br>class ItemViewSet(viewsets.ModelViewSet):<br>    &quot;&quot;&quot;<br>    A simple ViewSet for viewing and editing items scoped by tenant ID.<br>    &quot;&quot;&quot;<br>    serializer_class = ItemSerializer<br><br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Dynamically return items based on the tenant ID specified in the request header.<br>        &quot;&quot;&quot;<br>        tenant_id = self.request.headers.get(&#39;X-Tenant-ID&#39;)<br>        if not tenant_id:<br>            # Handle the case where no tenant ID is provided, possibly raise an exception<br>            raise ValueError(&quot;Tenant ID is required.&quot;)<br><br>        if self.request.user.is_staff:<br>            # Staff users can view items across all tenants, optionally filter by tenant<br>            queryset = Item.objects.all()<br>            if &#39;all_tenants&#39; not in self.request.query_params:<br>                queryset = queryset.filter(tenant_id=tenant_id)<br>        else:<br>            # Regular users can only view items within their tenant<br>            queryset = Item.objects.filter(tenant_id=tenant_id)<br><br>        # Further filter for public items if needed<br>        if &#39;public&#39; in self.request.query_params:<br>            queryset = queryset.filter(public=True)<br><br>        return queryset</pre><p>By customizing the get_queryset method as shown, you can maintain strict boundaries between tenant data, while providing the necessary flexibility to accommodate various user roles and filtering needs within your application. There are many more better ways of doing tenant scoping, this was just used as an example.</p><h4>Advanced Queryset Manipulations</h4><p>Imagine an e-commerce platform that needs to serve product information via an API. The requirements include filtering products by multiple criteria (such as category, tags, price range), sorting, and applying role-based access control to ensure that only authorized users can view certain products.</p><pre>from django.db.models import Q<br>from rest_framework import viewsets<br>from rest_framework.permissions import IsAuthenticated, IsAdminUser<br>from .models import Product<br>from .serializers import ProductSerializer<br><br>class ProductViewSet(viewsets.ModelViewSet):<br>    &quot;&quot;&quot;<br>    A ViewSet for viewing and editing product entries with complex filtering and access control.<br>    &quot;&quot;&quot;<br>    serializer_class = ProductSerializer<br><br>    def get_permissions(self):<br>        &quot;&quot;&quot;<br>        Assign permissions based on user role and action.<br>        &quot;&quot;&quot;<br>        if self.action in [&#39;list&#39;, &#39;retrieve&#39;]:<br>            permission_classes = [IsAuthenticated]<br>        else:<br>            permission_classes = [IsAdminUser]<br>        return [permission() for permission in permission_classes]<br><br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Dynamically filter products based on multiple criteria and enforce role-based restrictions.<br>        &quot;&quot;&quot;<br>        queryset = super().get_queryset()<br>        username = self.request.user.username<br><br>        # One should use something like django-filters ideally<br>        # for filtration purposes<br>        category = self.request.query_params.get(&#39;category&#39;)<br>        tags = self.request.query_params.getlist(&#39;tags&#39;)<br>        min_price = self.request.query_params.get(&#39;min_price&#39;)<br>        max_price = self.request.query_params.get(&#39;max_price&#39;)<br>        sort_by = self.request.query_params.get(&#39;sort&#39;, &#39;name&#39;)  # Default sorting by name<br><br>        # Basic role-based filtering<br>        if not self.request.user.is_staff:<br>            queryset = queryset.filter(is_public=True)<br><br>        # Dynamic filtering based on URL parameters<br>        if category:<br>            queryset = queryset.filter(category__name=category)<br>        if tags:<br>            queryset = queryset.filter(tags__name__in=tags).distinct()<br>        if min_price and max_price:<br>            queryset = queryset.filter(price__gte=min_price, price__lte=max_price)<br><br>        # Sort the queryset based on a parameter<br>        queryset = queryset.order_by(sort_by)<br><br>        return queryset</pre><p>This example really shows off how tweaking methods like get_queryset and get_permissions in DRF can turn you into ninja. These aren&#39;t just fancy tricks; they&#39;re essential tools for anyone looking to build APIs that don&#39;t just serve data but serve it smartly while coding as less as possible.</p><p>As commented before extracting query params, checkout <a href="https://django-filter.readthedocs.io/en/stable/">Django Filters.</a></p><h4><strong>By the way do you see a pattern?</strong></h4><p>In Django Rest Framework (DRF), when we define a method starting with get_, it essentially overrides a method from the superclass. This inheritance pattern allows us to customize the behavior of DRF components to better suit our application&#39;s needs.</p><p>Similarly, when working with viewsets in DRF, methods like get_queryset, get_serializer_class, and get_permissions are commonly overridden to tailor the behavior of the viewset according to specific requirements. These methods allow us to customize queryset retrieval, serializer selection, and permission checks, respectively.</p><h4>Dynamic Field Selection in Viewsets</h4><p>One of the challenges in designing performative APIs is managing the payload size, especially when dealing with large datasets or mobile clients where bandwidth and speed are concerns.</p><blockquote><a href="https://graphql.org/">GraphQL </a>fundamentally addresses the issue of dynamic field selection, among other concerns related to data fetching in web applications.</blockquote><p>DRF offers flexible mechanisms to customize responses, and one such technique is dynamic field selection. This approach allows clients to specify exactly which fields they want to receive in the response, thus minimizing the payload and improving the response times.</p><p>The example below demonstrates how to implement dynamic field selection by overriding the get_serializer_class method in a DRF viewset. This method modifies the serializer fields dynamically based on the &#39;fields&#39; parameter provided in the query string of the request.</p><pre>from rest_framework import viewsets<br>from rest_framework.serializers import ModelSerializer<br>from django.db.models import Field<br><br><br>class DynamicFieldsModelSerializer(ModelSerializer):<br>    def __init__(self, *args, **fields, **kwargs):<br>        # Don&#39;t pass the &#39;fields&#39; arg up to the superclass<br>        super().__init__(*args, **kwargs)<br><br>        if &#39;request&#39; in self.context:<br>            fields = self.context[&#39;request&#39;].query_params.get(&#39;fields&#39;)<br>            if fields:<br>                fields = fields.split(&#39;,&#39;)<br>                # Drop any fields that are not specified in the `fields` argument.<br>                allowed = set(fields)<br>                existing = set(self.fields)<br>                for field_name in existing - allowed:<br>                    self.fields.pop(field_name)<br><br>class UserViewSet(viewsets.ModelViewSet):<br>    queryset = User.objects.all()<br>    serializer_class = DynamicFieldsModelSerializer<br><br>    def get_serializer_context(self):<br>        &quot;&quot;&quot;Extend serializer context with request data.&quot;&quot;&quot;<br>        context = super().get_serializer_context()<br>        return context</pre><p>In the DynamicFieldsModelSerializer, the constructor (__init__) is modified to check for a &#39;fields&#39; parameter in the request. If present, the serializer adjusts its fields accordingly:</p><ul><li>Extract fields from request: The fields specified by the client are extracted from the query parameter.</li><li>Adjust serializer fields: It then compares these fields against the serializer’s existing fields. Fields not requested by the client are removed, ensuring that only the requested data is included in the serialized output.</li></ul><h4>Advanced Exception Handling in Django REST Framework</h4><p>Properly managing exceptions in your API isn’t just about catching errors; it’s about enhancing the reliability of your application and improving the user experience by providing clear and actionable error feedback. In Django REST Framework (DRF), customizing how your API handles exceptions allows you to tailor error responses to the needs of your client applications and ensure that any issues are adequately logged or reported. Overriding the handle_exception method in your views can provide granular control over these processes.</p><p>Consider an API that serves as a critical part of your service architecture, perhaps processing transactions or user data. In such cases, simply returning generic error messages isn’t sufficient. You need detailed insights into errors for debugging, while users require specific feedback that can guide their next actions. Customizing exception handling can address both these needs effectively.</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework.exceptions import APIException<br>import logging<br><br># Configure your logger<br>logger = logging.getLogger(__name__)<br><br>class CustomAPIView(APIView):<br>    def handle_exception(self, exc):<br>        &quot;&quot;&quot;<br>        Handle any exception that occurs, with special handling for APIExceptions.<br>        &quot;&quot;&quot;<br>        if isinstance(exc, APIException):<br>            # Log the error with detailed information for internal tracking<br>            logger.error(f&quot;API Exception occurred: {exc.detail}&quot;, exc_info=True)<br><br>            # Optionally, integrate with an external error monitoring service<br>            # monitor.send(exc)<br><br>        # Modify the API&#39;s error response to be more informative for the client<br>        response = super().handle_exception(exc)<br>        custom_response_data = {<br>            &#39;error&#39;: &#39;An unexpected error occurred&#39;,<br>            &#39;message&#39;: str(exc.detail) if isinstance(exc, APIException) else &#39;Internal server error&#39;,<br>            &#39;status_code&#39;: response.status_code<br>        }<br>        response.data = custom_response_data<br>        return response</pre><p><strong>Key components:</strong></p><ul><li>I<strong>ntegration with Monitoring Tools</strong>: While the example doesn’t directly implement it, there’s a placeholder comment suggesting integration with an external monitoring service like Sentry or New Relic. This can help in aggregating, notifying, and analyzing errors.</li><li><strong>User-Friendly Error Responses</strong>: The response structure is modified to include more user-friendly error messages, which can help clients understand what went wrong beyond just a status code.</li></ul><p><strong>Benefits of Custom Exception Handling:</strong></p><ul><li><strong>Better User Experience</strong>: Clear, descriptive error messages help users understand problems and reduce frustration.</li><li><strong>Compliance and Security</strong>: Ensuring that error messages do not expose sensitive information or system details, maintaining security and compliance.</li></ul><p>These all were but a few examples to demonstrate the extensibility and flexibility of Django &amp; DRF and as we’ve seen, Django and Django Rest Framework aren’t just stiff suits; they’re more like a Swiss Army knife for web developers — versatile and ready to be customized to fit the unique curves of your project.</p><p><strong>Now, I turn the keyboard over to you! Let me know in the comments:</strong></p><ul><li><em>What’s the most unusual or creative way you’ve customized Django or DRF?</em></li><li><em>Are there any topics or tutorials you’d like to see more of on blogs like this?</em></li><li><em>Any fun stories about your experiences with Django or coding in general?</em></li></ul><p>I’m all ears — well, all screens — and looking forward to your tales and requests. Happy coding, and remember, there’s no such thing as too many plugins… unless your app says otherwise!</p><p>You can check more about me at <a href="http://banerjeerishi.com/">banerjeerishi.com</a>, I am still working on it, but few things surely work, hopefully. <em>(P.S This was yet another shameless self promotion)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c5e6b6435c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/django-drf-flexibility-38c5e6b6435c">Django &amp; DRF Flexibility</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Lifecycle Hooks]]></title>
            <link>https://medium.com/django-unleashed/django-lifecycle-hooks-ed731e4c829a?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed731e4c829a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pip]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 06:37:52 GMT</pubDate>
            <atom:updated>2024-04-10T06:37:52.996Z</atom:updated>
            <content:encoded><![CDATA[<p>Django is a robust and versatile Python web framework used by developers worldwide to build all sorts of applications. Its all about making life easier! Except, of course, when it comes to managing model triggers with signals. That’s like trying to untangle headphones that have been in your pocket for more than five minutes — frustrating, time-consuming, and a test of patience.</p><p>I first encountered signals through <a href="https://www.youtube.com/c/dennisivy">Dennis Ivy’s YouTube channel</a>. He said its important and he uses it all the time, so I began integrating them across various projects, often complaining about my struggle with navigating Django’s extensive documentation.</p><p>Despite having worked with Django for two years, it was amusing how I managed to overlook signals entirely. It seems I never ventured deep enough into the documentation to unearth this feature, a testament to the vastness of Django’s capabilities waiting to be discovered.</p><h3>The Headache of Django Signals</h3><p>As it turns out, <strong>DjangoNauts</strong> rely on signals extensively to manage model triggers. This is fine and dandy for smaller projects. But as projects expanded into monstrosities, signals became a nightmare. Tracing signals through a large codebase felt like trying to find a specific grain of sand on a beach. It was messy, convoluted…. <strong>IT SUCKKEEEDDD!</strong> Some might call it a <strong><em>skill issue</em></strong> but still xD</p><h3>Signals Revision</h3><p>Django signals, much like the various tools in a developer’s toolbox, come into play at specific moments during the lifecycle of your models. Some of the signals that are most used are named <strong>‘pre_save’, ‘post_save’, ‘pre_delete’, ‘post_delete’, </strong>so on and so forth Each has its unique timing and purpose. Showing one example here since you know? We need to visit hooks :)</p><p>- <strong>post_save:</strong> Occurs right after the model’s <strong>`save()`</strong> method. Here is a simple example, after a new user signs up, you want to send a welcome email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAILeufyA47lEkJX46s-zQ.png" /></figure><p>This function is not a part of the model, it can be placed in the <strong>`models.py`</strong> file, but often as the models get large, it becomes really difficult to trace down where the hell are the trigger changes coming in from. Why not make the signals a part of the model itself?</p><p>By leveraging these signals, Django developers can perform auxiliary actions related to model events, and ensure that they set up a trap for themselves and their colleagues.</p><h3>Simplifying Model Events</h3><p>Enter Django lifecycle hooks, the hero I didn’t know that I needed? These hooks are like having a Swiss Army knife. They follow the mantra of fat models and thin views, meaning they keep the logic within the model (where it’s supposed to be) and the views as lean as a runway model.</p><h3>The Revised and Enlightened Approach</h3><p>Instead of mucking about with signals, we integrate lifecycle hooks directly into our model. It’s cleaner. Imagine we have an <strong>Article</strong> model. It’s a simple model but one key difference is, it extends from <strong>LifecycleModel </strong>instead of <strong>models.Model from django.db</strong>. When the author publishes it, a simple email trigger should be there Here’s how we do it using lifecycle hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mogs3gNAiBkFmmtKiqUvRQ.png" /></figure><p>In this comprehensive example, each hook serves a distinct purpose:</p><ul><li>notify_author_publication_status <strong>(AFTER_SAVE)</strong>: This combined hook notifies the author when their article is published or unpublished.</li><li>log_content_change <strong>(BEFORE_UPDATE)</strong>: Before the content of an existing article is updated, this hook logs a message. This could be expanded to include more complex logic, such as versioning article content or notifying editors of pending changes.</li><li>cleanup_related_resources <strong>(AFTER_DELETE)</strong>: After an article is deleted, this hook could be used to clean up any related resources that should no longer exist. For example, you might delete associated images, comments, or references in other parts of your application.</li></ul><h3>Watching ForeignKey Changes</h3><p>This is rather interesting, when an assignment to a foreign key changes, for example the organisation the user works for changes, we can simply put it here like this. Also a trigger for the layoff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLQnLCd15DXrAqxUR-euFg.png" /></figure><h3>Why Choose Django Lifecycle Hooks?</h3><p>Choosing Django lifecycle hooks over signals is like choosing a well-trained Labrador over a wild, untrained hyena to be your pet. It’s just smarter. Here’s why:</p><p>- <strong>Clarity and Cohesion</strong>: Keeps your logic tidy and in one place.<br>- <strong>Reduced Boilerplate</strong>: Say goodbye to the ritual of connecting signals to receivers. Less code, less stress.<br>-<strong> Performance</strong>: Sometimes, they’re just faster.</p><p>As it says in the official documentation</p><blockquote><strong>‘However, my team often finds that Signals introduce unnecessary indirection and are at odds with Django’s “fat models” approach.’ </strong>— author of Django Lifecycle Hooks</blockquote><p>They are the more civilised, sophisticated way to handle model events. It’s about keeping your codebase lean and your sanity intact.</p><p>If you think Django lifecycle hook can be a great tool in your toolbox check out more about it <a href="https://rsinger86.github.io/django-lifecycle/">here</a>.</p><p>You can check more about me at <a href="http://banerjeerishi.com/">banerjeerishi.com</a>, I am still working on it, but few things surely work, hopefully. <em>(P.S This was a shameless self promotion)</em></p><p>And remember, in the grand scheme of coding, using lifecycle hooks is like bringing a gun to a knife fight — a surefire way to ensure victory with minimal fuss 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed731e4c829a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/django-lifecycle-hooks-ed731e4c829a">Django Lifecycle Hooks</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grabbing the Dell Internship]]></title>
            <link>https://medium.com/@banerjeerishi/grabbing-the-dell-internship-e6a64b0fe537?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a64b0fe537</guid>
            <category><![CDATA[software-engineering-job]]></category>
            <category><![CDATA[internships]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 17:29:34 GMT</pubDate>
            <atom:updated>2020-09-14T17:29:34.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Here is a quick summarization of everything that you need to crack the Dell Internship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*36UQksMStgBfc0JB.jpg" /><figcaption>Stock Photo xD</figcaption></figure><h3>Overview</h3><p>Dell EMC visits the campus for intern hire in the month of October every year. They select students from the third year for the role of Software Engineering Intern. Done? Cool.</p><h3>The Process</h3><p>Dell follows a rather unconventional method of hiring. Unlike many companies, like Google, Amazon, and other tech titans, Dell uses a more <strong>comprehensive </strong>method to filter out talent. The process is more <strong>inclusive </strong>and since it does not depend on something like Competitive Coding, normal web and mobile app developers get a chance to showcase their skillset and get an amazing addition to their resume. Not just students of <strong>SCIT</strong> but even students of <strong>ECE</strong> are allowed to sit for the entire interview process.</p><h3>Requirements</h3><p><strong>70%+ in 10th, 12th</strong>, and a score above <strong>7 CGPA</strong> in college. That’s it.</p><h3>First Round</h3><p>The first round is called the MCQ round where we have around <strong>45 questions</strong>, and <strong>55 minutes</strong> or so to solve them. What are the topics? Data Structures and Algorithms, OS, RDBMS, STLD, Aptitude, and yeah this may hurt, but COA (Computer Organization &amp; Architecture). COA has like 1–2 questions, so I guess you’ll sail through.</p><p>The MCQ round happens online and within 3–4 hours of you giving the test, you will get to know whether you are among those <strong>80 people</strong> who are going to the 2nd round or not. After the first round, we have the team-building phase and the problem statement allocation. You build a great team and you select a simple problem statement. I repeat, a simple problem statement. Dell provides the TnP with <strong>5–6 problem statements</strong>, and then you have to select what your team wants to take up. The usual problem statement that gets in here are:</p><ol><li>Product Recommendation <strong>(Always repeats)</strong></li><li>Service Recommendation<strong> (Always repeats)</strong></li><li>Supply Chain Management</li><li>Drag &amp; Drop UI builder</li><li>Chatbot (yukk! who makes a chatbot)</li></ol><p>One problem statement can be used by a maximum of 5 teams. So, fastest fingers first I guess. On a personal note, the first two problem statements are the best because they are easy.</p><h3>Second Round</h3><p>Around 2 weeks or so after the first round, we have the first day of the Hackathon. If you are a student in MUJ and if you’ve taken part in Hackathons, this is gonna be a breeze for you! It starts at around 8 AM as far as I can remember. This round goes on until 4 PM.</p><p>The catch in this round is that your team will have a mentor assigned. The mentor is usually someone from Dell. He/she visits your team thrice. Usually thrice. They come to see what you are doing and make notes. I have absolutely no idea what they note down, but yeah. You get it. Scores or something. It doesn&#39;t matter. You need to make sure the mentor feels that your team is up to something. You have to talk about <strong>innovation, change, and the magnitude</strong> of your implementation of the problem statement. They will suggest improvements, and if you really believe the suggestions mean something, you can make appropriate adjustments.</p><h3>Third Round</h3><p>Ah, the most important round. This round takes place the next day. Again, it starts at 8 AM and goes on until 2 PM. All the teams are given time slots in which they need to come and present their project idea and impress the panel. The panel consists of 5–7 people from Dell. They are usually Principal Software Engineers, Vice Presidents, and HR’s. They are gonna critique the presentation and the project.</p><p><strong>Points to remember:</strong></p><ol><li>Make sure your presentation is crisp. Apply the 10/20/30 rule. 10 slides, 20 minutes, 30 Font Size. Thank me later xD</li><li>Make sure the code runs and fulfills the project requirement.</li><li>You should let your teammate speak. Do not cross him.<strong> If he/she makes a mistake or says something wrong, it is your biggest responsibility to not to correct him.</strong> They want to see teamwork. They want to see allies. If they have the slightest indication that you guys are unsure about yourselves, you are out.</li><li>Answer the questions asked to your team confidently. Assign questions beforehand. So that you know who is gonna answer which topic. Like Amish answers the part which involves the website. Rahul answers the mobile app part. Samarth handles the ML/AI.</li><li>Be respectful. If you think you know more than someone sitting in the panel, please show yourself the door and leave. Ego is a sin.</li></ol><p>After the presentation, you guys are given a time slot in which you are supposed to do only one thing. <strong>Panic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*hDlI1kt0LIrmbefE.jpg" /><figcaption>Panicking is important.</figcaption></figure><p>Get your resume ready for the final fourth round just in case you get selected.</p><h3>Final Round</h3><p>Out of the 80 students who started, 40 students are selected for the HR round. This round is perhaps the easiest if you are not a socially awkward human being. This round is gonna be long and you are gonna be hell anxious. Well, everyone has to go through this once in their life.</p><p><strong>Points to remember:</strong></p><ol><li>Be humble, be respectful. Do not forget to greet the HR when you enter the room. Its gonna be just the both of you.</li><li>Be calm and be comfortable. There are no technical questions.</li></ol><p><strong>Usual Questions:</strong></p><ol><li>Tell me something about yourself.</li><li>Where are you from? Why join MUJ? Do you like it here?</li><li>Why do you like Software Engineering?</li><li>Why do you like Dell? Why do you wanna join Dell?</li><li>Any plans for Higher Studies? <strong>(Always say no)</strong></li><li>Willing to relocate? <strong>(Always say yes)</strong></li><li>Location Preference? <strong>(No preference, anything works)</strong></li></ol><p>Once the HR round is over you are given some more time to panic. 25 student names are announced just like in the Oscars and you go grab that offer letter.</p><p><strong>Skills that Help</strong></p><p>Mobile Application or Web Application Development is a must. You must know how to make SQL queries to a database and use frontend engineering to render the required data in a specific form. Normal HTML/CSS literally won&#39;t cut it. <strong>Basics of Data Science and Machine Learning is a plus.</strong> You need to implement basic models. Knowledge of model integration into a software platform is also necessary.</p><p><strong>Backend Technologies</strong> that help: Django, Flask, Node.js, Spring. Since models are mostly written in python, ML integration happen way quicker if you are using Django or Flask. Avoid using PHP. Just avoid it.</p><p><strong>Frontend Technologies</strong> that help: React.js, jQuery, Ajax, Flutter. We used jQuery and Ajax because we were lazy, but you can go ahead and use a good and concrete frontend framework.</p><p>You can find my source code for both <a href="https://github.com/rshrc/dell-hackathon">Product Recommendation</a> and <a href="https://github.com/rshrc/service-recommendation">Service Recommendation</a>. Both of them were codes for winning teams and I’m sure you’ll get an idea about how you should go about coding the solutions. If you are able to deploy the application live, its a plus.</p><p>I hope this blog helps clear all the doubts. All the best if you are sitting for Dell! It is an amazing company and I am sure you will learn a lot if you are able to grab the internship ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a64b0fe537" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Curious Case of Dubios Clients]]></title>
            <link>https://medium.com/@banerjeerishi/the-curious-case-of-dubios-clients-9e56cefc5967?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e56cefc5967</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[wealth]]></category>
            <category><![CDATA[life-advice]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[comedy]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 10:17:29 GMT</pubDate>
            <atom:updated>2020-07-10T11:09:46.999Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Curious Case of Dubious Clients</h3><p>It has been a few years of me being in the field of making software applications for startups, companies, and normal people to enable them to do something extremely ridiculous or something extravagant. Maybe. I am not sure what kind of impact all of this has had on the life of people and how any of these has effected the space-time continuum. But, what we can know and analyze are the types of people, from the hospitable venture capitalists to the demented blabbering buffoons. We can effectively rationalize a conventional method that can be used time and again, to check for red flags and traps.</p><p>It all starts with that one phone call or that one awkward message on some hiring platform. Maybe they drop you a nice documented email about how they want to set out into a new adventure of highs and lows, mostly lows, and in the meanwhile change the world. A small rip-off of an existing application and make the world a better place to live in. You are the scapegoat in most cases but it might be a good deal if you think deep enough. You, need to Think!</p><p>In early 2018, I landed on my first ever client. <strong>Dumb guy, speaks loudly, self-proclaimed visionary and an outright savior of the human race.</strong> I was a poor guy, what did I know that I was looking at some low key “pocket money”. He offered me ₹5000 for making a blogging website. It struck me how groundbreaking this idea was. I did not know how I was gonna manage it. He met me somewhere in an office, and spoke to me softly, <em>“Rishi, this project is gonna change everything!”</em> My broke and greedy instincts kicked in, and I said, <em>“Thank you for letting me help you, it will be a great experience for both of us”</em>. And boy, it was. For him!</p><p>I made the website in a day using some fancy code I found on GitHub. I only knew Django back then and was able to stitch together some half-dead logic with some barely working piece of code and delivered it to him. He was sort of happy. He said, <em>“This, could have looked better”</em>, to which I firmly replied, <em>“You did not pay me for the designs now, did you sir?”</em>. He knew I was broke and pretty vulnerable. He asked me to make some changes. Some more changes and then around 100 more changes, which almost changed the entire application. I was sitting there in my hostel room thinking, <em>“Hmm, maybe Dad was right!”</em>. This entire experience led me to effectively label these kinds of clients as the <strong>“The Tyrannical Clowns”</strong></p><p>Having worked with a few more <strong>Tyrannical Clowns,</strong> I sunk into deep thought and realized, a small amount of money won&#39;t cut it. Though these people pay the money, when you get it, it seems of no use, because by the time you finished the project, life had no meaning.</p><p>A few months later, in the summer of 2018, I got a promising call from a well-established company. Let’s name the guy, Danveer Singh. He had a good offer of paying a little more than ₹5000. Now, this guy seemed professional. He made me sign contracts and agreements. Little did I know I was signing my death warrant with the Devil whom I would later relabel as the <strong>“Communal Capitalist”</strong></p><p>What did he tell me? He said, <em>“We have a project, its almost over. Our current developer has joined another company. You can come and finish it.”</em> It was a no brainer for me back then. I told myself, how hard could it be really? Most of the complex things are written, I just had to go fill in the missing blocks and voila, money in the bank.</p><p>In the next 2 years, I had an on and off relationship with this guy. And believe me, I felt as if I had sold my soul to him. He behaved more or less like that anxious girlfriend who would call you every hour to check up on you, but this guy would check up on the project and ask for a progress report every day. When I saw the project there were some text files with things written down there about how the project was supposed to be completed. A README.md file. I was left wondering, where was it almost over? His words ring like a daily reminder, “It&#39;s a 2-minute job really!”</p><p>He lived in a different dimension of time.</p><p>A 20-year-old dickwad strolled into my DMs on Instagram and asked me if I could set up a meeting with him to discuss his passion and goals. Sure, I was a people person and I ended up scheduling a meeting. The conversation was about a mobile application which was a rip-off of LinkedIn. I was not surprised since most Indian startups like to go with the “But it’s a niche market” attitude. I was willing to help him but then a few days later he told me there was supposed to be an option in the app to buy/sell stuff, just like Amazon. There should also be a feature of adding 24-hour stories just like Instagram. He named almost all successful mobile apps and wanted a part of them in his brainchild, aptly named “Jelda”. Yeah, even I don’t know the meaning. All of this was doable but at a good cost. I can be a no-nonsense guy sometimes and told him how this was gonna cost him money. He proudly said, “You’ll get equity”. Now, this company had a valuation of ₹0. And with a clear mathematical and logical assumption, this company was gonna have ₹0 market capital even after it’s first IPO. It was a big red flag for me and I promptly decided to cancel the contract. These young people come along and tell you stuff, but you should know these are the people I label as <strong>“Senile Idiots”.</strong></p><p>Next, I got a call from a guy in Paris, and he started to roll out his <em>“How I am gonna change the world”</em> monologue. I was listening. Intently. He seemed like a whale who was willing to put me through college and also pay for my movie tickets. It was a 5-hour long meeting. Perhaps one of the longest I’ve ever had. His original plan was to pay me some $1000 dollars for the entire project. He was not aware of the fact that I picked up his phone after watching the movie, <strong>“Wolf of The Wall Street”</strong>. I had seen millions and a red Ferrari. I was not gonna sell myself for that minuscule amount. I was a man of honor. So I settled for $800 dollars instead, but, for an 8-month long period and he had to pay me that amount every month. I saw him as a blessing. It was an easy decision or me, to label these kind of clients as the <strong>“Humble Fools”</strong>.</p><p>Things sailed through but later I happened to form a team. More manpower, lesser load, happier times. We were contacted by a guy from Texas and he offered us a contract of 38+ mobile apps. We were all in. It was a jackpot. Good money and all the apps were more or less the same. We were burning money at an exponential rate by just partying. You might ask me, so what was so special about this guy? Well, he used to drop us 50+ emails a day. 20+ messages on all the platforms. He was the embodiment of “Clueless Middleware”. The projects were not his, he got them from somewhere and outsourced 3 nitwits from Asia to help him earn some big bucks. Holding on was hard, but this made my team more tolerant and resilient.</p><p>It is not always when you get a call from some IIT. We all know how the pandemic has actually lifted the human species one step up. More innovative software to make life easier and comfortable. <strong>It is the responsibility of some people to join the bandwagon and come up with solutions for problems that don&#39;t exist.</strong> There were 3 IITians on the call and I was negotiating a deal with them. A software platform to automate the process of scheduling and attending supermarkets. Nice, seems like a snack. After all the long and deep thought out conversation about the business model, I put forward the only thing I was interested in, <em>“How much are you gonna pay me?”</em>. They said they were willing to pay me a sum total of ₹5000, if the product is delivered before time then maybe ₹7000. There was no equity in it. Again, this was not worth it and I said, <em>“I was not looking for Pocket Money! Sir!”. </em>My team labeled those guys as the <strong>“Stoned IITians”</strong></p><p>We landed on many more clients and all of these seemed to fit these few descriptions. In this quarantine, I along with my team negotiated with more than 100 clients. Closing a good deal with only around 5 of them. It is important to understand that time is a valuable asset, work for the projects you truly think is gonna be worth your time. Most people are dubious and more often than not, they are confident about their plan. They will offer you an equity share in their company and it is extremely important to understand that your value depends on the success of the project. Unless you truly believe in the project’s impact on a very deep financial level, say No!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q2K0My0TO9A41r4L" /><figcaption>Huge money comes with a Smaug!</figcaption></figure><p>Freelancing is a good occupation. Helping other people for a small fee, but your idea of sovereignty should always come first.</p><p><strong><em>Disclaimer:</em></strong><em> I have tried to recreate events, locales, and conversations from my memories of them. In order to maintain their anonymity in some instances, I have changed the names of individuals and places, I may have changed some identifying characteristics and details such as physical properties, occupations and places of residence.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e56cefc5967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Django for Machine Learning like a Legend!]]></title>
            <link>https://medium.com/analytics-vidhya/using-django-for-machine-learning-like-a-legend-23d0633a0732?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/23d0633a0732</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[legend]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Sat, 16 May 2020 06:09:42 GMT</pubDate>
            <atom:updated>2020-05-19T16:47:14.276Z</atom:updated>
            <content:encoded><![CDATA[<p>I often find myself in the middle of a situation where people are pondering over one topic. And the topic is quite big.</p><p><em>“We have made this ML model, how do we integrate it with our mobile app?”.</em></p><p>I answer with a rather overpowering voice, <em>“You use REST API’s you doofy nut.”</em></p><p>But is it that simple? NO. I never found any good tutorial to integrate ML with any web server. Figuring it out was a great ordeal for me. I’ve looped through so many possibilities. Using a minimized <strong>“trained model”</strong> embedded in the device for use. But that comes at a cost. Supporting so many platforms. Doing the same for an iOS device is exponentially difficult.</p><h3>What is the workaround?</h3><p>The simplest possible way is to manually hardcode your views with your model parameters. Doing so will enable you to run your model script on user interaction with your website. But it&#39;s kind of like 1995. Super slow and boring.</p><p>What we are looking here for is the legendary feel. Feel like a developer right out of Google. Duh!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctRMfb38pEMBx-Q7XZAQkQ.jpeg" /></figure><h3>Setting up the ML code</h3><p>Lets quickly set up a sample machine learning code that trains on a given dataset and stores the model for later use.</p><p>We are going to use the evergreen <strong>Salary dataset</strong> for ease of understanding by our <strong>“younger”</strong> audience.</p><p>You can download the dataset from <a href="https://github.com/rshrc/django-ml/blob/master/ml/data.csv"><strong>here</strong></a>.</p><p>Lets just quickly get through the ML code since its not our topic of discussion today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6vTzNfn0fSSvfCsMChJFA.png" /><figcaption>Understood?</figcaption></figure><p>The code here is a basic example of splitting the dataset data.csv into training and testing sets, training a simple <strong>Linear Regression</strong> model, and then storing the trained model inside a file named model.sav using pickle to enable model persistency. We use model persistence so that we don&#39;t have to train the model again and again. <strong>TRAIN once, USE anytime</strong>.</p><h3>The Interesting Part</h3><p>Now comes the Django part. We are gonna set up a basic Django project with two apps inside it. <strong>‘predict’</strong> and <strong>‘server’</strong>. The predict app holds the training code and a <strong>loader class</strong> which enables us to do the machine learning stuff. The server app has the <strong>API view</strong> which takes in a POST request and gives you the output back.</p><pre>django-admin startproject dj_ml_legend &amp;&amp; cd dj_ml_legend<br>python manage.py startapp predict<br>python manage.py startapp server</pre><p>Cool, you should now see two virgin apps in your directory.</p><h3>Predict App</h3><p>Let&#39;s work with the predict app first. Copy and paste your <strong><em>train.py</em></strong> file and the <strong><em>data.csv</em></strong> file inside your <strong><em>predict/</em></strong> directory. Then write the following Loader class inside your <strong><em>predict/views.py</em></strong> file. This file will enable you to <strong>load and use</strong> your saved model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HboEI-RTsu3AZVXuZhs60Q.png" /><figcaption>Ah, the Loader</figcaption></figure><h3>Server App</h3><p>Now, let&#39;s move towards the server app. We are gonna write a simple API view using the amazing <strong>django rest framework</strong>. The API view calls the Loader class that we just wrote and uses its output as a response to the POST request that is made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V16hnoTPaunIdKSMmeX3LQ.png" /><figcaption>we use BASE_DIR to track the <strong>model.sav</strong> file</figcaption></figure><p>Great, now we have an API view which, all 20 fingers crossed should work perfectly. Wait, we still have the urls to manage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuE3WrqqzVmYCbt2hRC4bg.png" /><figcaption>the API “Endpoint”</figcaption></figure><p>This endpoint will give us the salary for a specific age.</p><h3>No more code?</h3><p>Nope, no more code. This is the beauty of django. Made for Machine Learning engineers with deadlines xD. LOL</p><p>So let’s put our code to test by making a simple <strong>POST </strong>request in python. Fire up your <strong>python console</strong>. Before that python manage.py runserver on your root directory.</p><pre>&gt;&gt;&gt; import requests as r<br>&gt;&gt;&gt; v = r.post(&#39;<a href="http://localhost:8000/server/api/salary/&#39;"><strong>http://localhost:8000/server/api/salary/</strong>&#39;</a>, data=<strong>{&#39;exp&#39;: 5.6}</strong>)</pre><p>Done, now the post request should have worked. Let&#39;s see the output</p><pre>&gt;&gt;&gt; v.text<br>&#39;79153.46992551646&#39;</pre><p><strong>Fast, dynamic, and legendary.</strong></p><p>Now this API can be used anywhere. On your websites, your apps, everything.</p><p>To access the API from a different device, you might consider using <a href="https://ngrok.com/"><strong>ngrock</strong></a>, but when going into production, I highly recommend <strong>pythonanywhere</strong> or <strong>Heroku</strong>.</p><p>So I guess that was it, now you can use Django for Machine Learning like a Legend. You can find the source code in this <a href="https://github.com/rshrc/django-ml"><strong>repository</strong></a>.</p><p>Stay tuned for more <em>“Using X like a Legend”</em></p><p><em>Bye!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23d0633a0732" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-django-for-machine-learning-like-a-legend-23d0633a0732">Using Django for Machine Learning like a Legend!</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Django REST Auth Guide ]]></title>
            <link>https://medium.com/@banerjeerishi/the-django-rest-auth-guide-42fa1622e788?source=rss-757715c5ee6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/42fa1622e788</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Rishi Banerjee]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 00:38:09 GMT</pubDate>
            <atom:updated>2020-01-01T00:38:09.465Z</atom:updated>
            <content:encoded><![CDATA[<p>This is going to be a small blog on how to set up ‘users’ and authenticate them using REST API’s. The type of API’s I always keep talking about.</p><p>We all know Django is the <em>“batteries included”</em> web framework for perfectionists with deadlines. The problem is we are a bunch of super rookies who struggle with rendering a normal HTML page, let alone properly loading the static files in the first go.</p><p>It is <em>“easy”</em> to setup‘<strong>login/logout’</strong>, <strong>‘registration’ </strong>in django . We simply use the <strong>django.contrib.auth</strong> classes to reduce our work. But again we run into a lot of issues.</p><p><em>Too many double quotes?</em></p><p>Leaving that aside for another blog lets focus on the title of the blog.</p><p>Well I am a mobile app developer, and I need to authenticate users by using REST API’s. How do I do that?</p><h3><strong>Setting up our Project </strong>🛠️</h3><p>Let’s create a simple django project.</p><p>django-admin startproject coolproject</p><p>Dang! That wasn’t so hard. Now we navigate inside the project like obviously, and create a <strong>user</strong> app. We are gonna have some custom properties and the views are gonna be using <a href="https://www.django-rest-framework.org/"><strong>django-rest-framework</strong> </a>to answer API calls.</p><p>python manage.py startapp user</p><p>Cool. So now we have a app. Lets fill in the models.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQXugsn3zPdRY2DJ0KC2kA.png" /><figcaption>Defining a CustomUser model (Just in case)</figcaption></figure><p>It is always customary to define a custom user model in django so that when the time comes we have the option to reconfigure the models according to our needs.</p><p>For django to detect and actually consider this model when migrating the database, add the following line in your settings.py file.</p><p>AUTH_USER_MODEL = &#39;user.CustomUser&#39;</p><p>And also add the user app in the <strong>INSTALLED_APPS[…]</strong></p><h3><strong>Welcome Djoser </strong>🥳</h3><p>So now we have this third party package which allows us to create and authenticate users using rest apis. Really cool project, you should totally star it on <a href="https://github.com/sunscrapers/djoser">GitHub</a>.</p><p>We don’t need to write our custom <strong><em>CreateAPIViews</em></strong> for this whole authentication mayhem.</p><p>pip install djoser</p><p>Once we have that, we need to install rest_framework using pip install django-rest-framework</p><p>Bam! Lets add these to the <strong>INSTALLED_APPS[…]</strong></p><p>Now, simply add this url path to your main urls.py file.</p><p>path(&#39;<strong>auth/</strong>&#39;, include(&#39;<strong>djoser.urls</strong>&#39;))</p><p>Great~ now we have our url endpoints available for authentication. But wait, we need tokens during logging in. Things are as simple as they seem. We just need to add a couple of lines here and there.</p><p>First and foremost, the <strong>settings.py</strong></p><pre>REST_FRAMEWORK = {</pre><pre>      &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [</pre><pre>      <strong>&#39;rest_framework.authentication.TokenAuthentication&#39;,</strong></pre><pre>      ],<br>}</pre><p>Add these lines and you are, not yet good to go. Hold on, one last thing. We need to add a specific app to the INSTALLED_APPS which is <strong>‘rest_framework.authtoken’ </strong>and done. We have successfully setup a authentication workflow based on Rest API’s.</p><h3>Let’s test it ✈️</h3><p>Make migrations and then runserver.</p><pre>curl -X POST <strong>http://localhost:8000/auth/users/</strong> --data &#39;email=&amp;username=user1&amp;password=StrongPass&#39;</pre><p>I am basically copying these from the official docs haha xD. <strong>Sneak 100</strong>.</p><pre>{&quot;email&quot;: &quot;&quot;, &quot;username&quot;: &quot;user1&quot;, &quot;id&quot;:1}</pre><p>Great, the user is now created in the database.</p><p>So this part was the registration of the user. Now comes the login using a authentication token.</p><pre>curl -X POST <strong>http://localhost:8000/auth/token/login/</strong> --data <strong>&#39;username=user1&amp;password=StrongPass&#39;</strong></pre><p>Now this curl request comes back with a token.</p><pre>{&quot;auth_token&quot;: <strong>&quot;b704c9fc3655635646356ac295asda9f352ea1139&quot;</strong>}</pre><p>Great, now we use this auth token to get the user model.</p><pre>curl -LX GET http://localhost:8000/auth/users/me/ -H <strong>&#39;Authorization: Token b704c9fc3655635646356ac295asda9f352ea1139&#39;</strong></pre><p>Now this will definitely come back with this response.</p><pre>{&quot;email&quot;: &quot;&quot;, &quot;username&quot;: &quot;user1&quot;, &quot;id&quot;: 1}</pre><p>Voila! Done.</p><p><strong>Batteries Included. Duh! </strong>🔋</p><p>There is something I want to add as a footnote in this blog. If you are deploying your django app in <strong>AWS</strong>, specifically an <strong>EC2 machine</strong> using <strong>Apache</strong>, remember that it does not accept authorization tokens in the header. We have to switch that on manually. <strong>SWITCH ON</strong>. Damn.</p><p>Navigate to this file</p><pre>cd /etc/apache2/sites-available/<strong>000-default.config</strong></pre><p>and add this exact same line</p><pre><strong>WSGIAuthorization On</strong></pre><p>Great. Will be discussing how to create custom user profiles and use them with a sleek mobile app made using <a href="https://flutter.dev/"><strong>Flutter</strong></a>.</p><p><em>Bye!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42fa1622e788" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>