| 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 |
||
| 94 | @login_required |
||
| 95 | def protected_view(request, path): |
||
| 96 | """ |
||
| 97 | Redirect the request to the path used by nginx for protected media. |
||
| 98 | """ |
||
| 99 | |||
| 100 | logger.debug("Received path %s for download" % (path)) |
||
| 101 | |||
| 102 | # test for submission ownership |
||
| 103 | dirname = os.path.dirname(path) |
||
| 104 | |||
| 105 | if dirname == 'data_source': |
||
| 106 | # I got a submission. Get a submission belonging to owner or 404 |
||
| 107 | submission = get_object_or_404( |
||
| 108 | Submission, |
||
| 109 | owner=request.user, |
||
| 110 | uploaded_file=path) |
||
| 111 | |||
| 112 | logger.debug("Got submission %s" % (submission)) |
||
| 113 | |||
| 114 | # derive downloadable path. Applies to any protected file |
||
| 115 | full_path = os.path.join( |
||
| 116 | settings.PROTECTED_MEDIA_LOCATION_PREFIX, path |
||
| 117 | ) |
||
| 118 | |||
| 119 | file_name = os.path.basename(path) |
||
| 120 | |||
| 121 | # try to determine file type |
||
| 122 | file_type, encoding = mimetypes.guess_type(path) |
||
| 123 | |||
| 124 | logger.debug("Detected content type: %s" % (file_type)) |
||
| 125 | |||
| 126 | # get file size using protected storage |
||
| 127 | storage = ProtectedFileSystemStorage() |
||
| 128 | file_size = storage.size(path) |
||
| 129 | |||
| 130 | # try to set file type to response |
||
| 131 | # https://djangosnippets.org/snippets/1710/ |
||
| 132 | if file_type is None: |
||
| 133 | file_type = 'application/octet-stream' |
||
| 134 | |||
| 135 | # force django to attach file in response |
||
| 136 | response = HttpResponse(content_type=file_type) |
||
| 137 | |||
| 138 | if encoding is not None: |
||
| 139 | response['Content-Encoding'] = encoding |
||
| 140 | |||
| 141 | # https://stackoverflow.com/a/1158750/4385116 |
||
| 142 | response["X-Accel-Redirect"] = smart_str(full_path) |
||
| 143 | response['Content-Disposition'] = 'attachment; filename="{}"'.format( |
||
| 144 | file_name) |
||
| 145 | response['Content-Length'] = file_size |
||
| 146 | |||
| 147 | return response |
||
| 148 | |||
| 160 |