Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - Flask handling a PDF as its own page

For my personal website, I want to have a separate page just for my résumé, which is a PDF. I've tried multiple ways, but I can't figure out how to get flask to handle a PDF.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A note for anyone that came to this question because they're trying to serve PDF files from a database with Flask. Embedding a PDF when the file is stored on a database isn't as simple as when it's in the static folder. You have to use the make_response function and give it the appropriate headers so the browser knows what to do with your binary PDF data, rather than just returning it from the view function like normal. Here's some pseudocode to help:

from flask import make_response

@app.route('/docs/<id>')
def get_pdf(id=None):
    if id is not None:
        binary_pdf = get_binary_pdf_data_from_database(id=id)
        response = make_response(binary_pdf)
        response.headers['Content-Type'] = 'application/pdf'
        response.headers['Content-Disposition'] = 
            'inline; filename=%s.pdf' % 'yourfilename'
        return response

You can change the Content-Disposition from 'inline' to 'attachment' if you want the file to download rather than display in the browser. You could also put this view in a subdomain, e.g. docs.yourapp.com rather than yourapp.com/docs. The last step is to actually embed this document in the browser. On any page you'd like, just use rawrgulmuffin's strategy:

<embed src="/docs/pdfid8676etc" width="500" height="375">

You could even make the src dynamic with a Jinja2 template. Let's put this in doc.html (note the curly brackets):

<embed src="/docs/{{doc_id}}">

Then in a view function, you just return the rendered template with the appropriate doc_id:

from flask import render_template

@app.route('/<id>')
def show_pdf(id=None):
    if id is not None:
        return render_template('doc.html', doc_id=id)

This embeds a document the user requested from a database with a simple GET request. Hope this helps anyone working with lots of PDFs in a database!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...