-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.py
89 lines (58 loc) · 2.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#! /usr/bin/env python
import shutil
import io
from subprocess import Popen, PIPE
from werkzeug.wsgi import wrap_file
from werkzeug.exceptions import MethodNotAllowed, BadRequest
from werkzeug.wrappers import Request, Response
@Request.application
def application(request):
if is_valid_request(request):
if is_valid_file_request(request):
html_file = request.files['html']
pdf_file = generate_pdf(html_file)
response = build_response(request, pdf_file)
elif is_valid_form_request(request):
html_param = request.form.get('html').encode()
html_file = io.BytesIO(html_param)
file_name = request.form.get('filename')
pdf_file = generate_pdf(html_file)
response = build_post_response(request, pdf_file, file_name)
else:
response = BadRequest('html and filename params are required')
else:
response = BadRequest('Expect a POST request')
return response
def is_valid_request(request):
return request.method == 'POST'
def is_valid_form_request(request):
html_param = request.form.get('html')
filename_param = request.form.get('filename')
return html_param and filename_param
def is_valid_file_request(request):
html_param = request.files.get('html')
return html_param
def generate_pdf(html_file):
process = Popen(wkhtmltopdf_cmd(), stdin=PIPE, stdout=PIPE)
shutil.copyfileobj(html_file, process.stdin)
process.stdin.close()
return process.stdout
def build_response(request, pdf_file):
response = Response(wrap_file(request.environ, pdf_file))
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('content-type', 'application/pdf')
return response
def build_post_response(request, pdf_file, file_name):
response = build_response(request, pdf_file)
response.headers.add('Content-Disposition', header_filename(file_name))
response.headers.add('Content-Transfer-Encoding', 'binary')
return response
def header_filename(file_name):
return "attachment; filename={0}".format(file_name)
def wkhtmltopdf_cmd():
return ['/usr/bin/wkhtmltopdf.sh', '-q', '-d', '300', '-s', 'A4', '-', '-']
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple(
'127.0.0.1', 5000, application, use_debugger=True, use_reloader=True
)