Showing posts with label flask. Show all posts
Showing posts with label flask. Show all posts

Beyond the Time

Sometimes it's on our side, specially when we are young, yet sometimes it could be against our will. But it's unbeatable, unstoppable, for poor, rich, old and young. Its perpetual existence in our lives, almost gives and idea of a living entity, isn't it? But beyond our lyrical view, it's more practical than we generally imagine.

For us, Developers, from tasks that we need to finish of our sprints, to date and time computations that provide information from applications, time plays a big role.

I was truly wondering on some aspects about the perception that we can have from time, from science to software development, and this article came out. It could be an amalgamation of multiple subtopics, but it would be unfair to discuss about time computations in Python or any programming language, without writting about other time related things that precede the invention of the digital computer.

Earth's Spins

A complete rotation of Earth on its axis, it's a day (not exactly 24hs), divided in hours, minutes, seconds, etc., and Earth revolves in orbit around the sun, resulting in a Tropical or Solar Year. Even before knowing this astronomical perspective, Mexicas, Egyptians, Greeks and many other civilizations, were counting days, being by the cycle of Sun, Moon, or even by other more simpler events, creating their own devices for timekeeping.

Counting with Precision

In fact, Earth's revolution around the Sun has extra hours and minutes, which are later on added as the 29th day of February of a Leap Year. Worth to observe that Earth's rotation speed varies in response to climatic and geological events, resulting in Leap Seconds, which are gradually added to the Coordinated Universal Times (UTC), where Atomic Clocks have an important role on adjusting the time as we know, providing precise measure of a Second, based on the transitions of the Caesium-133 atoms.

Analogical clocks are useful, yes, even though they get out of sync. Before the Atomic Clocks, they were there, with great engineering on their manufacturing, like this UTC Clock designed and created by the great Mexican engineer, Alejandro Olvera Charolet, using cogs, pendulums, relying upon the force of gravity.

UTC Clock by Alejandro Olvera Charolet at Centanario Clocks factory (Zacatlán, Puebla - Mexico)

But since when should we count the days?

Besides the Gregorian Calendar, there are hundreds of calendar systems: Iranian, Japanese, Korean (South), Juche (North Korea), Tibetan, etc. What all of them have in common is: an epoch. A starting pointing for counting the time, generally being an event, an epoch.

On the Gregorian Calendar, the birth of Jesus Christ, is the epoch where the time starts to be counted, having the notion of time before (Before Christ) and after this event (Anno Domini). The fall of the Persian Empire was in 330 B.C., and the Colosseum was built in Rome between 70 ~ 80 AD: two events, one before and other after the birth of Jesus Christ.

That being said, computers should know from which epoch the time starts to be counted too for a matter of computations related with date and time. Operating Systems have different dates as the epoch. On Unix and GNU/Linux like OSes, January 1, 1970 00:00:00 is the epoch. The engineers Dennis Ritchie and Ken Thompson between the 60's and start of the 70's, where discussing the definition of an epoch for Unix and the New Year's Day was the option, later on inherited by all flavors of Unix 'n GNU/Linux created so until now.

Unfortunately, we don't have so much time until the Year 2038 problem, at least for the legacy 32-bits architectures, for the maximum signed integer supported by 32-bits computers, will reach the timestamp 03:14:07 on Tuesday, 19 January 2038. On the next second, 32-bits computers will start counting the time at 20:45:52 on Friday, 13 December 1901.

Software Development, Time and Scenarios

It's a challenge for us too. We have to deal with it, in terms of hard and soft skills, developing software that transforms and calculates time spent, while keeping an eye on the sprint, for time is running, and so the sprint. We have also Time Complexity serving to estimate the amount of computer time an instruction may consume, therefore understanding the worst case scenario of our code, helping us to optmize our code to the most efficient instructions, having some relation with Software Profiling (subject for another post).

Some tasks that we face, involving time computations:

  • data ingestion, normalizing and storing data and timestamps in databases
  • processing of programs/web services log files, measuring intervals between events
  • exposure of database records and their timestamps through APIs

And by the way, hardware clocks/computers must be synchronized with Time Servers connected with Atomic Clocks via a network protocol called NTP. As long as we have NTP protocol working fine (no firewall filters) and Time Servers synced with Atomic Clocks, hardware clocks will always be synced, so as the date and time of our applications, their events, everything precise, from the moment that you buy a product, to the moment that you received the package in your house.

Time computations with Strings? Nope.

String representations of time are hard to be calculated. Converting number representations to integer data types, then performing calculations, nope, that doesn't work. Fortunately, standard libraries from many programming languages have their own implementations for converting string representations of date, time or timestamps, to objects, so we can access years, days, minutes, seconds, etc., as attributes, making it way more easier to access and compute these values.

While interacting with external data sources (REST APIs, .csv files, etc.), things start to get complicated, for we may encounter a variety of date/time presentations (some not following ISO 8601 standard), and the evaluation of how the timestamps are presented is mandatory, in order to convert these representations into datetime objects, these being informed about the timezone (AWARE) or not (NAIVE), doing the required computations and storing it on a database system along with all data processed.

Human Readable Timestamps

The opposite operation. While retrieving database records and performing the necessary computations, datetime objects must be converted to human readable strings. On Python, it could be using strftime() or isoformat(), it depends on the business requirements.

Possible Scenarios While Creating/Consuming APIs

Not so common, but an API with a single endpoint, pretty much representing the flow between User <-> Webservice, serving data and timestamps that participate on relevant computations, delivering more data to the user or to the Frontend of the application (User Interface):

On the other hand, here's a process that performs a request to the API, doing an extra computation, providing an information that wasn't exposed by the API's endpoint (observe the intentational computation between AWARE and NAIVE datetime objects, for a matter of demonstration):

Final Thoughts

It's funny to think about how many things are related with time, specially for us, Developers. Even though we know how to make time computations, extracting information and insights from events, we are just touching the surface of what time really means, beyond our professions.

We may ramble on about the philosophical and technical aspects that this 'entity' constantly plays in our lives, and we may find answers, methods and tricks to make our lives easier while dealing with this titan, but it's the best that we can do so far, in order to invest our efforts on things that most matter for us, for we will not live forever, and neither our loved ones.

I heard once that, if we could extend our existences, then we could beat the time (hahaha). Just making our Telomeres more resistant to the natural shortening, so it will delay our natural end, it's not immortality. We want to live longer, but why?

As Neil DeGrasse Tyson once said:

"It is the knowledge that I am going to die that creates the focus that I bring to being alive. The urgency of accomplishment. The need to express love — now, not later. If we live forever, why even get out of bed in the morning? Because we always have tomorrow. That's not the type of life I want to lead."

Therefore, this Grim Reaper, plays an important role on how do we understand our existence.

The existence of humanity expressed through counted astronomical events, understanding for how long things existed (or still exist), or in which period of our calenders an event has happened. There's no deity or entity here: it's just us, counting events while we get old. And if that bothers you, think for a moment and realize, that you still have time :).

Google Cloud Functions, Serverless and Python

Diary Note turns into Article

It was supposed to be something short, but it became an article, since that the topic could be quite extensive. It might be a tour for you, and I hope you might find something useful. It also has a tutorial with a lot of images and few text (don't worry). Here we go.

First Steps with Cloud Functions

I recently started to work with Google Cloud solutions, specially using Cloud Functions, for a US based client, developing some components for its COVID-19 assessment and notification system. My experience with Google Cloud solutions was equivalent to 0 before this project. I was quite used with AWS for the last 2 years (EC2, S3, RDS, Lambda, etc.), and I felt a little bit lost at the beginning and to be honest, unhappy. It was quite of a journey, to bring things fast on a platform which I just started to work with and the pressure for releasing the product, was something to add up on an almost traumatic process. Fortunately, the day to day experience made me able to get through it successfully.

As a side task, I decide to create my own Google Cloud Free Trial account, make some tests and understand a little bit more about Google Cloud, on a sandbox environment. While I still have some credits, I decided to bring some tips and instructions, which can help someone with creating its own Google Cloud Free Trial account and deploy a simple Python-based Cloud Function.

What if Google charges me all of sudden?

Unlikely to happen. Google Cloud Free Trial is provided with U$ 300 for 90 days of usage. Which ever comes first, spending all the credits or reaching 90 days of usage, you won't have charges on your credit/debit card. The access to Google Cloud will be blocked and only when you decide to unblock it, you'll be charged, depending on usage of the service and its pricing. While setting up you're first Cloud Function, you have to enable billing, but don't worry, since that the billing will only consume the credits from your Free Trial.

Can I make big things with Cloud Functions?

Although I'm presenting just the snippet from Cloud Function editor (and also a small modification of this), you can have key components of your platform running as a Cloud Function, without setting up a server and setting up a lot of stuff. Using this, you're starting to have Microservices/Serverless oriented architecture, in other words. In a real case scenario, you can have a Cloud Function which receives a POST or GET request (Query String) from your main web application, and with the right logic, your Cloud Function can use the information provided on the request to lookup for some specific data from your database system, and do some businness rule with this like sending an email with a report to a costumer or notifying your main web application about the end of service for a user which has an expired service. And for such scenarios, I recommend to configure authentication on your Cloud Function in order to safely access its URL.

You Have to Know About Flask

Flask is a microframework for developing web applications and web services based on Python. It's very simplistic and easy to manage, letting you start little by little, instead of all steps and application structure that Django demands. Both have its own bennefits, but Flask is the framework which will handle HTTP requests to your Python-based Cloud Function. Here's a taste of a minimal Flask application and the handling of HTTP methods. You might also want to understand a little bit about flask.request object, which handles the HTTP request performed to your Cloud Function, which is also the parameter of your entrypoint function.

So we don't need to have Servers anymore ?

Besides being Software Developer, I'm experienced on infrastructure services and can guarantee, that a server designed and configured by an experienced System Administrator, could be much more secure, reliable and faster than a Cloud Function, allowing you to debug, secure, identify and improve your application performance with a flexibility that a Cloud Function won't provide to you. But you need someone to deal with this and the costs might be different from a Cloud Function. To have or not to have Serverless architecture, demands a deep look on all pros and cons, instead of following the buzz of Serverless and Microservices that Google, AWS, etc. makes. Might be a good thing for companies which don't have one or two individuals dedicated to infrastructure or startups, but would it be the right thing to your business?

Requesting Free Trial

Access Google Cloud and click on "Get started for free":

After login, a screen similar to this one will be prompted:

Navigate to Google Cloud Functions option:

Enable billing option (CTRL + click, for opening another window):

Come back to the Google Cloud Function window, reload it and start to create a function:


Setup a Google Cloud Function

Configure the name of the Cloud Function and allow unanthenticated access for its URL:

Configure the memory allocated for the Cloud Function (see pricing and capacities):

For now, it won't be necessary to setup environment variables:

Select Python on the Runtime menu:

No need to define additional packages on requirements.txt. Click on DEPLOY button:

Wait for the green check of the DEPLOY and click on the created function:

Click on TRIGGER menu and click on the URL defined to your Cloud Function:

Or perform a request from your terminal with curl:

For simulating a POST request or a GET with a Query String, you can do something like this:

On the screen where the URL is provided, click on VIEW LOGS for observing the activity of the HTTP requests performed at the Cloud Function:

Environment Variables

Using Environment Variables is a power up to your code and also to your Cloud Function. You can provide dynamic changes on your code, like setting up a different database address and credentials, or turning on/off other functionalities from your Flask app. For your local environment, it would be better to have all the Environment Variables necessary to your app, defined on a .env file, loading it via Python Dotenv. Here's an example below, using the same code, but defining an Environment Variable and obtaining its content inside the Cloud Function, just as you might normally do on your local environment.

After clicking on your Cloud Function, follow this click path and define your Environment Variables: EDIT => VARIABLES, NETWORKING AND ADVANCED SETTINGS => ENVIRONMENT VARIABLES:

Modify your Cloud Function by importing os library, then obtain the content of your defined Environment Variables via os.getenv(). After editing, click DEPLOY again for updating the Cloud Funtion:

Performing a simple GET request, without a query string, will bring the environemt variable DEFAULT MESSAGE. For POST with application/json as Content-Type and GET with Query String "message", it will bring the message sent via the request:


Have a mockup before a Cloud Function

Being on dev, stage or production environment, it's a good thing to guarantee that everything is working fine locally, before moving on with your Cloud Function. Here's a Gist for helping out with mocking up your Cloud Function:

Final Words

Indeed, relatively easy to setup a Cloud Function and a handy solution in order to bring up your component alive, without dealing with all the setups on an instance/server. Serverless architectures are here to stay and spreading very fast. From this Python-based Cloud Function example, Thousands of products from startups to established businesses, are delivering great solution on a Microservices oriented architecture, and taking advantage of what it has to offer, but it's not the end of the classic Server architecture. Remember, that although a Serverless architecture is easy to deal, maintain and also to scale, it doesn't provide the power and reliability that you can achieve while tunning up manny aspects from your administered server, from Kernel parameters to specific configurations to your Web Server, bringing more control, security and reliability to your products, not having a blackbox which you don't have control over it.

As an advice: analyze carefully, pros and cons. Don't get excited about the buzz. Both approaches have great things to offer, but only through a deep analysis, you can determine which one is better to your business, or maybe both.

Questions, doubts or improvements, feel free to leave your comments. Thanks for reading.

Mastodon