1 # Licensed to the Apache Software Foundation (ASF) under one or more
2 # contributor license agreements. See the NOTICE file distributed with
3 # this work for additional information regarding copyright ownership.
4 # The ASF licenses this file to You under the Apache License, Version 2.0
5 # (the "License"); you may not use this file except in compliance with
6 # the License. You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
19 from requests import Session
20 from requests.exceptions import (ConnectionError, InvalidSchema)
21 from cachecontrol import CacheControl
22 from cachecontrol.caches import FileCache
24 from .exceptions import LoaderException, DocumentNotFoundException
25 from .loader import Loader
28 SESSION_CACHE_PATH = os.path.join(tempfile.gettempdir(), 'aria_requests')
31 class RequestLoader(Loader):
33 Base class for ARIA request-based loaders.
35 Extracts a document from a URI by performing a request.
37 Note that the "file:" schema is not supported: :class:`FileTextLoader` should
41 def __init__(self, context, uri, headers=None):
44 self.context = context
46 self.headers = headers
55 SESSION = CacheControl(Session(), cache=FileCache(SESSION_CACHE_PATH))
58 self._response = SESSION.get(self.uri, headers=self.headers)
59 except InvalidSchema as e:
60 raise DocumentNotFoundException('document not found: "%s"' % self.uri, cause=e)
61 except ConnectionError as e:
62 raise LoaderException('request connection error: "%s"' % self.uri, cause=e)
63 except Exception as e:
64 raise LoaderException('request error: "%s"' % self.uri, cause=e)
66 status = self._response.status_code
69 raise DocumentNotFoundException('document not found: "%s"' % self.uri)
72 raise LoaderException('request error %d: "%s"' % (status, self.uri))
75 class RequestTextLoader(RequestLoader):
77 ARIA request-based text loader.
81 if self._response is not None:
83 if self._response.encoding is None:
84 self._response.encoding = 'utf8'
85 return self._response.text
86 except Exception as e:
87 raise LoaderException('request error: %s' % self.uri, cause=e)