1# Copyright 2013 by Rackspace Hosting, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""HTTP error classes and other Falcon-specific errors.
16
17This module implements a collection of `falcon.HTTPError`
18specializations that can be raised to generate a 4xx or 5xx HTTP
19response. All classes are available directly from the `falcon`
20package namespace::
21
22    import falcon
23
24    class MessageResource(object):
25        def on_get(self, req, resp):
26
27            # ...
28
29            raise falcon.HTTPBadRequest(
30                'TTL Out of Range',
31                'The message's TTL must be between 60 and 300 seconds, inclusive.'
32            )
33
34            # ...
35
36"""
37
38from datetime import datetime
39
40from falcon import util
41from falcon.http_error import HTTPError, NoRepresentation, \
42    OptionalRepresentation
43import falcon.status_codes as status
44
45
46class HeaderNotSupported(ValueError):
47    """The specified header is not supported by this method."""
48
49
50class HTTPBadRequest(HTTPError):
51    """400 Bad Request.
52
53    The server cannot or will not process the request due to something
54    that is perceived to be a client error (e.g., malformed request
55    syntax, invalid request message framing, or deceptive request
56    routing).
57
58    (See also: RFC 7231, Section 6.5.1)
59
60    Keyword Args:
61        title (str): Error title (default '400 Bad Request').
62        description (str): Human-friendly description of the error, along with
63            a helpful suggestion or two.
64        headers (dict or list): A ``dict`` of header names and values
65            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
66            *value* must be of type ``str`` or ``StringType``, and only
67            character values 0x00 through 0xFF may be used on platforms that
68            use wide characters.
69
70            Note:
71                The Content-Type header, if present, will be overridden. If
72                you wish to return custom error messages, you can create
73                your own HTTP error class, and install an error handler
74                to convert it into an appropriate HTTP response for the
75                client
76
77            Note:
78                Falcon can process a list of ``tuple`` slightly faster
79                than a ``dict``.
80        href (str): A URL someone can visit to find out more information
81            (default ``None``). Unicode characters are percent-encoded.
82        href_text (str): If href is given, use this as the friendly
83            title/description for the link (default 'API documentation
84            for this error').
85        code (int): An internal code that customers can reference in their
86            support request or to help them when searching for knowledge
87            base articles related to this error (default ``None``).
88    """
89
90    def __init__(self, title=None, description=None, headers=None, **kwargs):
91        super(HTTPBadRequest, self).__init__(status.HTTP_400, title,
92                                             description, headers, **kwargs)
93
94
95class HTTPUnauthorized(HTTPError):
96    """401 Unauthorized.
97
98    The request has not been applied because it lacks valid
99    authentication credentials for the target resource.
100
101    The server generating a 401 response MUST send a WWW-Authenticate
102    header field containing at least one challenge applicable to the
103    target resource.
104
105    If the request included authentication credentials, then the 401
106    response indicates that authorization has been refused for those
107    credentials. The user agent MAY repeat the request with a new or
108    replaced Authorization header field. If the 401 response contains
109    the same challenge as the prior response, and the user agent has
110    already attempted authentication at least once, then the user agent
111    SHOULD present the enclosed representation to the user, since it
112    usually contains relevant diagnostic information.
113
114    (See also: RFC 7235, Section 3.1)
115
116    Keyword Args:
117        title (str): Error title (default '401 Unauthorized').
118        description (str): Human-friendly description of the error, along with
119            a helpful suggestion or two.
120        challenges (iterable of str): One or more authentication
121            challenges to use as the value of the WWW-Authenticate header in
122            the response.
123
124            (See also: RFC 7235, Section 2.1)
125
126        headers (dict or list): A ``dict`` of header names and values
127            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
128            *value* must be of type ``str`` or ``StringType``, and only
129            character values 0x00 through 0xFF may be used on platforms that
130            use wide characters.
131
132            Note:
133                The Content-Type header, if present, will be overridden. If
134                you wish to return custom error messages, you can create
135                your own HTTP error class, and install an error handler
136                to convert it into an appropriate HTTP response for the
137                client
138
139            Note:
140                Falcon can process a list of ``tuple`` slightly faster
141                than a ``dict``.
142        href (str): A URL someone can visit to find out more information
143            (default ``None``). Unicode characters are percent-encoded.
144        href_text (str): If href is given, use this as the friendly
145            title/description for the link (default 'API documentation
146            for this error').
147        code (int): An internal code that customers can reference in their
148            support request or to help them when searching for knowledge
149            base articles related to this error (default ``None``).
150
151    """
152
153    def __init__(self, title=None, description=None, challenges=None, headers=None, **kwargs):
154        if headers is None:
155            headers = {}
156
157        if challenges:
158            headers['WWW-Authenticate'] = ', '.join(challenges)
159
160        super(HTTPUnauthorized, self).__init__(status.HTTP_401, title,
161                                               description, headers, **kwargs)
162
163
164class HTTPForbidden(HTTPError):
165    """403 Forbidden.
166
167    The server understood the request but refuses to authorize it.
168
169    A server that wishes to make public why the request has been
170    forbidden can describe that reason in the response payload (if any).
171
172    If authentication credentials were provided in the request, the
173    server considers them insufficient to grant access. The client
174    SHOULD NOT automatically repeat the request with the same
175    credentials. The client MAY repeat the request with new or different
176    credentials. However, a request might be forbidden for reasons
177    unrelated to the credentials.
178
179    An origin server that wishes to "hide" the current existence of a
180    forbidden target resource MAY instead respond with a status code of
181    404 Not Found.
182
183    (See also: RFC 7231, Section 6.5.4)
184
185    Keyword Args:
186        title (str): Error title (default '403 Forbidden').
187        description (str): Human-friendly description of the error, along with
188            a helpful suggestion or two.
189        headers (dict or list): A ``dict`` of header names and values
190            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
191            *value* must be of type ``str`` or ``StringType``, and only
192            character values 0x00 through 0xFF may be used on platforms that
193            use wide characters.
194
195            Note:
196                The Content-Type header, if present, will be overridden. If
197                you wish to return custom error messages, you can create
198                your own HTTP error class, and install an error handler
199                to convert it into an appropriate HTTP response for the
200                client
201
202            Note:
203                Falcon can process a list of ``tuple`` slightly faster
204                than a ``dict``.
205        href (str): A URL someone can visit to find out more information
206            (default ``None``). Unicode characters are percent-encoded.
207        href_text (str): If href is given, use this as the friendly
208            title/description for the link (default 'API documentation
209            for this error').
210        code (int): An internal code that customers can reference in their
211            support request or to help them when searching for knowledge
212            base articles related to this error (default ``None``).
213    """
214
215    def __init__(self, title=None, description=None, headers=None, **kwargs):
216        super(HTTPForbidden, self).__init__(status.HTTP_403, title,
217                                            description, headers, **kwargs)
218
219
220class HTTPNotFound(OptionalRepresentation, HTTPError):
221    """404 Not Found.
222
223    The origin server did not find a current representation for the
224    target resource or is not willing to disclose that one exists.
225
226    A 404 status code does not indicate whether this lack of
227    representation is temporary or permanent; the 410 Gone status code
228    is preferred over 404 if the origin server knows, presumably through
229    some configurable means, that the condition is likely to be
230    permanent.
231
232    A 404 response is cacheable by default; i.e., unless otherwise
233    indicated by the method definition or explicit cache controls.
234
235    (See also: RFC 7231, Section 6.5.3)
236
237    Keyword Args:
238        title (str): Human-friendly error title. If not provided, and
239            `description` is also not provided, no body will be included
240            in the response.
241        description (str): Human-friendly description of the error, along with
242            a helpful suggestion or two (default ``None``).
243        headers (dict or list): A ``dict`` of header names and values
244            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
245            *value* must be of type ``str`` or ``StringType``, and only
246            character values 0x00 through 0xFF may be used on platforms that
247            use wide characters.
248
249            Note:
250                The Content-Type header, if present, will be overridden. If
251                you wish to return custom error messages, you can create
252                your own HTTP error class, and install an error handler
253                to convert it into an appropriate HTTP response for the
254                client
255
256            Note:
257                Falcon can process a list of ``tuple`` slightly faster
258                than a ``dict``.
259        href (str): A URL someone can visit to find out more information
260            (default ``None``). Unicode characters are percent-encoded.
261        href_text (str): If href is given, use this as the friendly
262            title/description for the link (default 'API documentation
263            for this error').
264        code (int): An internal code that customers can reference in their
265            support request or to help them when searching for knowledge
266            base articles related to this error (default ``None``).
267    """
268
269    def __init__(self, headers=None, **kwargs):
270        super(HTTPNotFound, self).__init__(status.HTTP_404, headers=headers, **kwargs)
271
272
273class HTTPMethodNotAllowed(OptionalRepresentation, HTTPError):
274    """405 Method Not Allowed.
275
276    The method received in the request-line is known by the origin
277    server but not supported by the target resource.
278
279    The origin server MUST generate an Allow header field in a 405
280    response containing a list of the target resource's currently
281    supported methods.
282
283    A 405 response is cacheable by default; i.e., unless otherwise
284    indicated by the method definition or explicit cache controls.
285
286    (See also: RFC 7231, Section 6.5.5)
287
288    Args:
289        allowed_methods (list of str): Allowed HTTP methods for this
290            resource (e.g., ``['GET', 'POST', 'HEAD']``).
291
292    Keyword Args:
293        title (str): Human-friendly error title. If not provided, and
294            `description` is also not provided, no body will be included
295            in the response.
296        description (str): Human-friendly description of the error, along with
297            a helpful suggestion or two (default ``None``).
298        headers (dict or list): A ``dict`` of header names and values
299            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
300            *value* must be of type ``str`` or ``StringType``, and only
301            character values 0x00 through 0xFF may be used on platforms that
302            use wide characters.
303
304            Note:
305                The Content-Type header, if present, will be overridden. If
306                you wish to return custom error messages, you can create
307                your own HTTP error class, and install an error handler
308                to convert it into an appropriate HTTP response for the
309                client
310
311            Note:
312                Falcon can process a list of ``tuple`` slightly faster
313                than a ``dict``.
314        href (str): A URL someone can visit to find out more information
315            (default ``None``). Unicode characters are percent-encoded.
316        href_text (str): If href is given, use this as the friendly
317            title/description for the link (default 'API documentation
318            for this error').
319        code (int): An internal code that customers can reference in their
320            support request or to help them when searching for knowledge
321            base articles related to this error (default ``None``).
322    """
323
324    def __init__(self, allowed_methods, headers=None, **kwargs):
325        new_headers = {'Allow': ', '.join(allowed_methods)}
326        super(HTTPMethodNotAllowed, self).__init__(status.HTTP_405,
327                                                   headers=headers,
328                                                   **kwargs)
329        if not self.headers:
330            self.headers = {}
331
332        self.headers.update(new_headers)
333
334
335class HTTPNotAcceptable(HTTPError):
336    """406 Not Acceptable.
337
338    The target resource does not have a current representation that
339    would be acceptable to the user agent, according to the proactive
340    negotiation header fields received in the request, and the server
341    is unwilling to supply a default representation.
342
343    The server SHOULD generate a payload containing a list of available
344    representation characteristics and corresponding resource
345    identifiers from which the user or user agent can choose the one
346    most appropriate. A user agent MAY automatically select the most
347    appropriate choice from that list. However, this specification does
348    not define any standard for such automatic selection, as described
349    in RFC 7231, Section 6.4.1
350
351    (See also: RFC 7231, Section 6.5.6)
352
353    Keyword Args:
354        description (str): Human-friendly description of the error, along with
355            a helpful suggestion or two.
356        headers (dict or list): A ``dict`` of header names and values
357            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
358            *value* must be of type ``str`` or ``StringType``, and only
359            character values 0x00 through 0xFF may be used on platforms that
360            use wide characters.
361
362            Note:
363                The Content-Type header, if present, will be overridden. If
364                you wish to return custom error messages, you can create
365                your own HTTP error class, and install an error handler
366                to convert it into an appropriate HTTP response for the
367                client
368
369            Note:
370                Falcon can process a list of ``tuple`` slightly faster
371                than a ``dict``.
372        href (str): A URL someone can visit to find out more information
373            (default ``None``). Unicode characters are percent-encoded.
374        href_text (str): If href is given, use this as the friendly
375            title/description for the link (default 'API documentation
376            for this error').
377        code (int): An internal code that customers can reference in their
378            support request or to help them when searching for knowledge
379            base articles related to this error (default ``None``).
380    """
381
382    def __init__(self, description=None, headers=None, **kwargs):
383        super(HTTPNotAcceptable, self).__init__(status.HTTP_406,
384                                                'Media type not acceptable',
385                                                description, headers,
386                                                **kwargs)
387
388
389class HTTPConflict(HTTPError):
390    """409 Conflict.
391
392    The request could not be completed due to a conflict with the
393    current state of the target resource. This code is used in
394    situations where the user might be able to resolve the conflict and
395    resubmit the request.
396
397    The server SHOULD generate a payload that includes enough
398    information for a user to recognize the source of the conflict.
399
400    Conflicts are most likely to occur in response to a PUT request. For
401    example, if versioning were being used and the representation being
402    PUT included changes to a resource that conflict with those made by
403    an earlier (third-party) request, the origin server might use a 409
404    response to indicate that it can't complete the request. In this
405    case, the response representation would likely contain information
406    useful for merging the differences based on the revision history.
407
408    (See also: RFC 7231, Section 6.5.8)
409
410    Keyword Args:
411        title (str): Error title (default '409 Conflict').
412        description (str): Human-friendly description of the error, along with
413            a helpful suggestion or two.
414        headers (dict or list): A ``dict`` of header names and values
415            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
416            *value* must be of type ``str`` or ``StringType``, and only
417            character values 0x00 through 0xFF may be used on platforms that
418            use wide characters.
419
420            Note:
421                The Content-Type header, if present, will be overridden. If
422                you wish to return custom error messages, you can create
423                your own HTTP error class, and install an error handler
424                to convert it into an appropriate HTTP response for the
425                client
426
427            Note:
428                Falcon can process a list of ``tuple`` slightly faster
429                than a ``dict``.
430        href (str): A URL someone can visit to find out more information
431            (default ``None``). Unicode characters are percent-encoded.
432        href_text (str): If href is given, use this as the friendly
433            title/description for the link (default 'API documentation
434            for this error').
435        code (int): An internal code that customers can reference in their
436            support request or to help them when searching for knowledge
437            base articles related to this error (default ``None``).
438    """
439
440    def __init__(self, title=None, description=None, headers=None, **kwargs):
441        super(HTTPConflict, self).__init__(status.HTTP_409, title,
442                                           description, headers,
443                                           **kwargs)
444
445
446class HTTPGone(OptionalRepresentation, HTTPError):
447    """410 Gone.
448
449    The target resource is no longer available at the origin server and
450    this condition is likely to be permanent.
451
452    If the origin server does not know, or has no facility to determine,
453    whether or not the condition is permanent, the status code 404 Not
454    Found ought to be used instead.
455
456    The 410 response is primarily intended to assist the task of web
457    maintenance by notifying the recipient that the resource is
458    intentionally unavailable and that the server owners desire that
459    remote links to that resource be removed. Such an event is common
460    for limited-time, promotional services and for resources belonging
461    to individuals no longer associated with the origin server's site.
462    It is not necessary to mark all permanently unavailable resources as
463    "gone" or to keep the mark for any length of time -- that is left to
464    the discretion of the server owner.
465
466    A 410 response is cacheable by default; i.e., unless otherwise
467    indicated by the method definition or explicit cache controls.
468
469    (See also: RFC 7231, Section 6.5.9)
470
471    Keyword Args:
472        title (str): Human-friendly error title. If not provided, and
473            `description` is also not provided, no body will be included
474            in the response.
475        description (str): Human-friendly description of the error, along with
476            a helpful suggestion or two (default ``None``).
477        headers (dict or list): A ``dict`` of header names and values
478            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
479            *value* must be of type ``str`` or ``StringType``, and only
480            character values 0x00 through 0xFF may be used on platforms that
481            use wide characters.
482
483            Note:
484                The Content-Type header, if present, will be overridden. If
485                you wish to return custom error messages, you can create
486                your own HTTP error class, and install an error handler
487                to convert it into an appropriate HTTP response for the
488                client
489
490            Note:
491                Falcon can process a list of ``tuple`` slightly faster
492                than a ``dict``.
493        href (str): A URL someone can visit to find out more information
494            (default ``None``). Unicode characters are percent-encoded.
495        href_text (str): If href is given, use this as the friendly
496            title/description for the link (default 'API documentation
497            for this error').
498        code (int): An internal code that customers can reference in their
499            support request or to help them when searching for knowledge
500            base articles related to this error (default ``None``).
501    """
502
503    def __init__(self, headers=None, **kwargs):
504        super(HTTPGone, self).__init__(status.HTTP_410, headers=headers, **kwargs)
505
506
507class HTTPLengthRequired(HTTPError):
508    """411 Length Required.
509
510    The server refuses to accept the request without a defined Content-
511    Length.
512
513    The client MAY repeat the request if it adds a valid Content-Length
514    header field containing the length of the message body in the
515    request message.
516
517    (See also: RFC 7231, Section 6.5.10)
518
519    Keyword Args:
520        title (str): Error title (default '411 Length Required').
521        description (str): Human-friendly description of the error, along with
522            a helpful suggestion or two.
523        headers (dict or list): A ``dict`` of header names and values
524            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
525            *value* must be of type ``str`` or ``StringType``, and only
526            character values 0x00 through 0xFF may be used on platforms that
527            use wide characters.
528
529            Note:
530                The Content-Type header, if present, will be overridden. If
531                you wish to return custom error messages, you can create
532                your own HTTP error class, and install an error handler
533                to convert it into an appropriate HTTP response for the
534                client
535
536            Note:
537                Falcon can process a list of ``tuple`` slightly faster
538                than a ``dict``.
539        href (str): A URL someone can visit to find out more information
540            (default ``None``). Unicode characters are percent-encoded.
541        href_text (str): If href is given, use this as the friendly
542            title/description for the link (default 'API documentation
543            for this error').
544        code (int): An internal code that customers can reference in their
545            support request or to help them when searching for knowledge
546            base articles related to this error (default ``None``).
547    """
548    def __init__(self, title=None, description=None, headers=None, **kwargs):
549        super(HTTPLengthRequired, self).__init__(status.HTTP_411,
550                                                 title, description,
551                                                 headers, **kwargs)
552
553
554class HTTPPreconditionFailed(HTTPError):
555    """412 Precondition Failed.
556
557    One or more conditions given in the request header fields evaluated
558    to false when tested on the server.
559
560    This response code allows the client to place preconditions on the
561    current resource state (its current representations and metadata)
562    and, thus, prevent the request method from being applied if the
563    target resource is in an unexpected state.
564
565    (See also: RFC 7232, Section 4.2)
566
567    Keyword Args:
568        title (str): Error title (default '412 Precondition Failed').
569        description (str): Human-friendly description of the error, along with
570            a helpful suggestion or two.
571        headers (dict or list): A ``dict`` of header names and values
572            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
573            *value* must be of type ``str`` or ``StringType``, and only
574            character values 0x00 through 0xFF may be used on platforms that
575            use wide characters.
576
577            Note:
578                The Content-Type header, if present, will be overridden. If
579                you wish to return custom error messages, you can create
580                your own HTTP error class, and install an error handler
581                to convert it into an appropriate HTTP response for the
582                client
583
584            Note:
585                Falcon can process a list of ``tuple`` slightly faster
586                than a ``dict``.
587        href (str): A URL someone can visit to find out more information
588            (default ``None``). Unicode characters are percent-encoded.
589        href_text (str): If href is given, use this as the friendly
590            title/description for the link (default 'API documentation
591            for this error').
592        code (int): An internal code that customers can reference in their
593            support request or to help them when searching for knowledge
594            base articles related to this error (default ``None``).
595    """
596
597    def __init__(self, title=None, description=None, headers=None, **kwargs):
598        super(HTTPPreconditionFailed, self).__init__(status.HTTP_412, title,
599                                                     description, headers,
600                                                     **kwargs)
601
602
603class HTTPPayloadTooLarge(HTTPError):
604    """413 Payload Too Large.
605
606    The server is refusing to process a request because the request
607    payload is larger than the server is willing or able to process.
608
609    The server MAY close the connection to prevent the client from
610    continuing the request.
611
612    If the condition is temporary, the server SHOULD generate a Retry-
613    After header field to indicate that it is temporary and after what
614    time the client MAY try again.
615
616    (See also: RFC 7231, Section 6.5.11)
617
618    Keyword Args:
619        title (str): Error title (default '413 Payload Too Large').
620
621        description (str): Human-friendly description of the error, along with
622            a helpful suggestion or two.
623
624        retry_after (datetime or int): Value for the Retry-After
625            header. If a ``datetime`` object, will serialize as an HTTP date.
626            Otherwise, a non-negative ``int`` is expected, representing the
627            number of seconds to wait.
628        headers (dict or list): A ``dict`` of header names and values
629            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
630            *value* must be of type ``str`` or ``StringType``, and only
631            character values 0x00 through 0xFF may be used on platforms that
632            use wide characters.
633
634            Note:
635                The Content-Type header, if present, will be overridden. If
636                you wish to return custom error messages, you can create
637                your own HTTP error class, and install an error handler
638                to convert it into an appropriate HTTP response for the
639                client
640
641            Note:
642                Falcon can process a list of ``tuple`` slightly faster
643                than a ``dict``.
644        href (str): A URL someone can visit to find out more information
645            (default ``None``). Unicode characters are percent-encoded.
646        href_text (str): If href is given, use this as the friendly
647            title/description for the link (default 'API documentation
648            for this error').
649        code (int): An internal code that customers can reference in their
650            support request or to help them when searching for knowledge
651            base articles related to this error (default ``None``).
652    """
653
654    def __init__(self, title=None, description=None, retry_after=None, headers=None, **kwargs):
655        if headers is None:
656            headers = {}
657
658        if isinstance(retry_after, datetime):
659            headers['Retry-After'] = util.dt_to_http(retry_after)
660        elif retry_after is not None:
661            headers['Retry-After'] = str(retry_after)
662
663        super(HTTPPayloadTooLarge, self).__init__(status.HTTP_413,
664                                                  title,
665                                                  description,
666                                                  headers,
667                                                  **kwargs)
668
669
670class HTTPUriTooLong(HTTPError):
671    """414 URI Too Long.
672
673    The server is refusing to service the request because the request-
674    target is longer than the server is willing to interpret.
675
676    This rare condition is only likely to occur when a client has
677    improperly converted a POST request to a GET request with long query
678    information, when the client has descended into a "black hole" of
679    redirection (e.g., a redirected URI prefix that points to a suffix
680    of itself) or when the server is under attack by a client attempting
681    to exploit potential security holes.
682
683    A 414 response is cacheable by default; i.e., unless otherwise
684    indicated by the method definition or explicit cache controls.
685
686    (See also: RFC 7231, Section 6.5.12)
687
688    Keyword Args:
689        title (str): Error title (default '414 URI Too Long').
690        description (str): Human-friendly description of the error, along with
691            a helpful suggestion or two (default ``None``).
692        headers (dict or list): A ``dict`` of header names and values
693            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
694            *value* must be of type ``str`` or ``StringType``, and only
695            character values 0x00 through 0xFF may be used on platforms that
696            use wide characters.
697
698            Note:
699                The Content-Type header, if present, will be overridden. If
700                you wish to return custom error messages, you can create
701                your own HTTP error class, and install an error handler
702                to convert it into an appropriate HTTP response for the
703                client
704
705            Note:
706                Falcon can process a list of ``tuple`` slightly faster
707                than a ``dict``.
708        href (str): A URL someone can visit to find out more information
709            (default ``None``). Unicode characters are percent-encoded.
710        href_text (str): If href is given, use this as the friendly
711            title/description for the link (default 'API documentation
712            for this error').
713        code (int): An internal code that customers can reference in their
714            support request or to help them when searching for knowledge
715            base articles related to this error (default ``None``).
716    """
717
718    def __init__(self, title=None, description=None, headers=None, **kwargs):
719        super(HTTPUriTooLong, self).__init__(status.HTTP_414, title,
720                                             description, headers,
721                                             **kwargs)
722
723
724class HTTPUnsupportedMediaType(HTTPError):
725    """415 Unsupported Media Type.
726
727    The origin server is refusing to service the request because the
728    payload is in a format not supported by this method on the target
729    resource.
730
731    The format problem might be due to the request's indicated Content-
732    Type or Content-Encoding, or as a result of inspecting the data
733    directly.
734
735    (See also: RFC 7231, Section 6.5.13)
736
737    Keyword Args:
738        description (str): Human-friendly description of the error, along with
739            a helpful suggestion or two.
740        headers (dict or list): A ``dict`` of header names and values
741            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
742            *value* must be of type ``str`` or ``StringType``, and only
743            character values 0x00 through 0xFF may be used on platforms that
744            use wide characters.
745
746            Note:
747                The Content-Type header, if present, will be overridden. If
748                you wish to return custom error messages, you can create
749                your own HTTP error class, and install an error handler
750                to convert it into an appropriate HTTP response for the
751                client
752
753            Note:
754                Falcon can process a list of ``tuple`` slightly faster
755                than a ``dict``.
756        href (str): A URL someone can visit to find out more information
757            (default ``None``). Unicode characters are percent-encoded.
758        href_text (str): If href is given, use this as the friendly
759            title/description for the link (default 'API documentation
760            for this error').
761        code (int): An internal code that customers can reference in their
762            support request or to help them when searching for knowledge
763            base articles related to this error (default ``None``).
764    """
765
766    def __init__(self, description=None, headers=None, **kwargs):
767        super(HTTPUnsupportedMediaType, self).__init__(
768            status.HTTP_415, 'Unsupported media type',
769            description, headers, **kwargs)
770
771
772class HTTPRangeNotSatisfiable(NoRepresentation, HTTPError):
773    """416 Range Not Satisfiable.
774
775    None of the ranges in the request's Range header field overlap the
776    current extent of the selected resource or that the set of ranges
777    requested has been rejected due to invalid ranges or an excessive
778    request of small or overlapping ranges.
779
780    For byte ranges, failing to overlap the current extent means that
781    the first-byte-pos of all of the byte-range-spec values were greater
782    than the current length of the selected representation. When this
783    status code is generated in response to a byte-range request, the
784    sender SHOULD generate a Content-Range header field specifying the
785    current length of the selected representation.
786
787    (See also: RFC 7233, Section 4.4)
788
789    Args:
790        resource_length: The maximum value for the last-byte-pos of a range
791            request. Used to set the Content-Range header.
792    """
793
794    def __init__(self, resource_length, headers=None):
795        if headers is None:
796            headers = {}
797        headers.setdefault('Content-Range', 'bytes */' + str(resource_length))
798
799        super(HTTPRangeNotSatisfiable, self).__init__(status.HTTP_416,
800                                                      headers=headers)
801
802
803class HTTPUnprocessableEntity(HTTPError):
804    """422 Unprocessable Entity.
805
806    The server understands the content type of the request entity (hence
807    a 415 Unsupported Media Type status code is inappropriate), and the
808    syntax of the request entity is correct (thus a 400 Bad Request
809    status code is inappropriate) but was unable to process the
810    contained instructions.
811
812    For example, this error condition may occur if an XML request body
813    contains well-formed (i.e., syntactically correct), but semantically
814    erroneous, XML instructions.
815
816    (See also: RFC 4918, Section 11.2)
817
818    Keyword Args:
819        title (str): Error title (default '422 Unprocessable Entity').
820        description (str): Human-friendly description of the error, along with
821            a helpful suggestion or two.
822        headers (dict or list): A ``dict`` of header names and values
823            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
824            *value* must be of type ``str`` or ``StringType``, and only
825            character values 0x00 through 0xFF may be used on platforms that
826            use wide characters.
827
828            Note:
829                The Content-Type header, if present, will be overridden. If
830                you wish to return custom error messages, you can create
831                your own HTTP error class, and install an error handler
832                to convert it into an appropriate HTTP response for the
833                client
834
835            Note:
836                Falcon can process a list of ``tuple`` slightly faster
837                than a ``dict``.
838        href (str): A URL someone can visit to find out more information
839            (default ``None``). Unicode characters are percent-encoded.
840        href_text (str): If href is given, use this as the friendly
841            title/description for the link (default 'API documentation
842            for this error').
843        code (int): An internal code that customers can reference in their
844            support request or to help them when searching for knowledge
845            base articles related to this error (default ``None``).
846    """
847
848    def __init__(self, title=None, description=None, headers=None, **kwargs):
849        super(HTTPUnprocessableEntity, self).__init__(status.HTTP_422, title,
850                                                      description, headers, **kwargs)
851
852
853class HTTPLocked(OptionalRepresentation, HTTPError):
854    """423 Locked.
855
856    The 423 (Locked) status code means the source or destination resource
857    of a method is locked. This response SHOULD contain an appropriate
858    precondition or postcondition code, such as 'lock-token-submitted' or
859    'no-conflicting-lock'.
860
861    (See also: RFC 4918, Section 11.3)
862
863    Keyword Args:
864        title (str): Error title (default '423 Locked').
865        description (str): Human-friendly description of the error, along with
866            a helpful suggestion or two.
867        headers (dict or list): A ``dict`` of header names and values
868            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
869            *value* must be of type ``str`` or ``StringType``, and only
870            character values 0x00 through 0xFF may be used on platforms that
871            use wide characters.
872
873            Note:
874                The Content-Type header, if present, will be overridden. If
875                you wish to return custom error messages, you can create
876                your own HTTP error class, and install an error handler
877                to convert it into an appropriate HTTP response for the
878                client
879
880            Note:
881                Falcon can process a list of ``tuple`` slightly faster
882                than a ``dict``.
883        href (str): A URL someone can visit to find out more information
884            (default ``None``). Unicode characters are percent-encoded.
885        href_text (str): If href is given, use this as the friendly
886            title/description for the link (default 'API documentation
887            for this error').
888        code (int): An internal code that customers can reference in their
889            support request or to help them when searching for knowledge
890            base articles related to this error (default ``None``).
891    """
892
893    def __init__(self, title=None, description=None, headers=None, **kwargs):
894        super(HTTPLocked, self).__init__(status.HTTP_423, title,
895                                         description, headers,
896                                         **kwargs)
897
898
899class HTTPFailedDependency(OptionalRepresentation, HTTPError):
900    """424 Failed Dependency.
901
902    The 424 (Failed Dependency) status code means that the method could
903    not be performed on the resource because the requested action
904    depended on another action and that action failed.
905
906    (See also: RFC 4918, Section 11.4)
907
908    Keyword Args:
909        title (str): Error title (default '424 Failed Dependency').
910        description (str): Human-friendly description of the error, along with
911            a helpful suggestion or two.
912        headers (dict or list): A ``dict`` of header names and values
913            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
914            *value* must be of type ``str`` or ``StringType``, and only
915            character values 0x00 through 0xFF may be used on platforms that
916            use wide characters.
917
918            Note:
919                The Content-Type header, if present, will be overridden. If
920                you wish to return custom error messages, you can create
921                your own HTTP error class, and install an error handler
922                to convert it into an appropriate HTTP response for the
923                client
924
925            Note:
926                Falcon can process a list of ``tuple`` slightly faster
927                than a ``dict``.
928        href (str): A URL someone can visit to find out more information
929            (default ``None``). Unicode characters are percent-encoded.
930        href_text (str): If href is given, use this as the friendly
931            title/description for the link (default 'API documentation
932            for this error').
933        code (int): An internal code that customers can reference in their
934            support request or to help them when searching for knowledge
935            base articles related to this error (default ``None``).
936    """
937
938    def __init__(self, title=None, description=None, headers=None, **kwargs):
939        super(HTTPFailedDependency, self).__init__(status.HTTP_424, title,
940                                                   description, headers,
941                                                   **kwargs)
942
943
944class HTTPPreconditionRequired(HTTPError):
945    """428 Precondition Required.
946
947    The 428 status code indicates that the origin server requires the
948    request to be conditional.
949
950    Its typical use is to avoid the "lost update" problem, where a client
951    GETs a resource's state, modifies it, and PUTs it back to the server,
952    when meanwhile a third party has modified the state on the server,
953    leading to a conflict.  By requiring requests to be conditional, the
954    server can assure that clients are working with the correct copies.
955
956    Responses using this status code SHOULD explain how to resubmit the
957    request successfully.
958
959    (See also: RFC 6585, Section 3)
960
961    Keyword Args:
962        title (str): Error title (default '428 Precondition Required').
963        description (str): Human-friendly description of the error, along with
964            a helpful suggestion or two.
965        headers (dict or list): A ``dict`` of header names and values
966            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
967            *value* must be of type ``str`` or ``StringType``, and only
968            character values 0x00 through 0xFF may be used on platforms that
969            use wide characters.
970
971            Note:
972                The Content-Type header, if present, will be overridden. If
973                you wish to return custom error messages, you can create
974                your own HTTP error class, and install an error handler
975                to convert it into an appropriate HTTP response for the
976                client
977
978            Note:
979                Falcon can process a list of ``tuple`` slightly faster
980                than a ``dict``.
981        href (str): A URL someone can visit to find out more information
982            (default ``None``). Unicode characters are percent-encoded.
983        href_text (str): If href is given, use this as the friendly
984            title/description for the link (default 'API documentation
985            for this error').
986        code (int): An internal code that customers can reference in their
987            support request or to help them when searching for knowledge
988            base articles related to this error (default ``None``).
989    """
990    def __init__(self, title=None, description=None, headers=None, **kwargs):
991        super(HTTPPreconditionRequired, self).__init__(status.HTTP_428, title,
992                                                       description, headers,
993                                                       **kwargs)
994
995
996class HTTPTooManyRequests(HTTPError):
997    """429 Too Many Requests.
998
999    The user has sent too many requests in a given amount of time ("rate
1000    limiting").
1001
1002    The response representations SHOULD include details explaining the
1003    condition, and MAY include a Retry-After header indicating how long
1004    to wait before making a new request.
1005
1006    Responses with the 429 status code MUST NOT be stored by a cache.
1007
1008    (See also: RFC 6585, Section 4)
1009
1010    Keyword Args:
1011        title (str): Error title (default '429 Too Many Requests').
1012        description (str): Human-friendly description of the rate limit that
1013            was exceeded.
1014        retry_after (datetime or int): Value for the Retry-After
1015            header. If a ``datetime`` object, will serialize as an HTTP date.
1016            Otherwise, a non-negative ``int`` is expected, representing the
1017            number of seconds to wait.
1018        headers (dict or list): A ``dict`` of header names and values
1019            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1020            *value* must be of type ``str`` or ``StringType``, and only
1021            character values 0x00 through 0xFF may be used on platforms that
1022            use wide characters.
1023
1024            Note:
1025                The Content-Type header, if present, will be overridden. If
1026                you wish to return custom error messages, you can create
1027                your own HTTP error class, and install an error handler
1028                to convert it into an appropriate HTTP response for the
1029                client
1030
1031            Note:
1032                Falcon can process a list of ``tuple`` slightly faster
1033                than a ``dict``.
1034        href (str): A URL someone can visit to find out more information
1035            (default ``None``). Unicode characters are percent-encoded.
1036        href_text (str): If href is given, use this as the friendly
1037            title/description for the link (default 'API documentation
1038            for this error').
1039        code (int): An internal code that customers can reference in their
1040            support request or to help them when searching for knowledge
1041            base articles related to this error (default ``None``).
1042    """
1043
1044    def __init__(self, title=None, description=None, retry_after=None, headers=None, **kwargs):
1045        if headers is None:
1046            headers = {}
1047
1048        if isinstance(retry_after, datetime):
1049            headers['Retry-After'] = util.dt_to_http(retry_after)
1050        elif retry_after is not None:
1051            headers['Retry-After'] = str(retry_after)
1052
1053        super(HTTPTooManyRequests, self).__init__(status.HTTP_429,
1054                                                  title,
1055                                                  description,
1056                                                  headers,
1057                                                  **kwargs)
1058
1059
1060class HTTPRequestHeaderFieldsTooLarge(HTTPError):
1061    """431 Request Header Fields Too Large.
1062
1063    The 431 status code indicates that the server is unwilling to process
1064    the request because its header fields are too large.  The request MAY
1065    be resubmitted after reducing the size of the request header fields.
1066
1067    It can be used both when the set of request header fields in total is
1068    too large, and when a single header field is at fault.  In the latter
1069    case, the response representation SHOULD specify which header field
1070    was too large.
1071
1072    Responses with the 431 status code MUST NOT be stored by a cache.
1073
1074    (See also: RFC 6585, Section 5)
1075
1076    Keyword Args:
1077        title (str): Error title (default '431 Request Header Fields Too Large').
1078        description (str): Human-friendly description of the rate limit that
1079            was exceeded.
1080        headers (dict or list): A ``dict`` of header names and values
1081            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1082            *value* must be of type ``str`` or ``StringType``, and only
1083            character values 0x00 through 0xFF may be used on platforms that
1084            use wide characters.
1085
1086            Note:
1087                The Content-Type header, if present, will be overridden. If
1088                you wish to return custom error messages, you can create
1089                your own HTTP error class, and install an error handler
1090                to convert it into an appropriate HTTP response for the
1091                client
1092
1093            Note:
1094                Falcon can process a list of ``tuple`` slightly faster
1095                than a ``dict``.
1096        href (str): A URL someone can visit to find out more information
1097            (default ``None``). Unicode characters are percent-encoded.
1098        href_text (str): If href is given, use this as the friendly
1099            title/description for the link (default 'API documentation
1100            for this error').
1101        code (int): An internal code that customers can reference in their
1102            support request or to help them when searching for knowledge
1103            base articles related to this error (default ``None``).
1104    """
1105
1106    def __init__(self, title=None, description=None, headers=None, **kwargs):
1107        super(HTTPRequestHeaderFieldsTooLarge, self).__init__(status.HTTP_431,
1108                                                              title,
1109                                                              description,
1110                                                              headers,
1111                                                              **kwargs)
1112
1113
1114class HTTPUnavailableForLegalReasons(OptionalRepresentation, HTTPError):
1115    """451 Unavailable For Legal Reasons.
1116
1117    The server is denying access to the resource as a consequence of a
1118    legal demand.
1119
1120    The server in question might not be an origin server. This type of
1121    legal demand typically most directly affects the operations of ISPs
1122    and search engines.
1123
1124    Responses using this status code SHOULD include an explanation, in
1125    the response body, of the details of the legal demand: the party
1126    making it, the applicable legislation or regulation, and what
1127    classes of person and resource it applies to.
1128
1129    Note that in many cases clients can still access the denied resource
1130    by using technical countermeasures such as a VPN or the Tor network.
1131
1132    A 451 response is cacheable by default; i.e., unless otherwise
1133    indicated by the method definition or explicit cache controls.
1134
1135    (See also: RFC 7725, Section 3)
1136
1137    Keyword Args:
1138        title (str): Error title (default '451 Unavailable For Legal Reasons').
1139        description (str): Human-friendly description of the error, along with
1140            a helpful suggestion or two (default ``None``).
1141        headers (dict or list): A ``dict`` of header names and values
1142            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1143            *value* must be of type ``str`` or ``StringType``, and only
1144            character values 0x00 through 0xFF may be used on platforms that
1145            use wide characters.
1146
1147            Note:
1148                The Content-Type header, if present, will be overridden. If
1149                you wish to return custom error messages, you can create
1150                your own HTTP error class, and install an error handler
1151                to convert it into an appropriate HTTP response for the
1152                client
1153
1154            Note:
1155                Falcon can process a list of ``tuple`` slightly faster
1156                than a ``dict``.
1157        href (str): A URL someone can visit to find out more information
1158            (default ``None``). Unicode characters are percent-encoded.
1159        href_text (str): If href is given, use this as the friendly
1160            title/description for the link (default 'API documentation
1161            for this error').
1162        code (int): An internal code that customers can reference in their
1163            support request or to help them when searching for knowledge
1164            base articles related to this error (default ``None``).
1165    """
1166
1167    def __init__(self, title=None, headers=None, **kwargs):
1168        super(HTTPUnavailableForLegalReasons, self).__init__(status.HTTP_451,
1169                                                             title,
1170                                                             headers=headers,
1171                                                             **kwargs)
1172
1173
1174class HTTPInternalServerError(HTTPError):
1175    """500 Internal Server Error.
1176
1177    The server encountered an unexpected condition that prevented it
1178    from fulfilling the request.
1179
1180    (See also: RFC 7231, Section 6.6.1)
1181
1182    Keyword Args:
1183        title (str): Error title (default '500 Internal Server Error').
1184        description (str): Human-friendly description of the error, along with
1185            a helpful suggestion or two.
1186        headers (dict or list): A ``dict`` of header names and values
1187            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1188            *value* must be of type ``str`` or ``StringType``, and only
1189            character values 0x00 through 0xFF may be used on platforms that
1190            use wide characters.
1191
1192            Note:
1193                The Content-Type header, if present, will be overridden. If
1194                you wish to return custom error messages, you can create
1195                your own HTTP error class, and install an error handler
1196                to convert it into an appropriate HTTP response for the
1197                client
1198
1199            Note:
1200                Falcon can process a list of ``tuple`` slightly faster
1201                than a ``dict``.
1202        href (str): A URL someone can visit to find out more information
1203            (default ``None``). Unicode characters are percent-encoded.
1204        href_text (str): If href is given, use this as the friendly
1205            title/description for the link (default 'API documentation
1206            for this error').
1207        code (int): An internal code that customers can reference in their
1208            support request or to help them when searching for knowledge
1209            base articles related to this error (default ``None``).
1210
1211    """
1212
1213    def __init__(self, title=None, description=None, headers=None, **kwargs):
1214        super(HTTPInternalServerError, self).__init__(status.HTTP_500, title,
1215                                                      description, headers,
1216                                                      **kwargs)
1217
1218
1219class HTTPNotImplemented(HTTPError):
1220    """501 Not Implemented.
1221
1222    The 501 (Not Implemented) status code indicates that the server does
1223    not support the functionality required to fulfill the request.  This
1224    is the appropriate response when the server does not recognize the
1225    request method and is not capable of supporting it for any resource.
1226
1227    A 501 response is cacheable by default; i.e., unless otherwise
1228    indicated by the method definition or explicit cache controls
1229    as described in RFC 7234, Section 4.2.2.
1230
1231    (See also: RFC 7231, Section 6.6.2)
1232
1233    Keyword Args:
1234        title (str): Error title (default '500 Internal Server Error').
1235        description (str): Human-friendly description of the error, along with
1236            a helpful suggestion or two.
1237        headers (dict or list): A ``dict`` of header names and values
1238            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1239            *value* must be of type ``str`` or ``StringType``, and only
1240            character values 0x00 through 0xFF may be used on platforms that
1241            use wide characters.
1242
1243            Note:
1244                The Content-Type header, if present, will be overridden. If
1245                you wish to return custom error messages, you can create
1246                your own HTTP error class, and install an error handler
1247                to convert it into an appropriate HTTP response for the
1248                client
1249
1250            Note:
1251                Falcon can process a list of ``tuple`` slightly faster
1252                than a ``dict``.
1253
1254        href (str): A URL someone can visit to find out more information
1255            (default ``None``). Unicode characters are percent-encoded.
1256        href_text (str): If href is given, use this as the friendly
1257            title/description for the link (default 'API documentation
1258            for this error').
1259        code (int): An internal code that customers can reference in their
1260            support request or to help them when searching for knowledge
1261            base articles related to this error (default ``None``).
1262
1263    """
1264
1265    def __init__(self, title=None, description=None, headers=None, **kwargs):
1266        super(HTTPNotImplemented, self).__init__(status.HTTP_501, title,
1267                                                 description, headers,
1268                                                 **kwargs)
1269
1270
1271class HTTPBadGateway(HTTPError):
1272    """502 Bad Gateway.
1273
1274    The server, while acting as a gateway or proxy, received an invalid
1275    response from an inbound server it accessed while attempting to
1276    fulfill the request.
1277
1278    (See also: RFC 7231, Section 6.6.3)
1279
1280    Keyword Args:
1281        title (str): Error title (default '502 Bad Gateway').
1282        description (str): Human-friendly description of the error, along with
1283            a helpful suggestion or two.
1284        headers (dict or list): A ``dict`` of header names and values
1285            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1286            *value* must be of type ``str`` or ``StringType``, and only
1287            character values 0x00 through 0xFF may be used on platforms that
1288            use wide characters.
1289
1290            Note:
1291                The Content-Type header, if present, will be overridden. If
1292                you wish to return custom error messages, you can create
1293                your own HTTP error class, and install an error handler
1294                to convert it into an appropriate HTTP response for the
1295                client
1296
1297            Note:
1298                Falcon can process a list of ``tuple`` slightly faster
1299                than a ``dict``.
1300        href (str): A URL someone can visit to find out more information
1301            (default ``None``). Unicode characters are percent-encoded.
1302        href_text (str): If href is given, use this as the friendly
1303            title/description for the link (default 'API documentation
1304            for this error').
1305        code (int): An internal code that customers can reference in their
1306            support request or to help them when searching for knowledge
1307            base articles related to this error (default ``None``).
1308    """
1309
1310    def __init__(self, title=None, description=None, headers=None, **kwargs):
1311        super(HTTPBadGateway, self).__init__(status.HTTP_502, title,
1312                                             description, headers,
1313                                             **kwargs)
1314
1315
1316class HTTPServiceUnavailable(HTTPError):
1317    """503 Service Unavailable.
1318
1319    The server is currently unable to handle the request due to a
1320    temporary overload or scheduled maintenance, which will likely be
1321    alleviated after some delay.
1322
1323    The server MAY send a Retry-After header field to suggest an
1324    appropriate amount of time for the client to wait before retrying
1325    the request.
1326
1327    Note: The existence of the 503 status code does not imply that a
1328    server has to use it when becoming overloaded. Some servers might
1329    simply refuse the connection.
1330
1331    (See also: RFC 7231, Section 6.6.4)
1332
1333    Keyword Args:
1334        title (str): Error title (default '503 Service Unavailable').
1335        description (str): Human-friendly description of the error, along with
1336            a helpful suggestion or two.
1337        retry_after (datetime or int): Value for the Retry-After header. If a
1338            ``datetime`` object, will serialize as an HTTP date. Otherwise,
1339            a non-negative ``int`` is expected, representing the number of
1340            seconds to wait.
1341        headers (dict or list): A ``dict`` of header names and values
1342            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1343            *value* must be of type ``str`` or ``StringType``, and only
1344            character values 0x00 through 0xFF may be used on platforms that
1345            use wide characters.
1346
1347            Note:
1348                The Content-Type header, if present, will be overridden. If
1349                you wish to return custom error messages, you can create
1350                your own HTTP error class, and install an error handler
1351                to convert it into an appropriate HTTP response for the
1352                client
1353
1354            Note:
1355                Falcon can process a list of ``tuple`` slightly faster
1356                than a ``dict``.
1357        href (str): A URL someone can visit to find out more information
1358            (default ``None``). Unicode characters are percent-encoded.
1359        href_text (str): If href is given, use this as the friendly
1360            title/description for the link (default 'API documentation
1361            for this error').
1362        code (int): An internal code that customers can reference in their
1363            support request or to help them when searching for knowledge
1364            base articles related to this error (default ``None``).
1365    """
1366
1367    def __init__(self, title=None, description=None, retry_after=None, headers=None, **kwargs):
1368        if headers is None:
1369            headers = {}
1370
1371        if isinstance(retry_after, datetime):
1372            headers['Retry-After'] = util.dt_to_http(retry_after)
1373        elif retry_after is not None:
1374            headers['Retry-After'] = str(retry_after)
1375
1376        super(HTTPServiceUnavailable, self).__init__(status.HTTP_503,
1377                                                     title,
1378                                                     description,
1379                                                     headers,
1380                                                     **kwargs)
1381
1382
1383class HTTPGatewayTimeout(HTTPError):
1384    """504 Gateway Timeout.
1385
1386    The 504 (Gateway Timeout) status code indicates that the server,
1387    while acting as a gateway or proxy, did not receive a timely response
1388    from an upstream server it needed to access in order to complete the
1389    request.
1390
1391    (See also: RFC 7231, Section 6.6.5)
1392
1393    Keyword Args:
1394        title (str): Error title (default '503 Service Unavailable').
1395        description (str): Human-friendly description of the error, along with
1396            a helpful suggestion or two.
1397        headers (dict or list): A ``dict`` of header names and values
1398            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1399            *value* must be of type ``str`` or ``StringType``, and only
1400            character values 0x00 through 0xFF may be used on platforms that
1401            use wide characters.
1402
1403            Note:
1404                The Content-Type header, if present, will be overridden. If
1405                you wish to return custom error messages, you can create
1406                your own HTTP error class, and install an error handler
1407                to convert it into an appropriate HTTP response for the
1408                client
1409
1410            Note:
1411                Falcon can process a list of ``tuple`` slightly faster
1412                than a ``dict``.
1413
1414        href (str): A URL someone can visit to find out more information
1415            (default ``None``). Unicode characters are percent-encoded.
1416        href_text (str): If href is given, use this as the friendly
1417            title/description for the link (default 'API documentation
1418            for this error').
1419        code (int): An internal code that customers can reference in their
1420            support request or to help them when searching for knowledge
1421            base articles related to this error (default ``None``).
1422    """
1423
1424    def __init__(self, title=None, description=None, headers=None, **kwargs):
1425        super(HTTPGatewayTimeout, self).__init__(status.HTTP_504, title,
1426                                                 description, headers,
1427                                                 **kwargs)
1428
1429
1430class HTTPVersionNotSupported(HTTPError):
1431    """505 HTTP Version Not Supported
1432
1433    The 505 (HTTP Version Not Supported) status code indicates that the
1434    server does not support, or refuses to support, the major version of
1435    HTTP that was used in the request message.  The server is indicating
1436    that it is unable or unwilling to complete the request using the same
1437    major version as the client (as described in RFC 7230, Section 2.6),
1438    other than with this error message.  The server SHOULD
1439    generate a representation for the 505 response that describes why
1440    that version is not supported and what other protocols are supported
1441    by that server.
1442
1443    (See also: RFC 7231, Section 6.6.6)
1444
1445    Keyword Args:
1446        title (str): Error title (default '503 Service Unavailable').
1447        description (str): Human-friendly description of the error, along with
1448            a helpful suggestion or two.
1449        headers (dict or list): A ``dict`` of header names and values
1450            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1451            *value* must be of type ``str`` or ``StringType``, and only
1452            character values 0x00 through 0xFF may be used on platforms that
1453            use wide characters.
1454
1455            Note:
1456                The Content-Type header, if present, will be overridden. If
1457                you wish to return custom error messages, you can create
1458                your own HTTP error class, and install an error handler
1459                to convert it into an appropriate HTTP response for the
1460                client
1461
1462            Note:
1463                Falcon can process a list of ``tuple`` slightly faster
1464                than a ``dict``.
1465
1466        href (str): A URL someone can visit to find out more information
1467            (default ``None``). Unicode characters are percent-encoded.
1468        href_text (str): If href is given, use this as the friendly
1469            title/description for the link (default 'API documentation
1470            for this error').
1471        code (int): An internal code that customers can reference in their
1472            support request or to help them when searching for knowledge
1473            base articles related to this error (default ``None``).
1474    """
1475
1476    def __init__(self, title=None, description=None, headers=None, **kwargs):
1477        super(HTTPVersionNotSupported, self).__init__(status.HTTP_505, title,
1478                                                      description, headers,
1479                                                      **kwargs)
1480
1481
1482class HTTPInsufficientStorage(HTTPError):
1483    """507 Insufficient Storage.
1484
1485    The 507 (Insufficient Storage) status code means the method could not
1486    be performed on the resource because the server is unable to store
1487    the representation needed to successfully complete the request. This
1488    condition is considered to be temporary. If the request that
1489    received this status code was the result of a user action, the
1490    request MUST NOT be repeated until it is requested by a separate user
1491    action.
1492
1493    (See also: RFC 4918, Section 11.5)
1494
1495    Keyword Args:
1496        title (str): Error title (default '507 Insufficient Storage').
1497        description (str): Human-friendly description of the error, along with
1498            a helpful suggestion or two.
1499        headers (dict or list): A ``dict`` of header names and values
1500            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1501            *value* must be of type ``str`` or ``StringType``, and only
1502            character values 0x00 through 0xFF may be used on platforms that
1503            use wide characters.
1504
1505            Note:
1506                The Content-Type header, if present, will be overridden. If
1507                you wish to return custom error messages, you can create
1508                your own HTTP error class, and install an error handler
1509                to convert it into an appropriate HTTP response for the
1510                client
1511
1512            Note:
1513                Falcon can process a list of ``tuple`` slightly faster
1514                than a ``dict``.
1515        href (str): A URL someone can visit to find out more information
1516            (default ``None``). Unicode characters are percent-encoded.
1517        href_text (str): If href is given, use this as the friendly
1518            title/description for the link (default 'API documentation
1519            for this error').
1520        code (int): An internal code that customers can reference in their
1521            support request or to help them when searching for knowledge
1522            base articles related to this error (default ``None``).
1523    """
1524
1525    def __init__(self, title=None, description=None, headers=None, **kwargs):
1526        super(HTTPInsufficientStorage, self).__init__(status.HTTP_507, title,
1527                                                      description, headers,
1528                                                      **kwargs)
1529
1530
1531class HTTPLoopDetected(HTTPError):
1532    """508 Loop Detected.
1533
1534    The 508 (Loop Detected) status code indicates that the server
1535    terminated an operation because it encountered an infinite loop while
1536    processing a request with "Depth: infinity". This status indicates
1537    that the entire operation failed.
1538
1539    (See also: RFC 5842, Section 7.2)
1540
1541    Keyword Args:
1542        title (str): Error title (default '508 Loop Detected').
1543        description (str): Human-friendly description of the error, along with
1544            a helpful suggestion or two.
1545        headers (dict or list): A ``dict`` of header names and values
1546            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1547            *value* must be of type ``str`` or ``StringType``, and only
1548            character values 0x00 through 0xFF may be used on platforms that
1549            use wide characters.
1550
1551            Note:
1552                The Content-Type header, if present, will be overridden. If
1553                you wish to return custom error messages, you can create
1554                your own HTTP error class, and install an error handler
1555                to convert it into an appropriate HTTP response for the
1556                client
1557
1558            Note:
1559                Falcon can process a list of ``tuple`` slightly faster
1560                than a ``dict``.
1561        href (str): A URL someone can visit to find out more information
1562            (default ``None``). Unicode characters are percent-encoded.
1563        href_text (str): If href is given, use this as the friendly
1564            title/description for the link (default 'API documentation
1565            for this error').
1566        code (int): An internal code that customers can reference in their
1567            support request or to help them when searching for knowledge
1568            base articles related to this error (default ``None``).
1569    """
1570
1571    def __init__(self, title=None, description=None, headers=None, **kwargs):
1572        super(HTTPLoopDetected, self).__init__(status.HTTP_508, title,
1573                                               description, headers,
1574                                               **kwargs)
1575
1576
1577class HTTPNetworkAuthenticationRequired(HTTPError):
1578    """511 Network Authentication Required.
1579
1580    The 511 status code indicates that the client needs to authenticate
1581    to gain network access.
1582
1583    The response representation SHOULD contain a link to a resource that
1584    allows the user to submit credentials.
1585
1586    Note that the 511 response SHOULD NOT contain a challenge or the
1587    authentication interface itself, because clients would show the
1588    interface as being associated with the originally requested URL,
1589    which may cause confusion.
1590
1591    The 511 status SHOULD NOT be generated by origin servers; it is
1592    intended for use by intercepting proxies that are interposed as a
1593    means of controlling access to the network.
1594
1595    Responses with the 511 status code MUST NOT be stored by a cache.
1596
1597    (See also: RFC 6585, Section 6)
1598
1599    Keyword Args:
1600        title (str): Error title (default '511 Network Authentication Required').
1601        description (str): Human-friendly description of the error, along with
1602            a helpful suggestion or two.
1603        headers (dict or list): A ``dict`` of header names and values
1604            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1605            *value* must be of type ``str`` or ``StringType``, and only
1606            character values 0x00 through 0xFF may be used on platforms that
1607            use wide characters.
1608
1609            Note:
1610                The Content-Type header, if present, will be overridden. If
1611                you wish to return custom error messages, you can create
1612                your own HTTP error class, and install an error handler
1613                to convert it into an appropriate HTTP response for the
1614                client
1615
1616            Note:
1617                Falcon can process a list of ``tuple`` slightly faster
1618                than a ``dict``.
1619        href (str): A URL someone can visit to find out more information
1620            (default ``None``). Unicode characters are percent-encoded.
1621        href_text (str): If href is given, use this as the friendly
1622            title/description for the link (default 'API documentation
1623            for this error').
1624        code (int): An internal code that customers can reference in their
1625            support request or to help them when searching for knowledge
1626            base articles related to this error (default ``None``).
1627    """
1628
1629    def __init__(self, title=None, description=None, headers=None, **kwargs):
1630        super(HTTPNetworkAuthenticationRequired, self).__init__(status.HTTP_511,
1631                                                                title,
1632                                                                description,
1633                                                                headers,
1634                                                                **kwargs)
1635
1636
1637class HTTPInvalidHeader(HTTPBadRequest):
1638    """400 Bad Request.
1639
1640    One of the headers in the request is invalid.
1641
1642    Args:
1643        msg (str): A description of why the value is invalid.
1644        header_name (str): The name of the invalid header.
1645
1646    Keyword Args:
1647        headers (dict or list): A ``dict`` of header names and values
1648            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1649            *value* must be of type ``str`` or ``StringType``, and only
1650            character values 0x00 through 0xFF may be used on platforms that
1651            use wide characters.
1652
1653            Note:
1654                The Content-Type header, if present, will be overridden. If
1655                you wish to return custom error messages, you can create
1656                your own HTTP error class, and install an error handler
1657                to convert it into an appropriate HTTP response for the
1658                client
1659
1660            Note:
1661                Falcon can process a list of ``tuple`` slightly faster
1662                than a ``dict``.
1663        href (str): A URL someone can visit to find out more information
1664            (default ``None``). Unicode characters are percent-encoded.
1665        href_text (str): If href is given, use this as the friendly
1666            title/description for the link (default 'API documentation
1667            for this error').
1668        code (int): An internal code that customers can reference in their
1669            support request or to help them when searching for knowledge
1670            base articles related to this error (default ``None``).
1671    """
1672
1673    def __init__(self, msg, header_name, headers=None, **kwargs):
1674        description = ('The value provided for the {0} header is '
1675                       'invalid. {1}')
1676        description = description.format(header_name, msg)
1677
1678        super(HTTPInvalidHeader, self).__init__('Invalid header value',
1679                                                description, headers,
1680                                                **kwargs)
1681
1682
1683class HTTPMissingHeader(HTTPBadRequest):
1684    """400 Bad Request
1685
1686    A header is missing from the request.
1687
1688    Args:
1689        header_name (str): The name of the missing header.
1690
1691    Keyword Args:
1692        headers (dict or list): A ``dict`` of header names and values
1693            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1694            *value* must be of type ``str`` or ``StringType``, and only
1695            character values 0x00 through 0xFF may be used on platforms that
1696            use wide characters.
1697
1698            Note:
1699                The Content-Type header, if present, will be overridden. If
1700                you wish to return custom error messages, you can create
1701                your own HTTP error class, and install an error handler
1702                to convert it into an appropriate HTTP response for the
1703                client
1704
1705            Note:
1706                Falcon can process a list of ``tuple`` slightly faster
1707                than a ``dict``.
1708        href (str): A URL someone can visit to find out more information
1709            (default ``None``). Unicode characters are percent-encoded.
1710        href_text (str): If href is given, use this as the friendly
1711            title/description for the link (default 'API documentation
1712            for this error').
1713        code (int): An internal code that customers can reference in their
1714            support request or to help them when searching for knowledge
1715            base articles related to this error (default ``None``).
1716    """
1717
1718    def __init__(self, header_name, headers=None, **kwargs):
1719        description = 'The {0} header is required.'
1720        description = description.format(header_name)
1721
1722        super(HTTPMissingHeader, self).__init__('Missing header value',
1723                                                description, headers,
1724                                                **kwargs)
1725
1726
1727class HTTPInvalidParam(HTTPBadRequest):
1728    """400 Bad Request
1729
1730    A parameter in the request is invalid. This error may refer to a
1731    parameter in a query string, form, or document that was submitted
1732    with the request.
1733
1734    Args:
1735        msg (str): A description of the invalid parameter.
1736        param_name (str): The name of the parameter.
1737
1738    Keyword Args:
1739        headers (dict or list): A ``dict`` of header names and values
1740            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1741            *value* must be of type ``str`` or ``StringType``, and only
1742            character values 0x00 through 0xFF may be used on platforms that
1743            use wide characters.
1744
1745            Note:
1746                The Content-Type header, if present, will be overridden. If
1747                you wish to return custom error messages, you can create
1748                your own HTTP error class, and install an error handler
1749                to convert it into an appropriate HTTP response for the
1750                client
1751
1752            Note:
1753                Falcon can process a list of ``tuple`` slightly faster
1754                than a ``dict``.
1755        href (str): A URL someone can visit to find out more information
1756            (default ``None``). Unicode characters are percent-encoded.
1757        href_text (str): If href is given, use this as the friendly
1758            title/description for the link (default 'API documentation
1759            for this error').
1760        code (int): An internal code that customers can reference in their
1761            support request or to help them when searching for knowledge
1762            base articles related to this error (default ``None``).
1763    """
1764
1765    def __init__(self, msg, param_name, headers=None, **kwargs):
1766        description = 'The "{0}" parameter is invalid. {1}'
1767        description = description.format(param_name, msg)
1768
1769        super(HTTPInvalidParam, self).__init__('Invalid parameter',
1770                                               description, headers,
1771                                               **kwargs)
1772
1773
1774class HTTPMissingParam(HTTPBadRequest):
1775    """400 Bad Request
1776
1777    A parameter is missing from the request. This error may refer to a
1778    parameter in a query string, form, or document that was submitted
1779    with the request.
1780
1781    Args:
1782        param_name (str): The name of the missing parameter.
1783
1784    Keyword Args:
1785        headers (dict or list): A ``dict`` of header names and values
1786            to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
1787            *value* must be of type ``str`` or ``StringType``, and only
1788            character values 0x00 through 0xFF may be used on platforms that
1789            use wide characters.
1790
1791            Note:
1792                The Content-Type header, if present, will be overridden. If
1793                you wish to return custom error messages, you can create
1794                your own HTTP error class, and install an error handler
1795                to convert it into an appropriate HTTP response for the
1796                client
1797
1798            Note:
1799                Falcon can process a list of ``tuple`` slightly faster
1800                than a ``dict``.
1801        href (str): A URL someone can visit to find out more information
1802            (default ``None``). Unicode characters are percent-encoded.
1803        href_text (str): If href is given, use this as the friendly
1804            title/description for the link (default 'API documentation
1805            for this error').
1806        code (int): An internal code that customers can reference in their
1807            support request or to help them when searching for knowledge
1808            base articles related to this error (default ``None``).
1809    """
1810
1811    def __init__(self, param_name, headers=None, **kwargs):
1812        description = 'The "{0}" parameter is required.'
1813        description = description.format(param_name)
1814
1815        super(HTTPMissingParam, self).__init__('Missing parameter',
1816                                               description, headers,
1817                                               **kwargs)
1818