Spaces:
Runtime error
Runtime error
File size: 1,959 Bytes
e30962b fffd163 e30962b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import enum
from collections.abc import Sequence
import gradio as gr
import requests
class HttpContentType(str, enum.Enum):
"""Http content type values."""
HTML = "text/html"
JSON = "application/json"
def get_url_http_content(
url: str,
content_type: Sequence[HttpContentType] | None = None,
timeout: int = 30,
) -> tuple[str, str]:
"""Get the content of a URL using an HTTP GET request.
Args:
url: The URL to fetch the content from.
content_type: If given it should contain the expected
content types in the response body. The server may
not honor the requested content types.
timeout: Request timeout in seconds. Defaults to 30.
Returns:
A pair of strings (content, error_message). If there is an
error getting content from the URL the `content` will be
empty and `error_message` will, usually, contain the error
cause. Otherwise, `error_message` will be empty and the
content will be filled with data fetched from the URL.
"""
headers = {}
if content_type:
headers["Accept"] = ",".join(content_type)
try:
response = requests.get(
url,
headers=headers,
timeout=timeout,
)
except requests.exceptions.MissingSchema as err:
return "", str(err)
try:
response.raise_for_status()
except requests.HTTPError as err:
return "", str(err)
return response.text, ""
gr_get_url_http_content = gr.Interface(
fn=get_url_http_content,
inputs=["text", "text"],
outputs="text",
title="Get the content of a URL using an HTTP GET request.",
description=(
"Get the content of a URL in one of the specified content types."
" The server may not honor the content type and if it fails the"
" reason should also be returned with the corresponding HTTP"
" error code."
),
)
|