bvbrc.BVBRCResponse#
- class bvbrc.BVBRCResponse#
A BVBRCResponse object.
Inherits from requests.Response and adds some additional properties and methods to make interacting with a response from the BV-BRC API more convenient.
- close()#
Releases the connection back to the pool. Once this method has been called the underlying
rawobject must not be accessed again.Note: Should not normally need to be called explicitly.
- classmethod from_response(response: Response)#
Create a BVBRCResponse instance from a requests.Response object
Parameters#
- response: requests.Response
A requests response object that the BVBRCResponse will be created from.
Returns#
- BVBRCResponse
A BVBRCResponse object containing all the properties and contents of the requests.Response object it was derived from.
- iter_content(chunk_size=1, decode_unicode=False)#
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
chunk_size must be of type int or None. A value of None will function differently depending on the value of stream. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk.
If decode_unicode is True, content will be decoded using the best available encoding based on the response.
- iter_lines(chunk_size=512, decode_unicode=False, delimiter=None)#
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.
Note
This method is not reentrant safe.
- json(**kwargs)#
Returns the json-encoded content of a response, if any.
- Parameters:
**kwargs – Optional arguments that
json.loadstakes.- Raises:
requests.exceptions.JSONDecodeError – If the response body does not contain valid json.
- raise_for_status()#
Raises
HTTPError, if one occurred.
- to_pandas() pandas.DataFrame#
Convert the response content to a pandas DataFrame if possible.
The following return formats can be converted to a pandas DataFrame:
JSON (application/json)
SOLR_JSON (application/solr+json)
CSV (text/csv)
TSV (text/tsv)
EXCEL (application/vnd.openxmlformats)
Returns#
- pandas.DataFrame
The response content parsed into a pandas DataFrame.
Raises#
- ImportError
If pandas cannot be imported.
- ToDataFrameError
If the response content is in a format that cannot be converted to a pandas DataFrame.
Examples#
Search for recently collected E. coli genomes and convert the response into a pandas DataFrame:
>>> import bvbrc as bv >>> genome = bv.GenomeClient() >>> response = genome.search( ... genome.collection_year > 2015, ... species="Escherichia coli", ... genome_quality="Good", ... select=["genome_id", "genome_name", "collection_year", "host_name"], ... limit="max", ... return_format=bv.ReturnFormat.CSV ... ) >>> df = response.to_pandas() >>> print(df.head()) genome_id genome_name collection_year host_name 0 562.160986 Escherichia coli FG92-1 2018 NaN 1 562.160987 Escherichia coli FG31-1 2018 NaN 2 562.160990 Escherichia coli B19429 2019 NaN 3 562.161162 Escherichia coli 495R2 2018 Fly 4 562.161166 Escherichia coli 520R 2018 Fly
- to_polars() polars.DataFrame#
Convert the response content to a polars DataFrame if possible.
The following return formats can be converted to a polars DataFrame:
JSON (application/json)
SOLR_JSON (application/solr+json)
CSV (text/csv)
TSV (text/tsv)
EXCEL (application/vnd.openxmlformats)
Note
Polars would typically parse BV-BRC genome IDs as floats when reading a response in CSV or TSV format, so this method includes a schema override to force genome IDs to be parsed as strings.
Returns#
- polars.DataFrame
The response content parsed into a polars DataFrame.
Raises#
- ImportError
If polars cannot be imported.
- ToDataFrameError
If the response content is in a format that cannot be converted to a polars DataFrame.
Examples#
Search for recently collected E. coli genomes and convert the response into a polars DataFrame:
>>> import bvbrc as bv >>> genome = bv.GenomeClient() >>> response = genome.search( ... genome.collection_year > 2015, ... species="Escherichia coli", ... genome_quality="Good", ... select=["genome_id", "genome_name", "collection_year", "host_name"], ... limit="max", ... return_format=bv.ReturnFormat.CSV ... ) >>> df = response.to_polars() >>> print(df.head()) shape: (5, 4) ┌────────────┬─────────────────────────┬─────────────────┬───────────┐ │ genome_id ┆ genome_name ┆ collection_year ┆ host_name │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 ┆ str │ ╞════════════╪═════════════════════════╪═════════════════╪═══════════╡ │ 562.160986 ┆ Escherichia coli FG92-1 ┆ 2018 ┆ null │ │ 562.160987 ┆ Escherichia coli FG31-1 ┆ 2018 ┆ null │ │ 562.160990 ┆ Escherichia coli B19429 ┆ 2019 ┆ null │ │ 562.161162 ┆ Escherichia coli 495R2 ┆ 2018 ┆ Fly │ │ 562.161166 ┆ Escherichia coli 520R ┆ 2018 ┆ Fly │ └────────────┴─────────────────────────┴─────────────────┴───────────┘
- write_file(filepath: str | PathLike)#
Write the response content to the specified file path.
Parameters#
- filepath: str | PathLike
A path to the file where the contents of the response will be written to.
Examples#
Download all the annotated protein sequences for a genome in FASTA format and save to a file:
>>> import bvbrc as bv >>> gf = bv.GenomeFeatureClient() >>> response = gf.search( ... genome_id="511145.12", # genome ID for a reference E. coli genome, ... annotation="PATRIC", # only get PATRIC annotations (and not RefSeq ones) ... feature_type="CDS", # only get coding sequence annotations ... limit="max", ... return_format=bv.ReturnFormat.PROTEIN_FASTA ... ) >>> response.write_file("511145.12.fasta") # writes FASTA response to file
- property all_results_received: bool#
Whether or not all of the possible results for the query were received.
This is based on the “Content-Range” attribute of the repsonse header. For example, if 0-25 results out of 100 were received, then this will be False. On the other hand, if 0-25 results out of 25 possible results were received, then this will be True.
Whether or not all possible results are received will be based on the limit that was set in the submitted request. If no limit is provided BV-BRC has a default limit of 25. Additionally, BV-BRC seems to have a maximum limit of 25,000.
- property apparent_encoding#
The apparent encoding, provided by the charset_normalizer or chardet libraries.
- property content#
Content of the response, in bytes.
- property content_range: tuple[int, int, int] | None#
The “Content-Range” attribute of the response header as a tuple of three integers: start index, stop index (not inclusive), and total possible results.
For example, if “Content-Range” is “0-25/100” then this property will return a value of (0, 25, 100), which indicates that the first 25 out of 100 possible results were received.
If the “Content-Range” attribute is not found in the response header, then this property will be None.
- cookies#
A CookieJar of Cookies the server sent back.
- elapsed#
The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the
streamkeyword argument.
- encoding#
Encoding to decode with when accessing r.text.
- headers#
Case-insensitive Dictionary of Response Headers. For example,
headers['content-encoding']will return the value of a'Content-Encoding'response header.
- history#
A list of
Responseobjects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.
- property is_permanent_redirect#
True if this Response one of the permanent versions of redirect.
- property is_redirect#
True if this Response is a well-formed HTTP redirect that could have been processed automatically (by
Session.resolve_redirects()).
- property links#
Returns the parsed header links of the response, if any.
- property next#
Returns a PreparedRequest for the next request in a redirect chain, if there is one.
- property ok#
Returns True if
status_codeis less than 400, False if not.This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is
200 OK.
- raw#
File-like object representation of response (for advanced usage). Use of
rawrequires thatstream=Truebe set on the request. This requirement does not apply for use internally to Requests.
- reason#
Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”.
- request#
The
PreparedRequestobject to which this is a response.
- property return_format: ReturnFormat | None#
The return format of the response content, as specified in the “Content-Type” header. If the “Content-Type” header is not found or does not contain a valid return format, then this will be None.
- status_code#
Integer Code of responded HTTP Status, e.g. 404 or 200.
- property text#
Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
charset_normalizerorchardet.The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set
r.encodingappropriately before accessing this property.
- url#
Final URL location of Response.