예제 #1
0
def sendToCalibre(userid, productid):
    user = Globals.Settings.UserList.getUser(userid)
    if not user:
        abort(404)
    outputDir = app.config.get('output_dir')
    os.makedirs(outputDir, exist_ok=True)
    # GetBookOrBooks always returns an absolute path
    outputFileName = actions.GetBookOrBooks(user,
                                            outputDir,
                                            productId=productid)
    req = Request(
        'POST',
        url=Globals.Settings.UserList.calibre_web.url,
        files={'btn-upload': open(outputFileName, 'rb')},
    )
    if Globals.Settings.UserList.calibre_web.username:
        req.auth = HTTPBasicAuth(
            Globals.Settings.UserList.calibre_web.username,
            Globals.Settings.UserList.calibre_web.password,
        )
    success = None
    try:
        resp = Session().send(req.prepare())
        resp.raise_for_status()
        success = f"New book uploaded to {resp.json()['location']}"
    except HTTPError as err:
        return getUserBooks(userid=userid, error=err)
    except json.decoder.JSONDecodeError:
        return getUserBooks(
            userid=userid,
            error=
            "Could not decode response.  Check your CalibreWeb Credentials.")
    return getUserBooks(userid=userid, success=success)
예제 #2
0
    def send(self, req: requests.Request,
             **kwargs) -> Optional[requests.Response]:
        """Send a request to the DEP service.

        If the service responds that the token has expired, fetch a new session token and re-issue the request.

        Args:
              req (requests.Request): The request, which will have DEP auth headers added to it.
        Returns:
              requests.Response: The response
        """
        if self._access_token_expiry is not None and datetime.now(
        ) > self._access_token_expiry:
            raise DEPClientError(
                "DEP Service Token has expired, please generate a new one.")

        if self._retry_after is not None:  # refuse to send request
            return None

        if self.session_token is None:
            self.fetch_token()

        req.hooks = dict(response=self._response_hook)
        req.auth = DEPAuth(self._session_token)

        prepared = self._session.prepare_request(req)

        res = self._session.send(prepared, **kwargs)

        try:
            res.raise_for_status()
        except requests.HTTPError as e:
            raise DEPServiceError(response=res, request=res.request) from e

        return res
예제 #3
0
파일: wtt.py 프로젝트: jerrywang1974/wtt
    def send(self, url, session):
        """
		prepare request and sends it to server

		params:
		url	Url object with parsed URL
		session	current requests session
		"""
        if "Connection" not in self.headers:
            self.headers["Connection"] = "keep-alive"
        self.host = url.host
        self.protocol = url.protocol

        if self.url == None:
            if url.path == None:
                self.url = ""
            else:
                self.url = url.path
        else:
            self.url = ''.join(
                [url.path,
                 re.sub(r"^\/", "", self.url), url.parameters])

        if self.description == None or self.description.lower().find(
                'csrf') == -1:
            if self.csrf and self.method.upper() == "POST":
                self.get_csrf_token(session, self.uri)
                if self.body != None:
                    self.body += "&"
                if self.csrf_sendname != None:
                    self.body += "%s=%s" % (self.csrf_sendname,
                                            self.csrf_value)
                else:
                    self.body += "%s=%s" % (self.csrf_name, self.csrf_value)

        self.uri = "%s://%s:%s/%s" % (self.protocol, self.host, url.port,
                                      self.url)

        if "Referer" not in self.headers:
            self.headers["Referer"] = self.uri.split("?")[0]

        request = Request(self.method.upper(),
                          self.uri,
                          headers=self.headers,
                          data=self.body,
                          cookies=session.cookies)

        if self.auth == "basic" or self.auth == "digest":
            request.auth = self.auth_basic_digest()

        response = session.send(request.prepare(),
                                verify=False,
                                allow_redirects=False)
        self.raw_request = pretty_raw_request(response)
        self.actual_status_code = response.status_code
        self.response = response.text
예제 #4
0
    def _send_with_credentials(self, request: requests.Request, timeout) \
            -> requests.Response:
        """Sends the given request with HTTP Basic Authorization."""

        request.auth = self._credentials
        resp = self._perform_request(request, timeout)

        if "session_id" in resp.cookies:
            # Update the session ID if we don't already have one
            self._session_id = resp.cookies["session_id"]

        return resp
예제 #5
0
def sendHttpRequest(_args):
    s = Session()
    url = makeURL(_args)
    req = Request(_args.get("method"), url)
    if (_args.get("headers") is not None) : req.headers = _args.get("headers")
    if (_args.get("auth") is not None) : req.auth = HTTPBasicAuth(_args.get("auth")[0], _args.get("auth")[1])
    if (_args.get("params") is not None) : req.params = _args.get("params")
    if (_args.get("cookies") is not None) : req.cookies = _args.get("cookies")
    if (_args.get("data") is not None) : req.data = _args.get("data")

    prepped = req.prepare()
    if (_args.get("body") is not None) : prepped.body = _args.get("body")

    # do something with prepped.body
    # do something with prepped.headers

    resp = s.send(prepped,timeout=_args.get("timeout"), proxies=_args.get("proxies"))
    return resp
예제 #6
0
    def build_request(self, auth, endpoint, body, params, method, timeout,
                      headers):
        """ Build up the request object.
            auth : object | string
                Will either contain a configured form of authentication - like the well supported
                HTTPDigestAuth that is inbuilt to requests or  simply a string that will notify the
                service of which type of authentication to use.
            endpoint : string
                The URI path to send the request to
            body : dict
                If a GET request, will be used for the URL params.
                If a POST request this will be the data in the body of the packet.
            method : string
                The HTTP method
            timeout : float
                The time that the request will wait before timing out if there is
                no data from the server.
            headers : dict
                The headers that will be sent in the request
        """

        request = Request(method=method, url=endpoint, headers=headers)

        if auth is 'bearer':
            request.headers[
                'Authorization'] = f'Bearer {self.sws.access_token}'
        elif isinstance(auth, HTTPBasicAuth):
            request.auth = auth

        if method is 'GET' or method is 'DELETE':
            request.params = body

        if self.sws.test_env:
            request.headers.update(self.FirewallHeader.getHeader())

        if method == 'PUT' or method == 'PATCH' or method == 'POST':
            if 'Content-Type' in headers and headers[
                    'Content-Type'] == 'application/x-www-form-urlencoded':
                request.data = body
            else:
                request.data = json.dumps(body)  # JSON in the body by default
            if params != {}:
                request.params = params
        return request
예제 #7
0
def sendHttpRequest(_args):
    s = Session()
    url = makeURL(_args)
    req = Request(_args.get("method"), url)
    if (_args.get("headers") is not None): req.headers = _args.get("headers")
    if (_args.get("auth") is not None):
        req.auth = HTTPBasicAuth(_args.get("auth")[0], _args.get("auth")[1])
    if (_args.get("params") is not None): req.params = _args.get("params")
    if (_args.get("cookies") is not None): req.cookies = _args.get("cookies")
    if (_args.get("data") is not None): req.data = _args.get("data")

    prepped = req.prepare()
    if (_args.get("body") is not None): prepped.body = _args.get("body")

    # do something with prepped.body
    # do something with prepped.headers

    resp = s.send(prepped,
                  timeout=_args.get("timeout"),
                  proxies=_args.get("proxies"))
    return resp
예제 #8
0
    def send(self, req: requests.Request, **kwargs) -> requests.Response:
        """Send a request to the DEP service.

        If the service responds that the token has expired, fetch a new session token and re-issue the request.

        Args:
              req (requests.Request): The request, which will have DEP auth headers added to it.
        Returns:
              requests.Response: The response
        """
        req.hooks = dict(response=self._response_hook)
        req.auth = DEPAuth(self._token)

        prepared = self._session.prepare_request(req)

        res = self._session.send(prepared, **kwargs)

        try:
            res.raise_for_status()
        except requests.HTTPError as e:
            raise DEPError(response=res, request=res.request) from e

        return res