问题
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