<?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 Sadhana Jaiswal on Medium]]></title>
        <description><![CDATA[Stories by Sadhana Jaiswal on Medium]]></description>
        <link>https://medium.com/@sadhanajaiswal?source=rss-8d39fcda5b05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iTz2LSyYu3CrbM3H</url>
            <title>Stories by Sadhana Jaiswal on Medium</title>
            <link>https://medium.com/@sadhanajaiswal?source=rss-8d39fcda5b05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:35:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sadhanajaiswal/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[Notes on Git log, diff and show]]></title>
            <link>https://medium.com/@sadhanajaiswal/notes-on-git-log-diff-and-show-8c17a538aaea?source=rss-8d39fcda5b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c17a538aaea</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github-pages]]></category>
            <dc:creator><![CDATA[Sadhana Jaiswal]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 17:01:16 GMT</pubDate>
            <atom:updated>2020-09-06T17:01:16.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*wkR3mRJMl1WkxKwWcmiQcg.jpeg" /></figure><p>Git is a version control system used by wide range of software developers. It includes many command to do the thing. Here, we focus on log, diff and show commands and I am hoping you already have basic experience with github and git commands. If not then check some tutorial for git beginner level.</p><p>In this post, We learn many effective way are using these.</p><h3><strong>Magical part of Git Log</strong></h3><ul><li><strong>git log</strong></li></ul><p>It shows commit history with all details. By default this command displays the commit SHA, author, date and message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*j6U-1qE-ZFzHCA5vV8fjJw.png" /></figure><p>To scroll through the commit messages press up arrow to move up and q to quit out of the log.</p><ul><li><strong>— oneline</strong></li></ul><p>This command lists one commit per line. This we use when we just want to look on only commit message and SHA.</p><pre>git log --oneline</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*HynoUskQSMO16f4ZuATB_g.png" /></figure><p>Shows the first 7 characters of the commit SHA and the commit message and nothing more.</p><ul><li><strong>— stat</strong></li></ul><p>This command shows each commit in more details.</p><ol><li>show number of files have been modified, number of lines have been added or removed.</li><li>along with author name, date, commit message</li></ol><pre>git log --stat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Y19r4FmZhDgl-EjJtqCZXA.png" /></figure><ul><li><strong>-p / — patch</strong></li></ul><p>This displays following info..</p><ol><li>The files that have been modified,</li><li>Location of the lines that have been added or removed and the actual changes that have been made.</li><li>along with author name, date, commit message</li></ol><pre>git log -p<br>or <br>git log --patch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*nr8ZtCR5oYOOq1--tGkr8A.png" /></figure><p>It actually shows the code and place where the changes happened.</p><ul><li><strong>— graph</strong></li></ul><p>Draw a text-based graphical representation of the commit history on the left hand side of the output. This graph shows not only the commits (as asterisks *) but also their “parent” commits.</p><pre>git log --graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*2rUvC8PU73I69WO9j9kbrQ.png" /></figure><p>— graph, mostly use in case of checking merge flow and branch or commit in commit history. There are may other options you could use in combination with --graph. Couple of them are --decorate and --all. Try out with --graph.</p><h3><strong>Git Diff</strong></h3><ul><li><strong>— diff</strong></li></ul><p>Diff command is used in git to track the difference between the changes made on a file. <em>Diff</em> command takes two commit id (SHA) and reflects the differences between them.</p><pre>git --diff &lt;old commit&gt; &lt;new commit&gt;</pre><ul><li><strong>— difftool</strong></li></ul><p>This is a Git command that allows you to compare and edit files between revisions using common diff tools(like beyond compare editor or similar). You should have any comparison tool when use “git difftool”</p><pre>git --difftool  &lt;old commit&gt; &lt;new commit&gt;</pre><h3><strong>Git Show</strong></h3><ul><li><strong>show</strong></li></ul><p>git-show is a command line utility that is used to view expanded details on Git objects such as blobs, trees, tags, and commits. git-show has specific behavior per object type.</p><ol><li>Tags show the tag message and other objects included in the tag.</li><li>Trees show the names and content of objects in a tree.</li><li>Blobs show the direct content of the blob.</li><li>Commits show a commit log message and a diff output of the changes in the commit.</li></ol><pre>git show<br>git show HEAD<br>git show &lt;commit&gt;<br>...</pre><p><strong>Tricks with git log</strong></p><ul><li>filter commit by author name</li></ul><pre>git log --author=&quot;sadhana&quot;</pre><ul><li>filter commit by date</li></ul><pre>git log --after=&quot;2020-15-05&quot;</pre><pre>git log --after=&quot;2020-15-05&quot; --before=&quot;2020-25-05&quot;</pre><pre>git log --after=&quot;yesterday&quot; // shows only commits from yesterday</pre><pre>git log --after=&quot;today&quot; // shows only today commits </pre><pre>git log --before=&quot;10 day ago&quot; // omits last 10 days commits </pre><pre>git log --after=&quot;1 week ago&quot; //show only commits from last week </pre><pre>git log --after=&quot;2 week ago&quot; </pre><pre>git log --after=&quot;2 month ago&quot; // shows only last 2 months commits</pre><ul><li>filter commit by log message</li></ul><pre>git log --grep=&quot;fix calculation&quot;</pre><ul><li>show only merge commit</li></ul><pre>git log --merges</pre><ul><li>filter commit by files</li></ul><pre>git log main.py</pre><p>These are the basic level but strong things to know. It often require to use in our workplace and make our work easy. Finding any commit details or checking difference between two commit or files.</p><p>Hope this have help to you.</p><p>Thank you for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c17a538aaea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elasticsearch with django]]></title>
            <link>https://medium.com/@sadhanajaiswal/elasticsearch-with-django-2fde0b963fd6?source=rss-8d39fcda5b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fde0b963fd6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Sadhana Jaiswal]]></dc:creator>
            <pubDate>Mon, 04 May 2020 12:02:50 GMT</pubDate>
            <atom:updated>2020-05-04T12:02:50.040Z</atom:updated>
            <content:encoded><![CDATA[<p>Searching data into a huge data source, its’t easy in terms of speed, data accuracy if developing logic in basic way. But elasticsearch make it possible to get data based on given query. Implementing elasticseach in django, there are may way and it make you overwhelmed, just in think of picking best way.</p><p>Elasticsearch run on its own server and for communicating that server we need python libraries to do that.</p><h3><strong>First:- need to do setting to run elasticsearch server</strong></h3><h4>1. Elasticsearch Setup</h4><ul><li>mkdir elasticsearch-library</li><li>open this <a href="https://www.elastic.co/downloads/elasticsearch">https://www.elastic.co/downloads/elasticsearch</a></li><li>download elasticsearch based on your system</li><li>tar -xzf elasticsearch-5.1.1.tar.gz (extract downloaded elasticsearch folder)</li><li>cd elasticsearch-library</li><li>./elasticsearch-5.1.1/bin/elasticsearch (start elasticsearch server)</li></ul><h3>Second:- communication between elasticsearch and django</h3><p>I am using these below library</p><blockquote><em>elasticsearch.py,</em></blockquote><blockquote><em>elasticseach-dsl</em></blockquote><blockquote><a href="https://django-elasticsearch-dsl-drf.readthedocs.io/en/latest/#id1"><em>django-elasticsearch-dsl-drf</em></a></blockquote><p><strong>Note — </strong>if you know django project concept and structure and how it works then you are ready to go on. but if not then no worry, just open django doc and try to learn how to create a simple django project and that’s enough.</p><p><strong>Task :- </strong>to implement search engine in library project. search_engine provides an API that take a list of queries and an integer K and returns the top K matched books as list.</p><p>project link for reference</p><p><a href="https://github.com/sadhanaj28/search_engine"><em>https://github.com/sadhanaj28/search_engine</em></a></p><p><strong>File Structure</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*kHycyU-FoEnMBSfjQib6fw.png" /></figure><ol><li><strong>Install required libraries</strong></li></ol><p>pip install elasticsearch</p><p>pip install elasticsearch-dsl==0.0.2</p><p>pip install django-elasticsearch-dsl</p><p>pip install django-elasticsearch-dsl-drf</p><p>2. declare these libraries into “INSTALLED_APPS” in settings.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*XpSTpvD4wUdo849_9E94lQ.png" /></figure><p>3. define the elasticsearch server connection into settings.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*PJuMaIkZN9bVcGYXJpwCZA.png" /></figure><p><strong>Note:- </strong>localhost used in your local system but in production, then modify this host with production’s one elasticsearch server</p><p>3. search_engine/models.py — Define a model for Summaries table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*ONEWAHYePysOMN2OwUu_Fw.png" /></figure><p>4. search_engine/documents.py — Define an elastic_document for the model which data is going to be used in filter or search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weDR-F-K5m5FZQkLHLsBHw.png" /></figure><p>here creating connection with elasticsearch and also defining an index’s structure, which will be replicas of specified model(Summaries)</p><pre># create the connection with ELASTICSEARCH server<br>connections.create_connection(hosts=[&#39;localhost&#39;])</pre><p>It’s pretty good if you spend more time to understand, what is elasticsearch analyzer. Below link have very nice and in details about this. Enjoy and have fun.</p><p><a href="https://qbox.io/blog/introduction-to-elasticsearch-analyzers">Introduction to Elasticsearch Analyzers</a></p><p>5. search_engin/helps.py — edefining elasticsearch instance and adding query to filter/fetch data. add code in helps.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yAGHPmrfErST5pUOesSIQ.png" /></figure><pre>q = Q(&#39;bool&#39;, must=[Q(&#39;match&#39;, summary=self.query), ])</pre><p>Above syntax to define to query, here query means, bring the data which must match the given keywords(self.query) into summary’s data. ‘summary’ is a field-name in Summaries model.</p><pre># adding elastic search query,<br># sort filtered result based on _score,<br># result&#39;s length start from 0 to self.size<br>search_with_query = self.search_instance.query(q).sort(&#39;_score&#39;)[0:self.size]</pre><p>Here, q is getting add with elasticsearch instance using .query() method.</p><p>.sort() -&gt; this is used for sorting the elasticsearched’s result data.</p><p>[0:self.size] -&gt; here self.size could be any value. Suppose self.size=5, then it means in the above code, to show the top 5 records which start from 0 till 4 index. ( 0, 1, 2, 3, 4)</p><pre># execute elastic query<br>response = search_with_query.execute()</pre><p>Here finally, executing query.</p><pre>result = response.to_dict()[&#39;hits&#39;][&#39;hits&#39;]</pre><p>Might be you wonder about [‘hits’][‘hits’], actually it is part of elasticsearch’s output structure.</p><p>main filtered/searched data would be in [‘_source’] which would be inside [‘hits’][‘hits’].</p><p>Example , I guess now it is clear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*Iijjfzz6tKFf72bAfHOpaw.png" /></figure><p>6. search_engine/utils.py — To create and populate the Elasticsearch index and mapping use the search_index command::</p><p>$ python manage.py search_index — rebuild</p><p>so for running this command, use call_command method in django.</p><pre><em>&quot;&quot;&quot;<br>utils file, contains code which are generic<br>&quot;&quot;&quot;<br></em>from django.core.management import call_command<br><br><br># run elastic search command to rebuild index<br>def rebuild_elasticsearch_index():<br>    call_command(&#39;search_index&#39;, &#39;--rebuild&#39;, &#39;-f&#39;)<br><br><br># run elastic search command to delete index<br>def delete_elasticsearch_index():<br>    call_command(&#39;search_index&#39;, &#39;--delete&#39;, &#39;-f&#39;)</pre><p>7. search_engine/view.py, now using elasticsearch logic in view</p><pre><em>&quot;&quot;&quot;<br>View file<br>&quot;&quot;&quot;<br></em>import logging<br>from rest_framework.views import APIView<br>from rest_framework import status<br>from rest_framework.response import Response<br>import elasticsearch<br><br>from .documents import SummariesDocument<br>from .helps import ElasticSearchBookService<br>from .utils import is_empty_or_null, rebuild_elasticsearch_index, delete_elasticsearch_index<br><br># Get an instance of a logger<br>logger = logging.getLogger(__name__)<br><br><br>class SummarySearchView(APIView):<br><br>    <em>&quot;&quot;&quot;<br>    format the response with message, status, data<br>    and send as api response<br>    &quot;&quot;&quot;<br>    </em>def __send_response(self, message, status_code, data=None):<br>        content = {<br>            &quot;message&quot;: message,<br>            &quot;result&quot;: data if data is not None else []<br>            }<br>        return Response(content, status=status_code)<br><br>    &quot;&quot;&quot;<br>    handle post request<br>    filter the sammmaries data based on given query list with k number <br>    &quot;&quot;&quot;<br>    def post(self, request):<br>        query = request.data.get(&#39;queries&#39;, None)<br>        k = request.data.get(&#39;k&#39;, None)<br>        # response = None<br><br>        if is_empty_or_null(query):<br>            error_message = &quot;queries should not be empty&quot;<br>            return self.__send_response(error_message, status.HTTP_400_BAD_REQUEST)<br><br>        if is_empty_or_null(k):<br>            error_message = &quot;k should be integer and not empty&quot;<br>            return self.__send_response(error_message, status.HTTP_400_BAD_REQUEST)<br><br>        try:<br>            # build elastic search index<br>            rebuild_elasticsearch_index()<br><br>            # build search instance using SummariesDocument and save query_list and k as instance value<br>            search_doc = ElasticSearchBookService(SummariesDocument, query, k)<br><br>            # run each query using search instance<br>            result = search_doc.run_query_list()<br>            response = {&#39;books&#39;: result}<br><br>            # delete elastic search index<br>            delete_elasticsearch_index()<br><br>        except elasticsearch.ConnectionError as connection_error:<br>            # ConnectionError if elasticsearch server is down<br>            logger.debug(&#39;ConnectionError: &#39; + str(connection_error))<br>            error_message = &quot;Elastic search Connection refused&quot;<br>            return self.__send_response(error_message, status.HTTP_503_SERVICE_UNAVAILABLE)<br><br>        except Exception as exception_msg:<br>            # handle all type of error<br>            logger.debug(&#39;Exception: &#39; + str(exception_msg))<br>            error_message = str(exception_msg)<br>            return self.__send_response(error_message, status.HTTP_400_BAD_REQUEST)<br><br>        return self.__send_response(&#39;success&#39;, status.HTTP_200_OK, response)</pre><p>8. search_engine/urls.py — define the url for the above SummarySearchView</p><pre>from django.urls import path<br><br>from .views import SummarySearchView<br><br><br>urlpatterns = [<br>    path(&#39;api/v1/summaries_list/&#39;, SummarySearchView.as_view(), name=&#39;summaries-list&#39;),<br>]</pre><p>9. library/urls.py — import search_engine/urls.py into main urls</p><pre>from django.conf import settings<br>from django.conf.urls import include<br>from django.urls import path<br><br>from search_engine import urls as search_engine_urls<br><br><br>urlpatterns = [<br>    path(&#39;search_engine/&#39;, include(search_engine_urls)),<br>]</pre><p>10. vaaaalaaaa, done</p><p>11. run the django server</p><blockquote>python manager.py runserver</blockquote><p>Hope it will help you. Thankyou for your time. If any doubts, please ask in comment. I will response as soon as possible.</p><p>Thankyou</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fde0b963fd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Best Practices— Project Layout]]></title>
            <link>https://medium.com/@sadhanajaiswal/django-best-practices-project-layout-532ea4887751?source=rss-8d39fcda5b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/532ea4887751</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <dc:creator><![CDATA[Sadhana Jaiswal]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 22:05:05 GMT</pubDate>
            <atom:updated>2020-04-01T22:05:05.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UUjmXlDokPKPblr9pw596g.jpeg" /></figure><ul><li><strong>Default Django project layout — </strong>it get created when run following command on terminal</li></ul><blockquote>$ django-admin.py startapp my_app</blockquote><p><strong>Note</strong> — There are a number of problem with django’s default project layout. Its useful for tutorial but not useful in Real project.</p><h3><strong>Fundamentals of django App design</strong></h3><p>Django ( Project )— web framework</p><p>Django App — are small libraries designed to represent a single aspact of a project.</p><p>Dajngo project is made up of many django app.</p><p>INSTALLED-APPS — List of app/libraries</p><h3><strong>The golden rule of django app design</strong></h3><ul><li><strong>“</strong>the art of creating and maintaining a good django app is that it should follow the truncated Unix philosophy according to Douglas Mcllroy<strong>: Write programs that do one thing and do it well ”.</strong></li><li>Each app should be tightly focussed on its task.</li><li><strong>Need to divide App — </strong>When app is too big.</li></ul><h3><strong>Name your django App</strong></h3><ul><li>Possibly, keep to single word name like (flavours, animal)</li><li>The app’s name should be a plural version of the app’s main model. But there are same exception.</li><li>Don’t just consider the app’s main model. You should also consider how you want your URLs to appear when choosing a name.</li></ul><p><a href="https://www.example.com/weblog/">https://www.example.com/weblog/</a></p><p>Then consider naming your app weblog rather than “blog”, ‘post’ even if main model is “blog”. This style make easier for us to see which app corresponds with which part of site.</p><h3>Doubts, Keep Apps small</h3><ul><li>Design an app is as art. Sometimes you have to rewrite or break them up. That’s okay.</li><li><strong>Try to keep it small</strong></li></ul><h3>Modules Belongs in an App</h3><ul><li><strong>Common App Modules</strong> — python package</li><li><strong>Uncommon App Modules — </strong>following are</li></ul><ol><li><strong>behaviors.py</strong> — An option for locating model mixin.</li><li><strong>constants.py </strong>— A good name for placement of app-level settings. If there are enough of them involved in an app, breaking them out into their own module, this can add clarity to a project.</li><li><strong>decorators.py</strong> — Where to locate our decorators.</li><li><strong>db/</strong> — Used in many projects for any custom model fields or components.</li><li><strong>fields.py</strong> — is commonly used for form fields, but is sometimes used for model fields when there is not enough field code to justify creating a db/ package.</li><li><strong>factories.py</strong> — where to place test data factories</li><li><strong>helpers.py </strong>— also as <strong>utils.py</strong>. Here we put code extracted from view and models to make them lighter. code would be reusable.</li><li><strong>managers.py</strong> — When models.py grows too large, to move any custom model managers to this modules.</li><li><strong>signals.py</strong> — custom signals</li><li><strong>utils.py </strong>— helpers.py</li><li><strong>viewmixins.py </strong>— keeping any view mixin to this</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQRiRJHwsunfTzrDM_gL9g.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=532ea4887751" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Best Practices — Coding Style]]></title>
            <link>https://medium.com/@sadhanajaiswal/django-best-practices-coding-style-7870b398889b?source=rss-8d39fcda5b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/7870b398889b</guid>
            <category><![CDATA[django-girls]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django-framework]]></category>
            <dc:creator><![CDATA[Sadhana Jaiswal]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 20:40:33 GMT</pubDate>
            <atom:updated>2020-03-29T08:36:39.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django Best Practices — Coding Style</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*gytRltoeNeHniBy7Negcgg.jpeg" /></figure><p>First we start with very basic coding best practices.</p><h3><strong>Important of making code readable</strong></h3><ol><li>Avoid abbreviating variable names</li><li>Write out function arguments name</li><li>Document your class and method</li><li>Add comment in your code</li><li>Refactor repeated lines of code into reusable function/class and keep in utils file( make a uilts.py file where keep all common/reusable code ).</li><li>Keep function/methods/class( logical code ) short. A good rule is that scrolling should not be necessary to read on entire function/method/class.</li></ol><p><strong>PEP-8</strong></p><ol><li>use 4 space per indentation level</li><li>separate top-level function/class definition with 2 blank lines</li><li>Method definition inside a class are separated by a single blank line.</li><li>Limit of the text per line is 79 characters(code understandability)</li></ol><h3><strong>DON’T DO</strong></h3><p>Don’t change an existing project conventions. Never pick worse name of variables to fitting code in 79 columns</p><h3>Rules for Import</h3><p>PEP-8 suggests that <strong>import</strong> should be grouped into following order</p><ol><li>standard library import</li><li>Related third-party imports</li><li>local application/library import</li></ol><p>Django import order</p><ol><li>Standard library import</li><li>Import from the core django</li><li>Import from the third library</li><li>Import from local app/library</li></ol><h3>Use Explicit Relative Imports</h3><ol><li>When writing code, it is important to do so in such a way that it is easier to move, rename or version your work.</li><li>In python, explicit import removes the hardcoding a module’s package, separating individual modules from being tightly coupled to the architecture around them.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*dK2r6Z2sTmkxzHwpeOMI_Q.png" /></figure><p><strong>Scenario-1 which cause problem:</strong> What if you wanted to reuse your pizza app in another project, there you have to change pizza name because that project already have app with same name.</p><p><strong>Scenario-2 which cause problem: </strong>What if simply wanted to change the name of app at same point.</p><p>There would be many situation in real time project which cause the problem. The above two requirements we can handle doing manual work. But question here, is it good way doing this? NO</p><p>Good coding containing explicit relative imports,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*HCbb5-jxrE6EYKa8nLCDAw.png" /></figure><p><strong>TIP : </strong>use “from __future__ import absolute_import”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Er1UALlBYhvu12qTfxShJw.png" /></figure><h3><strong>Avoid using import *</strong></h3><ul><li>explicitly import each module.</li></ul><blockquote>from django import forms</blockquote><blockquote>from django.db import models</blockquote><ul><li><strong>Never </strong>do the following</li></ul><blockquote>from django.forms import *</blockquote><blockquote>form django.db.models import *</blockquote><p># bad code</p><blockquote>from django.forms import CharField</blockquote><blockquote>form django.db.models import CharField</blockquote><p>Both libraries have <strong>CharField, </strong>by implicitly loading both, models library overwrote the forms version <strong>CharField.</strong></p><p><strong>Note: </strong>Don’t use “ import * ”, it load unnecessary feature/ overwrite the code, which are not required.</p><h3><strong>Django Coding Style</strong></h3><p>Django have its own coding style, which is given in django official documents.</p><ol><li><a href="https://docs.djangoproject.com/en/3.0/internals/contributing/writing-code/coding-style/">https://docs.djangoproject.com/en/3.0/internals/contributing/writing-code/coding-style/</a></li><li>Use underscore in URL pattern name rather than dashes.</li></ol><p><strong><em>#bad-code</em></strong></p><p><em>url(https://medium.com/regex=%E2%80%99%5Eadd/$%E2%80%99,%20view%20=%20view.add_topping,%20name%20=%20%E2%80%98add-topping%E2%80%99)</em></p><p><strong><em># right-code</em></strong></p><p><em>url(https://medium.com/regex=%E2%80%99%5Eadd/$%E2%80%99,%20view%20=%20view.add_topping,%20name%20=%3C/em%3E%3Cstrong%3E%3Cem%3E%20%E2%80%98add_topping%E2%80%99%3C/em%3E%3C/strong%3E%3Cem%3E)</em></p><h3><strong>Django Project Protocol</strong></h3><p>Before starting coding for project, there are some basic elements, which should pull together in right manner to make base project ready. these all tools/technics make project smooth and strong so that a small group/large team can work easily.</p><ol><li><strong>Use the same database engine everywhere.</strong></li></ol><p>drawback if development database is differ then production database</p><ul><li>you can’t examine a correct database copy of production in local database. ex local database as sqlite and in production database — mysql</li><li>different database have different field type/ constraints</li><li>fixtures are magic solution here.</li></ul><p><strong>Fixtures </strong>— fixture are great for creating simple hardcoded test data sets. Sometimes we need to populate database with fake data during deployment at early stage of project.</p><p><strong>2. Use pip and virtualenv</strong></p><ul><li><strong>pip</strong> — install python package</li><li><strong>virtualenv</strong> — is a tool for creating isolated python environment for maintaining required libraries package for project</li></ul><p><strong>use-case for virtualenv </strong>— can have more than one project with their own dependency libraries in same system</p><p><strong>without virtualenv</strong> — have to reinstall django with that project dependencies at each time when switching to different project.</p><p><strong>TIP — virtualenvwrapper — </strong>this tool help to manage virtual environments. this is doc to follow for setup “<a href="https://virtualenvwrapper.readthedocs.io/en/latest/install.html">https://virtualenvwrapper.readthedocs.io/en/latest/install.html</a>”</p><ul><li>activate virtual env without virtualenv wrapper</li></ul><p>source project_env/bin/activate</p><ul><li>activate virtual env with virtualenv wrapper</li></ul><p>workon project_env</p><p><strong>3. Requirements.txt</strong></p><p>it is a list of python package that you want to install</p><p><strong>4. Version Control System — GIT</strong></p><p><strong>5. Using Isolated Docker container</strong></p><p>Hope this would have help you to understand basic project draw line and basic tool which required at beginning of any project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*HaQt0WKwXdP-i9SyW5q1-g.jpeg" /></figure><p>Thank you for your valuable time .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7870b398889b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Deeper in Python Iterator]]></title>
            <link>https://medium.com/@sadhanajaiswal/diving-deeper-in-python-iterator-3e27b9868025?source=rss-8d39fcda5b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e27b9868025</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iteration]]></category>
            <dc:creator><![CDATA[Sadhana Jaiswal]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 09:08:01 GMT</pubDate>
            <atom:updated>2020-04-03T08:33:47.403Z</atom:updated>
            <content:encoded><![CDATA[<h3>Digging Deeper in Python Iterator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*464BZGClDggjK9bJkTudQQ.jpeg" /></figure><p>We use Iterator on daily basics in python code. this article is about deep learning of iterator.</p><h3>for-loop</h3><p>Python for-loop doesn’t work, the way for-loop work in other language. Python does not have traditional way for-loop. Look at the for-loop syntax in image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNMvR6bxIFulrgcrpK5AyQ.png" /></figure><p>Python have for-loop but it works most like for-each loop. This for loops don’t have index variables. There’s no index initializing, bounds checking, or index incrementing. Python’s for loops do <em>all the work</em> of looping over iterator/list for us.</p><p><strong>A for-loop with an else-clause :- </strong>In python, for-loop have optional “else-clause”. The else-clause gets executed when the for-loop is done else it would not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPsaupgvXue_4PgSxLhw0g.png" /></figure><p><strong>else-clause </strong>would not get execute because for-loop get break.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2-vb80I5Pju448ga2d8Ug.png" /></figure><p><strong>Use of else-clause:-</strong> If we notice, else block get execute when for block is done. we have situations when we need to break out of for-loop when a certain condition is met. And if that condition is never met, then we want to execute a set of statements. We normally use a boolean flag to implement this. Let us see an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NghKvvKs8RJGYyGirCIM3Q.png" /></figure><p>Usages</p><pre>&gt;&gt;&gt; search([&quot;You&quot;, &quot;are&quot;, &quot;awesome!&quot;], &quot;are&quot;)<br>Found word &#39;are&#39;<br>&gt;&gt;&gt; search([&quot;You&quot;, &quot;are&quot;, &quot;awesome!&quot;], &quot;we&quot;)<br>Word &#39;we&#39; was not found!</pre><p>With the else-block, we could avoid the usage of the boolean flag, <em>found_item</em>.</p><h3>Container(Data Structure)</h3><p>Container are data-structure that lives in memory and support ‘membership’ test. It typically hold all values in memory. In python, there are many</p><ol><li>list, deque, ..</li><li>set, frozenset, ..</li><li>dict, defaultdict, counter, ..</li><li>tuple,</li><li>string, etc</li></ol><p>Container is like a real life a box, a house, a ship , where we can store some material(data). Technically, an object is a container when it can be asked whether it contains a certain element. You can perform such membership tests on lists, sets, or tuples alike:</p><pre>&gt;&gt;&gt; assert 1 in [1, 2, 3]      <em># lists</em><br>&gt;&gt;&gt; assert 4 not in [1, 2, 3]<br>Finally you can ask a string if it &quot;contains&quot; a substring:<br>&gt;&gt;&gt; s = &#39;foobar&#39; <br>&gt;&gt;&gt; assert &#39;b&#39; in s <br>&gt;&gt;&gt; assert &#39;x&#39; not in s</pre><p><strong>NOTES</strong></p><ol><li>Even though most containers provide a way to produce every element they contain, that ability does not make them a container but an iterable.</li><li>Not all containers are necessarily iterable.</li></ol><h3>Sequences</h3><p>An <strong>iterable</strong> is anything you can loop over with a for loop in Python. Iterables can be looped over and anything that can be looped over is an iterable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*rFpd8yA6F7pfWr4bomF5rQ.png" /></figure><p><strong>Sequences</strong> are a very common type of iterable. Lists, tuples, and strings are all sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*mg5O944NBJiKiQBXgGLSxw.png" /></figure><p>Sequences are iterables which have a specific set of features. They can be indexed starting from 0 and ending at one less than the length of the sequence, they have a length, and they can be sliced. Lists, tuples, strings and <em>all other</em> sequences work this way.</p><p><strong>Not Sequesnce: </strong>Lots of things in Python are iterables, but not all iterables are sequences. <strong>Sets</strong>, <strong>dictionaries</strong>, <strong>files</strong>, and <strong>generators</strong> are all iterables but none of these things are sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*TF-W1rAlL5OLMKCh_l0rfw.png" /></figure><p>So anything that can be looped over with a for loop is an iterable and sequences are one type of iterable but Python has many other kinds of iterables as well.</p><h3><strong>Is Loop use INDEX?</strong></h3><p>You might think Python for-loop use indexes to loop over. Here, while-loop code for looping over on indexes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*aXtTzn4hCjbpfLzM0uGLtg.png" /></figure><p>This works for lists, but it won’t work for everything. This way of looping <strong>only works for sequences</strong>.</p><p>If we try to manually loop over a set using indexes, we’ll get an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLjY3c5ghRcQMA7q3NEltQ.png" /></figure><p>Sets are not sequences so they don’t support indexing.</p><p>We <em>cannot</em> manually loop over every iterable in Python by using indexes. This simply won’t work for iterables that aren’t sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*AILokO1zU00Nwe8iB5o77Q.jpeg" /></figure><p><strong>Implementing Custom Sequence Class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0BjuCcvk_gwFhJz6z5fDQ.png" /></figure><p><em>sentence.py: A Sentence as a sequence of words</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YDNfpwawE670nPDvqkqhw.png" /></figure><p><strong>Key-Points</strong></p><ol><li>re.findall returns a list with all non-overlapping matches of the regular expression, as a list of strings.</li><li>self.words holds the result of .findall, so we simply return the word at the given index.</li><li>To complete the sequence protocol, we implement __len__ — , but it is not needed to make an iterable object.</li><li>reprlib.repr is a utility function to generate abbreviated string representations of data structures that can be very large. By default, reprlib.repr limits the generated string to 30 characters.</li><li>Sequence instance is iterable.</li></ol><h3><strong>Why Sequences Are Iterable:</strong></h3><p>Whenever interpreter need to iterate over an object x, it automatically call iter(x).</p><p>Iter() is a build-in function:</p><ol><li>check whether the object implemented, then call __iter__ function.</li><li>if not implemented __iter__, then check if it has implemented __getitem__ function. Python create an iterator that attempts to fetch in order, starting from 0 index.</li><li>If that fails, Python raises TypeError, usually saying that “this object is not iterable. ”</li></ol><p>This is why python sequence has __getitem__() or __iter__().</p><p>An object is consider as iterable if it implements __iter__().</p><p><strong>Non-Sequence</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*GzvitB4TGFAC0oPch2tXSg.png" /></figure><p><strong>Sequence</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7VDSvJuX8QEBa2zN6cdQug.png" /></figure><blockquote>$ False</blockquote><p>As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn’t. This is more accurate than using isinstance(x, abc.Iterable), because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.</p><h3>Iterables Versus Iterators</h3><blockquote><strong>Iterable</strong> — Any object from which iter() build-in function can obtain iterator. Object can implement __iter__() function and returning an iterator are an iterable.</blockquote><blockquote><strong>Relationship between Iterable and Iterator</strong> — Python obtains Iterators from Iterables.</blockquote><p>Ex- simple for-loop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Yh_5TZim9XDY0Gqq6pKiHA.png" /></figure><p>If same logic we do without for-loop then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*P98Oi6tSQpMGboIktqIZIg.png" /></figure><p><strong>Key-Points</strong></p><ol><li>build an iterator ‘it’ from iterable</li><li>repeatedly call next function to obtain next item.</li><li>the iterator raises StopIteration exception when there are no further items.</li><li>release the iterator reference ‘it’.</li><li>Exit the loop</li></ol><ul><li>the StopIteration Exception has handled internally in for-loop, list-comprehensions, tuple-unpacking , etc..</li></ul><p><strong>The standard interface for iterator has two method:</strong></p><p><strong>__next__ :</strong> return next available item, raising StopIteration exception when there is no more items.</p><p><strong>__iter__ :</strong> return self; this allows iterators to be used where iterable to be expected.</p><p>This is formalised in the collections.abc.Iterator ABC, which defines the __next__ abstract method, and subclasses Iterable — where the abstract __iter__ method is defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DBeg6d7hg-LYQzQSM0oZtg.png" /></figure><p><em>The Iterable and Iterator ABCs. Methods in italic are abstract. A concrete Iterable.iter should return a new Iterator instance. A concrete Iterator must implement next. The Iterator.iter method just returns the instance itself.</em></p><p>The Iterator ABC implements __iter__ by doing return self. This allows an iterator to be used wherever an iterable is required.</p><p>The source code for abc.Iterator is in below Example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DB5oMOEGDtFkJI2fXcIBOw.png" /></figure><p>The Iterator ABC abstract method is it.__next__() in Python 3 and it.next() in Python 2. <strong>As usual, you should avoid calling special methods directly. Just use the next(it): this built-in function does the right thing in Python 2 and 3.</strong></p><p>Don’t check the type! Use hasattr to check for both “__iter__” and “__next__” attributes instead. In fact, that’s exactly what the __subclasshook__ method of the abc.Iterator ABC does.</p><p>The best way to check if an object x is an iterator is to call isinstance(x, abc.Iterator). Thanks to Iterator.__subclasshook__, this test works even if the class of x is not a real or virtual subclass of Iterator.</p><p><strong>Iterator process:</strong></p><ol><li>object(x) should be iterable type.</li><li>obtain an iterator(it) from x.</li><li>next(it) fetches the next word.</li><li>if no more words to fetch, then iterator raises StopIteration exception.</li><li>Once exhausted, an iterator become useless.</li><li>to go over object(iterable) again, new iterator must be created.</li></ol><p><strong>Notes</strong></p><ol><li><strong>Is there any other way then __iter__ and __next, to check remaining items: </strong>No<strong>, </strong>Because the only methods required of an iterator are __next__ and __iter__, there is no way to check whether there are remaining items, other than to call next() and catch StopInteration.</li><li><strong>It’s not possible to “reset” an iterator</strong>. If you need to start over, you need to call iter(…) on the iterable that built the iterator in the first place. Calling iter(…) on the iterator itself won’t help, because — as mentioned — Iterator.__iter__ is implemented by returning self, so this will not reset a depleted iterator.</li><li><strong>Iterator is an Iterable:</strong> Python iterators also implement the __iter__ method so they are iterable as well.</li></ol><h3>A Classic Iterator</h3><p>This iterator design pattern will make explicit relationship between the Iterable collection and the Iterator object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*FGu3qEdoEpCXg36ZhjtijA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*t2VJpPNwusXTTRAO7Wy16g.png" /></figure><ol><li>the __iter__ method is only addition from previous example. This does not have __getitem__, to make it iterable has implemented __iter__.</li><li>__iter__ fulfils the iterable protocol by initiating and retering an iterator</li><li>SentenceIterator holds the reference of words.</li><li>self.index is used to determine the next word to fetch.</li><li>get word at self.index</li><li>if there is no word on self.index then raise the StopIteration</li><li>Increment the self.index</li><li>return the word</li><li>implement the self.__iter__</li></ol><p><strong>Notes:</strong></p><ul><li>implementing __iter__ in SentenceInterator , is not really needed for this to work as iterator. Iterator are supposed to implement the __next__ and __iter__ both. it is just Iterator protocal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*F3m77pOUYm4M5MM77gHpSg.jpeg" /></figure><h3><strong>Making Sentence as BAD Iterator</strong></h3><p><strong>To Clear Confusion b/w Iterable and Iterator</strong></p><p>Iterable has __iter__ method that instantiates a new iterator every times.</p><p>Iterator implements __next__ method to return one item at a time, __iter__ to return self.</p><ul><li>Iterators are also an Iterable. but Iterables are not an Iterator.</li></ul><p><strong>Problem</strong></p><p>It may be tempting to implement __next__ in addition to __iter__ in the Sentence class, making each Sentence instance at the same time an iterable and iterator over itself. But this is a terrible idea.</p><p><strong>Use the Iterator pattern</strong></p><ul><li>to access an aggregate object’s contents without exposing its internal representation.</li><li>to support multiple traversals of aggregate objects.</li><li>to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).</li></ul><p>To “support multiple traversals” it must be possible to obtain multiple independent iterators from the same iterable instance, and each iterator must keep its own internal state, so a proper implementation of the pattern requires each call to iter(my_iterable) to create a new, independent, iterator. That is why we need the SentenceIterator class in this example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e27b9868025" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I managed different mysql files in docker]]></title>
            <link>https://medium.com/@sadhanajaiswal/how-i-managed-different-mysql-files-in-docker-75f06b7885a1?source=rss-8d39fcda5b05------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f06b7885a1</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sadhana Jaiswal]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 07:34:22 GMT</pubDate>
            <atom:updated>2019-09-10T07:34:22.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*kmUdKtYfkhWfUxLhepUL8w.png" /><figcaption>mysql with docker</figcaption></figure><p>Many developers use Docker to spin up a local database. It reduce the stress of installation and configuration of database. For that need to do customize database with docker. I am not going to explain how you can customize your Docker database(there is so many article for ).</p><p><a href="https://medium.com/better-programming/customize-your-mysql-database-in-docker-723ffd59d8fb">https://medium.com/better-programming/customize-your-mysql-database-in-docker-723ffd59d8fb</a></p><p>This article for people who already know how to customized the database with docker. In this, I am going to tell you how sequence the sql files in correct order, so it would not collapsed.</p><h3>Many SQL scripts</h3><p>Mysql docker container read sql dump files from folder tree(/sql folder). Now question is if we want to run sql dump files in a sequence means if there is 2 sql dump files(file1.sql and file2.sql) and want to run first file1.sql and after this, file2.sql get execute. How we can predict that docker run in this order.</p><h3>Docker’s default pattern/sequence to run .sql files</h3><p>Docker follow alphabetical order to run .sql files if there is more than one .sql files. But we can not add ‘a’ or ‘b’ to initial of .sql file. this is not good way of naming convention.</p><h3>Naming convention for .sql files in Docker</h3><p>In programming way, we can follow database naming convention as adding 0001 or 0002 at initial of file name. Docker sort files in alphabetical order of file’s name,so for sort the file in correct order, we have followed file’s name in following way.</p><ul><li>0001_file_name_initial.sql (if file contains sql query for create )</li><li>0002_file_name_alter.sql (if file contains sql query for alter the db or table)</li><li>0003_file_name_insert.sql (if file contains sql query for insert values in tables)</li></ul><p>see below pic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*nf_walZU8FtJvXQtk0ju0w.png" /></figure><p>Hope this is helpful for you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f06b7885a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>