8

I use pdf.js to render pdf in web. The format of the target url like this:

http://www.example.com/book?file=abc.pdf

My problem is: I use flask template to generate page using:

return render_template('book.html', paraKey=paraValue)

But how to attach url parameter "file=abc.pdf" to url? The parameter will be read by viewer.js(included in book.html) that uses it to read file for rendering pdf.

I'm new to flask, hoping guys giving me some help!

jayzhen
  • 111
  • 1
  • 1
  • 7

3 Answers3

8

You could use redirect function, which can redirect you whatever you want:

@app.route('/book')
def hello():
    file = request.args.get('file')
    if not file:
        return redirect("/?file=abc.pdf")
    return render_template('book.html', paraKey=paraValue)
Ivan Bryzzhin
  • 2,009
  • 21
  • 27
  • Much obliged, Bryzzhin! It works! steps is:1)attach parameter to url;2)using render_template generate target page which contains parameter.Now I will not change any js files. – jayzhen Nov 21 '17 at 20:29
1

You can get the parameter that have been passed in the request url by using the request object.

    @app.route("/book", methods=["GET"])
    def get_book():
        file = request.args.get("file")
        if file:
            return render_template('book.html', file=file)
        abort(401, description="Missing file parameter in request url")
Noxiz
  • 279
  • 1
  • 8
  • Thank you for your reply, but render_template cannot let parameter("file" in here) be read by js file.I find a method to resolve it written in the following answer, but it seems not the best choice! – jayzhen Nov 18 '17 at 15:06
  • so why they remove the paramters when return render_template in post and why wtform need render_template then – Mahmoud Magdy May 23 '23 at 21:51
1

This topic helped me reslove my question, but it seems not the perfect answer. code viewer.py not changed.Solution is:

step1)I embed the code

<script>var FILE_PATH = {{ file }}</script>

in template.

step2)the script that will use the variable need to modify the code(viewer.js),from:

var file = 'file' in params ? params.file : DEFAULT_URL

to

var file = FILE_PATH ? FILE_PATH: DEFAULT_URL

It let viewer.js not independent anymore.

I hope someone provide a better solution.

jayzhen
  • 111
  • 1
  • 1
  • 7