<?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 Sarath Ravi on Medium]]></title>
        <description><![CDATA[Stories by Sarath Ravi on Medium]]></description>
        <link>https://medium.com/@ravisarath64?source=rss-a6e561985cdb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RM-k0XpdmAgYopchBjtodg@2x.jpeg</url>
            <title>Stories by Sarath Ravi on Medium</title>
            <link>https://medium.com/@ravisarath64?source=rss-a6e561985cdb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:28:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ravisarath64/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[ Tips to Use GitHub Copilot in IDE]]></title>
            <link>https://medium.com/@ravisarath64/tips-to-use-github-copilot-in-ide-3a4c08d58840?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a4c08d58840</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-tools-to-use]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 13:30:27 GMT</pubDate>
            <atom:updated>2025-06-13T13:30:27.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*4yM89MlniECY-_Fd0Ba5-Q.png" /></figure><p>Hey coders! 👩‍💻👨‍💻</p><p>If you’re just getting started with GitHub Copilot in your IDE, I’ve got some secret tips for you. 🤫 Keep it between us and enjoy the magic! ✨</p><h3>🚀 Let’s Start: GitHub Copilot</h3><p>GitHub Copilot is your AI-powered pair programmer. It helps you write code faster with smart, context-aware suggestions, refactor your functions, generate tests, explain code, translate between languages, and more. It’s like having a coding buddy 24/7.</p><p>(If you want to dive deeper, check out the docs: <a href="https://docs.github.com/">docs.github.com</a>)</p><p>no worries — I’m not going to explain how to install or activate it in PyCharm. I trust you’re already past that. 😉</p><p>So let’s start.</p><h3>🧠 First Things First: Understand the Prompt</h3><p>Imagine you’re asking a teammate for help — you wouldn’t leave out the important stuff, right? If they don’t have all the details, they can’t really help.</p><p>It’s the same with Copilot. Treat it like a teammate.</p><p>If you’re using AI, you’ve got to know how to communicate with it — and that’s where prompts come in.</p><blockquote><em>Don’t be afraid — Copilot isn’t going to steal your code. 😉 It already knows your project because it’s linked to your GitHub. But don’t worry, it won’t share anything — think of it as your personal teammate who keeps everything just between you two.</em></blockquote><p><strong><em>Prompt</em></strong><em>: The message or instruction you give to the AI.</em></p><p>Most AI models, including Copilot, respond best when you follow this structure:</p><pre>TASK / CONTEXT / TONE / EXAMPLE / FORMAT / PERSONA</pre><p>Now, don’t freak out! It’s simpler than it looks.</p><ul><li><strong>Task</strong> — What you want the AI to do.<br> → <em>Hey Copilot, write a function to fetch user data.</em></li><li><strong>Context</strong> — Background info like language, framework, environment.<br> → <em>I’m working in a Django 3.2 project using Python 3.8.</em></li><li><strong>Tone</strong> — How you want the response.<br> → <em>Explain it like I’m five.</em></li><li><strong>Example</strong> — Provide reference if needed.<br> → <em>Do it like the one I wrote for the login API.</em></li><li><strong>Format</strong> — Expected output format.<br> → <em>Give me the response in JSON.</em></li><li><strong>Persona</strong> — Who you are or how you code.<br> → <em>I’m a Python dev building REST APIs.</em></li></ul><p>If the prompt covers even just <strong>Task + Context</strong>, you’ll get better results.</p><p>Trust me — prompting is everything! 🎯</p><p>I will share an example :</p><blockquote><strong><em>“I’m a Python developer using Django 3.2, and I need to create a REST API endpoint that returns a list of users in JSON format. Please provide a simple, well-commented code snippet.”</em></strong></blockquote><p>Copilot delivers gold when you’re clear with your intent!</p><h3>🧪 Let’s discuss some Cool Copilot Tricks</h3><h3>🔸 Arbitrary Prompt Execution</h3><p>Let’s say you got this task:</p><p><strong>“Create a Django REST API endpoint to return a list of users in JSON format.”</strong></p><p>Just add this comment to the top of your file:</p><pre># task: Create a Django REST API endpoint to return a list of users in JSON format</pre><p>Boom 💥 — Copilot will generate the code right there for you.</p><p>(Just kidding 😄 — it doesn’t force anything on you!)</p><p>It simply gives you a suggestion that’s super close to what you’re looking for. Hit Tab to accept the whole suggestion, or use Ctrl + → to accept it bit by bit.</p><p>It’s all in your control!</p><h4>🔸 Simplify Your Code</h4><p>Want to make your code cleaner?</p><p>Right-click → <strong>GitHub Copilot → Simplify this</strong></p><p>Copilot will offer a simplified version. You can click “Add” to replace your code instantly.</p><h4>🔸 Fix Your Code</h4><p>Right-click → <strong>GitHub Copilot → Fix this</strong></p><p>Copilot will suggest a working version. Debugging made easy!</p><h4>🔸 Generate Test Cases</h4><ol><li>Highlight your function.</li><li>Right-click → <strong>GitHub Copilot → Generate tests</strong></li></ol><p>It’ll generate test cases using the testing framework you use — like pytest or unittest. Since Copilot understands your codebase (yep, it&#39;s tied to your GitHub), the tests are super relevant.</p><h4>🔸 Create Docstrings</h4><p>Want to add clean docstrings?</p><ol><li>Highlight the function.</li><li>Right-click → <strong>GitHub Copilot → Create docstring</strong></li></ol><p>It’ll auto-generate meaningful docstrings based on your code logic.</p><h4>🔸 Explain Code</h4><ol><li>Highlight the function.</li><li>Right-click → <strong>GitHub Copilot → Explain this</strong></li></ol><p>Great for onboarding new team members or understanding legacy code.</p><p><strong>😴 Tired of Right-Clicking Everything? -</strong>Yeah, me too.</p><p><strong>Let’s move on to Copilot Chat</strong> and <strong>slash commands</strong> come in handy.</p><h3>⌨️ Use Copilot Chat</h3><p>There’s a secret chat box just for you and Copilot — like your own little gossip corner. 😄</p><p>You can open the Copilot Chat window right inside your IDE, or just hit the secret combo Ctrl + Shift + I.</p><p>Once you&#39;re in, try out slash commands like:<br> /explain – Get a function explained<br> /simplify – Make messy code clean</p><p>And trust me, there’s a lot more in there. Go explore it — I’m already tired from all this typing! 😅</p><p>Use @workspace to get help from your own code, and @github to pull examples from public projects. Super useful during code reviews or when you’re stuck.</p><h3>🔧 Best Practices When Using Copilot</h3><h4>✅ Help your teammate, and they’ll help you back</h4><p>you can include descriptive file-level comments or #file annotations when start your job:</p><pre># file: utils.py<br># purpose: Helper functions for payment processing</pre><p>Copilot uses this to generate context-aware suggestions.</p><h4>⚠️ Don’t trust your teammate blindly!</h4><p>your Teammate is smart, but not always safe.</p><ul><li>It might generate <strong>insecure code</strong>, <strong>poor logic</strong>, or <strong>vulnerabilities</strong>.</li><li>Always <strong>review suggestions</strong>, especially before pushing to production.</li><li>Treat Copilot as a helpful assistant — not a replacement for critical thinking.</li></ul><h4>🔄 Keep the communication</h4><p>As your code evolves, so should your instructions. Keep comments fresh to maintain context relevance.</p><h3>🧐 Code Review on GitHub</h3><p>So you’ve rocked Copilot in your IDE now let it watch your back on GitHub, too!</p><p>When you open a pull request (PR), Copilot can <strong>summarize changes, spot problems, and draft comments</strong> 🚀</p><p>remember don’t trust blindly</p><p><strong>What Copilot Review Can Do For You</strong></p><ul><li><strong>PR Summary</strong> 👉 One-click summary of what changed &amp; why. Perfect when you’re dealing with a huge diff or coding at 2 AM 🥱</li><li><strong>Suggested Comments</strong> 👉 It drops inline suggestions like “Yo, missing a test here” or “Hey, that could break something.”</li><li><strong>Ask Copilot</strong> 👉 Just type your doubts next to any diff — like <em>“Is this causing an N+1 query?”</em> — and it answers!</li><li><strong>Auto Reviews</strong> 👉 Turn on auto-reviews for all PRs. Copilot will start reviewing stuff even before your teammates have had their coffee.</li></ul><p>🔧 <strong>How to Turn It On</strong><br> Go to: Repo Settings → Copilot → Code Review → Turn on Automatic Review<br> (Yes, you can limit it to specific branches.)<br> ⚠️ Note: This needs <strong>Copilot Pro/Enterprise</strong>, and yeah, reviews count as premium.</p><p>Just open or convert a Draft PR, give it a sec… and boom 💥 Copilot drops its review.</p><h3>🌍 <strong>Languages + Versions — It Knows Stuff!</strong></h3><p>Your teammate is not like you, It knews all the cool kids:<br> 🧠 <strong>Python</strong>, <strong>JavaScript</strong>, <strong>TypeScript</strong>, <strong>Go,</strong> <strong>Java</strong>, <strong>C#</strong>, <strong>C++</strong>, <strong>Rust</strong>, and more!</p><p>It even tailors suggestions based on version — <br> Python 3.6 ≠ Python 3.11, Django 2.2 ≠ Django 4.0.<br> So yes, context and versions totally matter.</p><blockquote>Include your tech stack and version in the prompt → You’ll get smarter and more relevant suggestions.</blockquote><p>🔥 <strong>Bonus Magic You Shouldn’t Miss</strong></p><ul><li>Use <strong>Copilot Labs</strong> in VS Code → Live refactoring &amp; code translation</li><li><strong>Onboarding juniors?</strong> Ask Copilot to explain legacy code for them</li><li><strong>Be safe, not sorry:</strong> Always review AI-generated code</li><li><strong>Context = King</strong> 👑 The more info you give, the better Copilot behaves</li></ul><h4>Alright, I’m too tired now 😴</h4><p>But before I crash — just remember:</p><p>GitHub Copilot isn’t just some fancy autocomplete — it’s your AI teammate.</p><p>The real trick? Talk to it properly. Be clear, give it context, and it’ll surprise you.</p><p><strong>Right prompt + Copilot = 💥 Big Brain Coding Power</strong></p><p>Now go explore, code like a wizard, and let Copilot do the heavy lifting.<br> And yeah… don’t forget to enjoy the magic. ✨</p><p>Happy Coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a4c08d58840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Schema with Protocol Buffers]]></title>
            <link>https://medium.com/@ravisarath64/python-schema-with-protocol-buffers-50456e2df502?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/50456e2df502</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-serialization]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 06:12:22 GMT</pubDate>
            <atom:updated>2024-06-19T06:12:22.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*Enq48UvJxAkIB2AUlGODQQ.png" /></figure><p>You might be familiar with Pydantic, a popular Python library for data validation and settings management using Python-type annotations. Similarly, Protocol Buffers help manage data structures, but they serve different purposes and possess distinct strengths:</p><ul><li><strong>Protocol Buffers</strong> are ideal for scenarios where you need to serialize and transmit data efficiently across different systems and programming languages. They shine in network communication and storage where performance and interoperability are critical.</li><li><strong>Pydantic</strong>, on the other hand, excels at data validation and settings management within Python applications. It leverages Python’s type hints to provide runtime type checking, making it great for API validation, configuration management, and ensuring data integrity within Python code.</li></ul><p>Protocol Buffers are ideal for efficiently serializing data and ensuring compatibility across multiple languages. On the other hand, if you’re developing a Python application and require strong data validation, Pydantic is a good tool to consider.</p><h3>How does protobuf work?</h3><p>Protocol Buffers (protobuf) operate as a system for serializing structured data into a compact binary format, ensuring efficient storage, transmission, and parsing across various platforms and programming languages.</p><p>You can define the structure of your data in .proto file, specifying each field and its type. When you compile this .proto file using the Protocol Buffers compiler (protoc), it generates language-specific code (like Python classes) that you can use in your applications. This generated code enables you to create instances of your defined messages, set values for their fields, and then serialize these messages into a binary format using methods like SerializeToString().</p><p>This binary representation is highly efficient, occupying less space compared to text-based formats like JSON, and it ensures fast transmission and storage of data. On the receiving end, you can deserialize the binary data back into structured messages, allowing applications to easily read and manipulate the data according to the original schema.</p><h3>Advantages of Protocol Buffers Over Pydantic</h3><p>Protocol Buffers offer significant advantages in scenarios where efficient serialization, cross-language compatibility, smaller payload sizes, and robust backward and forward compatibility are required. They are particularly well-suited for microservices and network communication in distributed systems.</p><blockquote>Ensuring Data Integrity</blockquote><p>Imagine spending a lot of time organizing your room, making sure everything is in its place. Then, when you want to move something to another room, you just toss it over without caring where it lands. That’s similar to how we treat data sometimes. With Protocol Buffers, it’s like packing things neatly in boxes before moving them — they stay organized and intact no matter where they go. It’s about keeping your data tidy and making sure it doesn’t get messed up when it moves between different parts of your system.</p><blockquote>Backward Compatibility</blockquote><p>Let&#39;s go with the above example you’ve meticulously organized your room with everything in specific places. This setup represents a version of your room’s layout, just like a version of data structure in software.</p><p>Now, suppose you need to add a new piece of furniture to your room. With Protocol Buffers, adding this new furniture is like adding a new box labeled neatly with its contents. You simply place it in your room without disturbing the existing arrangement of other items. Similarly, in Protocol Buffers, when you add a new field or change a data structure, it’s designed to seamlessly integrate with existing data without requiring you to rearrange or disrupt how your application processes older data.</p><p>In contrast, think of a scenario where you use a less structured approach, like tossing items around when you need to make room for something new. This approach might lead to chaos and confusion over time, much like how managing evolving data structures in JSON or other less structured formats can result in compatibility issues and errors.</p><blockquote>Serializing Data to Binary Format</blockquote><p>Serializing data to binary format in Protocol Buffers is like carefully packing items into neatly labeled boxes before moving them. First, you define the structure of your data in a blueprint (.proto file), much like planning where each piece of furniture goes in a room. Then, you create an instance of your data message and fill it with specific details. When it&#39;s time to transport or store this data, you use Protocol Buffers to serialize it into a compact binary format.</p><p>This process ensures that all information is efficiently packed and preserved, similar to how items in well-sealed boxes remain organized and intact during transport. Binary format offers advantages like faster processing and reduced storage space, making it ideal for efficiently managing and transmitting structured data across different systems and platforms.</p><h3>Using Protocol Buffers with Python</h3><p>Integrating Protocol Buffers (protobuf) with Python involves a series of steps to efficiently handle structured data serialization and deserialization. First, you’ll need to install the Protocol Buffers compiler (protoc) on your system, which is essential for compiling .proto files into language-specific code. This compiler can be downloaded from the Protocol Buffers GitHub releases page or installed via package managers like apt-get, brew, or choco, depending on your operating system.</p><p>Once installed, you can define your data structure using the Protocol Buffers language syntax in a .proto file. This file acts as a blueprint for your data, specifying each field and its type. For example, a person.proto file might define fields like name, id, and email for a Person message.</p><pre>syntax = &quot;proto3&quot;;<br><br>message Person {<br>  string name = 1;<br>  int32 id = 2;<br>  string email = 3;<br>}</pre><blockquote>The first line of the file specifies that you’re using <a href="https://protobuf.dev/programming-guides/proto3/">proto3</a> syntax: if you don’t do this the protocol buffer compiler will assume you are using <a href="https://protobuf.dev/programming-guides/proto2">proto2</a>. This must be the first non-empty, non-comment line of the file.</blockquote><p>After defining your .proto file, you use the protoc compiler to generate Python code from it. This step creates Python classes (e.g., person_pb2.py) that correspond to your defined message types.</p><pre>protoc --python_out=. person.proto</pre><p>Install protobuf Python package via pip.</p><pre>pip install protobuf</pre><p>With this package, you can import the generated Python classes (person_pb2) into your application code.</p><pre>from person_pb2 import Person<br><br># Create a new Person message<br>person = Person()<br>person.name = &quot;Alice&quot;<br>person.id = 123<br>person.email = &quot;alice@example.com&quot;</pre><p>This allows you to create instances of your Protocol Buffers messages, set values for their fields, and serialize them into a compact binary format using methods like SerializeToString(). This binary format is efficient for storage and transmission, making data handling more streamlined and performant.</p><pre># Serialize to binary format<br>serialized_person = person.SerializeToString()</pre><p>To complete the cycle, you can deserialize binary data back into structured messages using methods like ParseFromString(), enabling your applications to read and manipulate data according to the original schema.</p><pre># Deserialize from binary format<br>new_person = Person()<br>new_person.ParseFromString(serialized_person)<br><br>print(new_person)</pre><h3>Conclusion</h3><p>As you become more comfortable with Protocol Buffers, explore advanced features such as handling nested messages, enums, and integrating with frameworks like gRPC for building robust distributed systems. By following these steps, you can effectively harness Protocol Buffers in your Python projects, enhancing data management and interoperability across different platforms and services.</p><p>you can use the below links for more details</p><ul><li><a href="https://codeclimate.com/blog/choose-protocol-buffers">5 Reasons to Use Protocol Buffers Instead of JSON for Your Next...</a></li><li><a href="https://martin.kleppmann.com/2012/12/05/schema-evolution-in-avro-protocol-buffers-thrift.html">Schema evolution in Avro, Protocol Buffers and Thrift</a></li><li><a href="https://embeddedproto.com/documentation/">Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50456e2df502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Advanced Django Querying: Django Text Search Essentials]]></title>
            <link>https://medium.com/@ravisarath64/mastering-advanced-django-querying-part-1-780051f602b4?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/780051f602b4</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[querying]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 17:31:23 GMT</pubDate>
            <atom:updated>2024-06-11T12:54:56.227Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django Text Search Essentials</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxptEtIZ2gi2AxBNVL1zgQ.png" /></figure><p>Hi everyone!</p><p>Imagine this: You’ve built a Django app, but as your project grows, the complexity of your data increases. That’s where advanced querying comes in! It’s like having a superpower that enables you to fetch, filter, and manipulate data in ways you never imagined.</p><p>In this blog series, let’s embark on a journey to explore the hidden treasures of Django querying</p><h3>Django Text Search Essentials</h3><p>Let’s create a scenario where you, as a teacher, want to share articles with your students based on their interests using a Django web application. The students can search for articles related to their interests, and the application will display relevant articles using full-text search functionality.</p><p>First, let’s define the models for articles and students:</p><pre># models.py<br>from django.db import models<br><br>class Article(models.Model):<br>    title = models.CharField(max_length=100)<br>    content = models.TextField()<br><br>    def __str__(self):<br>        return self.title<br><br>class Student(models.Model):<br>    name = models.CharField(max_length=50)<br>    interests = models.TextField()<br><br>    def __str__(self):<br>        return self.name<br></pre><p>A common way to use full-text search is to search a single term against a single column in the database. For example:</p><pre>&gt;&gt;&gt; Student.objects.filter(interests__search=&quot;physics&quot;)</pre><p>We can search for a word in the database without considering case sensitivity.</p><p>In Django queries, both search and contains are used for filtering data, but they have different behaviors:</p><ul><li><em>contains is a basic lookup that checks whether a given field contains a specific value.</em><em>contains is useful for simple string matching scenarios where you need to check for the presence of a specific substring within a field.</em></li><li><em>icontains is a case-insensitive version of </em><em>contains</em></li><li><em>search typically refers to full-text search functionality, which is often provided by external libraries like </em><em>django.contrib.postgres.search or specialized full-text search engines like Elasticsearch.This allows you to perform more complex search operations, such as searching for words within larger bodies of text, handling stop words, stemming, and ranking search results based on relevance.</em></li></ul><p>To use the <strong>search</strong> lookup, <strong>&#39;django.contrib.postgres&#39;</strong> must be in your <a href="https://docs.djangoproject.com/en/5.0/ref/settings/#std-setting-INSTALLED_APPS"><strong>INSTALLED_APPS</strong></a>.</p><p>For full-text search in Django, you can use PostgreSQL’s full-text search capabilities along with Django’s <a href="https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/search/#searchvector">SearchVector</a>, <a href="https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/search/#searchquery">SearchQuery</a>, and <a href="https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/search/#searchrank">SearchRank</a> functionalities, which are available through django.contrib.postgres.search.</p><p>Certainly! Let’s delve deeper into <a href="https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/search/#searchvector">SearchVector</a> and explore the scenarios where it&#39;s commonly used.</p><blockquote>SearchVector is a PostgreSQL feature that converts text data into a format suitable for full-text searching.</blockquote><blockquote>Imagine you have a huge library with lots of books. Now, let&#39;s say you want to find all the books that contain a certain word or phrase. How would you do that? You&#39;d need some way to quickly search through all the books, right? That&#39;s where SearchVector comes in handy!</blockquote><p>here the SearchVector is like a super smart librarian. Its job is to read through all the words in your books and create a special list that makes it easy to find what you&#39;re looking for.</p><p>you tell it which fields you want to search through. For example, in our library analogy, you might say, “Hey, SearchVector, please look through the titles and the content of all the books.”</p><p>you can use it to search for specific words or phrases. It’s like telling the librarian, “Hey, can you find me all the books that mention the word ‘adventure’?”</p><p>By incorporating SearchVector into queries, developers can perform advanced search operations based on the content of text fields. It’s especially useful when you want to rank search results based on their relevance to a given search query.</p><p>let&#39;s code it</p><p>from the same model article think that we want to search the books containing “adventure” in the article content</p><pre>from django.contrib.postgres.search import SearchVector<br>from .models import Article<br><br><br># Step 2: Use the SearchVector in a search query<br>articles = Article.objects.annotate(<br>        search=SearchVector(&quot;content&quot;),<br>).filter(search=&quot;adventure&quot;)</pre><blockquote>SearchQuery is a way to represent a search query.</blockquote><p>Think of it like a container for the words you want to search for. When you use SearchQuery, you&#39;re basically saying, &quot;Hey Django, I want to search for these specific words.&quot;</p><p>if I want to search for more than one word, like ‘adventure’ and ‘mystery’. You can create a SearchQuery for each word you want to search for. So, you&#39;d have one SearchQuery for &#39;adventure&#39; and another for &#39;mystery&#39;. Then, I&#39;ll combine them using SearchVector to make sure the database knows what to look for.</p><pre>from django.contrib.postgres.search import SearchQuery, SearchVector<br>from .models import Article<br><br><br># Define the search queries<br>search_query_adventure = SearchQuery(&#39;adventure&#39;)<br>search_query_mystery = SearchQuery(&#39;mystery&#39;)<br><br># Use SearchVector to convert the search queries into a format the database can understand<br>search_vector = SearchVector(&#39;description&#39;)<br><br># Perform the search using the search queries and search vector<br>results = Article.objects.annotate(<br>   search=search_vector<br>).filter(search=search_query_adventure | search_query_mystery)</pre><p>you can also query with description containing both ‘adventure’ and ‘mystery’.</p><pre>results = Article.objects.annotate(<br>   search=search_vector<br>).filter(search=search_query_adventure &amp; search_query_mystery)</pre><p>SearchRank is a method used to calculate the relevance or ranking of search results based on how well they match the search query. It&#39;s typically used in conjunction with SearchQuery and SearchVector to order search results by their relevance.</p><p>When you perform a full-text search using Django’s PostgreSQL search features, each search result is assigned a rank based on how well it matches the search query. This rank indicates the relevance of the result to the query.</p><pre>from django.contrib.postgres.search import SearchQuer SearchRank, SearchVector<br><br>search_query = SearchQuery(&#39;adventure&#39;) | SearchQuery(&#39;mystery&#39;)<br>search_vector = SearchVector(&#39;description&#39;)<br><br>results = Article.objects.annotate(<br>   rank=SearchRank(search_vector, search_query)<br>).filter(<br>   search=search_query_adventure &amp; search_query_mystery<br>).order_by(&quot;-rank&quot;)</pre><p>which will provide the result</p><pre>&gt;&gt;&gt; results = [<br>    {<br>        &quot;title&quot;: &quot;The Adventure of the Mystery Island&quot;,<br>        &quot;content&quot;: &quot;In this thrilling adventure, our protagonist embarks on a journey to a mysterious island...&quot;,<br>        &quot;rank&quot;: 0.92<br>    },<br>    {<br>        &quot;title&quot;: &quot;Mystery in the Jungle&quot;,<br>        &quot;content&quot;: &quot;Lost in the depths of the jungle, our hero uncovers secrets and solves mysteries...&quot;,<br>        &quot;rank&quot;: 0.85<br>    },<br>    {<br>        &quot;title&quot;: &quot;The Secret Agent&quot;,<br>        &quot;content&quot;: &quot;A gripping tale of espionage and adventure, where nothing is as it seems...&quot;,<br>        &quot;rank&quot;: 0.72<br>    },<br>    {<br>        &quot;title&quot;: &quot;The Hidden Treasure&quot;,<br>        &quot;content&quot;: &quot;A group of intrepid explorers sets out on a quest to find a long-lost treasure...&quot;,<br>        &quot;rank&quot;: 0.68<br>    }<br>]</pre><p>The rank values are hypothetical and represent the relevance of each article to the search query. The higher the rank, the more relevant the article is to the search terms &quot;adventure&quot; and &quot;mystery&quot;.</p><h4><em>Conclusion</em></h4><p>Through this blog series, I aim to elucidate topics with scenarios and examples, focusing on clarity, particularly for beginners. I firmly believe that grasping the fundamentals empowers one to delve deeper into the subject matter.</p><p>You can refer to the links below for more detailed information.</p><p><a href="https://docs.djangoproject.com/en/5.0/ref/contrib/postgres/search/#searchquery">Full text search | Django documentation</a></p><p><a href="https://testdriven.io/blog/django-search/">https://testdriven.io/blog/django-search/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=780051f602b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Python API Development: An Introduction to Pydantic Schema Validation]]></title>
            <link>https://medium.com/@ravisarath64/boosting-python-api-development-an-introduction-to-pydantic-schema-validation-51f519c985c1?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/51f519c985c1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Wed, 29 May 2024 06:16:54 GMT</pubDate>
            <atom:updated>2024-05-29T06:16:54.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h0iLn9cvA1jh88GR" /></figure><p>Welcome to the world of Pydantic, where data validation in Python is made elegant and effortless. In this blog post, we’ll delve into the fundamentals of Pydantic schema and explore how it simplifies defining and validating data structures in Python applications.</p><blockquote>What is Pydantic?</blockquote><p>“Oh, it’s a straightforward` question. ‘Pydantic’ is an adjective that means ‘being persuasive in speech or writing.’ This could imply the ability to effectively communicate ideas, ensuring they are clear, convincing, and logically structured. Similarly, in the realm of software development, Pydantic, the library, excels at persuasively validating data structures.”</p><blockquote>Why Use Pydantic?</blockquote><p>“Imagine you’re stepping into a vibrant world of Python programming. You know, there’s this cool tool called Pydantic. It’s like having a magic wand for ensuring your data behaves just the way you want it to. With Pydantic, you can define the rules for your data, making sure it’s clear, consistent, and error-free. It’s kind of like creating a blueprint for your data, so everyone knows what to expect. And you know what’s even cooler? Pydantic plays nicely with other tools and frameworks, making it super easy to use in your projects. So, if you ever find yourself tangled in the web of data validation, just remember Pydantic — your trusty sidekick in the world of Python adventures!”</p><p>Let’s break down the wonders of Pydantic step by step:</p><ol><li><strong>Simplified Data Validation</strong>: Picture this: you’ve got this messy pile of data, and you need to make sense of it all. Pydantic swoops in like a superhero, offering you a simple way to define the structure of your data and set up validation rules. You can specify things like data types, constraints, and default values, ensuring that your data is neat, tidy, and error-free.</li><li><strong>Enhanced Code Readability</strong>: Now, imagine you’re trying to decipher someone else’s code, and it feels like trying to untangle a knot. Pydantic comes to the rescue again! By using Pydantic models to define your data schemas, you’re creating a roadmap for your code. It’s like adding signposts that make your code easier to understand for both you and your fellow developers.</li><li><strong>Improved Code Maintainability</strong>: Ever feel like you’re playing a game of hide-and-seek with your validation code? With Pydantic, you can kiss those days goodbye! By centralizing your data validation logic within your models, Pydantic keeps everything neat and organized. No more hunting through your codebase to find where that pesky validation rule is hiding!</li><li><strong>Integration with Frameworks and Libraries</strong>: Pydantic isn’t just a loner — it loves to play nice with other tools and frameworks. Whether you’re using FastAPI, Django, or SQLAlchemy, Pydantic seamlessly integrates with them all. It’s like having a versatile sidekick that’s always ready to lend a hand, no matter what project you’re working on.</li><li><strong>Automatic Documentation Generation</strong>: Ah, documentation — the bane of every developer’s existence. But fear not! Pydantic models can automatically generate API documentation based on their defined schemas. That means no more tedious manual documentation — Pydantic has got your back, keeping your docs up-to-date with minimal effort.</li></ol><blockquote>How Does Pydantic Work?</blockquote><p>Well, let me show you. Imagine you’re a blacksmith crafting a sword. With Pydantic, you start by forging a blueprint, or model, for your data. Here’s a simple example</p><pre>from pydantic import BaseModel<br><br>class Weapon(BaseModel):<br>    name: str<br>    damage: int<br>    weight: float = 10.0</pre><p>we’ve defined a Weapon class with attributes like name, damage, and weight. Pydantic automatically validates data against this model, ensuring it matches the specified types and constraints.</p><p>what happens if the data doesn’t match the model?</p><p>Ah, good question! Pydantic acts like a vigilant guardian, watching over our data. If it encounters any discrepancies, it raises its trusty sword — I mean, it raises informative exceptions. Let’s say someone tries to create a Weapon with invalid data:</p><pre>try:<br>    sword = Weapon(name=&#39;Excalibur&#39;, damage=&#39;great&#39;)  # Oh dear, &#39;damage&#39; should be an integer!<br>except ValidationError as e:<br>    print(e)<br><br>&gt;&gt;&gt;  value is not a valid integer (type=type_error.integer)</pre><p>We can add some new rules to the model. We want the Weapon name to be at least 5 characters long. So, if someone tries to create a too-short name, the code will say, “Hey, your name needs to be longer!”</p><pre>class Weapon(BaseModel):<br>    name: str<br>    damage: int<br>    weight: float = 10.0<br>    <br>    @validator(&#39;name&#39;)<br>    def name_length(cls, v):<br>        if len(v) &lt; 5:<br>            raise ValueError(&#39;name must be at least 5 characters long&#39;)<br>        return v</pre><p>We use something called the Field class from Pydantic. It&#39;s like a little tag we attach to each field in our model to give it extra information, like a description.</p><pre>from pydantic import BaseModel, Field<br><br>class Weapon(BaseModel):<br>    name: str = Field(..., description=&quot;The weapon name (at least 5 characters)&quot;)<br>    damage: int = Field(..., description=&quot;How the weapon create damage&quot;)<br>    weight: int = Field(..., description=&quot;The weapon weight(must be a positive integer)&quot;)</pre><p>you can access these descriptions by using the below code</p><pre>Weapon.schema()<br><br>&gt;&gt; {<br>  &quot;title&quot;: &quot;Weapon&quot;,<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;name&quot;: {<br>      &quot;title&quot;: &quot;Name&quot;,<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;minLength&quot;: 5,<br>      &quot;description&quot;: &quot;The weapon name (at least 5 characters)&quot;<br>    },<br>    &quot;damage&quot;: {<br>      &quot;title&quot;: &quot;Damage&quot;,<br>      &quot;type&quot;: &quot;integer&quot;,<br>      &quot;description&quot;: &quot;How the weapon creates damage&quot;<br>    },<br>    &quot;weight&quot;: {<br>      &quot;title&quot;: &quot;Weight&quot;,<br>      &quot;type&quot;: &quot;integer&quot;,<br>      &quot;minimum&quot;: 0,<br>      &quot;description&quot;: &quot;The weapon weight (must be a positive integer)&quot;<br>    }<br>  },<br>  &quot;required&quot;: [&quot;name&quot;, &quot;damage&quot;, &quot;weight&quot;]<br>}</pre><p>This JSON Schema represents the structure of the Weapon model, specifying the properties of each field, including their types, minimum lengths, minimum values (for integers), and descriptions. It also indicates that all fields are required (&quot;required&quot;: [&quot;name&quot;, &quot;damage&quot;, &quot;weight&quot;]).</p><blockquote>let&#39;s discuss with a real-world scenario</blockquote><p>Imagine you’re building a website with a signup form. You want to make sure that users enter their information correctly. Pydantic can help with that! You define a Pydantic model that represents the structure of the user data you expect, like their username, email, and age. Then, when users submit the form, Pydantic automatically checks if the data matches the model. If anything’s wrong, Pydantic provides helpful error messages to guide the user.</p><p>let’s add some code snippets to illustrate the scenarios:</p><pre>from pydantic import BaseModel, Field<br><br>class SignupForm(BaseModel):<br>    username: str = Field(..., description=&quot;Username (at least 5 characters)&quot;)<br>    email: str = Field(..., description=&quot;Email address&quot;)<br>    age: int = Field(..., description=&quot;Age (must be a positive integer)&quot;)<br><br># Example usage<br>form_data = {<br>    &quot;username&quot;: &quot;john_doe&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;age&quot;: 30<br>}<br><br>try:<br>    validated_form = SignupForm(**form_data)<br>    print(&quot;Form data is valid!&quot;)<br>    print(validated_form)<br>except ValueError as e:<br>    print(&quot;Form validation error:&quot;)<br>    print(e)</pre><p>It ensures that everyone speaks the same data language, preventing misunderstandings and errors.</p><blockquote>Are there any alternatives to Pydantic for data validation in Python?</blockquote><p>Yes, there are several alternatives to Pydantic for data validation in Python. Some popular alternatives include:</p><ol><li><strong>Marshmallow</strong>: Marshmallow is a popular library for object serialization and validation. It provides a flexible and expressive way to define schemas for validating and serializing complex data structures.</li><li><strong>Colander</strong>: Colander is a lightweight schema validation library for Python. It allows you to define schemas using a simple and declarative syntax, making it easy to validate and serialize data.</li><li><strong>cerberus</strong>: Cerberus is a lightweight and extensible data validation library for Python. It focuses on simplicity and flexibility, allowing you to define validation rules using simple dictionaries.</li><li><strong>Schema</strong>: Schema is a data validation library that focuses on providing a simple and intuitive way to define schemas for validating and serializing data. It supports both JSON and Python data structures.</li></ol><blockquote>Are there any common misconceptions about Pydantic?</blockquote><p>While Pydantic is a powerful tool for data validation and serialization in Python, there are some common pitfalls and misconceptions that users may encounter. Here are a few, along with suggestions on how to avoid them:</p><ol><li>Misconception: Overuse of Field Defaults: While Pydantic allows you to specify default values for fields using the Field class, overusing defaults can lead to unexpected behavior, especially when working with mutable types like lists or dictionaries.</li><li>Avoidance: Be cautious when using default values, especially for mutable types. Instead, consider explicitly initializing mutable fields in the model’s __init__ method to ensure that each instance has its own independent copy.</li><li>Pitfall: Mixing Business Logic with Data Validation: It’s tempting to add complex business logic directly into Pydantic models, but this can make the models harder to understand and maintain over time.</li><li>Avoidance: Keep your Pydantic models focused on data validation and serialization, and separate your business logic into separate functions or classes. This makes your code more modular and easier to test.</li><li>Misconception: Implicit Type Conversion: Pydantic performs implicit type conversion during data validation, which can sometimes lead to unexpected results if the input data doesn’t match the expected types.</li><li>Avoidance: Be aware of Pydantic’s type conversion behavior and ensure that your input data matches the expected types. If necessary, use validators to perform explicit type checks and conversions as needed.</li><li>Pitfall: Ignoring Validation Errors: It’s easy to ignore validation errors and assume that the input data is always valid, especially in a development environment. However, ignoring validation errors can lead to runtime errors and unexpected behavior in production.</li><li>Avoidance: Always handle validation errors gracefully and provide meaningful feedback to the user or caller. Consider using try-except blocks to catch validation errors and handle them appropriately.</li><li>Misconception: Pydantic is a Silver Bullet: While Pydantic is a powerful tool for data validation and serialization, it’s not a one-size-fits-all solution for every problem. There may be cases where other libraries or custom solutions are more appropriate.</li><li>Avoidance: Understand the strengths and limitations of Pydantic, and use it judiciously in your projects. Consider evaluating other options or combining Pydantic with other libraries as needed to meet your specific requirements.</li></ol><blockquote>Can Pydantic be the key to unlocking seamless data validation and serialization in Python projects?</blockquote><p>Pydantic stands as a robust and versatile tool for data validation and serialization in Python. Its intuitive syntax, powerful features, and seamless integration with web frameworks like FastAPI make it a go-to choice for developers across various domains. However, it’s crucial to understand Pydantic’s capabilities, best practices, and potential misconceptions to leverage it effectively in your projects. By embracing Pydantic’s strengths and addressing any challenges head-on, developers can streamline data handling, enhance code quality, and build more robust applications. Whether you’re developing web APIs, command-line tools, or data processing pipelines, Pydantic proves to be a valuable asset, empowering developers to tackle complex data validation tasks with ease</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51f519c985c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celery Deprecation]]></title>
            <link>https://medium.com/@ravisarath64/celery-deprecation-eb66fab22fa6?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb66fab22fa6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 12:10:01 GMT</pubDate>
            <atom:updated>2021-09-16T12:10:01.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBQP2bzWBIPydYMy-QkPBw.jpeg" /></figure><p>Hey, celery is now going to remove some imports, some setting from their latest version onwards (version 5+).</p><p>from your latest celery shows some warnings like below</p><pre>$ The &#39;CELERY_TIMEZONE&#39; setting is deprecated and scheduled for  removal in</pre><pre>$ alternative=f&#39;Use the {_TO_NEW_KEY[setting]} instead&#39;)</pre><pre>$ version 6.0.0. Use the result_backend instead</pre><pre>$ The &#39;CELERY_ACCEPT_CONTENT&#39; setting is deprecated and scheduled for removal in</pre><pre>$ alternative=f&#39;Use the {_TO_NEW_KEY[setting]} instead&#39;)</pre><pre>$ version 6.0.0. Use the result_serializer instead</pre><p>Version 4.0 introduced new lower case settings and setting organization. It is recommended to <strong>replace BROKER Settings</strong> , <strong>REDIS Result Backend Settings</strong>, and some <strong>Compat Task Modules</strong> since 4.0.</p><p>The changes are fully backwards compatible, so you have the option to wait until the old setting names are deprecated, but to ease the transition we have included a command-line utility that rewrites your settings automatically.</p><p>I will give you a simple technique to update settings file. Just run the command below and see the magic</p><pre>$ celery upgrade settings &lt; path_to_settings_file &gt;</pre><p>path_to_settings_file → path to which settings file where have added the celery settings.</p><p>After upgrading the settings file, you need to set the prefix explicitly in your proj/celery.py module:</p><pre>app.config_from_object(&#39;django.conf:settings&#39;, namespace=&#39;CELERY&#39;)</pre><p>it will automatically update the following</p><pre>CELERY_ACCEPT_CONTENT = [&#39;**&#39;]<br>CELERY_BROKER_URL = &quot;**&quot;<br>CELERY_TIMEZONE = &quot;**&quot;<br>CELERY_RESULT_BACKEND = &quot;**&quot;<br>..................<br>.................<br>................</pre><p>to this</p><pre>accept_content = [&#39;**&#39;]<br>CELERY_broker_url = &quot;**&quot;<br>timezone = &quot;**&quot;<br>result_backend = &quot;**&quot;<br>..............<br>.............<br>............</pre><p>see the document below for more details.</p><p><a href="https://docs.celeryproject.org/en/stable/history/whatsnew-4.0.html#v400-upgrade-settings">What&#39;s new in Celery 4.0 (latentcall) - Celery 5.1.2 documentation</a></p><blockquote>Compat Task Modules</blockquote><p>Celery also updated some compat task modules from the release 5.0 onward</p><ul><li>Module celery.decorators will be removed:</li><li>This means you need to change:</li></ul><pre>from celery.decorators import task</pre><p>Into:</p><pre>from celery import task</pre><ul><li>Module celery.task <em>may</em> be removed (not decided). This means you should change:</li></ul><pre>from celery.task import task</pre><p>into:</p><pre>from celery import task</pre><p>Note that the new <strong>Task</strong> class no longer uses <a href="https://docs.python.org/dev/library/functions.html#classmethod"><strong>classmethod()</strong></a> for these methods:</p><ul><li>delay</li><li>apply_async</li><li>retry</li><li>apply</li><li>AsyncResult</li><li>subtask</li></ul><p>This also means that you can’t call these methods directly on the class, but have to instantiate the task first:</p><pre><strong>&gt;&gt;&gt; </strong>MyTask.delay()          # NO LONGER WORKS<br></pre><pre><strong>&gt;&gt;&gt; </strong>MyTask().delay()        # WORKS!</pre><blockquote>Conclusion</blockquote><p>Please go through the documentation before configure celery in your django app.</p><p><a href="https://docs.celeryproject.org/en/stable/internals/deprecation.html">Celery Deprecation Time-line - Celery 5.1.2 documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb66fab22fa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python : Virtual Environments]]></title>
            <link>https://medium.com/@ravisarath64/python-virtual-environments-f95c328dd75f?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f95c328dd75f</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[pyenv]]></category>
            <category><![CDATA[virtualenv]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 06:12:36 GMT</pubDate>
            <atom:updated>2021-08-06T06:12:36.441Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python : Virtual Environments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpDUNMC23PsEZxyuSvyVuA.png" /></figure><blockquote>Hey, What’s that virtual environment ?</blockquote><p>Let’s suppose that you are working on 2 python projects. One uses python version 3.4 and the other uses 3.7, how do you manage these types of conditions? Would you switch the version while working on each one?</p><p>The answer is no. You can create an environment for each project so that you can manage both simultaneously.</p><p>A virtual environment is a <strong>tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.</strong></p><p>Virtual environments include a fresh duplicate of Python binaries, and a standalone copy of the entire Python standard library. so you can deploy a Python app in a dedicated server and can share dependencies with others.</p><blockquote>how can I set up a virtual environment?</blockquote><p>Python3 has the default module venv to manage virtual environments ( from Python 3.3+ the venv package is included ). To create the environment, just move to your project directory, and run the following script:</p><pre>$ python3 -m venv &lt; your environment name &gt;</pre><p>You can add your custom name for your virtual environment.</p><p>This will create the &lt; your environment name &gt; directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files.</p><p>For simplicity, let &lt; your environment name &gt;. name be <strong>test-env.</strong></p><blockquote>Activating Virtual Environment.</blockquote><p>Once you’ve created a virtual environment, you may need to activate it.</p><p>On Windows, run:</p><pre>$ test-env\Scripts\activate.bat</pre><p>On Unix or MacOS, run:</p><pre>$ source test-env/bin/activate</pre><p><strong>Note:</strong> you can carry your environment from one system having the same os. so other one doesn’t waste time to install the same. Pretty cool!</p><blockquote>Deactivating Virtual Environment.</blockquote><p>To deactivate, simply use the command:</p><pre>$ deactivate</pre><blockquote>how can i manage the python versions here?</blockquote><p><strong>pyenv</strong> is the best method for python version management. pyenv lets you easily switch between multiple versions of Python. It will let you change the global and local Python versions easily.</p><p>You can use the below installation guide to install pyenv and to manage the python version.</p><p><a href="https://github.com/pyenv/pyenv/blob/master/README.md">https://github.com/pyenv/pyenv/blob/master/README.md</a></p><p>Install pyenv.</p><pre>$ curl -L <a href="https://github.com/pyenv/pyenv-">https://github.com/pyenv/pyenv-</a>  installer/raw/master/bin/pyenv-installer | bash</pre><p><strong>NOTE:</strong> curl | bash is a risky command, make sure to execute them from trusted source only.</p><pre>$ echo &#39;export PYENV_ROOT=&quot;$HOME/.pyenv&quot;&#39; &gt;&gt; ~/.bashrc<br>$ echo &#39;export PATH=&quot;$PYENV_ROOT/bin:$PATH&quot;&#39; &gt;&gt; ~/.bashrc<br>$ echo -e &#39;if command -v pyenv 1&gt;/dev/null 2&gt;&amp;1; then\n  eval &quot;$(pyenv init -)&quot;\nfi&#39; &gt;&gt; ~/.bashrc</pre><p><strong>NOTE:</strong> Since I am using ubuntu I used the command ~/.bashrc . You can change it to ~/.bash_profile, ~/.profile or ~/.bashrc. According to your os</p><p>after the installation you can check for available versions.</p><pre>$ pyenv versions</pre><p>You can check the available list of all python versions, with the following command:</p><pre>$ pyenv install — list</pre><p>for example,</p><pre>$ pyenv install 3.9.5</pre><p>You can set the global python version and local python version (inside your environment ) using the following commands,</p><pre>$ pyenv global 3.9.5</pre><pre>$ pyenv local 3.9.5</pre><blockquote>How virtual environment works ?</blockquote><p>After activating the Virtual Environment, your terminal will show something like this:</p><pre>$ source env/bin/activate<br>(test-env) $ </pre><p>This means that you are in a virtual environment <strong>test-env.</strong></p><p>if you set the python version inside your environment as 3.7 and globally as 3.9 .</p><pre>(test-env) $ python --v<br>3.7.0</pre><p>Inside your environment, you can install the python packages using PIP which is a package manager used to install and manage Python packages.</p><pre>(test-env)$ pip install &lt; some package name &gt;</pre><p>You can generate the dependencies file of your project using the command below:</p><pre>(test-env)$ pip freeze</pre><p>pip freeze will produce a similar list of the installed packages, but the output uses the format that pip install expects. A common convention is to put this list in a requirements.txt ( requirements.txt is standard file name you can use different names that doesn’t matter ) file:</p><pre>(test-env)$ pip freeze &gt; requirements.txt</pre><blockquote>Conclusion</blockquote><p>Virtual environments, or “virtualenvs” are lightweight, self-contained Python installations designed to be set up with minimum fuss, and to “just work” without requiring extensive configuration or specialized knowledge.</p><p>At its core, the purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its dependencies, regardless of what dependencies every other project has.</p><p>In the example above, we created a separate virtual environment for both <strong><em>Project A</em></strong> and <strong><em>Project</em></strong>. Each environment, in turn, would be able to depend on whatever version of <strong><em>Project C</em></strong> they choose, independent of the other.</p><p>virtualenv avoids the need to install Python packages globally. When a virtualenv is active, pip will install packages within the environment, which does not affect the base Python installation in any way.</p><p>For more details you use the below links.</p><ul><li><a href="https://www.sitepoint.com/virtual-environments-python-made-easy/">Python Virtualenv: Virtual Environments in Python Made Easy - SitePoint</a></li><li><a href="https://github.com/pyenv/pyenv/blob/master/README.md">pyenv/README.md at master · pyenv/pyenv</a></li><li><a href="https://docs.python.org/3/tutorial/venv.html">12. Virtual Environments and Packages</a></li><li><a href="https://realpython.com/python-virtual-environments-a-primer/">Python Virtual Environments: A Primer - Real Python</a></li></ul><blockquote>Thank You</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f95c328dd75f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Django logging]]></title>
            <link>https://medium.com/@ravisarath64/introduction-to-django-logging-87e309eecfbe?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/87e309eecfbe</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 07:50:23 GMT</pubDate>
            <atom:updated>2021-08-04T07:50:23.579Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Is logging important in your application?</blockquote><p>Well, logging is very critical if you want to diagnose problems or understand what’s happening with your application.</p><p>Keeping a record of all data input, processes, data output, and final results in your application is very much helpful to diagnose the problems not only in your local environment but also in the production environment. A huge amount times of software developers are spending for monitoring, troubleshooting and debugging. Logging makes their job much easier.</p><p>“I don’t want to read all this bull shit. I just need the code.”</p><p>Hey wait you must read the all this bull shit becouse it will give something important you need to follow or you must remember before development. So don’t approach anything with prejudice</p><blockquote><strong>Let’s start the code</strong></blockquote><p>So our Django app use python logging module to perform system loggings. Don’t worry logging is a part of python standard library. You don’t need to pip install anything.</p><p>So you have to place code at the top of your files</p><pre>import logging</pre><pre>logger = logging.getLogger(__name__)</pre><p>Hey, what’s that ‘__name__’?</p><p>__name__ is a built-in variable which evaluates to the name of the current module.</p><p>This logger then can be used to emit simply-formatted messages at different log levels (<strong>DEBUG</strong>, <strong>INFO</strong>, <strong>WARNING</strong>, <strong>ERROR</strong>, <strong>CRITICAL</strong>.), which again can be used by the application to handle messages of higher priority different than those of a lower priority.</p><p>Let’s see some examples.</p><pre># “warning” level</pre><pre>logger.warning(&quot;Your log message is here&quot;)</pre><pre>#  “info” level</pre><pre>logger.info(&quot;The value of var is %s&quot;, var)</pre><p>If you call the logger in the try except block, the caught exception will automatically be fully logged, including the trace.</p><pre>try:<br>    &#39;&#39;&#39;do something…..&#39;&#39;&#39;<br>except Exception as e: <br>    logger.error(f&#39; Caught an error, {e}&#39;)</pre><blockquote><strong>Let’s Configure logging with Django.</strong></blockquote><p>To begin, here’s a small configuration that will allow you to output all log messages to the console:</p><pre>import os</pre><pre>LOGGING = {<br>    &#39;version&#39;: 1,<br>    &#39;disable_existing_loggers&#39;: True,<br>    &#39;formatters&#39;: {<br>        &#39;standard&#39;: {<br>            &#39;format&#39; : &quot;[%(asctime)s] %(levelname)s [%(name)s:%.  (lineno)s] %(message)s&quot;,<br>            &#39;datefmt&#39; : &quot;%d/%b/%Y %H:%M:%S&quot;<br>        },<br>    },<br>    &#39;handlers&#39;: {<br>        &#39;null&#39;: {<br>            &#39;level&#39;:&#39;DEBUG&#39;,<br>            &#39;class&#39;:&#39;django.utils.log.NullHandler&#39;,<br>        },<br>        &#39;logfile&#39;: {<br>            &#39;level&#39;:&#39;DEBUG&#39;,<br>            &#39;class&#39;:&#39;logging.handlers.RotatingFileHandler&#39;,<br>            &#39;filename&#39;: SITE_ROOT + &quot;/logfile&quot;,<br>            &#39;maxBytes&#39;: 50000,<br>            &#39;backupCount&#39;: 2,<br>            &#39;formatter&#39;: &#39;standard&#39;,<br>        },<br>        &#39;console&#39;:{<br>            &#39;level&#39;:&#39;INFO&#39;,<br>            &#39;class&#39;:&#39;logging.StreamHandler&#39;,<br>            &#39;formatter&#39;: &#39;standard&#39;<br>        },<br>    },<br>    &#39;loggers&#39;: {<br>        &#39;django&#39;: {<br>            &#39;handlers&#39;:[&#39;console&#39;],<br>            &#39;propagate&#39;: True,<br>            &#39;level&#39;:&#39;WARN&#39;,<br>        },<br>        &#39;django.db.backends&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;propagate&#39;: False,<br>        },<br>        &#39;MYAPP&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;, &#39;logfile&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>        },<br>    }<br>}</pre><p>Let’s discuss each line by line.</p><p><strong>Version</strong> :- Setting to ensures backward compatibility.</p><p><strong>disable_existing_loggers</strong> :- This setting disables existing loggers.</p><p>The default value is False, but it doesn’t hurt to be explicit. When setting this to True, define additional loggers. Otherwise, messages may be lost.</p><p><strong>Formaters</strong> :- This section defines what our log statements will look like.</p><p>%(name)<strong><em> </em></strong><em>:- </em>package name that emits the log message</p><p>%(levelname) :- Log level of the message (ERROR, WARNING, INFO, etc.)</p><p>%(message)<em> :- A</em>ctual log message</p><p>%(asctime)<strong><em> </em></strong><em>:- </em>This adds a timestamp to each message sent through the file handler.</p><p><strong>Handlers</strong> :- This section defines how to handle log messages.</p><p>We can send messages to the console, files, or even sockets! etc . This configuration defines separate handlers: one for console messages and another for messages sent to the file. In addition, for the file handler we specify the handler class, the filename to log to, and the log level. This handler also specifies which formatter to use.</p><p><strong>Loggers</strong> :- This section defines where we tie it all together and define our loggers, including how to handle the root logger (represented by the empty string) messages.</p><p>We also set the logging level to <em>DEBUG</em> and define two handlers, one to the console and one to the file.</p><blockquote><strong>Let’s discuss about some other Django’s logging extensions</strong></blockquote><p>Django provides several built-in loggers to handle the unique requirements of logging in Web server environment.</p><h4>django</h4><p>The catch-all logger for messages in the <strong>django</strong> hierarchy. No messages are posted using this name but instead using one of the loggers below.</p><pre>&#39;loggers&#39;: {<br>        &#39;django&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;propagate&#39;: True,<br>        },<br>    },</pre><h4>django.request</h4><p>Log messages related to the handling of requests. 5XX responses are raised as <strong>ERROR</strong> messages; 4XX responses are raised as <strong>WARNING</strong> messages.</p><p>Messages to this logger have the following extra context:</p><ul><li><strong>status_code</strong>: The HTTP response code associated with the request.</li><li><strong>request</strong>: The request object that generated the logging message.</li></ul><pre>&#39;loggers&#39;: {   <br>      &#39;django.request&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;propagate&#39;: True,<br>        },<br>}</pre><h4>django.server</h4><p>Log messages related to the handling of requests received by the server invoked by the runserver command. HTTP 5XX responses are logged as <strong>ERROR</strong> messages, 4XX responses are logged as <strong>WARNING</strong> messages, and everything else is logged as <strong>INFO</strong>.</p><pre>&#39;loggers&#39;: {   <br>      &#39;django.request&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;propagate&#39;: True,<br>        },<br>}</pre><h4>django.template</h4><p>Log messages related to the rendering of templates.</p><pre>&#39;loggers&#39;: {   <br>      &#39;django.template&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>        },<br>}</pre><h4>django.db.backends</h4><p>Messages relating to the interaction of code with the database. For example, every application-level SQL statement executed by a request is logged at the <strong>DEBUG</strong> level to this logger. Messages to this logger have the following extra context:</p><ul><li><strong>duration</strong>: The time taken to execute the SQL statement.</li><li><strong>sql</strong>: The SQL statement that was executed.</li><li><strong>params</strong>: The parameters that were used in the SQL call.</li></ul><pre>&#39;loggers&#39;: {   <br>      &#39;django.db.backends&#39;: {<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>            &#39;level&#39;: &#39;ERROR&#39;,<br>            &#39;propagate&#39;: True,<br>        }<br>}</pre><h4>django.security.</h4><p>The security loggers will receive messages on any occurrence of <strong>Suspicious Operation</strong> and other security-related errors. There is a sub-logger for each subtype of security error, including all <strong>Suspicious Operation’s</strong>. The level of the log event depends on where the exception is handled. Most occurrences are logged as a warning, while any <strong>Suspicious Operation </strong>that reaches the WSGI handler will be logged as an error. For example, when an HTTP <strong>Host</strong> header is included in a request from a client that does not match allowed_host, Django will return a 400 response, and an error message will be logged to the <strong>django.security.DisallowedHost</strong> logger.</p><pre>&#39;loggers&#39;: {<br>    &#39;django.security.DisallowedHost&#39;: {<br>        &#39;handlers&#39;: [&#39;console&#39;],<br>        &#39;propagate&#39;: False,<br>    },<br>},</pre><p>Other <strong>django.security</strong> loggers not based on <strong>SuspiciousOperation</strong> are:</p><ul><li><strong>django.security.csrf</strong>: For CSRF Failure.</li></ul><blockquote><strong>Conclusion</strong></blockquote><p>So Django uses the standard Python logging facilities for logging. If you need to delve further, use the below links.</p><p><a href="https://realpython.com/python-logging/">https://realpython.com/python-logging/</a></p><p><a href="https://www.scalyr.com/blog/getting-started-quickly-django-logging">https://www.scalyr.com/blog/getting-started-quickly-django-logging</a></p><blockquote><strong><em>Thank YOU</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87e309eecfbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you working on Django? is celery confuse you?]]></title>
            <link>https://medium.com/@ravisarath64/are-you-working-on-django-is-celery-confuse-you-629fedf8287b?source=rss-a6e561985cdb------2</link>
            <guid isPermaLink="false">https://medium.com/p/629fedf8287b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[celery]]></category>
            <dc:creator><![CDATA[Sarath Ravi]]></dc:creator>
            <pubDate>Thu, 29 Jul 2021 02:51:46 GMT</pubDate>
            <atom:updated>2021-08-06T06:23:59.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ebqXeX88dFY9FWbFIvMfHw.png" /></figure><p>Working on technologies like celery can be confusing at first. But it is not as hard as you think. I will briefly explain Celery and its uses while working with Django in this article.</p><p>Celery is a nice tool to use whenever you don’t want to wait for some other process to finish. Let us see this with an example.</p><p>in the normal way</p><pre>User sends request<br>Django receives =&gt; spawns a thread to do something else.<br>wait for the main thread to finishes &amp; the other thread to finishes after completion of both tasks<br>response is sent to the user as a package                          😭 --&gt; it takes too much time.</pre><p>by using celery</p><pre>User sends request<br>Django receives =&gt; lets Celery know &quot;hey! do this!&quot;<br>main thread finishes<br>response is sent to the user<br>The user receives the balance of the transaction                           😄 --&gt; it&#39;s so fast</pre><p>Can Django do multi-thread works? Yes it can do multi-thread works, but generally one uses Celery to do the equivalent</p><p>Wait a minute what is <strong>single-threaded</strong> &amp; <strong>multi-threaded</strong>?</p><p>Single-threaded processes contain the execution of instructions in a single sequence whereas, multithreaded processes<strong> </strong>allow the execution of multiple parts of a program at the same time.</p><blockquote><strong>let&#39;s look into deep.</strong></blockquote><p>Celery is an asynchronous queue/job based on distributed message passing. For managing the queue, Celery requires a solution to send and receive messages; usually, this comes in the form of a separate service called a <em>message broker</em>.</p><p>Redis, RabbitMQ, Amazon SQS are the choices available for brokers.</p><p>With <strong>Asynchronous </strong>execution, you will begin a task and while running the task in the background you can start your next task, then at some point, say “wait for this to finish”. Let’s look at an example:</p><pre>Django says =&gt; Celery starts a task A.</pre><pre>Django says =&gt; Celery starts a task B.</pre><pre>Django says =&gt; Celery starts a task C.</pre><pre>at some point Celery says =&gt;  <strong><em>Wait</em> for A to finish</strong></pre><p>The advantage is that you can execute both tasks B &amp; C while A is still running in the background, on a separate thread. This allows you to take better advantage of your resources.</p><p>Is celery used only for this?</p><p>No, it supports scheduling as well. Let us see this with an example.</p><pre>User sends request<br>Django receives =&gt; Celery send an email at midnight for the user.<br>main thread finishes</pre><pre>the response is sent to the user</pre><p>Celery sends the email at midnight. This is how task scheduling is done in celery.</p><p>Let us see another example.</p><pre>User sends request<br>Django receives =&gt; Celery sent alert to the user in every 10 min.<br>main thread finishes</pre><pre>the response is sent to the user</pre><p>celery will send an alert to the user every 10 mins. so celery can be used to schedule as well as to do the periodic task.</p><blockquote><strong>Let’s see how to install celery.</strong></blockquote><p>You can install celery using standard Python tools like pip or easy_install:</p><pre>pip install celery</pre><blockquote><strong>Now connect the celery to your application</strong></blockquote><p>First, you have to add the broker URL in project settings.py. You can use either Redis or RabbitMQ. Here I am using Redis</p><pre>BROKER_URL = &#39;redis://localhost:6379&#39;</pre><p>Add a new file called <strong><em>celery.py</em></strong><em> i</em>nside your Django project</p><pre>from __future__ import absolute_import<br>import os<br>from celery import Celery<br>from django.conf import settings<br><br># set the default Django settings module for the &#39;celery&#39; program.<br>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;project.settings&#39;)<br>app = Celery(&#39;picha&#39;)<br><br># Using a string here means the worker will not have to<br># pickle the object when using Windows.<br>app.config_from_object(&#39;django.conf:settings&#39;)<br>app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)</pre><pre># If you need to schedule a task or run a task periodically  you can # add this code </pre><pre>app.conf.beat_schedule = {                                                               <br>   # to run a task daily at 12.30 AM midnight                                &#39;generate_daily_settlement_report’: {<br>        &#39;task’: &#39;app.tasks.function_A’,<br>        &#39;schedule’: crontab(hour=1, minute=30),<br> },<br>   # to run a task in every 30 seconds<br> &#39;add-every-30-seconds’: {<br>        &#39;task’: &#39;app.tasks.function_B’,<br>        &#39;schedule’: <strong>30.0</strong>,<br>        &#39;args’: (<strong>16</strong>, <strong>16</strong>)<br>  },<br>}</pre><pre>@app.task(bind=True)<br>def debug_task(self):<br>    print(&#39;Request: {0!r}&#39;.format(self.request)) </pre><p>Next, we will create a file <strong>tasks.py</strong> in your app. Then create the functions, function_A, function_B, etc in your app.</p><pre>from celery.decorators import task<br><br>@task(name=&quot;function A&quot;)<br>def function_A():<br>    &#39;&#39;&#39;do something &#39;&#39;&#39;</pre><pre>@task(name=&quot;function B&quot;)<br>def function_B():<br>    &#39;&#39;&#39;do something &#39;&#39;&#39;</pre><pre>@task(name=&quot;function C&quot;)<br>def function_C():<br>    &#39;&#39;&#39;do something &#39;&#39;&#39;</pre><p>let the function_C another celery task to do something else. This function can be called from our view using the <a href="https://docs.celeryproject.org/en/stable/reference/celery.app.task.html#celery.app.task.Task.delay"><strong>delay()</strong></a> method. So we can do the task in other threads without affecting the main thread</p><pre>function_C.delay()</pre><p>What’s next?</p><p>we have to run the celery worker server</p><blockquote><strong>let’s run the celery worker server</strong></blockquote><p>You can now run your worker by executing the program with the worker argument:</p><pre>celery -A tasks worker --loglevel=INFO</pre><p>so the worker will execute the task. we have another argument called beat which will kick the periodic as well as scheduled tasks.</p><pre>celery -A tasks beat --loglevel=INFO</pre><p>celery beat is <strong>a scheduler</strong>; It kicks off tasks at regular intervals, that are then executed by available worker nodes in the cluster. By default, the entries are taken from the beat_schedule setting, but custom stores can also be used, like storing the entries in a SQL database.</p><p>Celery beat is <strong>a scheduler</strong>. It kicks off tasks at regular intervals, which are then executed by available worker nodes in the cluster. By default, the entries are taken from the beat_schedule setting, but custom stores can also be used, like storing the entries in an SQL database.</p><p>A short version of the steps you need to do:</p><ul><li>Run your Django and Redis.</li><li>Open two new terminal windows/tabs.</li><li>In each new window, navigate to your project directory.</li><li>Activate your virtualenv.</li><li>Run the celery beat and worker commands.</li></ul><blockquote>Conclusion</blockquote><p>This stuffs are only for beginners for more details you use the below links.</p><ul><li><a href="https://realpython.com/asynchronous-tasks-with-django-and-celery/">Asynchronous Tasks With Django and Celery - Real Python</a></li><li><a href="https://www.technoarchsoftwares.com/blog/optimization-using-celery-asynchronous-processing-in-django/">Optimization using Celery: Asynchronous Processing in Django | Technoarch Softwares</a></li></ul><blockquote><strong>Thank YOU</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629fedf8287b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>