Python Client¶
The Python client library, the pyami-3forge package, connects a Python program to 3forge Enterprise to run SQL, write tables, subscribe to live updates, publish objects, and register commands.
Overview¶
The package has 3 ways in, all built on one native client:
- The native client,
pyami.rt.ami_client, documented on this page. - The query builder, which runs a
SELECTwithout writing SQL. - The DB-API driver and SQLAlchemy dialect, for
pandas.read_sqland SQLAlchemy.
The model behind it, clusters, connections, and the callback thread, is in Concepts.
Prerequisites¶
- Python 3.14, on 64-bit Linux or Windows.
- The package, installed from the Python Package Index with
pip install pyami-3forge. It installs pandas and SQLAlchemy with it; the client needs pandas to start. - A client certificate the server accepts. See Connecting and Securing a Client.
Connecting¶
A program creates one AmiClient, adds a listener, and adds a cluster with a configuration for each connection it uses.
-
Configure the connections and add the cluster:
-
Check that
client.sql("N1", "SELECT 1")returns{'1': array([1], dtype=int32)}.
The listener can be any object: the client calls a method only if the object has it. Exceptions raised in a callback are printed and do not reach your code.
| Configuration | Arguments |
|---|---|
AmiDatabaseConfig |
port_or_service, use_ssl, username, password, then optionally query_timeout_ms=30000, query_limit=10000, db="" |
AmiSubscriptionConfig |
port_or_service, use_ssl, then optionally username="", password="" |
AmiPublicationConfig |
port_or_service, use_ssl, login_id, options. All 4 are required; pass 0 for no options, or int(Options.UNIX_MODE) for a Relay on Windows (see Checking what happened to a published object) |
Check the first query, not the connection
A client whose certificate the server refuses is still reported as connected: add_cluster returns, on_connect fires, and sql() returns {}. The only other sign is an on_log error, Synchronous operation failed: ....
Running SQL¶
To run SQL from Python, call sql(cluster, statement), which returns a dictionary.
| Statement | Returns |
|---|---|
| A query | One key per column. Text columns are lists; other columns are numpy arrays (see Column types) |
| An insert, update, or delete that changed rows | {'rows_affected': n}, plus generated_keys for a table with an AUTOGEN index |
| DDL, a change that changed no rows, or a cluster name the client does not have | {} |
| A failed statement | {'error': '[shard 0] 009-EXCEPTION: Unknown table: Quotes'}, with no other keys |
Check that the result holds the columns, not an error key: sql() does not raise on a server error. To load a result into pandas, pass it to pandas.DataFrame, or use the query builder with as_frame=True.
{}has several meanings: it is returned for DDL, for a change that changed no rows, for a cluster name the client does not have (with anon_logerrorFailed to execute SQL query: Cluster not found [<name>]), and when the server refused the certificate.- Several statements run in one call:
sql()accepts statements separated by;. If a later one fails, the earlier ones stay committed and the result holds only the error. - A NULL string comes back as
"", the same as an empty string.
sql_async(cluster, statement, callback) runs the statement in the background and calls callback(result) on the callback thread. Requests on one cluster are queued and run in order, so several threads can call sql() at once.
Results stop at 10,000 rows without saying so
A query returns at most query_limit rows, 10,000 by default, and nothing in the result shows that rows were left out. Raise query_limit on the configuration, or count first with SELECT count(*).
How each call reports errors¶
The client reports a failure in one of 3 ways, depending on the call:
| Call | On a server error |
|---|---|
sql(), sql_insert(), sql_bulk_insert(), sql_replace() |
Returns {'error': '...'} for an error the server or the table check reports |
| The same 3 write calls, for data they cannot send | Raises RuntimeError, e.g: All columns must have the same row count |
select(), run() |
Raises RuntimeError |
publish(), publish_batch(), remove(), register_command() |
Returns None; the Relay's reply arrives in on_message_received or on_log (see Checking what happened to a published object) |
Writing tables¶
3 calls upload rows in bulk. Each takes the cluster, a table name, and the data as a dictionary of equal-length lists or numpy arrays, or a pandas DataFrame.
| Call | Missing table | Existing table |
|---|---|---|
sql_insert(cluster, table, data, create_table_if_not_exist=True) |
Creates it | The data's columns must match the table's exactly; extra or missing columns return an error |
sql_bulk_insert(cluster, table, data) |
Returns {'error': '... Table not found for Upload: <table>'} |
Appends the rows. Columns missing from the data are stored as 0 or 0.0 |
sql_replace(cluster, table, data, suffix='') |
Creates it, with suffix as its table options |
Deletes every row, keeping the table and its indexes, then inserts the new rows. Columns missing from the data are stored as 0 or 0.0 |
Check that the call returned rows_affected, the number of rows written.
A column mismatch on sql_insert lists every difference, and is also logged to on_log as an error:
When sql_insert creates a table, it types each column from its values: str as String, float as Double, int as Long, and bool as Boolean. batch_size is accepted and ignored.
suffix takes table options without the word USE, e.g: suffix='RefreshPeriodMs="500"'. It is used only when sql_replace creates the table. A suffix the server does not accept fails with Table not found for Upload: <table>, and no table is created.
sql_replace deletes the rows before it writes
sql_replace empties the table, then inserts the new rows, so:
- A call with 0 rows leaves the table empty, and returns the number of rows it deleted as
rows_affected. - A call the server rejects after emptying the table, such as one with a column the table does not have or a value of the wrong type, returns the error and leaves the table empty, e.g:
{'error': "... Column not found in table '<table>': <column>"}. - A
PersistEngine="HISTORICAL"suffix fails, sosql_replacecannot create a historical table.
Check that the data's columns match the table before calling it. Data that cannot be sent at all, such as columns of unequal length, raises before the table is touched.
To load a historical table, create it yourself, then insert:
Data that does not upload as expected¶
- Empty data writes nothing:
sql_insertandsql_bulk_insertreturn{}for columns with no rows;sql_replaceempties the table. - DataFrame values change type: a missing string is stored as
"", a missing float as0.0, and a datetime column becomes aStringcolumn, with values such as2026-01-02 00:00:00. int8values wrap: a numpyint8column becomes aBytecolumn, and a value of-1is stored as255.datetime64arrays are refused: the call fails withColumn '<name>' must be a list or ndarray, so convert them to integers first.
Subscribing to live updates¶
subscribe(cluster, tables, sync=False) delivers each table's current rows, then every change, to on_update. unsubscribe(cluster, tables, sync=False) stops them.
Check that rows holds the table's rows once on_update has run for each of them.
- Updates merge by
id: an update carries only the changed columns, and a delete carries none. - The update is a copy: its values stay valid after the callback returns.
on_disconnectfires for the Center connection only.sync=Truedoes not wait for the rows: it returns once the server has answered, before the rows have all reachedon_update.- A subscription takes table names only: filters and column lists are C++ only.
How updates arrive is described in Live updates.
A mistyped table name is not reported
Subscribing to a table that does not exist reports success through on_subscribe and delivers nothing. Check the name with SELECT TableName FROM __TABLE.
Publishing objects¶
publish(cluster, type, id, fields, seqnum=0, expires_on_ms=0) sends one object to the Relay. The type names the table, and the id identifies the row.
fields: a dictionary or a list of(name, value)pairs. Aboolis sent as1or0and stored as aLong.publish_batch: takes a list of(id, fields)pairs, a list of dictionaries each with an"id"key, a dictionary of{id: fields}, or a DataFrame. DataFrame rows are published with no id, so each row is a new row and the table has noIcolumn.remove(cluster, id, type): deletes the object. The id comes before the type.
The target table must suit the object. A new type creates its table; an existing table needs an I column and a column for every field. See Publishing and the acknowledgement.
Checking what happened to a published object¶
The publish calls return None. The Relay's reply arrives in on_message_received, with status 0 when the Relay accepted the message:
Against a Relay running on Windows, the reply arrives instead in on_log, as a warning that starts Received message with unknown type:, because the Relay ends each message with a carriage return. Set Options.UNIX_MODE on the Relay connection when the server may run on Windows, and the replies reach on_message_received:
Without the option, S=0 in the logged reply means accepted:
Acceptance does not show that the row was stored: query the table to confirm it.
Leave expires_on_ms at 0
publish takes expires_on_ms. A time in the future stops the object being stored at all, and a time in the past is ignored.
A publish to a cluster name the client does not have is dropped, and logged to on_log as an error: Failed to send message: Cluster not found [<name>]. The same applies to register_command.
Registering commands¶
A command adds an action to the right-click menu of a real-time table panel in the Web. When a user runs it, the client calls on_command, and the program answers with send_command_response. Register it on the Relay connection.
Check that SELECT ID FROM __COMMAND lists restart_feed once the Relay replies OK, command accepted.
- A command lasts as long as the connection: it is removed when the client disconnects, so register it again after a reconnect.
- Level 0 is never registered:
set_level(0)is acknowledged, but the command does not appear. Leave the level unset; the server then stores level 1.
What a command call receives¶
A user selects rows in a real-time table panel, right-clicks, and runs the command. A command with help text shows it first, with a "Submit" button. The Web then waits for the program's reply and shows its message, done in the example above.
on_command receives:
| Argument | Value |
|---|---|
request_id |
Identifies this call; pass it to send_command_response |
cmd |
The command id |
user_name |
The Web user who ran the command |
object_type |
The selected row's table; empty for a command that takes several rows |
object_id |
The selected row's I value; empty for a command that takes several rows |
params |
A dict of strings: S, the Web session id, and o, the row's internal id. For a command that takes several rows, V replaces o |
- A command takes one row by default: run with several rows selected, it receives only one of them.
set_select_mode(min, max)takes several rows: withset_select_mode(1, 10),params["V"]is a JSON list with one entry per selected row, e.g:[{"O":"o2","o":37000370},{"O":"o3","o":37000371}], whereOis the row'sIvalue.set_where_clauselimits the rows: withset_where_clause("qty > 5"), the command appears in the menu only when the selected rows match.- Against a Relay on Windows, set
UNIX_MODE: without it, the call is logged toon_logasReceived message with unknown type: E@...,on_commandis not called, and the Web waits for a reply. See Checking what happened to a published object.
Disconnecting¶
remove_cluster(cluster, sync=False) closes the cluster's connections:
Check that the program then exits normally.
What this does not support¶
- Filtering or projecting a subscription: the Python client subscribes by table name only, and has no
get_table_schema. - Grouping statements in a transaction: every statement commits on its own.
- Awaiting calls with asyncio: asynchronous calls take callbacks, which run on the client's callback thread.
- Running on Python other than 3.14, or on macOS: the package ships compiled modules for CPython 3.14 on 64-bit Windows and 64-bit Linux with glibc 2.34 or later. On any other platform,
pip install pyami-3forgeinstalls an old 1.5.3 release instead, which this page does not describe.