|
| 1 | +import markupsafe |
| 2 | + |
| 3 | + |
| 4 | +class HTMLMiddleware: |
| 5 | + """ |
| 6 | + A middleware class for handling HTML-related operations, specifically for creating hidden input fields |
| 7 | + with specific methods (like PUT and DELETE) that are not natively supported by HTML forms. |
| 8 | +
|
| 9 | + Methods: |
| 10 | + - _input_html: Private method to generate HTML input element. |
| 11 | + - _put: Private method to generate a hidden input field for the PUT method. |
| 12 | + - _delete: Private method to generate a hidden input field for the DELETE method. |
| 13 | + - method: Public method to handle the generation of appropriate HTML based on a given string. |
| 14 | + """ |
| 15 | + |
| 16 | + def _input_html(self, input_method): |
| 17 | + """ |
| 18 | + Generates a hidden HTML input element. |
| 19 | +
|
| 20 | + Args: |
| 21 | + - input_method (str): The HTTP method to be used (e.g., 'put', 'delete'). |
| 22 | +
|
| 23 | + Returns: |
| 24 | + - str: An HTML string for a hidden input element with the specified method. |
| 25 | + """ |
| 26 | + return f"<input type='hidden' name='_method' value={input_method.upper()}>" |
| 27 | + |
| 28 | + def _put(self): |
| 29 | + """ |
| 30 | + Generates a hidden input field for the PUT method. |
| 31 | +
|
| 32 | + Returns: |
| 33 | + - str: An HTML string for a hidden input element for the PUT method. |
| 34 | + """ |
| 35 | + return self._input_html("put") |
| 36 | + |
| 37 | + def _delete(self): |
| 38 | + """ |
| 39 | + Generates a hidden input field for the DELETE method. |
| 40 | +
|
| 41 | + Returns: |
| 42 | + - str: An HTML string for a hidden input element for the DELETE method. |
| 43 | + """ |
| 44 | + return self._input_html("delete") |
| 45 | + |
| 46 | + def method(self, string): |
| 47 | + """ |
| 48 | + Determines the appropriate HTML string to return based on the given method string. |
| 49 | +
|
| 50 | + Args: |
| 51 | + - string (str): The method string (e.g., 'put', 'delete'). |
| 52 | +
|
| 53 | + Returns: |
| 54 | + - Markup: A markupsafe.Markup object containing the appropriate HTML string. |
| 55 | + This object is safe to render directly in templates. |
| 56 | + """ |
| 57 | + result = { |
| 58 | + "put": self._put(), |
| 59 | + "delete": self._delete(), |
| 60 | + }[string.lower()] |
| 61 | + |
| 62 | + return markupsafe.Markup(result) |
0 commit comments