Reading view

There are new articles available, click to refresh the page.

Getting started with Django Basics

Below listed are the high level steps involved to create a basic Django application.

  1. install python
  2. use venv before installing django =>python -m venv tutorial-env
  3. activate the venv: tutorial-env\Scripts\activate
  4. install django in the venv=> python -m pip install django
  5. check version =>django-admin –version
  6. Create a django project => django-admin startproject myApp
  7. To start the webserver =>python manage.py runserver
  8. From the myApp location, open cmd and type code .=> which will open vs code for this project from VSCode 1. init.py => when the proj receives a request it will understand that this is a package with the help of this init file 2.asgi & wsgi =>Both required during deployment 3.settings.py =>DB, Language, Timezone, Static, URL etc.,
  9. URLs.py => will contain the list of urls used for the project
  10. outside of myApp, db.sqlite3 will be used by default as a lite weight DB
  11. Manage.py =>Very important file
  12. Within the project myAPP, we can create multiple application. to create a new app => python manage.py startapp blog 1.migrations => DB related
    1. init => represent that it is a pkg
    2. admin => for admin purposes
    3. apps => app related config eg: name of the app etc.,
    4. models => contents 6.tests => used for testing the app 7.views 10.Register the app: from myApp->setting.py under Installed_Apps ->add the recently created app ‘blog’ 11.Create the first View:(in general we will receive the request and send back the response) from blog->views.py 1.import HTTPResponse => from django.http import HttpRespose a. Create a python function which take request as a parameter and return the HttpResponse=>A static string output 2.under blog, create a python file by name “urls.py” a.within that file add the urlpatterns list similar to myApp->urls.pyb.in this file, import path, and view from the project->from . import views c.to the urlpatterns list add and entry to the python function created under views.py path(“”<“” represents home directory>,views.index,name=”index”) 3.In myApp-> urls.py a. import path,include from django.urls b. under urlpatterns, add path(“”,include(“blog.urls”)) –> including the url from the blog->urls.py
      1. Time to test the changes. Go to the application url. it should show the content from views.py->index function
      2. Alternatively if we want to call the index with a seperate url a. from the myApp->urls.py-> in the urlpatterns.path -> instead of “”, provide “blogs/” b. Test the same with both default application url and url/blogs

Learning the basics of HTML, CSS & JS – Demo2

In the previous demo, I have used seperate Javascript function to achieve the result. But it looks like it is not the best practice to have multiple JS functions and also the HTML content should be isolated from that of the JS content. In my previous example I have used the HTML content within the JS code.

In this demo, I have called just one JS function with different parameters whenever different links are being clicked. Attaching the code for the same

<html>
<head>
<link rel="stylesheet" href="portfoliostyle.css">
<script src="portfolio_2.js"></script>
</head>
<body>
<nav class="navbar">
<div id="name">Kathir</div>
<div id="menu">
<a id="about" href="#" onclick="show('about')">About Me</a>
<a id="summary" href="#" onclick="show('summary')">Technical Summary</a>
<a id="projects" href="#" onclick="show('project')">Projects</a>
<a id="contact" href="#" onclick="show('contact')">Contact</a>
</div>
</nav>
<div id="pAbout" style="display:none">About Me About me About me</div>
<div id="pSummary" style="display:none">Summary Me Summary me Summary me</div>
<div id="pProject" style="display:none">Project Me Project me Project me</div>
<div id="pContact" style="display:none">Contact Me Contact me Contact me</div>
</body>
</html>
function show(menuID)
{
switch(menuID)
{
case 'about':
document.getElementById("pSummary").style.display='none';
document.getElementById("pProject").style.display='none';
document.getElementById("pContact").style.display='none';
document.getElementById("pAbout").style.display='block';
break;
case 'summary':
document.getElementById("pProject").style.display='none';
document.getElementById("pContact").style.display='none';
document.getElementById("pAbout").style.display='none';
document.getElementById("pSummary").style.display='block';
break;
case 'project':
document.getElementById("pSummary").style.display='none';
document.getElementById("pContact").style.display='none';
document.getElementById("pAbout").style.display='none';
document.getElementById("pProject").style.display='block';
break;
case 'contact':
document.getElementById("pSummary").style.display='none';
document.getElementById("pProject").style.display='none';
document.getElementById("pAbout").style.display='none';
document.getElementById("pContact").style.display='block';
break;
}
}
view raw portfolio_2.js hosted with ❤ by GitHub
.navbar
{
display:flex;
justify-content:space-between;
}
a:hover
{
color:orange;
}

OUTPUT:

Learning the basics of HTML, CSS & JS – Demo1

This is about a sample html page with Nav bar.

Requirement:

When we highlight the menu it should change the font color. And when we click on the menu only the content related to that link has to be displayed.

Solution:

I tried this with a basic html page calling seperate function for each menu item onclick event. Attaching the code snippet.

<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="portfolio.js"></script>
</head>
<body>
<nav class="navbar">
<div id="name">Kathir</div>
<div id="menu">
<a id="about" href="#" onclick="clickAbout()">About Me</a>
<a id="summary" href="#" onclick="clickSummary()">Technical Summary</a>
<a id="projects" href="#" onclick="clickProjects()">Projects</a>
<a id="contact" href="#" onclick="clickContact()">Contact</a>
</div>
</nav>
<p id="details"></p>
</body>
</html>
view raw portfolio.html hosted with ❤ by GitHub
function clickAbout()
{
document.getElementById("details").innerHTML="About Me About Me About Me About Me About Me About Me About Me About Me About Me About Me "
}
function clickSummary()
{
document.getElementById("details").innerHTML="Technical Summary Technical Summary Technical Summary Technical Summary Technical Summary Technical Summary "
}
function clickProjects()
{
document.getElementById("details").innerHTML="Projects Summary Projects Summary Projects Summary Projects Summary Projects Summary Projects Summary "
}
function clickContact()
{
document.getElementById("details").innerHTML="Contact Contact Contact Contact Contact Contact Contact Contact Contact Contact Contact Contact "
}
view raw portfolio.js hosted with ❤ by GitHub
.navbar
{
display:flex;
justify-content:space-between;
}
a:hover
{
color:orange;
}
view raw style.css hosted with ❤ by GitHub

துருவங்களை தந்தமைக்கு நன்றி

அன்பு ஆசிரியர் நக்கீரன் அவர்களுக்கு பாசம் கலந்த வணக்கங்கள்.

சில நாட்களுக்கு முன்பு தங்களது துருவங்கள் தொடரை படிப்பதற்கான வாய்ப்பு கிடைத்து அதை படித்தும் முடித்தேன். ஒரு புத்தகத்தை எடுத்து அதை முழுவதுமாக படித்ததாக எனக்கு சரித்திரமே கிடையாது. அந்த வகையில் நானும் ஒரு மழலையே!

முதலில் மதன் கதாபாத்திரத்தை பற்றிய எனது பார்வையில் சில வரிகள்.

“இரத்தம் சதை சுவாசம் இவை அனைத்திலும் linux” ஊறியிருந்தால் மட்டுமே அப்படி ஒரு பாத்திரத்தை எழுத முடியும். அதிலும் மதன் கார்த்திகா இருவருக்கும் இடையில் ஒரு மென்பொருள் பாலமாக அமைந்தது அரிதிலும் அரிது.

மேலும் மதன் இயற்கையாகவே அமைதி விரும்பி போலும். அதாவது அவர் தோற்றம் பார்ப்பதற்கு சிறிது கரடுமுரடாக இருப்பினும் மனம் லீனுஸ்ய்(linux) மேன்மையையும் நேர்மையையும் கொண்டதாகவே நான் உணர்கிறேன்.

அதே சமயத்தில், தனக்கோ தன சுற்றத்திற்கோ ஏதாவது தவறாக நடக்குமாயின் அதையும் லீனுஸ் (linux) லவே இரும்பு கரம் கொண்டு கட்டுப்படுகிறார். மற்றுமோர் குணமாக வரிந்தோருக்கு வழுங்குதலையும் ஒன்றாகவே இருப்பதாக உணர்கிறேன்.

எதிர்முனையில் கார்த்திகா தெளிந்த நீரோடை போன்று எப்போதுமே காணப்படுகிறார்.

கதையில் என்னை கவர்ந்த ஒரு சில இடங்களை சொல்ல முற்படுகிறேன். ஆண்களை எப்போதுமே தவறாக சித்தரிக்கும் இந்த கால சூழ்நிலையில் ஒரு ஆண் எவ்வளவு மென்மையானவன் என்பதை உணர்த்தும் வகையில் மதன் கதாபாத்திரம் எழுதப்பட்டிருந்தது.

அதுவும் குறிப்பாக, கார்த்திகா எப்போதெல்லாம் மதனுடன் தனிமையில் இருக்கிறாரோ, அப்போதெல்லாம் மதனின் ஆண்மைக்கு சவாலாகவே பார்க்கிறேன். ஒரு சராசரி ஆண்மகன், அந்த மாதிரியான சூழ்நிலையில் எவ்வாறு நடந்து கொள்வார் என்று நாம் பார்த்திருப்போம் அல்லது ஆவ்வாரே இதுவரையில் கதையிலும் திரையிலும் காட்டப்பட்டுள்ளது.

குறிப்பாக இருவரும் ஹோட்டல் அறையின் balconyil நின்று பேசும் போதும் சரி கார்த்திகாவின் வீட்டில் குணா படம் பார்க்கும் பொழுதும் சரி ஒரு ஆண் இப்படி தான் நடந்து கொள்ளவேண்டும் என்பதை அழுத்தம்திருத்தமாக சொல்லப்பட்டிருந்தது.

மறுமுனையில் ஒரு பெண் எப்போதுமே பின்பற்ற வேண்டிய அச்சம் மடம் நாணம் போன்ற குணங்கள் சற்றும் பொருந்தாத புதுமை பெண்ணாக வலம் வருகிறார். ஏன் எப்போதும் ஆண் முன்வந்து தன காதலயோ உணர்ச்சியையோ சொல்லவோ காட்டவோ வேண்டும். பாரதி கண்ட புதுமைபெண்ணல்லவோ நான் என்பது போல் துணிச்சலாக தன் உணர்ச்சிகளை வெளிப்படுத்துகிறாள்.

இந்த தொடரின் முக்கியமான வெற்றி எதுவெனில்? எப்போதெல்லாம் மென்பொருள் பற்றிய உரையாடல் நீள்கிறதோ என்ற எண்ணம் மேலோங்குகிறதோ அப்போது காதல் உள்ளே வந்துவிடும். அல்லது எங்கே மென்பொருளை மறந்து காதல் கதையாக இத்தொடர் மாறியதோ என்ற எண்ணம் வரும்பொழுது linux உள்ளே வரும். இப்படி மாறி மாறி கதைக்களம் நகர்வாதாலேயே சுவாரசியம் சற்றும் குறைய வில்லை.

மேலும் நான் இக்கதையை படிக்கும் பொழுது linux மடிக்கணினியை பக்கம் வைத்தே படித்தேன். மதன் கார்த்திகாவிற்கு எடுத்துரைக்கும் விடயங்களை வாசகர்களாகிய நாமும் செய்து பார்க்க முடிந்தது. அதற்காக மதன் கூறிய எல்லாவற்றையும் செய்து பார்க்க முடியுமா என்றால் முடியாது. ஏனெனில் அது இந்த கதையின் நோக்கமும் அல்ல. linux என்னும் தீப்பொறியையும் அதனின் நீட்சியையும் நம்முள் முதல் பாதியில் கத்திவிட்டு, இரண்டாம் பாதியில் லீனிக்ஸின் விஸ்வரூபத்தை விவரித்தது அருமை.

கதை சார்ந்த அரசியல் பேசவும் நீங்கள் மறக்கவில்லை . அதை சுவைக்கு தேவையான அளவு உப்பு சேர்ப்பது போல சேர்த்ததாலேயே இதை எல்லோராலும் ஏற்றுக்கொள்ள முடிகிறது.

ஒரே ஒரு இடத்தில மட்டுமே மதனின் கதாபாத்திரத்தை சற்றே அவசரக்காரர் போல காட்ட முற்பட்டிர்களா என்று தெரியவில்லை. கார்த்திகாவின் அப்பாவிடம் அவர் கோவப்படும் அந்த சூழல் இன்னும் சற்றே விவரித்திருக்கலாமோ என்று தோன்றியது.. ஓரிறிரு கருத்துக்களை மட்டும் வைத்தே அவர் அவ்வாறானவர் என்று முடிவுக்கு வந்து அதற்கு எதிர்வினையாற்றியதும் ஆச்சர்யத்தை ஊட்டியது. என்னை பொறுத்தவரை மதன் அவ்வாறானவர் இல்லை என்பது மட்டும் உறுதி

கதையில் மற்ற கதாபாத்திரங்களும் சிறப்பாகவே சித்தரிக்கப்பட்டிருக்கிறார்கள் உதாரணத்திற்கு கார்த்திகாவின் தோழி , மதனின் நண்பர் உதய் , நண்பரின் காதலி, நண்பரின் அம்மா, கார்த்திகாவின் பெற்றோர், மதன் வேலை செய்யும் அலுவலகத்தின் ceo கடைசியில் வரும் ஒலிபெருக்கியை கையாண்ட பொடியன் வரை அனைவரும் அருமை.

கடைசியாக உங்களின் ARR மீதான காதலை என்னவென்று சொல்வது. எல்லோரும் அந்த பாடல்களை கேட்டிருப்போம் நீங்கள் கூறிய பின்புலத்தோடு கேட்டிருப்போமா என்பது கேள்விக்குறியே. அதுவும் காதலன் படத்தில் வரும் இந்திரயோ பாடல் இதுநாள் வரை வைரமுத்து எழுதியதாகவே என்னை போல் பலரும் நினைத்திருப்பார்கள்.

இதே கதையை இரு ஆண்களுக்குஇடையே நடப்பதாகவோ, இரு பெண்களுக்குஇடையில் நடப்பதாகவோ சொல்லிருந்தால் இவளவு சுவாரசியம் இருந்திருக்குமா என்பது சந்தேகமே. அதேபோல் கிடைக்கும் இடத்தில எல்லாம் linux சார்ந்த தகவல்களை தரவுகளை விட்டுச்சென்றதும் பாராட்டுக்குரியதே. உதாரணமாக IRC, ILUGC. அருமை.

மொத்தமாக, ஒரு வரியில் கூறவேண்டுமாயின். கதை படித்துமுடித்ததும் குறிப்பாக மூவரை என் மனம் பார்க்க வேண்டுமென ஏங்கியது.

1) மதன் – அவருடைய linux ஆற்றலுக்காக

2) கார்த்திகா – நீங்கள் வர்ணித்தது நிஜமா என்று ஆராய

3) நக்கீரன் என்னும் உங்களை – இப்படி ஒரு பித்தனை உருவாக்கியதற்கு. மென்மேலும் எழுதி என்னை போல் பலரையும்

உங்கள் வலைக்குள் சிக்கவைக்க எனது மனமார்ந்த வாழ்த்துக்கள்.

துருவங்களை தந்தமைக்கு நன்றி

சேது

Reading#Eat the Frog: Ch-3

In chapter-3, the author introduces us to a new concept called 80/20. You can see this pattern in almost everything you comes across in our day to day life. Like in a given area/country 20 percent people will govern the rest of 80 percent people or 20 percent people will be wealthier compared to 80 percent, 20 percent of the customers will be responsible for 80 percent of the sales, etc., In the same way 20 percent of your activities will reflect the 80 percent of your results.

So framing the 20 percent is more important and the author is calling that 20 percent as “Vital few” and the remaining 80 percent as “trivial many”. As discussed in the previous chapters, we tend to spend our energy addressing things from the 80 percent and feel that we did not achieve anything. But that has to happen in the reverse order. From the entire pile of the activities you have listed, pick the top items that you feel either difficult to achieve or tedious yet valuable.

Focus should be given to that 20 percent items. So if you knock off the items from the “Vital few” you feel accomplished and achieving the things from 80 percent or the “Trivial many” shouldn’t be that tough.

As a reader even I am trying to follow and implement these principles in my day to day life and will share my experience in the future blogs. But to me this is very much achievable and we all should give this a try.

Happy reading and see you all in the next chapter discussion.

Reading#Eat the Frog: Ch-2

In continuation from Chapter 1, Chapter 2 starts with how to approach the priority list. Because for a normal person[without any priority like me :-)] every task will be a priority. Unlike that, the author is suggesting an alternative.

It goes like this. Take a piece of paper or use a text editor and name that as “Priorities” and start writing all the tasks that comes to your mind which you wanted to do. Not necessarily in a day, week or month. Just random. For eg: Complete reading a book, finish the assignment, save a minimum amount, practice meditation etc., By the end of this activity, you will have an exhaustive list of task that you wish you could complete.

Next, take one more sheet of paper or open one more text editor and name this as monthly. In here, from the list that you created in “Priorities”, pick up those tasks which could be or has to be completed in the next month. From our example, we can choose “Finish an assignment” and add it to the “monthly” list.

Now the monthly list will be comparatively less than the entire priorities and you have a clear idea of what needs to be done in next 30 days. From here, create one more list for “Weekly”. And do the same exercise of choosing the things that has to or could be completed in next 7 days. And start including them in the weekly list.

Hard part is now complete. From here, connect the things that was described in Chapter#1. Pick up the frog that is bigger to eat and add it to your daily list.

From a larger picture, the moment you knock off one task from daily it creates a ripple effect. That is, it knocks off a task from weekly, then monthly and from the entire priorities. You will accomplished by the end of first week. And if we do this on week 2 we will feel even more happier and accomplished.

This is all about Chapter-2. Once again, this is my understanding and nothing to do with authors narration.

See you again in Chapter-3! Thank you for reading!

Reading#Eat the Frog – Ch:1

I always have the challenge of reading. Whether it is technical documentation, general documentation or anything. If I remember correctly, the last time I read something continuously was when I was in my school and college days. And that too nothing extraordinary but weekly magazines like Anandha Vikatan/Kumudham and very rarely newspapers. That got improved when I started my work and regularly read the news headlines from “The Hindu”. That’s all the reading I have got in my entire life. I have this habit of purchasing the books and will think.. One day.. that One day will come and I will become a Pro Reader and I will read all the books. But that did not happened till date.

So I was pouring all these frustration in the “#Kaniyam” IRC chat along with some more concerns like I have trouble planning things. I use to start with one and if I come across something else I will leave whatever I was doing and start doing the new item and it goes on and on. Then Srini from the Kaniyam IRC group suggested various ideas to give a try and one such idea is reading this book called “Eat the Frog”.

I wouldn’t say the book has changed me completely overnight but the practice of reading a few pages continuously gives a sense of satisfaction. I am not saying I have read 20-30 pages continuously instead I planned to complete a chapter whenever i start.

The book as such has got things we often hear or see elsewhere but more importantly it is structured. When I say it is structured, it starts with the topic explanation on why the author has named the book as “Eat the Frog”.

In our daily life if we think eating a frog is one of our primary task. How will one plan. Because eating a frog is not that easy. And that too if you have more than one frog how will one plan to do that. Here the author compares the frog to that of the tasks we have in a day. Not all tasks are difficult as eating a frog. So if we have frogs of different size and the task is to complete eating them all in a day. How will one approach. He will target finishing the bigger one then the next then the next and it goes on. By the time one completes the biggest he will get the confidence to go for the next smaller sized frog.

This analogy works the same way for our daily tasks. Rather than picking the easy ones and save the bulk or harder tasks for a later time, plan to finish the harder or most difficult task first which will help us move with the next difficult task with a lot more confidence.

This was primarily discussed on Chapter 1. After reading this I wanted to see if this approach works. I started implementing it immediately but listing the items it wanted to complete for that day. And in that I sorted those items based on the difficulty(in terms of time). I did not create an exhaustive list rather 4 tasks for that day and out of which 2 are time taking or difficult task.

End of the day I was able to complete the top 2 leaving the remaining 2. I still felt happy because i completed the top 2 which is harder. And moved the pending 2 to next day and kept the priority as top for those 2.

So far it is working and I will continue to write about the other chapters as I complete reading them.

“Let us all start get into the habit of reading and celebrate..happy reading”

Task#6-New version of integrating the Store Billing app to produce a well formatted pdf file using python

I was so much into using the fpdf module that I almost gave up on this particular task. The challenge I faced is that, I can pass the entire content to the createpdf function but the formatting went completely off track. The other option i was thinking is that send lines one after the other to a text file and finally convert that text file to a pdf. But even that task looked out of my ability. I paused this for a few days and poured in all my frustration not just with this task but with all the other challenges in my IRC channel #kaniyam where I received awesome suggestions from Shrinivasan.T, again not just with the solution to this problem but in general about overcoming the challenges in reading.

Took a deep breath and started fresh and came across a resource where they implemented pdf creation using a different module called reportlab where there was a solution to insert the text to display into a python list and get the entries from the list using a loop and add it to the pdf construct. I was able to finally complete the first step using that module.

Here is the code block

import configparser
import psycopg2
import psycopg2.extras
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
config = configparser.ConfigParser()
config.read('config.ini')
hostname = config['ConnPostgres']['hostname']
database = config['ConnPostgres']['database']
port_id = config['ConnPostgres']['port_id']
pwd = config['ConnPostgres']['pwd']
username = config['ConnPostgres']['username']
bill=0
final_bill_txt = ''
textlines = []
def fetch_BillAmount(in_item,in_qty):
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
bill_amount = in_qty * dictItem['itemprice']
return dictItem['itemname'],bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
def billing():
global bill,textlines
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
item_name,calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
textlines.append(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
def write2Pdf(lsTextline):
pdf = canvas.Canvas('Demo.pdf')
pdf.setFillColorRGB(0,0,255)
pdf.setFont("Courier-Bold",24)
pdf.drawCentredString(290,720,"Shoppers Mart")
pdf.line(30,710,550,710)
text = pdf.beginText(40,680)
text.setFont("Courier",18)
for line in lsTextline:
text.textLine(line)
pdf.drawText(text)
pdf.save()
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print(f'Your total bill amount is ${bill}')
textlines.append(f'Your total bill amount is ${bill}')
print('Thank you for shopping!')
textlines.append('Thank you for shopping!')
write2Pdf(textlines)
break

Task#4- Secure the DB config using configParser

The below program uses configparser module to secure the DB config or the connection parameters. In the earlier programs the DB connections were all exposed and kept in the same program. In this program, DB connection is saved under a different file named “config.ini” and the parameters were called with the help of “ConfigParser”.

import configparser#Note: All lowercase
import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
config = configparser.ConfigParser()#Note:the calling method is a camel case
config.read('config.ini')
in_Item2buy = input('Enter the itemcode required:')
in_ItemQty = int(input('Enter the quantity:'))
hostname = config['ConnPostgres']['hostname']
database = config['ConnPostgres']['database']
port_id = config['ConnPostgres']['port_id']
pwd = config['ConnPostgres']['pwd']
username = config['ConnPostgres']['username']
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_Item2buy,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_ItemQty * dictItem['itemprice']
print('The bill amount for ',dictItem['itemname'],':$',bill_amount) # Print the price
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()

Task#3c: BillingApp with output in pdf file(not formatted properly)

After many unsuccessful attempts, I was able to send the output from my previous code block to a pdf file. Definitely a huge learning in terms of how to properly import the necessary packages how to troubleshoot the error messages and find out the deprecated syntax and replace with the updated ones etc.,

here is the snapshot of the exceptions i received during the process of fixing

And here I am with a screenshot with no exception mentioned

My final code snippet below:

import psycopg2
import psycopg2.extras
from fpdf import FPDF
from fpdf.enums import XPos, YPos
def fetch_BillAmount(in_item,in_qty):
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_qty * dictItem['itemprice']
return dictItem['itemname'],bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
bill=0
final_bill_txt = ''
def billing():
global bill,final_bill_txt
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
item_name,calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print(f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}')
final_bill_txt = final_bill_txt + (f'The Bill amount for {in_qty} of {item_name} : ${calc_bill}\n')
def write2Pdf(in_text):
pdf = FPDF()
pdf.add_page()
pdf.set_font("helvetica", size = 15)
pdf.cell(200, 10, text = "Shoppers Mart",new_x=XPos.LEFT, new_y=YPos.NEXT, align = 'C')
pdf.cell(200, 10, text = final_bill_txt,new_x=XPos.LEFT, new_y=YPos.NEXT,align = 'L')
pdf.output("ShoppersReceipt.pdf")
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print(f'Your total bill amount is ${bill}')
final_bill_txt = final_bill_txt + (f'\n\n\n\nYour total bill amount is ${bill}\n\n\n\n\n\n''Thank you for shopping!')
print(final_bill_txt)
write2Pdf(final_bill_txt)
#print('Thank you for shopping!')
break

PDF Output:

General: Failure to learn from mistakes!

I have been working on a task where I need to collect input(eg: Item code) from user, query the database to fetch the price and then to calculate the bill amount and print the output. I was able to do this successfully. Then comes the next learning where it was asked to feed this output into a pdf file.

I thought it would be a simple task where we will be importing a package and use that to write the output into a pdf file. I was proved terribly wrong.

I found a link where it was asked to use FPDF as a package to import and use it in the code. When I tried to install on my linux machine i kept getting the below error:

As usual I did not get the signal to use my senses rather my IT mindset to start searching like “unable to install fpdf” 🙂 I went link over link over link but ended up with the same error. It started from 4:45 am this morning and finally around 6 am I decided to learn from “mistakes”. My senses started to work, especially the eyes and the sense of seeing 🙂

I carefully went through the exception, yet my IT brain started to override and asked me to just copy and paste the command from the link. This is classic 🙂

It was mentioned something like this:

If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.

Then I tried exactly the same command but this time my brain partially worked it seems so replaced xyz to fpdf:

Thank god. Computers aren’t meant to use abusive language. hehehehe 🙂

Then I went back to the pavillion and started searching other links where they asked to install jinja2( i tried that too). And in the same error message, it was mentioned to consider virtual environment, why to leave that, yes I tried that too.

Somehow I got through installing the virtual environment. But after that, I do not know what to do or interpret the error details. So the failure streak continues

Finally…………………………….

My senses were awaken 🙂 And the brain started to work as if I had an espresso shot 🙂 This time i tried the below

Though it failed again. As I said, “I learnt from mistakes(error message)”. And this happened after that.

Moral of the story:

it was told by many people whom I have interacted so far that always “read through the error message. 99% it has got enough information to change and rerun the code or installation” But because of my inherited IT brain I have avoided that till today. But from today, I am planning to change…and “to learn from mistakes(errors)” always. 🙂

Thanks for reading my funny story! 🙂

Task#3b – Billing application from DB using loop

import psycopg2
import psycopg2.extras
def fetch_BillAmount(in_item,in_qty):
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_item,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_qty * dictItem['itemprice']
return bill_amount
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()
bill=0
def billing():
global bill,itemized_bill
in_item = input('Enter the item code:')
in_qty = int(input('Enter the quantity:'))
calc_bill = fetch_BillAmount(in_item,in_qty)
bill = bill + calc_bill
print('Welcome to Shoppers Mart')
first_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_login == 'Y' or in_Opt == 'Y':
billing()
first_login = 'N'
else:
print_txt = 'Your total Bill amount : ',bill
print('Your total Bill amount : ',bill)
print('Thank you for shopping!')
break

Task#3a – To retrieve the bill amount for a specific store item from database

In this program, the user can get the input about what item is required from the store and how many quantities. Based on the input the dynamic query returns the price of the item selected and the bill amount is calculated and printed.

import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
in_Item2buy = input('Enter the itemcode required:')
in_ItemQty = int(input('Enter the quantity:'))
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems where ItemCode= %s'''
cur.execute(select_script,(in_Item2buy,))
dict_items = dict()
dict_items = cur.fetchall()
for dictItem in dict_items:
#print(dictItem) #test print statement to verify the dict of items for the given input
bill_amount = in_ItemQty * dictItem['itemprice']
print('The bill amount for ',dictItem['itemname'],':$',bill_amount) # Print the price
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()

Task#3- My first python program to connect and retrieve data from DB

import psycopg2 #module to connect the postgreSQL DB
import psycopg2.extras #module to fetch the data from DB table in the form of Dictionaries
hostname = 'localhost'
database = 'deptstore'
port_id = 5432
pwd = 'admin@1234'
username = 'postgres'
conn=None
cur=None
try:
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port=port_id
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
#cur = conn.cursor()
select_script = '''Select ItemCode, ItemName, ItemPrice from StoreItems'''
cur.execute(select_script)
dict_items = dict()
dict_items = cur.fetchall()
for items in dict_items:
print(items)
#conn.commit() #not required for this program as we are not doing any DML
except Exception as error:
print(error)
finally:
if conn is not None:
conn.close()
if cur is not None:
cur.close()

Task#2a- A simple billing app to use the information stored in a csv file

#simple billing app using csv read functionality
#PRE_REQUISITE: Place the file "StoreItems.csv" in the current Python folder or specify the complete file path
import csv
in_ItemCode = input('Enter the item code:')
in_ItemQty = int(input('Enter the quantity required: '))
with open('StoreItems.csv','r') as file1:
reader1 = csv.DictReader(file1)
for row in reader1:
if row['ItemCode']==in_ItemCode:
print('The bill amount for',row['ItemName'],'is:$',int(row['ItemPrice'])*in_ItemQty)

Task#2: Billing application for a store

create a project – billing application for a grocery store. define the items and prices as a dictionary.get item number and quantity as input.in w while loop, till the itemnumber = 0.for now on the billing application, define the prices as a dictionary. later, read the price data from a CSV file

''' Function to calculate the billing for the purchased item'''
def billing_app():
item_to_buy = int(input('Enter the itemcode[Rice-1011 Dhal-1012 Oil-1013 Spices-1014]: '))
if item_to_buy in dictStoreItems.keys():
qty_to_buy = float(input('Enter the quamtity: '))
print('The total bill amount for ',item_to_buy,': ',qty_to_buy*dictStoreItems[item_to_buy])
else:
print('Invalid Item Code')
dictStoreItems = {1011:15,1022:10,1033:5,1044:3,1055:2}
input('Enter the membership number: ')
first_time_login = 'Y' #used to identify the first time a shopper logging in
i=1 #looping criteria
in_Opt='Y' #defaulting the option to Y for the first time shopping
while i != 0:
if first_time_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if in_Opt == 'Y' or first_time_login == 'Y':
billing_app()
first_time_login = 'N'
else:
print('Thank you for shopping!')
break
view raw billing_app.py hosted with ❤ by GitHub
#nested dictionaries
Bill_Total = 0
def billing_app():
item_to_buy = int(input('Enter the itemcode[Rice-1011 Dhal-1012 Oil-1013 Spices-1014]: '))
if item_to_buy in dictStoreItems.keys():
qty_to_buy = float(input('Enter the quamtity: '))
print('The Bill amount for ',dictStoreItems[item_to_buy]['Name'],': $',dictStoreItems[item_to_buy]['UnitPrice']*qty_to_buy)
global Bill_Total
Bill_Total = Bill_Total + dictStoreItems[item_to_buy]['UnitPrice']*qty_to_buy
else:
print('Invalid Item Code')
#below is the nested dictionary containing Product code, name and unit price
dictStoreItems = {1011:{'Name':'Rice','UnitPrice':15},1012:{'Name':'Dhal','UnitPrice':10},1013:{'Name':'Oil','UnitPrice':5},1014:{'Name':'Salt','UnitPrice':3}}
input('Enter the membership number: ')#dummy input
print('****Welcome to Payilagam Shoppers Mart*****')#dummy output
first_time_login = 'Y' #default initial condition
i=1 #default loop initial value
while i != 0:
if first_time_login != 'Y':
in_Opt = input('Do you wish to continue shopping?(Y/N)')
if first_time_login == 'Y' or in_Opt == 'Y':
billing_app()
first_time_login = 'N'
else:
print('Your total Bill amount : ',Bill_Total)
print('Thank you for shopping!')
break

Task#1:Calculator module

Basic calculator app code:

Alternate method by using function/method:

Code repo:

in_Option = input('Enter the option 1.Sum 2.Difference 3.Multiplcation 4.Division:')
in_Param1 = input('Enter the parameter 1:')
in_Param2 = input('Enter the parameter 2:')
def switch(in_Option):
if in_Option == '1':
print('You entered the option for Addition and the sum of the 2 inputs are: ',int(in_Param1)+int(in_Param2))
return
if in_Option == '2':
if in_Param1>in_Param2:
print('You entered the option for difference and the difference of the 2 inputs are: ',int(in_Param1)-int(in_Param2))
return
else:
print('You entered the option for difference and the difference of the 2 inputs are: ',int(in_Param2)-int(in_Param1))
return
if in_Option == '3':
print('You entered the option for Product and the Product of the 2 inputs are: ',int(in_Param1)*int(in_Param2))
return
if in_Option == '4':
print('You entered the option for Division and the Product of the 2 inputs are: ',int(in_Param1)/int(in_Param2))
return
else:
print('Invalid option selected')
return
switch(in_Option)
def calc_app(input, param1, param2):
if input == 1:
print('Sum=',param1+param2)
elif input ==2 and param1 > param2:
print('Difference=',param1-param2)
elif input == 2 and param2 > param1:
print('Difference=',param2 – param1)
elif input == 3:
print('Product=',param1*param2)
elif input ==4:
print('Division=',param1/param2)
in_Option = int(input('Enter the option[1-Add 2-Subtract 3-Multiply 4-Division]: '))
param1 = int(input('Enter the parameter 1:'))
param2 = int(input('Enter the parameter 2:'))
calc_app(in_Option,param1,param2)

❌