or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-parsing.mdfield-types.mdframework-parsers.mdindex.mdtesting-utilities.md

core-parsing.mddocs/

0

# Core Parsing

1

2

Central parsing functionality providing the foundation for request argument parsing and validation across web frameworks. The core parsing system includes the base Parser class, parsing methods, decorators for automatic argument injection, and extensible location-based data loading.

3

4

## Capabilities

5

6

### Parser Class

7

8

Base parser class that provides high-level implementation for parsing requests. Framework-specific parsers inherit from this class and implement framework-specific data loading methods.

9

10

```python { .api }

11

class Parser:

12

"""

13

Base parser class for parsing HTTP requests.

14

15

Args:

16

location (str, optional): Default location to parse data from

17

unknown (str, optional): Default handling for unknown fields

18

error_handler (callable, optional): Custom error handler function

19

schema_class (type, optional): Default marshmallow schema class

20

"""

21

def __init__(self, location=None, *, unknown=None, error_handler=None, schema_class=None): ...

22

```

23

24

Class attributes:

25

26

```python { .api }

27

Parser.DEFAULT_LOCATION = "json"

28

Parser.DEFAULT_UNKNOWN_BY_LOCATION = {

29

"json": None,

30

"form": None,

31

"json_or_form": None,

32

"querystring": "EXCLUDE",

33

"query": "EXCLUDE",

34

"headers": "EXCLUDE",

35

"cookies": "EXCLUDE",

36

"files": "EXCLUDE"

37

}

38

Parser.DEFAULT_SCHEMA_CLASS = marshmallow.Schema

39

Parser.DEFAULT_VALIDATION_STATUS = 422

40

Parser.KNOWN_MULTI_FIELDS = [marshmallow.fields.List, marshmallow.fields.Tuple]

41

Parser.USE_ARGS_POSITIONAL = True

42

```

43

44

### Parsing Methods

45

46

Core parsing methods for extracting and validating data from HTTP requests.

47

48

```python { .api }

49

def parse(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):

50

"""

51

Main request parsing method.

52

53

Args:

54

argmap: Schema, dict of field mappings, or callable returning schema

55

req: Request object to parse (uses default if None)

56

location (str): Where to parse data from ('json', 'query', 'form', 'headers', 'cookies', 'files')

57

unknown (str): How to handle unknown fields ('EXCLUDE', 'INCLUDE', 'RAISE')

58

validate: Validation function or list of validation functions

59

error_status_code (int): HTTP status code for validation errors

60

error_headers (dict): HTTP headers for validation errors

61

62

Returns:

63

dict: Parsed and validated arguments

64

65

Raises:

66

ValidationError: When validation fails

67

"""

68

69

def async_parse(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):

70

"""

71

Async variant of parse method with same signature.

72

73

Returns:

74

Awaitable[dict]: Parsed and validated arguments

75

"""

76

```

77

78

### Argument Injection Decorators

79

80

Decorators that automatically parse request arguments and inject them into view functions.

81

82

```python { .api }

83

def use_args(self, argmap, req=None, *, location=None, unknown=None, as_kwargs=False, arg_name=None, validate=None, error_status_code=None, error_headers=None):

84

"""

85

Decorator that injects parsed arguments into a view function.

86

87

Args:

88

argmap: Schema, dict of field mappings, or callable returning schema

89

req: Request object (uses framework detection if None)

90

location (str): Where to parse data from

91

unknown (str): How to handle unknown fields

92

as_kwargs (bool): Whether to inject as keyword arguments

93

arg_name (str): Name for positional argument (mutually exclusive with as_kwargs)

94

validate: Validation function or list of validation functions

95

error_status_code (int): HTTP status code for validation errors

96

error_headers (dict): HTTP headers for validation errors

97

98

Returns:

99

callable: Decorator function

100

"""

101

102

def use_kwargs(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):

103

"""

104

Decorator that injects parsed arguments as keyword arguments.

105

106

Shortcut for use_args with as_kwargs=True.

107

108

Returns:

109

callable: Decorator function

110

"""

111

```

112

113

### Location Loading System

114

115

System for loading data from different parts of HTTP requests.

116

117

```python { .api }

118

def location_loader(self, name):

119

"""

120

Decorator that registers a function for loading a request location.

121

122

Args:

123

name (str): Name of the location to register

124

125

Returns:

126

callable: Decorator function

127

128

Example:

129

@parser.location_loader("custom")

130

def load_custom_data(request, schema):

131

return request.custom_data

132

"""

133

134

def load_json(self, req, schema):

135

"""

136

Load JSON from request body.

137

138

Args:

139

req: Request object

140

schema: Marshmallow schema for field information

141

142

Returns:

143

dict or missing: Parsed JSON data or missing sentinel

144

"""

145

146

def load_querystring(self, req, schema):

147

"""Load query string parameters from request."""

148

149

def load_form(self, req, schema):

150

"""Load form data from request."""

151

152

def load_headers(self, req, schema):

153

"""Load headers from request."""

154

155

def load_cookies(self, req, schema):

156

"""Load cookies from request."""

157

158

def load_files(self, req, schema):

159

"""Load uploaded files from request."""

160

161

def load_json_or_form(self, req, schema):

162

"""Load JSON or form data with fallback."""

163

```

164

165

### Error Handling

166

167

Error handling and customization system.

168

169

```python { .api }

170

def error_handler(self, func):

171

"""

172

Decorator that registers a custom error handling function.

173

174

Args:

175

func: Error handler function that receives (error, request, schema, error_status_code, error_headers)

176

177

Returns:

178

callable: The registered error handler

179

180

Example:

181

@parser.error_handler

182

def handle_error(error, req, schema, *, error_status_code, error_headers):

183

# Custom error handling logic

184

raise CustomError(error.messages)

185

"""

186

187

def handle_error(self, error, req, schema, *, error_status_code, error_headers):

188

"""

189

Default error handler that logs and re-raises the error.

190

191

Args:

192

error (ValidationError): The validation error

193

req: Request object

194

schema: Marshmallow schema used for parsing

195

error_status_code (int): HTTP status code for the error

196

error_headers (dict): HTTP headers for the error

197

198

Raises:

199

ValidationError: Re-raises the original error

200

"""

201

```

202

203

### Utility Methods

204

205

Additional utility methods for parser customization.

206

207

```python { .api }

208

def pre_load(self, location_data, *, schema, req, location):

209

"""

210

Hook for transforming data after location loading.

211

212

Args:

213

location_data: Raw data loaded from the request location

214

schema: Marshmallow schema being used

215

req: Request object

216

location (str): Location being parsed

217

218

Returns:

219

dict: Transformed data for schema loading

220

"""

221

222

def get_default_request(self):

223

"""

224

Hook for frameworks with thread-local request objects.

225

226

Returns:

227

Request or None: Default request object

228

"""

229

230

def get_request_from_view_args(self, view, args, kwargs):

231

"""

232

Extract request object from view function arguments.

233

234

Args:

235

view: View function being decorated

236

args: Positional arguments passed to view

237

kwargs: Keyword arguments passed to view

238

239

Returns:

240

Request or None: Extracted request object

241

"""

242

243

def get_default_arg_name(self, location, schema):

244

"""

245

Generate default argument name for use_args.

246

247

Args:

248

location (str): Location being parsed

249

schema: Schema or argument map

250

251

Returns:

252

str: Default argument name (format: "{location}_args")

253

"""

254

```

255

256

## Utility Functions

257

258

Global utility functions for JSON parsing and MIME type detection.

259

260

```python { .api }

261

def parse_json(s, *, encoding="utf-8"):

262

"""

263

Parse JSON string with proper encoding handling.

264

265

Args:

266

s (str or bytes): JSON string to parse

267

encoding (str): Character encoding for bytes input

268

269

Returns:

270

Any: Parsed JSON data

271

272

Raises:

273

json.JSONDecodeError: When JSON parsing fails

274

"""

275

276

def get_mimetype(content_type):

277

"""

278

Extract MIME type from Content-Type header.

279

280

Args:

281

content_type (str): Full content-type header value

282

283

Returns:

284

str: MIME type portion

285

"""

286

287

def is_json(mimetype):

288

"""

289

Check if MIME type indicates JSON content.

290

291

Args:

292

mimetype (str): MIME type to check

293

294

Returns:

295

bool: True if MIME type is JSON-related

296

"""

297

```

298

299

## Constants

300

301

```python { .api }

302

DEFAULT_VALIDATION_STATUS = 422

303

```

304

305

## Types

306

307

```python { .api }

308

Request = TypeVar("Request")

309

310

# Generic type var with no particular meaning

311

T = TypeVar("T")

312

313

# Type var for callables, to make type-preserving decorators

314

C = TypeVar("C", bound=Callable)

315

316

# Type var for multidict proxy classes

317

MultiDictProxyT = TypeVar("MultiDictProxyT", bound=MultiDictProxy)

318

319

# Type var for a callable which is an error handler

320

ErrorHandlerT = TypeVar("ErrorHandlerT", bound=ErrorHandler)

321

322

ArgMapCallable = Callable[[Request], marshmallow.Schema]

323

324

ArgMap = Union[

325

marshmallow.Schema,

326

Type[marshmallow.Schema],

327

Mapping[str, marshmallow.fields.Field],

328

ArgMapCallable

329

]

330

331

ValidateArg = Union[None, Callable, Iterable[Callable]]

332

333

CallableList = list[Callable]

334

335

ErrorHandler = Callable[..., NoReturn]

336

337

AsyncErrorHandler = Callable[..., Awaitable[NoReturn]]

338

```