Python client for DataStream Direct API
Project description
DataStream Direct Python Client
A Python client library for connecting to and querying the DataStream Direct API.
Installation
pip install datastream-direct
Quick Start
from datastream_direct import connect
# Connect to the API
connection = connect(
username="your_username",
password="your_password",
host="your_host",
port=5432,
database="your_database"
)
# Get cursor and execute query
cursor = connection.cursor()
cursor.execute("SELECT * FROM well_combined LIMIT 10")
results = cursor.fetchall()
# Results will be a list of tuples
for row in results:
print(row)
# Close the connection
connection.close()
Pandas DataFrame Integration
from datastream_direct import connect, fetch_frame
import pandas as pd
# Connect
conn = connect(
username="user",
password="pass",
host="localhost",
port=5432,
database="mydb"
)
# Get results as a DataFrame with proper type conversion
df = fetch_frame(conn.cursor(), "SELECT * FROM well_combined LIMIT 100")
print(df.dtypes) # Shows proper column types
print(df.head())
# Clean up
conn.close()
API Reference
Functions
connect(username, password, host, port, database)
Create a connection to the DataStream Direct API.
Parameters:
username(str): Authentication usernamepassword(str): Authentication passwordhost(str): Database hostport(int): Database portdatabase(str): Database name
Returns: DatastreamDirectConnection instance
Raises:
ValueError: If any required parameter is invalidAuthenticationError: If authentication failsConnectionError: If connection fails
Example:
from datastream_direct import connect
connection = connect(
username="user",
password="pass",
host="data-api.energydomain.com",
port=443,
database="energy_domain"
)
fetch_frame(cursor, query)
Execute a query and return results as a pandas DataFrame with proper type conversion.
Parameters:
cursor(DatastreamDirectCursor): Cursor instancequery(str): SQL query string
Returns: pandas.DataFrame with properly typed columns
Example:
from datastream_direct import connect, fetch_frame
connection = connect(username="user", password="pass", ...)
cursor = connection.cursor()
# Get results as a DataFrame
df = fetch_frame(cursor, "SELECT * FROM well_combined LIMIT 100")
print(df.dtypes) # Shows proper column types
data_stream_direct_to_spotfire_types(dataframe, column_metadata)
Set Spotfire-specific data types for a pandas DataFrame.
Parameters:
dataframe(pandas.DataFrame): A pandas DataFrame to apply Spotfire types tocolumn_metadata(List[DataStreamDirectColumnMetadata]): List of column metadata objects describing the columns in the DataFrame
Returns: None (modifies the DataFrame in-place)
Raises:
ImportError: If the Spotfire package is not available
Note: This function is only available if the Spotfire package is installed.
Example:
from datastream_direct import connect, data_stream_direct_to_spotfire_types
import pandas as pd
connection = connect(username="user", password="pass", ...)
cursor = connection.cursor()
cursor.execute("SELECT * FROM well_combined LIMIT 100")
cursor.fetchall()
df = pd.DataFrame(cursor.rows, columns=[col.name for col in cursor.metadata])
data_stream_direct_to_spotfire_types(df, cursor.metadata)
Classes
DatastreamDirectConnection
Connection class for managing API connections.
Methods:
cursor(): Create a new cursor for executing queriesclose(): Close the connection and clean up resources
Properties:
is_closed(bool): Check if the connection is closed
DatastreamDirectCursor
Cursor class for executing SQL queries and retrieving results.
Methods:
execute(sql): Execute a SQL queryfetchall(): Fetch all results from the last executed queryclose(): Close the cursor and clean up resources
Properties:
metadata: Column metadata from the last executed queryis_closed(bool): Check if the cursor is closed
ConnectionConfig
Configuration dataclass for connecting to the DataStream Direct API.
Attributes:
username(str): Username for authenticationpassword(str): Password for authenticationhost(str): Hostname or IP address of the DataStream Direct serviceport(int): Port number (must be between 1 and 65535)database(str): Name of the database to connect to
Methods:
get_base_url(): Get the base URL for the connection
Raises:
ValueError: If any parameter is invalid or empty
Example:
from datastream_direct import ConnectionConfig
config = ConnectionConfig(
username="user",
password="pass",
host="data-api.energydomain.com",
port=443,
database="energy_domain"
)
base_url = config.get_base_url()
QueryResult
Result of a SQL query execution. Supports iteration over rows.
Attributes:
headers(List[str]): List of column namesrows(List[Tuple[Any, ...]]): List of tuples containing row dataresults_metadata(Optional[Dict[str, Any]]): Optional metadata about the query results
Example:
from datastream_direct import QueryResult
result = QueryResult(
headers=["id", "name"],
rows=[(1, "Alice"), (2, "Bob")]
)
print(len(result)) # 2
for row in result:
print(row)
Exceptions
DataStreamDirectError
Base exception class for all DataStream Direct errors. All exceptions raised by the client inherit from this class.
Attributes:
message(str): The error messageerror_code(Optional[str]): Optional error code if provided
Example:
from datastream_direct import connect, DataStreamDirectError
try:
connection = connect(...)
except DataStreamDirectError as e:
print(f"Error: {e.message}")
if e.error_code:
print(f"Error Code: {e.error_code}")
AuthenticationError(DataStreamDirectError)
Raised when authentication fails. This exception is raised when the provided credentials are invalid or when the authentication process fails.
Example:
from datastream_direct import connect, AuthenticationError
try:
connection = connect(username="user", password="wrong", ...)
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
ConnectionError(DataStreamDirectError)
Raised when connection to the API fails. This exception is raised when there are network issues, the service is unavailable, or when attempting to use a closed connection.
Example:
from datastream_direct import connect, ConnectionError
try:
connection = connect(...)
# Later, try to use closed connection
cursor = connection.cursor()
except ConnectionError as e:
print(f"Connection error: {e.message}")
QueryError(DataStreamDirectError)
Raised when query execution fails. This exception is raised when a SQL query fails to execute, either due to syntax errors, permission issues, or other query-related problems.
Example:
from datastream_direct import QueryError
try:
cursor.execute("INVALID SQL")
except QueryError as e:
print(f"Query failed: {e.message}")
APIError(DataStreamDirectError)
Raised when the API returns an error response. This exception is raised for general API errors that don't fall into other specific error categories.
Attributes:
message(str): The error messagestatus_code(Optional[HttpStatus]): HTTP status code if availableerror_code(Optional[str]): Optional error code if provided
Example:
from datastream_direct import APIError
try:
cursor.execute("SELECT * FROM nonexistent")
except APIError as e:
print(f"API error: {e.message}")
if e.status_code:
print(f"Status code: {e.status_code}")
Error Handling
The library provides specific exception classes for different error scenarios:
DataStreamDirectError: Base exception classAuthenticationError: Authentication failuresConnectionError: Connection issuesQueryError: SQL execution failuresAPIError: General API errors
Example:
from datastream_direct import connect, AuthenticationError, QueryError
try:
connection = connect(username="user", password="pass", ...)
cursor = connection.cursor()
cursor.execute("SELECT * FROM table")
results = cursor.fetchall()
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except QueryError as e:
print(f"Query failed: {e}")
finally:
connection.close()
Configuration
Logging
The library uses Python's standard logging module. To enable debug logging:
import logging
logging.basicConfig(level=logging.DEBUG)
Note: For connection configuration details, see the ConnectionConfig class in the API Reference section above.
License
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file datastream_direct-0.1.2.tar.gz.
File metadata
- Download URL: datastream_direct-0.1.2.tar.gz
- Upload date:
- Size: 28.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4a91b704b3803616be322cac11522218ffc0b84ca7ae671e62162ccc876fa67f
|
|
| MD5 |
f29dc78969db73ad7c916c6e34ba3a49
|
|
| BLAKE2b-256 |
d41cdb1cea3c7b25f95a49abb7e6713145339e2b7fcf1313de5ce112a8bdb830
|
File details
Details for the file datastream_direct-0.1.2-py3-none-any.whl.
File metadata
- Download URL: datastream_direct-0.1.2-py3-none-any.whl
- Upload date:
- Size: 27.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
71d15bf6dd964a13594b26c6c4a7eb0c5f7625fc0caa8ac7c7383320e281f790
|
|
| MD5 |
e297f94750a130e87261413d1665a7c0
|
|
| BLAKE2b-256 |
0954e13633258b7ceed9df9e2be244d639c6454337041b16fc2fabbd3ff3a5bc
|