I like Flask Framework For Web Application – Python Programming

I think Flask is an amazing Python framework because it is versatile and flexible. Although there is a drawback to using Flask instead of Django such as with Flask you have to implement many features that would come out of the box with Django. For example, with Django, you get a really good admin panel without any effort, but with Flask you have to write the whole admin panel yourself using Flask Security or Flask Login with Flask Admin — these packages together can help you to be able to code a completed admin panel that allows an administrator to do backend stuff and maintain the web application. With Django, the admin panel that comes out of the box looks very nice. Somehow though, perhaps I could be wrong but I’ve found Django’s admin panel, even with extensive personal customization, a heavy custom Django admin panel is still looking too similar to the one that comes out of the box. With Flask, since you have to code this yourself and depending on how much time and effort you put into the admin panel, it could look completely alien from one programmer’s Flask admin panel to the next.

I have learned Python for a couple of months or so, and I have found Flask is easier to work with than Django — I fondly remembered I started with Django first — and I had a hard time with making Django’s routing of internal paths to the way I like it. With Flask though, it’s simple as:

@app.route('/')
def home_page():
    custom code goes here
    return render_template('index.html', some_variable_to_pass_into_Jinja2_template=whatever)

The piece of code above would render an index.html page for a website using Flask. The decorator @app refers to the Flask app itself, and the route part is where the custom method home_page would render the template’s index.html page — in this case, the forward-slash (‘/’) would be a shortcut to render the index.html page. Now, let’s say you have a contact page where a web visitor could email you or so, how would you route this?

@app.route('/contact')
def contact_page():
    custom code goes here
    return render_template('contact.html', whatever=whatever, blah=blah, contact_form=contact_form)

So, when a visitor goes to ‘yourwebsite.yourdomain-name/contact — Flask would render the contact.html page.

I like how Flask routes internal paths like this because it’s so easy to see what is going on — not like Django’s black box. If you take a look at the custom code immediately after the @app.route, you would right away know that the block of codes belongs to what template’s page of the website.

I have heard a lot of people loved to use Flask for writing RESTful API, and I actually had done this once as a practice exercise. I could definitely see why people love Flask for this very purpose — it’s so easy to just jsonify the data using Flask. Once you have jsonify the data, you can totally choose how you would like to return these data when a request is made to the app using Flask. Nonetheless, recently I have been using Flask to just create small websites — not RESTful API — and this is fresher in my mind than doing RESTful API.

To sum it up, I just scratch the surface of what Flask can do in this blog post. Based on my own experience, I’ve found Flask is easier to work with than Django. Deploying the Flask web app felt easier than Django too. For example, once I’d finished writing a Flask web app, all I had to do was initialize a GitHub repository, commit, and push the web app to GitHub. Afterward, I could use Heroku or PythonAnywhere to host my Flask web app either through the free tier or paid tier. Setting up Flask with Heroku or PythonAnywhere isn’t that hard. The key is to do a double-check of the requirements.txt to make sure all required packages that Flask needs to run your web app are listed in this file. Heroku and PythonAnywhere rely on this file to install necessary third-party Python packages. Once you set up the necessary steps for Heroku or PythonAnywhere, the last thing you only have to do is to pull your app’s source from GitHub onto Heroku or PythonAnywhere. On Heroku’s CLI, you can just do [git push heroku main], and on PythonAnywhere Bash console you can just do [git pull].

Anywho, I just completed coding a Portfolio website using Flask. The main feature of this website is to allow a user to add various project showcases so he or she can show off the projects. The website relies on Bootstrap 5 and custom CSS I’d written — this means the whole website is responsive to various screen sizes, including mobile phones. In desktop mode, the website showcase two projects one at a time through the pagination feature — allowing visitors to flip to more projects by clicking next or back to previous projects. In mobile mode, I used lazy load to load the first few showcase projects’ images — then the rest would be loaded on-demand as the website visitors could forever scroll downward till all projects had been loaded. Check out the finished product on https://pythongenex.pythonanywhere.com/.

How To Make Flask’s Flash Message Appears Only Once After User Is Logged-In!

I have been using Flask to work on a personal website for a couple of days. A small snag got me stumped for a while but I finally figured it out. In Flask, you could use flash to alert signed-in users or visitors about their status on your website such as they’d logged in or whatever… One drawback about Flask’s flash message is that it doesn’t go away unless you refresh the browser. Secondly, in the case of an authenticated user, the flash message indicates he’d logged in could appear again and again every time he or she visited the same page.

To solve the problem of Flask’s flash message isn’t going away, I employed JQuery to make the flash message disappear after nine seconds or so. This is easily done by using JQuery, so I won’t go into the detail of how to do this. What I want to talk about is how to make flash messages only appear once after a user is authenticated and logged in.

First, you need to install Flask-Session. Once you got Flask-Session installed, you need to import like so:

from flask_session import Session
from flask import session

Before you can use Flask-Session, you need to configure it to work with Flask.

# Flask-Session
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SESSION_USE_SIGNER'] = True
Session(app)

In a login section of your website/web app, you could do something like this after you execute a function or whatever you do to log the user in:

session['user_id'] = current_user.id
session['flash_session_page_visit'] = 'page_visit'
flash(f'{current_user.name} is logged in!', 'login message')

The session[‘user_id’] = current_user.id is a Python line of code in which you want to store a user object’s property — that you called from the database — into a session which you named as user_id. The next trick is to create a new session out of the thin air just for the purpose of using a negation on it later. For this purpose I’d created ‘page_visit’ session which is just a bogus string, and then I stored this inside session’s flash_session_page_visit. The next step is to create a session_manager_func() as follow:

def session_manager_func():
    if current_user.is_authenticated:
        if not session.get('user_id):
            logout_user()
        else:
            if not session.get('flash_session_page_visit'):
                flash(f'User Status:  {current_user.name} is logged in!', 'user authentication status')

Now you can use the method session_manager_func() inside any Flask’s route to display any flash message just once after a user is logged in. This trick works because you use the negation keyword not to turn flash_session_page_visit into false. Since Flask’s session will be true and be available as long the browser isn’t closed, then this trick negates this session as if it isn’t there at all — this makes the flash message won’t appear twice as long as the browser isn’t closed, reopened, and then logged in again.

The current_user is the object got created by Flask-Login package that I imported for my program. Using Flask-Login I’m able to refer to any logged-in user as current_user either inside my Python script or in Flask’s Jinja HTML page. This makes me use my time more efficiently since I don’t really have to query the database for verifying a logged-in user.

Anywho, if you want to try this, don’t forget to implement some sort of Javascript or JQuery to make the flash message goes away for how many seconds you want this to happen, OK? Hopefully, this little trick will be of use for you as it is for me. Thanks for reading.

Was Our Universe Instantiated From A Superclass Universe?

If my memory isn’t too disconnected, then quantum mechanics — to how I remember best — is a science describing the smallest of the smallest matters and realms in which everyday physics rules do not apply. Quantum mechanics would try to explain the inner working mechanism of the smallest realm that forms particles that are even smaller than electrons – and these particles form electrons and other similar matters. To this day, the inner working mechanism of the quantum realm isn’t so clear, and so scientists sometimes can’t explain such as why one particle can appear to be at two different places at the same time. Theoretically, scientists like to think every matter in the universe is a wave of some sort, and this wave of some sort allows any matter to appear to be in multiple places at once.

To be honest, I don’t think we are too sure about all of this. In fact, I believe that some inner working mechanism of the universe would forever be hidden away from the human mind. Why? To explain this question in my own words, I like to allure you to the idea of object-oriented programming. In programming, languages such as Python use the concept of OOP to allow any programmer to be able to use new features from a class to enhance a programming project he or she is working on — but the programmer doesn’t necessarily need to know all the details of the class or how it was formed. In most cases, a programmer could import packages that got multiple classes and methods into a program he or she is working on, and then access the package’s class to create a new object in his or her image through cherry-picking some features from the package or package’s class — or just creating brand new features for the object through writing new functions and so forth. An example would be a programmer would import Flask into a program to allow the program to serve HTML/CSS/Javascript pages easily — in this case, the program doesn’t need an external web server such as Apache or whatever.

So, I imagine, you could too, that quantum mechanics could be like mechanics that allow our universe to import features from a superclass universe in which the inner working mechanisms of these features won’t be revealed to the human mind since the human mind is boxed inside this universe. Perhaps by chance, the superclass universe is generous that it would allow a mechanism to allow the quantum mechanics to reveal the thread back to itself, but to find out this truth I surmise it won’t be easy. Regardless, it’s not so hard for any of us to imagine this universe of ours is an object which could have been born from a superclass object like how a programmer could create a new object from a superclass without knowing how the superclass was created. If this is true, we could easily tempt to believe that this universe of ours is just one object among many hundreds of billions of similar objects out there that were also instantiated from the superclass universe.

Just Coded A Password Manager in Python.

Lately, I’m learning how to code in Python. So far I was able to complete coding a password manager in Python. This password manager can encrypt and decrypt the stored local passwords. You also need to create a master password before you can use the software. This program got a few minor bugs but it’s fully functioning. I’ve uploaded the source code to Github. Check out the source at https://github.com/aarriitt666/VPass.

Are You Going To Upgrade To Windows 11?

Windows 10 was supposed to be the last version of Windows because Windows 10 would get new frequent updates; Microsoft thought it would never release another version of Windows. Lately, it seems to be confirmed by various news outlets and Microsoft that Windows 11 will come out to replace Windows 10, but the release date is still to be confirmed. Nonetheless, the beta version of Windows 11 will become available for Windows Insiders (users who sign up to download experiment versions of Windows upgrade) on June 28th of 2021. Windows 11 is going to be a free upgrade for Windows 10 users.

There is one problem, the requirements for Windows 11 upgrade or the installation of Windows 11 are more demanding than Windows 10. The minimum requirements for Windows 11 installation are 64bit CPU with 1GHz or faster, a graphics card that supports DirectX 12, 4GB RAM, 64GB of storage at the least, UEFI capable, TPM version 2.0, and Internet connection ready. The most troublesome requirements for upgrading to Windows 11 from Windows 10 are the required graphics cards and TPM. A Graphics card could be expensive if one has to upgrade to a DirectX 12 compatible one. Many gamers who customized their PC for Windows 10 may not have TPM installed.

Now, onto my situation. I got one of those high-end gaming desktops. The graphics card is one of those top-notch ones; this means I do not have to worry about getting a DirectX 12 compatible one since mine is already so compatible with DirectX 12. The desktop got so much RAM which makes the 4GB of RAM requirement seem silly. The real problem which stands in the way of having my gaming desktop to be able to upgrade to Windows 11 is that it needs a TPM (Trusted Platform Module). Some high-end desktop does come with TPM 2.0 ready. My laptop does have it. For some strange reasons, my gaming desktop’s motherboard supports TPM but does not have it installed.

I want to upgrade to Windows 11 for my gaming desktop. So, I go looking everywhere online for a TPM (2.0 version). Unfortunately, everywhere I look, it seems the TPM that is compatible with my motherboard is out of stock. On Amazon, it is out of stock. On NewEgg, it is out of stock. Microcenter doesn’t have it. Google search for dubious online shops has me scratching my head because even these weird places don’t have this TPM module. eBay got the TPM I want, but it cost four times as much as the original listed price. As of right now, I’d add the TPM that is out of stock on Amazon to my Wish List and just hoping that it will become available someday.

In conclusion, I don’t think a free upgrade of Windows 10 to Windows 11 will be a walk in the park for some Windows 10 users. I want to upgrade my Windows 10 desktop to Windows 11 for various reasons — including better security updates, better User Interface, and newer features. For now, I need to get that TPM so I could just plug it onto my motherboard for my desktop to be able to update to Windows 11. Crossing my fingers, and will search for this TPM online again next time.

Will More Companies Seek Bankruptcy As Opening Up Continues?

Before the COVID-19 pandemic hit and the U.S. vs China trade war, JIT (Just in Time) or also known as the Lean Manufacturing method was the way to finish up production of a product line that is fast to bring the products to the market. JIT was made popular by Toyota in the 1930’s “The Toyota Way” production method. This method allows any company not to stock up raw materials and be overburdened with materials and parts in the production chain inventory, but instead, any company that uses JIT can just rely on an overseas or local third party to quickly deliver whatever stuff that a company needs to finish up production of a product line. JIT saves time, cost, and improves the efficiency of manufacturing. Unfortunately, the pandemic hit in early 2020 led to the shutdown of most parts of the world, and JIT isn’t viable as before. Shipping became more difficult, and shipping costs were rising tremendously. Furthermore, companies rather cut costs and shored up cash to protect the business during the uncertainty of the pandemic COVID-19. This pushed the JIT supply chain to the brink of collapse since companies weren’t ordered raw materials and whatever parts so freely as before.

The U.S. vs China trade war is still an ongoing thing, and JIT won’t be taken up favorably by the United States. The United States doesn’t want to be overly dependent on China for crucial and mission-critical materials and parts. One perfect example of this is rare earth minerals. China has cornered the rare earth mineral market, and with such influence, China could always use its power to subdue the United States to China’s demand by not selling rare earth minerals to the United States. Rare earth minerals, although the market isn’t big, these minerals are the absolute must for most electronic stuff that every country needs. To produce an electronic vehicle, smart TV, or just about any other electronic thing — rare earth materials must be present for such a thing to be successfully made. JIT is all about relying on a third partner/country to provide the raw materials and parts, but this could become a security nightmare for the United States in the rare earth mineral example. The pandemic has had only increased the divide between the United States and China in regards to how a global supply chain should be reformed onward.

As the United States and China try to promote different supply chain routes and methods for the globe, locally located companies aren’t yet weaning off the crisis of shortage of materials and parts such as microchip shortage — due to shipping difficulty and countries’ shutdowns across the globe — due to the pandemic is still an ongoing thing since many countries have yet to adequately allow the populations to be vaccinated with COVID-19 vaccines. While the shortages of everything are on the menu, companies are trying to alleviate many shortages as possible by hoarding raw materials and parts. Some companies are trying to overproduce the finished products as these companies have seen the demands of goods rising to an unseen level since the pandemic hit. Thus, rising demands produce rising inflationary prices of finished goods. Shortages of raw materials also push the prices of raw materials to be more expensive such as lumbers. As raw materials get expensive, the expense would pass on to the customers in the finished goods. In general, finished goods are more costly as the demands are high and raw materials’ shortage. With high demands come shrewd business sense, and so companies would go overdrive in producing more finished goods, The question is then when the COVID-19 pandemic slowly goes away and the world is opening up again just like how it was in 2019, services will come back to life, and customers would spend less on goods but more on services — how are the demand bubbles of physical goods would fare in such a scenario?

I think as the opening up roaring back, the inflation would collapse into deflation in how physical goods are being priced — while innovation would continue to drive the costs down of stuff such as electronic — and so many companies that overly produce the finished goods will face the glut of inventory. This could be so inefficient that these companies may wish JIT would become fashionable again. Thus, I think the future earnings of such companies will be way less impressive than most investors would have liked to see. The service sector may pick up again, but companies that are in this sector may still have to face bankruptcy since these companies borrowed a lot of debts during the pandemic COVID-19 service shutdown across the globe. Thus, I don’t think we will see the normal as how we had gotten used to before 2020. Companies with heavy debts should be valued less even if these companies fall into the value investing category. This could be an opportunity or a value trap kind of thing. We could not know an overly burdened indebted company is a bargain or a value trap since such a company could file bankruptcy easily.