11 Replies - 816 Views - Last Post: 13 May 2016 - 06:39 AM Rate Topic: -----

#1 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

I having problem to call the search function from Another python file.

Posted 12 May 2016 - 02:25 AM

Hi Python Experts,

I needed your help on from my code. Finding problem to search items from database file (catalogue.txt) using search.py.

I have used isys618wk9 main class that contain all the functions. From that I'm using search.py for search function.

--------------------------
isys618wk9.py

#!C:\Python33\python
publishers = ["Harper Collins",
"Penguins",
"St Pauls Publication",
"Franciscan Media",
"Orbis"]
categories = ["Books", "Audio Books", "Videos", "Music"]

catalogueItemLabels = ["ISBN: ",
"Quantity in stock: ",
"Title: ",
"Category: ",
"Publisher: ",
"Price: ",
"Image location: "]

fname= 'C:/inetpub/ftproot/isys618/Student/FinalWeb/database/catalogue.txt'
#catalogue = [["12121", 20,"Python Prog", "Books", "Orbis", 25.00, "C:\\f.jpg"],
# ["12122", 30,"SAD ", "Books", "Penguins", 100.00, "C:\\f2.jpg"]
#
# ]
def displayProduct(product):
productLabels = ["ISBN","Quantity in Stock","Title",
"Category", "Publisher","Price","Image location"]
i = 0
while i< len(product):
print(productLabels[i]," = ",product[i], end= " ")
i = i + 1
print()

def updateExistingProductInFile(catalogue):
'''
Overwrites the catalogue file with the details of an updated catalogue in the RAM
:param catalogue: The updated catalogue in the RAM
:return: None
'''
outfile = open(fname, "w")
#Order of tokens in a product is [isbn, quantity, title, category, publisher, price, image_location]

for product in catalogue:
outBuf=""
for productDetail in product:
outBuf += str(productDetail) + "\t"
outBuf = outBuf[0:len(outBuf)-1] + "\n"
if len(outBuf)>0:
outfile.write(outBuf)
outfile.close()


def addProductToCatalog(aProduct):
'''
Adds a product to the catalogue file if it is not an existing product
:param aProduct:
:return: None
'''
updatedProductAndCatalgoue = getExistingProduct(aProduct[0])
if updatedProductAndCatalgoue is None:
addNewProductToFile(aProduct)




def addNewProductToFile(product):
'''
Adds a new product to the catalogue file
:param product: The new product in the form of a list
:return: None
'''
outfile = open(fname, "a")
#Order of tokens in a product is [isbn, quantity, title, category, publisher, price, image_location]
outBuf=""
for productDetail in product:
outBuf += str(productDetail)+ "\t"
outBuf = outBuf[0:len(outBuf)-1]+"\n"
if len(outBuf)>0:
outfile.write(outBuf)
outfile.close()

def readProductsFromFile():
'''
Reads the product details from a catalogue file
:return: The catalogue as a list of lists where each inner list represents a product with details in the form:
[ Index 0 refers to isbn, 1 to quantity, 2 to title, 3 to category, 4 to publisher, 5 to price, 6 to image_location]
'''
import os.path

catalogue=[]
if not os.path.isfile(fname):
return catalogue

infile = open(fname, "r")
if infile is not None:
aLine = infile.readline()

while aLine:
#print(aLine)
aLine = aLine[0:len(aLine)-1] #omit \n char
product=aLine.split("\t")
# 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location

product[1] = float(product[1])
product[5] = float(product[5])
catalogue.append(product)
aLine = infile.readline()

infile.close()
return catalogue


def getExistingProduct(isbn):
'''
Finds if catalogue contains a product with the isbn specified as a parameter
:param isbn: The isbn of a product
:return: A list in which the first item is the product and the second item is the catalogue
'''

catalogue = readProductsFromFile()
for aProduct in catalogue:
if aProduct[0] == isbn:
return [aProduct, catalogue]
return None

def enterProductDetails ():
'''
Gets a product's detail from the user's keyboard. The isbn of the product is assumed to tbe unique.
The details entered at the keyboard are: ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location
If an entered isbn is same as an existing product's isbn, asks the user to if the quantity of the product
needs to be updated.
:return: Either an updated existing product or a new product as a list in which the details are in following order:
[ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location]
'''



#ensure a non empty isbn value is entered by the user
while True:
isbn = input("Enter isbn of a product\n")
if isbn != "":
break

#if the isbn is the same as an existing product in the catalogue, then ask the user
#if the quantity of the product needs to be changed. If so change the quantity of that product and return
#the updated product

#if not ask the user to enter a new isbn
resp = getExistingProduct(isbn)
if resp is not None:
#print("This product already exists with the following details\n")
displayProduct(resp)
qtyRes = input("This product already exists with the following details\n" +
" Do you want to update the qty(Y/N)?\n")
if qtyRes == 'Y' or qtyRes == 'y':
qty = float(input("Enter a new qty value\n"))
while qty < 0:
qty = float(input("Enter a new qty value\n"))
product = resp[0]
product[1] = qty
catalogue = resp[1]
updateExistingProductInFile(catalogue)
return product

#ensure a non empty title value is entered by the user
while True:
title = input("Enter the title of a product\n")
if title != "":
break

#ensure a valid price is entered by the user
while True:
price = input("Enter the price of a product\n")
price = float(price)
if price > 0:
break

#ensure a non impage file path is entered by the user
while True:
imagePath = input("Enter the path of an image of a product\n")
if imagePath != "":
break

#ensure valid category is entered by the user
while True:
print("Following categories of products are available\n")
for category in categories:
print(category)
myCategory = input("Enter a valid category\n")
if myCategory in categories:
break

#ensure valid publisher is entered by the user
while True:
print("Following publishers of products are available\n")
for publisher in publishers:
print(publisher)
myPublisher = input("Enter a valid publisher\n")
if myPublisher in publishers:
break

#ensure a valid quantity is entered by the user
while True:
quantity = input("Enter the quantity of a product\n")
quantity = float(quantity)
if quantity > 0:
break

##ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location
return [isbn,quantity,title,myCategory,myPublisher,price,imagePath]



def enterSearchKeyValues ():
print("The enterSearchKeyValues function got invoked\n")


def enterSearchKeyValues():
# enter the search criteria
# criteria can be a combination of the following: category, publisher, price range

res = input("Do you want to search based on 'category'? Y or y for yes, Any other character for no\n")
category = ""
if res == 'Y' or res == 'y':
while category not in categories:
print("Choose a category, valid ones are\n")
for c in categories:
print©
category = input("Enter a valid category\n")

res = input("Do you want to search based on 'publisher'? Y or y for yes, Any other character for no\n")
publisher = ""
if res == 'Y' or res == 'y':
while publisher not in publishers:
print("Choose a publisher, valid ones are\n")
for p in publishers:
print(p)
publisher = input("Enter a valid publisher\n")

res = input("Do you want to search based on 'lower limit of price'? Y or y for yes, Any other character for no\n")
price_lower_limit = -1.0
if res == 'Y' or res == 'y':
while price_lower_limit <= 0:
price_lower_limit = float(input("Enter a valid lower limit of price"))

res = input("Do you want to search based on 'upper limit of price'? Y or y for yes, Any other character for no\n")
price_upper_limit = -1.0
if res == 'Y' or res == 'y':
while price_upper_limit <= 0:
price_upper_limit = float(input("Enter a valid upper limit of price"))

return search(category, price_lower_limit, price_upper_limit, publisher)



def displaySearchResults(searchResults):
if searchResults is None:
print("No results found matching your search criteria")
return
counter = 0
for i in searchResults:
displayProduct(i)
counter += 1
if counter % 5 == 0:
res = input("Enter Y or y to view further set of results. Any other key to discontinue\n")
if res != 'Y' or res != 'y':
break


def displayCatalog():
catalogue = readProductsFromFile()
if len(catalogue) == 0:
print("Catalogue is empty\n")
return
for i in range(30):
print("=", end=" ")
print("\nDisplaying current items in the catalogue\n")
for i in range(30):
print("=", end=" ")
print("\n")

displayProducts(catalogue)

for i in range(30):
print("=", end=" ")
print("\n")


def displayProducts(catalogue):
for item in catalogue:
displayProduct(item)


def displayProduct(item):
i = 0
for detail in item:
print(catalogueItemLabels[i], detail)
i += 1
print("\n")

def search(category, price_lower_range, price_upper_range, publisher):
'''
Searches the catalogue based on search parameters which are specified as parameters
:param category: The search value for catagory
:param price_lower_range: The search value for lower limit of the price
:param price_upper_range: The search value for upper limit of the price
:param publisher: The search value for publisher
:return: A list of list where each inner list contains the details of the products that match
the search criteria
'''
searchResults = []
catalogue = readProductsFromFile()
if category != "" and publisher != "" and price_lower_range != -1 and price_upper_range != -1:
for item in catalogue:
if item[3] == category and item[4] == publisher and price_lower_range <= item[5] <= price_upper_range:
searchResults.append(item)
elif category != "" and price_lower_range != -1 and price_upper_range != -1:
for item in catalogue:
if item[3] == category and price_lower_range <= item[5] <= price_upper_range:
searchResults.append(item)
elif publisher != "" and price_lower_range != -1 and price_upper_range != -1:
for item in catalogue:
if item[4] == publisher and price_lower_range <= item[5] <= price_upper_range:
searchResults.append(item)
elif category != "" and publisher != "" and price_upper_range != -1:
for item in catalogue:
if item[3] == category and item[4] == publisher and item[5] <= price_upper_range:
searchResults.append(item)
elif category != "" and publisher != "" and price_lower_range != -1:
for item in catalogue:
if item[3] == category and item[4] == publisher and item[5] >= price_lower_range:
searchResults.append(item)
elif category != "" and publisher != "":
for item in catalogue:
if item[3] == category and item[4] == publisher:
searchResults.append(item)
elif category != "" and price_upper_range != -1:
for item in catalogue:
if item[3] == category and item[5] <= price_upper_range:
searchResults.append(item)
elif publisher != "" and price_upper_range != -1:
for item in catalogue:
if item[4] == publisher and item[5] <= price_upper_range:
searchResults.append(item)
elif category != "" and price_lower_range != -1:
for item in catalogue:
if item[3] == category and item[5] >= price_lower_range:
searchResults.append(item)
elif publisher != "" and price_lower_range != -1:
for item in catalogue:
if item[4] == publisher and price_lower_range <= item[5]:
searchResults.append(item)
elif price_lower_range != -1 and price_upper_range != -1:
for item in catalogue:
if price_lower_range <= item[5] <= price_upper_range:
searchResults.append(item)
elif category != "":
for item in catalogue:
if item[3] == category:
searchResults.append(item)
elif publisher != "":
for item in catalogue:
if item[4] == publisher:
searchResults.append(item)
elif price_upper_range != -1:
for item in catalogue:
if item[5] <= price_upper_range:
searchResults.append(item)
elif price_lower_range != -1:
for item in catalogue:
if item[5] >= price_lower_range:
searchResults.append(item)
# 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location
if len(searchResults) > 0:
return searchResults
return None

search()
displayCatalog()
displayProduct()
'''
def menu():
#prompt to enter 1 to read product details;ie. invoke enterProductDetails
#prompt to enter 2 to display catalog;ie. invoke displayCatalog
#prompt to enter 3 to read search criteria; ie. invoke enterSearchKeyValues
#prompt to enter 4 to exit
while True:
kbinput = input("Enter 1 to read product details\n" +
"Enter 2 to to display catalog\n" +
"Enter 3 to to read search criteria\n" +
"Enter 4 to exit the program\n"
)
if kbinput == '1':
aProduct = enterProductDetails()
addProductToCatalog(aProduct)
elif kbinput == '2':
displayCatalog()
elif kbinput == '3':
res= enterSearchKeyValues()
displayProducts(res)
elif kbinput == '4':
break



menu()

'''
.........................................................

search.py

#!C:\Python33\python
print( "Content-type: text/html")
# Import modules for CGI handling
import cgi, os
import cgitb; cgitb.enable()
import isys618wk9
# Create instance of FieldStorage
form = cgi.FieldStorage()

#The following two internet tutorials may be useful if you want to extend your program for better file upload code
#http://www.tutorialspoint.com/python/python_cgi_programming.htm CGI programming tutorial
#https://jimmyg.org/blog/2007/file-uploads-in-python.html may be useful to monitor upload progress

def save_uploaded_file(filename_key, save_path):

'''
Saves an POSTed file to a specified path
:param filename_key: The key of the file name field from the POST. The file is uploaded using this key
:param save_path: The path on the server where the file is to be saved
:return: A list indicating whether the file upload is successful or not
'''

fileitem = form[filename_key]
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)

url = os.environ["REQUEST_URI"]
#url will be of the form 'isys618/STUDENT ID/FinalWeb/python_srcs/publicationDetailsResponse.py'
#Hence url[0:url[0:url.rfind('/')].rfind('/')] will yield 'isys618/YOUR STUDENT ID/week10_2016AfterStorage/

base_url = "http://203.10.47.150" + url[0:url[0:url.rfind('/')].rfind('/')] + '/database/'

file_url = base_url + fn
file_path = save_path +fn

open(file_path, 'wb').write(fileitem.file.read())
message = [fn + '" was uploaded to ' , file_url]
else:
message = ['<B>File:</B>\tNo file was uploaded or file upload error\n']
return message



def getPostedValues():
'''
Retrieves the posted values from a HTML form
:return:
'''

category = form.getvalue('category')
publisher = form.getvalue('publisher')
price_lower_range = form.getvalue('lowerLimitPrice')
price_upper_range = form.getvalue('upperLimitPrice')

priceError=""
try:
price =float(price)
except Exception:
priceError = "<B>Invalid price.</B> Enter a value greater than 0\n"

isbnError=""
isbn = form.getvalue('isbn')
if isbn is None or isbn =="":
isbnError = "<B>Invalid ISBN.</B> Enter alpha numerics or numerics\n"

if isbnError=="":
resp = isys618wk9.getExistingProduct(isbn)
if resp is not None:
isbnError= "<B>Invalid ISBN.</B>" + isbn +" already exists in the catalogue\n"

titleError=""
title = form.getvalue('title')
if title is None or title =="":
titleError = "<B>Invalid Title.</B> Enter alphabets or alpha numerics or numerics\n"

quantityError=""
quantity = form.getvalue('quantity')
try:
quantity =float(quantity)
except Exception:
quantityError = "<B>Invalid quantity.</B> Enter a value greater than 0\n"

fileMessageError=""
fileMessage = save_uploaded_file('image_filename',"C:/inetpub/ftproot/isys618/Student/FinalWeb/database/")
if len(fileMessage)==1:
fileMessageError = fileMessage[0]

errorMessages = ["The following validations were not satisfied"]


successMessages=["Following values were successfully retrieved",
"<B>Category:</B>\t"+category, "<B>Publisher:</B>\t"+publisher, "<B>Publisher:</B>\t"+price ]

if priceError !="":
errorMessages.append(priceError)
else:
successMessages.append("<B>Price:</B>\t"+ str(price))

if isbnError !="":
errorMessages.append(isbnError)
else:
successMessages.append("<B>ISBN:</B>\t"+ str(isbn))

if titleError !="":
errorMessages.append(titleError)
else:
successMessages.append("<B>Title:</B>\t"+ title)

if quantityError !="":
errorMessages.append(quantityError)
else:
successMessages.append("<B>Quantity:</B>\t"+ str(quantity))

if fileMessageError !="":
errorMessages.append(fileMessageError)
else:
successMessages.append("<B>File:</B>\t"+ fileMessage[0]+fileMessage[1])
if len(errorMessages)>1:
return errorMessages


#[isbn,quantity,title,myCategory,myPublisher,price,imagePath]
data=[isbn,quantity,title,category,publisher,price,fileMessage[1]]

successMessages.append(data)
return successMessages


def getHTMLFormattedDisplay(messages):
r ='<b><p>' + messages[0] + '</p></b><br>'
index = 1
while index < len(messages):
r = r + '<p>' + messages[index] + '</p><br>'
index = index + 1
return r

def displayResponse():
print('''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Catalog Search</title>
<link rel="stylesheet" type="text/css" href="formCSS.css" />
<style type="text/css">
<!--
.style1 {
font-size: 16pt;
font-weight: bold;
}
-->
</style>
</head>
<body onload="MM_preloadImages('b6.JPG')">
<table width="1106" height="699" border="1" cellpadding="1" cellspacing="1">
<tr>
<th height="145" scope="col">Fitzroy's OnlineBook Shop!!!!</th>
</tr>
<tr>
<td><table width="1099" height="113" border="1" cellpadding="1" cellspacing="1">
<tr>
<th width="167" scope="col"><a href="home.xhtml">Home</a></th>
<th width="104" scope="col"><a href="siteMap.xhtml">Site Map</a></th>
<th width="159" scope="col"><a href="catalogSearch.xhtml">Catalog Search</a></th>
<th width="182" scope="col"><a href="catalogMaintance.xhtml">Catalog Maintance</a></th>
</tr>
</table></td>
</tr>
<tr>
<td height="389"><table width="1097" height="125" border="1" cellpadding="1" cellspacing="1">
<tr>
<th width="544" height="121" nowrap="nowrap" scope="col">New Arrival
<p><img src="img/b1.jpg" alt="b1" width="401" height="500" /></p></th>
<th>
<tr>
<td>
<table id="contentTable">
<tr>
<td id="contentLeft">

<div id="mainContent">

''')


messages = getPostedValues()
if messages[0]=='The following validations were not satisfied':
print (getHTMLFormattedDisplay(messages))
else:
aProduct = messages[-1]
isys618wk9.getExistingProduct(aProduct)
print (getHTMLFormattedDisplay(messages[0:len(messages)-1]))
isys618wk9.addProductToCatalog(aProduct)
print (getHTMLFormattedDisplay(messages[0:len(messages)-1]))


print('''
</div> <!-- mainContent -->
</td>
</tr>
</table>
</td>
</tr>
</th>
</tr>
</table>
<table width="1096" height="161" border="1" cellpadding="1" cellspacing="1">
<tr>
<td width="538" height="157"><p><a href="home.xhtml">Home</a></p>
<p>&nbsp;</p></td>
<td width="538" height="157"><p><a href="siteMap.xhtml">SiteMap</a></p>
<p>&nbsp;</p></td>
<td width="538" height="157"><p class="style1"><a href="catalogSearch.xhtml">CatalogSearch</a></p>
<p>&nbsp;</p></td>
<td width="538"><p><a href="catalogMaintance.xhtml">CatalogMaintance</a></p>
<p><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image5','','b6.JPG',1)"></a></p></td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>
''')

search()
...................................................

Expected output....

In front end -

User give publisher :- Orbis
select category :- Book
Price range :- 10 to 1100

By clicking button :-

The result must display.

Book :-
Price :- 50
Publisher :- Orbis
Qty :- 10
....


I need your help to sort this problem. I'm sure its only one line to be changed. But I do not know what went wrong.

Waiting for you feedback.

Thank you.
KIDX

Is This A Good Question/Topic? 0
  • +

Replies To: I having problem to call the search function from Another python file.

#2 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 768
  • View blog
  • Posts: 3,832
  • Joined: 25-October 06

Re: I having problem to call the search function from Another python file.

Posted 12 May 2016 - 02:29 AM

Posted Image
Was This Post Helpful? 0
  • +
  • -

#3 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

Re: I having problem to call the search function from Another python file.

Posted 12 May 2016 - 02:41 AM

Thank you . Horce. I will Do it again.
Hi Python Experts,

I needed your help on from my code. Finding problem to search items from database file (catalogue.txt) using search.py.

I have used isys618wk9 main class that contain all the functions. From that I'm using search.py for search function.

isys618wk9.py
#!C:\Python33\python
publishers = ["Harper Collins",
              "Penguins",
              "St Pauls Publication",
              "Franciscan Media",
              "Orbis"]
categories = ["Books", "Audio Books", "Videos", "Music"]

catalogueItemLabels = ["ISBN:               ",
                       "Quantity in stock:  ",
                       "Title:              ",
                       "Category:           ",
                       "Publisher:          ",
                       "Price:              ",
                       "Image location:     "]

fname= 'C:/inetpub/ftproot/isys618/S00194547/FinalWeb/database/catalogue.txt'
#catalogue = [["12121", 20,"Python Prog", "Books", "Orbis", 25.00, "C:\\f.jpg"],
#             ["12122", 30,"SAD ", "Books", "Penguins", 100.00, "C:\\f2.jpg"]
#
#          ]
def displayProduct(product):
    productLabels = ["ISBN","Quantity in Stock","Title",
                     "Category", "Publisher","Price","Image location"]
    i = 0
    while i< len(product):
        print(productLabels[i]," = ",product[i], end= " ")
        i = i + 1
    print()

def updateExistingProductInFile(catalogue):
    '''
    Overwrites the catalogue file with the details of an updated catalogue in the RAM
    :param catalogue: The updated catalogue in the RAM
    :return: None
    '''
    outfile = open(fname, "w")
    #Order of tokens in a product is [isbn, quantity, title, category, publisher, price, image_location]

    for product in catalogue:
        outBuf=""
        for productDetail in product:
            outBuf += str(productDetail) + "\t"
        outBuf = outBuf[0:len(outBuf)-1] + "\n"
        if len(outBuf)>0:
            outfile.write(outBuf)
    outfile.close()


def addProductToCatalog(aProduct):
    '''
    Adds a product to the catalogue file if it is not an existing product
    :param aProduct:
    :return: None
    '''
    updatedProductAndCatalgoue = getExistingProduct(aProduct[0])
    if updatedProductAndCatalgoue is None:
        addNewProductToFile(aProduct)




def addNewProductToFile(product):
    '''
    Adds a new product to the catalogue file
    :param product: The new product in the form of a list
    :return: None
    '''
    outfile = open(fname, "a")
    #Order of tokens in a product is [isbn, quantity, title, category, publisher, price, image_location]
    outBuf=""
    for productDetail in product:
        outBuf += str(productDetail)+ "\t"
    outBuf = outBuf[0:len(outBuf)-1]+"\n"
    if len(outBuf)>0:
        outfile.write(outBuf)
    outfile.close()

def readProductsFromFile():
    '''
    Reads the product details from a catalogue file
    :return: The catalogue as a list of lists where each inner list represents a product with details in the form:
    [ Index 0 refers to isbn, 1 to quantity, 2 to title, 3 to category, 4 to publisher, 5 to price, 6 to image_location]
    '''
    import os.path

    catalogue=[]
    if not os.path.isfile(fname):
        return catalogue

    infile = open(fname, "r")
    if infile is not None:
        aLine = infile.readline()

        while aLine:
            #print(aLine)
            aLine = aLine[0:len(aLine)-1] #omit \n char
            product=aLine.split("\t")
            # 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location

            product[1] = float(product[1])
            product[5] = float(product[5])
            catalogue.append(product)
            aLine = infile.readline()

        infile.close()
        return catalogue


def getExistingProduct(isbn):
    '''
    Finds if catalogue contains a product with the isbn specified as a parameter
    :param isbn: The isbn of a product
    :return: A list in which the first item is the product and the second item is the catalogue
    '''

    catalogue = readProductsFromFile()
    for aProduct in catalogue:
        if aProduct[0] == isbn:
            return [aProduct, catalogue]
    return None

def enterProductDetails ():
    '''
    Gets a product's detail from the user's keyboard. The isbn of the product is assumed to tbe unique.
    The details entered at the keyboard are: ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location
    If an entered isbn is same as an existing product's isbn, asks the user to if the quantity of the product
    needs to be updated.
    :return: Either an updated existing product or a new product as a list in which the details are in following order:
    [ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location]
    '''



    #ensure a non empty isbn value is entered by the user
    while True:
        isbn = input("Enter isbn of a product\n")
        if isbn != "":
            break

    #if the isbn is the same as an existing product in the catalogue, then ask the user
    #if the quantity of the product needs to be changed. If so change the quantity of that product and return
    #the updated product

    #if not ask the user to enter a new isbn
    resp = getExistingProduct(isbn)
    if resp is not None:
        #print("This product already exists with the following details\n")
        displayProduct(resp)
        qtyRes = input("This product already exists with the following details\n" +
                        " Do you want to update the qty(Y/N)?\n")
        if qtyRes == 'Y' or qtyRes == 'y':
            qty = float(input("Enter a new qty value\n"))
            while qty < 0:
                qty = float(input("Enter a new qty value\n"))
            product = resp[0]
            product[1] = qty
            catalogue = resp[1]
            updateExistingProductInFile(catalogue)
        return product

    #ensure a non empty title value is entered by the user
    while True:
        title = input("Enter the title of a product\n")
        if title != "":
            break

    #ensure a valid price is entered by the user
    while True:
        price = input("Enter the price of a product\n")
        price = float(price)
        if price > 0:
            break

    #ensure a non impage file path is entered by the user
    while True:
        imagePath = input("Enter the path of an image of a product\n")
        if imagePath != "":
            break

    #ensure valid category is entered by the user
    while True:
        print("Following categories of products are available\n")
        for category in categories:
            print(category)
        myCategory = input("Enter a valid category\n")
        if myCategory in categories:
            break

    #ensure valid publisher is entered by the user
    while True:
        print("Following publishers of products are available\n")
        for publisher in publishers:
            print(publisher)
        myPublisher = input("Enter a valid publisher\n")
        if myPublisher in publishers:
            break

     #ensure a valid quantity is entered by the user
    while True:
        quantity = input("Enter the quantity of a product\n")
        quantity = float(quantity)
        if quantity > 0:
            break

    ##ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location
    return [isbn,quantity,title,myCategory,myPublisher,price,imagePath]



def enterSearchKeyValues ():
   print("The enterSearchKeyValues function got invoked\n")


def enterSearchKeyValues():
    # enter the search criteria
    # criteria can be a combination of the following: category, publisher, price range

    res = input("Do you want to search based on 'category'? Y or y for yes, Any other character for no\n")
    category = ""
    if res == 'Y' or res == 'y':
        while category not in categories:
            print("Choose a category, valid ones are\n")
            for c in categories:
                print(c)
            category = input("Enter a valid category\n")

    res = input("Do you want to search based on 'publisher'? Y or y for yes, Any other character for no\n")
    publisher = ""
    if res == 'Y' or res == 'y':
        while publisher not in publishers:
            print("Choose a publisher, valid ones are\n")
            for p in publishers:
                print(p)
            publisher = input("Enter a valid publisher\n")

    res = input("Do you want to search based on 'lower limit of price'? Y or y for yes, Any other character for no\n")
    price_lower_limit = -1.0
    if res == 'Y' or res == 'y':
        while price_lower_limit <= 0:
            price_lower_limit = float(input("Enter a valid lower limit of price"))

    res = input("Do you want to search based on 'upper limit of price'? Y or y for yes, Any other character for no\n")
    price_upper_limit = -1.0
    if res == 'Y' or res == 'y':
        while price_upper_limit <= 0:
            price_upper_limit = float(input("Enter a valid upper limit of price"))

    return search(category, price_lower_limit, price_upper_limit, publisher)



def displaySearchResults(searchResults):
    if searchResults is None:
        print("No results found matching your search criteria")
        return
    counter = 0
    for i in searchResults:
        displayProduct(i)
        counter += 1
        if counter % 5 == 0:
            res = input("Enter Y or y to view further set of results. Any other key to discontinue\n")
            if res != 'Y' or res != 'y':
                break


def displayCatalog():
    catalogue = readProductsFromFile()
    if len(catalogue) == 0:
        print("Catalogue is empty\n")
        return
    for i in range(30):
        print("=", end=" ")
    print("\nDisplaying current items in the catalogue\n")
    for i in range(30):
        print("=", end=" ")
    print("\n")

    displayProducts(catalogue)

    for i in range(30):
        print("=", end=" ")
    print("\n")


def displayProducts(catalogue):
    for item in catalogue:
        displayProduct(item)


def displayProduct(item):
    i = 0
    for detail in item:
        print(catalogueItemLabels[i], detail)
        i += 1
    print("\n")

def search(category, price_lower_range, price_upper_range, publisher):
    '''
    Searches the catalogue based on search parameters which are specified as parameters
    :param category: The search value for catagory
    :param price_lower_range: The search value for lower limit of the price
    :param price_upper_range: The search value for upper limit of the price
    :param publisher: The search value for publisher
    :return: A list of list where each inner list contains the details of the products that match
    the search criteria
    '''
    searchResults = []
    catalogue = readProductsFromFile()
    if category != "" and publisher != "" and price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and item[4] == publisher and price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif publisher != "" and price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if item[4] == publisher and price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and publisher != "" and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and item[4] == publisher and item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and publisher != "" and price_lower_range != -1:
        for item in catalogue:
            if item[3] == category and item[4] == publisher and item[5] >= price_lower_range:
                searchResults.append(item)
    elif category != "" and publisher != "":
        for item in catalogue:
            if item[3] == category and item[4] == publisher:
                searchResults.append(item)
    elif category != "" and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and item[5] <= price_upper_range:
                searchResults.append(item)
    elif publisher != "" and price_upper_range != -1:
        for item in catalogue:
            if item[4] == publisher and item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and price_lower_range != -1:
        for item in catalogue:
            if item[3] == category and item[5] >= price_lower_range:
                searchResults.append(item)
    elif publisher != "" and price_lower_range != -1:
        for item in catalogue:
            if item[4] == publisher and price_lower_range <= item[5]:
                searchResults.append(item)
    elif price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "":
        for item in catalogue:
            if item[3] == category:
                searchResults.append(item)
    elif publisher != "":
        for item in catalogue:
            if item[4] == publisher:
                searchResults.append(item)
    elif price_upper_range != -1:
        for item in catalogue:
            if item[5] <= price_upper_range:
                searchResults.append(item)
    elif price_lower_range != -1:
        for item in catalogue:
            if item[5] >= price_lower_range:
                searchResults.append(item)
                # 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location
    if len(searchResults) > 0:
        return searchResults
    return None

search()
displayCatalog()
displayProduct()
'''
def menu():
   #prompt to enter 1 to read product details;ie. invoke enterProductDetails
   #prompt to enter 2 to display catalog;ie. invoke displayCatalog
   #prompt to enter 3 to read search criteria; ie. invoke enterSearchKeyValues
   #prompt to enter 4 to exit
    while True:
        kbinput = input("Enter 1 to read product details\n" +
              "Enter 2 to to display catalog\n"   +
              "Enter 3 to to read search criteria\n"   +
              "Enter 4 to exit the program\n"
              )
        if kbinput == '1':
            aProduct = enterProductDetails()
            addProductToCatalog(aProduct)
        elif kbinput == '2':
            displayCatalog()
        elif kbinput == '3':
            res= enterSearchKeyValues()
            displayProducts(res)
        elif kbinput == '4':
            break



menu()

'''



search.py
#!C:\Python33\python                           
print( "Content-type: text/html")              
# Import modules for CGI handling              
import cgi, os
import  cgitb; cgitb.enable()
import isys618wk9
# Create instance of FieldStorage
form = cgi.FieldStorage()

#The following two internet tutorials may be useful if you want to extend your program for better file upload code 
#http://www.tutorialspoint.com/python/python_cgi_programming.htm             CGI programming tutorial
#https://jimmyg.org/blog/2007/file-uploads-in-python.html may be useful to monitor upload progress

def save_uploaded_file(filename_key, save_path):

    '''
    Saves an POSTed file to a specified path
    :param filename_key:    The key of the file name field from the POST. The file is uploaded using this key
    :param save_path:       The path on the server where the file is to be saved
    :return:                A list indicating whether the file upload is successful or not
    '''

    fileitem = form[filename_key]
    # Test if the file was uploaded
    if fileitem.filename:
        # strip leading path from file name to avoid
        # directory traversal attacks
        fn = os.path.basename(fileitem.filename)

        url = os.environ["REQUEST_URI"]
        #url will be of the form 'isys618/YOUR STUDENT ID/week10_2016AfterStorage/python_srcs/publicationDetailsResponse.py'
        #Hence url[0:url[0:url.rfind('/')].rfind('/')] will yield 'isys618/YOUR STUDENT ID/week10_2016AfterStorage/

        base_url = "http://203.10.47.150" + url[0:url[0:url.rfind('/')].rfind('/')] + '/database/'

        file_url = base_url + fn
        file_path = save_path +fn

        open(file_path, 'wb').write(fileitem.file.read())
        message = [fn + '" was uploaded to ' , file_url]
    else:
        message = ['<B>File:</B>\tNo file was uploaded or file upload error\n']
    return message



def getPostedValues():
    '''
    Retrieves the posted values from a HTML form
    :return:
    '''

    category = form.getvalue('category')
    publisher = form.getvalue('publisher')
    price_lower_range = form.getvalue('lowerLimitPrice')
    price_upper_range = form.getvalue('upperLimitPrice')

    priceError=""
    try:
	    price =float(price)
    except Exception:
	    priceError = "<B>Invalid price.</B> Enter a value greater than 0\n"

    isbnError=""
    isbn = form.getvalue('isbn')
    if isbn is None or isbn =="":
        isbnError  = "<B>Invalid ISBN.</B> Enter alpha numerics or numerics\n"

    if isbnError=="":
        resp = isys618wk9.getExistingProduct(isbn)
        if resp is not None:
            isbnError= "<B>Invalid ISBN.</B>" + isbn +" already exists in the catalogue\n"

    titleError=""
    title = form.getvalue('title')
    if title is None or title =="":
        titleError = "<B>Invalid Title.</B> Enter alphabets or alpha numerics or numerics\n"

    quantityError=""
    quantity = form.getvalue('quantity')
    try:
	    quantity =float(quantity)
    except Exception:
	    quantityError = "<B>Invalid quantity.</B> Enter a value greater than 0\n"

    fileMessageError=""
    fileMessage = save_uploaded_file('image_filename',"C:/inetpub/ftproot/isys618/S00194547/FinalWeb/database/")
    if len(fileMessage)==1:
        fileMessageError = fileMessage[0]

    errorMessages = ["The following validations were not satisfied"]


    successMessages=["Following values were successfully retrieved",
                      "<B>Category:</B>\t"+category, "<B>Publisher:</B>\t"+publisher, "<B>Publisher:</B>\t"+price ]

    if priceError !="":
        errorMessages.append(priceError)
    else:
        successMessages.append("<B>Price:</B>\t"+ str(price))

    if isbnError !="":
        errorMessages.append(isbnError)
    else:
        successMessages.append("<B>ISBN:</B>\t"+ str(isbn))

    if titleError !="":
        errorMessages.append(titleError)
    else:
        successMessages.append("<B>Title:</B>\t"+ title)

    if quantityError !="":
        errorMessages.append(quantityError)
    else:
        successMessages.append("<B>Quantity:</B>\t"+ str(quantity))

    if fileMessageError !="":
        errorMessages.append(fileMessageError)
    else:
        successMessages.append("<B>File:</B>\t"+ fileMessage[0]+fileMessage[1])
    if len(errorMessages)>1:
        return errorMessages


    #[isbn,quantity,title,myCategory,myPublisher,price,imagePath]
    data=[isbn,quantity,title,category,publisher,price,fileMessage[1]]

    successMessages.append(data)
    return successMessages


def  getHTMLFormattedDisplay(messages):
    r ='<b><p>' + messages[0] + '</p></b><br>'
    index = 1
    while index < len(messages):
        r = r + '<p>' + messages[index] + '</p><br>'
        index = index + 1
    return r

def displayResponse():
    print('''
         <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Catalog Search</title>
<link rel="stylesheet" type="text/css" href="formCSS.css" />
<style type="text/css">
<!--
.style1 {
	font-size: 16pt;
	font-weight: bold;
}
-->
</style>
</head>
<body onload="MM_preloadImages('b6.JPG')">
<table width="1106" height="699" border="1" cellpadding="1" cellspacing="1">
  <tr>
    <th height="145" scope="col">Fitzroy's OnlineBook Shop!!!!</th>
  </tr>
  <tr>
    <td><table width="1099" height="113" border="1" cellpadding="1" cellspacing="1">
      <tr>
        <th width="167" scope="col"><a href="home.xhtml">Home</a></th>
        <th width="104" scope="col"><a href="siteMap.xhtml">Site Map</a></th>
        <th width="159" scope="col"><a href="catalogSearch.xhtml">Catalog Search</a></th>
        <th width="182" scope="col"><a href="catalogMaintance.xhtml">Catalog Maintance</a></th>
       </tr>
    </table></td>
  </tr>
  <tr>
    <td height="389"><table width="1097" height="125" border="1" cellpadding="1" cellspacing="1">
      <tr>
        <th width="544" height="121" nowrap="nowrap" scope="col">New Arrival
          <p><img src="img/b1.jpg" alt="b1" width="401" height="500" /></p></th>
		<th>
		   <tr>
        <td>
            <table id="contentTable">
                <tr>
                    <td id="contentLeft">

                        <div id="mainContent">

    ''')


    messages = getPostedValues()
    if messages[0]=='The following validations were not satisfied':
        print (getHTMLFormattedDisplay(messages))
    else:
        aProduct = messages[-1]
        isys618wk9.getExistingProduct(aProduct)
        print (getHTMLFormattedDisplay(messages[0:len(messages)-1]))
        isys618wk9.addProductToCatalog(aProduct)
        print (getHTMLFormattedDisplay(messages[0:len(messages)-1]))


    print('''
</div> <!-- mainContent -->
                    </td>
                </tr>
            </table>
        </td>
    </tr>
		  </th>
      </tr>
    </table>
      <table width="1096" height="161" border="1" cellpadding="1" cellspacing="1">
        <tr>
          <td width="538" height="157"><p><a href="home.xhtml">Home</a></p>
          <p>&nbsp;</p></td>
		  <td width="538" height="157"><p><a href="siteMap.xhtml">SiteMap</a></p>
	        <p>&nbsp;</p></td>
		  <td width="538" height="157"><p class="style1"><a href="catalogSearch.xhtml">CatalogSearch</a></p>
	      <p>&nbsp;</p></td>
          <td width="538"><p><a href="catalogMaintance.xhtml">CatalogMaintance</a></p>
            <p><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image5','','b6.JPG',1)"></a></p></td>
        </tr>
    </table></td>
  </tr>
</table>
</body>
</html>
    ''')


search()






Expected output from search.py....

In front end -

User give publisher :- Orbis
select category :- Book
Price range :- 10 to 1100

By clicking button :-

The result must display.

Book :-
Price :- 50
Publisher :- Orbis
Qty :- 10
....


I need your help to sort this problem. I'm sure its only one line to be changed. But I do not know what went wrong.

Waiting for you feedback.

Thank you.
KIDX
Was This Post Helpful? 0
  • +
  • -

#4 DK3250  Icon User is offline

  • Pythonian
  • member icon

Reputation: 349
  • View blog
  • Posts: 1,156
  • Joined: 27-December 13

Re: I having problem to call the search function from Another python file.

Posted 12 May 2016 - 09:23 AM

In your file 'search.py', the last line is
search()
In this file you have no function defined as def search():
In the other file you have def search(category, price_lower_range, price_upper_range, publisher):
So I see two problems:
1. The search function is unknown in the search.py code. You do import like import isys618wk9, but if you intend to use the function you must either do:
a. from isys618wk9 import search or
b. call like this:isys618wk9.search()
2. The required list of arguments is missing in the function call

This post has been edited by DK3250: 12 May 2016 - 09:24 AM

Was This Post Helpful? 0
  • +
  • -

#5 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

Re: I having problem to call the search function from Another python file.

Posted 12 May 2016 - 09:21 PM

Hi D.I.C,

I will do as you told.

Thank you.

KIDX.
Was This Post Helpful? 0
  • +
  • -

#6 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 01:43 AM

Hi D.I.C,

I did as you told , I'm getting error

Error message:
Premature end of script headers: search.py

Just could not get through my python.

Thanks alot.
Was This Post Helpful? 0
  • +
  • -

#7 DK3250  Icon User is offline

  • Pythonian
  • member icon

Reputation: 349
  • View blog
  • Posts: 1,156
  • Joined: 27-December 13

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 01:55 AM

Please post the full error message and the updated program.

From SO:

Quote

There must be at least an empty line between HTTP headers and body.
...
Reference: Wikipedia

So maybe line 145 should be
<meta http-equiv="Content-Type" content="text/html\n; charset=utf-8" />


Was This Post Helpful? 0
  • +
  • -

#8 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 02:50 AM

Hi D.I.C,

ERROR FROM MY BROWER

Server error!

The server encountered an internal error and was unable to complete your request.

Error message:
Premature end of script headers: search.py

If you think this is a server error, please contact the webmaster.
Error 500
203.10.47.150
13/05/2016 7:42:26 PM
Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1



---------------------------------------
Updated Code in Search.py
---------------------------------------
#!C:\Python33\python
print( "Content-type: text/html")
# Import modules for CGI handling              
import cgi, os
import cgitb; cgitb.enable()
import isys618wk9
#import search
# Create instance of FieldStorage
form = cgi.FieldStorage()

fname= 'C:/inetpub/ftproot/isys618/S00194547/FinalWeb/database/catalogue.txt'

#The following two internet tutorials may be useful if you want to extend your program for better file upload code
#http://www.tutorialspoint.com/python/python_cgi_programming.htm             CGI programming tutorial
#https://jimmyg.org/blog/2007/file-uploads-in-python.html may be useful to monitor upload progress

def save_uploaded_file(filename_key, save_path):

    '''
    Saves an POSTed file to a specified path
    :param filename_key:    The key of the file name field from the POST. The file is uploaded using this key
    :param save_path:       The path on the server where the file is to be saved
    :return:                A list indicating whether the file upload is successful or not
    '''

    fileitem = form[filename_key]
    # Test if the file was uploaded
    if fileitem.filename:
        # strip leading path from file name to avoid
        # directory traversal attacks
        fn = os.path.basename(fileitem.filename)

        url = os.environ["REQUEST_URI"]
        #url will be of the form 'isys618/YOUR STUDENT ID/week10_2016AfterStorage/python_srcs/publicationDetailsResponse.py'
        #Hence url[0:url[0:url.rfind('/')].rfind('/')] will yield 'isys618/YOUR STUDENT ID/week10_2016AfterStorage/

        base_url = "http://203.10.47.150" + url[0:url[0:url.rfind('/')].rfind('/')] + '/database/'

        file_url = base_url + fn
        file_path = save_path +fn

        open(file_path, 'wb').write(fileitem.file.read())
        message = [fn + '" was uploaded to ' , file_url]
    else:
        message = ['<B>File:</B>\tNo file was uploaded or file upload error\n']
    return message


def getPostedValues():
    '''
    Retrieves the posted values from a HTML form
    :return:
    '''

    category = form.getvalue('category')
    publisher = form.getvalue('publisher')
    price = form.getvalue('lowerLimitPrice') and form.getvalue('upperLimitPrice')

    priceError=""
    try:
        price = float(price)
    except Exception:
	    priceError = "<B>Invalid price.</B> Enter a value greater than 0\n"

    isbnError=""
    isbn = form.getvalue('isbn')
    if isbn is None or isbn =="":
        isbnError  = "<B>Invalid ISBN.</B> Enter alpha numerics or numerics\n"

    if isbnError=="":
        resp = isys618wk9.getExistingProduct(isbn)
        if resp is not None:
            isbnError= "<B>Invalid ISBN.</B>" + isbn +" already exists in the catalogue\n"

    titleError=""
    title = form.getvalue('title')
    if title is None or title =="":
        titleError = "<B>Invalid Title.</B> Enter alphabets or alpha numerics or numerics\n"

    quantityError=""
    quantity = form.getvalue('quantity')
    try:
	    quantity =float(quantity)
    except Exception:
	    quantityError = "<B>Invalid quantity.</B> Enter a value greater than 0\n"

    fileMessageError=""
    fileMessage = save_uploaded_file('image_filename',"C:/inetpub/ftproot/isys618/S00194547/FinalWeb/database/")
    if len(fileMessage)==1:
        fileMessageError = fileMessage[0]

    errorMessages = ["The following validations were not satisfied"]


    successMessages=["Following values were successfully retrieved",
                      "<B>Category:</B>\t"+category, "<B>Publisher:</B>\t"+publisher, "<B>Publisher:</B>\t"+ price,"<B> Price: </B>\t" ]

    if priceError !="":
        errorMessages.append(priceError)
    else:
        successMessages.append("<B>Price:</B>\t"+ str(price))

    if isbnError !="":
        errorMessages.append(isbnError)
    else:
        successMessages.append("<B>ISBN:</B>\t"+ str(isbn))

    if titleError !="":
        errorMessages.append(titleError)
    else:
        successMessages.append("<B>Title:</B>\t"+ title)

    if quantityError !="":
        errorMessages.append(quantityError)
    else:
        successMessages.append("<B>Quantity:</B>\t"+ str(quantity))

    if fileMessageError !="":
        errorMessages.append(fileMessageError)
    else:
        successMessages.append("<B>File:</B>\t"+ fileMessage[0]+fileMessage[1])
    if len(errorMessages)>1:
        return errorMessages

    #[isbn,quantity,title,myCategory,myPublisher,price,imagePath]
    data=[isbn,quantity,title,category,publisher,price,fileMessage[1]]

    successMessages.append(data)
    return successMessages

def  getHTMLFormattedDisplay(messages):
    r ='<b><p>' + messages[0] + '</p></b><br>'
    index = 1
    while index < len(messages):
        r = r + '<p>' + messages[index] + '</p><br>'
        index = index + 1
    return r

def displaySearchResults(searchResults):
    if searchResults is None:
        print("No results found matching your search criteria")
        return
    counter = 0
    for i in searchResults:
        displayProduct(i)
        counter += 1
        if counter % 5 == 0:
            #res = input("Enter Y or y to view further set of results. Any other key to discontinue\n")
            #if res != 'Y' or res != 'y':
                break

def readProductsFromFile():
    '''
    Reads the product details from a catalogue file
    :return: The catalogue as a list of lists where each inner list represents a product with details in the form:
    [ Index 0 refers to isbn, 1 to quantity, 2 to title, 3 to category, 4 to publisher, 5 to price, 6 to image_location]
    '''
    import os.path

    catalogue=[]
    if not os.path.isfile(fname):
        return catalogue

    infile = open(fname, "r")
    if infile is not None:
        aLine = infile.readline()

        while aLine:
            #print(aLine)
            aLine = aLine[0:len(aLine)-1] #omit \n char
            product=aLine.split("\t")
            # 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location

            product[1] = float(product[1])
            product[5] = float(product[5])
            catalogue.append(product)
            aLine = infile.readline()

        infile.close()
        return catalogue


def displayCatalog():
    catalogue = readProductsFromFile()
    if len(catalogue) == 0:
        print("Catalogue is empty\n")
        return
    print("\n")
    print(catalogue)
    #for i in range(30):
     #   print("=", end=" ")
    #print("\nDisplaying current items in the catalogue\n")
    #for i in range(30):
     #   print("=", end=" ")
   # print("\n")

def displayResponse():
    print('''
         <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Catalog Search</title>
<link rel="stylesheet" type="text/css" href="formCSS.css" />
<style type="text/css">
<!--
.style1 {
	font-size: 16pt;
	font-weight: bold;
}
-->
</style>
</head>
<body onload="MM_preloadImages('b6.JPG')">
<table width="1106" height="699" border="1" cellpadding="1" cellspacing="1">
  <tr>
    <th height="145" scope="col">Fitzroy's OnlineBook Shop!!!!</th>
  </tr>
  <tr>
    <td><table width="1099" height="113" border="1" cellpadding="1" cellspacing="1">
      <tr>
        <th width="167" scope="col"><a href="home.xhtml">Home</a></th>
        <th width="104" scope="col"><a href="siteMap.xhtml">Site Map</a></th>
        <th width="159" scope="col"><a href="catalogSearch.xhtml">Catalog Search</a></th>
        <th width="182" scope="col"><a href="catalogMaintance.xhtml">Catalog Maintance</a></th>
       </tr>
    </table></td>
  </tr>
  <tr>
    <td height="389"><table width="1097" height="125" border="1" cellpadding="1" cellspacing="1">
      <tr>
        <th width="544" height="121" nowrap="nowrap" scope="col">New Arrival
          <p><img src="img/b1.jpg" alt="b1" width="401" height="500" /></p></th>
		<th>
		   <tr>
        <td>
            <table id="contentTable">
                <tr>
                    <td id="contentLeft">

                        <div id="mainContent">

    ''')

    messages = getPostedValues()
    if messages[0]=='The following validations were not satisfied':
        print (getHTMLFormattedDisplay(messages))
    else:
        aProduct = messages[-1]
        isys618wk9.getExistingProduct(aProduct)
        print (getHTMLFormattedDisplay(messages[0:len(messages)-1]))
        isys618wk9.addProductToCatalog(aProduct)
        print (getHTMLFormattedDisplay(messages[0:len(messages)-1]))


    print('''
</div> <!-- mainContent -->
                    </td>
                </tr>
            </table>
        </td>
    </tr>
		  </th>
      </tr>
    </table>
      <table width="1096" height="161" border="1" cellpadding="1" cellspacing="1">
        <tr>
          <td width="538" height="157"><p><a href="home.xhtml">Home</a></p>
          <p>&nbsp;</p></td>
		  <td width="538" height="157"><p><a href="siteMap.xhtml">SiteMap</a></p>
	        <p>&nbsp;</p></td>
		  <td width="538" height="157"><p class="style1"><a href="catalogSearch.xhtml">CatalogSearch</a></p>
	      <p>&nbsp;</p></td>
          <td width="538"><p><a href="catalogMaintance.xhtml">CatalogMaintance</a></p>
            <p><a href="#" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Image5','','b6.JPG',1)"></a></p></td>
        </tr>
    </table></td>
  </tr>
</table>
</body>
</html>
    '''
          )
    #This is the display the information as per requested by the user.
    testinten = isys618wk9.search(category=displayCatalog(),price_lower_range=displayCatalog(),price_upper_range=displayCatalog(),publisher=displayCatalog())
    displaySearchResults(testinten)
    #display the searched results
    

    #isys618wk9.search()
    # noinspection PyArgumentList
    #testinten = isys618wk9.search(category,price_lower_range,price_upper_range,publisher)
    #testinten = isys618wk9.search(category=displayCatalog(),price_lower_range=displayCatalog(),price_upper_range=displayCatalog(),publisher=displayCatalog())

    #isys618wk9.search(displayCatalog(category),displayCatalog(price_lower_range),displayCatalog(price_upper_range),displayCatalog(publisher)




-----------------------------------------
This is isys618wk9.py code
-----------------------------------------

#!C:\Python33\python
publishers = ["Harper Collins",
              "Penguins",
              "St Pauls Publication",
              "Franciscan Media",
              "Orbis"]
categories = ["Books", "Audio Books", "Videos", "Music"]

catalogueItemLabels = ["ISBN:               ",
                       "Quantity in stock:  ",
                       "Title:              ",
                       "Category:           ",
                       "Publisher:          ",
                       "Price:              ",
                       "Image location:     "]

fname= 'C:/inetpub/ftproot/isys618/S00194547/FinalWeb/database/catalogue.txt'
#catalogue = [["12121", 20,"Python Prog", "Books", "Orbis", 25.00, "C:\\f.jpg"],
#             ["12122", 30,"SAD ", "Books", "Penguins", 100.00, "C:\\f2.jpg"]
#
#          ]
def displayProduct(product):
    productLabels = ["ISBN","Quantity in Stock","Title",
                     "Category", "Publisher","Price","Image location"]
    i = 0
    while i< len(product):
        print(productLabels[i]," = ",product[i], end= " ")
        i = i + 1
    print()

def updateExistingProductInFile(catalogue):
    '''
    Overwrites the catalogue file with the details of an updated catalogue in the RAM
    :param catalogue: The updated catalogue in the RAM
    :return: None
    '''
    outfile = open(fname, "w")
    #Order of tokens in a product is [isbn, quantity, title, category, publisher, price, image_location]

    for product in catalogue:
        outBuf=""
        for productDetail in product:
            outBuf += str(productDetail) + "\t"
        outBuf = outBuf[0:len(outBuf)-1] + "\n"
        if len(outBuf)>0:
            outfile.write(outBuf)
    outfile.close()


def addProductToCatalog(aProduct):
    '''
    Adds a product to the catalogue file if it is not an existing product
    :param aProduct:
    :return: None
    '''
    updatedProductAndCatalgoue = getExistingProduct(aProduct[0])
    if updatedProductAndCatalgoue is None:
        addNewProductToFile(aProduct)




def addNewProductToFile(product):
    '''
    Adds a new product to the catalogue file
    :param product: The new product in the form of a list
    :return: None
    '''
    outfile = open(fname, "a")
    #Order of tokens in a product is [isbn, quantity, title, category, publisher, price, image_location]
    outBuf=""
    for productDetail in product:
        outBuf += str(productDetail)+ "\t"
    outBuf = outBuf[0:len(outBuf)-1]+"\n"
    if len(outBuf)>0:
        outfile.write(outBuf)
    outfile.close()

def readProductsFromFile():
    '''
    Reads the product details from a catalogue file
    :return: The catalogue as a list of lists where each inner list represents a product with details in the form:
    [ Index 0 refers to isbn, 1 to quantity, 2 to title, 3 to category, 4 to publisher, 5 to price, 6 to image_location]
    '''
    import os.path

    catalogue=[]
    if not os.path.isfile(fname):
        return catalogue

    infile = open(fname, "r")
    if infile is not None:
        aLine = infile.readline()

        while aLine:
            #print(aLine)
            aLine = aLine[0:len(aLine)-1] #omit \n char
            product=aLine.split("\t")
            # 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location

            product[1] = float(product[1])
            product[5] = float(product[5])
            catalogue.append(product)
            aLine = infile.readline()

        infile.close()
        return catalogue


def getExistingProduct(price):
    '''
    Finds if catalogue contains a product with the isbn specified as a parameter
    :param price: The isbn of a product
    :return: A list in which the first item is the product and the second item is the catalogue
    '''

    catalogue = readProductsFromFile()
    for aProduct in catalogue:
        if aProduct[5] == price:
            return [aProduct, catalogue]
    return None

def enterProductDetails ():
    '''
    Gets a product's detail from the user's keyboard. The isbn of the product is assumed to tbe unique.
    The details entered at the keyboard are: ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location
    If an entered isbn is same as an existing product's isbn, asks the user to if the quantity of the product
    needs to be updated.
    :return: Either an updated existing product or a new product as a list in which the details are in following order:
    [ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location]
    '''



    #ensure a non empty isbn value is entered by the user
    while True:
        isbn = input("Enter isbn of a product\n")
        if isbn != "":
            break

    #if the isbn is the same as an existing product in the catalogue, then ask the user
    #if the quantity of the product needs to be changed. If so change the quantity of that product and return
    #the updated product

    #if not ask the user to enter a new isbn
    resp = getExistingProduct(isbn)
    if resp is not None:
        #print("This product already exists with the following details\n")
        displayProduct(resp)
        qtyRes = input("This product already exists with the following details\n" +
                        " Do you want to update the qty(Y/N)?\n")
        if qtyRes == 'Y' or qtyRes == 'y':
            qty = float(input("Enter a new qty value\n"))
            while qty < 0:
                qty = float(input("Enter a new qty value\n"))
            product = resp[0]
            product[1] = qty
            catalogue = resp[1]
            updateExistingProductInFile(catalogue)
        return product

    #ensure a non empty title value is entered by the user
    while True:
        title = input("Enter the title of a product\n")
        if title != "":
            break

    #ensure a valid price is entered by the user
    while True:
        price = input("Enter the price of a product\n")
        price = float(price)
        if price > 0:
            break

    #ensure a non impage file path is entered by the user
    while True:
        imagePath = input("Enter the path of an image of a product\n")
        if imagePath != "":
            break

    #ensure valid category is entered by the user
    while True:
        print("Following categories of products are available\n")
        for category in categories:
            print(category)
        myCategory = input("Enter a valid category\n")
        if myCategory in categories:
            break

    #ensure valid publisher is entered by the user
    while True:
        print("Following publishers of products are available\n")
        for publisher in publishers:
            print(publisher)
        myPublisher = input("Enter a valid publisher\n")
        if myPublisher in publishers:
            break

     #ensure a valid quantity is entered by the user
    while True:
        quantity = input("Enter the quantity of a product\n")
        quantity = float(quantity)
        if quantity > 0:
            break

    ##ISBN, Quantity in stock, Title, Category, Publisher, Price, Image location
    return [isbn,quantity,title,myCategory,myPublisher,price,imagePath]



def enterSearchKeyValues ():
   print("The enterSearchKeyValues function got invoked\n")


def enterSearchKeyValues():
    # enter the search criteria
    # criteria can be a combination of the following: category, publisher, price range

    res = input("Do you want to search based on 'category'? Y or y for yes, Any other character for no\n")
    category = ""
    if res == 'Y' or res == 'y':
        while category not in categories:
            print("Choose a category, valid ones are\n")
            for c in categories:
                print(c)
            category = input("Enter a valid category\n")

    res = input("Do you want to search based on 'publisher'? Y or y for yes, Any other character for no\n")
    publisher = ""
    if res == 'Y' or res == 'y':
        while publisher not in publishers:
            print("Choose a publisher, valid ones are\n")
            for p in publishers:
                print(p)
            publisher = input("Enter a valid publisher\n")

    res = input("Do you want to search based on 'lower limit of price'? Y or y for yes, Any other character for no\n")
    price_lower_limit = -1.0
    if res == 'Y' or res == 'y':
        while price_lower_limit <= 0:
            price_lower_limit = float(input("Enter a valid lower limit of price"))

    res = input("Do you want to search based on 'upper limit of price'? Y or y for yes, Any other character for no\n")
    price_upper_limit = -1.0
    if res == 'Y' or res == 'y':
        while price_upper_limit <= 0:
            price_upper_limit = float(input("Enter a valid upper limit of price"))

    return search(category, price_lower_limit, price_upper_limit, publisher)



def displaySearchResults(searchResults):
    if searchResults is None:
        print("No results found matching your search criteria")
        return
    counter = 0
    for i in searchResults:
        displayProduct(i)
        counter += 1
        if counter % 5 == 0:
            res = input("Enter Y or y to view further set of results. Any other key to discontinue\n")
            if res != 'Y' or res != 'y':
                break


def displayCatalog():
    catalogue = readProductsFromFile()
    if len(catalogue) == 0:
        print("Catalogue is empty\n")
        return
    for i in range(30):
        print("=", end=" ")
    print("\nDisplaying current items in the catalogue\n")
    for i in range(30):
        print("=", end=" ")
    print("\n")

    displayProducts(catalogue)

    for i in range(30):
        print("=", end=" ")
    print("\n")


def displayProducts(catalogue):
    for item in catalogue:
        displayProduct(item)


def displayProduct(item):
    i = 0
    for detail in item:
        print(catalogueItemLabels[i], detail)
        i += 1
    print("\n")

def search(category, price_lower_range, price_upper_range, publisher):
    '''
    Searches the catalogue based on search parameters which are specified as parameters
    :param category: The search value for catagory
    :param price_lower_range: The search value for lower limit of the price
    :param price_upper_range: The search value for upper limit of the price
    :param publisher: The search value for publisher
    :return: A list of list where each inner list contains the details of the products that match
    the search criteria
    '''
    searchResults = []
    catalogue = readProductsFromFile()
    if category != "" and publisher != "" and price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and item[4] == publisher and price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif publisher != "" and price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if item[4] == publisher and price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and publisher != "" and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and item[4] == publisher and item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and publisher != "" and price_lower_range != -1:
        for item in catalogue:
            if item[3] == category and item[4] == publisher and item[5] >= price_lower_range:
                searchResults.append(item)
    elif category != "" and publisher != "":
        for item in catalogue:
            if item[3] == category and item[4] == publisher:
                searchResults.append(item)
    elif category != "" and price_upper_range != -1:
        for item in catalogue:
            if item[3] == category and item[5] <= price_upper_range:
                searchResults.append(item)
    elif publisher != "" and price_upper_range != -1:
        for item in catalogue:
            if item[4] == publisher and item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "" and price_lower_range != -1:
        for item in catalogue:
            if item[3] == category and item[5] >= price_lower_range:
                searchResults.append(item)
    elif publisher != "" and price_lower_range != -1:
        for item in catalogue:
            if item[4] == publisher and price_lower_range <= item[5]:
                searchResults.append(item)
    elif price_lower_range != -1 and price_upper_range != -1:
        for item in catalogue:
            if price_lower_range <= item[5] <= price_upper_range:
                searchResults.append(item)
    elif category != "":
        for item in catalogue:
            if item[3] == category:
                searchResults.append(item)
    elif publisher != "":
        for item in catalogue:
            if item[4] == publisher:
                searchResults.append(item)
    elif price_upper_range != -1:
        for item in catalogue:
            if item[5] <= price_upper_range:
                searchResults.append(item)
    elif price_lower_range != -1:
        for item in catalogue:
            if item[5] >= price_lower_range:
                searchResults.append(item)
                # 0isbn, 1quantity, 2title, 3category, 4publisher, 5price, 6image_location
    if len(searchResults) > 0:
        return searchResults
    return None


-----------------------------------

User Side Condition :-

Category :- Book
publisher :- Orbis
Upper Price :- 1999$
Lower Price :- 10$

HIT :- Search the results in the DB.

Results:-
1) Book
publisher:- Orbis
price :- 200$
name :- Hello Python.
-----------------------------------

Inside DB :-
All the information of books available .
-----------------------------------

Kidx.
Was This Post Helpful? 0
  • +
  • -

#9 DK3250  Icon User is offline

  • Pythonian
  • member icon

Reputation: 349
  • View blog
  • Posts: 1,156
  • Joined: 27-December 13

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 05:48 AM

Try implement the change suggested in post #7 (Original line 145 is now line 202)

This post has been edited by DK3250: 13 May 2016 - 05:48 AM

Was This Post Helpful? 0
  • +
  • -

#10 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 06:24 AM

Hi D.I.C,

I did the changes . It's same error.
------------------------------

Server error!

The server encountered an internal error and was unable to complete your request.

Error message:
Premature end of script headers: search.py

If you think this is a server error, please contact the webmaster.
Error 500
203.10.47.150
13/05/2016 11:18:22 PM
Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1

-------------------------------------------



Code from search.py
def displayResponse():
    print('''
         <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html\n; charset=utf-8" />
<title>Catalog Search</title>
<link rel="stylesheet" type="text/css" href="formCSS.css" />
<style type="text/css">
<!--


Was This Post Helpful? 0
  • +
  • -

#11 DK3250  Icon User is offline

  • Pythonian
  • member icon

Reputation: 349
  • View blog
  • Posts: 1,156
  • Joined: 27-December 13

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 06:34 AM

OK, this problem is outside my range of expertise.
Let's hope someone else can take over...
Was This Post Helpful? 0
  • +
  • -

#12 KidX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 12-May 16

Re: I having problem to call the search function from Another python file.

Posted 13 May 2016 - 06:39 AM

Thanks alot for the support D.I.C.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1