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
  • 1,036
  • 3
  • 20
  • 39
  • 1
    Declare your variable above `@app.route('/')` and use it in your routes as `global document`. – bc291 Feb 06 '20 at 23:58
  • Question is: do you want to generate `document` for each user? Do all requests should share one `document`? – bc291 Feb 07 '20 at 00:00
  • Also, do some checking for `document` being `None`. That will happen if `save_doc` fires before `main`. – bc291 Feb 07 '20 at 00:03
  • So I set `global document` at the beginning of `def main()` and it works! – Philx94 Feb 07 '20 at 01:54

0 Answers0