File: uploader.py

package info (click to toggle)
python-tuspy 1.0.3-0.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 212 kB
  • sloc: python: 884; makefile: 3
file content (192 lines) | stat: -rw-r--r-- 6,269 bytes parent folder | download
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
from typing import Optional
import time
import asyncio
from urllib.parse import urljoin

import requests
import aiohttp

from tusclient.uploader.baseuploader import BaseUploader

from tusclient.exceptions import TusUploadFailed, TusCommunicationError
from tusclient.request import TusRequest, AsyncTusRequest, catch_requests_error


def _verify_upload(request: TusRequest):
    if 200 <= request.status_code < 300:
        return True
    else:
        raise TusUploadFailed("", request.status_code, request.response_content)


class Uploader(BaseUploader):
    def upload(self, stop_at: Optional[int] = None):
        """
        Perform file upload.

        Performs continous upload of chunks of the file. The size uploaded at each cycle is
        the value of the attribute 'chunk_size'.

        :Args:
            - stop_at (Optional[int]):
                Determines at what offset value the upload should stop. If not specified this
                defaults to the file size.
        """
        self.stop_at = stop_at or self.get_file_size()

        if not self.url:
            # Ensure the POST request is performed even for empty files.
            # This ensures even empty files can be uploaded; in this case
            # only the POST request needs to be performed.
            self.set_url(self.create_url())
            self.offset = 0

        while self.offset < self.stop_at:
            self.upload_chunk()

    def upload_chunk(self):
        """
        Upload chunk of file.
        """
        self._retried = 0

        # Ensure that we have a URL, as this is behavior we allowed previously.
        # See https://github.com/tus/tus-py-client/issues/82.
        if not self.url:
            self.set_url(self.create_url())
            self.offset = 0

        self._do_request()
        self.offset = int(self.request.response_headers.get("upload-offset"))

    @catch_requests_error
    def create_url(self):
        """
        Return upload url.

        Makes request to tus server to create a new upload url for the required file upload.
        """
        resp = requests.post(
            self.client.url,
            headers=self.get_url_creation_headers(),
            verify=self.verify_tls_cert,
        )
        url = resp.headers.get("location")
        if url is None:
            msg = "Attempt to retrieve create file url with status {}".format(
                resp.status_code
            )
            raise TusCommunicationError(msg, resp.status_code, resp.content)
        return urljoin(self.client.url, url)

    def _do_request(self):
        self.request = TusRequest(self)
        try:
            self.request.perform()
            _verify_upload(self.request)
        except TusUploadFailed as error:
            self._retry_or_cry(error)

    def _retry_or_cry(self, error):
        if self.retries > self._retried:
            time.sleep(self.retry_delay)

            self._retried += 1
            try:
                self.offset = self.get_offset()
            except TusCommunicationError as err:
                self._retry_or_cry(err)
            else:
                self._do_request()
        else:
            raise error


class AsyncUploader(BaseUploader):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def upload(self, stop_at: Optional[int] = None):
        """
        Perform file upload.

        Performs continous upload of chunks of the file. The size uploaded at each cycle is
        the value of the attribute 'chunk_size'.

        :Args:
            - stop_at (Optional[int]):
                Determines at what offset value the upload should stop. If not specified this
                defaults to the file size.
        """
        self.stop_at = stop_at or self.get_file_size()

        if not self.url:
            self.set_url(await self.create_url())
            self.offset = 0

        while self.offset < self.stop_at:
            await self.upload_chunk()

    async def upload_chunk(self):
        """
        Upload chunk of file.
        """
        self._retried = 0

        # Ensure that we have a URL, as this is behavior we allowed previously.
        # See https://github.com/tus/tus-py-client/issues/82.
        if not self.url:
            self.set_url(await self.create_url())
            self.offset = 0

        await self._do_request()
        self.offset = int(self.request.response_headers.get("upload-offset"))

    async def create_url(self):
        """
        Return upload url.

        Makes request to tus server to create a new upload url for the required file upload.
        """
        try:
            async with aiohttp.ClientSession() as session:
                headers = self.get_url_creation_headers()
                ssl = None if self.verify_tls_cert else False
                async with session.post(
                    self.client.url, headers=headers, ssl=ssl
                ) as resp:
                    url = resp.headers.get("location")
                    if url is None:
                        msg = (
                            "Attempt to retrieve create file url with status {}".format(
                                resp.status
                            )
                        )
                        raise TusCommunicationError(
                            msg, resp.status, await resp.content.read()
                        )
                    return urljoin(self.client.url, url)
        except aiohttp.ClientError as error:
            raise TusCommunicationError(error)

    async def _do_request(self):
        self.request = AsyncTusRequest(self)
        try:
            await self.request.perform()
            _verify_upload(self.request)
        except TusUploadFailed as error:
            await self._retry_or_cry(error)

    async def _retry_or_cry(self, error):
        if self.retries > self._retried:
            await asyncio.sleep(self.retry_delay)

            self._retried += 1
            try:
                self.offset = self.get_offset()
            except TusCommunicationError as err:
                await self._retry_or_cry(err)
            else:
                await self._do_request()
        else:
            raise error