|
31 | 31 | Status, |
32 | 32 | SWITCHING_PROTOCOLS_101, |
33 | 33 | OK_200, |
| 34 | + MOVED_PERMANENTLY_301, |
| 35 | + FOUND_302, |
34 | 36 | TEMPORARY_REDIRECT_307, |
35 | 37 | PERMANENT_REDIRECT_308, |
36 | 38 | ) |
@@ -393,19 +395,40 @@ def __init__( |
393 | 395 | url: str, |
394 | 396 | *, |
395 | 397 | permanent: bool = False, |
| 398 | + preserve_method: bool = False, |
| 399 | + status: Union[Status, Tuple[int, str]] = None, |
396 | 400 | headers: Union[Headers, Dict[str, str]] = None, |
397 | 401 | ) -> None: |
398 | 402 | """ |
| 403 | + By default uses ``permament`` and ``preserve_method`` to determine the ``status`` code to |
| 404 | + use, but if you prefer you can specify it directly. |
| 405 | +
|
| 406 | + Note that ``301 Moved Permanently`` and ``302 Found`` can change the method to ``GET`` |
| 407 | + while ``307 Temporary Redirect`` and ``308 Permanent Redirect`` preserve the method. |
| 408 | +
|
| 409 | + More information: |
| 410 | + https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages |
| 411 | +
|
399 | 412 | :param Request request: Request that this is a response to. |
400 | 413 | :param str url: URL to redirect to. |
401 | | - :param bool permanent: Whether to use a permanent redirect (308) or a temporary one (307). |
| 414 | + :param bool permanent: Whether to use a permanent redirect or a temporary one. |
| 415 | + :param bool preserve_method: Whether to preserve the method of the request. |
| 416 | + :param Status status: Status object or tuple with code and message. |
402 | 417 | :param Headers headers: Headers to include in response. |
403 | 418 | """ |
404 | | - super().__init__( |
405 | | - request, |
406 | | - status=PERMANENT_REDIRECT_308 if permanent else TEMPORARY_REDIRECT_307, |
407 | | - headers=headers, |
408 | | - ) |
| 419 | + |
| 420 | + if status is not None and (permanent or preserve_method): |
| 421 | + raise ValueError( |
| 422 | + "Cannot specify both status and permanent/preserve_method argument" |
| 423 | + ) |
| 424 | + |
| 425 | + if status is None: |
| 426 | + if preserve_method: |
| 427 | + status = PERMANENT_REDIRECT_308 if permanent else TEMPORARY_REDIRECT_307 |
| 428 | + else: |
| 429 | + status = MOVED_PERMANENTLY_301 if permanent else FOUND_302 |
| 430 | + |
| 431 | + super().__init__(request, status=status, headers=headers) |
409 | 432 | self._headers.update({"Location": url}) |
410 | 433 |
|
411 | 434 | def _send(self) -> None: |
|
0 commit comments