7
7
import os
8
8
9
9
from reliqua .resources .base import Resource
10
+ from reliqua .status_codes import HTTP
10
11
11
12
12
13
class Gzip (Resource ):
@@ -16,19 +17,25 @@ class Gzip(Resource):
16
17
"/gzip" : {},
17
18
}
18
19
19
- def on_get (self , req , resp ):
20
+ def on_get (self , _req , resp ):
20
21
"""
21
22
Send contact message.
22
23
23
24
:accepts json: Accepts JSON
24
- :response 200 binary: All good
25
- :return gzip: Return data
25
+ :response 200 binary: All good
26
+ :return gzip: Return data
26
27
"""
27
- fh = open ("/tmp/hello.txt.gz" , "rb" )
28
- resp .append_header ("Content-Disposition" , "attachment; filename=hello.txt.gz" )
29
- resp .content_type = "application/gzip"
30
- resp .content_encoding = "gzip"
31
- resp .data = fh .read ()
28
+ try :
29
+ with open ("/tmp/hello.txt.gz" , "rb" ) as fh :
30
+ resp .append_header ("Content-Disposition" , "attachment; filename=hello.txt.gz" )
31
+ resp .content_type = "application/gzip"
32
+ resp .content_encoding = "gzip"
33
+ resp .data = fh .read ()
34
+ except FileNotFoundError :
35
+ resp .status = HTTP ("404" )
36
+ except Exception as e :
37
+ resp .status = HTTP ("500" )
38
+ resp .media = {"error" : str (e )}
32
39
33
40
34
41
class Binary (Resource ):
@@ -38,16 +45,23 @@ class Binary(Resource):
38
45
"/bin/{filename}" : {},
39
46
}
40
47
41
- def on_get (self , req , resp , filename ):
48
+ def on_get (self , _req , resp , filename ):
42
49
"""
43
50
Send contact message.
44
51
45
52
:param str filename: [in=path] Filename
46
- :response 200 binary: All good
53
+ :response 200 binary: All good
47
54
:return binary: Return data
48
55
"""
49
56
path = f"/tmp/{ filename } "
50
- resp .stream = open (path , "rb" )
51
- resp .content_type = "application/gzip"
52
- resp .content_encoding = "gzip"
53
- resp .content_length = os .path .getsize (path )
57
+ try :
58
+ with open (path , "rb" ) as fh :
59
+ resp .stream = fh
60
+ resp .content_type = "application/gzip"
61
+ resp .content_encoding = "gzip"
62
+ resp .content_length = os .path .getsize (path )
63
+ except FileNotFoundError :
64
+ resp .status = HTTP ("404" )
65
+ except Exception as e :
66
+ resp .status = HTTP ("500" )
67
+ resp .media = {"error" : str (e )}
0 commit comments