Python httpx.Response() Examples

The following are 30 code examples of httpx.Response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httpx , or try the search function .
Example #1
Source File: client.py    From tiktok_bot with MIT License 7 votes vote down vote up
def __init__(
        self,
        base_url: str,
        default_headers: Optional[dict] = None,
        default_params: Optional[dict] = None,
        history_len: int = 30,
    ):
        self.base_url = base_url
        self.default_headers = default_headers or {}
        self.default_params = default_params or {}

        self.history: Deque[Response] = deque(maxlen=history_len)

        self.http_client = Client(
            base_url=self.base_url, headers=default_headers, params=self.default_params
        ) 
Example #2
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_resource(self, resource_file, **props) -> Response:
        """
        POST /resources

        Add a new resource
        :param resource_file: string, name of the resource_file
        :param props: dict
        :return: res: json result of the post
        """
        if 'title' not in props:
            raise ValueError('`create_resource` requires `title` in `props` property')

        data = {
            'filename': os.path.basename(resource_file),
            'resource_file': resource_file,
            'props': props}

        return await self.query('post', '/resources/', **data) 
Example #3
Source File: client.py    From tiktok_bot with MIT License 6 votes vote down vote up
def get(self, url: str, params: dict, headers: Optional[dict] = None):
        custom_headers = headers or {}
        all_params = {**self._generate_params(), **params}

        logger.debug(f"Sending request to {url}", params=all_params, custom_headers=custom_headers)
        response = self.http_client.get(url=url, params=all_params, headers=custom_headers)

        self.history.append(response)

        body = response.text or "is empty!"

        logger.debug(f"Response return status_code: {response.status_code}, body: {body}")

        for cookie_name, cookie_data in response.cookies.items():
            self.http_client.cookies.set(cookie_name, cookie_data)
            logger.debug(f"New cookies: {dict(response.cookies)}")

        return response 
Example #4
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_tags(self) -> Response:
        """
        GET /tags

        get the list of all the tags of the joplin profile
        :return: res: json result of the get
        """
        return await self.query('get', '/tags/') 
Example #5
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_note(self, note_id, title, body, parent_id, **kwargs) -> Response:
        """
        PUT /notes

        Edit a note
        :param note_id: string note id
        :param title: string
        :param body: string
        :param parent_id: string id of the parent folder
        :param kwargs: dict of additional data
        :return: res: json result of the put
        """
        is_todo = kwargs.get('is_todo', 0)
        data = {
            'title': title,
            'body': body,
            'parent_id': parent_id,
            'author': kwargs.get('author', ''),
            'source_url': kwargs.get('source_url', ''),
            'is_todo': is_todo,
            'tags': kwargs.get('tags', ''),
        }
        if is_todo:
            todo_due = kwargs.get('todo_due', 0)
            todo_completed = kwargs.get('todo_completed', 0)
            data['todo_due'] = todo_due
            data['todo_completed'] = todo_completed

        path = f'/notes/{note_id}'
        return await self.query('put', path, **data) 
Example #6
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_note(self, note_id) -> Response:
        """
        DELETE /notes/:id

        Delete a note
        :param note_id: string
        :return: res: json result of the delete
        """
        path = f'/notes/{note_id}'
        return await self.query('delete', path, self.note_props)

    ##############
    # FOLDERS
    ############## 
Example #7
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_folder(self, folder_id) -> Response:
        """
        GET /folders/:id

        get a folder
        :param folder_id: string of the folder id
        :return: res: json result of the get
        """
        path = f'/folders/{folder_id}'
        return await self.query('get', path, self.folder_props) 
Example #8
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_folders(self) -> Response:
        """
        GET /folders

        get the list of all the folders of the joplin profile
        :return: res: json result of the get
        """
        return await self.query('get', '/folders/', self.folder_props) 
Example #9
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_folders_notes(self, folder_id) -> Response:
        """
        GET /folders/:id/notes

        get the list of all the notes of this folder
        :param folder_id: string of the folder id
        :return: res: json result of the get
        """
        path = f'/folders/{folder_id}/notes'
        return await self.query('get', path, self.note_props) 
Example #10
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_folder(self, folder_id, title, **kwargs) -> Response:
        """
        PUT /folders/:id

        Edit the folder
        :param folder_id: id of the folder to update
        :param title: string name of the folder
        :return: res: json result of the put
        """
        parent_id = kwargs.get('parent_id', '')
        data = {'title': title, 'parent_id': parent_id}
        path = f'/folders/{folder_id}'
        return await self.query('put', path, **data) 
Example #11
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_folder(self, folder_id) -> Response:
        """
        DELETE /folders

        delete a folder
        :param folder_id: string of the folder to delete
        :return: res: json result of the delete
        """
        path = f'/folders/{folder_id}'
        return await self.query('delete', path) 
Example #12
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rename_folder(self, folder_id, folder) -> Response:
        """
        PUT /folders

        Rename the folder
        :param folder_id: id of the folder to update
        :param folder: string name of the folder
        :return: res: json result of the put
        """
        data = {'id': folder_id, 'folder': folder}
        return await self.query('put', '/folders/', **data)

    ##############
    # TAGS
    ############## 
Example #13
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_tag(self, tag_id) -> Response:
        """
        GET /tags/:id

        get a tag
        :param tag_id: string name of the tag
        :return: res: json result of the get
        """
        path = f'/tags/{tag_id}'
        return await self.query('get', path) 
Example #14
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_notes_tags(self, note_id) -> Response:
        """
        GET /notes/:id/tags

        get all the tags attached to this note
        :return: res: result of the get
        """
        path = f'/notes/{note_id}/tags'
        return await self.query('get', path, self.note_props) 
Example #15
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_tag(self, tag_id, title) -> Response:
        """
        PUT /tags/:id

        Edit the tag
        :param tag_id: string id of the tag to update
        :param title: string tag name
        :return: res: json result of the put
        """
        data = {'title': title}
        path = f'/tags/{tag_id}'
        return await self.query('put', path, **data) 
Example #16
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_tag(self, tag_id) -> Response:
        """
        DELETE /tags/:id

        delete a tag
        :param tag_id: string id of the tag to delete
        :return: res: json result of the delete
        """
        path = f'/tags/{tag_id}'
        return await self.query('delete', path) 
Example #17
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_tags_notes_preview(self, tag_id) -> Response:
        """
        GET /tags/:id/notes

        Gets all the notes with this tag.
        :return: res: json result of the get
        """
        path = f'/tags/{tag_id}/notes'
        return await self.query('get', path, self.preview_note_props) 
Example #18
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_tags_notes(self, tag_id) -> Response:
        """
        GET /tags/:id/notes

        Gets all the notes with this tag.
        :return: res: json result of the get
        """
        path = f'/tags/{tag_id}/notes'
        return await self.query('get', path, self.note_props) 
Example #19
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_tags_notes(self, note_id, tag) -> Response:
        """
        POST /tags/:id/notes

        create a tag from a note
        :return: res: json result of the get
        """
        data = {'id': note_id}
        path = f'/tags/{tag}/notes'
        return await self.query('post', path, **data) 
Example #20
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_resources(self, resource_id, **props) -> Response:
        """
        PUT /resources/:id

        Edit a resource
        :param resource_id: string id of the tag to update
        :param props: dict
        :return: res: json result of the put
        """
        if 'title' not in props:
            raise ValueError('`create_resource` requires `title` in `props` property')

        path = f'/resources/{resource_id}'
        return await self.query('put', path, **props) 
Example #21
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download_resources(self, resource_id) -> Response:
        """
        GET /resources/:id/file

        Download a file
        :param resource_id: string id of the tag to update
        :return: res: json result of the put
        """
        path = f'/resources/{resource_id}/file'
        return await self.query('get', path) 
Example #22
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_resources(self, resource_id) -> Response:
        """
        DELETE /resources/:id

        delete a tag
        :param resource_id: string id of the tag to delete
        :return: res: json result of the delete
        """
        path = f'/resources/{resource_id}'
        return await self.query('delete', path)

    ####################
    # PING
    #################### 
Example #23
Source File: core.py    From joplin-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ping(self) -> Response:
        """
        GET /ping

        get the status of the JoplinWebClipper service
        :return: res: json result of the request
        """
        res = await self.query('get', '/ping/')
        if res.text != 'JoplinClipperServer':
            raise ConnectionError('WebClipper unavailable. See "Tools > Webclipper options" if the service is enable')
        return res

    ####################
    # SEARCH
    #################### 
Example #24
Source File: httpx.py    From aiochclient with MIT License 5 votes vote down vote up
def _read_error_body(resp: Response):
    return (await resp.aread()).decode(errors='replace') 
Example #25
Source File: httpx_vcr_stubs.py    From mergify-engine with Apache License 2.0 5 votes vote down vote up
def _from_serialized_response(request, serialized_response, history=None):
    content = serialized_response.get("content").encode()
    response = httpx.Response(
        status_code=serialized_response.get("status_code"),
        request=request,
        http_version=serialized_response.get("http_version"),
        headers=_from_serialized_headers(serialized_response.get("headers")),
        content=content,
        history=history or [],
    )
    response._content = content
    return response 
Example #26
Source File: adapter_test.py    From iota.py with MIT License 5 votes vote down vote up
def create_http_response(content, status=200):
  # type: (Text, int) -> httpx.Response
  """
  Creates an HTTP Response object for a test.
  """
  return httpx.Response(
    status,
    request=httpx.Request('post','https://localhost:14265/'),
    content=content
  ) 
Example #27
Source File: adapter_test.py    From iota.py with MIT License 5 votes vote down vote up
def test_trytes_in_request(self):
    """
    Sending a request that includes trytes.
    """
    adapter = HttpAdapter('http://localhost:14265')

    # Response is not important for this test; we just need to make
    # sure that the request is converted correctly.
    mocked_sender = mock.Mock(return_value=async_return(create_http_response('{}')))

    with mock.patch.object(adapter, '_send_http_request', mocked_sender):
      await adapter.send_request({
        'command':  'helloWorld',
        'trytes': [
          TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA'),

          TryteString(
            b'CCPCBDVC9DTCEAKDXC9D9DEARCWCPCBDVCTCEAHDWCTCEAKDCDFD9DSCSA',
          ),
        ],
      })

    mocked_sender.assert_called_once_with(
      url = adapter.node_url,

      payload = json.dumps({
        'command': 'helloWorld',

        # Tryte sequences are converted to strings for transport.
        'trytes': [
          'RBTC9D9DCDQAEASBYBCCKBFA',
          'CCPCBDVC9DTCEAKDXC9D9DEARCWCPCBDVCTCEAHDWCTCEAKDCDFD9DSCSA',
        ],
      }),

      headers = {
        'Content-type':       'application/json',
        'X-IOTA-API-Version': API_VERSION,
      },
    ) 
Example #28
Source File: items.py    From ant_nest with GNU Lesser General Public License v3.0 5 votes vote down vote up
def extract(self, res: httpx.Response) -> Item:
        item = self.item_cls()
        for key, extractor in self.extractors.items():
            set_value(item, key, extractor(res))

        return item 
Example #29
Source File: items.py    From ant_nest with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(
        self,
        item_class: typing.Type[Item],
        root_extractor: typing.Callable[[httpx.Response], typing.Sequence],
    ):
        self.root_extractor = root_extractor
        super().__init__(item_class) 
Example #30
Source File: items.py    From ant_nest with GNU Lesser General Public License v3.0 5 votes vote down vote up
def extract_items(self, res: httpx.Response) -> typing.Generator[Item, None, None]:
        for node in self.root_extractor(res):
            yield super().extract(node)