or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-management.mdexception-handling.mdindex.mdrequest-handling.mdstorage-resumability.mdupload-operations.md

request-handling.mddocs/

0

# Request Handling

1

2

HTTP request abstraction layer for tus protocol operations. TusPy provides both synchronous and asynchronous request handling with automatic error conversion and retry mechanisms.

3

4

## Capabilities

5

6

### Base Request Class

7

8

Common functionality for HTTP request handling across sync and async implementations.

9

10

```python { .api }

11

class BaseTusRequest:

12

"""

13

Http Request Abstraction.

14

15

Sets up tus custom http request on instantiation.

16

17

Attributes:

18

response_headers (dict): Response headers from last request

19

status_code (int): HTTP status code from last request

20

response_content (bytes): Response content from last request

21

verify_tls_cert (bool): Whether to verify TLS certificates

22

file (IO): The file stream being uploaded

23

client_cert (Union[str, Tuple[str, str]]): Client certificate configuration

24

"""

25

26

def __init__(self, uploader):

27

"""

28

Initialize BaseTusRequest with uploader configuration.

29

30

Parameters:

31

- uploader: Uploader instance providing configuration and file details

32

"""

33

34

def add_checksum(self, chunk: bytes):

35

"""

36

Add upload-checksum header for the provided chunk if enabled.

37

38

Calculates checksum using configured algorithm and adds header

39

in format required by tus protocol.

40

41

Parameters:

42

- chunk (bytes): File chunk data to calculate checksum for

43

"""

44

```

45

46

### Synchronous Request Handler

47

48

HTTP request handler for synchronous uploads using the requests library.

49

50

```python { .api }

51

class TusRequest(BaseTusRequest):

52

"""Class to handle synchronous Tus upload requests using requests library."""

53

54

def perform(self):

55

"""

56

Perform actual HTTP PATCH request.

57

58

Reads chunk data from file, calculates checksum if enabled,

59

and sends PATCH request to upload URL with proper headers.

60

61

Raises:

62

TusUploadFailed: If request fails or returns error status

63

"""

64

```

65

66

### Asynchronous Request Handler

67

68

HTTP request handler for asynchronous uploads using the aiohttp library.

69

70

```python { .api }

71

class AsyncTusRequest(BaseTusRequest):

72

"""Class to handle async Tus upload requests using aiohttp library."""

73

74

def __init__(self, *args, io_loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs):

75

"""

76

Initialize AsyncTusRequest with optional event loop.

77

78

Parameters:

79

- io_loop (Optional[asyncio.AbstractEventLoop]): Event loop for async operations

80

- *args, **kwargs: Passed to BaseTusRequest constructor

81

"""

82

83

async def perform(self):

84

"""

85

Perform actual HTTP PATCH request asynchronously.

86

87

Reads chunk data from file, calculates checksum if enabled,

88

and sends async PATCH request to upload URL with proper headers

89

and SSL configuration.

90

91

Raises:

92

TusUploadFailed: If request fails or returns error status

93

"""

94

```

95

96

### Error Handling Decorator

97

98

Decorator function for converting requests library exceptions to tus-specific exceptions.

99

100

```python { .api }

101

def catch_requests_error(func):

102

"""

103

Decorator to catch requests exceptions and convert to TusCommunicationError.

104

105

Wraps functions that make HTTP requests using the requests library

106

and converts any requests.exceptions.RequestException to TusCommunicationError

107

for consistent error handling.

108

109

Parameters:

110

- func: Function to wrap that may raise requests exceptions

111

112

Returns:

113

Function: Wrapped function with error conversion

114

"""

115

```

116

117

## Usage Examples

118

119

### Direct Request Usage (Advanced)

120

121

```python

122

from tusclient.request import TusRequest, AsyncTusRequest

123

from tusclient.uploader import Uploader, AsyncUploader

124

from tusclient import client

125

126

# Create uploader (request is normally created internally)

127

my_client = client.TusClient('http://tusd.tusdemo.net/files/')

128

uploader = my_client.uploader('/path/to/file.ext', chunk_size=1024*1024)

129

130

# Create and perform synchronous request manually

131

# (This is normally done automatically by uploader.upload_chunk())

132

request = TusRequest(uploader)

133

try:

134

request.perform()

135

print(f"Upload successful, offset: {request.response_headers.get('upload-offset')}")

136

print(f"Status code: {request.status_code}")

137

except Exception as e:

138

print(f"Request failed: {e}")

139

```

140

141

### Async Request Usage (Advanced)

142

143

```python

144

import asyncio

145

from tusclient.request import AsyncTusRequest

146

from tusclient import client

147

148

async def manual_async_request():

149

my_client = client.TusClient('http://tusd.tusdemo.net/files/')

150

uploader = my_client.async_uploader('/path/to/file.ext', chunk_size=1024*1024)

151

152

# Create and perform async request manually

153

# (This is normally done automatically by uploader.upload_chunk())

154

request = AsyncTusRequest(uploader)

155

try:

156

await request.perform()

157

print(f"Async upload successful, offset: {request.response_headers.get('upload-offset')}")

158

print(f"Status code: {request.status_code}")

159

except Exception as e:

160

print(f"Async request failed: {e}")

161

162

# Run async request

163

asyncio.run(manual_async_request())

164

```

165

166

### Custom Request Processing

167

168

```python

169

from tusclient.request import TusRequest, catch_requests_error

170

from tusclient import client

171

import requests

172

173

# Example of using catch_requests_error decorator

174

@catch_requests_error

175

def custom_tus_operation(url, headers):

176

"""Custom function that makes requests and converts exceptions."""

177

response = requests.head(url, headers=headers)

178

return response.headers.get('upload-offset')

179

180

try:

181

my_client = client.TusClient('http://tusd.tusdemo.net/files/')

182

headers = {'Tus-Resumable': '1.0.0'}

183

offset = custom_tus_operation('http://tusd.tusdemo.net/files/some-id', headers)

184

print(f"Current offset: {offset}")

185

except Exception as e:

186

print(f"Custom operation failed: {e}")

187

```

188

189

### Checksum Validation

190

191

```python

192

from tusclient.request import TusRequest

193

from tusclient import client

194

195

# Example showing checksum handling (normally done automatically)

196

my_client = client.TusClient('http://tusd.tusdemo.net/files/')

197

uploader = my_client.uploader(

198

'/path/to/file.ext',

199

chunk_size=1024*1024,

200

upload_checksum=True # Enable checksum validation

201

)

202

203

# Request will automatically include upload-checksum header

204

request = TusRequest(uploader)

205

chunk_data = b"example chunk data"

206

request.add_checksum(chunk_data)

207

208

# Check if checksum header was added

209

print("Request headers:", request._request_headers)

210

# Will show: upload-checksum: sha1 <base64-encoded-hash>

211

```

212

213

### Request State Inspection

214

215

```python

216

from tusclient.request import TusRequest

217

from tusclient import client

218

219

my_client = client.TusClient('http://tusd.tusdemo.net/files/')

220

uploader = my_client.uploader('/path/to/file.ext', chunk_size=1024)

221

222

# Perform upload chunk to populate request

223

uploader.upload_chunk()

224

225

# Inspect request state (available after upload_chunk)

226

request = uploader.request

227

print(f"Last response status: {request.status_code}")

228

print(f"Response headers: {request.response_headers}")

229

print(f"Response content length: {len(request.response_content)}")

230

print(f"Upload offset: {request.response_headers.get('upload-offset')}")

231

```