<?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 Varun Gubbi on Medium]]></title>
        <description><![CDATA[Stories by Varun Gubbi on Medium]]></description>
        <link>https://medium.com/@varungubbi?source=rss-7f4d164c03d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yPeFZW-QFB3ZU2I8qkZB2g.jpeg</url>
            <title>Stories by Varun Gubbi on Medium</title>
            <link>https://medium.com/@varungubbi?source=rss-7f4d164c03d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:02:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varungubbi/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[A Trick to avoid web-scraping and make your life easy]]></title>
            <link>https://faun.pub/a-trick-to-avoid-web-scraping-and-make-your-life-easy-d01f52f078be?source=rss-7f4d164c03d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01f52f078be</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Varun Gubbi]]></dc:creator>
            <pubDate>Fri, 05 Feb 2021 11:02:39 GMT</pubDate>
            <atom:updated>2021-02-16T22:17:12.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to avoid Web Scraping?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOJL1gKkKr5y6Kv3LkMFkg.jpeg" /></figure><p>Have you ever been in a situation where you try writing a web scraping script to pull some data of a webpage but face a lot of problems as the websites HTML is not structured or the websites are written in some JS frameworks like React JS or Angular JS which make the HTML code really difficult to understand.</p><p>I have a neat trick which can pull you out of this situation almost always and the best part is we don’t have to scrape. In fact, it is better to first try &amp; implement this trick before trying out web-scraping.</p><p>Before starting with the trick we need a basic understanding of how a web-application/web-site can be implemented.</p><h3>Below are the two architectures that a website usually is created with:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*92NKE65mR1iRBF-bAYDygw.jpeg" /><figcaption>1 — Legacy Monolithic</figcaption></figure><p><strong>Monolithic style</strong>: In this style the user requests for a webpage to which the server responds with the entire webpage. This would include HTML and data intervened. Anyway, this is a old style of implementation and <strong>we would not be concentrating on this style in this blog.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*jQKuyAMmQgAarmdrz4YNPg.jpeg" /><figcaption>2 — Modern microservice style</figcaption></figure><p><strong>Micro-service style: </strong>In this style the user requests for a webpage to which the server responds with just the HTML and JS which instructs the browser to make additional calls to different URLs to get data which later can be intervened with HTML. <strong>We are going to use this separation between HTML and Data to our advantage.</strong></p><p><strong>If you haven’t noticed, we just need the data and not the HTML call. Hence, we just have to make the API call to get the data in JSON format.</strong></p><p>Let me explain this with an example.</p><p>Consider this webpage <a href="https://playhearthstone.com/en-us/cards?set=standard">https://playhearthstone.com/en-us/cards?set=standard</a>. We need to scrap the names of all the characters in each of the cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPHFL9IblpZzRnleGxG4BQ.png" /><figcaption>Snapshot of the cards from which we want to scrap the names</figcaption></figure><p>I would suggest you first give a swirl at your first instinct to solve this issue. You would probably pull out some web scrapper tool/program and start reading through the websites HTML to pull out all these names.</p><p>But, here is where the fun starts. Before writing the whole scraping script hold on and bare with me and see how easy things could have been.</p><p>Once the page is loaded, open the developer tools and select the network tab. With this tab open just reload the page, you will start to see the network calls that is done from the website. If you browse through these calls, you will be able to find the golden egg that is a network call whose response is a JSON will all the names of the cards that is shown in the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGAWEOZOb9VcvHAdRhQPGA.png" /><figcaption>Snapshot showing how to find the required call which has data</figcaption></figure><p>Now, it is just a matter of making this call alone, getting the JSON and pulling out the name from it. To know how what are all the request arguments, just click on the header tab above which show below details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ylk8Qg7AaUskHWIK27k0ow.png" /><figcaption>Snapshot showing the details of the request</figcaption></figure><p>We can pull three informations from this tab, <br>1. <em>Request URL<br>2. Request method<br>3. Authorization to be added into the request heade</em>r</p><p>With this information you should be able to make the http call pretty easily to pull out the required information. I have attached a python code snippet that is enough to perform this operation.</p><pre>import requests<br>url = &quot;https://api.blizzard.com/hearthstone/cards?class=all&amp;order=asc&amp;pageSize=200&amp;set=standard&amp;sort=manaCost&amp;locale=en_US&quot;<br>auth_code = &quot;KR0TZFpUeCM5q4QdrFqKfgdRUk5Wgayl4M&quot;<br>headers = { &quot;Authorization&quot;:  &quot;Bearer &quot;+auth_code}<br>res = requests.get(url=url, headers=headers)<br>names_list = [card[&#39;name&#39;] for card in  res.json()[&#39;cards&#39;]]<br>print(names_list)</pre><p>Yes, it is that simple!!</p><p>Always keep an eye out for networks tab. It might save tons of work hours trying to debug and understand the unnecessary HTML code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p>👋 <a href="https://faun.dev/join"><strong>Join FAUN today and receive similar stories each week in your inbox!</strong></a><strong> </strong>️ <strong>Get your weekly dose of the must-read tech stories, news, and tutorials.</strong></p><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and </strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷 <strong>and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook</strong></a><strong> and </strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin</strong></a><strong> Groups </strong>💬</p><figure><a href="https://www.faun.dev/join?utm_source=medium.com/faun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cT0_laE4iPcqW1qrbstAg.gif" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01f52f078be" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/a-trick-to-avoid-web-scraping-and-make-your-life-easy-d01f52f078be">A Trick to avoid web-scraping and make your life easy</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow — Trigger KubernetesPodOperator using HTTP call]]></title>
            <link>https://faun.pub/airflow-trigger-kubernetespodoperator-using-http-call-bd3f14d7ed4d?source=rss-7f4d164c03d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd3f14d7ed4d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <category><![CDATA[kubernetes-pods]]></category>
            <dc:creator><![CDATA[Varun Gubbi]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 09:10:42 GMT</pubDate>
            <atom:updated>2020-12-08T10:51:09.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>Airflow — Trigger KubernetesPodOperator using HTTP call</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*VZ4huot4kp_aUHUEWlVHhQ.png" /></figure><p>Airflow has an Operator called “Kubernetes Pod Operator” which would ideally connect to a cluster, create a pod run the desired program and delete the pod. This is a much-required feature where we will be able to run our post-load/Intermediate jobs or process in the Kubernetes cluster which can scale up and wide. This saves a lot in terms of cost as the pods will be up only when we are running the job. This also make our system flexible as we can run any number of jobs concurrently without having to worry about the computing power that we have as Kubernetes auto handles that for us.</p><p>Although the Kubernetes pod is perfect to use it has a caveat. It does not have an option to get the data from a DAG http trigger made to airflow. That’s when we will introduce a simple customization to the existing KubernetesPodOperator package to make use of the data coming in from the Http request.</p><p>Below is a sample DAG where it uses KubernetesPodOperator to make run a particular program inside the Kubernetes Cluster.</p><pre>import airflow<br>from airflow import DAG<br>from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: airflow.utils.dates.days_ago(0),<br>}<br><br>dag = DAG(&#39;sampleDAG&#39;, default_args=default_args, schedule_interval=None)<br><br><br>DriftTask = KubernetesPodOperator(<br>    namespace=&#39;default&#39;,<br>    image=&quot;python&quot;,<br>    cmds=[&quot;python&quot;, &quot;-c&quot;],<br>    arguments=[&quot;print(&#39;This code is running in a Kubernetes Pod&#39;)&quot;],<br>    labels={},<br>    name=&quot;sampleDAG&quot;,<br>    task_id=&quot;sampleDAG&quot;,<br>    get_logs=True,<br>    dag=dag,<br>    log_events_on_failure=True,<br>    is_delete_operator_pod=True)<br><br><br>DriftTask</pre><p>This Dag would use the python image from <a href="http://hub.docker.com/">hub.docker.com </a>to create a pod in the Kubernetes Cluster and run the below command in it.</p><pre>print(&#39;This code is running in a Kubernetes Pod&#39;)</pre><ul><li>What if you want to pass dynamic data that needs to be printed from this program?</li><li>What if the program that you try to trigger needs the dynamic input coming from an HTTP trigger?</li></ul><p>To answer these questions we will have to write a custom wrapper around the existing KubernetesPodOperator class. Below is its implementation.</p><pre>from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator<br><br><br>class CustomKubernetesPodOperator(KubernetesPodOperator):<br><br>    def execute(self, context):<br>        message = context[&#39;dag_run&#39;].conf.get(&#39;message&#39;)<br>        params = [f&quot;print(&#39;{message}&#39;)&quot;]<br>        self.arguments.extend(params)<br>        super().execute(context)</pre><p>The execute function in the KubernetesPodOperator package will be getting an input argument which will contain the context of the DAG trigger and the entire run. This context variable will also contain the data coming in from the HTTP trigger. We are accessing that data using</p><blockquote>context[‘dag_run’].conf.get(‘message’)</blockquote><p>And after accessing that I am just inserting the message into the print function to print it out.</p><p>An http request can be triggered using the below python code.</p><pre>import requests<br>import json<br><br>url = f&quot;http://&lt;address-of-airflow-instance&gt;:8080/api/experimental/dags/DriftDag/dag_runs&quot;<br>headers = {<br>    &quot;Cache-Control&quot;: &quot;no-cache&quot;,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>}<br>body = {<br>    &quot;conf&quot;: {<br>        &#39;message&#39;: &#39;I Got this message from the API request made to AIRFLOW&#39;<br>    }<br>}<br>requests.post(url=url, headers=headers, data=json.dumps(body))</pre><p>Hope, this helps in getting the dynamic data to your job which is running in the Kubernetes cluster. You can start off by using Kubernetes with your airflow scheduler. You can use the below link to follow along.</p><p><a href="https://kubernetes.io/blog/2018/06/28/airflow-on-kubernetes-part-1-a-different-kind-of-operator/#step-1-set-your-kubeconfig-to-point-to-a-kubernetes-cluster">Airflow on Kubernetes (Part 1): A Different Kind of Operator</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p>👋 <a href="https://faun.dev/join"><strong>Join FAUN today and receive similar stories each week in your inbox!</strong></a><strong> </strong>️ <strong>Get your weekly dose of the must-read tech stories, news, and tutorials.</strong></p><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and </strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷 <strong>and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook</strong></a><strong> and </strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin</strong></a><strong> Groups </strong>💬</p><figure><a href="https://www.faun.dev/join?utm_source=medium.com/faun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cT0_laE4iPcqW1qrbstAg.gif" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd3f14d7ed4d" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/airflow-trigger-kubernetespodoperator-using-http-call-bd3f14d7ed4d">Airflow — Trigger KubernetesPodOperator using HTTP call</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python decorator to parallelize any function]]></title>
            <link>https://medium.com/analytics-vidhya/python-decorator-to-parallelize-any-function-23e5036fb6a?source=rss-7f4d164c03d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e5036fb6a</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[multitasking]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Varun Gubbi]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 07:07:13 GMT</pubDate>
            <atom:updated>2020-12-26T07:31:47.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python decorator to parallelize any IO heavy function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okCGUrYHvcCte8IJCQgC6w.jpeg" /></figure><p>Wouldn’t it be cool if you can speed up your program by just adding a decorator to the function? Wouldn’t it be cool if you don’t have to worry about running the data in a list as a parallelly?</p><p>Today we are going to write a python decorator which exactly does these automatically for you, so that you can concentrate more on the logics of your code than worrying about multi-threading issues.</p><p>Some basics on python multi-threading before we start.</p><ol><li>The best place to implement it is where the function that we are trying to parallelize is <strong>IO heavy </strong>(the sleep time is pretty significant for the thread). Some examples are <strong>API calls, DB calls, Opening a file, Waiting for a stream of data, downloading a file from the internet</strong>.</li><li>It is a general practice to keep the <strong>number of threads spawned equal to the number of CPUs </strong>available in the system. (<strong>Important</strong>: It is just a standard, <strong>not a mandate</strong>. Will explain how we can go more than equal number of threads and extract more out of our system)</li></ol><p>Okay, we will start off with the code of the decorator. Have tried to make sure the code is self explanatory if you are not able to follow along or if you don’t know and don’t want to understand the logic to write a decorator, You can directly copy paste the decorator code. A sample project is available in this <a href="https://github.com/varungv/MultiThreadingSample">git repo</a>.</p><p>Below is the decorator code that we are going to use.</p><pre>import concurrent.futures<br>import os<br>from functools import wraps<br><br>def make_parallel(func):<br>    <em>&quot;&quot;&quot;<br>        Decorator used to decorate any function which needs to be parallized.<br>        After the input of the function should be a list in which each element is a instance of input fot the normal function.<br>        You can also pass in keyword arguements seperatley.<br>        </em><strong><em>:param</em></strong><em> func: function<br>            The instance of the function that needs to be parallelized.<br>        </em><strong><em>:return</em></strong><em>: function<br>    &quot;&quot;&quot;<br><br>    </em>@wraps(func)<br>    def wrapper(lst):<br>        <em>&quot;&quot;&quot;<br><br>        </em><strong><em>:param</em></strong><em> lst:<br>            The inputs of the function in a list.<br>        </em><strong><em>:return</em></strong><em>:<br>        &quot;&quot;&quot;<br>        </em># the number of threads that can be max-spawned.<br>        # If the number of threads are too high, then the overhead of creating the threads will be significant.<br>        # Here we are choosing the number of CPUs available in the system and then multiplying it with a constant.<br>        # In my system, i have a total of 8 CPUs so i will be generating a maximum of 16 threads in my system.<br>        number_of_threads_multiple = 2 # You can change this multiple according to you requirement<br>        number_of_workers = int(os.cpu_count() * number_of_threads_multiple)<br>        if len(lst) &lt; number_of_workers:<br>            # If the length of the list is low, we would only require those many number of threads.<br>            # Here we are avoiding creating unnecessary threads<br>            number_of_workers = len(lst)<br><br>        if number_of_workers:<br>            if number_of_workers == 1:<br>                # If the length of the list that needs to be parallelized is 1, there is no point in<br>                # parallelizing the function.<br>                # So we run it serially.<br>                result = [func(lst[0])]<br>            else:<br>                # Core Code, where we are creating max number of threads and running the decorated function in parallel.<br>                result = []<br>                with concurrent.futures.ThreadPoolExecutor(max_workers=number_of_workers) as executer:<br>                    bag = {executer.submit(func, i): i for i in lst}<br>                    for future in concurrent.futures.as_completed(bag):<br>                        result.append(future.result())<br>        else:<br>            result = []<br>        return result<br>    return wrapper</pre><p>We built a sample dummy function which would make HTTPS calls to JSON Placeholder API. Below is that sample code, please note that this is just to demonstrate how a IO heavy call would look like, you can replace this function with whatever function that you want to parallelize.</p><pre>import requests<br>def sample_function(post_id):<br>    <em>&quot;&quot;&quot;<br>        Just a sample function which would make dummy API calls<br>    &quot;&quot;&quot;<br><br>    </em>url = f&quot;https://jsonplaceholder.typicode.com/comments?postId={post_id}&quot;<br>    response = requests.get(url)<br>    if response.status_code == 200:<br>        return response.json()<br>    return {}</pre><p>When we try to make serial calls to this function our code would look something like this:</p><pre>list_of_post_ids = list(range(1, 20))<br><br># Serial way of calling the function<br>results = []<br>for post_id in list_of_post_ids:<br>    res = sample_function(post_id)<br>    results.append(res)</pre><p>But, when we use our decorator the code simplifies to being this:</p><pre># Paralleized way of calling the function<br>results = make_parallel(sample_function)(list_of_post_ids)</pre><p>You can observe the time difference between these two methods of calling the function to see for yourself how multithreading helps us quicken up IO heavy calls.</p><p>If you don’t like the code split up like in this article you can always got to my <a href="https://github.com/varungv/MultiThreadingSample">git Repository</a> in where I have hosted an entire demo project.</p><p>Also, note that this decorator only works for functions which have 1 input argument. Will be improving this decorator and also be adding auto selecting the number of threads based on function runtime in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e5036fb6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/python-decorator-to-parallelize-any-function-23e5036fb6a">Python decorator to parallelize any function</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>