Install and Authenticate the Python SDK
This page is suitable for developers who call NexusFlow through Python scripts. Once completed, you should be able to establish a controlled client session, verify that the account can access the platform, and read the workspace metadata available for the current account.
Before you start, please prepare:
- Python 3.10 or later; the current package metadata explicitly lists Python 3.10, 3.11, and 3.12;
- Platform root address, such as
https://nexusflow.example.com; - A valid account, or access token provided by a trusted system;
- When the target environment uses a private certificate authority, the corresponding CA certificate package;
- The account has permissions for at least one scheduled operation. Successful authentication only means that the identity is valid, but it does not mean that all spaces, models or jobs can be accessed.
For the permission determination sequence and resource boundaries, see Authentication and Permissions.
Confirm Package Name and Installation Source
The Python distribution package name is nexusflow-sdk, and the import name in the code is nexusflow_sdk. During installation, the currently declared running dependencies will also be parsed, including requests and websocket-client.
The installation source is determined by your delivery method.
Install the Delivered Wheel
If your administrator or release process provided you with wheel, install the file directly:
python -m pip install "/path/to/nexusflow_sdk-VERSION-py3-none-any.whl"
Replace the example path and VERSION with the actual file name. Do not guess server-side compatibility from the file name, but also check the delivery instructions.
Install from a Configured Package Index
Use only after the administrator has confirmed that nexusflow-sdk has been published to the current Python package index:
python -m pip install nexusflow-sdk
The source code repository itself cannot prove that this version already exists in a public index. This page does not specify unconfirmed warehouse addresses or version numbers.
Install from Local Source
When you need to develop or debug the SDK, execute in the source code directory:
cd /path/to/nexusflow-sdk
python -m pip install -e .
After installation, first verify that the public entrance can be imported:
python -c "from nexusflow_sdk import NexusFlowClient; print('SDK import ok')"
Production scripts should use a standalone virtual environment with verified actual versions documented in dependency lock files. Don't let production jobs temporarily upgrade the SDK on every launch.
Use Environment Variables to Save Connection Information
The example uses the following environment variables:
NEXUSFLOW_BASE_URL=https://nexusflow.example.com
NEXUSFLOW_USERNAME=<您的用户名>
NEXUSFLOW_PASSWORD=<由密钥服务注入的密码>
NEXUSFLOW_TIMEOUT_SECONDS=30
NEXUSFLOW_CA_BUNDLE=/path/to/company-ca.pem
NEXUSFLOW_CA_BUNDLE is only required if the target environment uses a private CA. The platform address should be the root address with http:// or https://, without appending /api/, Workbench path, model ID or job ID. The SDK will handle the ending /.
Environment variables are just example handoffs. The production environment prefers to use the key storage of the operating system, container platform or continuous integration system, and inject it when starting the process; do not write the above content into the source code, submit it to the warehouse, or print the complete environment variables. Directly entering the password environment variable in the shared terminal may also enter the command history. You should use the safe injection method provided by the platform.
Create a Minimal Client
The construction parameters of NexusFlowClient are all keyword parameters:
| Parameters | Required | Description |
|---|---|---|
base_url | Yes | Platform root address |
token | No | Access token already exists; parameter name is not access_token |
refresh_token | No | Refresh token paired with access token |
username | No | Used for delayed login and re-login after token refresh failure |
password | No | Supplied as a pair with username |
timeout | No | Timeout seconds used for single authentication, REST request and some real-time connections, default 30.0 |
session | No | Custom requests.Session for certificate, proxy or connection pool configuration |
Minimal example using username and password:
from __future__ import annotations
import os
from nexusflow_sdk import NexusFlowClient
def require_env(name: str) -> str:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"缺少环境变量:{name}")
return value
with NexusFlowClient(
base_url=require_env("NEXUSFLOW_BASE_URL"),
username=require_env("NEXUSFLOW_USERNAME"),
password=require_env("NEXUSFLOW_PASSWORD"),
timeout=float(os.getenv("NEXUSFLOW_TIMEOUT_SECONDS", "30")),
) as client:
workspace_types = client.meta.list_workspace_types(scope="access")
print(f"认证成功,可访问工作台空间数:{len(workspace_types)}")
Passing the account password to the constructor will not immediately send the login request. The first request that requires authentication will automatically log you in. If you want to detect account errors as early as possible before executing other logic, you can explicitly call:
client = NexusFlowClient(base_url=base_url, timeout=30)
try:
client.login(username, password)
finally:
client.close()
client.login() will get the token immediately, but the public method returns None. Do not treat its return value as a token object.
Understand Authentication and Token Lifecycle
Username and Password
When using username and password, the SDK logs in to the platform token interface and saves the access token, optional refresh token, and account credentials in the memory of the current client object. Account credentials are retained so that you can log in again if the refresh token is no longer available; the SDK does not automatically write them to disk.
If the security policy does not allow the password to be retained within the process for a long time, the external credential service should obtain the token pair and then use the existing token method to create the client. Either way, do not log the full response from the request headers, client authentication object, or token interface.
Already Have Access Token
The constructor's token represents the access token:
with NexusFlowClient(
base_url=require_env("NEXUSFLOW_BASE_URL"),
token=require_env("NEXUSFLOW_ACCESS_TOKEN"),
refresh_token=os.getenv("NEXUSFLOW_REFRESH_TOKEN") or None,
timeout=30,
) as client:
workspace_types = client.meta.list_workspace_types(scope="access")
The capability boundaries are as follows:
- Only
tokenis provided: the SDK can initiate requests, but the access token cannot be automatically restored after it expires; - Both
tokenandrefresh_tokenare provided: you can try to refresh after receiving the authentication failure response; - Only
refresh_tokenis provided: the current public process will not exchange it for an access token first, and the first request will fail due to lack of access token and account password; - Provide
tokenand provide the account password at the same time: when the access token expires, you can use the account password to log in again, even if the token is not refreshed.
A token can only be used in the platform environment on which it was issued. Do not copy test environment tokens to the production environment, and do not infer users, permissions, or expiration times based on the token text.
Auto Refresh
The SDK does not parse the expiration time of the access token, nor does it actively refresh it on a clock basis. After receiving 401 in a normal REST request, if the client holds a refresh token or account password, the SDK will:
- Prioritize using refresh token to request new access token;
- If the refresh fails and the account password is still retained, log in again;
- Retry the original request with the updated access token.
If a refresh response returns a new refresh token, the current client object will also update it. When a retry fails, the error will be handed over to the caller for handling and will not be retried indefinitely. The job live connection also attempts the same refresh process once when the handshake returns 401 or 403; a persistent 403 should still be troubleshooted as a permissions or result availability issue.
There are currently no top-level refresh() methods exposed for NexusFlowClient. Application code should generally rely on the automatic refresh described above and not create long-term dependencies by importing undocumented authentication implementations. The token validity period and revocation policy are determined by the server and cannot be hard-coded in the client code.
End Session and "Log Out"
It is recommended to use a context manager:
with NexusFlowClient(base_url=base_url, token=access_token) as client:
...
client.close() is called when leaving the with block, closing the HTTP session and connection pool. close() can also be called explicitly in finally.
There is currently no logout() or token revocation method exposed by the SDK. close() only closes the local network session and does not notify the server to revoke the token, nor does it promise to clear the token and account credentials in the client object. When it is necessary to end local use, the client object should be discarded and the token saved by the application should be cleared; when the server needs to be revoked, the management process disclosed by the platform should be used. Closing the connection should not be equated with logging out.
If a custom requests.Session is passed to the constructor, client.close() will also close the session. Don't hand over a shared session to the client that will continue to be used by other code.
Configure HTTPS, Certificates, and Timeouts
Production environments should use HTTPS. By default requests.Session will verify certificates; do not turn verification off to bypass certificate errors. When using a private CA, create a custom session and specify the CA certificate bundle:
from __future__ import annotations
import os
import requests
from nexusflow_sdk import NexusFlowClient
session = requests.Session()
session.verify = os.environ["NEXUSFLOW_CA_BUNDLE"]
with NexusFlowClient(
base_url=os.environ["NEXUSFLOW_BASE_URL"],
username=os.environ["NEXUSFLOW_USERNAME"],
password=os.environ["NEXUSFLOW_PASSWORD"],
timeout=30,
session=session,
) as client:
print(len(client.meta.list_workspace_types(scope="access")))
NexusFlowClient There is currently no verify= construct parameter; certificate verification should be configured through a custom session or system trust store. The above session.verify works on login and REST requests. The job results use a separate WebSocket client. The current SDK does not expose independent WebSocket CA parameters; when you need to access the wss:// address using a private CA, you should let the CA enter the system trust chain of the running environment and verify the result connection separately before release.
timeout should be the number of seconds greater than 0. It binds a single authentication or HTTP request, not the total deadline for an entire batch, job run, or result stream. Long processes such as job waiting and result reading also use their own bounded timeouts. The current HTTP layer does not automatically retry network errors except for authentication refresh; see Batch Automation and Error Handling for timeout and retry strategies.
Run Authentication Verification
Currently, the public client does not have a dedicated method for "reading the current user", so the workspace metadata interface is used below to verify the authentication. Even if an empty list is returned, as long as the request is successful, it means that the token has been accepted; the empty list means that the current account has no accessible workspace.
Save the following code as verify_nexusflow_auth.py:
from __future__ import annotations
import os
import sys
import requests
from nexusflow_sdk import APIError, AuthError, NexusFlowClient
def require_env(name: str) -> str:
value = os.getenv(name, "").strip()
if not value:
raise RuntimeError(f"缺少环境变量:{name}")
return value
def positive_timeout() -> float:
value = float(os.getenv("NEXUSFLOW_TIMEOUT_SECONDS", "30"))
if value <= 0:
raise ValueError("NEXUSFLOW_TIMEOUT_SECONDS 必须大于 0")
return value
def main() -> None:
session = requests.Session()
ca_bundle = os.getenv("NEXUSFLOW_CA_BUNDLE", "").strip()
if ca_bundle:
session.verify = ca_bundle
with NexusFlowClient(
base_url=require_env("NEXUSFLOW_BASE_URL"),
timeout=positive_timeout(),
session=session,
) as client:
# 显式登录,使账号或密码错误在这里立即暴露。
client.login(
require_env("NEXUSFLOW_USERNAME"),
require_env("NEXUSFLOW_PASSWORD"),
)
items = client.meta.list_workspace_types(scope="access")
workspace_types = [
str(item["type"])
for item in items
if isinstance(item, dict) and item.get("type")
]
print(f"认证成功,可访问工作台空间数:{len(workspace_types)}")
if workspace_types:
print("工作台空间:" + ", ".join(workspace_types[:10]))
if __name__ == "__main__":
try:
main()
except AuthError as exc:
print(f"认证失败:{exc}", file=sys.stderr)
raise SystemExit(2)
except APIError as exc:
print(
f"平台接口失败(HTTP {exc.status_code}):{exc}",
file=sys.stderr,
)
raise SystemExit(3)
except requests.exceptions.SSLError as exc:
print(f"HTTPS 证书校验失败:{exc}", file=sys.stderr)
raise SystemExit(4)
except requests.exceptions.Timeout as exc:
print(f"连接或读取超时:{exc}", file=sys.stderr)
raise SystemExit(5)
except requests.exceptions.ConnectionError as exc:
print(f"无法连接平台:{exc}", file=sys.stderr)
raise SystemExit(6)
The script only outputs the workspace type, not the password or token. Real automation jobs should also log unexpected configuration errors as controlled failures, but do not troubleshoot by printing the complete environment or client objects.
Common Authentication and Connection Issues
AuthError When Logging In
Shortest troubleshooting path:
- Confirm that
base_urlis the platform root address, with the correct protocol and no duplicate/api/; - Use the same account to confirm the username, password and user validity period;
- Confirm that the target environment is indeed the platform to which the account belongs, and that test and production addresses are not mixed;
- Check if the proxy or gateway replaces the token interface response with an HTML error page;
- Only HTTP phase, target host, and desensitization errors are logged, not passwords or tokens in responses.
AuthError will be thrown when the login interface returns an error status, does not return an access token, or fails to refresh and re-login.
Request Returns 401
401 indicates that the current access token was not accepted. First determine whether the client meets the refresh conditions:
- When there is only an access token, re-obtain a new token from a trusted credential source;
- When there is a refresh token or account password, confirm whether the automatic refresh also fails and throws
AuthError; - Do not perform unbounded retries on the same expired token;
- Confirm that the token comes from the environment corresponding to the current
base_url.
When there is no refresh capability, a normal request of 401 will be returned as APIError with status_code=401; if the initial login or refresh process fails, it will be returned as AuthError.
Request Returns 403
403 usually means that the identity has been recognized, but the current user does not have permission to perform the operation. Check workspace authorization, model or job ownership, organizational roles, and interfaces to see if they require higher permissions. Repeated logins or repeated refreshes usually do not resolve insufficient permissions. The server's permissions will be determined. Do not use a shared administrator account to bypass it.
Connection Timed Out, Refused, or Certificate Failed
ConnectionError: Check domain name resolution, port, proxy, network access policy and platform health status;Timeout: Confirm whether the single request timeout is too short, and distinguish between connection timeout and slow server processing;SSLError: Checks whether the host name matches, whether the certificate has expired, whether the full certificate chain is available, and whether the private CA has been added to the trust;- REST is accessible but the result stream fails: Check that HTTPS corresponds to
wss://, that the reverse proxy allows WebSocket, and that the private CA enters the system's chain of trust.
The underlying network exception comes from requests.exceptions, and the current SDK will not uniformly package it into NexusFlowError. The caller should capture the SDK business exception and requests network exception respectively.
Manage Multiple Environments
Test, pre-release and production environments should be configured separately:
- Independent
base_url, account or token, CA certificate and timeout; - Clear environment name, production scripts should refuse to run when the environment is not specified, and do not default to production;
- Minimum privilege account to prevent multiple automated jobs from sharing a high-privilege credential;
- Independent client instances and contexts, without reusing sessions, access tokens or refresh tokens between environments;
- The environment name and host name in the desensitized log make it easy to locate the platform on which the error occurred, but the request header and secret value are not output.
Non-secret configurations such as addresses can go into version control, passwords and tokens can only come from the corresponding environment's key store. When switching environments, run the verification script on this page first, and then write the model or create the job.
Next Steps
- To walk through a complete simulation, please read Run Your First Simulation with the Python SDK.
- To create, read and save models, please read Read, Edit, and Save Models with the SDK.
- To start the job and consume the results, please read Run Jobs and Read Results with the SDK.
- To design retries, batch execution and partial failure handling, please read Batch Automation and Error Handling.
- To understand token requests and responses directly, read Authentication and Token Refresh.