<?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 OnlyGod Ovbije on Medium]]></title>
        <description><![CDATA[Stories by OnlyGod Ovbije on Medium]]></description>
        <link>https://medium.com/@onlygod?source=rss-d251dffada9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OEVZH3-Q5OjR4JTuUkyd5g@2x.jpeg</url>
            <title>Stories by OnlyGod Ovbije on Medium</title>
            <link>https://medium.com/@onlygod?source=rss-d251dffada9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 16 May 2026 22:52:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onlygod/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[Async Views in Django DRF — Setup, Benefits, Bottlenecks, and Use Cases]]></title>
            <link>https://onlygod.medium.com/async-views-in-django-drf-setup-benefits-bottlenecks-and-use-cases-0747855c13a6?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0747855c13a6</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 13:51:53 GMT</pubDate>
            <atom:updated>2025-06-14T13:51:53.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Async Views in Django DRF — Setup, Benefits, Bottlenecks, and Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8_dJ_9LAhOmFnUe5nuRuQ.jpeg" /><figcaption>Made by Pexels</figcaption></figure><p>As web applications scale, handling I/O-bound tasks efficiently becomes critical. Django has historically been synchronous, but recent versions support async views — including with Django REST Framework. Let’s break down how to use it, why it matters, and where it fits (and doesn’t).</p><h3>🔧 How to Set It Up</h3><p>Since Django 3.1, you can write async views directly. DRF (as of v3.12+) also supports async-compatible views.</p><h3>1.Async APIView Example</h3><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br><br>class AsyncHelloView(APIView):<br>    async def get(self, request):<br>        return Response({&quot;message&quot;: &quot;Hello, async world!&quot;})</pre><h3>2.Using async in function-based views</h3><pre>from rest_framework.decorators import api_view<br>from rest_framework.response import Response<br><br>@api_view([&#39;GET&#39;])<br>async def async_hello(request):<br>    return Response({&quot;message&quot;: &quot;Hi from async FBV&quot;})</pre><h3>3.Run an async-compatible server</h3><p>To truly benefit from async, use <strong>ASGI</strong> servers like:</p><ul><li>uvicorn</li><li>daphne</li></ul><p>In asgi.py, make sure you have:</p><pre>from django.core.asgi import get_asgi_application<br>application = get_asgi_application()</pre><p>Then run:</p><pre>uvicorn your_project.asgi:application</pre><h3>⚡ Why Use Async in DRF?</h3><h4><strong>1 . Handle many requests efficiently</strong></h4><ul><li>Async allows the server to handle other requests while waiting for external I/O (e.g., DB, external APIs).</li></ul><h4><strong>2. Improved performance on I/O-heavy operations</strong></h4><p>Useful when calling:</p><ul><li><em>Third-party APIs</em></li><li><em>External services like Redis</em></li><li><em>File systems or cloud storage</em></li></ul><p><strong>3. Better concurrency without threads</strong></p><ul><li>Unlike threads, async uses a single-threaded event loop — reducing overhead.</li></ul><h3>🧱 Bottlenecks and Gotchas</h3><h4><strong>1. Django ORM is not async</strong></h4><ul><li>This is the biggest blocker. If you call:</li></ul><pre>await MyModel.objects.all()</pre><p>It will raise an error. You must use sync wrappers:</p><pre>from asgiref.sync import sync_to_async<br>queryset = await sync_to_async(MyModel.objects.all)()</pre><h4><strong>2. Mixing sync and async wrongly leads to problems</strong></h4><ul><li>Use sync_to_async carefully. Too many sync wrappers = performance hit.</li></ul><h4><strong>3. Third-party packages</strong></h4><ul><li>Not all are async-compatible. You must test your stack.</li></ul><h4><strong>4. Testing async views</strong></h4><ul><li>Django’s test client is sync by default. For proper async tests, use tools like httpx or pytest-asyncio.</li></ul><h3>🔥 Relatable Use Cases</h3><h3>✅ Good Use Cases</h3><ul><li>Calling <strong>external APIs</strong> (e.g., weather, payments)</li><li><strong>Fetching data from multiple services</strong> concurrently</li><li>Waiting on <strong>cloud storage or Redis/MongoDB</strong> (if async-enabled)</li><li><strong>Webhook endpoints</strong> with minimal DB hits</li></ul><h3>❌ Poor Use Cases</h3><ul><li>Heavy <strong>ORM operations</strong></li><li>Complex <strong>database transactions</strong></li><li>Views that just CRUD directly with Django ORM (better stay sync)</li></ul><h3>Final Thoughts</h3><p>Using async in DRF is a <strong>powerful tool</strong> when your app is I/O-bound — not CPU-bound or DB-heavy. Use it <strong>selectively</strong> in views that wait on external services, and be mindful of Django’s sync internals.</p><p><em>Start small. Test performance. Use async where it makes sense.</em></p><p><strong><em>References</em></strong></p><p><strong><em>Django 3.1 release notes (async view support)</em></strong><em><br> </em><a href="https://docs.djangoproject.com/en/3.1/releases/3.1/"><em>https://docs.djangoproject.com/en/3.1/releases/3.1/</em></a></p><p><strong><em>Testing async views in Django</em></strong><em><br> </em><a href="https://testdriven.io/blog/django-async-views/"><em>https://testdriven.io/blog/django-async-views/</em></a></p><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 Github <a href="https://github.com/Onlynfk">https://github.com/Onlynfk</a>/<br><a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><h3>Want to Work with me?</h3><p>If you’re looking for a skilled developer to collaborate with, you can view my portfolio <a href="https://onlygodovbijecodes.web.app/">here</a>. Let’s bring your ideas to life together</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0747855c13a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Generators: The Magic Behind Efficient Iteration ]]></title>
            <link>https://medium.com/codex/python-generators-the-magic-behind-efficient-iteration-e3f47b5c952d?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f47b5c952d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iteration]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 12:20:24 GMT</pubDate>
            <atom:updated>2025-02-06T12:20:24.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bd6CQ11Z8MNnqZEe" /><figcaption>ChatGPT(AI)</figcaption></figure><p>Ever cooked a meal in a <strong>slow cooker</strong>? You don’t prepare everything at once — you add ingredients <strong>one by one</strong>, let them cook <strong>step by step</strong>, and serve as needed. That’s exactly how <strong>Python generators</strong> work! Instead of storing everything in memory at once, they <strong>yield one item at a time</strong>, saving space and improving performance.</p><p>Let’s dive into this <strong>game-changing Python feature</strong> that every developer should know! 💡</p><h3>🍲 Scenario: The Buffet vs. The Waiter Approach</h3><p>Imagine you’re at an <strong>all-you-can-eat buffet</strong>. The restaurant brings out <strong>every dish</strong> at once, filling up the table (and your plate) with everything available. Sounds great, right? <strong>Not really</strong> — what if you can’t finish everything? <strong>Wasted memory!</strong> 😵</p><p>Now, compare that to a <strong>waiter service</strong>. You order <strong>one dish at a time</strong> and only get what you can eat. <strong>No wasted space</strong>, no overloaded table — just what you need, when you need it.</p><p>This is exactly how <strong>generators</strong> differ from <strong>lists</strong> in Python!</p><ul><li>🍽️ <strong>Buffet (Lists):</strong> Stores everything in memory at once.</li><li>👨‍🍳 <strong>Waiter Service (Generators):</strong> Provides items one by one <strong>on demand</strong>.</li></ul><h3>🛠️ How Do Generators Work?</h3><p>Before we talk about <strong>generators</strong>, let’s first understand <strong>iterators</strong>.</p><p>An <strong>iterator</strong> allows you to loop through <strong>a sequence of data</strong> <strong>without</strong> storing it all in memory.</p><p>For example, instead of <strong>storing</strong> numbers <strong>1 to 1 million</strong> in a list, an iterator <strong>generates them as needed</strong>. This saves a <strong>ton</strong> of memory.</p><p>💡 <strong>Python’s </strong><strong>range() function is an iterator!</strong></p><pre>import sys  </pre><pre>x = list(range(1000000))  # Stores 1 million numbers in memory  <br>y = range(1000000)  # Generates numbers on demand  </pre><pre>print(sys.getsizeof(x))  # Huge memory usage<br>print(sys.getsizeof(y))  # Tiny memory usage</pre><h3>⚡ Creating Your Own Iterator (Old Way)</h3><p>Let’s create an <strong>iterator manually</strong> using a class.</p><pre>class CountUpTo:<br>    def __init__(self, max):<br>        self.max = max<br>        self.current = 0<br>    <br>    def __iter__(self):<br>        return self  # Returns the iterator object<br>    <br>    def __next__(self):<br>        if self.current &gt;= self.max:<br>            raise StopIteration  # Ends iteration<br>        <br>        self.current += 1<br>        return self.current</pre><pre>counter = CountUpTo(5)  # Count up to 5<br>for num in counter:<br>    print(num)</pre><p>✅ <strong>Works well but requires a lot of code!</strong></p><p>Now, let’s do the same thing <strong>more elegantly with generators</strong>.</p><h3>🧙‍♂️ Generators: The Simple &amp; Elegant Way</h3><p>With <strong>generators</strong>, we don’t need to create a class. We just use <strong>yield</strong> instead of return!</p><pre>def count_up_to(max):<br>    current = 1<br>    while current &lt;= max:<br>        yield current  # Pause execution and return the value<br>        current += 1  # Continue from where we left off</pre><h3>🔹 Using the Generator</h3><pre>counter = count_up_to(5)</pre><pre>for num in counter:<br>    print(num)</pre><p>💡 <strong>How it Works:</strong></p><ol><li>Calls count_up_to(5), creating a generator.</li><li>yield returns a value but <strong>pauses execution</strong> (does NOT exit).</li><li>When next() is called, the function <strong>resumes</strong> where it left off!</li></ol><h3>🎭 Real-World Example: Reading Large Files</h3><p>Imagine you need to read <strong>a 1GB log file</strong>. You don’t want to load it <strong>all at once</strong>! Instead, you read it <strong>line by line</strong>, like this:</p><pre>def read_large_file(file_path):<br>    with open(file_path, &quot;r&quot;) as file:<br>        for line in file:<br>            yield line  # Yield one line at a time</pre><pre># Usage<br>for line in read_large_file(&quot;big_log.txt&quot;):<br>    print(line)  # Process one line at a time without using too much memory!</pre><p>🔹 <strong>Without generators:</strong> <strong>Python would try to store the entire file in memory.</strong><br> 🔹 <strong>With generators:</strong> Python <strong>streams</strong> one line at a time, keeping memory usage low.</p><h3>📌 Generator Comprehensions (One-Liner Generators)</h3><p>Just like <strong>list comprehensions</strong>, Python allows <strong>generator comprehensions</strong> for a more <strong>compact</strong> syntax.</p><p>🔹 <strong>List comprehension (stores everything in memory)</strong></p><pre>nums = [x**2 for x in range(10)]</pre><p>🔹 <strong>Generator comprehension (generates one at a time, saves memory)</strong></p><pre>nums = (x**2 for x in range(10))  # Uses parentheses instead of square brackets</pre><p>💡 You can iterate over nums just like any other generator:</p><pre>for num in nums:<br>    print(num)</pre><h3>🚀 Key Advantages of Generators</h3><p>✅ <strong>Memory Efficient</strong> — Does not store all values at once.<br> ✅ <strong>Faster Execution</strong> — Only computes when needed.<br> ✅ <strong>Better for Large Datasets</strong> — Useful for reading big files or streaming data.<br> ✅ <strong>Elegant Syntax</strong> — Less code than manual iterators.</p><h3>🔹 When to Use Generators?</h3><p>✅ Use Generators When… ❌ Don’t Use Generators When… Processing <strong>large datasets</strong> You need to modify elements before using them Streaming <strong>live data</strong> You need <strong>random access</strong> to the data <strong>Lazy evaluation</strong> is required You want to <strong>store all results</strong> for later use</p><h3>💡 Final Thoughts</h3><p>Python <strong>generators</strong> are a powerful feature that allows you to iterate efficiently <strong>without</strong> storing everything in memory.</p><p>👉 If you’re working with <strong>large files, databases, or data streams</strong>, generators <strong>can save you time and memory</strong>.</p><p>🔹 <strong>Try replacing loops with generators in your next project and see the difference!</strong> 🚀🐍</p><h3>References</h3><p><em>P</em><a href="https://www.youtube.com/watch?v=u3T7hmLthUU&amp;t=103s"><em>ython Generators Explained</em></a></p><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 Github <a href="https://github.com/Onlynfk">https://github.com/Onlynfk</a>/<br><a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><h3>Want to Work with me?</h3><p>If you’re looking for a skilled developer to collaborate with, you can view my portfolio <a href="https://onlygodovbijecodes.web.app/">here</a>. Let’s bring your ideas to life together</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f47b5c952d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/python-generators-the-magic-behind-efficient-iteration-e3f47b5c952d">Python Generators: The Magic Behind Efficient Iteration 🚀🐍</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Python Tricks in 2025]]></title>
            <link>https://medium.com/codex/10-python-tricks-in-2025-3f1948d2d02e?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f1948d2d02e</guid>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[2025]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 18:51:16 GMT</pubDate>
            <atom:updated>2025-01-28T14:51:13.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>10 Top Python Tricks in 2025</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9sELv93x_FmX57kPCerfA.png" /><figcaption>By ChatGPT (AI)</figcaption></figure><p>Python is a versatile language with constant updates and improvements that make coding simpler, faster, and more efficient. As we move into 2025, here are ten Python tricks you need to master to level up your coding game, whether you’re a developer, data analyst, or just diving into Python.</p><p><strong>1. The Walrus Operator (:=)</strong></p><p>The <strong>walrus </strong>operator, introduced in Python 3.8, is a game-changer for writing concise and efficient code. It allows assignment and evaluation in a single expression, reducing redundancy.</p><p><strong>Example:</strong></p><pre>my_list = [1, 2, 3, 4, 5]<br>if (n := len(my_list)) &gt; 3:<br>    print(f&quot;List is too long ({n} elements).&quot;)</pre><p>Here, n is assigned the length of my_list while also being evaluated in the if condition. This eliminates the need for a separate line to calculate the length.</p><p><strong>Use Case:</strong></p><p><em>• Filtering data in loops or comprehensions.</em></p><p><em>• Avoiding redundant calculations.</em></p><p><strong>2. Data Classes</strong></p><p>Data classes simplify the creation of classes for storing data. Available since Python 3.7, they automatically generate special methods like __init__(), __repr__(), and __eq__().</p><p><strong>Example:</strong></p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class Point:<br>    x: int<br>    y: int<br><br>p = Point(4, 6)<br>print(p)  # Output: Point(x=4, y=6)</pre><p><strong>Benefits:</strong></p><p><em>• Cleaner and more readable code.</em></p><p><em>• Automatic handling of repetitive boilerplate methods.</em></p><p><strong>3. Pattern Matching with match</strong></p><p>Introduced in Python 3.10, pattern matching offers a structured and readable way to handle multiple conditions, similar to switch in other languages but more powerful.</p><p><strong>Example:</strong></p><pre>status_code = 200<br><br>match status_code:<br>    case 200:<br>        print(&quot;OK&quot;)<br>    case 404:<br>        print(&quot;Not Found&quot;)<br>    case _:<br>        print(&quot;Unknown status&quot;)</pre><p><strong>Why Use It?</strong></p><p><em>• Simplifies nested if-else chains.</em></p><p><em>• Handles complex data structures elegantly.</em></p><p><strong>4. Enhanced F-Strings for Debugging</strong></p><p>F-strings, introduced in Python 3.6, allow for inline variable evaluation. Adding an equal sign (=) in an F-string displays both the variable name and its value, making debugging faster and cleaner.</p><p><strong>Example:</strong></p><pre>value = 45<br>print(f&quot;{value=}&quot;)  # Output: value=45</pre><p><strong>Advantages:</strong></p><p><em>• Quick inspection of variables.</em></p><p><em>• More informative debugging output.</em></p><p><strong>5. Unpacking with the Asterisk (*) Operator</strong></p><p>The asterisk (*) operator simplifies handling iterable unpacking, allowing for flexible assignment of elements.</p><p><strong>Example:</strong></p><pre>fruits = [&quot;banana&quot;, &quot;apple&quot;, &quot;mango&quot;, &quot;berry&quot;]<br>yellow, green, *red = fruits<br>print(yellow)  # Output: banana<br>print(red)     # Output: [&#39;mango&#39;, &#39;berry&#39;]</pre><p><strong>Applications:</strong></p><p><em>• Splitting lists dynamically.</em></p><p><em>• Passing variable-length arguments to functions.</em></p><p><strong>6. Type Hinting</strong></p><p>Type hinting improves code readability and helps static analysis tools detect type-related issues. It’s especially useful in team environments or when working on large projects.</p><p><strong>Example:</strong></p><pre>from typing import List<br><br>def average(numbers: List[float]) -&gt; float:<br>    return sum(numbers) / len(numbers)<br><br>print(average([1.0, 2.0, 3.0]))  # Output: 2.0</pre><p><strong>Why Use Type Hints?</strong></p><p><em>• Reduces debugging time.</em></p><p><em>• Enhances IDE support with better autocomplete and error detection.</em></p><p><strong>7. Context Managers with contextlib</strong></p><p>Custom context managers, created using the contextlib module, streamline resource management, such as file handling or database connections.</p><p><strong>Example:</strong></p><pre>from contextlib import contextmanager<br><br>@contextmanager<br>def my_context():<br>    print(&quot;Entering context&quot;)<br>    yield<br>    print(&quot;Exiting context&quot;)<br><br>with my_context():<br>    print(&quot;Inside the context&quot;)</pre><p><strong>Benefits:</strong></p><p><em>• Automatic cleanup of resources.</em></p><p><em>• Reduces code clutter.</em></p><p><strong>8. </strong>The lru_cache decorator caches the results of expensive function calls, speeding up repeated computations for the same inputs.</p><p><strong>Example:</strong></p><pre>from functools import lru_cache<br>@lru_cache(maxsize=None)<br>def fibonacci(n: int) -&gt; int:<br>  if n &lt; 2:<br>  return n<br>  return fibonacci(n - 1) + fibonacci(n - 2)<br>  print(fibonacci(50)) # Output: 12586269025</pre><p><strong>Use Cases:</strong></p><p><em>• Recursive algorithms.</em></p><p><em>• Improving performance in data processing.</em></p><p><strong>9. File Handling with pathlib</strong></p><p>The pathlib module provides an object-oriented approach to file system paths, replacing cumbersome os module operations.</p><p><strong>Example:</strong></p><pre>from pathlib import Path<br><br>file_path = Path(&quot;example.txt&quot;)<br>file_path.write_text(&quot;Hello, Pathlib!&quot;)<br>print(file_path.read_text())  # Output: Hello, Pathlib!</pre><p><strong>Why Use Pathlib?</strong></p><p><em>• Simplifies file operations.</em></p><p><em>• Cross-platform compatibility.</em></p><p><strong>10. Enumerate with Custom Start Index</strong></p><p>The enumerate function, enhanced with the start parameter, is perfect for loops where you need both the index and the value.</p><p><strong>Example:</strong></p><pre>items = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br>for index, item in enumerate(items, start=1):<br>    print(f&quot;{index}: {item}&quot;)</pre><p><strong>Applications:</strong></p><p><em>• Numbering items in a list.</em></p><p><em>• Simplifying code that tracks indices manually.</em></p><p><strong>Conclusion</strong></p><p>These Python tricks, ranging from new features like the walrus operator and pattern matching to advanced techniques like context managers and memoization, will keep your code efficient and modern. Master them to boost your productivity and make your code cleaner and more professional.</p><p>Which of these tricks do you use the most? Let me know in the comments! And don’t forget to share this post with your fellow Python enthusiasts. 🚀</p><h3>References</h3><ul><li><a href="https://www.youtube.com/watch?v=RBHG6Pi8-Vg"><em>Top 10 Python tricks you can learn in 2025</em></a></li></ul><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 Github <a href="https://github.com/Onlynfk">https://github.com/Onlynfk</a>/<br><a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><h3>Want to Work with me?</h3><p>If you’re looking for a skilled developer to collaborate with, you can view my portfolio <a href="https://onlygodovbijecodes.web.app/">here</a>. Let’s bring your ideas to life together</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f1948d2d02e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/10-python-tricks-in-2025-3f1948d2d02e">10 Python Tricks in 2025</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Python’s Path to Becoming a Web Developer]]></title>
            <link>https://onlygod.medium.com/navigating-pythons-path-to-becoming-a-web-developer-df709d0eab98?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/df709d0eab98</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[codi̇ng]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 08:52:02 GMT</pubDate>
            <atom:updated>2024-09-18T06:22:34.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*nQkILZOB42EZg9JWedAbIA@2x.jpeg" /></figure><p>Python is a popular programming language that is widely used in web development. If you are interested in becoming a web developer with Python, then this guide is for you.</p><h3>Tools needed to learn Python web development</h3><p>Before diving into Python web development, you need to have some tools in place. Here are some of the essential tools you need to learn Python web development:</p><ul><li><strong>Python</strong> — You need to have Python installed on your computer. You can download Python from the official website at <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>.</li><li><strong>Text editor</strong> — You need a good text editor to write your Python code. Popular text editors include Visual Studio Code, Sublime Text, and Atom.</li><li><strong>Web browser</strong> — You need a web browser to test your web applications. Chrome, Firefox, and Safari are popular web browsers.</li><li><strong>Command-line interface</strong> — You should be familiar with the command-line interface to execute commands in the terminal.</li></ul><h3>Best web frameworks to learn in Python</h3><p>There are several web frameworks for Python, and here are some of the best frameworks to get started with:</p><ul><li><strong>Django</strong> — Django is a high-level Python web framework that follows the model-view-controller (MVC) architecture. It is perfect for building complex web applications and is widely used by developers.</li><li><strong>Flask</strong> — Flask is a lightweight Python web framework that is easy to learn and use. It is perfect for building small web applications.</li><li><strong>Bottle</strong> — Bottle is a simple and lightweight Python web framework that is ideal for building RESTful web services.</li></ul><h3>10 sample projects to start with</h3><p>Here are ten Python web development projects you can start with:</p><ol><li><a href="https://github.com/greyli/flask-tutorial">Flask Blog</a> — A simple blogging application built with Flask.</li><li><a href="https://github.com/mitchell-j/django-polls">Django Polls</a> — A polling application built with Django.</li><li><a href="https://github.com/pallets/flask/tree/main/examples/tutorial">Flaskr</a> — A microblogging application built with Flask.</li><li><a href="https://github.com/bradtraversy/django-todo">Django Todo List</a> — A simple todo list application built with Django.</li><li><a href="https://github.com/samlopezf/flask-web-scraper">Flask Web Scraper</a> — A web scraper built with Flask.</li><li><a href="https://github.com/egorsmkv/simple-store">Django E-commerce</a> — A simple e-commerce application built with Django.</li><li><a href="https://github.com/igormcsouza/flask-chat">Flask Chat</a> — A real-time chat application built with Flask.</li><li><a href="https://github.com/mjrussell/django-contact-form">Django Contact Form</a> — A contact form application built with Django.</li><li><a href="https://github.com/jeffheaton/t81_558_deep_learning">Flask Image Recognition</a> — An image recognition application built with Flask.</li><li><a href="https://github.com/bradtraversy/django-fileupload">Django File Upload</a> — A file upload application built with Django.</li></ol><h3>Conclusion</h3><p>Python web development is an exciting field, and with the right tools and frameworks, you can build amazing web applications. Start with the projects listed above and continue to explore the world of Python web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df709d0eab98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Custom Google Authentication System with Django Rest Framework and React II]]></title>
            <link>https://blog.stackademic.com/building-a-custom-google-authentication-system-with-django-rest-framework-and-reactjs-ii-794fa8592782?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/794fa8592782</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 14:43:00 GMT</pubDate>
            <atom:updated>2024-09-18T06:23:19.759Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to Part 2 of our tutorial series on building a custom Google authentication system using Django Rest Framework and ReactJS. In this section, we’ll focus on the React frontend implementation that complements the Django backend we set up in the<a href="https://onlygod.medium.com/building-a-custom-google-authentication-system-with-django-rest-framework-and-reactjs-i-925d2ba9258"> previous part</a>. If you’re ready to dive into the frontend aspects of the authentication system, let’s get started! 🚀🚀</p><p>You can find the code for this blog on GitHub: <a href="https://github.com/Onlynfk/social-login-django-reactjs.git">Link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*jVktwL5dkuq6LNPY" /><figcaption>Photo by <a href="https://unsplash.com/@behy_studio">Behnam Norouzi</a> on Unsplash</figcaption></figure><h3>Tools</h3><p>Before we begin, make sure you have the following tools and technologies set up:</p><ul><li><a href="https://code.visualstudio.com/">Visual Studio Code</a> (Text Editor)</li><li><a href="https://www.python.org/">Python</a> version 3 ++</li><li><a href="https://nodejs.org/en/">Nodejs</a></li><li>Windows (OS) using <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">WSL</a> and <a href="https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701?activetab=pivot:overviewtab">windows terminal</a></li></ul><h3>Table of Content</h3><p>In this part of the tutorial, we will cover the following steps:</p><ol><li>Setup Project</li><li>Install Dependencies</li><li>Integrate Tailwindcss</li><li>Setup Routing</li><li>Setup Pages</li><li>SocialAuth Page</li><li>Add Environment Variables</li><li>Done 🚀 Testing How It Work</li></ol><h4>1. Setup Project</h4><p>Here we are creating our Project app using the terminal, ensure you have <a href="https://code.visualstudio.com/">Nodejs</a> and <a href="https://create-react-app.dev/docs/getting-started/">create-react-app </a>installed globally</p><pre>npx create-react-app &lt;project_name_here&gt;</pre><h4>2. Install dependencies</h4><pre>yarn add react-router-dom axios query-string</pre><p>open the project directory with vscode, now on your terminal start your server by running the command below</p><pre>yarn start // for those using yarn</pre><h4>3. Integrate Tailwindcss</h4><p>First, let’s update the public/index.html to use tailwindcss</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;%PUBLIC_URL%/favicon.ico&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>    &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt;<br>    &lt;meta<br>      name=&quot;description&quot;<br>      content=&quot;Web site created using create-react-app&quot;<br>    /&gt;<br>    &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp&quot;&gt;&lt;/script&gt;<br><br>    &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;%PUBLIC_URL%/logo192.png&quot; /&gt;<br>    &lt;!--<br>      manifest.json provides metadata used when your web app is installed on a<br>      user&#39;s mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/<br>    --&gt;<br>    &lt;link rel=&quot;manifest&quot; href=&quot;%PUBLIC_URL%/manifest.json&quot; /&gt;<br>    &lt;!--<br>      Notice the use of %PUBLIC_URL% in the tags above.<br>      It will be replaced with the URL of the `public` folder during the build.<br>      Only files inside the `public` folder can be referenced from the HTML.<br><br>      Unlike &quot;/favicon.ico&quot; or &quot;favicon.ico&quot;, &quot;%PUBLIC_URL%/favicon.ico&quot; will<br>      work correctly both with client-side routing and a non-root public URL.<br>      Learn how to configure a non-root public URL by running `npm run build`.<br>    --&gt;<br>    &lt;title&gt;Google Auth App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;!--<br>      This HTML file is a template.<br>      If you open it directly in the browser, you will see an empty page.<br><br>      You can add webfonts, meta tags, or analytics to this file.<br>      The build step will place the bundled scripts into the &lt;body&gt; tag.<br><br>      To begin the development, run `npm start` or `yarn start`.<br>      To create a production bundle, use `npm run build` or `yarn build`.<br>    --&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now open the <strong><em>index.js</em></strong><em> </em>file in the <strong><em>src </em></strong>folder, let’s setup routing using react-router-dom</p><h4>4. Setup Routing</h4><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./App&#39;;<br>import { BrowserRouter } from &#39;react-router-dom&#39;;<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;BrowserRouter&gt;<br>    &lt;App /&gt;<br>    &lt;/BrowserRouter&gt;<br>  &lt;/React.StrictMode&gt;<br>);<br></pre><p>In App.js let’s create the pages routes</p><pre>import React from &quot;react&quot;;<br>import { Route, Routes } from &quot;react-router-dom&quot;;<br>import Home from &quot;./pages/Home&quot;<br>import SocialAuth from &quot;./pages/social-auth&quot;<br><br>const App = () =&gt; {<br><br>  return (<br>    &lt;Routes&gt;<br>    &lt;Route exact path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>    &lt;Route exact path=&quot;/google&quot; element={&lt;SocialAuth /&gt;} /&gt;<br>    &lt;/Routes&gt;<br>  );<br>};<br><br>export default App;</pre><h4>5. Setup Pages</h4><p>Next let’s create a <strong>pages</strong> folder in our <strong>src</strong> folder and create a <strong>Home</strong> folder in it, with a index.js and also a <strong>SocialAuth</strong> folder with a <strong>index.js</strong></p><pre>// src/pages/Home/index.js<br><br><br>import React, { useCallback, useEffect, useState } from &quot;react&quot;;<br><br>const { REACT_APP_GOOGLE_CLIENT_ID, REACT_APP_GOGGLE_REDIRECT_URL_ENDPOINT } =<br>  process.env;<br><br>const Home = () =&gt; {<br>  const [username, setUsername] = useState(localStorage.getItem(&#39;goggleFirstName&#39;))<br><br>  useEffect(() =&gt; {<br>    const storedUsername = localStorage.getItem(&quot;user_goggle&quot;);<br>    if (storedUsername) {<br>      setUsername(storedUsername);<br>    }<br>  }, []);<br>  const openGoogleLoginPage = useCallback(() =&gt; {<br>    const googleAuthUrl = &quot;https://accounts.google.com/o/oauth2/v2/auth&quot;;<br>    <br>    const scope = [<br>      &quot;https://www.googleapis.com/auth/userinfo.email&quot;,<br>      &quot;https://www.googleapis.com/auth/userinfo.profile&quot;,<br>    ].join(&quot; &quot;);<br><br>    const params = new URLSearchParams({<br>      response_type: &quot;code&quot;,<br>      client_id: REACT_APP_GOOGLE_CLIENT_ID,<br>      redirect_uri: `${REACT_APP_GOGGLE_REDIRECT_URL_ENDPOINT}/google`,<br>      prompt: &quot;select_account&quot;,<br>      access_type: &quot;offline&quot;,<br>      scope,<br>    });<br><br>    const url = `${googleAuthUrl}?${params}`;<br><br>    window.location.href = url;<br>  }, []);<br><br>  const handleLogout = () =&gt; {<br>    localStorage.clear(); // Clear localStorage when the button is clicked<br>    setUsername(&quot;&quot;)<br>  };<br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center h-screen&quot;&gt;<br>       {!username &amp;&amp;  &lt;button<br>           <br>           className=&quot;bg-white text-gray-800 font-bold py-2 px-4 border rounded shadow  focus:outline-none  mb-8  mb-4&quot;<br>           onClick={openGoogleLoginPage}<br>         &gt;<br>           &lt;div className=&quot;flex items-center justify-center&quot;&gt;<br>             &lt;svg<br>               xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>               viewBox=&quot;0 0 48 48&quot;<br>               width=&quot;48px&quot;<br>               height=&quot;48px&quot;<br>             &gt;<br>               &lt;path<br>                 fill=&quot;#FFC107&quot;<br>                 d=&quot;M43.611,20.083H42V20H24v8h11.303c-1.649,4.657-6.08,8-11.303,8c-6.627,0-12-5.373-12-12c0-6.627,5.373-12,12-12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C12.955,4,4,12.955,4,24c0,11.045,8.955,20,20,20c11.045,0,20-8.955,20-20C44,22.659,43.862,21.35,43.611,20.083z&quot;<br>               /&gt;<br>               &lt;path<br>                 fill=&quot;#FF3D00&quot;<br>                 d=&quot;M6.306,14.691l6.571,4.819C14.655,15.108,18.961,12,24,12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C16.318,4,9.656,8.337,6.306,14.691z&quot;<br>               /&gt;<br>               &lt;path<br>                 fill=&quot;#4CAF50&quot;<br>                 d=&quot;M24,44c5.166,0,9.86-1.977,13.409-5.192l-6.19-5.238C29.211,35.091,26.715,36,24,36c-5.202,0-9.619-3.317-11.283-7.946l-6.522,5.025C9.505,39.556,16.227,44,24,44z&quot;<br>               /&gt;<br>               &lt;path<br>                 fill=&quot;#1976D2&quot;<br>                 d=&quot;M43.611,20.083H42V20H24v8h11.303c-0.792,2.237-2.231,4.166-4.087,5.571c0.001-0.001,0.002-0.001,0.003-0.002l6.19,5.238C36.971,39.205,44,34,44,24C44,22.659,43.862,21.35,43.611,20.083z&quot;<br>               /&gt;<br>             &lt;/svg&gt;<br>             Sign in with Google<br>           &lt;/div&gt;<br>         &lt;/button&gt;<br>     <br>      }<br>      {username ? (<br>        &lt;div className=&quot;text-center&quot;&gt;<br>          &lt;small className=&quot;text-primary-600&quot;&gt;User is logged as: {username}&lt;/small&gt;<br>          &lt;br/&gt;<br>          &lt;button onClick={handleLogout} className=&quot;bg-red-400 hover:bg-red-200 text-white font-semibold py-2 px-4 rounded mt-2&quot;&gt;<br>      Logout<br>    &lt;/button&gt;<br>        &lt;/div&gt;<br>      ) : (<br>        &lt;small className=&quot;text-primary-600&quot;&gt;Ops not Logged in yet&lt;/small&gt;<br>      )}<br><br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;<br><br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6R_2NIWGaz_xpVf_qL_X5A.png" /><figcaption>Home page</figcaption></figure><p>Next, let’s update the <strong>SocialAuth</strong> folder, <strong>index.js file</strong></p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br>import { useLocation, useNavigate } from &quot;react-router-dom&quot;;<br>import queryString from &quot;query-string&quot;;<br>import axios from &quot;axios&quot;;<br>import &quot;./index.css&quot;;<br><br>const { BACKEND_API_URL } = process.env;<br><br>const SocialAuth = () =&gt; {<br>  let location = useLocation();<br>  console.log(&quot;location&quot;, location);<br>  const [error, setError] = useState(&quot;&quot;);<br>  const navigate = useNavigate();<br><br>  useEffect(() =&gt; {<br>    const values = queryString.parse(location.search);<br>    const code = values.code ? values.code : null;<br><br>    if (code) {<br>      onGogglelogin();<br>    }<br>  }, []);<br><br>  const googleLoginHandler = (code) =&gt; {<br>    return axios<br>      .get(`${BACKEND_API_URL}/api/auth/google/${code}`)<br>      .then((res) =&gt; {<br>        localStorage.setItem(&quot;goggleFirstName&quot;, res.data.user.first_name);<br>        return res.data;<br>      })<br>      .catch((err) =&gt; {<br>        setError(err);<br>        return err;<br>      });<br>  };<br><br>  const onGogglelogin = async () =&gt; {<br>    const response = await googleLoginHandler(location.search);<br>    if (response.data.access) {<br>      navigate(&quot;/&quot;);<br>    }<br>  }<br><br>  return (<br>    &lt;div className=&quot;loading-icon-container&quot;&gt;<br>      &lt;div className=&quot;loading-icon&quot;&gt;<br>        &lt;div className=&quot;loading-icon__circle loading-icon__circle--first&quot;&gt;&lt;/div&gt;<br>        &lt;div className=&quot;loading-icon__circle loading-icon__circle--second&quot;&gt;&lt;/div&gt;<br>        &lt;div className=&quot;loading-icon__circle loading-icon__circle--third&quot;&gt;&lt;/div&gt;<br>        &lt;div className=&quot;loading-icon__circle loading-icon__circle--fourth&quot;&gt;&lt;/div&gt;<br>      &lt;/div&gt;<br>        &lt;small className=&quot; text-center mr-2&quot;&gt;<br>          Just a moment<br>        &lt;/small&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br><br>export default SocialAuth;</pre><p>In the social-auth folder let’s create a index.css</p><pre>// social-auth/index.css<br><br>.loading-icon-container {<br>    position: fixed;<br>    top: 50%;<br>    left: 50%;<br>    transform: translate(-50%, -50%);<br>  }<br>  <br>  .loading-icon {<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>    height: 50px;<br>    width: 150px;<br>    margin-left: -2rem;<br>  }<br>  <br>  .loading-icon__circle {<br>    height: 12px;<br>    width: 12px;<br>    border-radius: 50%;<br>    background-color: #2ba7dc;<br>    margin-right: 8px;<br>    animation: spin 1s ease-in-out infinite;<br>  }<br>  <br>  .loading-icon__circle--first {<br>    animation-delay: 0.1s;<br>    background-color: #ffc107;<br>  <br>  }<br>  <br>  .loading-icon__circle--second {<br>    animation-delay: 0.2s;<br>  }<br>  <br>  .loading-icon__circle--third {<br>    animation-delay: 0.3s;<br>    background-color: #ffc107;<br>  }<br>  .loading-icon__circle--fourth {<br>    animation-delay: 0.3s;<br>  }<br>  <br>  @keyframes spin {<br>    from {<br>      transform: translateX(0);<br>    }<br>    to {<br>      transform: translateX(130%);<br>    }<br>  }</pre><h4>6. Add environments variables</h4><p>Next, let’s create a .<strong>env</strong> file in our project</p><pre>BACKEND_API_URL=&#39;http://localhost:8000&#39;<br>REACT_APP_GOGGLE_REDIRECT_URL_ENDPOINT=&#39;http://localhost:3000&#39;<br>REACT_APP_GOOGLE_CLIENT_ID=&quot;YOUR_GOOGLE_CLIENT_ID&quot;</pre><h4>6. Done 🚀 testing how it works</h4><p>Let’s test how it all works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aA7bCy52XjVsUKtpfVhGdQ.png" /><figcaption>HomePage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3G1Q8xroFVGVIQ8o5qFfQ.png" /><figcaption>Sign In with Google</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AOQy-gP8ogsY2Ys8rwqog.png" /><figcaption>Loading page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5jFazl1fiA4ybafZmiZKA.png" /><figcaption>Logged in 🚀</figcaption></figure><p>Done 🚀 Congratulations! You’ve successfully integrated a custom Google login system into your Django and ReactJS project. This authentication mechanism enhances user experience and security while interacting with your application.</p><p>You can find the code for this blog on GitHub: <a href="https://github.com/Onlynfk/social-login-django-reactjs.git">Link</a></p><blockquote>Thanks for Your Time ♥️</blockquote><blockquote>I hope you’ve found this tutorial helpful. If you have any questions or feedback, feel free to reach out. Stay tuned for more tutorials and guides on various development topics!</blockquote><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 Github <a href="https://github.com/Onlynfk">https://github.com/Onlynfk</a>/<br><a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><h4>Want to Work with me?</h4><p>If you’re looking for a skilled developer to collaborate with, you can view my portfolio <a href="https://onlygodovbijecodes.web.app/">here</a>. Let’s bring your ideas to life together.</p><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><em> to find out more about how we are democratising free programming education around the world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794fa8592782" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/building-a-custom-google-authentication-system-with-django-rest-framework-and-reactjs-ii-794fa8592782">Build a Custom Google Authentication System with Django Rest Framework and React II</a> was originally published in <a href="https://blog.stackademic.com">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Google Authentication System with Django Rest Framework and ReactJS I]]></title>
            <link>https://medium.com/codex/building-a-custom-google-authentication-system-with-django-rest-framework-and-reactjs-i-925d2ba9258?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/925d2ba9258</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 14:41:39 GMT</pubDate>
            <atom:updated>2024-09-26T21:34:49.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jVktwL5dkuq6LNPY" /><figcaption>Photo by <a href="https://unsplash.com/@behy_studio">Behnam Norouzi</a> on Unsplash</figcaption></figure><p>Hello there! 😊 Today, we are going to embark on a journey to build a custom Google authentication system using Django Rest Framework and ReactJS, without relying on any social third-party plugins. This tutorial will be divided into two parts, focusing on the setup of our Django backend and the subsequent frontend implementation.</p><p><strong>Co-authored by </strong><a href="https://medium.com/u/5524241100aa"><strong>Adetola Abiodun</strong></a></p><p>I’m excited to share this article, co-authored with <a href="https://github.com/TolaAbiodun">Adetola Abiodun</a>. Tola is a seasoned full-stack Web/Mobile Engineer. Together, we’ve combined our insights to bring you a comprehensive look into building this custom authentication system. We hope you find our collaboration informative and engaging!</p><p>You can find the code for this blog on GitHub: <a href="https://github.com/Onlynfk/social-login-django-reactjs.git">Link</a></p><p>Before we begin, make sure you have the following tools and technologies set up:</p><ul><li><a href="https://code.visualstudio.com/">Visual Studio Code</a> (Text Editor)</li><li><a href="https://www.python.org/">Python</a> version 3 ++</li><li><a href="https://nodejs.org/en/">Nodejs</a></li><li>Windows (OS) using <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">WSL</a> and <a href="https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701?activetab=pivot:overviewtab">windows terminal</a></li></ul><h3>Table of Content</h3><p>In this part of the tutorial, we will cover the following steps:</p><ol><li>Setup Project Workflow</li><li>Setting up an Authentication System</li><li>Setting up Google APIs</li><li>Adding Google Credentials</li><li>Creating a Custom Google LoginView</li><li>Testing with Postman 🚀</li><li>Head to Part 2</li></ol><h3>1. Setup Project Workflow</h3><p>Let’s start with creating our django project</p><pre># Make a Directory for the Project and navigate into it.<br>mkdir social-login/backend &amp;&amp; cd social-login/backend</pre><pre># Create and activate a Python Virtual Environment<br>python3 -m venv venv<br>source venv/bin/activate</pre><pre># Install the corheaders plugin<br>pip install django-cors-headers</pre><pre># Create a Django Project<br>django-admin startproject social_login .</pre><pre># Test Run the server<br>python manage.py runserver</pre><h3>2. Setting up an Authentication System</h3><p>In the same social_login directory, let’s create an authentication app to handle the authentication workflow on the system:</p><pre>python manage.py startapp authentication</pre><p>Add ‘authentication’ to the INSTALLED_APPS in your settings.py:</p><pre>DEFAULT_APPS = [<br>    &quot;corsheaders&quot;, #new<br>    &quot;django.contrib.admin&quot;,<br>    &quot;django.contrib.auth&quot;,<br>    &quot;django.contrib.contenttypes&quot;,<br>    &quot;django.contrib.sessions&quot;,<br>    &quot;django.contrib.messages&quot;,<br>    &quot;django.contrib.staticfiles&quot;,<br>]<br><br>CUSTOM_APPS = [<br>    &quot;authentication&quot;,<br>]<br><br>INSTALLED_APPS =  DEFAULT_APPS + CUSTOM_APPS<br><br>MIDDLEWARE = [<br>    &quot;corsheaders.middleware.CorsMiddleware&quot;,<br>      ....<br>]</pre><p>now let&#39;s create a custom user model in our<em> authentication/models.py </em>using the AbstractUser class, as shown below</p><pre>from django.contrib.auth.models import AbstractUser<br>from django.db import models<br><br><br>class User(AbstractUser):<br>    # Add any additional fields you want in your custom user model<br>    email = models.CharField(max_length=250, unique=True, null=False, blank=False)<br>    REGISTRATION_CHOICES = [<br>        (&#39;email&#39;, &#39;Email&#39;),<br>        (&#39;google&#39;, &#39;Google&#39;),<br>    ]<br>    registration_method = models.CharField(<br>        max_length=10,<br>        choices=REGISTRATION_CHOICES,<br>        default=&#39;email&#39;<br>    )<br><br>    def __str__(self):<br>       return self.username</pre><ul><li>Importing necessary modules The code begins by importing the required modules: AbstractUser from django.contrib.auth.models and models from django.db.</li><li>Defining the custom user model The User class is defined, which inherits from AbstractUser. This allows the custom user model to have all the fields and functionality provided by the built-in Django User model.</li><li>Adding additional fields In this step, two additional fields are added to the custom user model:</li><li>email: This field is defined as a CharField with a maximum length of 250 characters. It is set to be unique, meaning each user must have a unique email address. It cannot be null (empty) or blank (whitespace-only).</li><li>registration_method: This field is defined as a CharField with a maximum length of 10 characters. It represents the method of user registration and has two choices: &#39;email&#39; and &#39;google&#39;. The default value is set to &#39;email&#39;.</li></ul><p>Next, let’s use the makemigrations command to create new database migration files for our authentication app</p><pre>python manage.py makemigrations</pre><p>and update the<em> settings.py file</em> to specify the custom user model to be used for authentication in our project.</p><p>AUTH_USER_MODEL = &#39;authentication.User&#39;</p><h3>3. Setting up Google APIs</h3><p>To enable Google login functionality in our application, we will need to set up an OAuth application through the <a href="https://console.developers.google.com/"><strong>Google Developers Console</strong></a> Follow the steps below.</p><h4>1. Create a New Google APIs project</h4><ul><li>Go to the Google Developer APIs Console and access the Dashboard.</li><li>Create a new project by clicking on the “New Project” button.</li><li>Provide a name for your project, preferably using your website or app name. This project name will be visible to users when they are redirected to the Google login page.</li><li>Click on “Create” to proceed.</li></ul><h4>2. Next Update the OAuth Consent Screen</h4><ul><li>After creating the project, register your app by configuring the OAuth consent screen.</li><li>You only need to provide the “App name,” “User support email,” and “Email addresses” under the “Developer contact information” section.</li><li>Click on the “Save and Continue” button.</li></ul><h4>3. Create New API Credentials</h4><ul><li>Go back to the “Dashboard” and select “Credentials” from the left panel.</li><li>Click on the “Create Credentials” button at the top, and choose the “OAuth Client ID” option from the dropdown menu.</li></ul><p>Under <strong>‘Authorized JavaScript origins’</strong>, add the following URIs:</p><ul><li><a href="http://localhost:8000">http://localhost:3000</a></li></ul><p>Under <strong>‘Authorized redirect URIs’</strong>, add the following URIs:</p><ul><li><a href="http://localhost:8000">http://localhost:300</a>0/google</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQHKT0ak70uAU6ByB1kczg.png" /><figcaption>Click on Create credentails</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yv9f22GhWRqHaBbNOSbzUw.png" /><figcaption>Fill in Javascript origins and Redirect URL</figcaption></figure><p>On the same page, you will find your Client ID and Client secret under the “Credentials” section. Follow the steps below to locate and copy these details:</p><ol><li>Go to the Google Developer APIs Console and access the “Credentials” section from the left-hand side menu.</li><li>Look for the section that displays your OAuth Client ID and Client secret.</li><li>Copy the Client ID and Client secret to use them in the next step of your application’s configuration.</li></ol><p>These credentials are essential for authenticating our application with Google APIs and enabling the Google login functionality. Make sure to keep them secure and avoid sharing them publicly.</p><h3>4. Adding Google Credentials</h3><p>Next let’s add our Google credentials to a <strong><em>.env </em></strong>file on our django project in our social_login directory</p><pre>export GOOGLE_OAUTH2_CLIENT_ID = YOUR_GOOGLE_CLIENT_ID<br>export GOOGLE_OAUTH2_CLIENT_SECRET = YOUR_GOOGLE_CLIENT_SECRET</pre><p>next let’s update and point to it our setting.py file</p><pre>import os<br><br><br>...<br># Google OAuth2 settings<br>BASE_FRONTEND_URL = os.environ.get(&#39;DJANGO_BASE_FRONTEND_URL&#39;, default=&#39;http://localhost:3000&#39;)<br>GOOGLE_OAUTH2_CLIENT_ID = os.environ.get(&#39;GOOGLE_OAUTH2_CLIENT_ID&#39;)<br>GOOGLE_OAUTH2_CLIENT_SECRET = os.environ.get(&#39;GOOGLE_OAUTH2_CLIENT_SECRET&#39;)</pre><h3>5. Creating a Custom Google LoginView</h3><p>Create a custom Google login functionality in your authentication app&#39;s views.py:</p><pre># views.py<br><br><br>from urllib.parse import urlencode<br>from rest_framework import serializers<br>from rest_framework.views import APIView<br>from django.conf import settings<br>from django.shortcuts import redirect<br>from rest_framework_simplejwt.serializers import TokenObtainPairSerializer<br>from rest_framework.response import Response<br>from .mixins import PublicApiMixin, ApiErrorsMixin<br>from .services import google_get_access_token, google_get_user_info<br>from apps.authentication.models import User<br>from apps.authentication.serializers import UserSerializer<br><br><br>def generate_tokens_for_user(user):<br>    &quot;&quot;&quot;<br>    Generate access and refresh tokens for the given user<br>    &quot;&quot;&quot;<br>    serializer = TokenObtainPairSerializer()<br>    token_data = serializer.get_token(user)<br>    access_token = token_data.access_token<br>    refresh_token = token_data<br>    return access_token, refresh_token<br><br><br>class GoogleLoginApi(PublicApiMixin, ApiErrorsMixin, APIView):<br>    class InputSerializer(serializers.Serializer):<br>        code = serializers.CharField(required=False)<br>        error = serializers.CharField(required=False)<br><br>    def get(self, request, *args, **kwargs):<br>        input_serializer = self.InputSerializer(data=request.GET)<br>        input_serializer.is_valid(raise_exception=True)<br><br>        validated_data = input_serializer.validated_data<br><br>        code = validated_data.get(&#39;code&#39;)<br>        error = validated_data.get(&#39;error&#39;)<br><br>        login_url = f&#39;{settings.BASE_FRONTEND_URL}/login&#39;<br>    <br>        if error or not code:<br>            params = urlencode({&#39;error&#39;: error})<br>            return redirect(f&#39;{login_url}?{params}&#39;)<br><br>        redirect_uri = f&#39;{settings.BASE_FRONTEND_URL}/google/&#39;<br>        access_token = google_get_access_token(code=code, <br>                                               redirect_uri=redirect_uri)<br><br>        user_data = google_get_user_info(access_token=access_token)<br><br>        try:<br>            user = User.objects.get(email=user_data[&#39;email&#39;])<br>            access_token, refresh_token = generate_tokens_for_user(user)<br>            response_data = {<br>                &#39;user&#39;: UserSerializer(user).data,<br>                &#39;access_token&#39;: str(access_token),<br>                &#39;refresh_token&#39;: str(refresh_token)<br>            }<br>            return Response(response_data)<br>        except User.DoesNotExist:<br>            username = user_data[&#39;email&#39;].split(&#39;@&#39;)[0]<br>            first_name = user_data.get(&#39;given_name&#39;, &#39;&#39;)<br>            last_name = user_data.get(&#39;family_name&#39;, &#39;&#39;)<br><br>            user = User.objects.create(<br>                username=username,<br>                email=user_data[&#39;email&#39;],<br>                first_name=first_name,<br>                last_name=last_name,<br>                registration_method=&#39;google&#39;,<br>                phone_no=None,<br>                referral=None<br>            )<br>         <br>            access_token, refresh_token = generate_tokens_for_user(user)<br>            response_data = {<br>                &#39;user&#39;: UserSerializer(user).data,<br>                &#39;access_token&#39;: str(access_token),<br>                &#39;refresh_token&#39;: str(refresh_token)<br>            }<br>            return Response(response_data)</pre><p>let&#39;s also create a serilizers.py file in our authentication app and update it as it is used in our views.py</p><pre># serializers.py<br><br>from rest_framework import serializers<br>from .models import User<br><br>class UserSerializer(serializers.ModelSerializer):<br>    <br>    class Meta:<br>        model = User<br>        fields = [&#39;first_name&#39;, &#39;last_name&#39;, &#39;email&#39;]<br><br></pre><p>let’s do so also for the mixins.py file and update it as it used in our views.py</p><pre># mixins.py<br><br>from rest_framework_simplejwt.authentication import JWTAuthentication<br>from rest_framework.permissions import IsAuthenticated<br>from rest_framework import exceptions as rest_exceptions<br><br>from django.core.exceptions import ValidationError<br><br>from .utils import get_error_message<br>from apps.authentication.models import User<br><br><br>class ApiAuthMixin:<br>    authentication_classes = (JWTAuthentication, )<br>    permission_classes = (IsAuthenticated, )<br><br><br>class PublicApiMixin:<br>    authentication_classes = ()<br>    permission_classes = ()<br><br><br>class ApiErrorsMixin:<br>    &quot;&quot;&quot;<br>    Mixin that transforms Django and Python exceptions into rest_framework ones.<br>    Without the mixin, they return 500 status code which is not desired.<br>    &quot;&quot;&quot;<br>    expected_exceptions = {<br>        ValueError: rest_exceptions.ValidationError,<br>        ValidationError: rest_exceptions.ValidationError,<br>        PermissionError: rest_exceptions.PermissionDenied,<br>        User.DoesNotExist: rest_exceptions.NotAuthenticated<br>    }<br><br>    def handle_exception(self, exc):<br>        if isinstance(exc, tuple(self.expected_exceptions.keys())):<br>            drf_exception_class = self.expected_exceptions[exc.__class__]<br>            drf_exception = drf_exception_class(get_error_message(exc))<br><br>            return super().handle_exception(drf_exception)<br><br>        return super().handle_exception(exc)<br></pre><p>also for the utils.py file and update it as it is used in our views.py</p><pre># utils.py<br><br><br>import requests<br>from typing import Dict, Any<br>from django.conf import settings<br>from django.core.exceptions import ValidationError<br>from rest_framework_simplejwt.serializers import TokenObtainPairSerializer<br><br><br>GOOGLE_ID_TOKEN_INFO_URL = &#39;https://www.googleapis.com/oauth2/v3/tokeninfo&#39;<br>GOOGLE_ACCESS_TOKEN_OBTAIN_URL = &#39;https://oauth2.googleapis.com/token&#39;<br>GOOGLE_USER_INFO_URL = &#39;https://www.googleapis.com/oauth2/v3/userinfo&#39;<br><br><br><br>def generate_tokens_for_user(user):<br>    &quot;&quot;&quot;<br>    Generate access and refresh tokens for the given user<br>    &quot;&quot;&quot;<br>    serializer = TokenObtainPairSerializer()<br>    token_data = serializer.get_token(user)<br>    access_token = token_data.access_token<br>    refresh_token = token_data<br>    return access_token, refresh_token<br><br><br>def google_get_access_token(*, code: str, redirect_uri: str) -&gt; str:<br>    data = {<br>        &#39;code&#39;: code,<br>        &#39;client_id&#39;: settings.GOOGLE_OAUTH2_CLIENT_ID,<br>        &#39;client_secret&#39;: settings.GOOGLE_OAUTH2_CLIENT_SECRET,<br>        &#39;redirect_uri&#39;: redirect_uri,<br>        &#39;grant_type&#39;: &#39;authorization_code&#39;<br>    }<br><br><br>    response = requests.post(GOOGLE_ACCESS_TOKEN_OBTAIN_URL, data=data)<br><br>    if not response.ok:<br>        raise ValidationError(&#39;Failed to obtain access token from Google.&#39;)<br><br>    access_token = response.json()[&#39;access_token&#39;]<br><br>    return access_token<br><br><br>def google_get_user_info(*, access_token:  str) -&gt; Dict[str, Any]:<br>    response = requests.get(<br>        GOOGLE_USER_INFO_URL,<br>        params={&#39;access_token&#39;: access_token}<br>    )                   <br><br>    if not response.ok:<br>        raise ValidationError(&#39;Failed to obtain user info from Google.&#39;)<br><br>    return response.json()</pre><p>next, let’s update our urls.py</p><pre>from django.urls import path<br>from . import views<br><br>urlpatterns = [<br>      path(&quot;auth/login/google/&quot;, GoogleLoginApi.as_view(), <br>         name=&quot;login-with-google&quot;),<br>]</pre><p>lastly, let’s update our project urls.py and .env file</p><pre># socail_login/urls.py<br><br>from django.urls import path, include<br><br>urlpatterns = [<br>   path(&quot;admin/&quot;, admin.site.urls),<br>   path(&quot;api/&quot;, include(&quot;authentication.urls&quot;)),<br><br>]</pre><p>next our <strong>.env file</strong></p><pre># socail_login/.env<br>export GOOGLE_OAUTH2_CLIENT_ID = YOUR_GOOGLE_CLIENT_ID<br>export GOOGLE_OAUTH2_CLIENT_SECRET = YOUR_GOOGLE_CLIENT_SECRET<br><br>export DJANGO_BASE_FRONTEND_URL=&quot;http://localhost:3000&quot; #new</pre><p>and then update <strong>settings.py</strong></p><pre>BASE_FRONTEND_URL = os.environ.get(&#39;DJANGO_BASE_FRONTEND_URL&#39;) # new<br><br># Google OAuth2 settings<br>GOOGLE_OAUTH2_CLIENT_ID = os.environ.get(&#39;DJANGO_GOOGLE_OAUTH2_CLIENT_ID&#39;)<br>GOOGLE_OAUTH2_CLIENT_SECRET = os.environ.get(&#39;DJANGO_GOOGLE_OAUTH2_CLIENT_SECRET&#39;)</pre><h3>6. Testing with Postman</h3><p>Test the Google login view using Postman:</p><pre>http://127.0.0.1:8000/api/v1/auth/login/google/?<br>code=4%2F0AZEOvhV5qNkTEnISqWASmWy0O6UaivxTrQvfc6RFUF9Hqxuezmz1EH-umQj0TkeJS_98Xw<br>&amp;scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&amp;authuser=0&amp;prompt=none</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usqBpVSD7vQQEHlwbrQP7g.png" /><figcaption>Postman testing</figcaption></figure><p>We see get an error,</p><pre>[<br>    &quot;Failed to obtain access token from Google.&quot;<br>]</pre><p>You might encounter an error indicating that the access token from Google couldn’t be obtained. This is expected due to the expired code in the URL.</p><p>In the next section, we’ll cover the<a href="https://onlygod.medium.com/building-a-custom-google-authentication-system-with-django-rest-framework-and-reactjs-ii-794fa8592782"> front-end implementation using ReactJS.</a></p><p>You can find the code for this blog on GitHub: <a href="https://github.com/Onlynfk/social-login-django-reactjs.git">Link</a></p><p><em>Thanks for Your Time ♥️</em></p><p><em>I hope you’ve found this tutorial helpful. If you have any questions or feedback, feel free to reach out. Stay tuned for more tutorials and guides on various development topics!</em></p><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 Github <a href="https://github.com/Onlynfk">https://github.com/Onlynfk</a>/<br><a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><h3>Want to Work with me?</h3><p>If you’re looking for a skilled developer to collaborate with, you can view my portfolio <a href="https://onlygodovbijecodes.web.app/">here</a>. Let’s bring your ideas to life together</p><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=925d2ba9258" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/building-a-custom-google-authentication-system-with-django-rest-framework-and-reactjs-i-925d2ba9258">Building a Custom Google Authentication System with Django Rest Framework and ReactJS I</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Steps to JavaScript Promises: A Beginner’s Guide]]></title>
            <link>https://onlygod.medium.com/7-steps-to-javascript-promises-a-beginners-guide-388df4e6e2c6?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/388df4e6e2c6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 03:10:06 GMT</pubDate>
            <atom:updated>2023-07-01T03:17:56.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*TUF3ZW39TVFL-9HK.jpg" /><figcaption>Photo from <a href="https://www.pinterest.com/pin/3377768464835487/">Pinterest</a></figcaption></figure><blockquote><strong>Promises</strong> are an essential feature of JavaScript that help manage asynchronous operations and handle their results. They provide a way to write cleaner and more readable code when dealing with tasks that may take some time to complete, such as making API requests or executing time-consuming operations.</blockquote><blockquote>In this blog post, we’ll explore the basics of promises and demonstrate their usage through code examples.</blockquote><h4>Let’s get started!!! 🚀🚀</h4><h4>Contents</h4><ul><li>Creating a Promise</li><li>Resolving a Promise</li><li>Chaining Promises</li><li>Executing Functions on Resolve</li><li>Handling Rejection with Catch</li><li>Chaining Multiple Promises</li><li>Using JSONPlaceholder API for Testing</li></ul><h3><strong>1. Creating a Promise</strong></h3><pre>const count = false;<br><br>let countValue = new Promise(function(resolve, reject) {<br>    if (count) {<br>        resolve(&#39;There is a count value.&#39;);<br>    } else {<br>        reject(&#39;There is no count value.&#39;);<br>    }<br>});</pre><p>In this example, we create a promise countValue that represents an asynchronous operation. If count is true, the promise is resolved with the message &quot;There is a count value.&quot; Otherwise, it is rejected with the message &quot;There is no count value.&quot; You can console.log(countValue) statement to see the result.</p><h3>2. Resolving a Promise</h3><pre>let promise = new Promise(function(resolve, reject) {<br>    setTimeout(() =&gt; reject(new Error(&#39;Whoops&#39;)), 1000);<br>});</pre><p>Here, we create a promise promise that resolves after a delay of 5 seconds (5000 milliseconds). Once resolved, it logs the success message &quot;done&quot; to the console.</p><h3>3. Rejecting a Promise</h3><pre>let promise = new Promise(function(resolve, reject) {<br>    setTimeout(() =&gt; reject(new Error(&#39;Whoops&#39;)), 1000);<br>});</pre><p>In this example, the promise promise is rejected after a delay of 1 second (1000 milliseconds) with an Error object containing the message &quot;Whoops&quot;. You can handle the rejection using the catch method, which we&#39;ll see in example 5.</p><h3>3: Chaining Promises</h3><pre>const promise = doSomething();<br><br>const promise2 = promise2.then(successCallback, failureCallback);<br><br>// simplified<br>const promise3 = doSomething().then(successCallback, failureCallback);</pre><p>Promises can be chained together to perform a sequence of asynchronous tasks. In this example, doSomething() represents the first asynchronous task, which returns a promise. Then, we chain the then method to handle the resolved value (successCallback) or the rejected value (failureCallback) of the promise</p><h3>4: Executing Functions on Resolve</h3><pre>let exampleTask = new Promise(function(resolve, reject) {<br>    resolve(&#39;Promise resolved&#39;);<br>});<br><br>exampleTask.then(function successValue1(result){<br>    console.log(result);<br>}).then(function successValue2(){<br>    console.log(&#39;You can call multiple functions this way&#39;);<br>});</pre><p>In this example, the promise exampleTask is resolved successfully, and we use the then method to execute the successValue1 function, which logs the resolved result. We can also chain multiple then methods to call multiple functions sequentially.</p><h3>5: Handling Rejection with Catch</h3><pre>let exampleTask = new Promise(function(resolve, reject) {<br>    reject(&#39;Promise rejected&#39;);<br>});<br><br>exampleTask.then(function successValue1(result){<br>    console.log(result);<br>}).catch(function errorValue(result){<br>    console.log(result);<br>});</pre><p>In this example, the promise exampleTask is rejected, and we handle the rejection using the catch method. The errorValue function is executed, logging the rejected result. Using catch allows us to handle errors in a centralized manner.</p><h3>6: Using Finally</h3><pre>let countValue = new Promise(function(resolve, reject) {<br>    reject(&quot;Promise rejected&quot;);<br>});<br><br>countValue.then((success) =&gt; {})<br>    .catch((error) =&gt; {<br>        console.log(error);<br>    })<br>    .finally(function greet(){<br>        console.log(&quot;This code is executed.&quot;);<br>    });</pre><p>The finally method is used to execute a function regardless of whether the promise is resolved or rejected. In this example, the greet function is always executed, regardless of the promise result.</p><h3>7: Chaining Multiple Promises</h3><pre>examplePromiseTask()<br>    .then(function (result) {<br>        return secondTask();<br>    })<br>    .then(function (result) {<br>        return thirdTask(); <br>    })<br>    .catch(function (err) {<br>        // Handle any errors here<br>    });</pre><p>Promises can be chained together to perform multiple asynchronous tasks sequentially. In this example, examplePromiseTask is executed first, followed by secondTask, and then thirdTask. If any promise in the chain is rejected, the catch method is called to handle the error.</p><h3>Using JSONPlaceholder API for Testing</h3><p>To demonstrate the usage of promises with a real API, you can integrate the <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> API into your code examples. JSONPlaceholder provides a set of mock endpoints for testing purposes.</p><p>For example, you can replace doSomething() in Example 3 with an API call:</p><pre>function doSomething() {<br>    return fetch(&#39;https://jsonplaceholder.typicode.com/posts/1&#39;)<br>        .then(response =&gt; response.json());<br>}</pre><p>Similarly, you can modify other examples to include API requests and handle the returned data or errors accordingly.</p><p><strong>Conclusion</strong></p><blockquote>Promises are a powerful tool in JavaScript for managing asynchronous operations. They simplify the handling of asynchronous code and make it easier to reason about complex flows. By understanding and practicing with promises, you can write more efficient and maintainable code in JavaScript.</blockquote><blockquote><em>Happy coding!💻</em></blockquote><p><em>Also if you need more help check this video on </em><a href="https://www.youtube.com/watch?v=novBIqZh4Bk&amp;list=PLf16UKl7nR5ACgsLey93vrcZdKEdVewjp"><strong>Learn JavaScript Promises in 19 minutes (For Beginners)</strong></a><strong> </strong>from Sonny Sanga on Youtube</p><blockquote>Thanks for your time ♥</blockquote><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 Github <a href="https://github.com/Onlynfk">https://github.com/Onlynfk</a>/<br><a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=388df4e6e2c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Django Development: A Comprehensive Guide.]]></title>
            <link>https://medium.com/codex/mastering-django-development-a-comprehensive-guide-ce5526403220?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5526403220</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 14:07:16 GMT</pubDate>
            <atom:updated>2023-06-04T14:07:16.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zRSbGlaEQhsBUJ4S" /><figcaption>Photo by <a href="https://unsplash.com/@faisaldada">Faisal</a> on Unsplash</figcaption></figure><p>Django is a powerful web framework that empowers developers to build robust and scalable web applications efficiently. Whether you’re a beginner or an experienced developer, mastering Django is a valuable skill that opens up a world of possibilities. In this comprehensive guide, we will dive into 10 essential topics that every Django developer should focus on to become proficient in Django web development. Let’s explore these topics in detail:</p><p><strong>Let’s begin!!! 🚀🚀</strong></p><h3>1. Django Framework</h3><ul><li>Understand Django’s architecture, which follows the Model-View-Controller (MVC) pattern.</li><li>Learn how to create Django projects using the django-admin command-line tool and set up the project structure.</li><li>Familiarize yourself with Django applications, which are modular components within a Django project.</li><li>Explore Django’s URL routing system to map URLs to views.</li><li>Understand how to define models using Django’s Object-Relational Mapping (ORM) and perform database operations.</li><li>Create views to handle user requests and generate responses.</li><li>Utilize Django’s template system to render dynamic HTML pages.</li><li>Learn about Django’s built-in middleware and how to handle HTTP requests and responses.</li></ul><h3>2. Django ORM (Object-Relational Mapping):</h3><ul><li>Understand Django’s ORM and its advantages, which abstracts the database layer.</li><li>Define models using Python classes and Django’s field types.</li><li>Learn about model relationships such as one-to-one, one-to-many, and many-to-many.</li><li>Perform CRUD (Create, Read, Update, Delete) operations on database records using the ORM.</li><li>Utilize QuerySets to filter, order, and aggregate data.</li><li>Optimize database performance by understanding database indexing and query optimization techniques.</li><li>Handle transactions and concurrency in Django.</li></ul><h3>3. Django Admin:</h3><ul><li>Explore Django’s built-in admin site and learn how to register models.</li><li>Customize the admin site by overriding templates and defining custom admin classes.</li><li>Create custom admin views to extend the functionality of the admin site.</li><li>Define permissions and restrict access to specific admin sections.</li><li>Understand how to integrate third-party libraries and plugins with the Django admin.</li></ul><h3>4. Authentication and Authorization:</h3><ul><li>Implement user authentication using Django’s built-in authentication system.</li><li>Create user registration and login views.</li><li>Handle user sessions, including login/logout functionality.</li><li>Utilize decorators and mixins to handle user permissions and roles.</li><li>Implement additional authentication methods, such as social login (OAuth).</li></ul><h3>5. Django Forms:</h3><ul><li>Learn how to create forms using Django’s form classes.</li><li>Customize form fields and widgets to suit your application’s requirements.</li><li>Handle form validation and display validation errors to the user.</li><li>Utilize form handling techniques, including form rendering, submission, and processing.</li></ul><h3>6. Django Templates:</h3><ul><li>Understand Django’s template language and its syntax.</li><li>Learn about template inheritance and create reusable templates.</li><li>Utilize template tags and filters to perform logic and manipulate data.</li><li>Pass data to templates using context variables.</li><li>Handle template rendering and display dynamic content.</li></ul><h3>7. Django REST Framework:</h3><ul><li>Learn how to build RESTful APIs using Django REST Framework (DRF).</li><li>Define API endpoints using DRF’s class-based views.</li><li>Implement serialization and deserialization of data using serializers.</li><li>Handle requests and responses, including authentication and authorization.</li><li>Implement pagination, filtering, and sorting in API views.</li><li>Version your APIs to ensure backward compatibility.</li><li>Utilize third-party libraries for API documentation (e.g., Swagger).</li></ul><h3>8. Testing in Django:</h3><ul><li>Understand the importance of testing in Django development.</li><li>Learn about Django’s testing framework and write unit tests for models, views, and forms.</li><li>Implement functional tests to verify the behavior of your application as a whole.</li><li>Use test fixtures to set up test data and simulate different scenarios.</li><li>Explore testing techniques, such as mocking external dependencies and testing edge cases.</li></ul><h3>9. Django Deployment:</h3><ul><li>Learn how to deploy Django applications to production environments.</li><li>Set up and configure web servers like Apache or Nginx o serve Django applications.</li><li>Understand server setup and configuration, including security considerations.</li><li>Optimize Django application performance for production environments.</li><li>Explore deployment options, such as deploying to platforms like Heroku, AWS, or Docker containers.</li><li>Set up continuous integration and deployment (CI/CD) pipelines for automated deployments.</li><li>Implement monitoring and logging for your deployed Django application.</li><li>Understand server setup and configuration, including security considerations.</li><li>Optimize Django application performance for production environments.</li><li>Explore deployment options, such as deploying to platforms like Heroku, AWS, or Docker containers.</li><li>Set up continuous integration and deployment (CI/CD) pipelines for automated deployments.</li><li>Implement monitoring and logging for your deployed Django application.</li></ul><h3>10. Django Best Practices:</h3><ul><li>Stay updated with Django&#39;s best practices and coding conventions.</li><li>Follow the Django project’s official documentation and community recommendations.</li><li>Organize your code using Django’s recommended project structure.</li><li>Implement modular design and adhere to the Don’t Repeat Yourself (DRY) principle.</li><li>Implement security measures, such as protecting against cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.</li><li>Optimize your Django application’s performance, including database query optimization and caching.</li><li>Practice efficient debugging techniques using Django’s logging and debugging tools.</li><li>Implement version control using Git and follow best practices for collaboration and code review.</li><li>Stay updated with the latest Django releases and new features.</li><li>Engage with the Django community through forums, mailing lists, and conferences to learn from others and share knowledge.|</li></ul><p>Mastering Django development requires dedication, practice, and continuous learning. By focusing on these 10 essential topics, you’ll build a strong foundation in Django and gain the skills necessary to develop complex web applications. Remember, the Django ecosystem is vast, and there’s always more to explore beyond these core topics. Engage with the <a href="https://www.djangoproject.com/community/">Django community,</a> work on real-world projects, and keep up with the latest advancements to enhance your Django expertise. <br><br>Also, here are a few other articles related to mastering Django below, do check them out 👇</p><ol><li><a href="https://www.twilio.com/blog/building-a-blog-with-django-3-and-deploying-to-heroku">Building a Blog with Django 3 and Deploying to Heroku</a></li><li><a href="https://www.twilio.com/blog/how-to-build-a-chatbot-with-django-and-chatfuel">How to Build a Chatbot with Django and Chatfuel</a></li><li><a href="https://www.twilio.com/blog/how-to-build-a-django-api-in-2021">How to Build a Django API in 2021: A Simple Guide</a></li><li><a href="https://www.twilio.com/blog/building-a-restful-api-with-django-rest-framework">Building a RESTful API with Django Rest Framework</a></li><li><a href="https://www.twilio.com/blog/django-channels-tutorial-websockets-made-easy">Django Channels Tutorial: Websockets Made Easy</a></li><li><a href="https://www.twilio.com/blog/how-to-build-a-real-time-chat-application-with-django-and-pusher">Building a Real-Time Chat Application with Django and Pusher</a></li><li><a href="https://www.twilio.com/blog/how-to-add-two-factor-authentication-to-django">How to Add Two-Factor Authentication to Django</a></li><li><a href="https://www.twilio.com/blog/building-a-search-engine-with-django-and-elasticsearch">Building a Search Engine with Django and Elasticsearch</a></li><li><a href="https://www.twilio.com/blog/how-to-build-a-url-shortener-with-django">How to Build a URL Shortener with Django</a></li><li><a href="https://www.twilio.com/blog/django-and-react-tutorial-building-a-social-network">Django and React Tutorial: Building a Social Network</a></li></ol><p>Happy coding! 💻</p><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 <a href="https://github.com/Onlynfk/">Github</a> / <a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><p>Thanks for your time ♥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5526403220" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/mastering-django-development-a-comprehensive-guide-ce5526403220">Mastering Django Development: A Comprehensive Guide.</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 5 JavaScript Libraries and Frameworks for 2023]]></title>
            <link>https://medium.com/codex/top-5-javascript-libraries-and-frameworks-for-2023-c2bf04138144?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bf04138144</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Sat, 27 May 2023 12:37:08 GMT</pubDate>
            <atom:updated>2023-05-27T12:37:08.756Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript has become one of the most popular programming languages used today. To keep up with the latest trends and stay ahead of the competition, knowing the top JavaScript libraries and frameworks for 2023 is essential. Here are the top five JavaScript libraries and frameworks for 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SjTH2zCxDvi1UGvM" /><figcaption>Photo by Arnold Francisca on Unsplash</figcaption></figure><h3>Let’s dive in!!! 🚀🚀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*MO66ccgxHr9CLEKx" /></figure><h3>1. React</h3><p>React is one of the most popular JavaScript libraries used for building user interfaces. It is maintained by Facebook and used by companies such as Netflix, Airbnb, and Instagram. React provides a simple programming model and is very efficient in rendering dynamic web applications. According to statistics from <a href="https://www.npmtrends.com/react-vs-angular-vs-vue-vs-svelte">npm trends</a>, React has over 1.5 million weekly downloads, making it the most popular JavaScript library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*OuulOYA_KiK7x9Mn" /></figure><h3>2. Angular</h3><p>Angular is a popular JavaScript framework for building web applications. It is maintained by Google and used by companies such as Microsoft, IBM, and Apple. Angular provides a comprehensive set of features and tools for building complex and scalable web applications. According to statistics from <a href="https://www.npmtrends.com/react-vs-angular-vs-vue-vs-svelte">npm trends</a>, Angular has over 800,000 weekly downloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*DariUgkFCdaJC-8D" /></figure><h3>3. Vue.js</h3><p>Vue.js is a lightweight JavaScript framework for building web applications. It is maintained by Evan You and used by companies such as Xiaomi, Alibaba, and GitLab. Vue.js provides a simple and easy-to-learn programming model, making it an excellent choice for beginners. According to statistics from <a href="https://www.npmtrends.com/react-vs-angular-vs-vue-vs-svelte">npm trends</a>, Vue.js has over 600,000 weekly downloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*3zGZjOx86OUvwzo0.png" /></figure><h3>4. Svelte</h3><p>Svelte is a new JavaScript framework that has gained popularity in recent years. It provides a unique approach to building web applications by compiling the code at build time. This approach results in faster loading times and better performance. According to statistics from <a href="https://www.npmtrends.com/react-vs-angular-vs-vue-vs-svelte">npm trends</a>, Svelte has over 100,000 weekly downloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*BoN3AEOYWFkKKurXTfVLZw.png" /></figure><h3>5. Ember.js</h3><p>Ember.js is a JavaScript framework for building complex web applications. It is maintained by the Ember.js core team and used by companies like LinkedIn, Netflix, and Yahoo. Ember.js provides a set of conventions and best practices for building scalable and maintainable web applications. According to statistics from <a href="https://www.npmtrends.com/react-vs-angular-vs-vue-vs-svelte">npm trends</a>, Ember.js has over 40,000 weekly downloads.</p><h3>Comparison and Statistics</h3><p>Here is a comparison based on their weekly downloads according to <a href="https://www.npmtrends.com/react-vs-angular-vs-vue-vs-svelte">npm trends</a>.</p><p>Library/Framework - Weekly Downloads</p><p>React - 1.5 million</p><p>Angular - 800,000</p><p>Vue.js - 600,000</p><p>Svelte -100,000</p><p>Ember.js - 40,000</p><p>There are so many other frameworks apart from these, but picking should depend on the project you are working on. Consider the project requirements, scalability, performance, and ease of use before selecting a library or framework.</p><p>Keep coding 💻</p><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 <a href="https://github.com/Onlynfk/">Github</a> / <a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><p>Thanks for your time ♥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bf04138144" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/top-5-javascript-libraries-and-frameworks-for-2023-c2bf04138144">Top 5 JavaScript Libraries and Frameworks for 2023</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Essential Topics for Python Beginners: A Comprehensive Guide]]></title>
            <link>https://onlygod.medium.com/10-essential-topics-for-python-beginners-a-comprehensive-guide-20accca28ee5?source=rss-d251dffada9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/20accca28ee5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[OnlyGod Ovbije]]></dc:creator>
            <pubDate>Sat, 27 May 2023 10:01:39 GMT</pubDate>
            <atom:updated>2023-05-27T10:01:39.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is a beginner-friendly programming language that is versatile and easy to read. This blog post covers 20 essential topics for beginners, from variables and data types to file handling and web scraping. Learning Python is a great foundation for beginners to programming and can lead to exciting opportunities in the programming world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*MUCoruLfb4kkV9T0" /><figcaption>Photo by <a href="https://unsplash.com/@pakata">Pakata Goh</a> from Unsplash</figcaption></figure><p><strong>Let’s dive in!!! 🚀🚀</strong></p><h3>1. Variables and Data Types:</h3><p>Variables and data types are fundamental concepts in Python. Understanding how to declare variables and work with different data types such as numbers, strings, and booleans is crucial for any programming endeavor.</p><h3><strong>2. Control Flow and Loops:</strong></h3><p>Learn about conditional statements like if-else and loops such as for and while loops. Mastering control flow will enable you to execute code selectively and repeatedly based on certain conditions.</p><h3>3. Functions and Modules:</h3><p>Functions allow you to break down your code into reusable blocks, while modules provide a way to organize and reuse related functions. Discover the power of functions and how to import and use modules in your projects.</p><h3>4. File Handling:</h3><p>Explore how to read from and write to files using Python. Learn essential file-handling operations such as opening, closing, reading, and writing data to files.</p><h3>5. Exception Handling:</h3><p>Discover how to handle errors and exceptions in your code gracefully. Gain insights into try-except blocks, raise statements, and handling specific exceptions.</p><h3>6. Object-Oriented Programming (OOP):</h3><p>Dive into the world of OOP and learn about classes, objects, inheritance, and polymorphism. OOP allows you to create more organized and scalable code.</p><h3>7. Data Structures:</h3><p>Explore essential data structures like arrays, lists, stacks, queues, and linked lists. Understand their properties, use cases, and how to implement them in Python.</p><h3>8. Regular Expressions:</h3><p>Master the art of pattern matching and text manipulation using regular expressions. Learn how to search, match, and substitute patterns within strings effectively.</p><h3>9. Database Connectivity:</h3><p>Discover how to connect Python with databases, such as SQLite and MySQL. Learn the basics of executing queries, fetching data, and performing CRUD operations.</p><h3>10. Introduction to Web Development:</h3><p>Get a glimpse into web development with Python. Learn about frameworks like Flask and Django, and understand how to build simple web applications.</p><p>That’s it you can check other topics here</p><ol><li><a href="https://realpython.com/python-beginner-tips/">&quot;Python for Beginners&quot; by Real Python</a></li><li><a href="https://www.python.org/about/gettingstarted/">&quot;Python Basics&quot; by Python.org</a></li><li><a href="https://www.w3schools.com/python/">&quot;Python Tutorial&quot; by W3Schools</a></li><li><a href="https://www.programiz.com/python-programming/variables-datatypes">&quot;Python Data Types&quot; by Programiz</a></li><li><a href="https://www.datacamp.com/community/tutorials/control-flow-python">&quot;Control Flow in Python&quot; by DataCamp</a></li><li><a href="https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions">&quot;Python Functions&quot; by Codecademy</a></li><li><a href="https://realpython.com/python3-object-oriented-programming/">&quot;Object-Oriented Programming in Python&quot; by Real Python</a></li><li><a href="https://www.pythonforbeginners.com/error-handling/python-exceptions">&quot;Python Exceptions&quot; by PythonForBeginners</a></li><li><a href="https://www.pythonfordatascience.org/python-libraries/">&quot;Python Libraries&quot; by PythonForDataScience</a></li><li><a href="https://data-flair.training/blogs/python-project-ideas-beginners/">&quot;Python Projects for Beginners&quot; by DataFlair</a></li></ol><p>Happy coding! 💻</p><h3>Where to find Me 👇</h3><p>Here on <a href="https://onlygod.medium.com/">Medium </a>♥️</p><p>You can also find me also 👉 <a href="https://github.com/Onlynfk/">Github</a> / <a href="https://www.instagram.com/onlyg.codes/">Instagram</a> / <a href="https://www.linkedin.com/in/onlygod-o-b64084166/">LinkedIn</a></p><p>Thanks for your time ♥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20accca28ee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>