<?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 Fırat/Mustafa Özcan on Medium]]></title>
        <description><![CDATA[Stories by Fırat/Mustafa Özcan on Medium]]></description>
        <link>https://medium.com/@firatozc555?source=rss-c695730a8e39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0zm04JLj-uLvzi952BlJ3Q.jpeg</url>
            <title>Stories by Fırat/Mustafa Özcan on Medium</title>
            <link>https://medium.com/@firatozc555?source=rss-c695730a8e39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:10:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@firatozc555/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[Test Automation in Django: Unit Tests, Integration Tests, and Coverage Analysis]]></title>
            <link>https://medium.com/@firatozc555/test-automation-in-django-unit-tests-integration-tests-and-coverage-analysis-b3cd514e6b72?source=rss-c695730a8e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3cd514e6b72</guid>
            <category><![CDATA[django-tests]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[coverage]]></category>
            <category><![CDATA[integration-test]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fırat/Mustafa Özcan]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 12:21:30 GMT</pubDate>
            <atom:updated>2024-09-26T12:21:30.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why is Test Automation Important?</h3><p>Relying solely on manual testing while developing can be both time-consuming and prone to errors. As your application grows in complexity, it becomes unrealistic to test everything manually after each change. This is where <strong>test automation</strong> becomes indispensable, allowing your software to be consistently tested without human intervention. Django makes writing tests easy with its seamless integration with Python’s powerful <strong>unittest</strong> module.</p><p>Tests can generally be categorized into three main types: <strong>unit tests</strong>, <strong>integration tests</strong>, and tests backed by <strong>coverage analysis</strong>. Let’s dive into each of these concepts and see how they can be applied in Django.</p><h3><strong>1. Unit Tests: Strengthening the Foundation of Your Code</strong></h3><p><strong>Unit tests</strong> focus on testing the smallest components of your code, such as individual functions, classes, or methods in isolation. Since unit tests are isolated, they are usually fast and effective in ensuring the basic functionality of your code.</p><h4>Writing Unit Tests in Django</h4><p>Django makes it simple to write unit tests based on the <strong>unittest</strong> module. For example, let&#39;s assume we have a simple <strong>Post</strong> model in a blog application:</p><pre>from django.db import models<br><br>class Post(models.Model):<br>    title = models.CharField(max_length=200)<br>    content = models.TextField()<br>    published_at = models.DateTimeField(auto_now_add=True)<br><br>    def __str__(self):<br>        return self.title</pre><p>We can write a unit test for this <strong>Post</strong> model as follows:</p><pre>from django.test import TestCase<br>from .models import Post<br><br>class PostModelTest(TestCase):<br>    def test_string_representation(self):<br>        post = Post(title=&quot;Test Title&quot;)<br>        self.assertEqual(str(post), post.title)</pre><p>Here, we are simply testing the <strong>__str__()</strong> method of the <strong>Post </strong>model. The test will pass if the <strong>title</strong> field returns correctly.</p><p>To run the tests in Django, you can use the command python manage.py test. This command will automatically discover and run all the tests in your project, displaying the results in your terminal.</p><h3>2. Integration Tests: Testing the Components Together</h3><p>While unit tests focus on isolated parts of your code, <strong>integration tests</strong> ensure that these components work together as expected. For instance, integration tests can be used to check if a form processes data correctly or if an API endpoint returns the expected results.</p><p>In Django, integration tests are often written for <strong>views</strong> and <strong>forms</strong>. Let’s write an integration test for a simple blog post creation form.</p><h4>Form Testing:</h4><pre>from django.test import TestCase<br>from .forms import PostForm<br><br>class PostFormTest(TestCase):<br>    def test_post_form_valid(self):<br>        form_data = {&#39;title&#39;: &#39;Test Title&#39;, &#39;content&#39;: &#39;Test content&#39;}<br>        form = PostForm(data=form_data)<br>        self.assertTrue(form.is_valid())<br>    <br>    def test_post_form_invalid(self):<br>        form_data = {&#39;title&#39;: &#39;&#39;, &#39;content&#39;: &#39;Missing title&#39;}<br>        form = PostForm(data=form_data)<br>        self.assertFalse(form.is_valid())</pre><p>In this test, we’re validating two cases: one where the form is valid (title and content are provided), and one where the form is invalid (the title is missing). This ensures that our form behaves as expected in both scenarios.</p><h4>View Testing:</h4><pre>from django.urls import reverse<br>from django.test import TestCase<br>from .models import Post<br><br>class PostViewTest(TestCase):<br>    def test_post_list_view(self):<br>        response = self.client.get(reverse(&#39;post_list&#39;))<br>        self.assertEqual(response.status_code, 200)<br>        self.assertContains(response, &quot;Blog Posts&quot;)<br><br>    def test_post_create_view(self):<br>        data = {&#39;title&#39;: &#39;New Title&#39;, &#39;content&#39;: &#39;New content&#39;}<br>        response = self.client.post(reverse(&#39;post_create&#39;), data)<br>        self.assertEqual(response.status_code, 302)  # Redirect after creation<br>        self.assertEqual(Post.objects.count(), 1)</pre><p>In these tests, we check whether a view returns the correct HTTP response and if data submitted through a form is successfully saved to the database. The <strong>self.client</strong> object is a Django test client that allows us to make HTTP requests within our tests.</p><h3>3. Coverage Analysis: Measuring the Scope of Your Tests</h3><p>Writing tests is important, but it’s equally crucial to know how much of your codebase is actually being tested. This is where <strong>Coverage Analysis</strong> comes into play. Tools like coverage.py can be used in Django projects to measure which parts of your code are tested and which are not.</p><h4>Setting Up Coverage</h4><p>First, you need to install coverage.py:</p><pre>pip install coverage</pre><p>Then, you can run your tests with coverage tracking:</p><pre>coverage run manage.py test<br>coverage report</pre><p>This will execute your tests and show a report of the test coverage. For a more detailed report, you can generate an HTML file:</p><pre>coverage html</pre><p>This will create a detailed HTML report where you can visually inspect which files, functions, or lines are covered by tests and which are missed.</p><h3>Conclusion: Build a Robust Application with Test Automation</h3><p>Test automation in Django is a powerful way to make sure your application is both reliable and maintainable. With <strong>unit tests</strong>, you can ensure the correctness of individual components, while <strong>integration tests</strong> validate that these components work well together. By supporting your testing process with <strong>coverage analysis</strong>, you can track how much of your code is tested and ensure that you aren’t missing critical parts of your application.</p><p>Remember, well-tested code gives you the confidence to iterate and refactor without fear of breaking things. Make testing a natural part of your development process, and always ensure you’re writing sufficient tests for every new feature or change. Your future self (and your users) will thank you for it.</p><p>Thanks For Reading Till Here, If You Like My Content and Want To Support Me The Best Way is —</p><p>Leave a Clap👋and your thoughts 💬 below.<br>Follow Me On <a href="https://medium.com/@firatozc555">Medium</a>.<br>Connect With Me On <a href="https://www.linkedin.com/in/f%C4%B1rat-%C3%B6zcan-208578216/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3cd514e6b72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transitioning to Microservices with Django: From Monolith to Microservices]]></title>
            <link>https://medium.com/@firatozc555/transitioning-to-microservices-with-django-from-monolith-to-microservices-91356528fc02?source=rss-c695730a8e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/91356528fc02</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[django-architecture]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fırat/Mustafa Özcan]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 18:20:53 GMT</pubDate>
            <atom:updated>2024-09-23T18:20:53.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWqlfVm9fbEtiKEIY7ZoXg.png" /></figure><p>Django is one of the most popular web frameworks in the Python ecosystem. It is typically used in a <strong>monolithic architecture</strong>, where all components of an application are bundled together. This approach is great for small to medium projects as it provides rapid development and ease of management. However, as projects grow and become more complex, monolithic architectures can present challenges, particularly in scalability and flexibility.</p><p>So, what should you do when you encounter these challenges? <strong>Microservices architecture</strong> comes to the rescue. It offers greater flexibility, independent services, and better scalability, making it a more suitable architecture for large, complex applications. In this article, we will explore the process of transitioning a Django monolith to a <strong>microservices architecture</strong>.</p><h3>What is Monolithic Architecture?</h3><p>A <strong>monolithic architecture</strong> is a software design where all components are tightly coupled and run as a single, unified system. In the case of Django, this is the default approach. For instance, in an e-commerce app, user management, product catalog, payment processing, and order tracking would all be part of the same codebase. This architecture is often preferred for small applications due to several advantages:</p><ol><li><strong>Simplicity in development and management</strong>.</li><li><strong>Direct integration between components</strong>.</li><li><strong>Quick prototyping</strong> using a single database and application server.</li></ol><p>However, as your application grows, you may encounter some disadvantages:</p><ul><li><strong>Scalability issues</strong>: You need to scale the entire system, not just the parts with high traffic.</li><li><strong>Harder to maintain</strong>: Changes in one part of the system can unintentionally affect others.</li><li><strong>Increased dependencies</strong>: Teams may need to work on intertwined code, slowing down development.</li></ul><p>This is where <strong>microservices architecture</strong> becomes a compelling alternative.</p><h3>What is Microservices Architecture?</h3><p>Microservices architecture is an approach where each core function of an application is built as an independent service. These services can communicate with each other but remain loosely coupled. Compared to monolithic architecture, microservices offer several key benefits:</p><ul><li><strong>Independent scalability</strong>: You can scale individual services as needed.</li><li><strong>Independent deployment</strong>: Each service can be updated and deployed independently.</li><li><strong>Technology flexibility</strong>: You can use different technologies or databases for different services.</li><li><strong>Faster development</strong>: Teams can work on different microservices without stepping on each other’s toes.</li></ul><p>These advantages are especially valuable for large, growing applications. However, transitioning to microservices comes with its own set of challenges.</p><h3>Transitioning from Monolith to Microservices with Django</h3><p>Although Django was designed with monolithic applications in mind, it’s possible to transition to a microservices architecture. Here’s how you can successfully make the switch:</p><h4>1. Analyze Your Monolith</h4><p>Before starting the transition, carefully analyze your current monolithic application. Identify which components can be separated into microservices. For example, <strong>user management</strong>, <strong>product catalog</strong>, and <strong>order processing</strong> are typically good candidates for microservices. Breaking down your monolith into discrete domains is the first critical step.</p><h4>2. Database Decoupling</h4><p>In a monolithic architecture, you often have a single database. However, in a microservices architecture, each service should manage its own database. This ensures <strong>data independence</strong> and allows each microservice to function autonomously. Django’s ORM supports the management of multiple databases, which you can configure in the <strong>DATABASES</strong> setting. Each microservice should be linked to its own dedicated database for maximum separation.</p><h4>3. API-Based Communication</h4><p>Once you’ve separated your services, they need a way to communicate. This is where <strong>APIs</strong> come into play. <strong>Django Rest Framework (DRF)</strong> is an excellent tool for building RESTful APIs between services. Alternatively, you can use <strong>gRPC</strong> or <strong>GraphQL</strong> for more efficient and scalable communication if needed.</p><h4>4. Service Discovery and Load Balancing</h4><p>With multiple services running, service discovery and load balancing become important considerations. Tools like <strong>Kubernetes</strong> provide orchestration, enabling services to discover each other and balance loads efficiently. Kubernetes also handles auto-scaling, service health checks, and restarting failed services, making it a powerful solution for managing a microservices architecture.</p><h4>5. Asynchronous Communication with Messaging Systems</h4><p>In a monolithic system, everything often happens synchronously. However, in a microservices architecture, many tasks can and should be <strong>asynchronous</strong> for improved performance and flexibility. Django supports asynchronous task processing through tools like <strong>Celery</strong>. You can also implement <strong>message brokers</strong> like <strong>RabbitMQ</strong> or <strong>Kafka</strong> to enable message-based communication between microservices.</p><h4>6. Independent Deployment with CI/CD</h4><p>After splitting your application into microservices, each service should have its own deployment pipeline. This is where <strong>CI/CD pipelines</strong> come into play. You can use <strong>Docker</strong> to containerize each Django service, making deployment isolated and easier to manage.</p><h3>Challenges of Transitioning to Microservices</h3><p>While microservices offer many advantages, the transition is not without its difficulties:</p><ul><li><strong>Service dependencies</strong>: Ensuring that microservices can communicate properly without creating tight coupling is challenging.</li><li><strong>Data consistency</strong>: In a monolith, maintaining data consistency is straightforward. In microservices, each service has its own database, and ensuring consistent data across services requires careful planning.</li><li><strong>Testing and debugging</strong>: Testing and debugging become more complex in a distributed system. Each service needs to be tested independently, and integration tests are critical.</li><li><strong>Management and orchestration</strong>: Managing and orchestrating numerous services can be overwhelming. Tools like <strong>Kubernetes</strong> help, but they come with their own learning curves.</li></ul><h3><strong>Conclusion</strong></h3><p>Transitioning from a monolith to microservices is a significant but rewarding change, particularly for large-scale, complex applications. Even with Django’s roots in monolithic development, it’s entirely possible to move to a microservices architecture. However, careful planning is necessary to decouple your data, structure communication between services, and manage the new complexity introduced by distributed systems.</p><p>Microservices architecture offers scalability, flexibility, and independent development, helping ensure the long-term success of your application. That said, this transition requires a solid understanding of the new challenges it brings, along with the right tools to manage these challenges.</p><p>Thanks For Reading Till Here, If You Like My Content and Want To Support Me The Best Way is —</p><p>Leave a Clap👋and your thoughts 💬 below.<br>Follow Me On <a href="https://medium.com/@firatozc555">Medium</a>.<br>Connect With Me On <a href="https://www.linkedin.com/in/f%C4%B1rat-%C3%B6zcan-208578216/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91356528fc02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adversarial Validation]]></title>
            <link>https://medium.com/@firatozc555/adversarial-validation-20545e865610?source=rss-c695730a8e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/20545e865610</guid>
            <dc:creator><![CDATA[Fırat/Mustafa Özcan]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 16:14:46 GMT</pubDate>
            <atom:updated>2024-09-22T16:14:46.195Z</atom:updated>
            <content:encoded><![CDATA[<h4>Adversarial Validation to reduce overfitting</h4><h3>What is Adversarial Validation?</h3><p>Adversarial validation is a machine learning technique used to detect differences between training and test datasets in order to assess if they are drawn from different distributions. It is particularly beneficial in scenarios where there is a mismatch between these datasets, which can negatively impact model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*nReYRvLT8GrpqhSOWpuaZw.png" /></figure><h3>How Adversarial Validation Works:</h3><ol><li><strong>Combine Training and Test Data</strong>: Combine the training and test data, but without the target labels. Create a new binary label indicating whether each data point belongs to the training set (label 0) or the test set (label 1).</li><li><strong>Train a Classifier</strong>: Train a classifier (such as a logistic regression or decision tree) to distinguish between training data and test data using this new label.</li><li><strong>Check Classifier Performance</strong>: If the classifier performs well, it means the training and test sets are distinguishable, indicating a distributional difference between them. For example, if the classifier can easily separate the two datasets, the test data might have features or patterns that don’t exist in the training data.</li><li><strong>Interpretation</strong>:</li></ol><ul><li><strong>High Accuracy</strong>: The model can easily differentiate between training and test datasets, suggesting a problem with data distribution or potential data leakage.</li><li><strong>Low Accuracy</strong>: If the classifier struggles, this indicates that the training and test sets come from similar distributions.</li></ul><h3>Learning the Adversarial Validation model</h3><p>First, some boilerplate import statements to avoid confusion:</p><pre>import numpy as np<br>import pandas as pd<br>import xgboost as xgb<br>from xgboost import XGBClassifier<br>from xgboost import plot_importance<br>from xgboost import cv<br>import matplotlib.pyplot as plt<br>plt.rcParams.update({&#39;font.size&#39;: 12})</pre><pre># read in the data<br>train = pd.read_csv(&quot;titanic/train.csv&quot;)<br>test  = pd.read_csv(&quot;titanic/test.csv&quot;)<br><br># select only the numerical features<br>X_test  = test.select_dtypes(include=[&#39;number&#39;]).copy()<br>X_train = train.select_dtypes(include=[&#39;number&#39;]).copy()<br><br># drop the target column from the training data<br>X_train = X_train.drop([&#39;Survived&#39;], axis=1)<br><br># add the train/test labels<br>X_train[&quot;AV_label&quot;] = 0<br>X_test[&quot;AV_label&quot;]  = 1<br><br># make one big dataset<br>all_data = pd.concat([X_train, X_test], axis=0, ignore_index=True)<br><br># shuffle<br>all_data_shuffled = all_data.sample(frac=1)<br><br># create our DMatrix (the XGBoost data structure)<br>X = all_data_shuffled.drop([&#39;AV_label&#39;], axis=1)<br>y = all_data_shuffled[&#39;AV_label&#39;]<br>XGBdata = xgb.DMatrix(data=X,label=y)<br><br># our XGBoost parameters<br>params = {&quot;objective&quot;:&quot;binary:logistic&quot;,<br>          &quot;eval_metric&quot;:&quot;logloss&quot;,<br>          &#39;learning_rate&#39;: 0.05,<br>          &#39;max_depth&#39;: 5, }<br><br># perform cross validation with XGBoost<br>cross_val_results = cv(dtrain=XGBdata, params=params, <br>                       nfold=5, metrics=&quot;auc&quot;, <br>                       num_boost_round=200,early_stopping_rounds=20,<br>                       as_pandas=True)<br><br># print out the final result<br>print((cross_val_results[&quot;test-auc-mean&quot;]).tail(1))</pre><pre>0    <strong>0.998074</strong><br>Name: test-auc-mean, dtype: float64</pre><p>We can see an AUC of 1 which indicates that our classifier is able to perfectly distinguish between the original training and test data. Let us look at the most important features:</p><pre>classifier = XGBClassifier(eval_metric=&#39;logloss&#39;,use_label_encoder=False)<br>classifier.fit(X, y)<br>fig, ax = plt.subplots(figsize=(12,4))<br>plot_importance(classifier, ax=ax)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*ZSMVz1n8in_ifkSjh5McHw.png" /></figure><p>This was actually to be expected since we did not drop the PassengerId column. Our classifier has learned that the distribution of values of this feature are very different for the train and test rows. Let us drop the PassengerId column and re-calculate the ROC.</p><pre>X = X.drop([&#39;PassengerId&#39;], axis=1)</pre><pre>XGBdata = xgb.DMatrix(data=X,label=y)<br>cross_val_results = cv(dtrain=XGBdata, params=params, <br>                       nfold=5, metrics=&quot;auc&quot;, <br>                       num_boost_round=200,early_stopping_rounds=20,<br>                       as_pandas=True)<br><br>print((cross_val_results[&quot;test-auc-mean&quot;]).tail(1))</pre><pre>25    <strong>0.534496</strong><br>Name: test-auc-mean, dtype: float64</pre><p>we now have a much more reasonable value, much closer to our ideal value of 0.5</p><p>Thanks For Reading Till Here, If You Like My Content and Want To Support Me The Best Way is —</p><p>Leave a Clap👋and your thoughts 💬 below.<br>Follow Me On <a href="https://medium.com/@firatozc555">Medium</a>.<br>Connect With Me On <a href="https://www.linkedin.com/in/f%C4%B1rat-%C3%B6zcan-208578216/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20545e865610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorization in Django: JWT, OAuth2, and Social Auth Integrations]]></title>
            <link>https://medium.com/@firatozc555/authentication-and-authorization-in-django-jwt-oauth2-and-social-auth-integrations-57995fd8aa74?source=rss-c695730a8e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/57995fd8aa74</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Fırat/Mustafa Özcan]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 14:53:13 GMT</pubDate>
            <atom:updated>2024-09-21T14:53:13.975Z</atom:updated>
            <content:encoded><![CDATA[<p>We will explore how to handle authentication and authorization in Django projects by integrating JWT (JSON Web Token), OAuth2, and Social Authentication. Designed for intermediate and advanced developers, this deep dive will show you how to enhance security in your Django applications.</p><h3>What Are Authentication and Authorization?</h3><p>Let’s first clarify two important concepts:</p><ol><li><strong>Authentication</strong>: The process of verifying the identity of a user. This is usually done via a username and password combination, but modern approaches can use OAuth2, JWT, or social media accounts.</li><li><strong>Authorization</strong>: Once a user’s identity is verified, authorization determines what resources the user is allowed to access.</li></ol><p>Django comes with built-in tools for both, but in modern applications, it’s essential to integrate additional techniques to enhance security. Let’s explore how to do that with JWT, OAuth2, and Social Auth.</p><h3>JWT Integration with Django Rest Framework (DRF)</h3><p><strong>JWT (JSON Web Token)</strong> is a popular mechanism for authenticating users in modern web applications. It allows secure transmission of authentication and authorization data between the client and server.</p><h3>Why Use JWT?</h3><ul><li><strong>Stateless</strong>: Unlike traditional session-based authentication, JWT does not require the server to maintain user session information.</li><li><strong>High Performance</strong>: JWT improves performance, especially in scalable applications.</li><li><strong>Secure</strong>: JWT tokens are signed with HMAC or RSA, making them tamper-proof.</li></ul><h3>How to Implement JWT in Django?</h3><p>To implement JWT in Django, the most common package is <strong>djangorestframework-simplejwt</strong>. This package integrates seamlessly with the Django Rest Framework (DRF).</p><p><strong>First, install the required package:</strong></p><pre>pip install djangorestframework-simplejwt</pre><p>Next, add the necessary configuration to <strong>settings.py</strong>:</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;rest_framework&#39;,<br>]<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>    ),<br>}</pre><p>Now, create the views for token issuance and token refresh:</p><pre>from rest_framework_simplejwt.views import (<br>    TokenObtainPairView,<br>    TokenRefreshView,<br>)<br><br>urlpatterns = [<br>    path(&#39;api/token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),<br>    path(&#39;api/token/refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),<br>]</pre><p>Once configured, your application will support JWT-based authentication. When a user logs in, a JWT token is generated, which can be used in subsequent requests for authentication and authorization.</p><h3>OAuth2 for Authorization</h3><p>OAuth2 is a widely used authorization protocol in modern web applications. It allows users to authenticate through third-party services (such as Google or Facebook) and manage authorization based on those external identities.</p><p>For Django, the most common tools to support OAuth2 are <strong>django-allauth</strong> and <strong>django-oauth-toolkit</strong>. These libraries provide OAuth2 authentication and authorization in your applications.</p><h3>How to Implement OAuth2 in Django?</h3><ol><li>First, install the <strong>django-oauth-toolkit</strong> and <strong>django-rest-framework</strong> packages:</li></ol><pre>pip install django-oauth-toolkit</pre><p>2. Add the required apps to your <strong>INSTALLED_APPS</strong>:</p><pre>INSTALLED_APPS = [<br>    &#39;oauth2_provider&#39;,<br>    &#39;rest_framework&#39;,<br>]</pre><p>3. Configure OAuth2 in your <strong>settings.py</strong>:</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;oauth2_provider.contrib.rest_framework.OAuth2Authentication&#39;,<br>    ),<br>}</pre><p>After setting up OAuth2, you can allow users to authenticate via external services, making your app more versatile and secure.</p><h3>Social Auth with Django-Allauth</h3><p>If you want to let users log in using their Google, Facebook, or Twitter accounts, you can use the <strong>django-allauth</strong> package. Social Authentication makes the login and registration processes quicker and enhances the user experience.</p><h3>How to Implement Social Auth with Django-Allauth?</h3><ol><li>Install the django-allauth package:</li></ol><pre>pip install django-allauth</pre><p>2. Add the necessary apps to your INSTALLED_APPS in settings.py:</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;allauth&#39;,<br>    &#39;allauth.account&#39;,<br>    &#39;allauth.socialaccount&#39;,<br>    &#39;allauth.socialaccount.providers.google&#39;,  # Add other providers as needed<br>]</pre><p>3. Include the allauth URLs in your urls.py file:</p><pre>urlpatterns = [<br>    path(&#39;accounts/&#39;, include(&#39;allauth.urls&#39;)),<br>]</pre><p>4. Set up your provider-specific configurations in <strong>settings.py</strong>. For example, to integrate Google:</p><pre>SOCIALACCOUNT_PROVIDERS = {<br>    &#39;google&#39;: {<br>        &#39;SCOPE&#39;: [<br>            &#39;profile&#39;,<br>            &#39;email&#39;,<br>        ],<br>        &#39;AUTH_PARAMS&#39;: {<br>            &#39;access_type&#39;: &#39;online&#39;,<br>        },<br>    }<br>}</pre><p>With social authentication enabled, users can log in with their social media accounts, improving both speed and security.</p><h3>Conclusion</h3><p>In this article, we explored how to integrate modern authentication and authorization techniques in Django using JWT, OAuth2, and Social Auth. Each method serves different purposes:</p><ul><li><strong>JWT</strong>: Ideal for stateless authentication in microservice architectures.</li><li><strong>OAuth2</strong>: Perfect for managing authorization through third-party providers.</li><li><strong>Social Auth</strong>: Enhances the user experience by allowing social media logins.</li></ul><p>Thanks For Reading Till Here, If You Like My Content and Want To Support Me The Best Way is —</p><p>Leave a Clap👋and your thoughts 💬 below.<br>Follow Me On <a href="https://medium.com/@firatozc555">Medium</a>.<br>Connect With Me On <a href="https://www.linkedin.com/in/f%C4%B1rat-%C3%B6zcan-208578216/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57995fd8aa74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing APIs with Django Rest Framework (DRF): Basic and Advanced Techniques]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Django Rest FrameWork (DRF) is a powerful toolkit built on Django, specifically designed for building web APIs. We will explore both the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@firatozc555/developing-apis-with-django-rest-framework-drf-basic-and-advanced-techniques-7b70d93c3345?source=rss-c695730a8e39------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@firatozc555/developing-apis-with-django-rest-framework-drf-basic-and-advanced-techniques-7b70d93c3345?source=rss-c695730a8e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b70d93c3345</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Fırat/Mustafa Özcan]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 14:22:36 GMT</pubDate>
            <atom:updated>2024-09-20T14:22:36.105Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Ordinal Encoding vs LabelEncoding vs OneHotEncoding]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@firatozc555/ordinal-encoding-vs-labelencoding-vs-onehotencoding-6422223a7038?source=rss-c695730a8e39------2"><img src="https://cdn-images-1.medium.com/max/1099/1*t5UGfH9zokBIHa-IfuakxA.png" width="1099"></a></p><p class="medium-feed-snippet">In machine learning, encoding categorical variables is a crucial preprocessing step.</p><p class="medium-feed-link"><a href="https://medium.com/@firatozc555/ordinal-encoding-vs-labelencoding-vs-onehotencoding-6422223a7038?source=rss-c695730a8e39------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@firatozc555/ordinal-encoding-vs-labelencoding-vs-onehotencoding-6422223a7038?source=rss-c695730a8e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/6422223a7038</guid>
            <category><![CDATA[preprocesing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Fırat/Mustafa Özcan]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 17:55:31 GMT</pubDate>
            <atom:updated>2024-09-19T17:55:31.261Z</atom:updated>
        </item>
    </channel>
</rss>