Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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 <code>make_response</code> 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:</p> <pre><code>from flask import make_response @app.route('/docs/&lt;id&gt;') 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 </code></pre> <p>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:</p> <pre><code>&lt;embed src="/docs/pdfid8676etc" width="500" height="375"&gt; </code></pre> <p>You could even make the src dynamic with a Jinja2 template. Let's put this in doc.html (note the curly brackets):</p> <pre><code>&lt;embed src="/docs/{{doc_id}}"&gt; </code></pre> <p>Then in a view function, you just return the rendered template with the appropriate doc_id:</p> <pre><code>from flask import render_template @app.route('/&lt;id&gt;') def show_pdf(id=None): if id is not None: return render_template('doc.html', doc_id=id) </code></pre> <p>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!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload