<?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 Dhaval Savalia on Medium]]></title>
        <description><![CDATA[Stories by Dhaval Savalia on Medium]]></description>
        <link>https://medium.com/@dhavalsavalia?source=rss-c90e793fccd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*p2efK_kaiyWUbEEz.</url>
            <title>Stories by Dhaval Savalia on Medium</title>
            <link>https://medium.com/@dhavalsavalia?source=rss-c90e793fccd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:14:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhavalsavalia/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[FastAPI Logging Middleware: Logging Requests and Responses with Ease and Style]]></title>
            <link>https://medium.com/@dhavalsavalia/fastapi-logging-middleware-logging-requests-and-responses-with-ease-and-style-201b9aa4001a?source=rss-c90e793fccd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/201b9aa4001a</guid>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Dhaval Savalia]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 18:23:41 GMT</pubDate>
            <atom:updated>2023-02-11T18:25:23.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XX9xdLzAeH-obRBi5dkPCw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@aleskrivec?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ales Krivec</a> on <a href="https://unsplash.com/photos/KnV-mJDGWzU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. One of the key features of FastAPI is its ability to use middleware to add functionality to the application. In this tutorial, we will be creating a middleware function that logs all incoming requests and outgoing responses for our API. This can be useful for debugging, monitoring, and tracking the usage of our API.</p><h3>What is the Router Logging Middleware?</h3><p>The router logging middleware is a custom middleware for FastAPI. It logs all requests and responses including status codes, content, methods, paths, etc. This helps to debug issues quickly and also keep track of API usage. It is a useful tool for API developers. It can be used to log the request and response in JSON format. This makes it easy to parse the logs and extract the necessary information.</p><h3>Prerequisites</h3><p>To follow this tutorial, you should have:</p><ul><li>Basic knowledge of Python</li><li>Basic knowledge of the FastAPI framework and/or the Starlette framework</li></ul><p>To get started, you will need to have Python 3.6+ and following libraries installed. You can install those by running the following command in your terminal:</p><pre>pip install fastapi sqlmodel uvicorn python-json-logger</pre><p>Once you have libraries installed, you can create a new file in your project called main.py. This file will contain the code for FastAPI app and logging configuration.</p><p>In this file, we will start by importing the necessary modules:</p><pre>import logging.config<br>import logging<br>import sys<br>from fastapi import FastAPI<br>from sqlmodel import Field, SQLModel</pre><p>Now, we will write logging configuration as a dictionary, and initiate as dictConfig .</p><pre># Logging configuration<br>logging_config = {<br>    &quot;version&quot;: 1,<br>    &quot;formatters&quot;: {<br>        &quot;json&quot;: {<br>            &quot;class&quot;: &quot;pythonjsonlogger.jsonlogger.JsonFormatter&quot;,<br>            &quot;format&quot;: &quot;%(asctime)s %(process)s %(levelname)s %(name)s %(module)s %(funcName)s %(lineno)s&quot;<br>        }<br>    },<br>    &quot;handlers&quot;: {<br>        &quot;console&quot;: {<br>            &quot;level&quot;: &quot;DEBUG&quot;,<br>            &quot;class&quot;: &quot;logging.StreamHandler&quot;,<br>            &quot;formatter&quot;: &quot;json&quot;,<br>            &quot;stream&quot;: sys.stderr,<br>        }<br>    },<br>    &quot;root&quot;: {<br>        &quot;level&quot;: &quot;DEBUG&quot;,<br>        &quot;handlers&quot;: [<br>            &quot;console&quot;<br>        ],<br>        &quot;propagate&quot;: True<br>    }<br>}<br><br>logging.config.dictConfig(logging_config)</pre><p>This config will utilize python-json-logger library to format output log in JSON. Next, we will define and initialize FastAPI application. In addition to that, we will also define a simple SQLModel model for a user. Finally, we will add a root route to the application, which returns a user object.</p><pre># Define application<br>def get_application() -&gt; FastAPI:<br>    application = FastAPI(title=&quot;FastAPI Logging&quot;, debug=True)<br><br>    return application<br><br># Initialize application<br>app = get_application()<br><br># Define SQLModel for testing<br>class User(SQLModel):<br>    first_name: str<br>    last_name: str<br>    email: str<br><br># Root route that returns a User model<br>@app.get(<br>    &quot;/&quot;,<br>    response_model=User,<br>)<br>def root():<br>    user = User(<br>        first_name=&quot;John&quot;,<br>        last_name=&quot;Doe&quot;,<br>        email=&quot;jon@doe.com&quot;<br>    )<br>    return user</pre><p>The get_application function will hold all middlewares and custom routers that will come along.</p><p>To test the route, run the following command and visit [&lt;http://127.0.0.1:8000/&gt;](&lt;http://127.0.0.1:8000/&gt;) from your browser. Here, --reloadflag will hot reload any changes made to the application.</p><pre>uvicorn main:app --reload</pre><figure><img alt="https://cdn-images-1.medium.com/max/800/1*rBxaTGF2NYIvFNyRITe-VA@2x.png" src="https://cdn-images-1.medium.com/proxy/1*rBxaTGF2NYIvFNyRITe-VA@2x.png" /></figure><p>Result from the / route</p><p>If that is working, let us start writing a middleware. A middleware in FastAPI is a function or class that sits between the incoming request and the outgoing response. It can be used to modify or process the request or response, or to add additional functionality, such as logging or authentication. Middleware in FastAPI are executed in the order in which they are added, so it’s important to keep this in mind when designing your application.</p><p>In simple words, middleware is a tool that allows you to run some code before or after handling a request. Let’s start by creating logging_lib.py and importing modules.</p><pre>import logging<br>import time<br>import json<br>from typing import Callable<br>from uuid import uuid4<br>from fastapi import FastAPI, Request, Response<br>from starlette.middleware.base import BaseHTTPMiddleware<br>from starlette.types import Message</pre><p>Next up, we will be creating a custom middleware for FastAPI called RouterLoggingMiddleware that inherits from BaseHTTPMiddleware from the starlette.middleware.base module. The BaseHTTPMiddleware class provides a basic structure for creating middleware in FastAPI. It has a dispatch method which is a key part of our middleware. It is responsible for handling the flow of incoming requests and outgoing responses. The dispatch method takes in two arguments: request and call_next. request is an instance of the starlette.requests.Request class, and contains information about the incoming request such as the headers, query parameters, and the body. call_next is a callable that, when invoked, will pass the request on to the next middleware in the stack or to the final endpoint handler.</p><p>In RouterLoggingMiddleware, we will be passing in the FastAPI app and a logger object as parameters to the class constructor. This will allow us to access the app and log information about requests and responses as they pass through the application.</p><pre>class RouterLoggingMiddleware(BaseHTTPMiddleware):<br>    def __init__(<br>            self,<br>            app: FastAPI,<br>            *,<br>            logger: logging.Logger<br>    ) -&gt; None:<br>        self._logger = logger<br>        super().__init__(app)<br>   <br>    async def dispatch(self,<br>                       request: Request,<br>                       call_next: Callable<br>                       ) -&gt; Response:<br>    <br>        request_id: str = str(uuid4())<br>        logging_dict = {<br>            &quot;X-API-REQUEST-ID&quot;: request_id  # X-API-REQUEST-ID maps each request-response to a unique ID<br>        }<br><br>        await self.set_body(request)<br>        response, response_dict = await self._log_response(call_next,<br>                                                           request,<br>                                                           request_id<br>                                                           )<br>        request_dict = await self._log_request(request)<br>        logging_dict[&quot;request&quot;] = request_dict<br>        logging_dict[&quot;response&quot;] = response_dict<br><br>        self._logger.info(logging_dict)<br><br>        return response<br><br>    async def set_body(self, request: Request):<br>        &quot;&quot;&quot;Avails the response body to be logged within a middleware as,<br>            it is generally not a standard practice.<br><br>               Arguments:<br>               - request: Request<br>               Returns:<br>               - receive_: Receive<br>        &quot;&quot;&quot;<br>        receive_ = await request._receive()<br><br>        async def receive() -&gt; Message:<br>            return receive_<br><br>        request._receive = receive</pre><p>In above code, the first thing that happens in the dispatch method is that a unique request ID is generated using the uuid4() function. This request ID is used to map each request-response to a unique ID, it is added to the headers of the request using the key &quot;X-API-REQUEST-ID&quot;.</p><p>The set_body function is used to make the response body available to be logged within the middleware. Normally, it is not a standard practice to log the response body, but this function allows us to do so. This is particularly useful for debugging and tracking API usage.</p><p>The self._log_response function is called with the call_next function, the request object and the request ID as arguments. This function returns the response object and the response data in the form of a dictionary.</p><p>Similarly, the self._log_request function is called with the request object as an argument. This function returns the request data in the form of a dictionary as well.</p><p>The request and response data dictionaries, along with the request ID are then added to a logging_dict object which is logged using the self._logger.info() function.</p><p>Finally, the response object is returned from the dispatch method.</p><pre>async def _log_request(<br>            self,<br>            request: Request<br>    ) -&gt; str:<br>        &quot;&quot;&quot;Logs request part<br>            Arguments:<br>           - request: Request<br><br>        &quot;&quot;&quot;<br><br>        path = request.url.path<br>        if request.query_params:<br>            path += f&quot;?{request.query_params}&quot;<br><br>        request_logging = {<br>            &quot;method&quot;: request.method,<br>            &quot;path&quot;: path,<br>            &quot;ip&quot;: request.client.host<br>        }<br><br>        try:<br>            body = await request.json()<br>            request_logging[&quot;body&quot;] = body<br>        except:<br>            body = None<br><br>        return request_logging</pre><p>The _log_request method logs the request part of the request-response cycle. It accepts a Request object as an argument and returns the request data in the form of a dictionary. The dictionary contains information about the request such as the method, path, IP address and request body (if it exists). This data can be used to log or track the requests that are made to the API.</p><pre>async def _log_response(self,<br>                            call_next: Callable,<br>                            request: Request,<br>                            request_id: str<br>                            ) -&gt; Response:<br>        &quot;&quot;&quot;Logs response part<br><br>               Arguments:<br>               - call_next: Callable (To execute the actual path function and get response back)<br>               - request: Request<br>               - request_id: str (uuid)<br>               Returns:<br>               - response: Response<br>               - response_logging: str<br>        &quot;&quot;&quot;<br><br>        start_time = time.perf_counter()<br>        response = await self._execute_request(call_next, request, request_id)<br>        finish_time = time.perf_counter()<br><br>        overall_status = &quot;successful&quot; if response.status_code &lt; 400 else &quot;failed&quot;<br>        execution_time = finish_time - start_time<br><br>        response_logging = {<br>            &quot;status&quot;: overall_status,<br>            &quot;status_code&quot;: response.status_code,<br>            &quot;time_taken&quot;: f&quot;{execution_time:0.4f}s&quot;<br>        }<br><br>        resp_body = [section async for section in response.__dict__[&quot;body_iterator&quot;]]<br>        response.__setattr__(&quot;body_iterator&quot;, AsyncIteratorWrapper(resp_body))<br><br>        try:<br>            resp_body = json.loads(resp_body[0].decode())<br>        except:<br>            resp_body = str(resp_body)<br><br>        response_logging[&quot;body&quot;] = resp_body<br><br>        return response, response_logging<br><br>    async def _execute_request(self,<br>                               call_next: Callable,<br>                               request: Request,<br>                               request_id: str<br>                               ) -&gt; Response:<br>        &quot;&quot;&quot;Executes the actual path function using call_next.<br>               It also injects &quot;X-API-Request-ID&quot; header to the response.<br><br>               Arguments:<br>               - call_next: Callable (To execute the actual path function<br>                            and get response back)<br>               - request: Request<br>               - request_id: str (uuid)<br>               Returns:<br>               - response: Response<br>        &quot;&quot;&quot;<br>        try:<br>            response: Response = await call_next(request)<br><br>            # Kickback X-Request-ID<br>            response.headers[&quot;X-API-Request-ID&quot;] = request_id<br>            return response<br><br>        except Exception as e:<br>            self._logger.exception(<br>                {<br>                    &quot;path&quot;: request.url.path,<br>                    &quot;method&quot;: request.method,<br>                    &quot;reason&quot;: e<br>                }<br>            )</pre><p>The _log_response function is used to log the response part of the request-response cycle. It accepts the call_nextfunction, Request object and request ID as arguments. This function is responsible for taking the response object and the response data and creating a dictionary which includes the overall status, status code, the time taken to execute the request and the body of the response.</p><p>The call_next function is an important part of the process, as it executes the path function and allows us to obtain the response. It is also passed to the _execute_request function which executes the path function and injects the &quot;X-API-Request-ID&quot; header to the response before sending it back. If any exceptions occur throughout the process, the self._logger.exception() function is used to log them. The logging dictionary contains information about the path, method and the reason for the exception.</p><p>In order to obtain the body_iterator attribute, the AsyncIteratorWrapper class is used. This class accepts an async iterable as an argument and returns an instance of an async iterator. This allows us to access the response body and log it accordingly. Moreover, as it is an asynchronous process, it ensures that the logging is carried out with minimal disruption to the overall request-response cycle.</p><pre>class AsyncIteratorWrapper:<br>    &quot;&quot;&quot;The following is a utility class that transforms a<br>        regular iterable to an asynchronous one.<br><br>        link: https://www.python.org/dev/peps/pep-0492/#example-2<br>    &quot;&quot;&quot;<br><br>    def __init__(self, obj):<br>        self._it = iter(obj)<br><br>    def __aiter__(self):<br>        return self<br><br>    async def __anext__(self):<br>        try:<br>            value = next(self._it)<br>        except StopIteration:<br>            raise StopAsyncIteration<br>        return value</pre><p>In order to use the RouterLoggingMiddleware, it needs to be imported first. This can be done as follows:</p><pre>from logging_lib import RouterLoggingMiddleware</pre><p>Once the middleware is imported, it can be added to the get_application method as a middleware and the logger can be passed to it as an argument. This can be done as follows:</p><pre>application.add_middleware(<br>    RouterLoggingMiddleware,<br>    logger=logging.getLogger(__name__)<br>)</pre><p>Finally, use uvicorn to run the application as before. This is a simple and straightforward way to get up and running with your application. To make sure everything is working correctly, visit <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a> in your web browser. You should then be able to view the log, which will give you further information about the progress of your application. If everything is set up correctly, you should see a following log message.</p><pre>{<br>    &quot;asctime&quot;: &quot;2023-02-11 13:10:17,143&quot;,<br>    &quot;process&quot;: 34614,<br>    &quot;levelname&quot;: &quot;INFO&quot;,<br>    &quot;name&quot;: &quot;main&quot;,<br>    &quot;module&quot;: &quot;logging_lib&quot;,<br>    &quot;funcName&quot;: &quot;dispatch&quot;,<br>    &quot;lineno&quot;: 38,<br>    &quot;X-API-REQUEST-ID&quot;: &quot;9f364930-cecc-416a-968e-956761211fd1&quot;,<br>    &quot;request&quot;: {<br>        &quot;method&quot;: &quot;GET&quot;,<br>        &quot;path&quot;: &quot;/&quot;,<br>        &quot;ip&quot;: &quot;127.0.0.1&quot;<br>    },<br>    &quot;response&quot;: {<br>        &quot;status&quot;: &quot;successful&quot;,<br>        &quot;status_code&quot;: 200,<br>        &quot;time_taken&quot;: &quot;0.0015s&quot;,<br>        &quot;body&quot;: {<br>            &quot;first_name&quot;: &quot;John&quot;,<br>            &quot;last_name&quot;: &quot;Doe&quot;,<br>            &quot;email&quot;: &quot;jon@doe.com&quot;<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=201b9aa4001a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Colorize Google Calendar Event Using Apps Script (2/2)]]></title>
            <link>https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-2-2-59593b8b8567?source=rss-c90e793fccd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/59593b8b8567</guid>
            <category><![CDATA[ifttt]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <category><![CDATA[google-calendar]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Dhaval Savalia]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 10:22:14 GMT</pubDate>
            <atom:updated>2020-04-21T10:43:24.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*ldRCe84tv8RkNaLNsRjPiQ.png" /><figcaption>Google Calendar + Google Apps Script | Made using Canva</figcaption></figure><p>Automatically colorize your calendar events using the power of Google Calendar and Google Apps Script platform.</p><p>In the previous part, we have learned how to use Google Apps Script to colorize our Google Calendar events. However, it was very basic and you would have to go through that rigorous process of launching your Apps Script project then running the project and what not. In this part, we will automate the same by deploying our project as a web module and setting up an IFTTT applet which will get triggered every time a new event is added.</p><h3>Outline</h3><p>Google Apps Script requires doGet() and doPost() methods to handle GET and POST requests respectively. The structure might be the same but we will be using doPost() method.</p><p>Every new event added in the calendar will cause IFTTT to invoke the doPost() method and subsequently assign_color() method that we previously wrote. (<a href="https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-1-2-d88dd27658f0">ref</a>)</p><p>Let’s start coding, shall we?</p><h4>doPost() Method</h4><p>We will append to the script that we wrote in the previous part. (<a href="https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-1-2-d88dd27658f0">link</a>)</p><pre><strong>function</strong> doPost() {<br>  assign_color();<br>}</pre><p>Wait, what? Is that it? Well, yes that is pretty much what goes into out doPost() method! Although, we might want to make a slight optimizations to our script. As of now, anytime the script is getting executing, it is iterating through every date from 01/01/1970 to 01/01/2500. As you add more event, this process might take enormous amount of computing down the road. So, we will limit the amount of events that are being iterated in the process. It is better to process every event from 7-days ago to practically every events in the future. I hope you get the idea.</p><pre><strong>var</strong> beginDate = new Date(new Date().getTime() - (7 * 86400000));<br><strong>var</strong> endDate = new Date(2500, 0, 1);</pre><blockquote><strong>NOTE</strong>: Integer ‘7’ in the beginDate represents days.</blockquote><h4>Deploying As Web App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Ya5QYYEPB1qnvNJgnp4Ynw.png" /><figcaption>Publish Menu</figcaption></figure><p>Click on ‘Deploy as web app…’. It will prompt a dialog box. Select “New” for the project version. For <em>Execute the app as </em>select <em>Me (your email address) </em>and finally for <em>Who has access to the app</em> select <em>Anyone, even anonymous</em>. Here is what each of those settings do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*9AKH01D7o2fDiKpwBhFH5w.png" /><figcaption>Deployment Dialog Box</figcaption></figure><ul><li><em>Execute the app as</em>: When you request to the URL given at the time of deploying, it will execute as the user who deployed it. In this case, it is <em>you</em>.</li><li><em>Who has access to the app: </em>This setting indicates who has access to this URL. In this it is practically anyone with the link. The reason we might want to enable this setting is that by using IFTTT services, you will not get authorization prompt.</li></ul><h3>IFTTT</h3><p>According to Wikipedia, <em>If This Then That</em>, also known as IFTTT, is a free web-based service to create chains of simple conditional statements, called applets. It is truly an amazing service for any kind of automation.</p><p>Sign up with IFTTT and we will start creating our first applet! Go to <a href="https://ifttt.com/create">https://ifttt.com/create</a></p><h4>Step 1</h4><p>You will arrive at following screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLacW7bvATdGGs-O9OahIQ.png" /><figcaption>IFTTT Applet Create Portal</figcaption></figure><h4>Step 2</h4><p>Select ‘Google Calendar’ for <em>This </em>part of the trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pU8C05iqHio1uPaZF-nHGA.png" /><figcaption>Google Calendar Service on IFTTT Platform</figcaption></figure><h4>Step 3</h4><p>Choose ‘New event added’ trigger from the available list of Google Calendar triggers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-pD1jWaWk4oTmJJfjHGBg.png" /><figcaption>Triggers Available for Google Calendar Service</figcaption></figure><h4>Step 4</h4><p>Select your calendar from the list. You might want to authorize your IFTTT account with Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXdkFDtDiaPU3IIYXFGIdQ.png" /><figcaption>Selecting Calendar</figcaption></figure><h4>Step 5</h4><p>Now, we will go to <em>That</em> part of the applet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PITfeZPMYQ6qjVOwdyFALA.png" /><figcaption>“This” Part is Complete</figcaption></figure><h4>Step 6</h4><p>Choose “Webhooks” for <em>That</em> part of the applet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wui6IQ7iEhxJhPMLdjNlLw.png" /><figcaption>Webhooks of IFTTT Platform</figcaption></figure><h4>Step 7</h4><p>Choose “Make a web request” action. That might be the only action available under “Webhooks” service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7mqRlHaAx9HSgCKK0e8lQ.png" /><figcaption>Selecting “Make a web request” Action</figcaption></figure><h4>Step 8</h4><p>Enter URL that you obtained while deploying the project and select ‘POST’ as HTTP Method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*vZsmEmnu3mW6RenvCon7Qw.png" /><figcaption>Configuring ‘Webhooks’</figcaption></figure><h4>Step 9</h4><p>Save and name the applet. Make sure it is enabled and you are good to go!</p><h3>Testing</h3><p>Create an event in the appropriate calendar using the naming convention that we discussed before. Wait for a couple of seconds and it will colorize the event automatically! There is so much more optimization that we can do on Apps Script. Let me know in the comments if you want to see those as well.</p><h3>Conclusion</h3><p>I hope this article was helpful! Thank you for taking time into reading.</p><p>Please share it if you found this article to be helpful. :)</p><p>Link to part one: <a href="https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-1-2-d88dd27658f0">https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-1-2-d88dd27658f0</a></p><h3>Resources and Further Reading</h3><ul><li><a href="https://developers.google.com/apps-script/guides/web">Web Apps | Apps Script | Google Developers</a></li><li><a href="http://googleappscripting.com/doget-dopost-tutorial-examples/">doGet and doPost Tutorial + 6 Web App Examples * Google Apps Script Tutorials and Examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59593b8b8567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Colorize Google Calendar Event Using Apps Script (1/2)]]></title>
            <link>https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-1-2-d88dd27658f0?source=rss-c90e793fccd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d88dd27658f0</guid>
            <category><![CDATA[google-calendar]]></category>
            <category><![CDATA[google-apps-script]]></category>
            <category><![CDATA[colorize-events]]></category>
            <dc:creator><![CDATA[Dhaval Savalia]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 18:23:12 GMT</pubDate>
            <atom:updated>2020-04-21T10:41:19.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*ldRCe84tv8RkNaLNsRjPiQ.png" /><figcaption>Google Calendar + Google Apps Script | Made using Canva</figcaption></figure><p>Automatically colorize your calendar events using the power of Google Calendar and Google Apps Script platform.</p><p>We have so many things going in our life. In this fast paced era, one must keep track of their daily activities and agenda. I use Google Calendar to organize my academic and personal life and I bet you are using it as well. Google Calendar provides a facility to create multiple calendars in order to keep different kind of events tidy. It also let’s us colorize them, but in the addition to that, you can also colorize different events in a single calendar!</p><p>This can be a real life changer when used to it’s full potential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*pKxwBawbV5YKO5sE4oqcwg.png" /><figcaption>Colorized Events From My Academic Calendar</figcaption></figure><p>As you can see in the image, even without reading the title I can get a quick look on what kind of event is up next in my schedule. For example, Lectures gets “Green”, Test gets “Orange”, etc. Sounds interesting, right?</p><p>Let’s get right into it, shall we?</p><h3>Prerequisites</h3><p>Before we start coding, grab your Calendar ID from that calendar’s <a href="https://calendar.google.com/calendar/r/settings">settings page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*uvvHpRRxfmu5rW935v5AjA.png" /></figure><p>You need to follow certain convention on how to name your events. In our case, we are naming our events as follow,</p><ul><li>Assignment: “Event Name”</li><li>Test: “Event Name”</li></ul><p>Excluding double quotes.</p><p>Now that we have our Calendar ID, let’s open Apps Script console. Follow this link: <a href="https://script.google.com/home">https://script.google.com/home</a></p><p>We will create a new project. This is what it will look like on the first start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPGlURzeVj2S5VVJ5otvew.png" /><figcaption>New Project in Apps Script</figcaption></figure><h4>A bit about Apps Script</h4><p>Google Apps Script is a JavaScript platform in the cloud. With access to several Google products like Sheets, Drive, Calendar to name a few. If you happen to know a little bit of JavaScript, this will come natural to you.</p><p><strong>NOTE: </strong>All the reference are quoted where needed. Look for (ref) tag. I have also attached references and further guide in the footer of this article.</p><h3>Coding</h3><p>Remove the boilerplate code and let’s start writing our own.</p><pre>var calendar = CalendarApp.getCalendarById(&#39;putYourCalendarIdHere:String&#39;);</pre><pre>var beginDate = new Date(1970, 0, 1); <br>var endDate = new Date(2500, 0, 1);</pre><p>Let’s understand the code line by line.</p><p>Line 1 create a variable called calendar and it fetches Calendar using the Calendar ID you just passed. (<a href="https://developers.google.com/apps-script/reference/calendar/calendar-app#getCalendarById(String)">ref</a>)</p><p>Line 2 and 3 denotes start date and end date respectively. We will query all the events falling into this time frame.</p><pre>function assign_color() {</pre><pre>  var events = calendar.getEvents(beginDate, endDate);</pre><pre>  for (var i=0; i&lt;events.length; i++) {</pre><pre>    var event = events[i];<br>    var title = event.getTitle();</pre><pre>    if (/Submission:/.test(title)) {<br>      event.setColor(&#39;3&#39;);<br>    } else if (/Test:/.test(title)) {<br>      event.setColor(&#39;5&#39;);<br>    } else if (/Subscription:/.test(title)) {<br>      event.setColor(&#39;9&#39;);<br>    } else {}</pre><pre>  }</pre><pre>}</pre><p>Function assign_color() is where all the magic happens! Query the all events falling between beginDate and endDate using getEvents() method. This will return an array of CalendarEvent (<a href="https://developers.google.com/apps-script/reference/calendar/calendar#getEvents(Date,Date)">ref</a>)</p><p>Now, let’s loop over events . We will grab title of the event using getTitle() method. It will return a string type. Check if the title we got contains any of our “Event Type” using Regular Expression.</p><p>/Submission:/.test(title) will return true if the variable title has Submission: inside it. Here /Submission:/ is a <em>RegExpObject. </em>If regular expression matches any of the given, it will go ahead and colorize the event using setColor() method. This method will take String-ed integer as parameter. Here is the list of available colors: <a href="https://developers.google.com/apps-script/reference/calendar/event-color">https://developers.google.com/apps-script/reference/calendar/event-color</a></p><h4>Testing</h4><p>Create some random events in your calendar and remember to follow the naming convention!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*5BX8wuDY0slRDP0v2Zi83g.png" /><figcaption>Three Events in the Calendar With Default Color</figcaption></figure><p>As you can see, we have three events in our calendar with their default color. Now, let’s run our assign_color method!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*30Y_CxvJAhbZ5vKTVPMDOg.png" /><figcaption>Running the assign_color Method</figcaption></figure><p><strong>NOTE</strong>: You might be asked to allow access to use your Google Calendar when your first run your code.</p><p>As soon as you run your code, head over to calendar to see the magic!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*FoQbPHdH6LST6pDzeQ86MA.png" /><figcaption>Colorized Calendar Events Using Apps Script</figcaption></figure><h3>Conclusion</h3><p>Impressed? Show your creativity using the Google Apps Script. It is real fun to write code in Apps Script. The possibilities are endless.</p><p>In the next part of this article, we will see how we can automate this script using IFTTT! (Edit: I have switched from Python to IFTTT platform.)</p><p>I hope this article was helpful! Thank you for taking time into reading.</p><p>Link to part two: <a href="https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-2-2-59593b8b8567">https://medium.com/@dhavalsavalia/how-to-colorize-google-calendar-event-using-apps-script-2-2-59593b8b8567</a></p><h3>References and Further Reading</h3><ul><li><a href="https://developers.google.com/apps-script/reference/calendar">Calendar Service | Apps Script | Google Developers</a></li><li><a href="https://developers.google.com/apps-script/overview">Google Apps Script overview | Google for Developers</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular expressions - JavaScript | MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d88dd27658f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate PayTM With Django]]></title>
            <link>https://medium.com/@dhavalsavalia/how-to-integrate-paytm-with-django-d8df17932026?source=rss-c90e793fccd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8df17932026</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[paytm]]></category>
            <dc:creator><![CDATA[Dhaval Savalia]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 00:09:46 GMT</pubDate>
            <atom:updated>2020-04-14T00:09:46.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*qnPhDJR2IoNiwjAaN6-iWQ.png" /><figcaption>Django + PayTM | Made using Canva</figcaption></figure><p>Whether you are making an e-commerce website or an online niche tutorials website. At some point you will need to integrate a payment gateway to start getting paid for your hard work. It you happen to be developing your website using Django web-framework then PayTM might be the perfect choice as your payment processor.</p><h3>Why PayTM?</h3><p>To start with, PayTM is as secure as it can get with it’s <strong>PCI DSS compliant </strong>infrastructure. Moreover, it is just breeze to integrate to your existing project. It shall take no more than an hour to complete the process.</p><p><strong>NOTE</strong>: Obtain your PayTM developer credentials beforehand. You can get them from here, <a href="https://dashboard.paytm.com/next/">https://dashboard.paytm.com/next/</a></p><h3>Integration</h3><p>We will start by installing dependencies for the project. Those include Django(duh?), <a href="https://pycryptodome.readthedocs.io/en/latest/">PyCryptodome</a>(To calculate hash value for PayTM transaction). Keep in mind that we will use <a href="https://pipenv.pypa.io/en/latest/">Pipenv</a> for our virtual environment.</p><pre>$ pipenv install<br>$ pipenv shell<br>(env) $ pipenv install django <a href="https://pycryptodome.readthedocs.io/en/latest/">pycryptodome</a></pre><p>Perfect! Now we have installed our dependencies. It is time to start new Django project.</p><pre>(env) $ django-admin startproject paytm_django<br>(env) $ cd paytm_django<br>(env) $ python manage.py startapp payments</pre><p>This will create new Django app named payments . Now that is taken care of, add this application in the list of INSTALLED_APPS in settings.py file.</p><p>We will also add our credentials we got from PayTM in settings.py file. Ideally this should be stored as environment variables but for the time being we will store them in the file only.</p><h4>File — settings.py</h4><pre>... # Django related code</pre><pre>PAYTM_COMPANY_NAME = &quot;Company Name&quot;   # For representation purposes <br>PAYTM_INDUSTRY_TYPE_ID = &quot;Retail&quot;     # For staging environment<br>PAYTM_CHANNEL_ID = &quot;WEB&quot;<br>PAYTM_MERCHANT_KEY = &quot;your_merchant_key&quot;<br>PAYTM_MERCHANT_ID = &quot;your_merchant_id&quot;<br>PAYTM_CALLBACK_URL = &quot;<a href="http://localhost:8000/response/">http://localhost:8000/response/</a>&quot; # Hardcode<br>PAYTM_WEBSITE = &quot;WEBSTAGING&quot;<br>PAYTM_PAYMENT_GATEWAY_URL = &quot;<a href="https://securegw-stage.paytm.in/order/process">https://securegw-stage.paytm.in/order/process</a>&quot;<br>PAYTM_TRANSACTION_STATUS_URL = &quot;<a href="https://securegw-stage.paytm.in/order/status">https://securegw-stage.paytm.in/order/status</a>&quot;</pre><p>Good! Let’s head over to our application directory and create utils.py which will hold our payment verification function.</p><pre>(env) $ cd ..<br>(env) $ cd payments<br>(env) $ touch utils.py</pre><p><strong>NOTE:</strong> Download Checksum.py file from <a href="https://gist.github.com/dhavalsavalia/f721b926e17292f1b7a293904f613fa6">this GitHub Gist</a> and place in the same directory as payments application.</p><h3>Code</h3><p>It is time to start writing actual code for the project.</p><h4>Files — views.py | utils.py | payment.html</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb347d90125837a27cd2db010a648cc4/href">https://medium.com/media/cb347d90125837a27cd2db010a648cc4/href</a></iframe><p>So, there are three views in total,</p><ol><li>home() — Takes care of home page and displays a link to checkout</li><li>payment() — Serializes data and prepares request to send to PayTM</li><li>response() — Checks and validates the transaction</li></ol><h4>payment() in detail</h4><p>We have constructed a data_dict which holds data about the order like order id, amount, customer id, etc. Although, we have hard-coded these fields but ideally it should come from a database.</p><pre>data_dict[‘CHECKSUMHASH’] = Checksum.generate_checksum(data_dict, settings.PAYTM_MERCHANT_KEY)</pre><p>This calculates checksum for the order dictionary that we have created. It also gets added to the same dictionary, which ultimately will be sent to PayTM for payment processing.</p><h4>response() in detail</h4><p>This view validates the transaction by following PayTM’s component interaction flow chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZ2I8tgsLLfZ00iFbgQrVQ.png" /><figcaption>Source: PayTM</figcaption></figure><p><strong>NOTE</strong>: VerifyPaytmResponse function from utils.py is responsible for performing steps 6, 7 and 8 from the above flow chart.</p><p>Finally, our urls.py should look something like this,</p><pre>from django.contrib import admin<br>from django.urls import path<br>from payments import views</pre><pre>urlpatterns = [<br>    path(&#39;&#39;, views.home),<br>    path(&#39;payment/&#39;, views.payment),<br>    path(&#39;response/&#39;, views.response),<br>    path(&#39;admin/&#39;, admin.site.urls),<br>]</pre><p>This concludes our coding part. Let’s have a birds eye view on our directory structure.</p><pre>.<br>├── db.sqlite3<br>├── manage.py<br>├── payments<br>│   ├── Checksum.py<br>│   ├── __init__.py<br>│   ├── admin.py<br>│   ├── apps.py<br>│   ├── models.py<br>│   ├── templates<br>│   │   └── payments<br>│   │       └── payment.html<br>│   ├── tests.py<br>│   ├── utils.py<br>│   └── views.py<br>└── paytmdjango<br>    ├── __init__.py<br>    ├── asgi.py<br>    ├── settings.py<br>    ├── urls.py<br>    └── wsgi.py</pre><h3>Run Time</h3><p>It is time to test our code! Fasten your seat belts.</p><pre>(env) $ python manage.py runserver 8000</pre><p>Visit, <a href="http://127.0.0.1:8000/payment/">http://127.0.0.1:8000/payment/</a> it will redirect you to PayTM’s checkout page. If you gave MOBILE_NO or EMAIL along with payment query in payment()view, it should pre-populate the checkout page with that detail. You can get test instruments for payment gateway from here, <a href="https://developer.paytm.com/docs/testing-integration/">https://developer.paytm.com/docs/testing-integration/</a></p><p>Complete your payment and if you receive Transaction Successful message then the PayTM payment gateway is successfully integrated with your Django project!</p><p>Thanks for reading. I hope this was helpful. If you have any questions, feel free to leave a response.</p><h3>References and further reading</h3><p><a href="https://github.com/harishbisht/paytm">https://github.com/harishbisht/paytm</a></p><p><a href="https://developer.paytm.com/docs/">https://developer.paytm.com/docs/</a></p><p><a href="https://developer.paytm.com/docs/v1/payment-gateway/">https://developer.paytm.com/docs/v1/payment-gateway/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8df17932026" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>