python-3.xflask

How to get console output into a txt file (using python flask server)


Let's suppose I have a server code and when the function savePersonList() is called, the result printed on console should be saved into a text file.

#server coding

app = Flask(__name__)
def allowed_file(filename):
  # this has changed from the original example because the original did not work for me
    return filename[-3:].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST']) #integrate code below function
def upload_file(): 

    if request.authorization and request.authorization.username == 'user1' and request.authorization.password == 'pass2': #login code line
        if request.method == 'POST':
            print("This is a post Request \n\n")
            file = request.files['file']
            if file and allowed_file(file.filename):
                print("File Sent is valid \n\n")
                print('**found file', file.filename)
                filename = secure_filename(file.filename) #use this from existing code before calling video capture 
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  
    #code
                ''' This is the start of face recongition script '''
                CF.Key.set('d7c5495c64a44bc692761cd7c45ad56e')
                CF.BaseUrl.set('https://southeastasia.api.cognitive.microsoft.com/face/v1.0/')

                firstRun = True
                lastRun  = False

                #savePersonList()

Solution

  • if you are running on linux just use python app.py > file.txt(provided file.txt is created) might as well work on windows.

    and add logger to your flask app as described in docs

    so you can write it for each request yourself the file.txt then acts as your debug log.Hope it helps.