简体   繁体   中英

for-loop in Python Function Prevents Further Iterations of Function from Working

I have a Flask application that runs python functions that isn't working properly. I have identified the source of the problem to be a for loop within a function, but I don't understand why it creates an issue or how.

My flask application launches a webserver that allows users to press a button to select "searching by ID" or "searching by date." This then directs them a different page corresponding to their choice of search, and allows them to perform the search which brings up an html file containing the results in a new tab. The search page then redirects back to the original page with button selection. The code for the app is as follows:

from flask import Flask, render_template, redirect, request, url_for
from xml_identifiersearch import searchXML, printHTML

app = Flask(__name__)

@app.route('/') 
def index():
     return render_template('index.html')       

@app.route('/', methods=['POST'])
def gateway():
    if request.form['submit'] == 'Identifier Search':
        return redirect(url_for('identifier_home'))
    else:
        return redirect(url_for('date_home'))

@app.route('/id/')
def identifier_home():
    return render_template('id_home.html')

@app.route('/id/', methods=['POST'])
def identifier_search():
    printHTML(request.form['input'])
    return redirect(url_for('index'))

@app.route('/date/')
def date_home():
    return render_template('date_home.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,debug=True)

The problem, lies in the function "printHTML" This function works properly when I do not include the for loop in its body, but once I do, problems start arising. The code for the function is as follows:

from xml.dom import minidom
import glob
import os
import webbrowser
import random

def searchXML(identifier):
    li = []
    os.chdir('/Users/dinakarguthy/Documents/audit_sample')
    for files in glob.glob("*.xml"):
        with open(files) as f:
            contents=f.read()
        if identifier in contents:
            li.append(files)
    return li

def printHTML(search):    

    f = open("output.html", "w")           #output to a single html file

    print >>f, '<html><head><link rel="stylesheet" type="text/css" href="my_style.css"></head><body><table border="1">'

    print >>f, random.random()*100

    for fileName in searchXML(search):           #search and print a row for each file

        xmldoc=minidom.parse('/Users/dinakarguthy/Documents/audit_sample/' + fileName)   #parse the file
        commonBase=xmldoc.childNodes[1]
        contextData=commonBase.childNodes[1]
        contextValue = contextData.childNodes[1]
        y = contextValue.childNodes[0]

        print >>f, "<tr>"                                                                    
        print >>f, "<td rowspan = '2'>" + fileName + "</td>"                                          
        print >>f, "</tr>"

        print >>f, "<tr>"
        for data in xmldoc.getElementsByTagName('extendedDataElements'):                   #Descriptions
            print >>f, "<td>"
            print >>f, "</td>"

        print >>f, "</tr>"


     print >>f, "</table></body></html>"

    f.close()
    """open html page that was created on webbrowser"""
    new=2
    url="file:///Users/dinakarguthy/Documents/main3/output.html"
    webbrowser.open(url,new=new)

Here is the problem: when I include the for loop that starts with

for filenames in searchXML(search):

The entire function only functions the first time I call it. Every time afterwards, when I call the function, it still runs and my flask app works fine, but all of the function calls between and including the lines

f = open('output.html', 'w')
f.close()

don't run. The part of the function below the line

f.close()

still runs. So a new tab is still opened displaying the file output.html, but the file has not been written over or even truncated by the rest of the function. This is evidenced by the fact that the random number is generated and displayed at the top of the file every time the function runs, but this random number no longer changes.

Without the for loop however, the function works properly and a new random number is written to the file every time. With the for loop, it only works the first time and every time afterwards it fails to run the line

 f = open('output.html', 'w')

and everything associated under it. What is even more curious is that if I add other functions that do similar things, I can't even output or write to OTHER files either. If I run the other functions without for loops, everything functions properly, until I run this function with the for loop and then nothing can be output anymore.

I know this is a long question but I would really appreciate some help because none of what is going on makes any sense.

I have solved this myself. The problem lies in the function "searchXML", which is called in the for loop. The function utilizes the line

os.chdir('/Users/dinakarguthy/Documents/audit_sample')

but the line that opens the file is simply

f = open('output.html', 'w')

I open the file with a relative pathname, instead of an absolute, which is the problem. After the for loop is run my directory is changed to a different one, and so a different output.html file is created/edited in that otehr directory. However, my function still opens up a tab with the 'output.html' that is still in the original directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM