Conditions | 4 |
Total Lines | 54 |
Code Lines | 27 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | #!/usr/bin/env python3 |
||
82 | @login_required |
||
83 | def protected_view(request, path): |
||
84 | """ |
||
85 | Redirect the request to the path used by nginx for protected media. |
||
86 | """ |
||
87 | |||
88 | logger.debug("Received path %s for download" % (path)) |
||
89 | |||
90 | # test for submission ownership |
||
91 | dirname = os.path.dirname(path) |
||
92 | |||
93 | if dirname == 'data_source': |
||
94 | # I got a submission. Get a submission belonging to owner or 404 |
||
95 | submission = get_object_or_404( |
||
96 | Submission, |
||
97 | owner=request.user, |
||
98 | uploaded_file=path) |
||
99 | |||
100 | logger.debug("Got submission %s" % (submission)) |
||
101 | |||
102 | # derive downloadable path. Applies to any protected file |
||
103 | full_path = os.path.join( |
||
104 | settings.PROTECTED_MEDIA_LOCATION_PREFIX, path |
||
105 | ) |
||
106 | |||
107 | file_name = os.path.basename(path) |
||
108 | |||
109 | # try to determine file type |
||
110 | file_type, encoding = mimetypes.guess_type(path) |
||
111 | |||
112 | logger.debug("Detected content type: %s" % (file_type)) |
||
113 | |||
114 | # get file size using protected storage |
||
115 | storage = ProtectedFileSystemStorage() |
||
116 | file_size = storage.size(path) |
||
117 | |||
118 | # try to set file type to response |
||
119 | # https://djangosnippets.org/snippets/1710/ |
||
120 | if file_type is None: |
||
121 | file_type = 'application/octet-stream' |
||
122 | |||
123 | # force django to attach file in response |
||
124 | response = HttpResponse(content_type=file_type) |
||
125 | |||
126 | if encoding is not None: |
||
127 | response['Content-Encoding'] = encoding |
||
128 | |||
129 | # https://stackoverflow.com/a/1158750/4385116 |
||
130 | response["X-Accel-Redirect"] = smart_str(full_path) |
||
131 | response['Content-Disposition'] = 'attachment; filename="{}"'.format( |
||
132 | file_name) |
||
133 | response['Content-Length'] = file_size |
||
134 | |||
135 | return response |
||
136 |