1

Pardon me if I am still getting to know Flask and Python...

I have made a .py script using python-docx to build and save a word file. At the end I want to render in my template a button with that calls '/download_file' without refreshing the page.

My document variable is declared inside def main(), which renders my template base.html

I want to perform a .save action on document so I created another function to do so. The problem is, since document is out of scope I am not sure if I can access it.

I get the error AttributeError: 'NoneType' object has no attribute 'save'

from flask import Flask, render_template
from docx import Document

app = Flask(__name__)
document = None

@app.route('/')
def main():

    ...

    # new word document is built from saved information
    document = Document('template.docx')
    table.cell(1, 0).text = text
    table.cell(1, 1).text = text

    return render_template('base.html',
                           messages=messages_list)


@app.route('/download_file')
def save_doc():
    document.save('soumission_export5.docx')


if __name__ == '__main__':
    app.run()

My template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello world!</title>
</head>
<body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type=text/javascript>
            $(function() {
              $('a#test').bind('click', function() {
                $.getJSON('/download_file',
                    function(data) {
                  //do nothing
                });
                return false;
              });
            });
    </script>

    <form>
        <a href=# id=test><button class='btn btn-default'>Download</button></a>
    </form>
</body>
</html>
Philx94
  • 616
  • 3
  • 12
  • 30

0 Answers0