OpenResty Edge™ Python SDK User Manual

Welcome to the user manual for OpenResty Edge™ Python SDK.

Installation

The Python SDK for OpenResty Edge depends on Python3. Please make sure you have Python 3.6 or above installed.

You can install the Python SDK like any other Python module:

  1. Open a Linux terminal or Windows command prompt window.

  2. Enter the following command to install the Python SDK:

    pip3 install openresty-edge-sdk --index-url https://pypi.org/simple
    

If you want to install a specific version of the Python SDK, you can append the version number to the module name:

pip3 install openresty-edge-sdk==1.2.39 --index-url https://pypi.org/simple

After the installation command is successfully executed, you can verify whether it has been installed correctly as follows:

$ python3
>>> from edge2client import Edge2Client
>>> client = Edge2Client('https://EDGE_ADMIN_HOST:EDGE_ADMIN_PORT', 'USERNAME', 'PASSWORD')
>>> client.login()
True
>>> client.get_version()
{'waf': {'waf_version': '3.3.4-1' ...}
>>> exit()

After typing client.login(), if the output is True, it means it has been installed correctly. If your Edge Admin is using a self-signed certificate (which is the default), you also need to call client.set_ssl_verify(False) before client.login(). You can then use client.get_version() to view the version information of OpenResty Edge.

In addition, you can find the release notes of this Python SDK here.

So far the installation is complete, you can refer to the subsequent content in this document to realize more complex operations.

Synopsis

import sys
import time
from edge2client import Edge2Client

def get_client():
    client = Edge2Client(host, username, password)
    # if a self-signed certificate is causing SSL verification failure, you can uncomment the following line.
    # client.set_ssl_verify(False)
    ok = client.login()

    return client

if __name__ == '__main__':
    try:
        client = get_client()
    except Exception as e:
        print("failed to get client: ", str(e))
        sys.exit(1)

    try:
        app_ids = client.get_all_apps()
    except Exception as e:
        print("failed to get all apps: ", str(e))
        sys.exit(1)

    for app_id in app_ids:
        client.use_app(app_id)
        if client.pending_changes() > 0:
            ret = client.new_release()
            if ret:
                print('release ok app id: ' + str(app_id))
            else:
                print('release failed: ' + str(app_id))
            time.sleep(1)

Methods

MethodDescription
Edge2ClientThis method is used to initialize the SDK client.
set_ssl_verifySets whether to perform SSL verification when accessing Edge Admin, verification is performed by default.
loginThis method is used for logging into OpenResty Edge in order to perform subsequent operations.
use_appThis method is used to specify the application ID for the current instance operation.
new_appThis method is used to add a new HTTP application.
put_appThis method is used to modify the basic information of an HTTP application.
get_appThis method is used to retrieve related information of the HTTP application, including domain, tags, and the group it belongs to, etc.
put_app_configThis method is used to modify the configuration of the HTTP application.
get_app_configThis method is used to obtain the configuration information of the specified HTTP application.
del_appThis method deletes the specified HTTP application based on the provided app_id.
search_appThis method is used to search HTTP applications based on the specified domain.
search_http_app_by_keywordThis method is used to search for HTTP applications based on domain names or application names.
search_upstream_by_ipThis method is used to search upstream information through IP addresses.
search_k8s_upstream_by_ipThis method is used to search for upstream in Kubernetes by IP.
search_upstream_by_nameThis method is used to search for upstream by name.
search_k8s_upstream_by_nameThis method is used to search for Kubernetes upstream by specifying names.
search_k8s_upstreamThis method allows users to search for upstream on Kubernetes by specifying the namespace, service name, and port number.
search_k8s_upstream_historyThis method searches the upstream history on Kubernetes based on the namespace, service name, and port number.
get_all_appsThis method is used to get information of all applications.
new_upstreamThis method is used to add a new upstream, and the return value is the id of the newly added upstream.
put_upstreamThis method is used to modify upstream information.
get_upstreamThis method is used to get upstream information.
del_upstreamThis method is used to delete an upstream.
get_all_upstreamsThis method is used to acquire all detailed information about upstreams.
new_k8s_upstreamThis method is used to add a new global Kubernetes upstream, and will return the ID of the newly created k8s upstream.
copy_upstream_to_k8s_upstreamThis method is used to copy a regular upstream to a Kubernetes upstream.
put_k8s_upstreamThis method is used to modify the upstream information on Kubernetes.
get_k8s_upstreamThis method is used to obtain information on the k8s upstream.
del_k8s_upstreamThis method is used to delete the Kubernetes upstream.
get_all_k8s_upstreamsThis method is used to get information of all Kubernetes upstreams.
new_ruleThis method is used to create new page rules, including various types of rules, such as: General rules, Proxy rules, WAF rules, and Cache rules. You can also specify the prerequisite conditions for rule execution.
put_ruleThis method is used to modify page rules.
get_ruleThis method is used to get page rules according to the rule ID.
del_ruleThis method is used to delete the page rule corresponding to rule_id.
get_all_rulesThis method is used to obtain all page rules for the specified application ID (app_id).
reorder_rulesThis method is used to adjust the order of the rules.
get_all_rules_by_app_domainThis method is used to get the corresponding page rules according to the specified application domain.
get_all_rules_by_upstream_ipThis method is used to retrieve all associated page rules based on the upstream IP address.
get_all_waf_rulesThis method is used to get the corresponding WAF rules based on the specific application id (app_id).
get_global_actions_used_in_appThis method is used to get custom rule IDs associated with the application ID (app_id).
set_cert_keyThis method is used to add a new SSL certificate and provides an option to manually upload the certificate.
set_le_certThis method is used to add a Let’s Encrypt certificate.
put_cert_keyThis method is used to update SSL certificate (manual upload method).
put_le_certThis method is used to update the Let’s Encrypt certificate.
get_le_certThis method is used to obtain the issuance status of a Let’s Encrypt certificate.
get_cert_keyThis method is used to obtain the content of the SSL certificate.
get_all_cert_keysThis method is used to obtain all the certificate information of the current application.
del_cert_keyDeletes the certificate information associated with the given certificate_id.
new_elThis method is used to add custom edge language code.
new_releaseThis method is used to release updates for the current application.
pending_changesThis method is used to query the number of changes pending for release.
sync_statusPublish new changes to all nodes.
node_sync_statusThis method is used to get the synchronization details of each node.
get_healthcheck_statusThis piece of code is used to get health check information for each node.
add_app_userThis method is used to add application-level users.
update_app_userThis method is used to update user information at the application level.
get_app_userThis method is used to get user information at the application level, including username, permissions, etc.
del_app_userThis method is used to delete a user from a specific application.
get_all_app_usersThis method is used to get all users at the current application level. Users of a specific application can also be obtained by specifying the app_id.
add_user_for_all_appsThis method is used to add a user for all applications.
add_all_users_for_appThis method is used to add all global users to the specified application.
new_cache_purge_taskThis method is used to add a new condition purge task. The trigger conditions are passed in array format, and multiple trigger conditions can be set. Only when all set conditions are met at the same time, the corresponding purge task will be triggered.
get_cache_purge_taskThis method retrieves the details of a task by specifying the refresh task id.
get_all_cache_purge_tasksThis method is used to obtain detailed information about all cache purge tasks.
del_cache_purge_taskThis method is used to delete the refresh task of a specified ID.
new_waf_whitelistThis method is used to add new WAF whitelist rules.
update_waf_whitelistThis method is used to update WAF whitelist rules.
get_waf_whitelistThis method is used to obtain the whitelist rules of WAF.
del_waf_whitelistPerforming this operation will delete the specified WAF whitelist rule.
get_all_waf_whitelistsThis method is used to get all WAF whitelist rules.
new_app_dymetricsCreates a new application dynamic metric.
put_app_dymetricsThis method is used to modify the dynamic metrics of the application.
del_app_dymetricsThis method is used to delete the dynamic metrics of a specified application.
get_app_dymetricsThis method is used to get the dynamic metrics of the specified application.
get_all_app_dymetricsThis method is used to obtain all the dynamic metric information of a specified application.
get_app_dymetrics_dataThis method is used to obtain the dynamic metrics data of the application, and it returns the data of the last 30 minutes by default.
get_app_metricsThis method is used to get the HTTP request status metrics and network transmission and reception metrics of the application. By default, it will get data for the last 30 minutes.
new_ip_listAdd a new application-level IP list.
put_ip_listThis method is used to modify the specified IP list.
del_ip_listThis method is used to delete the specified IP list.
get_ip_listThis method is used to view specific IP list.
append_to_ip_listThis method is used to append IPs to specific IP list.
remove_from_ip_listThis method is used to remove IPs from specific IP list.
node_monitorThis method is used to obtain CPU and memory load-related information of a network node.
new_global_dymetricsThis method is used to create global dynamic metrics.
put_global_dymetricsThis method is used to modify global dynamic indicators.
del_global_dymetricsThis method is used to delete the specified global dynamic metric.
get_global_dymetricsThis method is used to get the specified global dynamic metrics.
get_all_global_dymetricsThis method is used to get all global dynamic metrics.
get_global_dymetrics_dataThis method is used to get global dynamic metrics data, the default range is the most recent 30 minutes.
use_dns_appThis method is used to switch the DNS application that the current instance operates.
new_dns_appThis method is used to create a new DNS application.
put_dns_appThis method is used to modify the relevant information of the DNS application.
get_dns_appThis method is used to get the relevant information of the DNS application.
del_dns_appThis method is used to delete a specified DNS application.
new_dns_recordThis method is used to add a DNS record.
put_dns_recordThis method is used to modify DNS records.
get_dns_recordThis method is used to obtain DNS records.
del_dns_recordThis method is used to delete a DNS record.
new_global_upstreamThis method is used to add a new upstream and returns the id of the newly created global upstream.
update_global_upstreamThis method is used to update global upstream information.
get_global_upstreamThis method is used to retrieve global upstream information.
del_global_upstreamThis method is used to delete the global upstream.
get_all_global_upstreamsThis method is used to get all the upstream information.
new_global_k8s_upstreamThis method is used to create a new global Kubernetes upstream and returns the ID of the newly created upstream.
put_global_k8s_upstreamThis method is used to modify the information of the global Kubernetes upstream.
fetch_global_k8s_upstreamThis method is used to fetch global Kubernetes upstream information.
del_global_k8s_upstreamThis method is used to delete the global k8s upstream.
get_all_global_k8s_upstreamsThis method is used to get all Kubernetes upstream information.
set_global_cert_keyUsed to add a global SSL certificate.
put_global_cert_keyThis method is used to modify the global SSL certificate.
get_global_cert_keyThis method is used to get the SSL certificate information associated with cert_id.
del_global_cert_keyThis method is used to delete a specified global SSL certificate.
add_global_userThis method is used to add a global user.
search_global_userThis method is used to search for global user information based on the username.
get_all_global_usersThis method is used to get the information of all global users.
new_global_ruleThis method is used to add new global rules.
put_global_ruleThis method is used to modify the global rule.
get_global_ruleThis method is used to obtain global rule information.
get_global_action_by_nameThis method is used to obtain the corresponding global custom action based on the given application name.
get_all_global_rulesThis method is used to obtain all global rules.
del_global_ruleThis method is used to delete the global rule.
new_global_varThis method is used to create a new global variable.
put_global_varThis method is used to modify global variables.
get_global_varThis method is used to get global variables.
get_all_global_varsThis method is used to get all global variables.
del_global_varThis method is used to delete a global variable by its ID.
get_global_ngx_configThis method is used to get global nginx configuration information.
set_global_ngx_configThis method sets the global nginx configuration information.
get_global_misc_configThis method is used to obtain global miscellaneous configuration information.
set_global_misc_configThis method is used to set global miscellaneous configuration information.
get_request_id_statusThis method is used to query the status of the request id.
enable_request_idThis method is used to activate the request id function.
disable_request_idThis method is used to disable the request ID feature.
new_global_waf_ruleThis method is used to add a new global WAF rule.
put_global_waf_ruleThis method is used to modify global WAF rules.
get_global_waf_ruleThis method retrieves a global WAF rule set by using the provided rule set ID (rule_id).
del_global_waf_ruleThis method is used to delete global WAF rules.
get_all_global_waf_rulesThis method is used to retrieve all global WAF rules.
new_global_actionThis method is used to add a new global custom action.
put_global_actionThis method is used to modify the global custom action.
get_global_actionThis method is used to obtain the global custom action.
del_global_actionThis method is used to delete a specified global custom action.
count_global_actionsThis method is used to get the total number of global custom actions.
get_all_global_actionsThis method is used to obtain all global custom actions.
upload_static_fileThis method is used to upload static files.
get_static_fileThis method is used to obtain the configuration of a specified static file.
del_static_fileThis method is used to delete uploaded static files.
new_cluster_groupThis method is used to add a new cluster group.
put_cluster_groupThis method is used to modify cluster group information.
get_cluster_groupThis method is used to obtain detailed information of the cluster group.
get_all_cluster_groupsThis method is used to obtain information on all cluster groups.
del_cluster_groupThis method is used to delete cluster group information.
put_proxy_ruleThis method is used to modify upstream proxy rules.
new_global_k8sThis method is used to add new k8s cluster connection parameters.
put_global_k8sThis method is used to modify the connection parameters of a Kubernetes cluster.
get_global_k8sThis method is used to get the connection parameter information of a Kubernetes cluster.
get_k8s_service_detailThis method is used to obtain the service-related information defined in the k8s cluster.
get_all_global_k8sThis method is used to obtain the id of all global Kubernetes clusters.
del_global_k8sThis method is used to delete the connection parameters of the k8s cluster.
update_proxy_ruleUpdate the specified upstream proxy rule.
new_global_ip_listThis method is used to create a new global IP list.
put_global_ip_listThis method is used to modify the specified global-level IP list.
del_global_ip_listThis method is used to delete a specified global IP list.
get_global_ip_listThis method is used to get the specified global IP list.
append_to_global_ip_listThis method is used to append IPs to specified global IP list.
remove_from_global_ip_listThis method is used to remove IPs from specified global IP list.
new_user_varThis is a function for adding new user-level variables.
put_user_varThis method is used to modify user-level variables.
get_user_varThis method is used to obtain user-level variables.
del_user_varThis method is used to delete user-level variables.
decode_request_idThis method is used to decode request_id to get information such as app_id.
search_waf_logThis method is used to get the WAF log through the request id.
get_versionThis method is used to get the version information of Admin, Admin DB, Log Server, Log Server DB and WAF.
add_api_tokenThis method is used to generate an API Token.
get_api_tokenThis method is used to acquire an API token.
del_api_tokenThis method is used to delete a specified API Token.
get_all_gateway_tagThis method is used to obtain tags for all gateway clusters.
get_all_gatewayThis method is used to get the information of all gateway clusters.
add_gatewayThis method is used to create a new gateway cluster.
del_gatewayThis method is used to delete a specified gateway cluster.
get_all_nodesThis method is used to obtain all gateway nodes.
get_nodeThis method retrieves the node information corresponding to the provided node ID.
get_node_by_mac_addressThis method is used to retrieve the detailed information of a node based on the node’s hardware ID.
put_nodeThis method is used for updating node information.
del_nodeThis method is used to delete a specific node according to its node ID.
lmdb_backupThis method is used to trigger the backup of LMDB. If the backup is successful, the method will return True. If the backup fails, it will return a dict information containing the failed Node nodes, where the key is the Node ID and the value is the reason for the failure. You can confirm whether the backup is successful by calling the node_sync_status interface. If the backup_time of the node in this interface is greater than the call time of the lmdb_backup() method, then it can be considered that the backup of this node has been successfully executed.
get_global_cert_referencedThis method is used to get a list of applications that use the specified global certificate.
get_all_partition_lua_moduleThis method is used to obtain all Lua modules of the specified partition.
get_partition_lua_moduleThis method is used to get the specified lua module in the specified partition.
new_partition_lua_moduleThis method is used to add a new Lua module to the specified partition.
put_partition_lua_moduleThis method is used to edit a specific lua module in a specified partition.
del_partition_lua_moduleThis method is used to delete a specific lua module within a specified partition.
conv_crl_to_lua_moduleThis method is used to convert CRL files into Lua modules.
get_all_candidate_nodeThis method is used to get all nodes waiting for approval. Subsequently, these nodes can be approved to join the specified cluster by calling the approve_candidate_node interface.
approve_candidate_nodeApproves the node with the MAC address mac_address to join the gateway cluster with the ID gateway_id.
get_waf_logsThis method is used to retrieve the WAF logs of the specified application.
get_dos_logsThis method is used to retrieve the Dos logs of the specified application.
get_global_page_templateThis method is used to get the specified global page template.
get_all_global_page_templatesThis method is used to get all global page templates.
del_global_page_templateThis method is used to delete the specified global page template.
new_global_page_templateThis method is used to create a new global page template.
put_global_page_templateThis method is used to update the specified global page template.
get_app_basic_auth_user_groupThis method is used to get the information of the specified Basic Auth user group in the specified application.
get_all_app_basic_auth_user_groupsThis method is used to get the information of all Basic Auth user groups in the specified application.
del_app_basic_auth_user_groupThis method is used to delete the information of the specified Basic Auth user group in the specified application.
new_app_basic_auth_user_groupThis method is used to create a Basic Auth user group in the specified application.
put_app_basic_auth_user_groupThis method is used to update the information of the specified Basic Auth user group in the specified application.
get_app_basic_auth_userThis method is used to get the information of the specified user in the Basic Auth user group of the specified application.
get_app_basic_auth_users_in_groupThis method is used to get the information of all users in the Basic Auth user group of the specified application.
del_app_basic_auth_userThis method is used to delete the information of the specified user in the Basic Auth user group of the specified application.
new_app_basic_auth_userThis method is used to create a user in the Basic Auth user group of the specified application.
put_app_basic_auth_userThis method is used to update the information of the specified user in the Basic Auth user group of the specified application.
new_acme_providerThis method is used to add a new ACME provider record. It returns the id of the newly added record.
put_acme_providerThis method is used to modify an ACME provider record.
get_acme_providerThis method is used to retrieve an ACME provider record.
get_all_acme_providersThis method is used to retrieve records of all ACME providers.
del_acme_providerThis method is used to delete an ACME provider record.
get_acme_logsThis method is used to retrieve logs for a specified ACME certificate, up to 100 entries.
get_node_error_logsThis method is used to retrieve error logs for the Edge Node.
get_admin_error_logsThis method is used to retrieve error logs for the Edge Admin.
get_log_server_error_logsThis method is used to retrieve error logs for the Edge Log Server.
get_http_app_error_logsThis method is used to retrieve error logs for a specified HTTP application.

Method Documentation


Edge2Client

client = Edge2Client(host, username, password, api_token=None)

This method is used to initialize the SDK client.

Parameters

NameData TypeRequiredDescription
hoststringYesThe address of edge-admin, including protocol and port
usernamestringYesUsername for logging into edge-admin
passwordstringYesPassword for logging into edge-admin
api_tokenstringNoAccess token

Returns

  • Returns an edge2client.Edge2Client object.

Examples

  1. When the address of Edge Admin is https://127.0.0.1:443, and the Edge2Client object is initialized using the username username and password password:

    from edge2client import Edge2Client
    
    client = Edge2Client('https://127.0.0.1:443', 'username', 'password')
    
  2. When initializing the Edge2Client object using the API Token api_token:

    from edge2client import Edge2Client
    
    client = Edge2Client('https://127.0.0.1:443', None, None, "api_token")
    

set_ssl_verify

set_ssl_verify(verify)

Sets whether to perform SSL verification when accessing Edge Admin, verification is performed by default. When your Edge Admin is using a self-signed certificate, it is necessary to disable SSL verification.

Parameters

NameData TypeRequiredDescription
verifyboolYesWhether to enable SSL verification

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.set_ssl_verify(False)
ok = client.login()

login

ok = login()

This method is used for logging into OpenResty Edge in order to perform subsequent operations.

Returns

  • True: indicates a successful login.
  • False: indicates a failed login.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)

ok = client.login()

use_app

ok = use_app(app_id)

This method is used to specify the application ID for the current instance operation.

Returns

  • True: Application ID specification was successful.
  • False: Application ID specification failed.

Examples

The following example demonstrates how to change the application ID for the current instance operation to 10.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 10
client.use_app(app_id)

new_app

app_id = new_app(domains, label)

This method is used to add a new HTTP application.

Parameters

NameData TypeRequiredDescription
domainslistYesDomains required by the application
labelstringYesIdentifier name of the application
cluster_groupslistNoCluster groups where the application is located

Returns

  • app_id: Returns the ID of the newly created application, its data type is number.

Examples

The following example shows how to create an HTTP application with the domain orig.foo.com, the label origin site for foo.com, and the application is located in the cluster group [1].

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = client.new_app(
    domains=['orig.foo.com'],
    label='origin site for foo.com',
    cluster_groups = [1])

put_app

ok = put_app(app_id, domains, label, cluster_groups=None, offline=None)

This method is used to modify the basic information of an HTTP application.

Parameters

NameData TypeRequiredDescription
app_idnumberYesUnique identifier of the application
domainslistYesList of domains of the application
labelstringYesName of the application
cluster_groupslistNoList of cluster groups the application resides in
offlineboolNoOnline/offline status of the application, True represents offline, False represents online

Returns

  • True: Indicates modification was successful.
  • False: Indicates modification failed.

Examples

The following example demonstrates how to modify the domain of a previously created application (with domain orig.foo.com) to *.foo.com.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 10
client.use_app(app_id)

ok = client.put_app(app_id, domains=['*.foo.com'], label='foo.com')

get_app

data = get_app()

This method is used to retrieve related information of the HTTP application, including domain, tags, and the group it belongs to, etc.

Returns

  • data: Returns a dict type data.

Examples

The following example demonstrates how to retrieve the application information with an app_id of 1.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_app()

put_app_config

put_app_config(app_id, limiter)

This method is used to modify the configuration of the HTTP application.

Parameters

Parameter NameData TypeRequiredDescription
app_idnumberYesThe id of the application
limiterdictYesThe limiter configuration of the application
enable_websocketboolNoWhether to enable websocket

Returns

  • True: The configuration was successfully modified.
  • False: The configuration modification failed.

Examples

The following example shows how to modify the configuration of the application with an app_id of 1.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1

res = client.put_app_config(app_id=app_id,
                            limiter={
                                        'max_uri_args': 130,
                                        'max_post_args': 140,
                                        'max_req_headers': 150,
                                        'check_post_args_type': True
                                    },
                            enable_websocket=True)

get_app_config

data = get_app_config(app_id)

This method is used to obtain the configuration information of the specified HTTP application.

Parameters

NameData TypeRequiredDescription
app_idnumberYesId of the application to be queried

Returns

  • data: Returns a dictionary (dict) type of data.

Examples

The following example shows how to obtain the configuration information of the application with id 1:

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1

data = client.get_app_config(app_id)

del_app

success = del_app(app_id)

This method deletes the specified HTTP application based on the provided app_id.

Parameters

NameData TypeRequiredDescription
app_idnumberYesUnique id of the application to be deleted

Returns

  • True: Indicates the application was deleted successfully.
  • False: Indicates the application deletion failed.

Examples

The following example demonstrates how to delete an application with an app_id of 1.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1

success = client.del_app(app_id)

search_app

data = search_app(app_domain)

This method is used to search HTTP applications based on the specified domain.

Parameters

NameData TypeRequiredDescription
app_domainstringYesThe application domain to search
pagenumberNoThe page of the results to return, default is 1
pagesizenumberNoThe number of results to return per page, default is 20

Returns

  • data: Returns a list type of result, each element of which is related information about the application.

Examples

The following example searches for HTTP applications with orig.foo.com as the domain.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_app(app_domain='orig.foo.com')

search_http_app_by_keyword

data = search_http_app_by_keyword(keyword, page, pagesize)

This method is used to search for HTTP applications based on domain names or application names.

Parameters

Parameter NameData TypeRequiredDescription
keywordstringYesThe keyword to search, will be searched in both domain name and application name
pagenumberNoThe page number of the returned results, default value is 1
pagesizenumberNoThe number of entries returned on each page, default value is 20

Returns

  • data: This return value is of list type, each element contains related information of the application.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_http_app_by_keyword('orig.foo.com')
data = client.search_http_app_by_keyword('orig.foo.com', 1, 2)
data = client.search_http_app_by_keyword('origin')

search_upstream_by_ip

data = search_upstream_by_ip(ip, page=1, pagesize=20)

This method is used to search upstream information through IP addresses.

Parameters

Parameter NameData TypeNecessaryDescription
ipstringYesThe IP address to be searched
pagenumberNoThe expected result page number, default is the first page
pagesizenumberNoThe number of results returned per page, default is 20

Returns

  • data: Returns a list type of data, each element in the list represents detailed information of an upstream.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_upstream_by_ip('1.1.1.1')

search_k8s_upstream_by_ip

data = search_k8s_upstream_by_ip(ip, page, pagesize)

This method is used to search for upstream in Kubernetes by IP.

Parameters

NameData TypeRequiredDescription
ipstringYesThe IP to be searched
pagenumberNoThe page number of the returned results, default is 1 if not specified
pagesizenumberNoNumber of results returned per page, default is 20 if not specified

Returns

  • data: A list type variable, which contains information about upstream in Kubernetes.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_k8s_upstream_by_ip('1.1.1.1')

search_upstream_by_name

data = search_upstream_by_name(name, page, pagesize)

This method is used to search for upstream by name.

Parameters

Parameter NameData TypeRequiredDescription
namestringYesThe name of the upstream to be searched
pagenumberNoThe page number of the returned results, defaults to 1 if not specified
pagesizenumberNoThe number of items per page in the returned results, defaults to 20 if not specified

Returns

  • data: This is a list type, each element represents an upstream information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_upstream_by_name('test')

search_k8s_upstream_by_name

data = search_k8s_upstream_by_name(name, page, pagesize)

This method is used to search for Kubernetes upstream by specifying names.

Parameters

ParameterData TypeRequiredDescription
namestringYesThe name of the Kubernetes upstream to be searched
pagenumberNoThe page number of the search results, default is 1
pagesizenumberNoNumber of search results per page, default is 20

Returns

  • data: This is of list type, containing information of multiple Kubernetes upstreams.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_k8s_upstream_by_name('test')

search_k8s_upstream

data = search_k8s_upstream(namespace, service, port, page, pagesize, type_list)

This method allows users to search for upstream on Kubernetes by specifying the namespace, service name, and port number.

Parameters

NameData TypeRequiredDescription
namespacestringnoThe name of the namespace to search
servicestringnoThe name of the service to search
portnumbernoThe port number of the service to search
pagenumbernoThe page number of the return results, default value is 1
pagesizenumbernoThe number of entries per page of return results, default value is 20
type_listlistnoThe list of upstream types to search, including k8s_http and k8s_global, all types are searched by default

Returns

  • data: list type, each element in the list is the information of Kubernetes upstream.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = self.client.search_k8s_upstream(port = 80, service = "test-hello", namespace = "default")

search_k8s_upstream_history

data = search_k8s_upstream_history(page, pagesize, start_time, end_time)

This method searches the upstream history on Kubernetes based on the namespace, service name, and port number.

Parameters

NameData TypeRequiredDescription
pagenumberNoThe page number of the returned results, default is 1 if not specified
pagesizenumberNoThe number of entries returned, default is 20 if not specified
start_timenumberNoThe start timestamp for the search
end_timenumberNoThe end timestamp for the search

Returns

  • data: The return value is of list type, with each element representing an update operation of Kubernetes upstream history.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.search_k8s_upstream_history(port = 80, service = "test-hello", namespace = "default")

get_all_apps

data = get_all_apps(detail)

This method is used to get information of all applications.

Parameters

Parameter NameData TypeRequiredDescription
detailboolNoWhether to return detailed information of each application, default is False

Returns

  • When the detail parameter is False, the function returns a Python object of type list, containing the basic information of all applications.
  • When the detail parameter is True, the function returns a Python object of type dict, keyed by the app id, containing all the app details.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

# Get basic information
apps = client.get_all_apps()

# Get detailed information
apps = client.get_all_apps(detail=True)

new_upstream

up_id = new_upstream(**kwargs)

This method is used to add a new upstream, and the return value is the id of the newly added upstream.

Parameters

NameData TypeMandatoryDescription
namestringYesThe name of the upstream
serverslistYesThe information of the upstream
sslboolNoWhether to use HTTPS protocol, default is False
health_checkerdictNoThe detailed configuration of health check, default is None
gidarrayYesList of group id, such as [1]

Servers Parameter

NameData TypeMandatoryDescription
domainstringNoThe domain of the upstream
ipstringNoThe IP address of the upstream. Note, at least one of the parameters domain and IP must be filled in
portstringYesThe port number of the upstream
weightnumberNoThe weight of the upstream, default is 1

Returns

  • up_id:The ID of the successfully created upstream.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = client.new_upstream(
    name='origin-upstream',
    servers=[
        {'ip': '172.22.31.1', 'port': 80},
        {'ip': '172.22.31.2', 'port': 80, 'weight': 2}
    ])

put_upstream

ok = put_upstream(**kwargs)

This method is used to modify upstream information.

Parameters

NameData TypeRequiredDescription
namestringYesDefines the name of the upstream
serverslistYesDetailed definition of upstream information
sslboolNoEnable HTTPS protocol, default is False
health_checkerdictNoConfigures the details for health checking, default is None
gidarrayYesList of user group ids, e.g., [1]

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = 1
ok = client.put_upstream(up_id,
    name='origin-upstream',
    servers=[
        {'domain': 'test.com', 'port': 8080},
        {'ip': '172.22.31.2', 'port': 8080, 'weight': 1}
    ],
    health_checker={
        'type': 'http',
        'http_req_uri': '/status',
        'http_req_host': 'test.com',
        'interval': 3,
        'interval_unit': 'sec',
        'timeout': 1,
        'fall': 3,
        'rise': 2,
        'valid_statuses': [200, 302],
        'report_interval': 3,
        'report_interval_unit': 'min'
    })

get_upstream

data = get_upstream(up_id)

This method is used to get upstream information.

Parameters

Parameter NameData TypeRequiredParameter Description
up_idstringNoID of the upstream

Returns

  • data: Returns upstream information of type dict.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = 1
data = client.get_upstream(up_id)

del_upstream

del_upstream(up_id)

This method is used to delete an upstream.

Parameters

NameData TypeRequiredDescription
up_idstringNoUnique identifier of the upstream

Returns

  • Returns True: Indicates the upstream was deleted successfully.
  • Returns False: Indicates the upstream deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = 1

ok = client.del_upstream(up_id)

In this example, we first import Edge2Client, then create an Edge2Client object, and log in with host, username, and password. Then, we try to delete the upstream with the identifier 1 using the del_upstream method.


get_all_upstreams

upstreams = client.get_all_upstreams()

This method is used to acquire all detailed information about upstreams.

Returns

  • upstreams: Returns a list type of data, which contains all upstream information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

upstreams = client.get_all_upstreams()

new_k8s_upstream

up_id = new_k8s_upstream(**kwargs)

This method is used to add a new global Kubernetes upstream, and will return the ID of the newly created k8s upstream.

Parameters

NameData TypeRequiredDescription
namestringYesName of the upstream
k8s_serviceslistYesInformation required when the upstream is a k8s service
sslboolNoWhether to use the HTTPS protocol, default is False
health_checkerdictNoDetailed configuration for health checking, default is None
gidarrayYesList of user group IDs, for example: [1]

k8s_services Parameters

NameData TypeRequiredDescription
k8snumberYesID of the k8s cluster
k8s_namespacestringYesNamespace of the k8s cluster
k8s_servicestringYesService of the k8s cluster
k8s_service_portnumberYesPort of the k8s cluster service

Returns

  • up_id: The ID of the newly created k8s upstream.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

k8s_up_id = client.new_k8s_upstream(
    name = 'k8s-upstream',
    k8s_services = [
        {
            'k8s' : 1,
            'k8s_namespace' : 'default',
            'k8s_service' : 'foo',
            'k8s_service_port' : 80,
        }
    ])

copy_upstream_to_k8s_upstream

k8s_up_id = copy_upstream_to_k8s_upstream(up_id, k8s_services, rules)

This method is used to copy a regular upstream to a Kubernetes upstream.

Parameters

NameData TypeRequiredDescription
up_idstringYesThe ID of the upstream to be copied
k8s_serviceslistYesInformation when the upstream is a Kubernetes service
rulesarrayNoTraverse the rules in rules, use the rules of the original upstream to migrate all to Kubernetes upstream, if this parameter is not provided, the function will by default find all rules of this app for traversal. Using this parameter can prevent the function from automatically finding all rules multiple times

Returns

  • up_id: The ID of the newly created Kubernetes upstream.

Examples

Example 1:

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = client.new_app(domains = ['orig.foo.com'], label = 'origin site for foo.com')

up_id = client.new_upstream(name = 'origin-upstream',
                            servers = [
                                {'ip': '172.22.31.1', 'port': 80},
                                {'ip': '172.22.31.2', 'port': 80, 'weight': 2}
                            ])

k8s_up_id = client.copy_upstream_to_k8s_upstream(up_id,
                            k8s_services = [
                                {
                                    'k8s' : 1,
                                    'k8s_namespace' : 'default',
                                    'k8s_service' : 'foo',
                                    'k8s_service_port' : 80,
                                }
                            ])

Example 2:


client.use_app(app_id)

rules = client.get_all_rules()

k8s_up_id = client.copy_upstream_to_k8s_upstream(up_id = up_id,
                            k8s_services = [
                                {
                                    'k8s' : 1,
                                    'k8s_namespace' : 'default',
                                    'k8s_service' : 'foo',
                                    'k8s_service_port' : 80,
                                }
                            ],
                            rules = rules)


put_k8s_upstream

ok = put_k8s_upstream(**kwargs)

This method is used to modify the upstream information on Kubernetes.

Parameters

NameData TypeRequiredDescription
namestringYesSpecifies the upstream name
k8s_serviceslistYesDetailed information required when the upstream is a k8s service
sslboolNoDetermines whether to use HTTPS, default is False
health_checkerdictNoConfigures specific parameters for health checking, default is None
gidarrayYesList of Group ID, for example [1]

Returns

  • True: Indicates modification was successful.
  • False: Indicates modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = 1
ok = client.put_k8s_upstream(up_id,
    name='k8s-upstream',
    k8s_services = [
        {
            'k8s' : 1,
            'k8s_namespace' : 'default',
            'k8s_service' : 'foo',
            'k8s_service_port' : 80,
        }
    ],
    health_checker={
        'type': 'http',
        'http_req_uri': '/status',
        'http_req_host': 'test.com',
        'interval': 3,
        'interval_unit': 'sec',
        'timeout': 1,
        'fall': 3,
        'rise': 2,
        'valid_statuses': [200, 302],
        'report_interval': 3,
        'report_interval_unit': 'min'
    })

get_k8s_upstream

data = get_k8s_upstream(up_id)

This method is used to obtain information on the k8s upstream.

Parameters

Parameter NameData TypeRequiredDescription
up_idstringYesID of the upstream

Returns

  • data: Returns a dict type of data.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = 1
data = client.get_k8s_upstream(up_id)

del_k8s_upstream

success = del_k8s_upstream(upstream_id)

This method is used to delete the Kubernetes upstream.

Parameters

NameData TypeRequiredDescription
upstream_idstringYesThe unique ID of the corresponding upstream

Returns

  • True: Indicates successful deletion.
  • False: Indicates failure of deletion.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

upstream_id = '1'
success = client.del_k8s_upstream(upstream_id)

get_all_k8s_upstreams

upstreams = client.get_all_k8s_upstreams()

This method is used to get information of all Kubernetes upstreams.

Returns

  • upstreams: Returns a list type of Kubernetes upstreams list.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

upstreams = client.get_all_k8s_upstreams()

new_rule

rule_id = new_rule(**kwargs)

This method is used to create new page rules, including various types of rules, such as: General rules, Proxy rules, WAF rules, and Cache rules. You can also specify the prerequisite conditions for rule execution.

Parameters

NameData TypeRequiredDescription
conditionlistNoRule conditions
conseqdict or listNoRule actions
waflistNoWAF rules
proxylistNoProxy rules
cachelistNoCache rules
contentlistNoContent rules
topnumberNo1: top rule, -1: bottom rule
ordernumberNoRule order, lower priority than top parameter
lastboolNoSkip all remaining page rules if this rule hits, default is False
reorderboolNoWhether to rebuild the order value, default is False
enableboolNoIf this option is set to False, the page rule will be disabled, default is True.

condition Parameter

NameData TypeRequiredDescription
varstring or arrayYesIf it’s a string type, fill in the variable name name. If it’s an array type, fill in the variable name name and parameter args.
opstringNoOperator, default is eq, i.e., string equal (equal)
valstringChoose one with valsstring type or array type, when specifying regex or wildcard type, pass [regex expression, 'rx'], [wildcard expression, 'wc']
valslistChoose one with valCollection of val

conseq Parameter

NameData TypeRequiredDescription
edge language built-in functionstringYesEdge language built-in function
parameters of edge language built-in functionlistYesParameters of edge language built-in function

conseq can be dict type or list type, below is an example of a dict type.

waf Parameter

NameData TypeRequiredDescription
rule_setslistNoDefault global user rule sets, the default value is an empty list
actionstringYesChoose one from log, 403 Forbidden, edge-captcha, redirect
thresholdstringNoChoose one from high, medium, low, none. Alternately choose sensitivity, sensitivity has higher priority. High sensitivity corresponds to low threshold, low sensitivity corresponds to high threshold
sensitivitystringNoChoose one from high, medium, low, none. Alternately choose threshold, sensitivity has higher priority. High sensitivity corresponds to low threshold, low sensitivity corresponds to high threshold
clearancenumberNoDuration after captcha is triggered, default value is 60 seconds
redirect_urlstringNoThe specified url when the action is redirect (redirection)
cross_requestsboolNoWhen set to True, cross-request mode is used, default is True
rule_sets_thresholdlistNoSet the sensitivity score for each rule set individually
scoreintegerNoWhen threshold or sensitivity choose none, you can customize the sensitivity score

proxy Parameter

Description of proxy array:

NameData TypeRequiredDescription
upstreamslistYesUpstream information
backup_upstreamslistYesBackup upstream node information
upstreams_el_codestrYesEdgelang setting upstream
timeoutnumberNoProxy timeout, default value is 3 seconds
connect_timeoutnumberNoConnection timeout, default value is 3 seconds
read_timeoutnumberNoRead timeout, default value is 3 seconds
send_timeoutnumberNoSend timeout, default value is 3 seconds
retriesnumberNoNumber of retries, default value is 1
retry_conditionlistNoRetry condition, default value is [“error”, “timeout”, “invalid_header”, “http_500”, “http_502”, “http_504”]. Options include http_503, http_403, http_404, http_429 and non_valueempotent (i.e., the method can be POST, LOCK, PATCH)
balancer_algorithmstringNoLoad balancing algorithm, default value is roundrobin. Other supported algorithms include hash and chash
balancer_varslistNoVariables that the load balancing algorithm depends on, this field needs to be filled in when the load balancing algorithm is set to hash or chash
multi_tiernumberNoMulti-tier network policy ID

upstreams Parameter

Description of upstreams and backup_upstreams array:

NameData TypeRequiredDescription
upstreamnumberYesID of the upstream
global_upstreamnumberYesID of the global upstream
k8s_upstreamnumberYesID of the k8s upstream
global_k8s_upstreamnumberYesID of the global k8s upstream
weightnumberNoWeight of the upstream, default value is 1

cache Parameter

NameData TypeRequiredDescription
cache_keylistYesCache key
default_ttlslistNoWhether to enable default cache, default value is None
browser_ttlnumberNoWhether to enable browser cache, default value is None
browser_ttl_unitstringNoBrowser cache unit, effective only when browser_ttl is set, default value is min
enable_globalboolNoWhether to enable cross-domain cache, default value is False
enforce_cacheboolNoWhether to enable always cache, default value is False
cluster_hashboolNoWhether to enable cluster cache, default value is False
disable_convert_headboolNoWhether to convert HEAD request method to GET, default value is True

Returns

  • rule_id: ID of the new rule.

Examples

Example 1: Create a new rule using dict type condition and action.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

condition = [
    {
        'var': 'host',
        'val': 'con.' + APEX
    },
    {
        'var': ['req-header', 'Referer'],
        'vals': [
            'foo.com',
            ['foo\d+', 'rx'],
            ['foo*', 'wc']
        ]
    }
]

conseq = {
    'enable-websocket': {},
    'redirect': {'url': '/cn/2017/', 'code': 302}
}

rule_id = client.new_rule(condition=condition, conseq=conseq)

Because dict type cannot sort itself and cannot set actions with duplicate names, so it is recommended to use the list type instead of the dict type as follows.

Example 2: Create a new rule using list type condition and action.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

condition = [
    {'var': 'host', 'val': 'con.' + APEX},
    {'var': ['req-header', 'Referer'], 'vals': [['foo\d+', 'rx'], 'foo.com']}
]

conseq = [
    {'set-proxy-header': {
        'header': 'Foo',
        'value': 'default'
    }},
    {'set-proxy-header': {
        'header': 'Host',
        'value': "orig"
    }},
    {'print': {
        'msg': 'hello'
    }}
]

rule_id = client.new_rule(condition=condition, conseq=conseq)

Example three: Enable WAF rule.

Create a custom WAF rule, and use this rule in the application.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

global_waf_rule_id = client.new_global_waf_rule(
    name='foo',
    code="uri-arg('foo') => waf-mark-risk(level: 'definite', msg: 'found foo');")

condition = [{'var': 'uri', 'op': 'prefix', 'val': '/foo'}]

waf_rule = {
    'rule_sets': [global_waf_rule_id],
    'action': '403 Forbidden', 'threshold': 'low'}

rule_id = client.new_rule(condition=condition, waf=waf_rule)

Example four: Enable proxy rule.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

up_id = client.new_upstream(
    name='origin-upstream',
    servers=[
        {'ip': '172.22.31.1', 'port': 80},
        {'ip': '172.22.31.2', 'port': 80, 'weight': 2}
    ])

k8s_up_id = client.new_k8s_upstream(
    name='k8s-upstream',
    k8s_services = [
        {
            'k8s' : k8s_id,
            'k8s_namespace' : 'default',
            'k8s_service' : 'test-hello',
            'k8s_service_port' : 80,
        }
    ])

ok = client.put_upstream(up_id,
    name='origin-upstream',
    servers=[
      {'ip': '172.22.31.1', 'port': 8080},
      {'ip': '172.22.31.2', 'port': 8080, 'weight': 1}
    ])

backup_up_id = client.new_upstream(
    name='backup-upstream',
    servers=[
        {'ip': '172.22.31.3', 'port': 80},
        {'ip': '172.22.31.4', 'port': 80, 'weight': 3}
    ])

proxy_rule = {
    'upstreams': [{'upstream': up_id, 'weight': 2}],
    'backup_upstreams': [{'upstream': backup_up_id}],
    'upstream_el_code': '',
    'retries': 2,
    "retry_condition": ["invalid_header", "http_500"],
    "balancer_algorithm": "hash",
    "balancer_vars": [
        {"name":"uri"},
        {
            "name":"uri-arg",
            "args":"foo"
        }
    ]
}

rule_id = client.new_rule(proxy = proxy_rule)

k8s_proxy_rule = {
    'upstreams': [{'k8s_upstream': k8s_up_id, 'weight': 2}],
    'upstream_el_code': '',
    'retries': 2,
    "retry_condition": ["invalid_header", "http_500"],
    "balancer_algorithm": "hash",
    "balancer_vars": [
        {"name":"uri"},
        {
            "name":"uri-arg",
            "args":"foo"
        }
    ]
}

k8s_rule_id = client.new_rule(proxy = k8s_proxy_rule)

Example five: Enable caching.

In this example, when the source of access IP is located in China (CN), caching rules will be implemented. The specific cache key includes the URL, query string, and the client’s source city.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

condition = [{'var': 'client-country', 'op': 'eq', 'val': 'CN'}]
# cache_key = ['uri', 'query-string', 'client-city']
# or
cache_key = [
    {'name': 'uri'},
    {'name':'query-string'},
    {'name': 'client-city', 'args': 'first-x-forwarded-addr'}
]

default_ttls = [
    {
        'ttl_unit': "min", 'status': 200, 'ttl': 1
    }, {
        'ttl_unit': "min", 'status': 301, 'ttl': 1
    }
]
cache_rule = {'cache_key': cache_key, 'default_ttls': default_ttls}

rule_id = client.new_rule(condition=condition, cache=cache_rule)

put_rule

ok = put_rule(**kwargs)

This method is used to modify page rules.

Parameters

NameData TypeRequiredDescription
conditionlistNoDefines the condition of the rule
conseqdict or listNoDefines the action of the rule
waflistNoDefines WAF rules
proxylistNoDefines proxy rules
cachelistNoDefines cache rules
contentlistNoDefines content rules
topnumberNoUsed to set the position of the rule, 1 indicates the top rule, -1 indicates the bottom rule
ordernumberNoUsed to set the order of the rule, priority is lower than the top parameter
lastboolNoIf this option is set to True, and this rule is hit, all remaining page rules will be skipped, default is False
enableboolNoIf this option is set to False, the page rule will be disabled, default is True.

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

from edge2client import Edge2Client
from edge2client.constants import OFF, ON

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

conseq = {
    'enable-websocket': {},
    'redirect': {'url': '/cn/2017/', 'code': 302},
    'user-code': {'el': 'true => say(\"hello\");'}
}

conseq['redirect']['url'] = '/cn/2018/'

ok = client.put_rule(rule_id=rule_id, condition=condition, conseq=conseq)

# disable the conditions in the page rules
ok = client.put_rule(rule_id=rule_id, condition=OFF, conseq=conseq)

get_rule

data = get_rule(rule_id)

This method is used to get page rules according to the rule ID.

Parameters

Parameter NameData TypeRequiredDescription
rule_idnumberYesID of the page rule

Returns

  • data: Returns a dict type page rule information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

rule_id = 1
data = client.get_rule(rule_id)

del_rule

success = del_rule(rule_id)

This method is used to delete the page rule corresponding to rule_id.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesThe unique identifier of the rule

Returns

  • True: Indicates the page rule was successfully deleted.
  • False: Indicates the deletion of the page rule failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

rule_id = 1
success = client.del_rule(rule_id)

get_all_rules

rules = get_all_rules(app_id)

This method is used to obtain all page rules for the specified application ID (app_id).

Parameters

NameData TypeRequiredDescription
app_idnumberNoThe designated application id. If not provided, the current application id is defaulted

Returns

  • Returns a list of rules. The type of each element in this list is consistent with the return type of the get_rule function.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_all_rules()

reorder_rules

ok = reorder_rules(orders)

This method is used to adjust the order of the rules.

Parameters

NameData TypeRequiredDescription
ordersdictYesThis dictionary defines the new order of the rules, where key represents rule ID, and value represents the order of the rule.

Returns

  • True: If the rule order is successfully adjusted.
  • False: If the rule order adjustment fails.

Examples

The following example shows how to swap the order of rule ID 2 and 3.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

new_orders = {
    1: 1,
    2: 3,
    3: 2,
}
data = client.reorder_rules(new_orders)

get_all_rules_by_app_domain

rules = get_all_rules_by_app_domain(domain)

This method is used to get the corresponding page rules according to the specified application domain.

Parameters

NameData TypeRequiredDescription
domainstringYesApplication’s domain

Returns

  • rules: A list type of rule sets.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_all_rules_by_app_domain('orig.foo.com')

get_all_rules_by_upstream_ip

rules = get_all_rules_by_upstream_ip(upstream_ip)

This method is used to retrieve all associated page rules based on the upstream IP address.

Parameters

NameData TypeRequiredDescription
upstream_ipstringYesSpecifies the upstream IP address

Returns

  • rules: This is a list type that contains all relevant rules.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

upstream_ip = '1.2.3.4'
data = client.get_all_rules_by_upstream_ip(upstream_ip)

for app_id, rules in data.items():
    print(app_id)

get_all_waf_rules

rules = get_all_waf_rules(app_id)

This method is used to get the corresponding WAF rules based on the specific application id (app_id).

Parameters

NameData TypeMandatoryDescription
app_idnumbernoThe id of the application, default is the current application id if not specified

Returns

  • rules: Return a list type of rule list.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_all_waf_rules()

get_global_actions_used_in_app

rule_ids = get_global_actions_used_in_app(app_id)

This method is used to get custom rule IDs associated with the application ID (app_id).

Parameters

NameTypeRequiredDescription
app_idnumberNoUnique identifier of the application

Returns

  • rule_ids: It returns a list, the elements of which are the unique IDs of each rule. If you need to get detailed information about the rules, you can query further based on these rule IDs. For details, please refer to the get_global_rule() method.

Examples

The following example shows how to get the IDs of all global rules.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
rule_ids = client.get_global_actions_used_in_app(app_id)

set_cert_key

cert_id = set_cert_key(**kwargs)

This method is used to add a new SSL certificate and provides an option to manually upload the certificate.

Parameters

NameData TypeRequiredDescription
keystringYesPrivate key content
certstringNoCertificate content
ca_chainstringNoCA chain content
global_cert_idnumberNoGlobal ID of the certificate
gidlistNoList of user group IDs

Returns

  • cert_id:Returns the ID of the newly added certificate.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

key_file = os.path.join('tests', 'key.pem')
cert_file = os.path.join('tests', 'cert.pem')

with open(key_file) as f:
    key = f.read()
with open(cert_file) as f:
    cert = f.read()

cert_id = client.set_cert_key(key=key, cert=cert)

set_le_cert

cert_id = set_le_cert(**kwargs)

This method is used to add certificates from Let’s Encrypt or other certificate providers (such as ZeroSSL).

Parameters

NameData TypeRequiredDescription
domainsstring arrayYesDomains that need to auto-obtain the LE certificate
gidlistNoList of user group IDs
resignboolNoWhether to trigger re-issuance of the certificate
acme_providerintegerNoID of the ACME Provider
acme_csr_typestringNoSignature algorithm type, options: ec, rsa
enabledboolNoWhether to enable automatic certificate management

Returns

  • cert_id: ID of the newly created Let’s Encrypt certificate

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

cert_id = client.set_le_cert(domains=["orig.foo.com"])

put_cert_key

ok = put_cert_key(**kwargs)

This method is used to update SSL certificate (manual upload method).

Parameters

NameData TypeRequiredParameter Description
cert_idnumberYesUnique identifier id of the certificate
keystringYesDetailed content of the private key
certstringNoDetailed content of the server-side certificate
ca_chainstringNoDetailed content of CA chain
global_cert_idnumberNoGlobal unique identifier id of the certificate
gidlistNoList form of user group id

Returns

  • True: indicates that the update was successful.
  • False: indicates that the update failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

new_key_file = os.path.join('tests', 'new_key.pem')
new_cert_file = os.path.join('tests', 'new_cert.pem')
with open(new_key_file) as f:
    new_key = f.read()
with open(new_cert_file) as f:
    new_cert = f.read()

cert_id = 1
ok = client.put_cert_key(cert_id=cert_id, key=new_key, cert=new_cert)

put_le_cert

ok = put_le_cert(**kwargs)

This method is used to update certificates from Let’s Encrypt or other certificate providers (such as ZeroSSL).

Parameters

NameData TypeRequiredDescription
cert_idintegerNoInteger ID
domainsstring arrayYesDomains that need to auto-obtain the LE certificate
gidlistNoList of user group IDs
resignboolNoWhether to trigger re-issuance of the certificate
acme_providerintegerNoID of the ACME Provider
acme_csr_typestringNoSignature algorithm type, options: ec, rsa
enabledboolNoWhether to enable automatic certificate management

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

cert_id = 1
ok = client.put_le_cert(cert_id=cert_id, domains=["xx.foo.com"], resign=False)

get_le_cert

data = get_le_cert(cert_id)

This method is used to obtain the issuance status of a Let’s Encrypt certificate.

Parameters

NameData TypeMandatoryDescription
cert_idnumberYesCertificate ID

Returns

  • data: Returns a dict type of data containing the following fields:
Field NameData TypeDescription
statusstringDescribes the issuance status of the certificate, possible values include: valid / pending / invalid
expdatenumberThe expiration time of the certificate, represented by Unix timestamp
next_udpatenumberThe next update time of the certificate, represented by Unix timestamp

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

cert_id = 1
data = client.get_le_cert(cert_id)

get_cert_key

cert_data = get_cert_key(cert_id)

This method is used to obtain the content of the SSL certificate.

Parameters

Parameter NameData TypeMandatoryDescription
cert_idnumberYesRepresents the id of the certificate

Returns

  • The return value is cert_data, which represents the content of the certificate. The data type is dict.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

cert_id = 1
data = client.get_cert_key(cert_id)

get_all_cert_keys

cert_data = get_all_cert_keys()

This method is used to obtain all the certificate information of the current application.

Returns

  • cert_data: The certificate data returned in the form of a dict.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_all_cert_keys()

del_cert_key

success = del_cert_key(certificate_id)

Deletes the certificate information associated with the given certificate_id.

Parameters

NameData TypeRequiredDescription
certificate_idnumberYesUnique identifier of the certificate

Returns

  • True: Deletion successful.
  • False: Deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

application_id = 1
client.use_application(application_id)

certificate_id = 1
success = client.del_cert_key(certificate_id)

new_el

ok = new_el(**kwargs)

This method is used to add custom edge language code.

Parameters

NameData TypeRequiredDescription
phasestringYesUsed to define the phase of edge language execution
codestringYesThe edge language code to be executed
postboolYesIf set to True, this code will be executed after the selected phase, default value is False
preboolYesIf set to True, this code will be executed before the selected phase, default value is False

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

code = "true => print('hello, world');"

ok = client.new_el(phase='req-rewrite', code=code, pre=True)

new_release

ok = new_release()

This method is used to release updates for the current application.

Returns

  • True: Indicates the update was successful.
  • False: Indicates the update failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

ok = client.new_release()

This example demonstrates how to use the new_release method of Edge2Client to release updates for the application.


pending_changes

changes = pending_changes()

This method is used to query the number of changes pending for release.

Returns

  • changes: This is an integer that represents the number of changes pending for release.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

changes = client.pending_changes()

In the above example, an Edge2Client instance is first created and logged in. Then, the id of the application is set to 1, and the pending_changes function is used to query the number of changes pending for release.


sync_status

total, synced = sync_status()

Query Synchronization Status.

Returns

  • total: The total number of Edge Node servers.
  • synced: The number of Edge Node servers that have been successfully synchronized.

Examples

Create multiple rules and confirm whether they have been successfully published to the entire network.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

total, synced = client.sync_status()
if total == synced:
    print('The new release has been synchronized to all nodes')

node_sync_status

data = node_sync_status()

This method is used to get the synchronization details of each node.

Returns

  • data: dict type, it returns the node_id of each node and the delay time from the last release to now on this node.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.node_sync_status()
for node_id, delay in data.items():
    if delay > 0:
        print('Warning: Node id {}: Lag {}'
        .format(str(node_id), str(delay)))

get_healthcheck_status

data = get_healthcheck_status(node_id, page=1, page_size=1000)

This piece of code is used to get health check information for each node.

Returns

  • data: This is a dict type data, it returns the node_id and the corresponding health status of each node.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.node_sync_status()

for node_id, node_info in data.items():
    node_id = int(node_id)
    data = client.get_healthcheck_status(node_id, 1, 1000)

add_app_user

user_id = add_app_user(name, read, write, release, dns_read, dns_write)

This method is used to add application-level users.

Parameters

NameData TypeRequiredDescription
namestringYesUsername
readboolNoWhether the user has read permissions, default is True
writeboolNoWhether the user has write permissions, default is True
releaseboolNoWhether the user has release permissions, default is False
dns_readboolNoWhether the user has DNS read permissions, default is False
dns_writeboolNoWhether the user has DNS write permissions, default is False

Returns

  • user_id: The ID of the newly added user.

Please note: The user_id here is different from the user_id of the global user.

Examples

The following example shows how to add an application-level user named only_reader who does not have write and release permissions.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

user_id = client.add_app_user(name='only_reader', write=False, release=False)

update_app_user

success = update_app_user(id, name, read, write, release, dns_read, dns_write)

This method is used to update user information at the application level.

Parameters

NameData TypeRequiredDescription
idlistyesUser id
namestringyesUsername
readboolnoWhether the user has read permissions, default is True
writeboolnoWhether the user has write permissions, default is True
releaseboolnoWhether the user has permission to publish changes, default is False
dns_readboolnoWhether the user has read permissions for DNS, default is False
dns_writeboolnoWhether the user has write permissions for DNS, default is False

Returns

  • True: User information updated successfully.
  • False: Failed to update user information.

Examples

The following example shows how to use This method to update the permissions of the user with id 1, set the username to master, and grant write and release permissions.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

uid = 1
success = client.update_app_user(id=uid, name='master', write=True, release=True)

get_app_user

data = get_app_user(id=None, name=None, app_id=None, user_id=None)

This method is used to get user information at the application level, including username, permissions, etc.

Parameters

Parameter NameData TypeRequiredDescription
idlistNoUser’s id
namestringNoUsername
app_idnumberNoApplication’s id, default to current app id if not specified
user_idnumberNoGlobal user id

Returns

  • data: Returns a dictionary type data containing user information such as username, permissions, etc.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

username = 'only_reader'
data = client.get_app_user(name=username)

del_app_user

ok = del_app_user(id, name, app_id, user_id)

This method is used to delete a user from a specific application.

Parameters

NameData TypeRequiredDescription
idlistNoUser id
namestringNoUsername
app_idnumberNoApplication id, defaults to current app if not specified
user_idnumberNoGlobal user id

Returns

  • Returns True if the operation is successful.
  • Returns False if the operation fails.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

username = 'only_reader'
ok = client.del_app_user(name=username)

In this example, we first created an Edge2Client instance and logged in. Then, we selected an application, and finally, we deleted a user from the application by passing in the username.


get_all_app_users

data = get_all_app_users(app_id)

This method is used to get all users at the current application level. Users of a specific application can also be obtained by specifying the app_id.

Parameters

NameData TypeRequiredDescription
app_idnumberNoApplication id, default is current application id

Returns

  • data: The return value is of list type, and each element in the list is of dict type.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_all_app_users()

add_user_for_all_apps

ok = add_user_for_all_apps(name, read, write, release, dns_read, dns_write)

This method is used to add a user for all applications.

Parameters

NameData TypeRequiredDescription
namestringNoUsername
readboolNoWhether the user has read permission, default is True
writeboolNoWhether the user has write permission, default is True
releaseboolNoWhether the user has the permission to release changes, default is False
dns_readboolNoWhether the user has the permission to read DNS, default is False
dns_writeboolNoWhether the user has the permission to edit DNS, default is False

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

# Use add_global_user() function to create a user named 'write'.
username='write'

data = client.add_user_for_all_apps(name=username)

add_all_users_for_app

ok = add_all_users_for_app(app_id, read, write, release, dns_read, dns_write)

This method is used to add all global users to the specified application.

Parameters

NameData TypeRequiredDescription
app_idnumberNoID of the application, if not specified, defaults to the current application ID
readboolNoWhether the user has read permission, if not specified, defaults to True
writeboolNoWhether the user has write permission, if not specified, defaults to True
releaseboolNoWhether the user has release changes permission, if not specified, defaults to False
dns_readboolNoWhether the user has DNS read permission, if not specified, defaults to False
dns_writeboolNoWhether the user has DNS write permission, if not specified, defaults to False

Returns

  • True: Indicates the addition was successful.
  • False: Indicates the addition failed.

Examples

The following example shows how to add users to the application with ID 1, where all global users will be added to this application, and the release (release changes) permission is True, other permissions remain default.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.add_all_users_for_app(release=True)

new_cache_purge_task

task_id = client.new_cache_purge_task(condition=condition)

This method is used to add a new condition purge task. The trigger conditions are passed in array format, and multiple trigger conditions can be set. Only when all set conditions are met at the same time, the corresponding purge task will be triggered.

Parameters

NameData TypeRequiredDescription
conditionlistNoTrigger conditions

Returns

  • task_id: Returns the ID of the created purge task. You can query the execution details of the purge task through this ID.

Examples

In the following example, the trigger condition of the new conditional purge task is set as: “When the accessed Host is con.foo.com, and the value of Referer in the request header matches the regular expression foo\d+.”

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

condition = [
    {'var': 'host', 'val': 'con.foo.com'},
    {'var': ['req-header', 'Referer'], 'vals': [['foo\d+', 'rx'], 'foo.com']}
]

rule_id = client.new_cache_purge_task(condition=condition)

get_cache_purge_task

data = client.get_cache_purge_task(task_id)

This method retrieves the details of a task by specifying the refresh task id.

Parameters

NameDataTypeRequiredDescription
task_idnumberYesUnique id of the refresh task

Returns

  • data: Returns a dictionary (dict) type of data containing the details of the task.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

task_id = 1

data = client.get_cache_purge_task(task_id)

get_all_cache_purge_tasks

data = client.get_all_cache_purge_tasks()

This method is used to obtain detailed information about all cache purge tasks.

Returns

  • data: Returns a list containing all purge tasks.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_all_cache_purge_tasks()

del_cache_purge_task

ok = client.del_cache_purge_task(task_id)

This method is used to delete the refresh task of a specified ID.

Parameters

NameData TypeRequiredDescription
task_idnumberYesID of the refresh task to be deleted

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failure.

Examples

The following example demonstrates how to delete a cache refresh task with an ID of 1.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

task_id = 1
ok = client.del_cache_purge_task(task_id)

new_waf_whitelist

rule_id = new_waf_whitelist(**kwargs)

This method is used to add new WAF whitelist rules.

Parameters

Parameter NameData TypeRequiredDescription
conditionlistNoRule execution conditions
rule_setslistYesList of WAF rule IDs

WAF Condition Parameters

Parameter NameData TypeRequiredDescription
varstring or arrayYesBuilt-in function name in Edge language. When the data type is array, the parameters required by the function need to be added after the function name
opstringNoOperator, default is eq
valstringChoose one from val / valsValue
valslistChoose one from val / valsA set of values (using array)

Returns

  • rule_id: The ID of the newly created WAF whitelist rule.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

condition = [
    {'var': 'host', 'val': 'con.foo.com'},
    {'var': ['req-header', 'Referer'], 'vals': [['foo\d+', 'rx'], 'foo.com']}
]

id = client.new_waf_whitelist(condition=condition, rule_sets=[1, 2])

update_waf_whitelist

ok = update_waf_whitelist(**kwargs)

This method is used to update WAF whitelist rules.

Parameters

NameData TypeRequiredDescription
whitelist_idnumberYesWhitelist id to update
conditionlistNoSet of conditions for rule execution
rule_setslistYesList containing waf ids

Returns

  • Returns True if successful.
  • Returns False if failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

condition = [
    {'var': 'host', 'val': 'con.foo.com'},
    {'var': ['req-header', 'Referer'], 'vals': [['foo\d+', 'rx'], 'foo.com']}
]

waf_whitelist_id = 1
ok = client.update_waf_whitelist(
    whitelist_id=waf_whitelist_id, condition=condition, rule_sets=[1])

get_waf_whitelist

data = get_waf_whitelist(whitelist_id)

This method is used to obtain the whitelist rules of WAF.

Parameters

NameData TypeRequiredDescription
whitelist_idnumberYesThe unique identifier id of the whitelist rule

Returns

  • data: Returns a dict type, containing the rules data of WAF whitelist.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_waf_whitelist(waf_whitelist_id)

del_waf_whitelist

ok = del_waf_whitelist(whitelist_id)

Performing this operation will delete the specified WAF whitelist rule.

Parameters

NameData TypeRequiredDescription
whitelist_idnumberYesID of whitelist rule

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failed.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

# Specify APP ID
app_id = 1
client.use_app(app_id)

# Delete specific WAF whitelist rule
ok = client.del_waf_whitelist(waf_whitelist_id)

get_all_waf_whitelists

data = get_all_waf_whitelists()

This method is used to get all WAF whitelist rules.

Returns

  • data: Returns a list type of WAF whitelist data.

Examples

from edge2client import Edge2Client

# Create and log in to the client
client = Edge2Client(host, username, password)
client.login()

# Select application
app_id = 1
client.use_app(app_id)

# Get all WAF whitelists
data = client.get_all_waf_whitelists()

new_app_dymetrics

id = new_app_dymetrics(app_id=None, name=None, note=None, interval=60, sql=None)

Creates a new application dynamic metric. If you want to enable the built-in dynamic indicators of OpenResty Edge, you can get the name and SQL of the built-in dynamic metrics from this document.

Parameters

ParameterData TypeRequiredDescription
app_idnumberYesUnique identifier id of the application
namestringYesName used to identify the dynamic metric
sqlstringYesSQL statement used to generate the dynamic metric
notestringNoAdditional explanation or remarks for the metric
intervalnumberNoRefresh time interval for the metric (in seconds)

Returns

  • id: Unique identifier for the newly created dynamic metric.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

sql = 'select status, count(*) from reqs group by status'

dymetrics_id = client.new_app_dymetrics(app_id=1, name='test', sql=sql)

put_app_dymetrics

ok = put_app_dymetrics(app_id=None, id=None, name=None, note=None, interval=60, sql=None)

This method is used to modify the dynamic metrics of the application.

Parameters

ParameterData TypeRequiredDescription
idnumberYesID of the dynamic metric to modify
app_idnumberYesID of the application
namestringYesName of the metric
sqlstringYesSQL statement defining the metric
notestringNoNote information
intervalnumberNoData refresh interval in seconds

Returns

  • True: The modification was successful.
  • False: The modification failed.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

id=1
sql = 'select status, count(*) from reqs group by status'
data = client.put_app_dymetrics(app_id=1, id=id, name='test', sql=sql)

del_app_dymetrics

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

app_id = 1

ok = del_app_dymetrics(app_id, id)

This method is used to delete the dynamic metrics of a specified application.

Parameters

ParameterData TypeMandatoryDescription
idnumberYesThe ID of the dynamic metrics to be deleted
app_idnumberYesThe ID of the specified application

Returns

  • True: Indicates successful deletion.
  • False: Indicates failure in deletion.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

app_id = 1

ok = client.del_app_dymetrics(app_id, dymetrics_id)

get_app_dymetrics

data = get_app_dymetrics(app_id, id)

This method is used to get the dynamic metrics of the specified application.

Parameters

ParameterData TypeRequiredDescription
idnumberYesID of the dynamic metrics
app_idnumberYesID of the application

Returns

  • data: Returns a dict type of dynamic metrics data.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

app_id = 1
data = client.get_app_dymetrics(app_id, dymetrics_id)

get_all_app_dymetrics

data = get_all_app_dymetrics(app_id)

This method is used to obtain all the dynamic metric information of a specified application.

Parameters

NameData TypeRequiredDescription
app_idnumberYesThe unique id that represents the application

Returns

  • data: The returned data is a list type list that contains all dynamic metric information.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

app_id = 1
data = client.get_all_app_dymetrics(app_id)

get_app_dymetrics_data

data = get_app_dymetrics_data(app_id, id, chart_type='line', start_time=None, end_time=None, node_id=None)

This method is used to obtain the dynamic metrics data of the application, and it returns the data of the last 30 minutes by default.

Parameters

Parameter NameData TypeRequiredDescription
app_idnumberYesThe id of the application
idnumberYesThe id of the dynamic metrics
chart_typenumberYesThe type of chart
start_timenumberYesThe start time of the data
end_timenumberYesThe end time of the data
node_idnumberYesThe ID of the Edge Node

Returns

  • data: The returned dynamic metrics data, with a data type of list.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

app_id = 1
dymetrics_id = 1
data = client.get_app_dymetrics_data(app_id, dymetrics_id)

get_app_metrics

data = get_app_metrics(id, start_time=None, end_time=None)

This method is used to get the HTTP request status metrics and network transmission and reception metrics of the application. By default, it will get data for the last 30 minutes.

Parameters

ParameterData TypeRequiredDescription
idnumberYesThe id of the metrics
start_timenumberYesThe start time of the metrics collection
end_timenumberYesThe end time of the metrics collection

Returns

  • data: This is a list type that contains metric data.

Examples

from edge2client import Edge2Client

# Initialize client and log in
client = Edge2Client(host, username, password)
client.login()

app_id = 1

data = client.get_app_metrics(app_id)

new_ip_list

id = new_ip_list(name=None, type='ipv4', items=None)

Add a new application-level IP list.

Parameters

NameData TypeRequiredDescription
namestringyesThe name of the IP list
typestringnoThe type of IP address, can be ipv4 or soon to be supported ipv6
itemsarraynoList of IP addresses

items Parameter

NameTypeRequiredDescription
ipstringyesIP address
exptimeintNoIP expiration time, in Unix timestamp. If not set, the IP is valid permanently

Returns

  • id: ID of the newly created IP list.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

ok = client.new_ip_list(name = 'ip-list-1',
                        type = 'ipv4',
                        items = [
                            {'ip': '127.0.0.0/24'},
                            {'ip': '192.168.1.0/24'},
                            {'ip': '192.168.2.0/24', 'exptime': 1725000000},
                            {'ip': '192.168.3.0/24', 'exptime': 1735000000}
                        ])

put_ip_list

ok = put_ip_list(rule_id=None, name=None, type='ipv4', items=None)

This method is used to modify the specified IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUsed to specify the ID of the IP list that needs to be modified
namestringYesUsed to specify the name of the IP list
typestringNoUsed to specify the type of IP address, currently only supports ‘ipv4’, ‘ipv6’ will be launched in the future
itemsarrayNoUsed to specify the IP address list

Returns

  • True: Indicates that the specified IP list was successfully modified.
  • False: Indicates that the modification of the specified IP list failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

ok = client.put_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.2'} ])

del_ip_list

ok = del_ip_list(rule_id=None)

This method is used to delete the specified IP list.

Parameters

NameData TypeMandatoryDescription
rule_idnumberYesThe ID of the IP list to delete

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

ok = client.del_ip_list(rule_id=1)

In this example, we first log in using an instance of Edge2Client, then select an application, and finally delete the IP list with the specified ID.


get_ip_list

data = get_ip_list(rule_id=None)

This method is used to view specific IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUnique identifier ID of the IP list to be viewed

Returns

  • data: Returns a dictionary type IP list data.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

data = client.get_ip_list(rule_id=1)

append_to_ip_list

ok = append_to_ip_list(rule_id=None, items=None)

This method is used to append IPs to specific IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUsed to specify the ID of the IP list that needs to be modified
itemsarrayYesUsed to specify the IP address list
remove_expiredboolNoWhether to remove expired IPs. Default is False. If set to True, expired IPs will be removed before appending new IPs

Returns

  • True: Indicates that the specified IP list was successfully modified.
  • False: Indicates that the modification of the specified IP list failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

ok = client.append_to_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.3'} ])

ok = client.append_to_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.3'} ], remove_expired = True)

remove_from_ip_list

ok = remove_from_ip_list(rule_id=None, items=None)

This method is used to remove IPs from specific IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUsed to specify the ID of the IP list that needs to be modified
itemsarrayNoUsed to specify the IP address list

Returns

  • True: Indicates that the specified IP list was successfully modified.
  • False: Indicates that the modification of the specified IP list failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

ok = client.remove_from_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.3'} ])

node_monitor

data = node_monitor(node_id, start_time=None, end_time=None, step=60)

This method is used to obtain CPU and memory load-related information of a network node.

Parameters

Parameter NameData TypeRequiredDescription
node_idNumericYesID of the gateway node
start_timeNumericNoData start time
end_timeNumericNoData end time
stepNumericNoInterval for data retrieval

Returns

  • data: returns a list containing monitoring data.

Examples

node_id = 1
data = client.node_monitor(node_id)

new_global_dymetrics

id = new_global_dymetrics(name=None, note=None, interval=60, sql=None)

This method is used to create global dynamic metrics.

Parameters

NameData TypeRequiredDescription
namestringYesThe name of the global dynamic metric to be created
notestringNoRemarks for the global dynamic metric
intervalnumberNoThe time interval of statistics
sqlstringYesSQL statement for collecting metrics

Returns

  • id: The unique identifier ID of the newly created global dynamic metric.

Examples

sql = 'select status, count(*) from reqs group by status'

dymetrics_id = client.new_global_dymetrics(name='test', sql=sql)

put_global_dymetrics

ok = put_global_dymetrics(id=None, name=None, note=None, interval=60, sql=None)

This method is used to modify global dynamic indicators.

Parameters

NameData TypeRequiredDescription
idnumberYesID of the global dynamic indicator
namestringYesName of the global dynamic indicator
notestringNoAdditional notes
intervalnumberNoData collection interval
sqlstringYesSQL statement for collecting metrics

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

id=1
sql = 'select status, count(*) from reqs group by status'
data = client.put_global_dymetrics(id=id, name='test', sql=sql)

del_global_dymetrics

ok = del_global_dymetrics(id)

This method is used to delete the specified global dynamic metric.

Parameters

Parameter NameData TypeRequiredDescription
idnumberYesThe ID of the global dynamic metric to be deleted

Returns

  • True: Represents successful deletion of the global dynamic metric.
  • False: Represents failure in deleting the global dynamic metric.

Examples

ok = client.del_global_dymetrics(dymetrics_id)

get_global_dymetrics

data = get_global_dymetrics(id)

This method is used to get the specified global dynamic metrics.

Parameters

Parameter NameData TypeMandatoryDescription
idnumberYesID of the global dynamic metrics

Returns

  • data: Returns a global dynamic metrics information of type dict.

Examples

data = client.get_global_dymetrics(dymetrics_id)

get_all_global_dymetrics

data = get_all_global_dymetrics()

This method is used to get all global dynamic metrics.

Returns

  • data: Returns a list type data containing global dynamic metrics information.

Examples

data = client.get_all_global_dymetrics()

get_global_dymetrics_data

data = get_global_dymetrics_data(id, chart_type='line', start_time=None, end_time=None, node_id=None)

This method is used to get global dynamic metrics data, the default range is the most recent 30 minutes.

Parameters

NameData TypeRequiredDescription
idnumberYesThe ID of dynamic metrics
chart_typestringNoChart type, default is ’line’
start_timenumberNoStart time, default is None
end_timenumberNoEnd time, default is None
node_idnumberNoThe ID of the Edge Node, default is None

Returns

  • data: The return is a list containing global dynamic metrics data.

Examples

dymetrics_id = 1
data = client.get_global_dymetrics_data(dymetrics_id)

use_dns_app

ok = use_dns_app(dns_id)

This method is used to switch the DNS application that the current instance operates.

Parameters

Parameter NameData TypeIs RequiredDescription
dns_idnumberYesThe id of the DNS application to be operated

Returns

  • True: Indicates the switch was successful.
  • False: Indicates the switch failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1
client.use_dns_app(dns_id)

new_dns_app

dns_id = new_dns_app(**kwargs)

This method is used to create a new DNS application.

Parameters

NameData TypeRequiredDescription
zonestringYesDomain name
authoritylistYesNS record
soa_emailstringNoSOA EMAIL record

Returns

  • dns_id: Returns the ID of the newly created DNS application.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

authority = [
    {'domain': 'ns1.foo.com', 'ttl': '2 [hour]'},
    {'domain': 'ns2.foo.com', 'ttl': '1 [day]'}
]

soa_email = 'admin@foo.com'

dns_id = client.new_dns_app(
    authority=authority,
    soa_email=soa_email,
    zone='foo.com')

put_dns_app

ok = put_dns_app(**kwargs)

This method is used to modify the relevant information of the DNS application.

Parameters

NameData TypeRequiredDescription
dns_idNumericYesUnique id of DNS application
zoneStringYesDomain record of DNS
authorityListYesNS record of DNS
soa_emailStringNoSOA EMAIL record of DNS

Returns

  • True: Indicates that the information was modified successfully.
  • False: Indicates that the information modification failed.

Examples

The following example shows how to modify the application with dns_id 1.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1

authority = [
    {'domain': 'ns1.foo.com', 'ttl': '4 [hour]'},
    {'domain': 'ns2.foo.com', 'ttl': '1 [day]'}
]

ok = client.put_dns_app(
    dns_id=dns_id,
    authority=authority,
    soa_email=soa_email,
    zone='foo.com')

get_dns_app

data = get_dns_app(dns_id)

This method is used to get the relevant information of the DNS application.

Parameters

Parameter NameData TypeRequiredDescription
dns_idnumberYesRepresents the unique id of the DNS application

Returns

  • data: A dict type of data, containing detailed information of the DNS application.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1

data = client.get_dns_app(dns_id)

del_dns_app

ok = del_dns_app(dns_id)

This method is used to delete a specified DNS application.

Parameters

The following table lists the parameters required by This method.

NameData TypeRequiredDescription
dns_idnumberYesThe id of the DNS application to be deleted

Returns

  • True: Indicates that the DNS application was successfully deleted.
  • False: Indicates that the deletion of the DNS application failed.

Examples

The following example shows how to delete a specified DNS application.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1

data = client.del_dns_app(dns_id)

new_dns_record

record_id = new_dns_record(**kwargs)

This method is used to add a DNS record.

Parameters

NameData TypeRequiredDescription
sub_domainstringYesSubdomain
linestringYesLine, refer to the Line.txt file in the same directory
record_typestringYesType of the record, options include [A, TXT, MX, CNAME, CAA]
textstringNoThis field needs to be filled out when the record type is [TXT, CAA]
ipstringNoThis field needs to be filled out when the record type is IP
gatewaynumberNoThis field needs to be filled out when the record points to a specific gateway cluster
domainstringNoThis field needs to be filled out when the record type is a domain
prioritynumberNoThis field needs to be filled out when the record type is MX

Returns

  • record_id: The ID of the newly added DNS record.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1
use_dns_app(dns_id)

record_id = client.new_dns_record(
    sub_domain='bar', record_type='TXT', text='text string')
client.new_dns_record(
    sub_domain='bar', record_type='A', ip='127.0.0.1')
client.new_dns_record(
    sub_domain='bar', record_type='CNAME', domain='test.com')
client.new_dns_record(
    sub_domain='bar', record_type='MX', domain='test.com', priority=3)

put_dns_record

ok = put_dns_record(**kwargs)

This method is used to modify DNS records.

Parameters

NameData TypeRequiredDescription
record_idnumberYesID of the DNS record
sub_domainstringYesSubdomain
linestringYesLine, refer to the Line.txt file in same directory
record_typestringYesType of the record, options include [A, TXT, MX, CNAME, CAA]
textstringNoRequired when record type is [TXT, CAA]
ipstringNoRequired when record type is IP
domainstringNoRequired when record type is a domain
prioritynumberNoRequired when record type is MX

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1
use_dns_app(dns_id)

record_id = 1

ok = client.put_dns_record(
    record_id=record_id,
    sub_domain='a.bar',
    record_type='TXT',
    text='text string')

get_dns_record

data = get_dns_record(record_id)

This method is used to obtain DNS records.

Parameters

NameData TypeRequiredDescription
record_idnumberYesID of DNS record

Returns

  • data: Returns a dict type DNS record information.

Examples

If you need to obtain DNS record information with record_id as 1, you can refer to the following steps.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1
use_dns_app(dns_id)

record_id = 1

data = client.get_dns_record(record_id)

del_dns_record

ok = del_dns_record(record_id)

This method is used to delete a DNS record.

Parameters

Parameter NameData TypeRequiredDescription
record_idnumberYesRepresents the id of the DNS record

Returns

  • Returns True if the deletion is successful.
  • Returns False if the deletion fails.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

dns_id = 1
use_dns_app(dns_id)

record_id = 1

ok = client.del_dns_record(record_id)

In this example, we first create an Edge2Client client and log in with a specific host, username, and password. Then, we choose to use the DNS application with a specific id. Finally, we attempt to delete the DNS record with a specific id using this client, and save the result in ok.


new_global_upstream

up_id = new_global_upstream(**kwargs)

This method is used to add a new upstream and returns the id of the newly created global upstream.

Parameters

NameData TypeRequiredDescription
namestringYesThe name of the upstream
serverslistYesDetailed information of the upstream
sslboolNoEnable HTTPS protocol, default is False
health_checkerdictNoDetailed configuration of health check, default is None
gidarrayYesList of user group ids, e.g., [1]

Returns

  • up_id: ID of the newly created upstream.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = client.new_global_upstream(
    name='origin-upstream',
    servers=[
        {'ip': '172.22.31.1', 'port': 80},
        {'ip': '172.22.31.2', 'port': 80, 'weight': 2}
    ])

update_global_upstream

ok = update_global_upstream(**kwargs)

This method is used to update global upstream information.

Parameters

NameData TypeRequiredDescription
namestringYesName of the upstream
serverslistYesList of upstream information
sslboolNoWhether to use HTTPS protocol, default False
health_checkerdictNoDetailed configuration of health check, default None
gidarrayYesList of user group ids, for example: [1]

Returns

  • True: The operation was successful.
  • False: The operation failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = 1

ok = client.update_global_upstream(up_id,
    name='origin-upstream',
    servers=[
        {'domain': 'test.com', 'port': 8080},
        {'ip': '172.22.31.2', 'port': 8080, 'weight': 1}
    ],
    health_checker={
        'type': 'http',
        'http_req_uri': '/status',
        'http_req_host': 'test.com',
        'interval': 3,
        'interval_unit': 'sec',
        'timeout': 1,
        'fall': 3,
        'rise': 2,
        'valid_statuses': [200, 302],
        'report_interval': 3,
        'report_interval_unit': 'min'
    })

get_global_upstream

data = get_global_upstream(up_id)

This method is used to retrieve global upstream information.

Parameters

NameData TypeRequiredDescription
up_idstringNoID of the upstream

Returns

  • True: When the information is successfully retrieved.
  • False: When the information retrieval fails.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = 1

data = client.get_global_upstream(up_id)

del_global_upstream

del_global_upstream(up_id)

This method is used to delete the global upstream.

Parameters

NameData TypeMandatoryDescription
up_idstringNoUnique ID of the upstream

Returns

  • True: Indicates successful deletion.
  • False: Indicates failure in deletion.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = 1

operation_status = client.del_global_upstream(up_id)

get_all_global_upstreams

upstreams = client.get_all_global_upstreams()

This method is used to get all the upstream information.

Returns

  • upstreams: Returns a list type variable containing all global upstream information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

upstreams = client.get_all_global_upstreams()

new_global_k8s_upstream

up_id = new_global_k8s_upstream(**kwargs)

This method is used to create a new global Kubernetes upstream and returns the ID of the newly created upstream.

Parameters

NameData TypeRequiredParameter Description
namestringYesDefines the name of the upstream
k8s_serviceslistYesProvides detailed information about k8s services
sslboolNoDefines whether to use HTTPS protocol. Default is False
health_checkerdictNoDetailed configuration to check the health status of the upstream. Default is None
gidarrayYesList of user group IDs, for example: [1]

Returns

  • up_id: The ID of the newly created k8s upstream.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

k8s_up_id = client.new_global_k8s_upstream(
    name = 'k8s-upstream',
    k8s_services = [
        {
            'k8s' : 1,
            'k8s_namespace' : 'default',
            'k8s_service' : 'foo',
            'k8s_service_port' : 80,
        }
    ])

put_global_k8s_upstream

ok = put_global_k8s_upstream(**kwargs)

This method is used to modify the information of the global Kubernetes upstream.

Parameters

NameData TypeRequiredDescription
namestringYesDefinition of the upstream name
k8s_serviceslistYesInformation when the upstream is a Kubernetes service
sslboolNoUse HTTPS protocol or not, default is False
health_checkerdictNoDetailed configuration for health check, default is None
gidarrayYesList of user group ids, such as [1]

Returns

  • True: Indicates modification was successful.
  • False: Indicates modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = 1

ok = client.put_global_k8s_upstream(up_id,
    name='k8s-upstream',
    k8s_services = [
        {
            'k8s' : 1,
            'k8s_namespace' : 'default',
            'k8s_service' : 'foo',
            'k8s_service_port' : 80,
        }
    ],
    health_checker={
        'type': 'http',
        'http_req_uri': '/status',
        'http_req_host': 'test.com',
        'interval': 3,
        'interval_unit': 'sec',
        'timeout': 1,
        'fall': 3,
        'rise': 2,
        'valid_statuses': [200, 302],
        'report_interval': 3,
        'report_interval_unit': 'min'
    })

fetch_global_k8s_upstream

data = fetch_global_k8s_upstream(up_id)

This method is used to fetch global Kubernetes upstream information.

Parameters

NameData TypeRequiredDescription
up_idStringYesUnique ID of the upstream

Returns

  • data: Returns a dictionary type value containing Kubernetes upstream information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = '1'

data = client.fetch_global_k8s_upstream(up_id)

del_global_k8s_upstream

del_global_upstream(up_id)

This method is used to delete the global k8s upstream.

Parameters

NameData TypeRequiredDescription
up_idstringYesUnique ID of the upstream

Returns

  • Returns True if the deletion is successful.
  • Returns False if the deletion fails.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

up_id = '1'

ok = client.del_global_k8s_upstream(up_id)

get_all_global_k8s_upstreams

upstreams = client.get_all_global_k8s_upstreams()

This method is used to get all Kubernetes upstream information.

Returns

  • upstreams: Returns a list of Kubernetes upstream information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

upstreams = client.get_all_global_k8s_upstreams()

set_global_cert_key

cert_id = set_global_cert_key(**kwargs)

Used to add a global SSL certificate.

Parameters

Parameter NameTypeRequiredDescription
keyStringYesPrivate key content
certStringNoServer certificate content
ca_chainStringNoCA chain certificate content

Returns

  • cert_id: The ID of the newly created global certificate.

Examples

The following example demonstrates how to upload local key.pem and cert.pem files to create a global certificate.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

key_file = os.path.join('tests', 'key.pem')
cert_file = os.path.join('tests', 'cert.pem')
with open(key_file) as f:
    key = f.read()
with open(cert_file) as f:
    cert = f.read()

cert_id = client.set_global_cert_key(key=key, cert=cert)

put_global_cert_key

ok = put_global_cert_key(**kwargs)

This method is used to modify the global SSL certificate.

Parameters

Parameter NameTypeRequiredDescription
cert_idNumberYesID of the certificate
keyStringYesContent of the private key
certStringNoContent of the certificate
ca_chainStringNoContent of the CA chain

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

cert_id = 1

new_key_file = os.path.join('tests', 'new_key.pem')
new_cert_file = os.path.join('tests', 'new_cert.pem')
with open(new_key_file) as f:
    new_key = f.read()
with open(new_cert_file) as f:
    new_cert = f.read()

ok = client.put_global_cert_key(cert_id=cert_id, key=new_key, cert=new_cert)

get_global_cert_key

data = get_global_cert_key(cert_id)

This method is used to get the SSL certificate information associated with cert_id.

Parameters

NameTypeRequiredDescription
cert_idnumberYesUnique identifier id of the certificate

Returns

  • data: Returns a dict type data that contains all the information of the global certificate.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

cert_id = 1

data = client.get_global_cert_key(cert_id)

del_global_cert_key

ok = del_global_cert_key(cert_id)

This method is used to delete a specified global SSL certificate.

Parameters

NameData TypeRequiredDescription
cert_idnumberYesThe id of the certificate to be deleted

Returns

  • True: Indicates successful deletion.
  • False: Indicates failed deletion.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

cert_id = 1

ok = client.del_global_cert_key(cert_id)

add_global_user

uid = add_global_user(name, pwd, gid)

This method is used to add a global user.

Parameters

NameData TypeMandatoryDescription
namestringYesThe name of the global user to be added
pwdstringYesThe password for the global user
gidarrayYesList containing the user group id, such as [1]

Returns

  • uid: The unique identification ID of the newly added global user.

Note: The ID of the global user needs to be distinguished from the user ID at application level.

Examples

The following example shows how to create a global user named global_demo_user, who has the permission to create a new application, and whose role is a regular user.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

username='global_demo_user'

uid = client.add_global_user(name=username, pwd=pwd, gid=[1])

search_global_user

user_info = search_global_user(name)

This method is used to search for global user information based on the username.

Parameters

Parameter NameData TypeRequiredDescription
namestringYesGlobal username

Returns

  • user_info: dict type, containing the searched user information and its related permission information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

username = 'global_demo_user'

data = client.search_global_user(username)
user_id = data.get('id')

get_all_global_users

data = get_all_global_users(detail)

This method is used to get the information of all global users.

Parameters

NameData TypeRequiredDescription
detailnumberNoValue is either 0 or 1, indicating whether to return detailed information of the user.

Returns

  • data: Returns a list type data, each element of which is a dict type, containing the information of the corresponding global user.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_global_users()
data = client.get_all_global_users(True)

new_global_rule

rule_id = new_global_rule(**kwargs)

This method is used to add new global rules.

Parameters

NameData TypeRequiredDescription
conditionlistNoConditions that trigger the rule
conseqdictionary or listNoActions included in the rule
gidlistNoList of user group IDs

Returns

  • rule_id: ID of the successfully created global rule.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

condition = [
    {'var': 'host', 'val': 'con.' + APEX},
    {'var': ['req-header', 'Referer'], 'vals': [['foo\d+', 'rx'], 'foo.com']}
]

conseq = {
    'enable-websocket': {},
    'redirect': {'url': '/cn/2017/', 'code': 302}
}

rule_id = client.new_global_rule(condition=condition, conseq=conseq,gid=[1])

put_global_rule

ok = put_global_rule(**kwargs)

This method is used to modify the global rule.

Parameters

Parameter NameData TypeRequiredDescription
rule_idnumberYesUnique identifier of the rule
conditionlistNoDefines the conditions of the rule
conseqdict or listNoSpecifies the actions of the rule
gidlistNoList of user group ids

Returns

  • True: Indicates success.
  • False: Indicates failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

rule_id = 1

conseq['redirect']['url'] = '/cn/2018/'

ok = client.put_global_rule(
    rule_id=rule_id, condition=condition, conseq=conseq)

get_global_rule

data = get_global_rule(rule_id)

This method is used to obtain global rule information.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesThe unique identifier id of the rule

Returns

  • data: The return value is a dict type, containing detailed information of the global rule.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

rule_id = 1

data = client.get_global_rule(rule_id)

This example demonstrates how to use an instance of Edge2Client to obtain global rule information for a specific id.


get_global_action_by_name

rule_id = get_global_action_by_name(name)

This method is used to obtain the corresponding global custom action based on the given application name.

Parameters

Parameter NameData TypeRequiredDescription
namestringYesRule name

Returns

  • data: Returns a dict type data containing global rule information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

rule_name = 'test-actions'

rule_id = client.get_global_action_by_name(rule_name)

get_all_global_rules

data = get_all_global_rules()

This method is used to obtain all global rules.

Returns

  • data: This is a list type of global rule information list.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_global_rules()

del_global_rule

ok = del_global_rule(rule_id)

This method is used to delete the global rule.

Parameters

Parameter NameData TypeRequiredDescription
rule_idnumberYesUnique identifier of the rule

Returns

  • Returns True: The rule is successfully deleted.
  • Returns False: The rule deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

rule_id = 1

ok = client.del_global_rule(rule_id)

This example shows how to use the del_global_rule method of the Edge2Client object to delete a specified global rule.


new_global_var

var_id = new_global_var(**kwargs)

This method is used to create a new global variable.

Parameters

NameData TypeRequiredDescription
namestringYesThe name of the variable
var_typestringYesThe type of the variable
defaultstringYesThe default value of the variable
gidlistNoArray of user group IDs

Returns

  • var_id: If creation is successful, the ID of the newly created variable is returned.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = client.new_global_var(
    name='is-whitelist', var_type='string', default='no')

put_global_var

ok = put_global_var(**kwargs)

This method is used to modify global variables.

NameData TypeRequiredDescription
var_idnumberYesUnique identifier of the variable
namestringYesName of the variable
var_typestringYesData type of the variable
defaultstringYesDefault value of the variable
gidlistNoList of user group IDs

Returns

  • True: Indicates that the global variable was modified successfully.
  • False: Indicates that the modification of the global variable failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = 1

ok = client.put_global_var(
    var_id=var_id,
    name='is-whitelist',
    var_type='string',
    default='yes',
    gid=[1])

In this example, we first create an Edge2Client object and log in. Then, using the put_global_var() function, we modify the global variable with ID 1 by specifying the corresponding parameters, changing its name to ‘is-whitelist’, its type to ‘string’, its default value to ‘yes’, and associating it with the user group with ID 1.


get_global_var

data = get_global_var(var_id)

This method is used to get global variables.

Parameters

Parameter NameData TypeRequiredDescription
var_idnumberYesGlobal variable id

Returns

  • data: The return value is a dict type, containing information about the global variable.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = 1

data = client.get_global_var(var_id)

get_all_global_vars

data = get_all_global_vars()

This method is used to get all global variables.

Returns

  • data: This is a list-type object, each element of which is a dict-type that contains relevant information about the global variables.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password) # Create an Edge2Client instance
client.login() # Log in

data = client.get_all_global_vars() # Get all global variables

del_global_var

ok = del_global_var(var_id)

This method is used to delete a global variable by its ID.

Parameters

| Name | Data Type | Required | Description | | var_id | number | Yes | Specifies the ID of the global variable to be deleted |

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = 1

ok = client.del_global_var(var_id)

get_global_ngx_config

data = get_global_ngx_config()

This method is used to get global nginx configuration information.

Returns

  • data: Returns a dict type of global ngx configuration information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_global_ngx_config()

set_global_ngx_config

data = set_global_ngx_config(opts)

This method sets the global nginx configuration information.

Parameters

NameData TypeMandatoryDescription
access_log_buffernumberNoBuffer size for access log
access_log_buffer_unit[‘k’, ’m’, ‘g’]NoUnit of buffer size for access log
access_log_flushnumberNoMaximum retention time for access log in memory
enable_access_logboolNoWhether to enable access log
access_log_formatsdictNoFormat of access log
avoid_gen_error_logboolNoWhether to avoid generating error log
client_body_timeoutnumberNoTimeout for client request body
client_body_timeout_unit[’s’, ’m’]NoUnit for client request body timeout
client_header_timeoutnumberNoTimeout for client request header
client_header_timeout_unit[’s’, ’m’]NoUnit for client request header timeout
client_max_body_sizenumberNoMaximum size for client request body
client_max_body_size_unit[‘k’, ’m’]NoUnit for maximum client request body size
client_header_buffer_sizenumberNoBuffer size for client request header
client_header_buffer_size_unit[‘k’, ’m’]NoUnit for client request header buffer size
max_client_request_line_sizenumberNoMaximum size for client request line
max_client_request_header_size[‘k’, ’m’]NoMaximum size for client request header

access_log_formats Parameter

NameData TypeMandatoryDescription
defaultboolNoWhether this log format is the default. Note: At least one default log format is required in the configuration
namestringYesThe name of this access log format, it needs to be globally unique
formatstringYesThe format of this access log, it needs to be set according to the nginx log_format directive

Returns

  • True: Setting successful.
  • False: Setting failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

opts = {'keepalive_timeout': 10, 'enable_open_file_cache': False}
ok = client.set_global_ngx_config(opts)

get_global_misc_config

data = get_global_misc_config()

This method is used to obtain global miscellaneous configuration information.

Returns

  • data: Returns a dict type, which includes miscellaneous configuration information.

Examples

from edge2client import Edge2Client

# Create client and login
client = Edge2Client(host, username, password)
client.login()

# Get global miscellaneous configuration information
data = client.get_global_misc_config()

set_global_misc_config

ok = set_global_misc_config(opts)

This method is used to set global miscellaneous configuration information.

Parameters

Parameter NameData TypeRequiredDescription
optsDictionary (dict)NoMiscellaneous (misc) configuration items

Returns

  • True: Indicates the setting is successful.
  • False: Indicates the setting failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

opts = {'enabled_req_id': True}
ok = client.set_global_misc_config(opts)

get_request_id_status

status = get_request_id_status()

This method is used to query the status of the request id.

Returns

  • True: The request id is enabled.
  • False: The request id is disabled.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

status = client.get_request_id_status()

enable_request_id

ok = enable_request_id()

This method is used to activate the request id function.

Returns

  • True: Indicates activation was successful.
  • False: Indicates activation failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.enable_request_id()

disable_request_id

ok = disable_request_id()

This method is used to disable the request ID feature.

Returns

  • True: Represents that the request ID feature has been successfully disabled.
  • False: Indicates that the request ID feature failed to be disabled.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.disable_request_id()

new_global_waf_rule

rule_id = new_global_waf_rule(**kwargs)

This method is used to add a new global WAF rule.

Parameters

Parameter NameData TypeMandatoryDescription
namestringYesSpecified rule name
codestringYesEdge language code for the rule

Returns

  • rule_id: Returns the unique ID of the newly created global WAF rule set.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

waf_rule_id = client.new_global_waf_rule(
    name='foo',
    code="uri-arg('foo') => waf-mark-risk(level: 'definite', msg: 'found foo');")

In this example, we first create an instance of Edge2Client, then use the new_global_waf_rule method to create a new global WAF rule and store its rule ID in waf_rule_id. The rule name is ‘foo’, and the edge language code is “uri-arg(‘foo’) => waf-mark-risk(level: ‘definite’, msg: ‘found foo’);”.


put_global_waf_rule

ok = put_global_waf_rule(**kwargs)

This method is used to modify global WAF rules.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUnique identifier id of the rule
namestringYesName of the rule
codestringYesEdge language script of the rule

Returns

  • True: indicates modification is successful.
  • False: indicates modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

waf_rule_id = 1

ok = client.put_global_waf_rule(
    rule_id=waf_rule_id,
    name='bar',
    code="uri-arg('bar') => waf-mark-risk(level: 'definite', msg: 'found bar');")

In this example, we modify the global WAF rule with id 1 using the put_global_waf_rule function.


get_global_waf_rule

data = get_global_waf_rule(rule_id)

This method retrieves a global WAF rule set by using the provided rule set ID (rule_id).

Parameters

| Name | Data Type | Required | Description | | rule_id | number | Yes | The unique identifier of the WAF rule set |

Returns

  • data: Returns a dictionary containing detailed information about the WAF rule set.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

waf_rule_id = 1

data = client.get_global_waf_rule(waf_rule_id)

del_global_waf_rule

ok = del_global_waf_rule(rule_id)

This method is used to delete global WAF rules.

Parameters

| Name | Data Type | Required | Description | | rule_id | number | Yes | ID of the rule set |

Returns

  • True: Deletion successful.
  • False: Deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

waf_rule_id = 1

ok = client.del_global_waf_rule(waf_rule_id)

get_all_global_waf_rules

data = get_all_global_waf_rules(detail=False)

This method is used to retrieve all global WAF rules.

Parameters

NameData TypeRequiredDescription
detailboolNoIndicates whether to show detailed rules, default is False

Returns

  • data: Returns a list type of WAF rule set information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_global_waf_rules()

new_global_action

rule_id = new_global_action(**kwargs)

This method is used to add a new global custom action.

Parameters

NameData typeRequiredDescription
namestringYesThe name of the custom action
conditionlistNoThe conditions for executing the custom action
conseqdict or listYesThe custom action to execute
gidlistNoThe ID list of the user groups

Returns

  • rule_id: Returns the ID of the newly created global custom action.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

name = 'test'
condition = [
    {'var': 'req-method', 'vals': ['GET', 'POST', 'HEAD']}
]

conseq = [
    {
        'exit': {'code': 403}
    }
]

action_id = client.new_global_action(
    name=name, condition=condition, conseq=conseq, gid=[1, 2])

put_global_action

ok = put_global_action(**kwargs)

This method is used to modify the global custom action.

Parameters

ParameterData TypeRequiredDescription
action_idnumberYesThe id of the custom action
namestringNoThe name of the custom action
conditionlistNoThe execution condition of the custom action
conseqdict or listNoThe result of the custom action
gidlistNoList of user group ids

Returns

  • True: Represents the operation was successful.
  • False: Represents the operation failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

action_id = 1

ok = client.put_global_action(
    name=name,
    action_id=action_id,
    condition=condition,
    conseq=conseq,
    gid=[1])

get_global_action

data = get_global_action(action_id)

This method is used to obtain the global custom action.

Parameters

NameData TypeRequiredDescription
action_idnumberYesID of the custom action

Returns

  • data: The returned data is a dictionary containing relevant information about the global custom action.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

action_id = 1

data = client.get_global_action(action_id)

del_global_action

ok = del_global_action(action_id)

This method is used to delete a specified global custom action.

Parameters

NameData TypeRequiredDescription
action_idnumberYesID of the custom action

Returns

  • Returns True: Indicates successful deletion.
  • Returns False: Indicates deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

action_id = 1

ok = client.del_global_action(action_id)

count_global_actions

count = count_global_actions()

This method is used to get the total number of global custom actions.

Returns

  • count: Returns the total number of global custom actions.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

count = client.count_global_actions()

get_all_global_actions

data = get_all_global_actions()

This method is used to obtain all global custom actions.

Parameters

NameData TypeRequiredDescription
pagenumberNoRepresents the page number
pagesizenumberNoRepresents the number of entries displayed per page

Returns

  • data: Returns a list containing all global custom action information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_global_actions()

upload_static_file

file_id = upload_static_file(**kwargs)

This method is used to upload static files.

Parameters

NameData TypeRequiredDescription
contentstringYesContent of the static file
labelstringYesLabel of the static file
file_typestringNoType of the static file
gidlistNoList of user group IDs

Returns

  • file_id: Returns the ID of the newly uploaded static file.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

file_id = client.upload_static_file(content='test_content', label='500.html', gid=[1])

get_static_file

data = get_static_file(file_id)

This method is used to obtain the configuration of a specified static file.

Parameters

ParameterData TypeRequiredDescription
file_idnumberYesID of the static file to be retrieved

Returns

  • data: Returns a dict type object, containing the information of the retrieved static file.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

file_id = 1

data = client.get_static_file(file_id)

In this example, we first import the Edge2Client class from the edge2client module, then create an Edge2Client object and login. Afterwards, we call its get_static_file method to get the configuration information of the static file with ID 1, and store it in the data variable.


del_static_file

ok = del_static_file(file_id)

This method is used to delete uploaded static files.

Parameters

NameData TypeMandatoryDescription
file_idnumberyesID of the static file to be deleted

Returns

  • True: Indicates that the file was deleted successfully.
  • False: Indicates that the file deletion failed.

Examples

from edge2client import Edge2Client

# Create an Edge2Client instance
client = Edge2Client(host, username, password)

# Log in
client.login()

# Set the ID of the file to be deleted
file_id = 1

# Delete the static file with the specified ID
ok = client.del_static_file(file_id)

new_cluster_group

group_id = new_cluster_group(group_name)

This method is used to add a new cluster group.

Parameters

NameData TypeRequiredDescription
group_namestringYesName of the new cluster group

Returns

  • id: Returns the unique identifier ID of the newly created cluster group.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

group_id = client.new_cluster_group('foo')

put_cluster_group

ok = put_cluster_group(**kwargs)

This method is used to modify cluster group information.

Parameters

Parameter NameData TypeRequiredDescription
group_idnumberYesUnique identifier of the cluster group
group_namestringYesThe cluster group name to be changed

Returns

  • True: Indicates that the cluster group information was successfully modified.
  • False: Indicates that the modification of cluster group information failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

group_id = 1

ok = client.put_cluster_group(group_id=group_id, group_name='bar')

This example demonstrates how to use the put_cluster_group function to modify the name of the cluster group with the specified group_id to ‘bar’.


get_cluster_group

data = get_cluster_group(group_id)

This method is used to obtain detailed information of the cluster group.

Parameters

NameData TypeRequiredDescription
group_idNumericYesUnique identifier of the cluster group

Returns

  • data: Returns a dict type of detailed information of the cluster group.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

group_id = 1

data = client.get_cluster_group(group_id)

get_all_cluster_groups

data = get_all_cluster_groups()

This method is used to obtain information on all cluster groups.

Returns

  • data: This is a list type containing information on all cluster groups.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_cluster_groups()

del_cluster_group

ok = del_cluster_group(group_id)

This method is used to delete cluster group information.

Parameters

Parameter NameData TypeRequiredDescription
group_idnumberYesID of the cluster group to be deleted

Returns

  • Returns True: The cluster group information was successfully deleted.
  • Returns False: The cluster group information failed to be deleted.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

group_id = 1

ok = client.del_cluster_group(group_id)

In the example above, an Edge2Client object is initially initialized and logged in, then the ID of the cluster group to be deleted is specified, and the del_cluster_group method is invoked to perform the deletion operation.


put_proxy_rule

ok = put_proxy_rule(**kwargs)

This method is used to modify upstream proxy rules.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUnique identifier for the rule
proxylistYesList defining the proxy rules

Returns

  • True: Indicates that the rule modification was successful.
  • False: Indicates that the rule modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

rule_id = 1
proxy_rule = []

ok = client.put_proxy_rule(rule_id=rule_id, proxy=proxy_rule)

new_global_k8s

k8s_id = new_global_k8s(name=None, host=None, port=None, ssl_verify=True, token=None)

This method is used to add new k8s cluster connection parameters.

Parameters

NameData TypeRequiredDescription
namestringYesName of the k8s cluster
hoststringNoAddress of the k8s cluster
domainstringNoDomain of the k8s cluster, either host or domain must be filled and only one can be filled
portnumberYesPort of the k8s cluster
connect_timeoutnumberNoConnection timeout of the k8s cluster in seconds, default is 5 seconds
read_timeoutnumberNoData read timeout of the k8s cluster in seconds, default is 5 seconds
ssl_verifyboolNoWhether SSL verification is needed
tokenstringYesAPI token of the k8s cluster

Returns

  • k8s_id: ID of the newly established k8s cluster.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

k8s_id = client.new_global_k8s(name = "k8s", host = "192.168.1.1", port = 443, token = "xxxxx")

put_global_k8s

ok = put_global_k8s(**kwargs)

This method is used to modify the connection parameters of a Kubernetes cluster.

Parameters

NameData TypeRequiredDescription
k8s_idnumberYesUnique identifier of the Kubernetes cluster
namestringNoName of the Kubernetes cluster
hoststringNoHost address of the Kubernetes cluster
domainstringNoDomain of the Kubernetes cluster. At least one of host or domain is required and cannot be filled in at the same time
portnumberNoConnection port of the Kubernetes cluster
connect_timeoutnumberNoConnection timeout of the Kubernetes cluster, in seconds
read_timeoutnumberNoData reading timeout of the Kubernetes cluster, in seconds
ssl_verifyboolNoWhether SSL verification is required
tokenstringNoAPI token of the Kubernetes cluster

Returns

  • Returns True: Indicates success.
  • Returns False: Indicates failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.put_global_k8s(k8s_id = 1, name = "k8s", host = "192.168.1.1", port = 443, token = "xxxxx")

get_global_k8s

data = get_global_k8s(k8s_id)

This method is used to get the connection parameter information of a Kubernetes cluster.

Parameters

NameData TypeRequiredDescription
k8s_idnumberYesUnique identifier for the Kubernetes cluster

Returns

  • data: Returns a dict type of data that contains detailed information about the Kubernetes cluster.

Examples

from edge2client import Edge2Client

# Create an Edge2Client instance
client = Edge2Client(host, username, password)

# Log into the client
client.login()

# Use the get_global_k8s method to get Kubernetes cluster information
data = client.get_global_k8s(k8s_id = 1)

get_k8s_service_detail

data = get_k8s_service_detail()

This method is used to obtain the service-related information defined in the k8s cluster.

Parameters

NameData TypeMandatoryDetailed Description
k8s_idnumberYesUnique identifier of the k8s cluster

Returns

  • Returns a dict type of data, containing detailed information of the k8s cluster.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_k8s_service_detail(k8s_id = 1)

get_all_global_k8s

data = get_all_global_k8s()

This method is used to obtain the id of all global Kubernetes clusters.

Returns

  • data: Returns a list type of Kubernetes cluster information.

Application Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_k8s()

del_global_k8s

ok = del_global_k8s(k8s_id)

This method is used to delete the connection parameters of the k8s cluster.

Parameters

Parameter nameData typeRequiredDescription
k8s_idnumberYesUnique identifier of k8s cluster

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failure.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.del_global_k8s(k8s_id = 1)

The above code shows how to use Edge2Client to delete specific k8s cluster connection parameters.


update_proxy_rule

result = update_proxy_rule(**kwargs)

Update the specified upstream proxy rule.

Parameters

NameData TypeRequiredDescription
rule_idnumberYesUnique identifier of the rule
proxylistYesDetailed information of the proxy rule

Returns

  • True: Represents the proxy rule was successfully updated.
  • False: Represents the update of the proxy rule failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

rule_id = 1
proxy_rule = [...]

result = client.update_proxy_rule(rule_id=rule_id, proxy=proxy_rule)

This method is used to update the global level IP rule list.


new_global_ip_list

data = new_global_ip_list(name=None, type='ipv4', items=None)

This method is used to create a new global IP list.

Parameters

NameData TypeRequiredDescription
namestringYesName of the new global IP list to be created
typestringNoType of IP address, currently supports ipv4 or ipv6 (coming soon)
itemsarrayNoList of IP addresses included

items Parameter

NameData TypeRequiredDescription
ipstringYesIP address
exptimeintNoIP expiration time, in Unix timestamp. If not set, the IP is valid permanently

Returns

  • id: The unique ID of the newly created global IP list.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.new_global_ip_list(name = 'ip-list-1',
                               type = 'ipv4',
                               items = [
                                   {'ip': '127.0.0.0/24'},
                                   {'ip': '192.168.1.0/24'},
                                   {'ip': '192.168.2.0/24', 'exptime': 1725000000},
                                   {'ip': '192.168.3.0/24', 'exptime': 1735000000}
                               ])

put_global_ip_list

data = put_global_ip_list(rule_id=None, name=None, type='ipv4', items=None)

This method is used to modify the specified global-level IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberyesID of the specified global-level IP list
namestringyesName of the global-level IP list to be modified
typestringnoType of IP address, currently supporting ‘ipv4’ and soon supporting ‘ipv6’
itemsarraynoIP address list to be modified

Returns

  • True: Indicates the modification was successful.
  • False: Indicates the modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.put_global_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.2'} ])

del_global_ip_list

ok = del_global_ip_list(rule_id=None)

This method is used to delete a specified global IP list.

Parameters

Parameter NameData TypeRequiredDescription
rule_idnumberYesID of the global IP list to be deleted

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.del_global_ip_list(rule_id=1)

get_global_ip_list

data = get_global_ip_list(rule_id=None)

This method is used to get the specified global IP list.

Parameters

NameData TypeMandatoryDescription
rule_idnumberYesUsed to specify the ID of the global level IP list

Returns

  • data: Returns a dict type of IP list information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_global_ip_list(rule_id=1)

append_to_global_ip_list

ok = append_to_global_ip_list(rule_id, items)

This method is used to append the IPs to specified global-level IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberyesID of the specified global-level IP list
itemsarrayyesIP address list to be modified
remove_expiredboolNoWhether to remove expired IPs. Default is False. If set to True, expired IPs will be removed before appending new IPs

Returns

  • True: Indicates the modification was successful.
  • False: Indicates the modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.append_to_global_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.3'} ])

ok = client.append_to_global_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.3'} ], remove_expired = True)

remove_from_global_ip_list

ok = remove_from_global_ip_list(rule_id, items)

This method is used to remove the IPs from specified global-level IP list.

Parameters

NameData TypeRequiredDescription
rule_idnumberyesID of the specified global-level IP list
itemsarrayyesIP address list to be modified

Returns

  • True: Indicates the modification was successful.
  • False: Indicates the modification failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.remove_from_global_ip_list(rule_id = 1, items = [ {'ip': '127.0.0.3'} ])

new_user_var

var_id = new_user_var(**kwargs)

This is a function for adding new user-level variables.

Parameters

NameData TypeRequiredDescription
namestringYesVariable name
var_typestringYesVariable type
defaultstringYesDefault value

Returns

  • id: Returns the unique ID of the newly created user-level variable.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = client.new_user_var(
    name='is-whitelist',
    var_type='string',
    default='no')

put_user_var

ok = put_user_var(**kwargs)

This method is used to modify user-level variables.

Parameters

NameData TypeRequiredDescription
var_idnumberYesUnique identifier for the variable
namestringYesName of the variable
var_typestringYesType of the variable
defaultstringYesDefault value of the variable

Returns

  • True: Indicates that the user-level variable was successfully modified.
  • False: Indicates that the modification of the user-level variable failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = 1

ok = client.put_user_var(var_id=var_id,
                         name='is-whitelist',
                         var_type='string',
                         default='yes')

Please note, this example will set the value of the variable named ‘is-whitelist’ to ‘yes’.


get_user_var

data = get_user_var(var_id)

This method is used to obtain user-level variables.

Parameters

NameData TypeMandatoryDescription
var_idnumberYesThe unique identifier of the variable

Returns

  • data: Returns a dict type, including detailed information about the user variable.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = 1

data = client.get_user_var(var_id)

del_user_var

ok = del_user_var(var_id)

This method is used to delete user-level variables.

Parameters

NameData TypeRequiredDescription
var_idnumberYesThe id of the variable to delete

Returns

  • True: Variable deletion successful.
  • False: Variable deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

var_id = 1

ok = client.del_user_var(var_id)

In this example, we first import Edge2Client from the edge2client module. Then, we create an instance of Edge2Client and use it to log in. Finally, we attempt to delete the user-level variable with var_id of 1.


decode_request_id

data = decode_request_id(request_id)

This method is used to decode request_id to get information such as app_id.

Parameters

| Name | Data Type | Required | Description | | request_id | String | Yes | Request ID |

Returns

  • data: Returns a dictionary type of data, which includes information about the gateway, application, etc. that processes the request.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.decode_request_id('00000a00000c0826c9803222')

print(data)

search_waf_log

data = search_waf_log(request_id)

This method is used to get the WAF log through the request id.

Parameters

ParameterData TypeRequiredDescription
request_idstringYesUnique identifier of the request

Returns

  • data: Returns a dict type of WAF log information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

request_id = "0000008000042c421ea80011"

data = client.search_waf_log(request_id)

This example shows how to use the Edge2Client instance to call the search_waf_log function and get the WAF log.


get_version

data = get_version()

This method is used to get the version information of Admin, Admin DB, Log Server, Log Server DB and WAF.

Returns

  • data: Returns a dict type that contains version information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_version()

add_api_token

data = add_api_token(name=None, expire=0)

This method is used to generate an API Token.

Parameters

NameData TypeRequiredDescription
namestringNoThe name of the API Token
expirenumberNoThe expiration time of the API Token

Returns

  • data: Returns a dict type, containing detailed information about the API Token.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.add_api_token("name", 0)

get_api_token

data = get_api_token(id=None, limit=20)

This method is used to acquire an API token.

Parameters

ParameterData TypeRequiredDescription
idnumberNoIdentifier of the API token
limitnumberNoLimit on the number of returned results

Returns

  • data: Returns the information about the API token in dict type.

Examples

from edge2client import Edge2Client

# Create client and login
client = Edge2Client(host, username, password)
client.login()

# Acquire the API token of a specified id
data = client.get_api_token(id)

# Acquire the API token limited to 100
data = client.get_api_token(None, 100)

del_api_token

ok = del_api_token(id)

This method is used to delete a specified API Token.

Parameters

ParameterData TypeRequiredDescription
idnumberNoIdentifier of API token

Returns

  • Returns True: Indicates the API Token was successfully deleted.
  • Returns False: Indicates the API Token deletion failed.

Examples

from edge2client import Edge2Client

# Create an instance of Edge2Client
client = Edge2Client(host, username, password)

# Log in
client.login()

# Delete a specified API Token
data = client.del_api_token(id)

get_all_gateway_tag

tags = get_all_gateway_tag()

This method is used to obtain tags for all gateway clusters.

Returns

  • data: Returns a list type containing all gateway tag information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

tags = client.get_all_gateway_tag()

for i, tag in enumerate(tags):
    print(i, tag)

get_all_gateway

gateways = get_all_gateway()

This method is used to get the information of all gateway clusters.

Returns

  • data: Returns a list type, containing detailed information of all gateways.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)  # Create and initialize an instance of Edge2Client
client.login()  # Log in to the server

gateways = client.get_all_gateway()  # Get information of all gateway clusters

# Loop to print all gateway information
for i, gateway in enumerate(gateways):
    print(i, gateway)

add_gateway

id = add_gateway(name, partition_id, tag=None)

This method is used to create a new gateway cluster.

Parameters

ParameterData TypeRequiredDescription
namestringYesThe name of the gateway cluster
partition_idstringYesThe ID of the gateway partition to which the created gateway cluster belongs
tagarrayNoThe tag used to mark the created gateway cluster

Returns

  • id: Returns the unique ID of the newly created gateway cluster.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

default_partition_id = 1
id = client.add_gateway('my-cluster', default_partition_id)

del_gateway

ok = del_gateway(gateway_id)

This method is used to delete a specified gateway cluster.

Parameters

ParameterData TypeRequiredDescription
gateway_idstringYesThe unique identifier of the gateway cluster to be deleted

Returns

  • True: Indicates that the gateway cluster has been successfully deleted.
  • False: Indicates that the gateway cluster deletion failed.
true

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

gateway_id = 1
ok = client.del_gateway(gateway_id)

In this example, we first create a client using Edge2Client, and then log in. Next, we try to delete the gateway cluster with an ID of 1, and store the result in the variable ok.


get_all_nodes

nodes = get_all_nodes()

This method is used to obtain all gateway nodes.

Returns

  • data: This return value is a list type, containing all relevant information about gateway nodes (servers).

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

nodes = client.get_all_nodes()

for i, node in enumerate(nodes):
    print(i, node)

get_node

node = get_node(node_id, gateway_id=None)

This method retrieves the node information corresponding to the provided node ID.

Parameters

NameData TypeRequiredDescription
node_idnumberYesUnique identifier (ID) of the node
gateway_idnumberNoUnique identifier (ID) of the gateway cluster, used to locate the node if not specified

Returns

  • Returns a dict type that contains relevant information about the gateway node.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

node = client.get_node(1)  # Get node information for node ID 1
node = client.get_node(1, gateway_id=1)  # Within the scope of gateway cluster ID 1, get node information for node ID 1

get_node_by_mac_address

node = get_node_by_mac_address(mac_address)

This method is used to retrieve the detailed information of a node based on the node’s hardware ID.

Parameters

Parameter NameData TypeMandatoryDescription
mac_addressstringYesThe specific MAC address of the node

Returns

  • node: Returns a dict type gateway node detailed information.
{
    "mac_address": "46:b1:5f:1d:fa:ea",
    "serial": "2655388572",
    "is_limited": false,
    "config": {
        "enable_qat": false
    },
    "name": "test-edge-node-75c5bf6969-65tgg\n",
    "id": 11,
    "external_ip": "172.20.0.2",
    "sync_status_utime": 0,
    "online_status": true,
    "internal_ip": "10.244.0.6",
    "hardware_id": "a11abe66fe25be7941bda81c3f358344",
    "is_healthy": true,
    "status": 1,
    "gateway_id": 14
}

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

node = client.get_node_by_mac_address("e2:d1:d9:e0:c4:6e")

put_node

ok = put_node(node_id, gateway_id=None, **kwargs)

This method is used for updating node information.

Parameters

NameData TypeRequiredDescription
node_idnumberYesID of the node
gateway_idnumberNoCluster ID of the gateway. If not specified, the corresponding node will be found by traversal.
namestringNoName of the node
is_grayboolNoSet/unset the node as a gray node
statusnumberNo0: Disable DNS, enable cluster cache, 1: Enable DNS, enable cluster cache, 2: Disable DNS, disable cluster cache
external_ipstringNoPublic IP address
external_ipv6stringNoPublic IPv6 address
internal_ipstringNoInternal IP address

Returns

  • True: If the operation is successful.
  • False: If the operation fails.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

node_id=1
gateway_id=1
ok = self.client.put_node(node_id, \
    gateway_id=gateway_id, name='test', \
    is_gray=False, status=1, external_ip='127.0.0.1', \
    external_ipv6='::1', internal_ip='127.0.0.1')

del_node

node = del_node(node_id, gateway_id=None)

This method is used to delete a specific node according to its node ID.

Parameters

Parameter NameData TypeIs RequiredDescription
node_idnumberYesID of the node to be deleted
gateway_idnumberNoID of the gateway cluster. If not specified, the system will traverse to find the corresponding node

Returns

  • True: Indicates successful deletion.
  • False: Indicates deletion failed.
true

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

success = client.del_node(1)
success = client.del_node(1, gateway_id=1)

lmdb_backup

ok = lmdb_backup()

This method is used to trigger the backup of LMDB. If the backup is successful, the method will return True. If the backup fails, it will return a dict information containing the failed Node nodes, where the key is the Node ID and the value is the reason for the failure.

You can confirm whether the backup is successful by calling the node_sync_status interface. If the backup_time of the node in this interface is greater than the call time of the lmdb_backup() method, then it can be considered that the backup of this node has been successfully executed.

Returns

  • True: Indicates that the backup is successful.
  • False: Indicates that the backup failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

result = self.client.lmdb_backup()

get_global_cert_referenced

result = get_global_cert_referenced(id)

This method is used to get a list of applications that use the specified global certificate.

Parameters

NameData TypeRequiredDescription
idnumberYesGlobal Certificate ID

Returns

  • data: Returns a list type containing application information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()
global_cert_id = 1
result = client.get_global_cert_referenced(global_cert_id)

get_all_partition_lua_module

data = get_all_partition_lua_module(partition_id)

This method is used to obtain all Lua modules of the specified partition.

Parameters

NameData TypeRequiredDescription
partition_idnumberYesUnique identifier ID of the partition

Returns

  • data: Returns a list, containing all the Lua module information of the queried partition.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()
partition_id = 1
result = client.get_all_partition_lua_module(partition_id)

get_partition_lua_module

data = get_partition_lua_module(partition_id, module_id)

This method is used to get the specified lua module in the specified partition.

Parameters

Parameter NameData TypeRequiredDescription
partition_idnumberYesPartition ID
module_idnumberYesModule ID

Returns

  • data: Returns a dict type of global Lua module information.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()
partition_id = 1
module_id = 1
result = client.get_partition_lua_module(partition_id, module_id)

new_partition_lua_module

data = new_partition_lua_module(partition_id, name, code)

This method is used to add a new Lua module to the specified partition.

Parameters

NameData TypeRequiredDescription
partition_idnumberYesPartition ID
namestringYesModule name
codestringYesModule code

Returns

  • data: Returns a dictionary type of data, containing the ID of the newly created Lua module.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

partition_id = 1
name = "example"
code = """
local _M = {}
return _M
"""
result = client.new_partition_lua_module(partition_id, name, code)

put_partition_lua_module

ok = put_partition_lua_module(partition_id, module_id, name, code)

This method is used to edit a specific lua module in a specified partition.

Parameters

NameData TypeRequiredDetailed Description
partition_idnumberYesID of the partition
module_idnumberYesID of the module
namestringNoName of the module
codestringNoCode of the module

Returns

  • True: indicates the operation was successful.
  • False: indicates the operation failed.

For example:

true

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

partition_id = 1
module_id = 1
name = "example"
code = """
local _M = {}
return _M
"""
result = self.client.put_partition_lua_module(partition_id, module_id, name, code)

del_partition_lua_module

result = del_partition_lua_module(partition_id, module_id)

This method is used to delete a specific lua module within a specified partition.

Parameters

NameData TypeRequiredDescription
partition_idnumberYesPartition ID
module_idnumberYesModule ID

Returns

  • Returns True if successful.
  • Returns False if failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

partition_id = 1
module_id = 1
result = self.client.del_partition_lua_module(partition_id, module_id)

conv_crl_to_lua_module

code = conv_crl_to_lua_module(crl_files)

This method is used to convert CRL files into Lua modules.

Parameters

Parameter NameData TypeRequiredDescription
crl_filesarrayYesArray of CRL files

Returns

  • code: The converted Lua module code after completion.

Examples

import sys

from edge2client import Edge2Client

client = Edge2Client('https://your-admin-addr', 'your-admin-user', 'your-admin-password')

crl_files = ["~/test.crl"]
code = client.conv_crl_to_lua_module(crl_files)

client.login()

partition_id = 1
name = "crl_test.com"

result = client.new_partition_lua_module(partition_id, name, code)
mod_id = result["id"]

result = client.put_partition_lua_module(partition_id, mod_id, name, code)
print(result)

get_all_candidate_node

nodes = get_all_candidate_node()

This method is used to get all nodes waiting for approval. Subsequently, these nodes can be approved to join the specified cluster by calling the approve_candidate_node interface.

Returns

  • nodes: returns a list type, containing detailed information of all candidate gateway nodes.

For example:

[
    {
        "priv_hash": "0ab3a37cfea7d044c93a46712053a081",
        "external_ipv6": "",
        "external_ip": "172.20.0.2",
        "hostname": "test-edge-node-75c5bf6969-65tgg\n",
        "client_city": "/",
        "internal_ip": "10.244.0.3",
        "os": "Linux\n3.10.0-1127.19.1.el7.x86_64\n",
        "hardware_id": "3e20ff1b92ca06e03b2ab0d877687662",
        "mac_address": "9e:18:28:f5:1b:d5",
        "csr": "..."
    }
]

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

nodes = client.get_all_candidate_node()

approve_candidate_node

ok = approve_candidate_node(gateway_id, mac_address, internal_ip=None, external_ip=None, name=None, external_ipv6=None, status=1)

Approves the node with the MAC address mac_address to join the gateway cluster with the ID gateway_id.

Parameters

Parameter NameData TypeRequiredDescription
gateway_idnumberYesID of the gateway cluster, if not specified, the corresponding node will be found through traversal
mac_addressstringYesMAC address of the node
internal_ipstringNoInternal IPv4 address of the node
external_ipstringNoExternal IPv4 address of the node
namestringNoName of the node, if not named, the hostname will be used by default
external_ipv6stringNoExternal IPv6 address of the node
statusstringNoNode status, 0 for disabled, 1 for enabled, 2 for disconnected (DNS disabled and cluster cache sharing disabled)

Returns

  • True: Approval success.
  • False: Approval failed.

Examples

The following example shows how to approve the node with the host name “new-edge-node” to join the gateway cluster with ID 1.

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()
def first_address(addrs):
    return addrs.split(' ')[0]

gateway_id=1
nodes = client.get_all_candidate_node()
for i, node in enumerate(nodes):
    if nodes.get('hostname') == "new-edge-node":
        ok = client.approve_candidate_node(gateway_id, first_address(nodes.get('mac_address')))
        break

get_waf_logs

data, count = get_waf_logs(app_id, page=1, pagesize=20, request_id=None,
                  start_time=None, end_time=None, host=None, header=None,
                  rule_set_id=None, resp_status=None, action=None,
                  remote_addr=None, show_all=False)

This method is used to retrieve the WAF logs of the specified application.

Parameters

Parameter NameData TypeRequiredDescription
app_idnumberYesID of the HTTP application
pagenumberNoSpecifies the page number to retrieve
pagesizenumberNoSpecifies the number of logs per page
request_idstringNoRetrieves the logs of a specific request ID
start_timenumberNoRetrieves the logs within a specific time range, the start time is a Unix timestamp, measured in seconds
end_timenumberNoRetrieves the logs within a specific time range, the end time is a Unix timestamp, measured in seconds
hoststringNoRetrieves the logs containing a specific host
headerstringNoRetrieves the logs containing a specific request header
rule_set_idnumberNoRetrieves the logs containing a specific rule set ID
resp_statusnumberNoRetrieves the logs containing a specific response status code
actionstringNoRetrieves the logs containing a specific action, value: log, block, edge-captcha, hcaptcha, redirect, page-template, close-connection, redirect-validate, js-challenge
remote_addrstringNoRetrieves the logs containing a specific client address
show_allboolNoIndicates whether to get all logs. When False, logs not reaching the threshold are not returned. When True, logs are returned regardless of the threshold size

Returns

  • data: The list of logs retrieved this time, list type.
  • count: The total number of logs, note that this is not the number of logs retrieved this time.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

page = 1
while True:
    logs, count = get_waf_logs(app_id, page=page, pagesize=10,
                                start_time=1698888000,
                                end_time=1699988000)

    if logs is None:
        break

    if len(logs) <= 0:
        break

    for log in logs:
        print(log)

    page = page + 1

get_dos_logs

data, count = get_dos_logs(app_id, page=1, pagesize=20, request_id=None,
                     start_time=None, end_time=None, host=None, uri=None,
                     user_agent=None, action=None, remote_addr=None):

This method is used to retrieve the Dos logs of the specified application.

Parameters

Parameter NameData TypeRequiredDescription
app_idnumberYesID of the HTTP application
pagenumberNoSpecifies the page number to retrieve
pagesizenumberNoSpecifies the number of logs per page
request_idstringNoRetrieves the logs of a specific request ID
start_timenumberNoRetrieves the logs within a specific time range, the start time is a Unix timestamp, measured in seconds
end_timenumberNoRetrieves the logs within a specific time range, the end time is a Unix timestamp, measured in seconds
hoststringNoRetrieves the logs containing a specific host
uristringNoRetrieves the logs containing a specific URI
user_agentnumberNoRetrieves the logs containing a specific User Agent
actionstringNoRetrieves the logs containing a specific action, value: close_connection, error_page, enable_hcaptcha, enable_edge_captcha, redirect_validate, js_challenge, delay
remote_addrstringNoRetrieves the logs containing a specific client address

Returns

  • data: The list of logs retrieved this time, list type.
  • count: The total number of logs, note that this is not the number of logs retrieved this time.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

page = 1
while True:
    logs, count = get_waf_logs(app_id, page=page, pagesize=10,
                                start_time=1698888000,
                                end_time=1699988000)

    if logs is None:
        break

    if len(logs) <= 0:
        break

    for log in logs:
        print(log)

    page = page + 1

get_global_page_template

data = get_global_page_template(id)

This method is used to obtain the specified global page template.

Parameters

Parameter NameData TypeRequiredDescription
idnumberYesID of the global page template

Returns

  • data: The global page template retrieved this time, of dict type.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_global_page_template(id)

get_all_global_page_templates

data = get_all_global_page_templates()

This method is used to obtain all global page templates.

Returns

  • data: The list of global page templates retrieved this time, of list type.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

templates = client.get_all_global_page_templates()
for t in templates:
    print(t)

del_global_page_template

ok = del_global_page_template(id)

This method is used to delete the specified global page template.

Parameters

Parameter NameData TypeRequiredDescription
idnumberYesID of the global page template

Returns

  • True: Deletion successful.
  • False: Deletion failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

ok = client.del_global_page_template(id)

new_global_page_template

id = new_global_page_template(name, content)

This method is used to create a new global page template.

Parameters

Parameter NameData TypeRequiredDescription
namestringYesName of the global page template
contentstringYesContent of the global page template

Returns

  • id: Returns the unique ID of the newly created global page template.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

name = "default"
content = """
<!doctype html>
<html>
<head>
  <title>404 NOT FOUND</title>
</head>
<body>
  ::CLIENT_IP::
</body>
</html>
"""
id = client.new_global_page_template(name=name, content=content)

put_global_page_template

ok = put_global_page_template(id, name=None, content=None)

This method is used to update the specified global page template.

Parameters

Parameter NameData TypeRequiredDescription
idnumberYesID of the global page template
namestringNoName of the global page template
contentstringNoContent of the global page template

At least one of name or content must be specified.

Returns

  • True: Update successful.
  • False: Update failed.

Examples

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

name = "newname"
ok = client.put_global_page_template(name=name, content=content)

get_app_basic_auth_user_group

data = get_app_basic_auth_user_group(id, app_id=None)

This method is used to get the Basic Auth user group information in the specified application.

Parameters

Parameter nameData typeMandatoryDescription
idnumberYesID of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • data: The Basic Auth user group information retrieved this time, dict type.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

group_id = 1
data = client.get_app_basic_auth_user_group(group_id)

get_all_app_basic_auth_user_groups

data = get_all_app_basic_auth_user_groups(app_id=None)

This method is used to get all Basic Auth user group information in the specified application.

Parameters

Parameter nameData typeMandatoryDescription
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • data: The list of Basic Auth user groups retrieved this time, list type.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
# client.use_app(app_id)

groups = client.get_all_app_basic_auth_user_groups(app_id)
for g in groups:
    print(g)

del_app_basic_auth_user_group

ok = del_app_basic_auth_user_group(id, app_id=None)

This method is used to delete the specified Basic Auth user group information in the specified application.

Parameters

Parameter nameData typeMandatoryDescription
idnumberYesID of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • True: Delete successful.
  • False: Delete failed.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

group_id = 1
ok = client.del_app_basic_auth_user_group(group_id)

new_app_basic_auth_user_group

id = new_app_basic_auth_user_group(name, label=None, app_id=None)

This method is used to create a Basic Auth user group in the specified application.

Parameters

Parameter nameData typeMandatoryDescription
namestringYesName of the Basic Auth user group
labelstringNoLabel of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • id: Return the unique ID of the newly created Basic Auth user group.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

name = "default"
label = "default label"
id = client.new_app_basic_auth_user_group(name, label)

put_app_basic_auth_user_group

ok = put_app_basic_auth_user_group(id, name=None, label=None, app_id=None)

This method is used to update the specified Basic Auth user group information in the specified application.

Parameters

Parameter nameData typeMandatoryDescription
idnumberYesID of the Basic Auth user group
namestringNoName of the Basic Auth user group
labelstringNoLabel of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

At least one of name and label must be specified.

Return Value

  • True: Update successful.
  • False: Update failed.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

group_id = 1
name = "new-name"
label = "new-label"
ok = client.put_app_basic_auth_user_group(group_id, name=name, label=label)

get_app_basic_auth_user

data = get_app_basic_auth_user(id, group_id, app_id=None)

This method is used to get the information of the specified user in the Basic Auth user group of the specified application.

Parameters

Parameter nameData typeMandatoryDescription
idnumberYesID of the Basic Auth user
group_idnumberYesID of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • data: The Basic Auth user information retrieved this time, dict type.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

user_id = 1
group_id = 1
data = client.get_app_basic_auth_user(user_id, group_id)

get_app_basic_auth_users_in_group

data = get_app_basic_auth_users_in_group(group_id, app_id=None)

This method is used to get all user information in the Basic Auth user group of the specified application.

Parameters

Parameter nameData typeMandatoryDescription
group_idnumberYesID of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • data: The list of Basic Auth users retrieved this time, list type.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

group_id = 1
users = client.get_app_basic_auth_users_in_group(group_id)
for u in users:
    print(u)

del_app_basic_auth_user

ok = del_app_basic_auth_user(id, group_id, app_id=None)

This method is used to delete the information of the specified user in the Basic Auth user group of the specified application.

Parameters

Parameter nameData typeMandatoryDescription
idnumberYesID of the Basic Auth user
group_idnumberYesID of the Basic Auth user group
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • True: Delete successful.
  • False: Delete failed.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

user_id = 1
group_id = 1
ok = client.del_app_basic_auth_user(user_id, group_id)

new_app_basic_auth_user

id = new_app_basic_auth_user(group_id, username, password, app_id=None)

This method is used to create a user in the Basic Auth user group of the specified application.

Parameters

Parameter nameData typeMandatoryDescription
group_idnumberYesID of the user group to which the Basic Auth user belongs
usernamestringYesName of the Basic Auth user
passwordstringYesPassword of the Basic Auth user
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • id: Return the unique ID of the newly created Basic Auth user.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

group_id = 1
username = "username1"
password = "password"
id = client.new_app_basic_auth_user(group_id, username, password)

put_app_basic_auth_user

ok = put_app_basic_auth_user(id, group_id, username, password, app_id=None)

This method is used to update the information of the specified user in the Basic Auth user group of the specified application.

Parameters

Parameter nameData typeMandatoryDescription
idnumberYesID of the Basic Auth user
group_idnumberYesID of the user group to which the Basic Auth user belongs
usernamestringYesName of the Basic Auth user
passwordstringYesPassword of the Basic Auth user
app_idnumberNoID of the HTTP application, can be omitted if specified with use_app

Return Value

  • True: Update successful.
  • False: Update failed.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
client.use_app(app_id)

user_id = 1
group_id = 1
username = "new-username"
password = "new-password"
ok = client.put_app_basic_auth_user(user_id, group_id, username, password)

new_acme_provider

provider_id = new_acme_provider(name=None, endpoint=None,
                                eab_hmac_key=None, eab_kid=None,
                                email=None)

This method is used to add an ACME provider/issuer.

Parameters

NameData TypeRequiredDescription
namestringYesName of the ACME provider
endpointstringYesEndpoint information for obtaining ACME certificates
eab_hmac_keystringNoHMAC key associated with the ACME provider’s account
eab_kidnumberNoKey identifier associated with the ACME provider’s account
emailnumberNoEmail associated with the ACME provider’s account

Return Value

  • provider_id: The ID of the newly created ACME provider information.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

endpoint = "https://acme.zerossl.com/v2/DV90"
email = "oredge-sdk@openresty.com"
eab_hmac_key = "abcdefghijklmnopqrstuvwxyz"
eab_kid = "_abcdefghijklmnopqrstuvwxyz_dL4"
provider_id = self.client.new_acme_provider(name="zerossl",
                                            endpoint=endpoint,
                                            eab_hmac_key=eab_hmac_key,
                                            eab_kid=eab_kid, email=email)

put_acme_provider

ok = put_acme_provider(**kwargs)

This method is used to modify the information of an ACME provider.

Parameters

NameData TypeRequiredDescription
idintegerYesID of the ACME provider
namestringYesName of the ACME provider
endpointstringYesEndpoint information for obtaining ACME certificates
eab_hmac_keystringNoHMAC key associated with the ACME provider’s account
eab_kidnumberNoKey identifier associated with the ACME provider’s account
emailnumberNoEmail associated with the ACME provider’s account

Return Value

  • Returns True: indicates success.
  • Returns False: indicates failure.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

new_endpoint = "https://acme.zerossl.com/v2/DV90new"
new_email = "oredge-sdk-new@openresty.com"
new_eab_hmac_key = "abcdefghijklmnopqrstuvwxyz-new"
new_eab_kid = "_abcdefghijklmnopqrstuvwxyz_dL4_new"
ok = self.client.put_acme_provider(id=provider_id,
                                    name=f"new_zerossl",
                                    endpoint=new_endpoint,
                                    eab_hmac_key=new_eab_hmac_key,
                                    eab_kid=new_eab_kid, email=new_email)

get_acme_provider

data = get_acme_provider(provider_id)

This method is used to retrieve information about an ACME provider.

Parameters

NameData TypeRequiredDescription
idnumberYesUnique identifier of the ACME provider

Return Value

  • data: Returns a dict containing detailed information about the ACME provider.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)

client.login()

provider_id = 1
data = client.get_acme_provider(provider_id)

get_all_acme_providers

data = get_all_acme_providers()

This method is used to retrieve information about all ACME providers.

Return Value

  • data: Returns a list of information about ACME providers.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

data = client.get_all_acme_providers()

del_acme_provider

ok = del_acme_provider(id)

This method is used to delete information about an ACME provider.

Parameters

Parameter NameData TypeRequiredDescription
idnumberYesUnique identifier of the ACME provider record

Return Value

  • True: indicates successful deletion.
  • False: indicates deletion failure.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

provider_id = 1
ok = client.del_acme_provider(provider_id)

The above code demonstrates using Edge2Client to delete a specific ACME provider record.


get_acme_logs

data, count = client.get_acme_logs(cert_id)

This method is used to retrieve the issuance logs for a specified ACME certificate, with a maximum of 100 records.

Parameters

Parameter NameData TypeRequiredDescription
cert_idnumberYesID of the ACME certificate

Return Values

  • data: A list of logs retrieved in this query, of type list.
  • count: The total number of logs, note that this is not the number of logs retrieved in this query.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

cert_id = 1
logs, count = client.get_acme_logs(cert_id)

get_node_error_logs

data, count = client.get_node_error_logs(page=1, page_size=10,
                       node_id=None, req_id=None, level=None,
                       start_time=None, end_time=None)

This method is used to retrieve error logs for Edge Nodes.

Parameters

Parameter NameData TypeRequiredDescription
pagenumberNoSpecifies the page number to retrieve
page_sizenumberNoSpecifies the number of logs per page
node_idstringNoRetrieves error logs for one or more specified Edge Nodes
req_idstringNoRetrieves error logs for a specified request
levelstringNoRetrieves error logs of a specified level. Log levels include: stderr, emerg, alert, crit, error, warn, notice, info, debug
start_timenumberNoRetrieves logs within a specific time range, start time as Unix timestamp in seconds
end_timenumberNoRetrieves logs within a specific time range, end time as Unix timestamp in seconds

Return Values

  • data: A list of logs retrieved in this query, of type list.
  • count: The total number of logs, note that this is not the number of logs retrieved in this query.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

logs, count = client.get_node_error_logs(page=1, page_size=10,
                            start_time=1698888000,
                            end_time=1699988000)

get_admin_error_logs

data, count = client.get_admin_error_logs(page=1, page_size=10, level=None,
                       start_time=None, end_time=None)

This method is used to retrieve error logs for Edge Admin.

Parameters

Parameter NameData TypeRequiredDescription
pagenumberNoSpecifies the page number to retrieve
page_sizenumberNoSpecifies the number of logs per page
levelstringNoRetrieves error logs of a specified level. Log levels include: stderr, emerg, alert, crit, error, warn, notice, info, debug
start_timenumberNoRetrieves logs within a specific time range, start time as Unix timestamp in seconds
end_timenumberNoRetrieves logs within a specific time range, end time as Unix timestamp in seconds

Return Values

  • data: A list of logs retrieved in this query, of type list.
  • count: The total number of logs, note that this is not the number of logs retrieved in this query.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

logs, count = client.get_admin_error_logs(page=1, page_size=10,
                            start_time=1698888000,
                            end_time=1699988000)

get_log_server_error_logs

data, count = client.get_log_server_error_logs(page=1, page_size=10, level=None,
                       start_time=None, end_time=None)

This method is used to retrieve error logs for Edge Log Server.

Parameters

Parameter NameData TypeRequiredDescription
pagenumberNoSpecifies the page number to retrieve
page_sizenumberNoSpecifies the number of logs per page
levelstringNoRetrieves error logs of a specified level. Log levels include: stderr, emerg, alert, crit, error, warn, notice, info, debug
start_timenumberNoRetrieves logs within a specific time range, start time as Unix timestamp in seconds
end_timenumberNoRetrieves logs within a specific time range, end time as Unix timestamp in seconds

Return Values

  • data: A list of logs retrieved in this query, of type list.
  • count: The total number of logs, note that this is not the number of logs retrieved in this query.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

logs, count = client.get_log_server_error_logs(page=1, page_size=10,
                            start_time=1698888000,
                            end_time=1699988000)

get_http_app_error_logs

data, count = client.get_http_app_error_logs(page=1, page_size=10, app_id=None,
                       node_id=None, req_id=None, level=None,
                       start_time=None, end_time=None)

This method is used to retrieve error logs for a specified HTTP application.

Parameters

Parameter NameData TypeRequiredDescription
app_idstringNoRetrieves error logs for a specified HTTP application
pagenumberNoSpecifies the page number to retrieve
page_sizenumberNoSpecifies the number of logs per page
node_idstringNoRetrieves error logs for one or more specified Edge Nodes
req_idstringNoRetrieves error logs for a specified request
levelstringNoRetrieves error logs of a specified level. Log levels include: stderr, emerg, alert, crit, error, warn, notice, info, debug
start_timenumberNoRetrieves logs within a specific time range, start time as Unix timestamp in seconds
end_timenumberNoRetrieves logs within a specific time range, end time as Unix timestamp in seconds

Return Values

  • data: A list of logs retrieved in this query, of type list.
  • count: The total number of logs, note that this is not the number of logs retrieved in this query.

Example

from edge2client import Edge2Client

client = Edge2Client(host, username, password)
client.login()

app_id = 1
logs, count = client.get_http_app_error_logs(app_id=app_id, page=1, page_size=10,
                            req_id="000028800bac65d7fed03afd",
                            start_time=1698888000,
                            end_time=1699988000)