flask render_template with url parameter

女生的网名这么多〃 提交于 2020-01-01 14:20:09

问题


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!


回答1:


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)



回答2:


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")



回答3:


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.



来源:https://stackoverflow.com/questions/47346167/flask-render-template-with-url-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!