code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
# zuora-aqua-client-cli [](https://travis-ci.com/molnarjani/zuora-aqua-client-cli)
Run ZOQL queries through AQuA from the command line
# Installation
#### Mac
`pip3 install zuora-aqua-client-cli`
The executable will be installed to `/usr/local/bin/zacc`
#### Linux
`pip3 install zuora-aqua-client-cli`
The executable will be installed to `~/.local/bin/zacc`
Make sure `~/.local/bin/` is added to your `$PATH`
# Configuration
Configuration should be provided by the `-c /path/to/file` option.
If option is not provided, will be read from `~/.zacc.ini`
#### Example config
```
[zacc]
# When environement option is ommited the default environment will be used
default_environment = preprod
[prod]
# Use production Zuora endpoints, defaults to `false`
production = true
client_id = <oauth_client_id>
client_secret = <oauth_client_secret>
# Optional partner and project fields can be configured per environment, see more on what these do:
# https://knowledgecenter.zuora.com/Central_Platform/API/AB_Aggregate_Query_API/B_Submit_Query
# partner = partner
# project = myproject
[mysandbox]
client_id = <oauth_client_id>
client_secret = <oauth_client_secret>
```
# Usage
#### Cheatsheet
```
# List fiels for resource
$ zacc describe Account
Account
AccountNumber - Account Number
AdditionalEmailAddresses - Additional Email Addresses
AllowInvoiceEdit - Allow Invoice Editing
AutoPay - Auto Pay
Balance - Account Balance
...
Related Objects
BillToContact<Contact> - Bill To
DefaultPaymentMethod<PaymentMethod> - Default Payment Method
ParentAccount<Account> - Parent Account
SoldToContact<Contact> - Sold To
# Request a bearer token, then exit
$ zacc bearer
Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaa
# Execute an AQuA job
$ zacc query "select Account.Name from Account where Account.CreatedDate > '2019-01-10'"
Account.Name
John Doe
Jane Doe
# Save results to CSV file instead of printing it
$ zacc query ~/query_names.zoql -o account_names.csv
# Execute an AQuA job from a ZOQL query file
$ zacc query ~/query_names.zoql
Account.Name
John Doe
Jane Doe
# Use different configurations than default
$ zacc -c ~/.myotherzaccconfig.ini -e notdefualtenv query ~/query_names.zoql
```
## Commands
#### zacc
```
Usage: zacc [OPTIONS] COMMAND [ARGS]...
Sets up an API client, passes to commands in context
Options:
-c, --config-filename PATH Config file containing Zuora ouath credentials
[default: /Users/janosmolnar/.zacc.ini]
-e, --environment TEXT Zuora environment to execute on
--project TEXT Project name
--partner TEXT Partner name
-m, --max-retries FLOAT Maximum retries for query
--help Show this message and exit.
Commands:
bearer Prints bearer than exits
describe List available fields of Zuora resource
query Run ZOQL Query
```
#### zacc query
```
Usage: zacc query [OPTIONS]
Run ZOQL Query
Options:
-o, --output PATH Where to write the output to, default is STDOUT
--help Show this message and exit.
```
#### zacc describe
```
Usage: zacc describe [OPTIONS] RESOURCE
List available fields of Zuora resource
Options:
--help Show this message and exit.
```
#### zacc bearer
```
Usage: zacc bearer [OPTIONS]
Prints bearer than exits
Options:
--help Show this message and exit.
```
# Useful stuff
Has a lot of graphs on Resource relationships:
https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/D_Zuora_Business_Objects_Relationship
https://community.zuora.com/t5/Engineering-Blog/AQUA-An-Introduction-to-Join-Processing/ba-p/13262
| zuora-aqua-client-cli | /zuora-aqua-client-cli-1.4.0.tar.gz/zuora-aqua-client-cli-1.4.0/README.md | README.md |
import time
from datetime import datetime
import requests
class ZuoraClient(object):
def __init__(
self,
client_id,
client_secret,
is_prod=False,
max_retries=float("inf"),
project="",
project_prefix="",
partner="",
):
self.client_id = client_id
self.client_secret = client_secret
self.is_prod = is_prod
self.max_retries = max_retries
self.project = project
self.project_prefix = project_prefix
self.partner = partner
self.base_url = "https://zuora.com" if self.is_prod else "https://apisandbox.zuora.com"
self.base_api_url = "https://rest.zuora.com" if self.is_prod else "https://rest.apisandbox.zuora.com"
self.set_headers()
def set_headers(self):
self.bearer_token = self.get_bearer_token()
self._headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.bearer_token}",
}
def get_bearer_token(self):
payload = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"grant_type": "client_credentials",
}
try:
r = requests.post(self.base_api_url + "/oauth/token", data=payload)
r.raise_for_status()
bearer_token = r.json()["access_token"]
except requests.exceptions.ConnectionError as e:
# raise more generic error so CLI does not have to know about implementations of API
raise TimeoutError(e)
except requests.exceptions.HTTPError as e:
raise ValueError(e)
return bearer_token
def query(self, zoql):
self._job_url = self.start_job(zoql)
self._file_ids = self.poll_job()
self.content = []
for file_id in self._file_ids:
self.content.append(self.get_file_content(file_id))
return self.content
def start_job(self, queries):
query_payload = {
"format": "csv",
"version": "1.1",
"encrypted": "none",
"useQueryLabels": "true",
"dateTimeUtc": "true",
"queries": [{"query": query, "type": "zoqlexport"} for query in queries],
}
if self.partner:
query_payload["partner"] = self.partner
if self.project_prefix:
query_payload["project"] = "{prefix}_{timestamp}".format(
prefix=self.project_prefix, timestamp=datetime.now()
)
if self.project:
query_payload["project"] = self.project
query_url = self.base_api_url + "/v1/batch-query/"
r = requests.post(query_url, json=query_payload, headers=self._headers)
r.raise_for_status()
try:
job_id = r.json()["id"]
_job_url = query_url + "/jobs/{}".format(job_id)
except KeyError:
raise ValueError(r.text)
return _job_url
def poll_job(self):
""" Continuously polls the job until done
Unless max_retries is provided it polls until end of universe
otherwise tries it `max_retries` times
# TODO: Change timeout to actual timeout rather than # of times
"""
status = "pending"
trial_count = 0
while status != "completed":
r = requests.get(self._job_url, headers=self._headers)
r.raise_for_status()
status = r.json()["status"]
if status == "completed":
break
time.sleep(1)
trial_count += 1
if trial_count >= self.max_retries:
raise TimeoutError()
return map(lambda batch: batch["fileId"], r.json()["batches"])
def get_file_content(self, file_id):
file_url = self.base_url + "/apps/api/file/{}".format(file_id)
r = requests.get(file_url, headers=self._headers)
return r.content.decode("utf-8")
def get_resource(self, resource):
r = requests.get(self.base_api_url + f"/v1/describe/{resource}", headers=self._headers)
r.raise_for_status()
return r.text | zuora-aqua-client-cli | /zuora-aqua-client-cli-1.4.0.tar.gz/zuora-aqua-client-cli-1.4.0/zuora_aqua_client_cli/api.py | api.py |
import os
import click
import configparser
import xml.etree.ElementTree as ET
from pathlib import Path
from .consts import ZUORA_RESOURCES
from .api import ZuoraClient
HOME = os.environ["HOME"]
DEFAULT_CONFIG_PATH = Path(HOME) / Path(".zacc.ini")
default_environment = None
production = False
class Errors:
config_not_found = "ConfigNotFoundError"
retries_exceeded = "RetriesExceededError"
invalid_zoql = "InvalidZOQLError"
resource_not_found = "ResourceNotFound"
file_not_exists = "FileNotExists"
environment_not_found = "EnvironmentNotFoundError"
connection_error = "ConnectionError"
def read_conf(filename):
config = configparser.ConfigParser()
config.read(filename)
return config
def get_client_data(config, environment):
global production
if not config.sections():
error = f"""
Configuration not found or empty!
Please create config in $HOME/.zacc.ini or explicitly pass using the '-c /path/to/config' option!
Sample configuration:
# Cli settings
[zacc]
# In case the environment is not passed use 'env1' section
default_environment = env1
[env1]
client_id = client1
client_secret = secret1
# Optional partner and project fields can be configured per environment, see more on what these do:
# https://knowledgecenter.zuora.com/Central_Platform/API/AB_Aggregate_Query_API/B_Submit_Query
# partner = partner
# Adding project prefix will add only a prefix to the project, so it's easy to identify
# but will add a timestamp to it so it's not hanging when multiple jobs are executed at the same time
# project_prefix = myproject
# If both 'project' and 'project_prefix' is defined, project takes precedence
# project = myproject
[env2]
# Uses the production Zuora endpoints instead of the apisandbox
production = true
client_id = client2
client_secret = secret2
"""
click.echo(click.style(error, fg="red"))
raise click.ClickException(Errors.config_not_found)
if environment is None:
try:
environment = config.get("zacc", "default_environment")
except (configparser.NoOptionError, configparser.NoSectionError):
error = f"""
No environment passed, no default environment set!
Please set a default environment by adding
[zacc]
default_environment = <environment_section>
to your configuration, or pass environment explicitly using the '-e' flag.
"""
click.echo(click.style(error, fg="red"))
raise click.ClickException(Errors.environment_not_found)
# Throw away config-only section, as it is not a real environment
try:
del config["zacc"]
except KeyError:
pass
try:
is_production = config[environment].get("production") == "true"
client_id = config[environment]["client_id"]
client_secret = config[environment]["client_secret"]
partner = config[environment].get("partner")
project = config[environment].get("project")
project_prefix = config[environment].get("project_prefix")
except KeyError:
environments = ", ".join(config.sections())
error = f"""
Environment '{environment}' not found!
Environments configured: {environments}
"""
click.echo(click.style(error, fg="red"))
raise click.ClickException(Errors.environment_not_found)
return client_id, client_secret, is_production, partner, project, project_prefix
@click.group()
@click.option(
"-c",
"--config-filename",
default=DEFAULT_CONFIG_PATH,
help="Config file containing Zuora ouath credentials",
type=click.Path(exists=False),
show_default=True,
)
@click.option("-e", "--environment", help="Zuora environment to execute on")
@click.option("--project", help="Project name")
@click.option("--project-prefix", help="Project prefix")
@click.option("--partner", help="Partner name")
@click.option(
"-m", "--max-retries", default=float("inf"), help="Maximum retries for query", type=click.FLOAT,
)
@click.pass_context
def cli(ctx, config_filename, environment, project, project_prefix, partner, max_retries):
""" Sets up an API client, passes to commands in context """
config = read_conf(config_filename)
(
client_id,
client_secret,
is_production,
default_partner,
default_project,
default_project_prefix,
) = get_client_data(config, environment)
try:
zuora_client = ZuoraClient(
client_id=client_id,
client_secret=client_secret,
is_prod=is_production,
max_retries=max_retries,
partner=default_partner if default_partner else partner,
project=default_project if default_project else project,
project_prefix=default_project_prefix if default_project_prefix else project_prefix,
)
except TimeoutError:
error = """
Connection error, please check you network connection!
Tips:
- Are you connected to network?
- Can you resolve 'rest.zuora.com'?
- Can you reach Zuora servers?
"""
click.echo(click.style(error, fg="red"))
raise click.ClickException(Errors.connection_error)
except ValueError as e:
error = f"""
Authentication error, please check you credentials!
Message from Zuora:
{e.__context__.response.text}
"""
click.echo(click.style(error, fg="red"))
raise click.ClickException(Errors.connection_error)
ctx.obj = zuora_client
def read_zoql_file(filename):
with open(filename, "r") as f:
return f.read().split("\n\n")
def write_to_output_file(outfile, content):
with open(outfile, "w+") as out:
out.write("\n".join(content))
@cli.command()
@click.pass_obj
@click.argument("resource")
def describe(zuora_client, resource):
""" List available fields of Zuora resource """
if resource not in ZUORA_RESOURCES:
click.echo(click.style(f"Resource cannot be found '{resource}', available resources:", fg="red"))
for resource in ZUORA_RESOURCES:
click.echo(click.style(resource))
click.echo()
raise click.ClickException(Errors.resource_not_found)
response = zuora_client.get_resource(resource)
root = ET.fromstring(response)
resource_name = root[1].text
fields = root[2]
related_objects = root[3]
click.echo(click.style(resource_name, fg="green"))
for child in fields:
name = ""
label = ""
for field in child:
if field.tag == "name":
name = field.text
elif field.tag == "label":
label = field.text
click.echo(click.style(f" {name} - {label}", fg="green"))
click.echo(click.style("Related Objects", fg="green"))
for child in related_objects:
name = ""
label = ""
object_type = child.items()[0][1].split("/")[-1]
for field in child:
if field.tag == "name":
name = field.text
elif field.tag == "label":
label = field.text
click.echo(click.style(f" {name}<{object_type}> - {label}", fg="green"))
@cli.command()
@click.pass_obj
def bearer(zuora_client):
""" Prints bearer than exits """
click.echo(click.style(zuora_client._headers["Authorization"], fg="green"))
@cli.command()
@click.pass_obj
@click.argument("zoql")
@click.option(
"-o",
"--output",
default=None,
help="Where to write the output to, default is STDOUT",
type=click.Path(),
show_default=True,
)
def query(zuora_client, zoql, output):
""" Run ZOQL Query
:arg
- zoql: Filename or inline query string
as inline query:
`zacc query "select ... from ..."` - query is read as inline query, argument is passed to query as is
as path:
`zacc query ~/test.zql`
`zacc query test.zql`
`zacc query /tmp/test.zql`
File can contain on or more queries separated with 1 empty line between 2 queries
:param
-- output: output filename to write the file to
-- max-retries: after how many retries to stop polling (if the query takes too long)
"""
# In order to check if file exists, first we check if it looks like a path,
# by checking if the dirname is valid, then check if the file exists.
# If we would only check if the file exist, we'd pass the filename as an inline ZOQL query
# Length is checked because it can cause OS Error if its too long, see: https://github.com/molnarjani/zuora-aqua-client-cli/issues/38
if len(zoql) < 255 and (os.path.exists(os.path.dirname(zoql)) or Path(Path.cwd() / zoql).exists()):
if os.path.isfile(zoql):
zoql = read_zoql_file(zoql)
else:
click.echo(click.style(f"File does not exist '{zoql}'", fg="red"))
raise click.ClickException(Errors.file_not_exists)
try:
# Transform to list of one element if it's an inline query
zoql = zoql if isinstance(zoql, list) else [zoql]
content = zuora_client.query(zoql)
except ValueError as e:
click.echo(click.style(str(e), fg="red"))
raise click.ClickException(Errors.invalid_zoql)
except TimeoutError:
error = """
Max trials exceeded!
You can increase it by '-m [number of retries]' option.
If '-m' is not provided it will poll until job is finished.
"""
click.echo(click.style(error, fg="red"))
raise click.ClickException(Errors.retries_exceeded)
# TODO: Make reuqest session instead of 3 separate requests
# TODO: Pass headers to request session
if output is not None:
write_to_output_file(output, content)
else:
click.echo(click.style("\n".join(content), fg="green"))
if __name__ == "__main__":
cli() | zuora-aqua-client-cli | /zuora-aqua-client-cli-1.4.0.tar.gz/zuora-aqua-client-cli-1.4.0/zuora_aqua_client_cli/cli.py | cli.py |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
options, args = parser.parse_args()
######################################################################
# load/install setuptools
to_reload = False
try:
import pkg_resources
import setuptools
except ImportError:
ez = {}
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
# XXX use a more permanent ez_setup.py URL when available.
exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py'
).read(), ez)
setup_args = dict(to_dir=tmpeggs, download_delay=0)
ez['use_setuptools'](**setup_args)
if to_reload:
reload(pkg_resources)
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0:
raise Exception(
"Failed to execute command:\n%s",
repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | zuora-client | /zuora-client-1.0.tar.gz/zuora-client-1.0/bootstrap.py | bootstrap.py |
import os
import logging
from datetime import datetime
from datetime import timedelta
from ConfigParser import SafeConfigParser
from suds import WebFault
from suds.client import Client
from suds.sax.text import Text
from suds.sax.element import Element
from zuora.transport import HttpTransportWithKeepAlive
DEFAULT_SESSION_DURATION = 15 * 60
logger = logging.getLogger(__name__)
logger_suds = logging.getLogger('suds')
logger_suds.propagate = False
class ZuoraException(Exception):
"""
Base Zuora Exception.
"""
pass
class BaseZuora(object):
"""
SOAP Client based on Suds
"""
def __init__(self, wsdl, username, password,
session_duration=DEFAULT_SESSION_DURATION):
self.wsdl = wsdl
self.username = username
self.password = password
self.session = None
self.session_duration = session_duration
self.session_expiration = datetime.now()
self.wsdl_path = 'file://%s' % os.path.abspath(self.wsdl)
self.client = Client(
self.wsdl_path,
transport=HttpTransportWithKeepAlive())
def instanciate(self, instance_type_string):
"""
Create object for client.factory.
"""
return self.client.factory.create(instance_type_string)
def set_session(self, session_id):
"""
Record the session info.
"""
self.session = session_id
self.session_expiration = datetime.now() + timedelta(
seconds=self.session_duration)
session_namespace = ('ns1', 'http://api.zuora.com/')
session = Element('session', ns=session_namespace).setText(session_id)
header = Element('SessionHeader', ns=session_namespace)
header.append(session)
self.client.set_options(soapheaders=[header])
def reset(self):
"""
Reset the connection to the API.
"""
self.session = None
self.client.options.transport = HttpTransportWithKeepAlive()
def call(self, method, *args, **kwargs):
"""
Call a SOAP method.
"""
if self.session is None or self.session_expiration >= datetime.now():
self.login()
try:
response = method(*args, **kwargs)
logger.info('Sent: %s', self.client.last_sent())
logger.info('Received: %s', self.client.last_received())
if isinstance(response, Text): # Occasionally happens
logger.warning('Invalid response %s, retrying...', response)
self.reset()
return self.call(method, *args, **kwargs)
except WebFault as error:
if error.fault.faultcode == 'fns:INVALID_SESSION':
logger.warning('Invalid session, relogging...')
self.reset()
return self.call(method, *args, **kwargs)
else:
logger.info('Sent: %s', self.client.last_sent())
logger.info('Received: %s', self.client.last_received())
logger.error('WebFault: %s', error.__dict__)
raise ZuoraException('WebFault: %s' % error.__dict__)
except Exception as error:
logger.info('Sent: %s', self.client.last_sent())
logger.info('Received: %s', self.client.last_received())
logger.error('Unexpected error: %s', error)
raise ZuoraException('Unexpected error: %s' % error)
logger.debug('Successful response %s', response)
return response
def amend(self, amend_requests):
"""
Amend susbcriptions.
"""
response = self.call(
self.client.service.amend,
amend_requests)
return response
def create(self, z_objects):
"""
Create z_objects.
"""
response = self.call(
self.client.service.create,
z_objects)
return response
def delete(self, object_string, ids=[]):
"""
Delete z_objects by ID.
"""
response = self.call(
self.client.service.delete,
object_string, ids)
return response
def execute(self, object_string, synchronous=False, ids=[]):
"""
Execute a process by IDs.
"""
response = self.call(
self.client.service.execute,
object_string, synchronous, ids)
return response
def generate(self, z_objects):
"""
Generate z_objects.
"""
response = self.call(
self.client.service.execute,
z_objects)
return response
def get_user_info(self):
"""
Return current user's info.
"""
response = self.call(
self.client.service.get_user_info)
return response
def login(self):
"""
Login on the API to get a session.
"""
response = self.client.service.login(self.username, self.password)
self.set_session(response.Session)
return response
def query(self, query_string):
"""
Execute a query.
"""
response = self.call(
self.client.service.query,
query_string)
return response
def query_more(self, query_locator):
"""
Execute the suite of a query.
"""
response = self.call(
self.client.service.queryMore,
query_locator)
return response
def subscribe(self, subscribe_requests):
"""
Subscribe accounts.
"""
response = self.call(
self.client.service.subscribe,
subscribe_requests)
return response
def update(self, z_objects):
"""
Update z_objects.
"""
response = self.call(
self.client.service.update,
z_objects)
return response
def __str__(self):
"""
Display the client __str__ method.
"""
return self.client.__str__()
class Zuora(BaseZuora):
"""
Final SOAP Zuora Client
"""
def __init__(self):
default_config = {'session_duration': str(DEFAULT_SESSION_DURATION)}
config = SafeConfigParser(default_config)
config.add_section('client')
config.read([os.path.expanduser('~/.zuora.cfg'),
os.path.join(os.getcwd(), 'etc/zuora.cfg')])
wsdl = config.get('client', 'wsdl')
username = config.get('client', 'username')
password = config.get('client', 'password')
session_duration = config.getint('client', 'session_duration')
super(Zuora, self).__init__(
wsdl, username, password, session_duration) | zuora-client | /zuora-client-1.0.tar.gz/zuora-client-1.0/zuora/client.py | client.py |
# swagger-client
# Introduction Welcome to the reference for the Zuora Billing REST API!
To learn about the common use cases of Zuora Billing REST APIs, check out the [API Guides](https://www.zuora.com/developer/api-guides/). In addition to Zuora API Reference; Billing, we also provide API references for other Zuora products: * [API Reference: Collect](https://www.zuora.com/developer/collect-api/) * [API Reference: Revenue](https://www.zuora.com/developer/revpro-api/) The Zuora REST API provides a broad set of operations and resources that: * Enable Web Storefront integration from your website. * Support self-service subscriber sign-ups and account management. * Process revenue schedules through custom revenue rule models. * Enable manipulation of most objects in the Zuora Billing Object Model. Want to share your opinion on how our API works for you? <a href=\"https://community.zuora.com/t5/Developers/API-Feedback-Form/gpm-p/21399\" target=\"_blank\">Tell us how you feel </a>about using our API and what we can do to make it better.
## Access to the API
If you have a Zuora tenant, you can access the Zuora REST API via one of the following endpoints:
| Tenant | Base URL for REST Endpoints |
|-------------------------|-------------------------|
|US Production | https://rest.zuora.com |
|US API Sandbox | https://rest.apisandbox.zuora.com|
|US Performance Test | https://rest.pt1.zuora.com |
This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
## Requirements.
Python 2.7 and 3.4+
## Installation & Usage
### pip install
If the python package is hosted on Github, you can install directly from Github
```sh
pip install git+https://github.com//.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://github.com//.git`)
Then import the package:
```python
import swagger_client
```
### Setuptools
Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)
Then import the package:
```python
import swagger_client
```
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# create an instance of the API class
api_instance = swagger_client.APIHealthApi(swagger_client.ApiClient(configuration))
authorization = 'authorization_example' # str | The value is in the `Bearer {token}` format where {token} is a valid OAuth token generated by calling [Create an OAuth token](https://www.zuora.com/developer/api-references/api/operation/createToken).
start_time = '2013-10-20T19:20:30+01:00' # datetime | Start time of the volume summary. Format: `yyyy-MM-dd'T'HH:mmZ` Example: `2022-09-22T09:07+0800`.
end_time = '2013-10-20T19:20:30+01:00' # datetime | End time of the volume summary. Format: `yyyy-MM-dd'T'HH:mmZ` Example: `2022-09-29T09:07+0800`.
accept_encoding = 'accept_encoding_example' # str | Include the `Accept-Encoding: gzip` header to compress responses as a gzipped file. It can significantly reduce the bandwidth required for a response. If specified, Zuora automatically compresses responses that contain over 1000 bytes of data, and the response contains a `Content-Encoding` header with the compression algorithm so that your client can decompress it. (optional)
content_encoding = 'content_encoding_example' # str | Include the `Content-Encoding: gzip` header to compress a request. With this header specified, you should upload a gzipped file for the request payload instead of sending the JSON payload. (optional)
zuora_entity_ids = 'zuora_entity_ids_example' # str | An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you do not need to set this header. (optional)
zuora_track_id = 'zuora_track_id_example' # str | A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`\"`), and quote (`'`). (optional)
path = 'path_example' # str | Filters the volume summary by API path name. You can refer to the api listed in the [API System Health Dashboard](https://knowledgecenter.zuora.com/Zuora_Central_Platform/Zuora_System_Health/B_APIs_dashboard) for the path name. Example: `/v1/accounts/{account-key}`. (optional)
http_method = 'http_method_example' # str | Filters the volume summary by http method. Example: `POST`. (optional)
try:
# List API volume summary records
api_response = api_instance.g_et_system_health_api_volume_summary(authorization, start_time, end_time, accept_encoding=accept_encoding, content_encoding=content_encoding, zuora_entity_ids=zuora_entity_ids, zuora_track_id=zuora_track_id, path=path, http_method=http_method)
pprint(api_response)
except ApiException as e:
print("Exception when calling APIHealthApi->g_et_system_health_api_volume_summary: %s\n" % e)
```
## Documentation for API Endpoints
All URIs are relative to *https://rest.zuora.com*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*APIHealthApi* | [**g_et_system_health_api_volume_summary**](docs/APIHealthApi.md#g_et_system_health_api_volume_summary) | **GET** /system-health/api-requests/volume-summary | List API volume summary records
*AccountingCodesApi* | [**d_elete_accounting_code**](docs/AccountingCodesApi.md#d_elete_accounting_code) | **DELETE** /v1/accounting-codes/{ac-id} | Delete an accounting code
*AccountingCodesApi* | [**g_et_accounting_code**](docs/AccountingCodesApi.md#g_et_accounting_code) | **GET** /v1/accounting-codes/{ac-id} | Retrieve an accounting code
*AccountingCodesApi* | [**g_et_all_accounting_codes**](docs/AccountingCodesApi.md#g_et_all_accounting_codes) | **GET** /v1/accounting-codes | List all accounting codes
*AccountingCodesApi* | [**p_ost_accounting_code**](docs/AccountingCodesApi.md#p_ost_accounting_code) | **POST** /v1/accounting-codes | Create an accounting code
*AccountingCodesApi* | [**p_ut_accounting_code**](docs/AccountingCodesApi.md#p_ut_accounting_code) | **PUT** /v1/accounting-codes/{ac-id} | Update an accounting code
*AccountingCodesApi* | [**p_ut_activate_accounting_code**](docs/AccountingCodesApi.md#p_ut_activate_accounting_code) | **PUT** /v1/accounting-codes/{ac-id}/activate | Activate an accounting code
*AccountingCodesApi* | [**p_ut_deactivate_accounting_code**](docs/AccountingCodesApi.md#p_ut_deactivate_accounting_code) | **PUT** /v1/accounting-codes/{ac-id}/deactivate | Deactivate an accounting code
*AccountingPeriodsApi* | [**d_elete_accounting_period**](docs/AccountingPeriodsApi.md#d_elete_accounting_period) | **DELETE** /v1/accounting-periods/{ap-id} | Delete an accounting period
*AccountingPeriodsApi* | [**g_et_accounting_period**](docs/AccountingPeriodsApi.md#g_et_accounting_period) | **GET** /v1/accounting-periods/{ap-id} | Retrieve an accounting period
*AccountingPeriodsApi* | [**g_et_all_accounting_periods**](docs/AccountingPeriodsApi.md#g_et_all_accounting_periods) | **GET** /v1/accounting-periods | List all accounting periods
*AccountingPeriodsApi* | [**p_ost_accounting_period**](docs/AccountingPeriodsApi.md#p_ost_accounting_period) | **POST** /v1/accounting-periods | Create an accounting period
*AccountingPeriodsApi* | [**p_ut_close_accounting_period**](docs/AccountingPeriodsApi.md#p_ut_close_accounting_period) | **PUT** /v1/accounting-periods/{ap-id}/close | Close an accounting period
*AccountingPeriodsApi* | [**p_ut_pending_close_accounting_period**](docs/AccountingPeriodsApi.md#p_ut_pending_close_accounting_period) | **PUT** /v1/accounting-periods/{ap-id}/pending-close | Set an accounting period to pending close
*AccountingPeriodsApi* | [**p_ut_reopen_accounting_period**](docs/AccountingPeriodsApi.md#p_ut_reopen_accounting_period) | **PUT** /v1/accounting-periods/{ap-id}/reopen | Reopen an accounting period
*AccountingPeriodsApi* | [**p_ut_run_trial_balance**](docs/AccountingPeriodsApi.md#p_ut_run_trial_balance) | **PUT** /v1/accounting-periods/{ap-id}/run-trial-balance | Run trial balance
*AccountingPeriodsApi* | [**p_ut_update_accounting_period**](docs/AccountingPeriodsApi.md#p_ut_update_accounting_period) | **PUT** /v1/accounting-periods/{ap-id} | Update an accounting period
*AccountsApi* | [**d_elete_account**](docs/AccountsApi.md#d_elete_account) | **DELETE** /v1/accounts/{account-key} | Delete an account
*AccountsApi* | [**g_et_account**](docs/AccountsApi.md#g_et_account) | **GET** /v1/accounts/{account-key} | Retrieve an account
*AccountsApi* | [**g_et_account_summary**](docs/AccountsApi.md#g_et_account_summary) | **GET** /v1/accounts/{account-key}/summary | Retrieve an account summary
*AccountsApi* | [**g_et_acount_default_payment_method**](docs/AccountsApi.md#g_et_acount_default_payment_method) | **GET** /v1/accounts/{account-key}/payment-methods/default | Retrieve the default payment method of an account
*AccountsApi* | [**g_et_acount_payment_methods**](docs/AccountsApi.md#g_et_acount_payment_methods) | **GET** /v1/accounts/{account-key}/payment-methods | List payment methods of an account
*AccountsApi* | [**p_ost_account**](docs/AccountsApi.md#p_ost_account) | **POST** /v1/accounts | Create an account
*AccountsApi* | [**p_ut_account**](docs/AccountsApi.md#p_ut_account) | **PUT** /v1/accounts/{account-key} | Update an account
*ActionsApi* | [**action_pos_tcreate**](docs/ActionsApi.md#action_pos_tcreate) | **POST** /v1/action/create | Create
*ActionsApi* | [**action_pos_tdelete**](docs/ActionsApi.md#action_pos_tdelete) | **POST** /v1/action/delete | Delete
*ActionsApi* | [**action_pos_tquery**](docs/ActionsApi.md#action_pos_tquery) | **POST** /v1/action/query | Query
*ActionsApi* | [**action_pos_tquery_more**](docs/ActionsApi.md#action_pos_tquery_more) | **POST** /v1/action/queryMore | QueryMore
*ActionsApi* | [**action_pos_tupdate**](docs/ActionsApi.md#action_pos_tupdate) | **POST** /v1/action/update | Update
*AdjustmentsApi* | [**create_adjustment**](docs/AdjustmentsApi.md#create_adjustment) | **POST** /v1/adjustments | Create an adjustment
*AdjustmentsApi* | [**g_et_adjustment**](docs/AdjustmentsApi.md#g_et_adjustment) | **GET** /v1/adjustments/{adjustment-key} | Retrieve an adjustment
*AdjustmentsApi* | [**g_et_subscription_adjustments**](docs/AdjustmentsApi.md#g_et_subscription_adjustments) | **GET** /v1/adjustments | List all adjustments of the latest version subscription
*AdjustmentsApi* | [**p_ut_cancel_adjustment**](docs/AdjustmentsApi.md#p_ut_cancel_adjustment) | **PUT** /v1/adjustments/{adjustmentId}/cancel | Cancel an adjustment
*AdjustmentsApi* | [**preview_adjustment**](docs/AdjustmentsApi.md#preview_adjustment) | **POST** /v1/adjustments/preview | Preview an adjustment
*AggregateQueriesApi* | [**d_elete_batch_query_job**](docs/AggregateQueriesApi.md#d_elete_batch_query_job) | **DELETE** /v1/batch-query/jobs/{jobid} | Cancel a running aggregate query job
*AggregateQueriesApi* | [**g_et_batch_query_job**](docs/AggregateQueriesApi.md#g_et_batch_query_job) | **GET** /v1/batch-query/jobs/{jobid} | Retrieve an aggregate query job
*AggregateQueriesApi* | [**g_et_last_batch_query_job**](docs/AggregateQueriesApi.md#g_et_last_batch_query_job) | **GET** /v1/batch-query/jobs/partner/{partner}/project/{project} | Retrieve the last completed aggregate query job
*AggregateQueriesApi* | [**p_ost_batch_query_job**](docs/AggregateQueriesApi.md#p_ost_batch_query_job) | **POST** /v1/batch-query/ | Submit an aggregate query job
*AttachmentsApi* | [**d_elete_attachments**](docs/AttachmentsApi.md#d_elete_attachments) | **DELETE** /v1/attachments/{attachment-id} | Delete an attachment
*AttachmentsApi* | [**g_et_attachments**](docs/AttachmentsApi.md#g_et_attachments) | **GET** /v1/attachments/{attachment-id} | Retrieve an attachment
*AttachmentsApi* | [**g_et_attachments_list**](docs/AttachmentsApi.md#g_et_attachments_list) | **GET** /v1/attachments/{object-type}/{object-key} | List attachments by object type and key
*AttachmentsApi* | [**p_ost_attachments**](docs/AttachmentsApi.md#p_ost_attachments) | **POST** /v1/attachments | Create an attachment
*AttachmentsApi* | [**p_ut_attachments**](docs/AttachmentsApi.md#p_ut_attachments) | **PUT** /v1/attachments/{attachment-id} | Update an attachment
*BillRunApi* | [**d_elete_delete_bill_run**](docs/BillRunApi.md#d_elete_delete_bill_run) | **DELETE** /v1/bill-runs/{billRunId} | Delete a bill run
*BillRunApi* | [**g_et_bill_run**](docs/BillRunApi.md#g_et_bill_run) | **GET** /v1/bill-runs/{billRunId} | Retrieve a bill run
*BillRunApi* | [**p_ost_create_bill_run**](docs/BillRunApi.md#p_ost_create_bill_run) | **POST** /v1/bill-runs | Create a bill run
*BillRunApi* | [**p_ost_email_billing_documentsfrom_bill_run**](docs/BillRunApi.md#p_ost_email_billing_documentsfrom_bill_run) | **POST** /v1/bill-runs/{billRunKey}/emails | Email billing documents generated from a bill run
*BillRunApi* | [**p_ut_cancel_bill_run**](docs/BillRunApi.md#p_ut_cancel_bill_run) | **PUT** /v1/bill-runs/{billRunId}/cancel | Cancel a bill run
*BillRunApi* | [**p_ut_post_bill_run**](docs/BillRunApi.md#p_ut_post_bill_run) | **PUT** /v1/bill-runs/{billRunId}/post | Post a bill run
*BillRunHealthApi* | [**g_et_system_health_billing_doc_volume_summary**](docs/BillRunHealthApi.md#g_et_system_health_billing_doc_volume_summary) | **GET** /system-health/billing-documents/volume-summary | List billing document volume summary records
*BillingDocumentsApi* | [**g_et_billing_document_files_deletion_job**](docs/BillingDocumentsApi.md#g_et_billing_document_files_deletion_job) | **GET** /v1/accounts/billing-documents/files/deletion-jobs/{jobId} | Retrieve a job of hard deleting billing document files
*BillingDocumentsApi* | [**g_et_billing_documents**](docs/BillingDocumentsApi.md#g_et_billing_documents) | **GET** /v1/billing-documents | List billing documents for an account
*BillingDocumentsApi* | [**p_ost_billing_document_files_deletion_job**](docs/BillingDocumentsApi.md#p_ost_billing_document_files_deletion_job) | **POST** /v1/accounts/billing-documents/files/deletion-jobs | Create a job to hard delete billing document files
*BillingDocumentsApi* | [**p_ost_generate_billing_documents**](docs/BillingDocumentsApi.md#p_ost_generate_billing_documents) | **POST** /v1/accounts/{key}/billing-documents/generate | Generate billing documents by account ID
*BillingPreviewRunApi* | [**g_et_billing_preview_run**](docs/BillingPreviewRunApi.md#g_et_billing_preview_run) | **GET** /v1/billing-preview-runs/{billingPreviewRunId} | Retrieve a billing preview run
*BillingPreviewRunApi* | [**p_ost_billing_preview_run**](docs/BillingPreviewRunApi.md#p_ost_billing_preview_run) | **POST** /v1/billing-preview-runs | Create a billing preview run
*CatalogApi* | [**g_et_catalog**](docs/CatalogApi.md#g_et_catalog) | **GET** /v1/catalog/products | List all products
*CatalogApi* | [**g_et_product**](docs/CatalogApi.md#g_et_product) | **GET** /v1/catalog/product/{product-key} | Retrieve a product
*CatalogGroupsApi* | [**d_elete_catalog_group**](docs/CatalogGroupsApi.md#d_elete_catalog_group) | **DELETE** /v1/catalog-groups/{catalog-group-key} | Delete a catalog group
*CatalogGroupsApi* | [**g_et_list_all_catalog_groups**](docs/CatalogGroupsApi.md#g_et_list_all_catalog_groups) | **GET** /v1/catalog-groups | List all catalog groups
*CatalogGroupsApi* | [**g_et_retrieve_catalog_group**](docs/CatalogGroupsApi.md#g_et_retrieve_catalog_group) | **GET** /v1/catalog-groups/{catalog-group-key} | Retrieve a catalog group
*CatalogGroupsApi* | [**p_ost_create_catalog_group**](docs/CatalogGroupsApi.md#p_ost_create_catalog_group) | **POST** /v1/catalog-groups | Create a catalog group
*CatalogGroupsApi* | [**p_ut_update_catalog_group**](docs/CatalogGroupsApi.md#p_ut_update_catalog_group) | **PUT** /v1/catalog-groups/{catalog-group-key} | Update a catalog group
*ConfigurationTemplatesApi* | [**d_elete_deployment_template**](docs/ConfigurationTemplatesApi.md#d_elete_deployment_template) | **DELETE** /deployment-manager/deployment_templates/{id} | Delete a template
*ConfigurationTemplatesApi* | [**g_et_deployment_template_detail**](docs/ConfigurationTemplatesApi.md#g_et_deployment_template_detail) | **GET** /deployment-manager/deployment_templates/{id} | List all details of a template
*ConfigurationTemplatesApi* | [**g_et_download_deployment_template**](docs/ConfigurationTemplatesApi.md#g_et_download_deployment_template) | **GET** /deployment-manager/deployment_artifacts | Download a template
*ConfigurationTemplatesApi* | [**g_et_source_component_details**](docs/ConfigurationTemplatesApi.md#g_et_source_component_details) | **GET** /deployment-manager/deployment_artifacts/retrieve-settings | List all details of source components
*ConfigurationTemplatesApi* | [**g_et_templates**](docs/ConfigurationTemplatesApi.md#g_et_templates) | **GET** /deployment-manager/deployment_templates | List all templates
*ConfigurationTemplatesApi* | [**p_ost_compare_template**](docs/ConfigurationTemplatesApi.md#p_ost_compare_template) | **POST** /deployment-manager/deployment_artifacts/compare | Compare settings between a source tenant and a target tenant
*ConfigurationTemplatesApi* | [**p_ost_deployment_template**](docs/ConfigurationTemplatesApi.md#p_ost_deployment_template) | **POST** /deployment-manager/deployment_templates | Create a deployment template
*ConfigurationTemplatesApi* | [**p_ost_migrate_tenant_settings**](docs/ConfigurationTemplatesApi.md#p_ost_migrate_tenant_settings) | **POST** /deployment-manager/deployment_artifacts/deploy | Migrate settings from source tenant to target tenant
*ContactSnapshotsApi* | [**g_et_contact_snapshot**](docs/ContactSnapshotsApi.md#g_et_contact_snapshot) | **GET** /v1/contact-snapshots/{contact-snapshot-id} | Retrieve a contact snapshot
*ContactsApi* | [**d_elete_contact**](docs/ContactsApi.md#d_elete_contact) | **DELETE** /v1/contacts/{contactId} | Delete a contact
*ContactsApi* | [**g_et_contact**](docs/ContactsApi.md#g_et_contact) | **GET** /v1/contacts/{contactId} | Retrieve a contact
*ContactsApi* | [**p_ost_create_contact**](docs/ContactsApi.md#p_ost_create_contact) | **POST** /v1/contacts | Create a contact
*ContactsApi* | [**p_ut_contact**](docs/ContactsApi.md#p_ut_contact) | **PUT** /v1/contacts/{contactId} | Update a contact
*ContactsApi* | [**p_ut_scrub_contact**](docs/ContactsApi.md#p_ut_scrub_contact) | **PUT** /v1/contacts/{contactId}/scrub | Scrub a contact
*CreditMemosApi* | [**d_elete_credit_memo**](docs/CreditMemosApi.md#d_elete_credit_memo) | **DELETE** /v1/creditmemos/{creditMemoKey} | Delete a credit memo
*CreditMemosApi* | [**g_et_credit_memo**](docs/CreditMemosApi.md#g_et_credit_memo) | **GET** /v1/creditmemos/{creditMemoKey} | Retrieve a credit memo
*CreditMemosApi* | [**g_et_credit_memo_item**](docs/CreditMemosApi.md#g_et_credit_memo_item) | **GET** /v1/creditmemos/{creditMemoKey}/items/{cmitemid} | Retrieve a credit memo item
*CreditMemosApi* | [**g_et_credit_memo_item_part**](docs/CreditMemosApi.md#g_et_credit_memo_item_part) | **GET** /v1/creditmemos/{creditMemoKey}/parts/{partid}/itemparts/{itempartid} | Retrieve a credit memo part item
*CreditMemosApi* | [**g_et_credit_memo_item_parts**](docs/CreditMemosApi.md#g_et_credit_memo_item_parts) | **GET** /v1/creditmemos/{creditMemoKey}/parts/{partid}/itemparts | List all credit memo part items
*CreditMemosApi* | [**g_et_credit_memo_items**](docs/CreditMemosApi.md#g_et_credit_memo_items) | **GET** /v1/creditmemos/{creditMemoKey}/items | List credit memo items
*CreditMemosApi* | [**g_et_credit_memo_part**](docs/CreditMemosApi.md#g_et_credit_memo_part) | **GET** /v1/creditmemos/{creditMemoKey}/parts/{partid} | Retrieve a credit memo part
*CreditMemosApi* | [**g_et_credit_memo_parts**](docs/CreditMemosApi.md#g_et_credit_memo_parts) | **GET** /v1/creditmemos/{creditMemoKey}/parts | List all parts of a credit memo
*CreditMemosApi* | [**g_et_credit_memos**](docs/CreditMemosApi.md#g_et_credit_memos) | **GET** /v1/creditmemos | List credit memos
*CreditMemosApi* | [**g_et_taxation_items_of_credit_memo_item**](docs/CreditMemosApi.md#g_et_taxation_items_of_credit_memo_item) | **GET** /v1/creditmemos/{creditMemoId}/items/{cmitemid}/taxation-items | List all taxation items of a credit memo item
*CreditMemosApi* | [**p_ost_create_credit_memos**](docs/CreditMemosApi.md#p_ost_create_credit_memos) | **POST** /v1/creditmemos/bulk | Create credit memos
*CreditMemosApi* | [**p_ost_credit_memo_from_invoice**](docs/CreditMemosApi.md#p_ost_credit_memo_from_invoice) | **POST** /v1/invoices/{invoiceKey}/creditmemos | Create a credit memo from an invoice
*CreditMemosApi* | [**p_ost_credit_memo_from_prpc**](docs/CreditMemosApi.md#p_ost_credit_memo_from_prpc) | **POST** /v1/creditmemos | Create a credit memo from a charge
*CreditMemosApi* | [**p_ost_credit_memo_pdf**](docs/CreditMemosApi.md#p_ost_credit_memo_pdf) | **POST** /v1/creditmemos/{creditMemoKey}/pdfs | Generate a credit memo PDF file
*CreditMemosApi* | [**p_ost_email_credit_memo**](docs/CreditMemosApi.md#p_ost_email_credit_memo) | **POST** /v1/creditmemos/{creditMemoKey}/emails | Email a credit memo
*CreditMemosApi* | [**p_ost_refund_credit_memo**](docs/CreditMemosApi.md#p_ost_refund_credit_memo) | **POST** /v1/creditmemos/{creditMemoKey}/refunds | Refund a credit memo
*CreditMemosApi* | [**p_ost_upload_file_for_credit_memo**](docs/CreditMemosApi.md#p_ost_upload_file_for_credit_memo) | **POST** /v1/creditmemos/{creditMemoKey}/files | Upload a file for a credit memo
*CreditMemosApi* | [**p_ostcm_taxation_items**](docs/CreditMemosApi.md#p_ostcm_taxation_items) | **POST** /v1/creditmemos/{creditMemoKey}/taxationitems | Create taxation items for a credit memo
*CreditMemosApi* | [**p_ut_apply_credit_memo**](docs/CreditMemosApi.md#p_ut_apply_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey}/apply | Apply a credit memo
*CreditMemosApi* | [**p_ut_cancel_credit_memo**](docs/CreditMemosApi.md#p_ut_cancel_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey}/cancel | Cancel a credit memo
*CreditMemosApi* | [**p_ut_post_credit_memo**](docs/CreditMemosApi.md#p_ut_post_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey}/post | Post a credit memo
*CreditMemosApi* | [**p_ut_reverse_credit_memo**](docs/CreditMemosApi.md#p_ut_reverse_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey}/reverse | Reverse a credit memo
*CreditMemosApi* | [**p_ut_unapply_credit_memo**](docs/CreditMemosApi.md#p_ut_unapply_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey}/unapply | Unapply a credit memo
*CreditMemosApi* | [**p_ut_unpost_credit_memo**](docs/CreditMemosApi.md#p_ut_unpost_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey}/unpost | Unpost a credit memo
*CreditMemosApi* | [**p_ut_update_credit_memo**](docs/CreditMemosApi.md#p_ut_update_credit_memo) | **PUT** /v1/creditmemos/{creditMemoKey} | Update a credit memo
*CreditMemosApi* | [**p_ut_update_credit_memos**](docs/CreditMemosApi.md#p_ut_update_credit_memos) | **PUT** /v1/creditmemos/bulk | Update credit memos
*CreditMemosApi* | [**p_ut_write_off_credit_memo**](docs/CreditMemosApi.md#p_ut_write_off_credit_memo) | **PUT** /v1/creditmemos/{creditMemoId}/write-off | Write off a credit memo
*CustomEventTriggersApi* | [**d_elete_event_trigger**](docs/CustomEventTriggersApi.md#d_elete_event_trigger) | **DELETE** /events/event-triggers/{id} | Delete an event trigger
*CustomEventTriggersApi* | [**g_et_event_trigger**](docs/CustomEventTriggersApi.md#g_et_event_trigger) | **GET** /events/event-triggers/{id} | Retrieve an event trigger
*CustomEventTriggersApi* | [**g_et_event_triggers**](docs/CustomEventTriggersApi.md#g_et_event_triggers) | **GET** /events/event-triggers | List event triggers
*CustomEventTriggersApi* | [**p_ost_event_trigger**](docs/CustomEventTriggersApi.md#p_ost_event_trigger) | **POST** /events/event-triggers | Create an event trigger
*CustomEventTriggersApi* | [**p_ut_event_trigger**](docs/CustomEventTriggersApi.md#p_ut_event_trigger) | **PUT** /events/event-triggers/{id} | Update an event trigger
*CustomExchangeRatesApi* | [**g_et_custom_exchange_rates**](docs/CustomExchangeRatesApi.md#g_et_custom_exchange_rates) | **GET** /v1/custom-exchange-rates/{currency} | List custom exchange rates by currency
*CustomObjectDefinitionsApi* | [**delete_custom_object_definition_by_type**](docs/CustomObjectDefinitionsApi.md#delete_custom_object_definition_by_type) | **DELETE** /objects/definitions/default/{object} | Delete a custom object definition
*CustomObjectDefinitionsApi* | [**g_et_all_custom_object_definitions_in_namespace**](docs/CustomObjectDefinitionsApi.md#g_et_all_custom_object_definitions_in_namespace) | **GET** /objects/definitions/default | List custom object definitions
*CustomObjectDefinitionsApi* | [**g_et_custom_object_definition_by_type**](docs/CustomObjectDefinitionsApi.md#g_et_custom_object_definition_by_type) | **GET** /objects/definitions/default/{object} | Retrieve a custom object definition
*CustomObjectDefinitionsApi* | [**p_ost_custom_object_definitions**](docs/CustomObjectDefinitionsApi.md#p_ost_custom_object_definitions) | **POST** /objects/definitions/default | Create custom object definitions
*CustomObjectDefinitionsApi* | [**p_ost_update_custom_object_definition**](docs/CustomObjectDefinitionsApi.md#p_ost_update_custom_object_definition) | **POST** /objects/migrations | Update a custom object definition
*CustomObjectJobsApi* | [**g_et_all_custom_object_bulk_jobs**](docs/CustomObjectJobsApi.md#g_et_all_custom_object_bulk_jobs) | **GET** /objects/jobs | List all custom object bulk jobs
*CustomObjectJobsApi* | [**g_et_custom_object_bulk_job**](docs/CustomObjectJobsApi.md#g_et_custom_object_bulk_job) | **GET** /objects/jobs/{id} | Retrieve a custom object bulk job
*CustomObjectJobsApi* | [**g_et_custom_object_bulk_job_errors**](docs/CustomObjectJobsApi.md#g_et_custom_object_bulk_job_errors) | **GET** /objects/jobs/{id}/errors | List all errors for a custom object bulk job
*CustomObjectJobsApi* | [**p_atch_custom_object_bulk_job**](docs/CustomObjectJobsApi.md#p_atch_custom_object_bulk_job) | **PATCH** /objects/jobs/{id}/cancel | Cancel a custom object bulk job
*CustomObjectJobsApi* | [**p_ost_custom_object_bulk_job**](docs/CustomObjectJobsApi.md#p_ost_custom_object_bulk_job) | **POST** /objects/jobs | Submit a custom object bulk job
*CustomObjectJobsApi* | [**p_ost_upload_file_for_custom_object_bulk_job**](docs/CustomObjectJobsApi.md#p_ost_upload_file_for_custom_object_bulk_job) | **POST** /objects/jobs/{id}/files | Upload a file for a custom object bulk job
*CustomObjectRecordsApi* | [**delete_custom_object_record_by_id**](docs/CustomObjectRecordsApi.md#delete_custom_object_record_by_id) | **DELETE** /objects/records/default/{object}/{id} | Delete a custom object record
*CustomObjectRecordsApi* | [**g_et_all_records_for_custom_object_type**](docs/CustomObjectRecordsApi.md#g_et_all_records_for_custom_object_type) | **GET** /objects/records/default/{object} | List records for a custom object
*CustomObjectRecordsApi* | [**g_et_custom_object_record_by_id**](docs/CustomObjectRecordsApi.md#g_et_custom_object_record_by_id) | **GET** /objects/records/default/{object}/{id} | Retrieve a custom object record
*CustomObjectRecordsApi* | [**p_ost_custom_object_records**](docs/CustomObjectRecordsApi.md#p_ost_custom_object_records) | **POST** /objects/records/default/{object} | Create custom object records
*CustomObjectRecordsApi* | [**p_ost_custom_object_records_batch_update_or_delete**](docs/CustomObjectRecordsApi.md#p_ost_custom_object_records_batch_update_or_delete) | **POST** /objects/batch/default/{object} | Update or delete custom object records
*CustomObjectRecordsApi* | [**p_ut_custom_object_record**](docs/CustomObjectRecordsApi.md#p_ut_custom_object_record) | **PUT** /objects/records/default/{object}/{id} | Update a custom object record
*CustomObjectRecordsApi* | [**patch_partial_update_custom_object_record**](docs/CustomObjectRecordsApi.md#patch_partial_update_custom_object_record) | **PATCH** /objects/records/default/{object}/{id} | Partially update a custom object record
*CustomPaymentMethodTypesApi* | [**g_et_open_payment_method_type_publish**](docs/CustomPaymentMethodTypesApi.md#g_et_open_payment_method_type_publish) | **GET** /open-payment-method-types/{paymentMethodTypeName}/published | Retrieve a published custom payment method type
*CustomPaymentMethodTypesApi* | [**g_et_open_payment_method_type_revision**](docs/CustomPaymentMethodTypesApi.md#g_et_open_payment_method_type_revision) | **GET** /open-payment-method-types/{paymentMethodTypeName}/draft/{revisionNumber} | Retrieve a specific draft revision of a custom payment method type
*CustomPaymentMethodTypesApi* | [**p_ost_create_draft_open_payment_method_type**](docs/CustomPaymentMethodTypesApi.md#p_ost_create_draft_open_payment_method_type) | **POST** /open-payment-method-types | Create a draft custom payment method type
*CustomPaymentMethodTypesApi* | [**p_ut_publish_open_payment_method_type**](docs/CustomPaymentMethodTypesApi.md#p_ut_publish_open_payment_method_type) | **PUT** /open-payment-method-types/publish/{paymentMethodTypeName} | Publish a custom payment method type
*CustomPaymentMethodTypesApi* | [**p_ut_update_open_payment_method_type**](docs/CustomPaymentMethodTypesApi.md#p_ut_update_open_payment_method_type) | **PUT** /open-payment-method-types/{paymentMethodTypeName} | Update a custom payment method type
*CustomScheduledEventsApi* | [**d_elete_scheduled_event_by_id**](docs/CustomScheduledEventsApi.md#d_elete_scheduled_event_by_id) | **DELETE** /events/scheduled-events/{id} | Delete a scheduled event by ID
*CustomScheduledEventsApi* | [**g_et_scheduled_event_by_id**](docs/CustomScheduledEventsApi.md#g_et_scheduled_event_by_id) | **GET** /events/scheduled-events/{id} | Retrieve a scheduled event by ID
*CustomScheduledEventsApi* | [**g_et_scheduled_events**](docs/CustomScheduledEventsApi.md#g_et_scheduled_events) | **GET** /events/scheduled-events | List all scheduled events
*CustomScheduledEventsApi* | [**p_ost_scheduled_event**](docs/CustomScheduledEventsApi.md#p_ost_scheduled_event) | **POST** /events/scheduled-events | Create a scheduled event
*CustomScheduledEventsApi* | [**u_pdate_scheduled_event_by_id**](docs/CustomScheduledEventsApi.md#u_pdate_scheduled_event_by_id) | **PUT** /events/scheduled-events/{id} | Update a scheduled event by ID
*DataQueriesApi* | [**d_elete_data_query_job**](docs/DataQueriesApi.md#d_elete_data_query_job) | **DELETE** /query/jobs/{job-id} | Cancel a data query job
*DataQueriesApi* | [**g_et_data_query_job**](docs/DataQueriesApi.md#g_et_data_query_job) | **GET** /query/jobs/{job-id} | Retrieve a data query job
*DataQueriesApi* | [**g_et_data_query_jobs**](docs/DataQueriesApi.md#g_et_data_query_jobs) | **GET** /query/jobs | List data query jobs
*DataQueriesApi* | [**p_ost_data_query_job**](docs/DataQueriesApi.md#p_ost_data_query_job) | **POST** /query/jobs | Submit a data query
*DebitMemosApi* | [**d_elete_debit_memo**](docs/DebitMemosApi.md#d_elete_debit_memo) | **DELETE** /v1/debitmemos/{debitMemoKey} | Delete a debit memo
*DebitMemosApi* | [**g_et_debit_memo**](docs/DebitMemosApi.md#g_et_debit_memo) | **GET** /v1/debitmemos/{debitMemoKey} | Retrieve a debit memo
*DebitMemosApi* | [**g_et_debit_memo_application_parts**](docs/DebitMemosApi.md#g_et_debit_memo_application_parts) | **GET** /v1/debitmemos/{debitMemoId}/application-parts | List all application parts of a debit memo
*DebitMemosApi* | [**g_et_debit_memo_item**](docs/DebitMemosApi.md#g_et_debit_memo_item) | **GET** /v1/debitmemos/{debitMemoKey}/items/{dmitemid} | Retrieve a debit memo item
*DebitMemosApi* | [**g_et_debit_memo_items**](docs/DebitMemosApi.md#g_et_debit_memo_items) | **GET** /v1/debitmemos/{debitMemoKey}/items | List debit memo items
*DebitMemosApi* | [**g_et_debit_memos**](docs/DebitMemosApi.md#g_et_debit_memos) | **GET** /v1/debitmemos | List debit memos
*DebitMemosApi* | [**g_et_taxation_items_of_debit_memo_item**](docs/DebitMemosApi.md#g_et_taxation_items_of_debit_memo_item) | **GET** /v1/debitmemos/{debitMemoId}/items/{dmitemid}/taxation-items | List all taxation items of a debit memo item
*DebitMemosApi* | [**p_ost_create_debit_memos**](docs/DebitMemosApi.md#p_ost_create_debit_memos) | **POST** /v1/debitmemos/bulk | Create debit memos
*DebitMemosApi* | [**p_ost_debit_memo_collect**](docs/DebitMemosApi.md#p_ost_debit_memo_collect) | **POST** /v1/debitmemos/{debitMemoKey}/collect | Collect a posted debit memo
*DebitMemosApi* | [**p_ost_debit_memo_from_invoice**](docs/DebitMemosApi.md#p_ost_debit_memo_from_invoice) | **POST** /v1/invoices/{invoiceKey}/debitmemos | Create a debit memo from an invoice
*DebitMemosApi* | [**p_ost_debit_memo_from_prpc**](docs/DebitMemosApi.md#p_ost_debit_memo_from_prpc) | **POST** /v1/debitmemos | Create a debit memo from a charge
*DebitMemosApi* | [**p_ost_debit_memo_pdf**](docs/DebitMemosApi.md#p_ost_debit_memo_pdf) | **POST** /v1/debitmemos/{debitMemoKey}/pdfs | Generate a debit memo PDF file
*DebitMemosApi* | [**p_ost_email_debit_memo**](docs/DebitMemosApi.md#p_ost_email_debit_memo) | **POST** /v1/debitmemos/{debitMemoKey}/emails | Email a debit memo
*DebitMemosApi* | [**p_ost_upload_file_for_debit_memo**](docs/DebitMemosApi.md#p_ost_upload_file_for_debit_memo) | **POST** /v1/debitmemos/{debitMemoKey}/files | Upload a file for a debit memo
*DebitMemosApi* | [**p_ostdm_taxation_items**](docs/DebitMemosApi.md#p_ostdm_taxation_items) | **POST** /v1/debitmemos/{debitMemoKey}/taxationitems | Create taxation items for a debit memo
*DebitMemosApi* | [**p_ut_cancel_debit_memo**](docs/DebitMemosApi.md#p_ut_cancel_debit_memo) | **PUT** /v1/debitmemos/{debitMemoKey}/cancel | Cancel a debit memo
*DebitMemosApi* | [**p_ut_debit_memo**](docs/DebitMemosApi.md#p_ut_debit_memo) | **PUT** /v1/debitmemos/{debitMemoKey} | Update a debit memo
*DebitMemosApi* | [**p_ut_post_debit_memo**](docs/DebitMemosApi.md#p_ut_post_debit_memo) | **PUT** /v1/debitmemos/{debitMemoKey}/post | Post a debit memo
*DebitMemosApi* | [**p_ut_unpost_debit_memo**](docs/DebitMemosApi.md#p_ut_unpost_debit_memo) | **PUT** /v1/debitmemos/{debitMemoKey}/unpost | Unpost a debit memo
*DebitMemosApi* | [**p_ut_update_debit_memos**](docs/DebitMemosApi.md#p_ut_update_debit_memos) | **PUT** /v1/debitmemos/bulk | Update debit memos
*DebitMemosApi* | [**p_ut_update_debit_memos_due_dates**](docs/DebitMemosApi.md#p_ut_update_debit_memos_due_dates) | **PUT** /v1/debitmemos | Update due dates for debit memos
*DescribeApi* | [**g_et_describe**](docs/DescribeApi.md#g_et_describe) | **GET** /v1/describe/{object} | Describe an object
*ElectronicPaymentsHealthApi* | [**g_et_system_health_payment_volume_summary**](docs/ElectronicPaymentsHealthApi.md#g_et_system_health_payment_volume_summary) | **GET** /system-health/payments/volume-summary | List payment volume summary records
*FilesApi* | [**g_et_files**](docs/FilesApi.md#g_et_files) | **GET** /v1/files/{file-id} | Retrieve a file
*FulfillmentsApi* | [**create_fulfillment**](docs/FulfillmentsApi.md#create_fulfillment) | **POST** /v1/fulfillments | Create fulfillments
*FulfillmentsApi* | [**create_fulfillment_item**](docs/FulfillmentsApi.md#create_fulfillment_item) | **POST** /v1/fulfillment-items | Create fulfillment items
*FulfillmentsApi* | [**delete_fulfillment**](docs/FulfillmentsApi.md#delete_fulfillment) | **DELETE** /v1/fulfillments/{key} | Delete a fulfillment
*FulfillmentsApi* | [**delete_fulfillment_item**](docs/FulfillmentsApi.md#delete_fulfillment_item) | **DELETE** /v1/fulfillment-items/{id} | Delete a fulfillment item
*FulfillmentsApi* | [**g_et_fulfillment**](docs/FulfillmentsApi.md#g_et_fulfillment) | **GET** /v1/fulfillments/{key} | Retrieve a fulfillment
*FulfillmentsApi* | [**g_et_fulfillment_item**](docs/FulfillmentsApi.md#g_et_fulfillment_item) | **GET** /v1/fulfillment-items/{id} | Retrieve a fulfillment item
*FulfillmentsApi* | [**p_ut_fulfillment**](docs/FulfillmentsApi.md#p_ut_fulfillment) | **PUT** /v1/fulfillments/{key} | Update a fulfillment
*FulfillmentsApi* | [**p_ut_fulfillment_item**](docs/FulfillmentsApi.md#p_ut_fulfillment_item) | **PUT** /v1/fulfillment-items/{id} | Update a fulfillment item
*HostedPagesApi* | [**get_hosted_pages**](docs/HostedPagesApi.md#get_hosted_pages) | **GET** /v1/hostedpages | List hosted pages
*ImportsApi* | [**object_get_import**](docs/ImportsApi.md#object_get_import) | **GET** /v1/object/import/{id} | CRUD: Retrieve an import
*ImportsApi* | [**object_post_import**](docs/ImportsApi.md#object_post_import) | **POST** /v1/object/import | CRUD: Create an import
*InvoiceSchedulesApi* | [**d_elete_invoice_schedule**](docs/InvoiceSchedulesApi.md#d_elete_invoice_schedule) | **DELETE** /v1/invoice-schedules/{scheduleKey} | Delete an invoice schedule
*InvoiceSchedulesApi* | [**g_et_invoice_schedule**](docs/InvoiceSchedulesApi.md#g_et_invoice_schedule) | **GET** /v1/invoice-schedules/{scheduleKey} | Retrieve an invoice schedule
*InvoiceSchedulesApi* | [**p_ost_create_invoice_schedule**](docs/InvoiceSchedulesApi.md#p_ost_create_invoice_schedule) | **POST** /v1/invoice-schedules | Create an invoice schedule
*InvoiceSchedulesApi* | [**p_ost_execute_invoice_schedule**](docs/InvoiceSchedulesApi.md#p_ost_execute_invoice_schedule) | **POST** /v1/invoice-schedules/{scheduleKey}/execute | Execute an invoice schedule
*InvoiceSchedulesApi* | [**p_ut_pause_invoice_schedule**](docs/InvoiceSchedulesApi.md#p_ut_pause_invoice_schedule) | **PUT** /v1/invoice-schedules/{scheduleKey}/pause | Pause an invoice schedule
*InvoiceSchedulesApi* | [**p_ut_resume_invoice_schedule**](docs/InvoiceSchedulesApi.md#p_ut_resume_invoice_schedule) | **PUT** /v1/invoice-schedules/{scheduleKey}/resume | Resume an invoice schedule
*InvoiceSchedulesApi* | [**p_ut_update_invoice_schedule**](docs/InvoiceSchedulesApi.md#p_ut_update_invoice_schedule) | **PUT** /v1/invoice-schedules/{scheduleKey} | Update an invoice schedule
*InvoicesApi* | [**d_elete_delete_invoice**](docs/InvoicesApi.md#d_elete_delete_invoice) | **DELETE** /v1/invoices/{invoiceKey} | Delete an invoice
*InvoicesApi* | [**g_et_invoice_application_parts**](docs/InvoicesApi.md#g_et_invoice_application_parts) | **GET** /v1/invoices/{invoiceKey}/application-parts | List all application parts of an invoice
*InvoicesApi* | [**g_et_invoice_files**](docs/InvoicesApi.md#g_et_invoice_files) | **GET** /v1/invoices/{invoiceKey}/files | List all files of an invoice
*InvoicesApi* | [**g_et_invoice_items**](docs/InvoicesApi.md#g_et_invoice_items) | **GET** /v1/invoices/{invoiceKey}/items | List all items of an invoice
*InvoicesApi* | [**g_et_taxation_items_of_invoice_item**](docs/InvoicesApi.md#g_et_taxation_items_of_invoice_item) | **GET** /v1/invoices/{invoiceKey}/items/{itemId}/taxation-items | List all taxation items of an invoice item
*InvoicesApi* | [**get_get_invoice**](docs/InvoicesApi.md#get_get_invoice) | **GET** /v1/invoices/{invoiceKey} | Retrieve an invoice
*InvoicesApi* | [**p_ost_email_invoice**](docs/InvoicesApi.md#p_ost_email_invoice) | **POST** /v1/invoices/{invoiceKey}/emails | Email an invoice
*InvoicesApi* | [**p_ost_post_invoices**](docs/InvoicesApi.md#p_ost_post_invoices) | **POST** /v1/invoices/bulk-post | Post invoices
*InvoicesApi* | [**p_ost_standalone_invoice**](docs/InvoicesApi.md#p_ost_standalone_invoice) | **POST** /v1/invoices | Create a standalone invoice
*InvoicesApi* | [**p_ost_standalone_invoices**](docs/InvoicesApi.md#p_ost_standalone_invoices) | **POST** /v1/invoices/batch | Create standalone invoices
*InvoicesApi* | [**p_ost_upload_file_for_invoice**](docs/InvoicesApi.md#p_ost_upload_file_for_invoice) | **POST** /v1/invoices/{invoiceKey}/files | Upload a file for an invoice
*InvoicesApi* | [**p_ostinv_taxation_items**](docs/InvoicesApi.md#p_ostinv_taxation_items) | **POST** /v1/invoices/{invoiceKey}/taxationitems | Create taxation items for an invoice
*InvoicesApi* | [**p_ut_batch_update_invoices**](docs/InvoicesApi.md#p_ut_batch_update_invoices) | **PUT** /v1/invoices | Update invoices
*InvoicesApi* | [**p_ut_reverse_invoice**](docs/InvoicesApi.md#p_ut_reverse_invoice) | **PUT** /v1/invoices/{invoiceKey}/reverse | Reverse an invoice
*InvoicesApi* | [**p_ut_update_invoice**](docs/InvoicesApi.md#p_ut_update_invoice) | **PUT** /v1/invoices/{invoiceKey} | Update an invoice
*InvoicesApi* | [**p_ut_write_off_invoice**](docs/InvoicesApi.md#p_ut_write_off_invoice) | **PUT** /v1/invoices/{invoiceKey}/write-off | Write off an invoice
*JournalRunsApi* | [**d_elete_journal_run**](docs/JournalRunsApi.md#d_elete_journal_run) | **DELETE** /v1/journal-runs/{jr-number} | Delete a journal run
*JournalRunsApi* | [**g_et_journal_run**](docs/JournalRunsApi.md#g_et_journal_run) | **GET** /v1/journal-runs/{jr-number} | Retrieve a journal run
*JournalRunsApi* | [**p_ost_journal_run**](docs/JournalRunsApi.md#p_ost_journal_run) | **POST** /v1/journal-runs | Create a journal run
*JournalRunsApi* | [**p_ut_journal_run**](docs/JournalRunsApi.md#p_ut_journal_run) | **PUT** /v1/journal-runs/{jr-number}/cancel | Cancel a journal run
*MassUpdaterApi* | [**g_et_mass_updater**](docs/MassUpdaterApi.md#g_et_mass_updater) | **GET** /v1/bulk/{bulk-key} | List all results of a mass action
*MassUpdaterApi* | [**p_ost_mass_updater**](docs/MassUpdaterApi.md#p_ost_mass_updater) | **POST** /v1/bulk | Perform a mass action
*MassUpdaterApi* | [**p_ut_mass_updater**](docs/MassUpdaterApi.md#p_ut_mass_updater) | **PUT** /v1/bulk/{bulk-key}/stop | Stop a mass action
*NotificationsApi* | [**d_elete_delete_email_template**](docs/NotificationsApi.md#d_elete_delete_email_template) | **DELETE** /notifications/email-templates/{id} | Delete an email template
*NotificationsApi* | [**d_elete_delete_notification_definition**](docs/NotificationsApi.md#d_elete_delete_notification_definition) | **DELETE** /notifications/notification-definitions/{id} | Delete a notification definition
*NotificationsApi* | [**d_elete_delete_notification_history_for_account**](docs/NotificationsApi.md#d_elete_delete_notification_history_for_account) | **DELETE** /notifications/history | Delete notification histories for an account
*NotificationsApi* | [**g_et_callout_history**](docs/NotificationsApi.md#g_et_callout_history) | **GET** /v1/notification-history/callout | List callout notification histories
*NotificationsApi* | [**g_et_email_history**](docs/NotificationsApi.md#g_et_email_history) | **GET** /v1/notification-history/email | List email notification histories
*NotificationsApi* | [**g_et_get_email_template**](docs/NotificationsApi.md#g_et_get_email_template) | **GET** /notifications/email-templates/{id} | Retrieve an email template
*NotificationsApi* | [**g_et_get_notification_definition**](docs/NotificationsApi.md#g_et_get_notification_definition) | **GET** /notifications/notification-definitions/{id} | Retrieve a notification definition
*NotificationsApi* | [**g_et_get_notification_history_deletion_task**](docs/NotificationsApi.md#g_et_get_notification_history_deletion_task) | **GET** /notifications/history/tasks/{id} | Retrieve a notification history deletion task
*NotificationsApi* | [**g_et_query_email_templates**](docs/NotificationsApi.md#g_et_query_email_templates) | **GET** /notifications/email-templates | List email templates
*NotificationsApi* | [**g_et_query_notification_definitions**](docs/NotificationsApi.md#g_et_query_notification_definitions) | **GET** /notifications/notification-definitions | List notification definitions
*NotificationsApi* | [**p_ost_create_email_template**](docs/NotificationsApi.md#p_ost_create_email_template) | **POST** /notifications/email-templates | Create an email template
*NotificationsApi* | [**p_ost_create_notification_definition**](docs/NotificationsApi.md#p_ost_create_notification_definition) | **POST** /notifications/notification-definitions | Create a notification definition
*NotificationsApi* | [**p_ost_create_or_update_email_templates**](docs/NotificationsApi.md#p_ost_create_or_update_email_templates) | **POST** /notifications/email-templates/import | Create or update email templates
*NotificationsApi* | [**p_ost_resend_callout_notifications**](docs/NotificationsApi.md#p_ost_resend_callout_notifications) | **POST** /notifications/callout-histories/resend | Resend callout notifications
*NotificationsApi* | [**p_ost_resend_email_notifications**](docs/NotificationsApi.md#p_ost_resend_email_notifications) | **POST** /notifications/email-histories/resend | Resend email notifications
*NotificationsApi* | [**p_ut_update_email_template**](docs/NotificationsApi.md#p_ut_update_email_template) | **PUT** /notifications/email-templates/{id} | Update an email template
*NotificationsApi* | [**p_ut_update_notification_definition**](docs/NotificationsApi.md#p_ut_update_notification_definition) | **PUT** /notifications/notification-definitions/{id} | Update a notification definition
*OAuthApi* | [**create_token**](docs/OAuthApi.md#create_token) | **POST** /oauth/token | Create an OAuth token
*OffersApi* | [**d_elete_offer**](docs/OffersApi.md#d_elete_offer) | **DELETE** /v1/offers/{offer-key} | Delete an offer
*OffersApi* | [**g_et_list_offers**](docs/OffersApi.md#g_et_list_offers) | **GET** /v1/offers | List offers
*OffersApi* | [**g_et_retrieve_offer**](docs/OffersApi.md#g_et_retrieve_offer) | **GET** /v1/offers/{offer-key} | Retrieve an offer
*OffersApi* | [**p_ost_create_offer**](docs/OffersApi.md#p_ost_create_offer) | **POST** /v1/offers | Create an offer
*OperationsApi* | [**g_et_operation_job**](docs/OperationsApi.md#g_et_operation_job) | **GET** /v1/operations/jobs/{jobId} | Retrieve an operation job
*OperationsApi* | [**p_ost_billing_preview**](docs/OperationsApi.md#p_ost_billing_preview) | **POST** /v1/operations/billing-preview | Generate a billing preview
*OperationsApi* | [**p_ost_transaction_invoice_payment**](docs/OperationsApi.md#p_ost_transaction_invoice_payment) | **POST** /v1/operations/invoice-collect | Invoice and collect
*OrderActionsApi* | [**p_ut_order_actions**](docs/OrderActionsApi.md#p_ut_order_actions) | **PUT** /v1/orderActions/{id} | Update an order action
*OrderLineItemsApi* | [**g_et_order_line_item**](docs/OrderLineItemsApi.md#g_et_order_line_item) | **GET** /v1/order-line-items/{itemId} | Retrieve an order line item
*OrderLineItemsApi* | [**p_ut_order_line_item**](docs/OrderLineItemsApi.md#p_ut_order_line_item) | **PUT** /v1/order-line-items/{itemId} | Update an order line item
*OrderLineItemsApi* | [**post_order_line_items**](docs/OrderLineItemsApi.md#post_order_line_items) | **POST** /v1/order-line-items/bulk | Update order line items
*OrdersApi* | [**d_elete_order**](docs/OrdersApi.md#d_elete_order) | **DELETE** /v1/orders/{orderNumber} | Delete an order
*OrdersApi* | [**g_et_all_orders**](docs/OrdersApi.md#g_et_all_orders) | **GET** /v1/orders | List orders
*OrdersApi* | [**g_et_job_status_and_response**](docs/OrdersApi.md#g_et_job_status_and_response) | **GET** /v1/async-jobs/{jobId} | Retrieve the status and response of a job
*OrdersApi* | [**g_et_order**](docs/OrdersApi.md#g_et_order) | **GET** /v1/orders/{orderNumber} | Retrieve an order
*OrdersApi* | [**g_et_orders_by_invoice_owner**](docs/OrdersApi.md#g_et_orders_by_invoice_owner) | **GET** /v1/orders/invoiceOwner/{accountNumber} | List orders of an invoice owner
*OrdersApi* | [**g_et_orders_by_subscription_number**](docs/OrdersApi.md#g_et_orders_by_subscription_number) | **GET** /v1/orders/subscription/{subscriptionNumber} | List orders by subscription number
*OrdersApi* | [**g_et_orders_by_subscription_owner**](docs/OrdersApi.md#g_et_orders_by_subscription_owner) | **GET** /v1/orders/subscriptionOwner/{accountNumber} | List orders of a subscription owner
*OrdersApi* | [**g_et_pending_orders_by_subscription_number**](docs/OrdersApi.md#g_et_pending_orders_by_subscription_number) | **GET** /v1/orders/subscription/{subscription-key}/pending | List pending orders by subscription number
*OrdersApi* | [**p_ost_create_order_asynchronously**](docs/OrdersApi.md#p_ost_create_order_asynchronously) | **POST** /v1/async/orders | Create an order asynchronously
*OrdersApi* | [**p_ost_order**](docs/OrdersApi.md#p_ost_order) | **POST** /v1/orders | Create an order
*OrdersApi* | [**p_ost_preview_order**](docs/OrdersApi.md#p_ost_preview_order) | **POST** /v1/orders/preview | Preview an order
*OrdersApi* | [**p_ost_preview_order_asynchronously**](docs/OrdersApi.md#p_ost_preview_order_asynchronously) | **POST** /v1/async/orders/preview | Preview an order asynchronously
*OrdersApi* | [**p_ut_order**](docs/OrdersApi.md#p_ut_order) | **PUT** /v1/orders/{orderNumber} | Update an order
*OrdersApi* | [**p_ut_order_activate**](docs/OrdersApi.md#p_ut_order_activate) | **PUT** /v1/orders/{orderNumber}/activate | Activate an order
*OrdersApi* | [**p_ut_order_cancel**](docs/OrdersApi.md#p_ut_order_cancel) | **PUT** /v1/orders/{orderNumber}/cancel | Cancel an order
*OrdersApi* | [**p_ut_order_trigger_dates**](docs/OrdersApi.md#p_ut_order_trigger_dates) | **PUT** /v1/orders/{orderNumber}/triggerDates | Update order action trigger dates
*OrdersApi* | [**p_ut_update_order_custom_fields**](docs/OrdersApi.md#p_ut_update_order_custom_fields) | **PUT** /v1/orders/{orderNumber}/customFields | Update order custom fields
*OrdersApi* | [**p_ut_update_subscription_custom_fields**](docs/OrdersApi.md#p_ut_update_subscription_custom_fields) | **PUT** /v1/subscriptions/{subscriptionNumber}/customFields | Update subscription custom fields
*PaymentAuthorizationApi* | [**p_ost_cancel_authorization**](docs/PaymentAuthorizationApi.md#p_ost_cancel_authorization) | **POST** /v1/payment-methods/{payment-method-id}/voidAuthorize | Cancel authorization
*PaymentAuthorizationApi* | [**p_ost_create_authorization**](docs/PaymentAuthorizationApi.md#p_ost_create_authorization) | **POST** /v1/payment-methods/{payment-method-id}/authorize | Create authorization
*PaymentGatewayReconciliationApi* | [**p_ost_reconcile_refund**](docs/PaymentGatewayReconciliationApi.md#p_ost_reconcile_refund) | **POST** /v1/refunds/{refund-key}/reconcile | Reconcile a refund
*PaymentGatewayReconciliationApi* | [**p_ost_reject_payment**](docs/PaymentGatewayReconciliationApi.md#p_ost_reject_payment) | **POST** /v1/gateway-settlement/payments/{payment-key}/reject | Reject a payment
*PaymentGatewayReconciliationApi* | [**p_ost_reverse_payment**](docs/PaymentGatewayReconciliationApi.md#p_ost_reverse_payment) | **POST** /v1/gateway-settlement/payments/{payment-key}/chargeback | Reverse a payment
*PaymentGatewayReconciliationApi* | [**p_ost_settle_payment**](docs/PaymentGatewayReconciliationApi.md#p_ost_settle_payment) | **POST** /v1/gateway-settlement/payments/{payment-key}/settle | Settle a payment
*PaymentGatewaysApi* | [**g_et_paymentgateways**](docs/PaymentGatewaysApi.md#g_et_paymentgateways) | **GET** /v1/paymentgateways | List all payment gateways
*PaymentMethodSnapshotsApi* | [**object_get_payment_method_snapshot**](docs/PaymentMethodSnapshotsApi.md#object_get_payment_method_snapshot) | **GET** /v1/object/payment-method-snapshot/{id} | CRUD: Retrieve a payment method snapshot
*PaymentMethodTransactionLogsApi* | [**object_get_payment_method_transaction_log**](docs/PaymentMethodTransactionLogsApi.md#object_get_payment_method_transaction_log) | **GET** /v1/object/payment-method-transaction-log/{id} | CRUD: Retrieve a payment method transaction log
*PaymentMethodUpdaterApi* | [**g_et_payment_method_updater_instances**](docs/PaymentMethodUpdaterApi.md#g_et_payment_method_updater_instances) | **GET** /v1/payment-method-updaters | List Payment Method Updater instances
*PaymentMethodUpdaterApi* | [**p_ost_payment_method_updater_batch**](docs/PaymentMethodUpdaterApi.md#p_ost_payment_method_updater_batch) | **POST** /v1/payment-method-updaters/batches | Create a Payment Method Updater batch asynchronously
*PaymentMethodsApi* | [**d_elete_payment_methods**](docs/PaymentMethodsApi.md#d_elete_payment_methods) | **DELETE** /v1/payment-methods/{payment-method-id} | Delete a payment method
*PaymentMethodsApi* | [**g_et_payment_method**](docs/PaymentMethodsApi.md#g_et_payment_method) | **GET** /v1/payment-methods/{payment-method-id} | Retrieve a payment method
*PaymentMethodsApi* | [**g_et_stored_credential_profiles**](docs/PaymentMethodsApi.md#g_et_stored_credential_profiles) | **GET** /v1/payment-methods/{payment-method-id}/profiles | List stored credential profiles of a payment method
*PaymentMethodsApi* | [**p_ost_cancel_stored_credential_profile**](docs/PaymentMethodsApi.md#p_ost_cancel_stored_credential_profile) | **POST** /v1/payment-methods/{payment-method-id}/profiles/{profile-number}/cancel | Cancel a stored credential profile
*PaymentMethodsApi* | [**p_ost_create_payment_session**](docs/PaymentMethodsApi.md#p_ost_create_payment_session) | **POST** /web-payments/sessions | Create a payment session
*PaymentMethodsApi* | [**p_ost_create_stored_credential_profile**](docs/PaymentMethodsApi.md#p_ost_create_stored_credential_profile) | **POST** /v1/payment-methods/{payment-method-id}/profiles | Create a stored credential profile
*PaymentMethodsApi* | [**p_ost_expire_stored_credential_profile**](docs/PaymentMethodsApi.md#p_ost_expire_stored_credential_profile) | **POST** /v1/payment-methods/{payment-method-id}/profiles/{profile-number}/expire | Expire a stored credential profile
*PaymentMethodsApi* | [**p_ost_payment_methods**](docs/PaymentMethodsApi.md#p_ost_payment_methods) | **POST** /v1/payment-methods | Create a payment method
*PaymentMethodsApi* | [**p_ost_payment_methods_decryption**](docs/PaymentMethodsApi.md#p_ost_payment_methods_decryption) | **POST** /v1/payment-methods/decryption | Create an Apple Pay payment method
*PaymentMethodsApi* | [**p_ut_payment_method**](docs/PaymentMethodsApi.md#p_ut_payment_method) | **PUT** /v1/payment-methods/{payment-method-id} | Update a payment method
*PaymentMethodsApi* | [**p_ut_scrub_payment_methods**](docs/PaymentMethodsApi.md#p_ut_scrub_payment_methods) | **PUT** /v1/payment-methods/{payment-method-id}/scrub | Scrub a payment method
*PaymentMethodsApi* | [**p_ut_verify_payment_methods**](docs/PaymentMethodsApi.md#p_ut_verify_payment_methods) | **PUT** /v1/payment-methods/{payment-method-id}/verify | Verify a payment method
*PaymentRunsApi* | [**d_elete_payment_run**](docs/PaymentRunsApi.md#d_elete_payment_run) | **DELETE** /v1/payment-runs/{paymentRunKey} | Delete a payment run
*PaymentRunsApi* | [**g_et_payment_run**](docs/PaymentRunsApi.md#g_et_payment_run) | **GET** /v1/payment-runs/{paymentRunKey} | Retrieve a payment run
*PaymentRunsApi* | [**g_et_payment_run_data**](docs/PaymentRunsApi.md#g_et_payment_run_data) | **GET** /v1/payment-runs/{paymentRunKey}/data | Retrieve payment run data
*PaymentRunsApi* | [**g_et_payment_run_summary**](docs/PaymentRunsApi.md#g_et_payment_run_summary) | **GET** /v1/payment-runs/{paymentRunKey}/summary | Retrieve a payment run summary
*PaymentRunsApi* | [**g_et_payment_runs**](docs/PaymentRunsApi.md#g_et_payment_runs) | **GET** /v1/payment-runs | List payment runs
*PaymentRunsApi* | [**p_ost_payment_run**](docs/PaymentRunsApi.md#p_ost_payment_run) | **POST** /v1/payment-runs | Create a payment run
*PaymentRunsApi* | [**p_ut_payment_run**](docs/PaymentRunsApi.md#p_ut_payment_run) | **PUT** /v1/payment-runs/{paymentRunKey} | Update a payment run
*PaymentSchedulesApi* | [**g_et_payment_schedule**](docs/PaymentSchedulesApi.md#g_et_payment_schedule) | **GET** /v1/payment-schedules/{paymentScheduleKey} | Retrieve a payment schedule
*PaymentSchedulesApi* | [**g_et_payment_schedule_item**](docs/PaymentSchedulesApi.md#g_et_payment_schedule_item) | **GET** /v1/payment-schedule-items/{item-id} | Retrieve a payment schedule item
*PaymentSchedulesApi* | [**g_et_payment_schedule_statistic**](docs/PaymentSchedulesApi.md#g_et_payment_schedule_statistic) | **GET** /v1/payment-schedules/statistics/{yyyy-mm-dd} | Retrieve payment schedule statistic of a date
*PaymentSchedulesApi* | [**g_et_payment_schedules**](docs/PaymentSchedulesApi.md#g_et_payment_schedules) | **GET** /v1/payment-schedules | List payment schedules by customer account
*PaymentSchedulesApi* | [**p_ost_add_items_to_custom_payment_schedule**](docs/PaymentSchedulesApi.md#p_ost_add_items_to_custom_payment_schedule) | **POST** /v1/payment-schedules/{paymentScheduleKey}/items | Add payment schedule items to a custom payment schedule
*PaymentSchedulesApi* | [**p_ost_payment_schedule**](docs/PaymentSchedulesApi.md#p_ost_payment_schedule) | **POST** /v1/payment-schedules | Create a payment schedule
*PaymentSchedulesApi* | [**p_ost_payment_schedules**](docs/PaymentSchedulesApi.md#p_ost_payment_schedules) | **POST** /v1/payment-schedules/batch | Create multiple payment schedules at once
*PaymentSchedulesApi* | [**p_ost_retry_payment_schedule_item**](docs/PaymentSchedulesApi.md#p_ost_retry_payment_schedule_item) | **POST** /v1/payment-schedule-items/retry-payment | Retry failed payment schedule items
*PaymentSchedulesApi* | [**p_ut_cancel_payment_schedule**](docs/PaymentSchedulesApi.md#p_ut_cancel_payment_schedule) | **PUT** /v1/payment-schedules/{paymentScheduleKey}/cancel | Cancel a payment schedule
*PaymentSchedulesApi* | [**p_ut_cancel_payment_schedule_item**](docs/PaymentSchedulesApi.md#p_ut_cancel_payment_schedule_item) | **PUT** /v1/payment-schedule-items/{item-id}/cancel | Cancel a payment schedule item
*PaymentSchedulesApi* | [**p_ut_payment_schedule**](docs/PaymentSchedulesApi.md#p_ut_payment_schedule) | **PUT** /v1/payment-schedules/{paymentScheduleKey} | Update a payment schedule
*PaymentSchedulesApi* | [**p_ut_payment_schedule_item**](docs/PaymentSchedulesApi.md#p_ut_payment_schedule_item) | **PUT** /v1/payment-schedule-items/{item-id} | Update a payment schedule item
*PaymentSchedulesApi* | [**p_ut_payment_schedule_update_preview**](docs/PaymentSchedulesApi.md#p_ut_payment_schedule_update_preview) | **PUT** /v1/payment-schedules/{paymentScheduleKey}/preview | Preview the result of payment schedule updates
*PaymentSchedulesApi* | [**p_ut_skip_payment_schedule_item**](docs/PaymentSchedulesApi.md#p_ut_skip_payment_schedule_item) | **PUT** /v1/payment-schedule-items/{item-id}/skip | Skip a payment schedule item
*PaymentTransactionLogsApi* | [**object_get_payment_transaction_log**](docs/PaymentTransactionLogsApi.md#object_get_payment_transaction_log) | **GET** /v1/object/payment-transaction-log/{id} | CRUD: Retrieve a payment transaction log
*PaymentsApi* | [**d_elete_payment**](docs/PaymentsApi.md#d_elete_payment) | **DELETE** /v1/payments/{paymentKey} | Delete a payment
*PaymentsApi* | [**g_et_payment**](docs/PaymentsApi.md#g_et_payment) | **GET** /v1/payments/{paymentKey} | Retrieve a payment
*PaymentsApi* | [**g_et_payment_item_part**](docs/PaymentsApi.md#g_et_payment_item_part) | **GET** /v1/payments/{paymentKey}/parts/{partid}/itemparts/{itempartid} | Retrieve a payment part item
*PaymentsApi* | [**g_et_payment_item_parts**](docs/PaymentsApi.md#g_et_payment_item_parts) | **GET** /v1/payments/{paymentKey}/parts/{partid}/itemparts | List all payment part items
*PaymentsApi* | [**g_et_payment_part**](docs/PaymentsApi.md#g_et_payment_part) | **GET** /v1/payments/{paymentKey}/parts/{partid} | Retrieve a payment part
*PaymentsApi* | [**g_et_payment_parts**](docs/PaymentsApi.md#g_et_payment_parts) | **GET** /v1/payments/{paymentKey}/parts | List all parts of a payment
*PaymentsApi* | [**g_et_retrieve_all_payments**](docs/PaymentsApi.md#g_et_retrieve_all_payments) | **GET** /v1/payments | List payments
*PaymentsApi* | [**p_ost_create_payment**](docs/PaymentsApi.md#p_ost_create_payment) | **POST** /v1/payments | Create a payment
*PaymentsApi* | [**p_ost_refund_payment**](docs/PaymentsApi.md#p_ost_refund_payment) | **POST** /v1/payments/{paymentKey}/refunds | Refund a payment
*PaymentsApi* | [**p_ost_refund_paymentwith_auto_unapply**](docs/PaymentsApi.md#p_ost_refund_paymentwith_auto_unapply) | **POST** /v1/payments/{paymentKey}/unapply | Refund a payment with auto-unapplying
*PaymentsApi* | [**p_ut_apply_payment**](docs/PaymentsApi.md#p_ut_apply_payment) | **PUT** /v1/payments/{paymentKey}/apply | Apply a payment
*PaymentsApi* | [**p_ut_cancel_payment**](docs/PaymentsApi.md#p_ut_cancel_payment) | **PUT** /v1/payments/{paymentKey}/cancel | Cancel a payment
*PaymentsApi* | [**p_ut_transfer_payment**](docs/PaymentsApi.md#p_ut_transfer_payment) | **PUT** /v1/payments/{paymentKey}/transfer | Transfer a payment
*PaymentsApi* | [**p_ut_unapply_payment**](docs/PaymentsApi.md#p_ut_unapply_payment) | **PUT** /v1/payments/{paymentKey}/unapply | Unapply a payment
*PaymentsApi* | [**p_ut_update_payment**](docs/PaymentsApi.md#p_ut_update_payment) | **PUT** /v1/payments/{paymentId} | Update a payment
*PriceBookItemsApi* | [**d_elete_price_book_item**](docs/PriceBookItemsApi.md#d_elete_price_book_item) | **DELETE** /v1/price-book-items/{price-book-item-key} | Delete a price book item
*PriceBookItemsApi* | [**g_et_list_price_book_items**](docs/PriceBookItemsApi.md#g_et_list_price_book_items) | **GET** /v1/price-book-items | List price book items
*PriceBookItemsApi* | [**g_et_retrieve_price_book_item**](docs/PriceBookItemsApi.md#g_et_retrieve_price_book_item) | **GET** /v1/price-book-items/{price-book-item-key} | Retrieve a price book item
*PriceBookItemsApi* | [**p_ost_create_price_book_item**](docs/PriceBookItemsApi.md#p_ost_create_price_book_item) | **POST** /v1/price-book-items | Create a price book item
*PriceBookItemsApi* | [**p_ut_update_price_book_item**](docs/PriceBookItemsApi.md#p_ut_update_price_book_item) | **PUT** /v1/price-book-items/{price-book-item-key} | Update a price book item
*ProductRatePlanChargeTiersApi* | [**object_get_product_rate_plan_charge_tier**](docs/ProductRatePlanChargeTiersApi.md#object_get_product_rate_plan_charge_tier) | **GET** /v1/object/product-rate-plan-charge-tier/{id} | CRUD: Retrieve a product rate plan charge tier
*ProductRatePlanChargeTiersApi* | [**object_put_product_rate_plan_charge_tier**](docs/ProductRatePlanChargeTiersApi.md#object_put_product_rate_plan_charge_tier) | **PUT** /v1/object/product-rate-plan-charge-tier/{id} | CRUD: Update a product rate plan charge tier
*ProductRatePlanChargesApi* | [**object_delete_product_rate_plan_charge**](docs/ProductRatePlanChargesApi.md#object_delete_product_rate_plan_charge) | **DELETE** /v1/object/product-rate-plan-charge/{id} | CRUD: Delete a product rate plan charge
*ProductRatePlanChargesApi* | [**object_get_product_rate_plan_charge**](docs/ProductRatePlanChargesApi.md#object_get_product_rate_plan_charge) | **GET** /v1/object/product-rate-plan-charge/{id} | CRUD: Retrieve a product rate plan charge
*ProductRatePlanChargesApi* | [**object_post_product_rate_plan_charge**](docs/ProductRatePlanChargesApi.md#object_post_product_rate_plan_charge) | **POST** /v1/object/product-rate-plan-charge | CRUD: Create a product rate plan charge
*ProductRatePlanChargesApi* | [**object_put_product_rate_plan_charge**](docs/ProductRatePlanChargesApi.md#object_put_product_rate_plan_charge) | **PUT** /v1/object/product-rate-plan-charge/{id} | CRUD: Update a product rate plan charge
*ProductRatePlansApi* | [**g_et_product_rate_plan**](docs/ProductRatePlansApi.md#g_et_product_rate_plan) | **GET** /v1/product-rate-plans/{id} | Retrieve a product rate plan by ID
*ProductRatePlansApi* | [**g_et_product_rate_plans**](docs/ProductRatePlansApi.md#g_et_product_rate_plans) | **GET** /v1/rateplan/{product-key}/productRatePlan | List all product rate plans of a product
*ProductRatePlansApi* | [**g_et_product_rate_plans_by_external_id**](docs/ProductRatePlansApi.md#g_et_product_rate_plans_by_external_id) | **GET** /v1/product-rate-plans/external-id/{id} | List product rate plans by external ID
*ProductRatePlansApi* | [**object_delete_product_rate_plan**](docs/ProductRatePlansApi.md#object_delete_product_rate_plan) | **DELETE** /v1/object/product-rate-plan/{id} | CRUD: Delete a product rate plan
*ProductRatePlansApi* | [**object_get_product_rate_plan**](docs/ProductRatePlansApi.md#object_get_product_rate_plan) | **GET** /v1/object/product-rate-plan/{id} | CRUD: Retrieve a product rate plan
*ProductRatePlansApi* | [**object_post_product_rate_plan**](docs/ProductRatePlansApi.md#object_post_product_rate_plan) | **POST** /v1/object/product-rate-plan | CRUD: Create a product rate plan
*ProductRatePlansApi* | [**object_put_product_rate_plan**](docs/ProductRatePlansApi.md#object_put_product_rate_plan) | **PUT** /v1/object/product-rate-plan/{id} | CRUD: Update a product rate plan
*ProductsApi* | [**object_delete_product**](docs/ProductsApi.md#object_delete_product) | **DELETE** /v1/object/product/{id} | CRUD: Delete a product
*ProductsApi* | [**object_get_product**](docs/ProductsApi.md#object_get_product) | **GET** /v1/object/product/{id} | CRUD: Retrieve a product
*ProductsApi* | [**object_post_product**](docs/ProductsApi.md#object_post_product) | **POST** /v1/object/product | CRUD: Create a product
*ProductsApi* | [**object_put_product**](docs/ProductsApi.md#object_put_product) | **PUT** /v1/object/product/{id} | CRUD: Update a product
*RSASignaturesApi* | [**p_ost_decrypt_rsa_signatures**](docs/RSASignaturesApi.md#p_ost_decrypt_rsa_signatures) | **POST** /v1/rsa-signatures/decrypt | Decrypt an RSA signature
*RSASignaturesApi* | [**p_ostrsa_signatures**](docs/RSASignaturesApi.md#p_ostrsa_signatures) | **POST** /v1/rsa-signatures | Generate an RSA signature
*RampsApi* | [**g_et_ramp_by_ramp_number**](docs/RampsApi.md#g_et_ramp_by_ramp_number) | **GET** /v1/ramps/{rampNumber} | Retrieve a ramp
*RampsApi* | [**g_et_ramp_metrics_by_order_number**](docs/RampsApi.md#g_et_ramp_metrics_by_order_number) | **GET** /v1/orders/{orderNumber}/ramp-metrics | List ramp metrics by order number
*RampsApi* | [**g_et_ramp_metrics_by_ramp_number**](docs/RampsApi.md#g_et_ramp_metrics_by_ramp_number) | **GET** /v1/ramps/{rampNumber}/ramp-metrics | List all ramp metrics of a ramp
*RampsApi* | [**g_et_ramp_metrics_by_subscription_key**](docs/RampsApi.md#g_et_ramp_metrics_by_subscription_key) | **GET** /v1/subscriptions/{subscriptionKey}/ramp-metrics | List ramp metrics by subscription key
*RampsApi* | [**g_et_ramps_by_subscription_key**](docs/RampsApi.md#g_et_ramps_by_subscription_key) | **GET** /v1/subscriptions/{subscriptionKey}/ramps | Retrieve a ramp by subscription key
*RatePlansApi* | [**g_et_rate_plan**](docs/RatePlansApi.md#g_et_rate_plan) | **GET** /v1/rateplans/{ratePlanId} | Retrieve a rate plan
*RefundsApi* | [**d_elete_refund**](docs/RefundsApi.md#d_elete_refund) | **DELETE** /v1/refunds/{refundKey} | Delete a refund
*RefundsApi* | [**g_et_refund**](docs/RefundsApi.md#g_et_refund) | **GET** /v1/refunds/{refundKey} | Retrieve a refund
*RefundsApi* | [**g_et_refund_item_part**](docs/RefundsApi.md#g_et_refund_item_part) | **GET** /v1/refunds/{refundKey}/parts/{refundpartid}/itemparts/{itempartid} | Retrieve a refund part item
*RefundsApi* | [**g_et_refund_item_parts**](docs/RefundsApi.md#g_et_refund_item_parts) | **GET** /v1/refunds/{refundKey}/parts/{refundpartid}/itemparts | List all refund part items
*RefundsApi* | [**g_et_refund_part**](docs/RefundsApi.md#g_et_refund_part) | **GET** /v1/refunds/{refundKey}/parts/{refundpartid} | Retrieve a refund part
*RefundsApi* | [**g_et_refund_parts**](docs/RefundsApi.md#g_et_refund_parts) | **GET** /v1/refunds/{refundKey}/parts | List all parts of a refund
*RefundsApi* | [**g_et_refunds**](docs/RefundsApi.md#g_et_refunds) | **GET** /v1/refunds | List refunds
*RefundsApi* | [**p_ut_cancel_refund**](docs/RefundsApi.md#p_ut_cancel_refund) | **PUT** /v1/refunds/{refundKey}/cancel | Cancel a refund
*RefundsApi* | [**p_ut_update_refund**](docs/RefundsApi.md#p_ut_update_refund) | **PUT** /v1/refunds/{refundId} | Update a refund
*SequenceSetsApi* | [**d_elete_sequence_set**](docs/SequenceSetsApi.md#d_elete_sequence_set) | **DELETE** /v1/sequence-sets/{id} | Delete a sequence set
*SequenceSetsApi* | [**g_et_sequence_set**](docs/SequenceSetsApi.md#g_et_sequence_set) | **GET** /v1/sequence-sets/{id} | Retrieve a sequence set
*SequenceSetsApi* | [**g_et_sequence_sets**](docs/SequenceSetsApi.md#g_et_sequence_sets) | **GET** /v1/sequence-sets | List sequence sets
*SequenceSetsApi* | [**p_ost_sequence_sets**](docs/SequenceSetsApi.md#p_ost_sequence_sets) | **POST** /v1/sequence-sets | Create sequence sets
*SequenceSetsApi* | [**p_ut_sequence_set**](docs/SequenceSetsApi.md#p_ut_sequence_set) | **PUT** /v1/sequence-sets/{id} | Update a sequence set
*SettingsApi* | [**g_et_list_all_settings**](docs/SettingsApi.md#g_et_list_all_settings) | **GET** /settings/listing | List all settings
*SettingsApi* | [**p_ost_process_settings_batch_request**](docs/SettingsApi.md#p_ost_process_settings_batch_request) | **POST** /settings/batch-requests | Submit settings requests
*SignUpApi* | [**p_ost_sign_up**](docs/SignUpApi.md#p_ost_sign_up) | **POST** /v1/sign-up | Sign up
*SubscriptionsApi* | [**g_et_subscriptions_by_account**](docs/SubscriptionsApi.md#g_et_subscriptions_by_account) | **GET** /v1/subscriptions/accounts/{account-key} | List subscriptions by account key
*SubscriptionsApi* | [**g_et_subscriptions_by_key**](docs/SubscriptionsApi.md#g_et_subscriptions_by_key) | **GET** /v1/subscriptions/{subscription-key} | Retrieve a subscription by key
*SubscriptionsApi* | [**g_et_subscriptions_by_key_and_version**](docs/SubscriptionsApi.md#g_et_subscriptions_by_key_and_version) | **GET** /v1/subscriptions/{subscription-key}/versions/{version} | Retrieve a subscription by key and version
*SubscriptionsApi* | [**p_ost_preview_subscription**](docs/SubscriptionsApi.md#p_ost_preview_subscription) | **POST** /v1/subscriptions/preview | Preview a subscription
*SubscriptionsApi* | [**p_ost_subscription**](docs/SubscriptionsApi.md#p_ost_subscription) | **POST** /v1/subscriptions | Create a subscription
*SubscriptionsApi* | [**p_ut_cancel_subscription**](docs/SubscriptionsApi.md#p_ut_cancel_subscription) | **PUT** /v1/subscriptions/{subscription-key}/cancel | Cancel a subscription
*SubscriptionsApi* | [**p_ut_delete_subscription**](docs/SubscriptionsApi.md#p_ut_delete_subscription) | **PUT** /v1/subscriptions/{subscription-key}/delete | Delete a subscription by number
*SubscriptionsApi* | [**p_ut_renew_subscription**](docs/SubscriptionsApi.md#p_ut_renew_subscription) | **PUT** /v1/subscriptions/{subscription-key}/renew | Renew a subscription
*SubscriptionsApi* | [**p_ut_resume_subscription**](docs/SubscriptionsApi.md#p_ut_resume_subscription) | **PUT** /v1/subscriptions/{subscription-key}/resume | Resume a subscription
*SubscriptionsApi* | [**p_ut_subscription**](docs/SubscriptionsApi.md#p_ut_subscription) | **PUT** /v1/subscriptions/{subscription-key} | Update a subscription
*SubscriptionsApi* | [**p_ut_suspend_subscription**](docs/SubscriptionsApi.md#p_ut_suspend_subscription) | **PUT** /v1/subscriptions/{subscription-key}/suspend | Suspend a subscription
*SubscriptionsApi* | [**p_ut_update_subscription_custom_fields_of_a_specified_version**](docs/SubscriptionsApi.md#p_ut_update_subscription_custom_fields_of_a_specified_version) | **PUT** /v1/subscriptions/{subscriptionNumber}/versions/{version}/customFields | Update subscription custom fields of a subscription version
*SummaryJournalEntriesApi* | [**d_elete_summary_journal_entry**](docs/SummaryJournalEntriesApi.md#d_elete_summary_journal_entry) | **DELETE** /v1/journal-entries/{je-number} | Delete a summary journal entry
*SummaryJournalEntriesApi* | [**g_et_all_summary_journal_entries**](docs/SummaryJournalEntriesApi.md#g_et_all_summary_journal_entries) | **GET** /v1/journal-entries/journal-runs/{jr-number} | List all summary journal entries in a journal run
*SummaryJournalEntriesApi* | [**g_et_summary_journal_entry**](docs/SummaryJournalEntriesApi.md#g_et_summary_journal_entry) | **GET** /v1/journal-entries/{je-number} | Retrieve a summary journal entry
*SummaryJournalEntriesApi* | [**p_ost_summary_journal_entry**](docs/SummaryJournalEntriesApi.md#p_ost_summary_journal_entry) | **POST** /v1/journal-entries | Create a summary journal entry
*SummaryJournalEntriesApi* | [**p_ut_basic_summary_journal_entry**](docs/SummaryJournalEntriesApi.md#p_ut_basic_summary_journal_entry) | **PUT** /v1/journal-entries/{je-number}/basic-information | Update a summary journal entry
*SummaryJournalEntriesApi* | [**p_ut_summary_journal_entry**](docs/SummaryJournalEntriesApi.md#p_ut_summary_journal_entry) | **PUT** /v1/journal-entries/{je-number}/cancel | Cancel a summary journal entry
*TaxationItemsApi* | [**d_elete_taxation_item**](docs/TaxationItemsApi.md#d_elete_taxation_item) | **DELETE** /v1/taxationitems/{id} | Delete a taxation item
*TaxationItemsApi* | [**g_et_taxation_item**](docs/TaxationItemsApi.md#g_et_taxation_item) | **GET** /v1/taxationitems/{id} | Retrieve a taxation item
*TaxationItemsApi* | [**object_post_taxation_item**](docs/TaxationItemsApi.md#object_post_taxation_item) | **POST** /v1/object/taxation-item | CRUD: Create a taxation item
*TaxationItemsApi* | [**p_ut_taxation_item**](docs/TaxationItemsApi.md#p_ut_taxation_item) | **PUT** /v1/taxationitems/{id} | Update a taxation item
*UsageApi* | [**g_et_usage**](docs/UsageApi.md#g_et_usage) | **GET** /v1/usage/accounts/{account-key} | Retrieve a usage record
*UsageApi* | [**g_et_usage_rate_detail_by_invoice_item**](docs/UsageApi.md#g_et_usage_rate_detail_by_invoice_item) | **GET** /v1/invoices/invoice-item/{invoice-item-id}/usage-rate-detail | Retrieve usage rate detail for an invoice item
*UsageApi* | [**object_delete_usage**](docs/UsageApi.md#object_delete_usage) | **DELETE** /v1/object/usage/{id} | CRUD: Delete a usage record
*UsageApi* | [**object_get_usage**](docs/UsageApi.md#object_get_usage) | **GET** /v1/object/usage/{id} | CRUD: Retrieve a usage record
*UsageApi* | [**object_post_usage**](docs/UsageApi.md#object_post_usage) | **POST** /v1/object/usage | CRUD: Create a usage record
*UsageApi* | [**object_put_usage**](docs/UsageApi.md#object_put_usage) | **PUT** /v1/object/usage/{id} | CRUD: Update a usage record
*UsageApi* | [**p_ost_usage**](docs/UsageApi.md#p_ost_usage) | **POST** /v1/usage | Upload a usage file
*WorkflowsApi* | [**d_elete_workflow**](docs/WorkflowsApi.md#d_elete_workflow) | **DELETE** /workflows/{workflow_id} | Delete a workflow
*WorkflowsApi* | [**d_elete_workflow_version**](docs/WorkflowsApi.md#d_elete_workflow_version) | **DELETE** /versions/{version_id} | Delete a workflow version
*WorkflowsApi* | [**g_et_workflow**](docs/WorkflowsApi.md#g_et_workflow) | **GET** /workflows/{workflow_id} | Retrieve a workflow
*WorkflowsApi* | [**g_et_workflow_export**](docs/WorkflowsApi.md#g_et_workflow_export) | **GET** /workflows/{workflow_id}/export | Export a workflow version
*WorkflowsApi* | [**g_et_workflow_run**](docs/WorkflowsApi.md#g_et_workflow_run) | **GET** /workflows/workflow_runs/{workflow_run_id} | Retrieve a workflow run
*WorkflowsApi* | [**g_et_workflow_versions**](docs/WorkflowsApi.md#g_et_workflow_versions) | **GET** /workflows/{workflow_id}/versions | List all versions of a workflow definition
*WorkflowsApi* | [**g_et_workflows**](docs/WorkflowsApi.md#g_et_workflows) | **GET** /workflows | List workflows
*WorkflowsApi* | [**g_et_workflows_task**](docs/WorkflowsApi.md#g_et_workflows_task) | **GET** /workflows/tasks/{task_id} | Retrieve a workflow task
*WorkflowsApi* | [**g_et_workflows_tasks**](docs/WorkflowsApi.md#g_et_workflows_tasks) | **GET** /workflows/tasks | List workflow tasks
*WorkflowsApi* | [**g_et_workflows_usages**](docs/WorkflowsApi.md#g_et_workflows_usages) | **GET** /workflows/metrics.json | Retrieve workflow task usage
*WorkflowsApi* | [**p_atch_update_workflow**](docs/WorkflowsApi.md#p_atch_update_workflow) | **PATCH** /workflows/{workflow_id} | Update a workflow
*WorkflowsApi* | [**p_ost_run_workflow**](docs/WorkflowsApi.md#p_ost_run_workflow) | **POST** /workflows/{workflow_id}/run | Run a workflow
*WorkflowsApi* | [**p_ost_workflow_import**](docs/WorkflowsApi.md#p_ost_workflow_import) | **POST** /workflows/import | Import a workflow
*WorkflowsApi* | [**p_ost_workflow_versions_import**](docs/WorkflowsApi.md#p_ost_workflow_versions_import) | **POST** /workflows/{workflow_id}/versions/import | Import a workflow version
*WorkflowsApi* | [**p_ost_workflows_task_rerun**](docs/WorkflowsApi.md#p_ost_workflows_task_rerun) | **POST** /workflows/tasks/{task_id}/rerun | Rerun a workflow task
*WorkflowsApi* | [**p_ut_workflows_tasks_update**](docs/WorkflowsApi.md#p_ut_workflows_tasks_update) | **PUT** /workflows/tasks/batch_update | Update workflow tasks
*ZuoraRevenueIntegrationApi* | [**p_ut_rev_pro_accounting_codes**](docs/ZuoraRevenueIntegrationApi.md#p_ut_rev_pro_accounting_codes) | **PUT** /v1/revpro-accounting-codes | Update a Zuora Revenue accounting code
## Documentation For Models
- [Account](docs/Account.md)
- [AccountCreditCardHolder](docs/AccountCreditCardHolder.md)
- [AccountData](docs/AccountData.md)
- [AccountObjectCustomFields](docs/AccountObjectCustomFields.md)
- [AccountObjectNSFields](docs/AccountObjectNSFields.md)
- [AccountingCodeObjectCustomFields](docs/AccountingCodeObjectCustomFields.md)
- [AccountingPeriodObjectCustomFields](docs/AccountingPeriodObjectCustomFields.md)
- [ActionsErrorResponse](docs/ActionsErrorResponse.md)
- [ApiVolumeSummaryRecord](docs/ApiVolumeSummaryRecord.md)
- [ApplyCreditMemoType](docs/ApplyCreditMemoType.md)
- [ApplyPaymentType](docs/ApplyPaymentType.md)
- [BadRequestResponse](docs/BadRequestResponse.md)
- [BadRequestResponseErrors](docs/BadRequestResponseErrors.md)
- [BatchDebitMemoType](docs/BatchDebitMemoType.md)
- [BatchInvoiceType](docs/BatchInvoiceType.md)
- [BatchQueries](docs/BatchQueries.md)
- [BatchQuery](docs/BatchQuery.md)
- [BatchesQueries](docs/BatchesQueries.md)
- [BatchesQueriesById](docs/BatchesQueriesById.md)
- [BillRunFilterRequestType](docs/BillRunFilterRequestType.md)
- [BillRunFilterResponseType](docs/BillRunFilterResponseType.md)
- [BillRunFilters](docs/BillRunFilters.md)
- [BillRunScheduleRequestType](docs/BillRunScheduleRequestType.md)
- [BillRunScheduleResponseType](docs/BillRunScheduleResponseType.md)
- [BillToContact](docs/BillToContact.md)
- [BillToContactPostOrder](docs/BillToContactPostOrder.md)
- [BillingDocVolumeSummaryRecord](docs/BillingDocVolumeSummaryRecord.md)
- [BillingDocumentQueryResponseElementType](docs/BillingDocumentQueryResponseElementType.md)
- [BillingOptions](docs/BillingOptions.md)
- [BillingPreviewResult](docs/BillingPreviewResult.md)
- [BillingUpdate](docs/BillingUpdate.md)
- [Body](docs/Body.md)
- [BodyInSettingValueReponse](docs/BodyInSettingValueReponse.md)
- [BodyInSettingValueRequest](docs/BodyInSettingValueRequest.md)
- [BulkCreditMemosResponseType](docs/BulkCreditMemosResponseType.md)
- [BulkDebitMemosResponseType](docs/BulkDebitMemosResponseType.md)
- [CalloutAuth](docs/CalloutAuth.md)
- [CalloutMergeFields](docs/CalloutMergeFields.md)
- [CancelBillRunResponseType](docs/CancelBillRunResponseType.md)
- [CancelSubscription](docs/CancelSubscription.md)
- [CatalogGroupResponse](docs/CatalogGroupResponse.md)
- [ChangePlan](docs/ChangePlan.md)
- [ChangePlanRatePlanOverride](docs/ChangePlanRatePlanOverride.md)
- [ChargeModelConfigurationType](docs/ChargeModelConfigurationType.md)
- [ChargeModelDataOverride](docs/ChargeModelDataOverride.md)
- [ChargeModelDataOverrideChargeModelConfiguration](docs/ChargeModelDataOverrideChargeModelConfiguration.md)
- [ChargeOverride](docs/ChargeOverride.md)
- [ChargeOverrideBilling](docs/ChargeOverrideBilling.md)
- [ChargeOverridePricing](docs/ChargeOverridePricing.md)
- [ChargePreviewMetrics](docs/ChargePreviewMetrics.md)
- [ChargePreviewMetricsCmrr](docs/ChargePreviewMetricsCmrr.md)
- [ChargePreviewMetricsTax](docs/ChargePreviewMetricsTax.md)
- [ChargePreviewMetricsTcb](docs/ChargePreviewMetricsTcb.md)
- [ChargePreviewMetricsTcv](docs/ChargePreviewMetricsTcv.md)
- [ChargeTier](docs/ChargeTier.md)
- [ChargeUpdate](docs/ChargeUpdate.md)
- [ChargeUpdatePricing](docs/ChargeUpdatePricing.md)
- [ChildrenSettingValueRequest](docs/ChildrenSettingValueRequest.md)
- [CommonErrorResponse](docs/CommonErrorResponse.md)
- [CommonResponseType](docs/CommonResponseType.md)
- [CommonResponseTypeReasons](docs/CommonResponseTypeReasons.md)
- [CompareSchemaInfoResponse](docs/CompareSchemaInfoResponse.md)
- [CompareSchemaKeyValue](docs/CompareSchemaKeyValue.md)
- [ConfigTemplateErrorResponse](docs/ConfigTemplateErrorResponse.md)
- [ConfigTemplateErrorResponseReasons](docs/ConfigTemplateErrorResponseReasons.md)
- [ConfigurationTemplateContent](docs/ConfigurationTemplateContent.md)
- [ContactInfo](docs/ContactInfo.md)
- [ContactObjectCustomFields](docs/ContactObjectCustomFields.md)
- [ContactResponse](docs/ContactResponse.md)
- [ContactSnapshotObjectCustomFields](docs/ContactSnapshotObjectCustomFields.md)
- [CreateChangePlan](docs/CreateChangePlan.md)
- [CreateOfferRatePlanOverride](docs/CreateOfferRatePlanOverride.md)
- [CreateOrUpdateEmailTemplatesResponse](docs/CreateOrUpdateEmailTemplatesResponse.md)
- [CreateOrderChangePlanRatePlanOverride](docs/CreateOrderChangePlanRatePlanOverride.md)
- [CreateOrderChargeOverride](docs/CreateOrderChargeOverride.md)
- [CreateOrderChargeOverrideBilling](docs/CreateOrderChargeOverrideBilling.md)
- [CreateOrderChargeOverridePricing](docs/CreateOrderChargeOverridePricing.md)
- [CreateOrderChargeUpdate](docs/CreateOrderChargeUpdate.md)
- [CreateOrderCreateSubscription](docs/CreateOrderCreateSubscription.md)
- [CreateOrderCreateSubscriptionNewSubscriptionOwnerAccount](docs/CreateOrderCreateSubscriptionNewSubscriptionOwnerAccount.md)
- [CreateOrderCreateSubscriptionTerms](docs/CreateOrderCreateSubscriptionTerms.md)
- [CreateOrderCreateSubscriptionTermsInitialTerm](docs/CreateOrderCreateSubscriptionTermsInitialTerm.md)
- [CreateOrderOfferUpdate](docs/CreateOrderOfferUpdate.md)
- [CreateOrderOrderAction](docs/CreateOrderOrderAction.md)
- [CreateOrderOrderActionAddProduct](docs/CreateOrderOrderActionAddProduct.md)
- [CreateOrderOrderActionUpdateProduct](docs/CreateOrderOrderActionUpdateProduct.md)
- [CreateOrderOrderLineItem](docs/CreateOrderOrderLineItem.md)
- [CreateOrderPricingUpdate](docs/CreateOrderPricingUpdate.md)
- [CreateOrderPricingUpdateChargeModelData](docs/CreateOrderPricingUpdateChargeModelData.md)
- [CreateOrderPricingUpdateDiscount](docs/CreateOrderPricingUpdateDiscount.md)
- [CreateOrderPricingUpdateRecurringDeliveryBased](docs/CreateOrderPricingUpdateRecurringDeliveryBased.md)
- [CreateOrderPricingUpdateRecurringFlatFee](docs/CreateOrderPricingUpdateRecurringFlatFee.md)
- [CreateOrderPricingUpdateRecurringPerUnit](docs/CreateOrderPricingUpdateRecurringPerUnit.md)
- [CreateOrderPricingUpdateRecurringTiered](docs/CreateOrderPricingUpdateRecurringTiered.md)
- [CreateOrderPricingUpdateRecurringVolume](docs/CreateOrderPricingUpdateRecurringVolume.md)
- [CreateOrderPricingUpdateUsageFlatFee](docs/CreateOrderPricingUpdateUsageFlatFee.md)
- [CreateOrderPricingUpdateUsageOverage](docs/CreateOrderPricingUpdateUsageOverage.md)
- [CreateOrderPricingUpdateUsagePerUnit](docs/CreateOrderPricingUpdateUsagePerUnit.md)
- [CreateOrderPricingUpdateUsageTiered](docs/CreateOrderPricingUpdateUsageTiered.md)
- [CreateOrderPricingUpdateUsageTieredWithOverage](docs/CreateOrderPricingUpdateUsageTieredWithOverage.md)
- [CreateOrderPricingUpdateUsageVolume](docs/CreateOrderPricingUpdateUsageVolume.md)
- [CreateOrderProductOverride](docs/CreateOrderProductOverride.md)
- [CreateOrderRatePlanFeatureOverride](docs/CreateOrderRatePlanFeatureOverride.md)
- [CreateOrderRatePlanOverride](docs/CreateOrderRatePlanOverride.md)
- [CreateOrderRatePlanUpdate](docs/CreateOrderRatePlanUpdate.md)
- [CreateOrderResume](docs/CreateOrderResume.md)
- [CreateOrderSuspend](docs/CreateOrderSuspend.md)
- [CreateOrderTermsAndConditions](docs/CreateOrderTermsAndConditions.md)
- [CreateOrderTriggerParams](docs/CreateOrderTriggerParams.md)
- [CreateOrderUpdateProductTriggerParams](docs/CreateOrderUpdateProductTriggerParams.md)
- [CreatePMPayPalECPayPalNativeECPayPalCP](docs/CreatePMPayPalECPayPalNativeECPayPalCP.md)
- [CreatePaymentMethodACH](docs/CreatePaymentMethodACH.md)
- [CreatePaymentMethodApplePayAdyen](docs/CreatePaymentMethodApplePayAdyen.md)
- [CreatePaymentMethodBankTransfer](docs/CreatePaymentMethodBankTransfer.md)
- [CreatePaymentMethodBankTransferAccountHolderInfo](docs/CreatePaymentMethodBankTransferAccountHolderInfo.md)
- [CreatePaymentMethodCCReferenceTransaction](docs/CreatePaymentMethodCCReferenceTransaction.md)
- [CreatePaymentMethodCardholderInfo](docs/CreatePaymentMethodCardholderInfo.md)
- [CreatePaymentMethodCommon](docs/CreatePaymentMethodCommon.md)
- [CreatePaymentMethodCreditCard](docs/CreatePaymentMethodCreditCard.md)
- [CreatePaymentMethodGooglePayAdyenChase](docs/CreatePaymentMethodGooglePayAdyenChase.md)
- [CreatePaymentMethodPayPalAdaptive](docs/CreatePaymentMethodPayPalAdaptive.md)
- [CreatePaymentType](docs/CreatePaymentType.md)
- [CreateStoredCredentialProfileRequest](docs/CreateStoredCredentialProfileRequest.md)
- [CreateSubscribeToProduct](docs/CreateSubscribeToProduct.md)
- [CreateSubscription](docs/CreateSubscription.md)
- [CreateSubscriptionNewSubscriptionOwnerAccount](docs/CreateSubscriptionNewSubscriptionOwnerAccount.md)
- [CreateSubscriptionTerms](docs/CreateSubscriptionTerms.md)
- [CreateTemplateRequestContent](docs/CreateTemplateRequestContent.md)
- [CreditCard](docs/CreditCard.md)
- [CreditMemoApplyDebitMemoItemRequestType](docs/CreditMemoApplyDebitMemoItemRequestType.md)
- [CreditMemoApplyDebitMemoRequestType](docs/CreditMemoApplyDebitMemoRequestType.md)
- [CreditMemoApplyInvoiceItemRequestType](docs/CreditMemoApplyInvoiceItemRequestType.md)
- [CreditMemoApplyInvoiceRequestType](docs/CreditMemoApplyInvoiceRequestType.md)
- [CreditMemoEntityPrefix](docs/CreditMemoEntityPrefix.md)
- [CreditMemoFromChargeCustomRatesType](docs/CreditMemoFromChargeCustomRatesType.md)
- [CreditMemoFromChargeDetailType](docs/CreditMemoFromChargeDetailType.md)
- [CreditMemoFromChargeType](docs/CreditMemoFromChargeType.md)
- [CreditMemoFromInvoiceType](docs/CreditMemoFromInvoiceType.md)
- [CreditMemoItemFromInvoiceItemType](docs/CreditMemoItemFromInvoiceItemType.md)
- [CreditMemoItemFromWriteOffInvoice](docs/CreditMemoItemFromWriteOffInvoice.md)
- [CreditMemoItemObjectCustomFields](docs/CreditMemoItemObjectCustomFields.md)
- [CreditMemoObjectCustomFields](docs/CreditMemoObjectCustomFields.md)
- [CreditMemoObjectNSFields](docs/CreditMemoObjectNSFields.md)
- [CreditMemoResponseType](docs/CreditMemoResponseType.md)
- [CreditMemoTaxItemFromInvoiceTaxItemType](docs/CreditMemoTaxItemFromInvoiceTaxItemType.md)
- [CreditMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation](docs/CreditMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation.md)
- [CreditMemoUnapplyDebitMemoItemRequestType](docs/CreditMemoUnapplyDebitMemoItemRequestType.md)
- [CreditMemoUnapplyDebitMemoRequestType](docs/CreditMemoUnapplyDebitMemoRequestType.md)
- [CreditMemoUnapplyInvoiceItemRequestType](docs/CreditMemoUnapplyInvoiceItemRequestType.md)
- [CreditMemoUnapplyInvoiceRequestType](docs/CreditMemoUnapplyInvoiceRequestType.md)
- [CreditMemosFromCharges](docs/CreditMemosFromCharges.md)
- [CreditMemosFromInvoices](docs/CreditMemosFromInvoices.md)
- [CreditTaxationItemObjectCustomFields](docs/CreditTaxationItemObjectCustomFields.md)
- [CustomAccountPaymentMethod](docs/CustomAccountPaymentMethod.md)
- [CustomFields](docs/CustomFields.md)
- [CustomObjectAllFieldsDefinition](docs/CustomObjectAllFieldsDefinition.md)
- [CustomObjectBulkDeleteFilter](docs/CustomObjectBulkDeleteFilter.md)
- [CustomObjectBulkDeleteFilterCondition](docs/CustomObjectBulkDeleteFilterCondition.md)
- [CustomObjectBulkJobErrorResponse](docs/CustomObjectBulkJobErrorResponse.md)
- [CustomObjectBulkJobErrorResponseCollection](docs/CustomObjectBulkJobErrorResponseCollection.md)
- [CustomObjectBulkJobRequest](docs/CustomObjectBulkJobRequest.md)
- [CustomObjectBulkJobResponse](docs/CustomObjectBulkJobResponse.md)
- [CustomObjectBulkJobResponseCollection](docs/CustomObjectBulkJobResponseCollection.md)
- [CustomObjectBulkJobResponseError](docs/CustomObjectBulkJobResponseError.md)
- [CustomObjectCustomFieldDefinition](docs/CustomObjectCustomFieldDefinition.md)
- [CustomObjectCustomFieldDefinitionUpdate](docs/CustomObjectCustomFieldDefinitionUpdate.md)
- [CustomObjectCustomFieldsDefinition](docs/CustomObjectCustomFieldsDefinition.md)
- [CustomObjectDefinition](docs/CustomObjectDefinition.md)
- [CustomObjectDefinitionSchema](docs/CustomObjectDefinitionSchema.md)
- [CustomObjectDefinitionUpdateActionRequest](docs/CustomObjectDefinitionUpdateActionRequest.md)
- [CustomObjectDefinitionUpdateActionResponse](docs/CustomObjectDefinitionUpdateActionResponse.md)
- [CustomObjectDefinitions](docs/CustomObjectDefinitions.md)
- [CustomObjectRecordBatchAction](docs/CustomObjectRecordBatchAction.md)
- [CustomObjectRecordBatchRequest](docs/CustomObjectRecordBatchRequest.md)
- [CustomObjectRecordBatchUpdateMapping](docs/CustomObjectRecordBatchUpdateMapping.md)
- [CustomObjectRecordWithAllFields](docs/CustomObjectRecordWithAllFields.md)
- [CustomObjectRecordWithOnlyCustomFields](docs/CustomObjectRecordWithOnlyCustomFields.md)
- [CustomObjectRecordsBatchUpdatePartialSuccessResponse](docs/CustomObjectRecordsBatchUpdatePartialSuccessResponse.md)
- [CustomObjectRecordsErrorResponse](docs/CustomObjectRecordsErrorResponse.md)
- [CustomObjectRecordsThrottledResponse](docs/CustomObjectRecordsThrottledResponse.md)
- [CustomObjectRecordsWithError](docs/CustomObjectRecordsWithError.md)
- [DataAccessControlField](docs/DataAccessControlField.md)
- [DataQueryErrorResponse](docs/DataQueryErrorResponse.md)
- [DataQueryJob](docs/DataQueryJob.md)
- [DataQueryJobCancelled](docs/DataQueryJobCancelled.md)
- [DataQueryJobCommon](docs/DataQueryJobCommon.md)
- [DebitMemoCollectRequest](docs/DebitMemoCollectRequest.md)
- [DebitMemoCollectRequestPayment](docs/DebitMemoCollectRequestPayment.md)
- [DebitMemoCollectResponse](docs/DebitMemoCollectResponse.md)
- [DebitMemoCollectResponseAppliedCreditMemos](docs/DebitMemoCollectResponseAppliedCreditMemos.md)
- [DebitMemoCollectResponseAppliedPayments](docs/DebitMemoCollectResponseAppliedPayments.md)
- [DebitMemoEntityPrefix](docs/DebitMemoEntityPrefix.md)
- [DebitMemoFromChargeCustomRatesType](docs/DebitMemoFromChargeCustomRatesType.md)
- [DebitMemoFromChargeDetailType](docs/DebitMemoFromChargeDetailType.md)
- [DebitMemoFromChargeType](docs/DebitMemoFromChargeType.md)
- [DebitMemoFromInvoiceType](docs/DebitMemoFromInvoiceType.md)
- [DebitMemoItemFromInvoiceItemType](docs/DebitMemoItemFromInvoiceItemType.md)
- [DebitMemoItemObjectCustomFields](docs/DebitMemoItemObjectCustomFields.md)
- [DebitMemoObjectCustomFields](docs/DebitMemoObjectCustomFields.md)
- [DebitMemoObjectCustomFieldsCMWriteOff](docs/DebitMemoObjectCustomFieldsCMWriteOff.md)
- [DebitMemoObjectNSFields](docs/DebitMemoObjectNSFields.md)
- [DebitMemoTaxItemFromInvoiceTaxItemType](docs/DebitMemoTaxItemFromInvoiceTaxItemType.md)
- [DebitMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation](docs/DebitMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation.md)
- [DebitMemosFromCharges](docs/DebitMemosFromCharges.md)
- [DebitMemosFromInvoices](docs/DebitMemosFromInvoices.md)
- [DebitTaxationItemObjectCustomFields](docs/DebitTaxationItemObjectCustomFields.md)
- [DeleteAccountResponseType](docs/DeleteAccountResponseType.md)
- [DeleteAccountResponseTypeReasons](docs/DeleteAccountResponseTypeReasons.md)
- [DeleteBatchQueryJobResponse](docs/DeleteBatchQueryJobResponse.md)
- [DeleteDataQueryJobResponse](docs/DeleteDataQueryJobResponse.md)
- [DeleteInvoiceResponseType](docs/DeleteInvoiceResponseType.md)
- [DeleteResult](docs/DeleteResult.md)
- [DeleteWorkflowError](docs/DeleteWorkflowError.md)
- [DeleteWorkflowSuccess](docs/DeleteWorkflowSuccess.md)
- [DeletedRecord](docs/DeletedRecord.md)
- [DeletedRecord1](docs/DeletedRecord1.md)
- [DeliveryScheduleParams](docs/DeliveryScheduleParams.md)
- [DetailedWorkflow](docs/DetailedWorkflow.md)
- [DiscountItemObjectCustomFields](docs/DiscountItemObjectCustomFields.md)
- [DiscountItemObjectNSFields](docs/DiscountItemObjectNSFields.md)
- [DiscountPricingOverride](docs/DiscountPricingOverride.md)
- [DiscountPricingUpdate](docs/DiscountPricingUpdate.md)
- [EndConditions](docs/EndConditions.md)
- [Error401](docs/Error401.md)
- [ErrorResponse](docs/ErrorResponse.md)
- [ErrorResponse401Record](docs/ErrorResponse401Record.md)
- [ErrorResponseReasons](docs/ErrorResponseReasons.md)
- [EventTrigger](docs/EventTrigger.md)
- [EventType](docs/EventType.md)
- [ExecuteInvoiceScheduleBillRunResponse](docs/ExecuteInvoiceScheduleBillRunResponse.md)
- [ExportWorkflowVersionResponse](docs/ExportWorkflowVersionResponse.md)
- [FieldsAdditionalProperties](docs/FieldsAdditionalProperties.md)
- [FieldsAdditionalPropertiesForPostDefinition](docs/FieldsAdditionalPropertiesForPostDefinition.md)
- [FilterRuleParameterDefinition](docs/FilterRuleParameterDefinition.md)
- [FilterRuleParameterDefinitions](docs/FilterRuleParameterDefinitions.md)
- [FilterRuleParameterValues](docs/FilterRuleParameterValues.md)
- [FulfillmentCommon](docs/FulfillmentCommon.md)
- [FulfillmentCustomFields](docs/FulfillmentCustomFields.md)
- [FulfillmentGet](docs/FulfillmentGet.md)
- [FulfillmentItemCommon](docs/FulfillmentItemCommon.md)
- [FulfillmentItemCustomFields](docs/FulfillmentItemCustomFields.md)
- [FulfillmentItemGet](docs/FulfillmentItemGet.md)
- [FulfillmentItemPost](docs/FulfillmentItemPost.md)
- [FulfillmentItemPostFromFulfillmentPost](docs/FulfillmentItemPostFromFulfillmentPost.md)
- [FulfillmentItemPut](docs/FulfillmentItemPut.md)
- [FulfillmentPost](docs/FulfillmentPost.md)
- [FulfillmentPut](docs/FulfillmentPut.md)
- [GETAPaymentGatwayResponse](docs/GETAPaymentGatwayResponse.md)
- [GETARPaymentType](docs/GETARPaymentType.md)
- [GETARPaymentTypeWithPaymentOption](docs/GETARPaymentTypeWithPaymentOption.md)
- [GETARPaymentTypewithSuccess](docs/GETARPaymentTypewithSuccess.md)
- [GETAccountPMAccountHolderInfo](docs/GETAccountPMAccountHolderInfo.md)
- [GETAccountPaymentMethodType](docs/GETAccountPaymentMethodType.md)
- [GETAccountSummaryInvoiceType](docs/GETAccountSummaryInvoiceType.md)
- [GETAccountSummaryPaymentInvoiceType](docs/GETAccountSummaryPaymentInvoiceType.md)
- [GETAccountSummaryPaymentType](docs/GETAccountSummaryPaymentType.md)
- [GETAccountSummarySubscriptionRatePlanType](docs/GETAccountSummarySubscriptionRatePlanType.md)
- [GETAccountSummarySubscriptionType](docs/GETAccountSummarySubscriptionType.md)
- [GETAccountSummaryType](docs/GETAccountSummaryType.md)
- [GETAccountSummaryTypeBasicInfo](docs/GETAccountSummaryTypeBasicInfo.md)
- [GETAccountSummaryTypeBillToContact](docs/GETAccountSummaryTypeBillToContact.md)
- [GETAccountSummaryTypeSoldToContact](docs/GETAccountSummaryTypeSoldToContact.md)
- [GETAccountSummaryTypeTaxInfo](docs/GETAccountSummaryTypeTaxInfo.md)
- [GETAccountSummaryUsageType](docs/GETAccountSummaryUsageType.md)
- [GETAccountType](docs/GETAccountType.md)
- [GETAccountTypeBasicInfo](docs/GETAccountTypeBasicInfo.md)
- [GETAccountTypeBillToContact](docs/GETAccountTypeBillToContact.md)
- [GETAccountTypeBillingAndPayment](docs/GETAccountTypeBillingAndPayment.md)
- [GETAccountTypeMetrics](docs/GETAccountTypeMetrics.md)
- [GETAccountTypeSoldToContact](docs/GETAccountTypeSoldToContact.md)
- [GETAccountingCodeItemType](docs/GETAccountingCodeItemType.md)
- [GETAccountingCodeItemWithoutSuccessType](docs/GETAccountingCodeItemWithoutSuccessType.md)
- [GETAccountingCodesType](docs/GETAccountingCodesType.md)
- [GETAccountingPeriodType](docs/GETAccountingPeriodType.md)
- [GETAccountingPeriodWithoutSuccessType](docs/GETAccountingPeriodWithoutSuccessType.md)
- [GETAccountingPeriodsType](docs/GETAccountingPeriodsType.md)
- [GETAdjustmentsBySubscriptionNumberResponseType](docs/GETAdjustmentsBySubscriptionNumberResponseType.md)
- [GETAdjustmentsResponseType](docs/GETAdjustmentsResponseType.md)
- [GETAllCustomObjectDefinitionsInNamespaceResponse](docs/GETAllCustomObjectDefinitionsInNamespaceResponse.md)
- [GETAttachmentResponseType](docs/GETAttachmentResponseType.md)
- [GETAttachmentResponseWithoutSuccessType](docs/GETAttachmentResponseWithoutSuccessType.md)
- [GETAttachmentsResponseType](docs/GETAttachmentsResponseType.md)
- [GETBillingDocumentFilesDeletionJobResponse](docs/GETBillingDocumentFilesDeletionJobResponse.md)
- [GETBillingDocumentsResponseType](docs/GETBillingDocumentsResponseType.md)
- [GETCMTaxItemType](docs/GETCMTaxItemType.md)
- [GETCMTaxItemTypeNew](docs/GETCMTaxItemTypeNew.md)
- [GETCalloutHistoryVOType](docs/GETCalloutHistoryVOType.md)
- [GETCalloutHistoryVOsType](docs/GETCalloutHistoryVOsType.md)
- [GETCancelAdjustmentResponseType](docs/GETCancelAdjustmentResponseType.md)
- [GETCatalogGroupProductRatePlanResponse](docs/GETCatalogGroupProductRatePlanResponse.md)
- [GETCatalogType](docs/GETCatalogType.md)
- [GETContactSnapshotResponse](docs/GETContactSnapshotResponse.md)
- [GETCreditMemoCollectionType](docs/GETCreditMemoCollectionType.md)
- [GETCreditMemoItemPartType](docs/GETCreditMemoItemPartType.md)
- [GETCreditMemoItemPartTypewithSuccess](docs/GETCreditMemoItemPartTypewithSuccess.md)
- [GETCreditMemoItemPartsCollectionType](docs/GETCreditMemoItemPartsCollectionType.md)
- [GETCreditMemoItemType](docs/GETCreditMemoItemType.md)
- [GETCreditMemoItemTypewithSuccess](docs/GETCreditMemoItemTypewithSuccess.md)
- [GETCreditMemoItemsListType](docs/GETCreditMemoItemsListType.md)
- [GETCreditMemoPartType](docs/GETCreditMemoPartType.md)
- [GETCreditMemoPartTypewithSuccess](docs/GETCreditMemoPartTypewithSuccess.md)
- [GETCreditMemoPartsCollectionType](docs/GETCreditMemoPartsCollectionType.md)
- [GETCreditMemoType](docs/GETCreditMemoType.md)
- [GETCreditMemoTypewithSuccess](docs/GETCreditMemoTypewithSuccess.md)
- [GETCustomExchangeRatesDataType](docs/GETCustomExchangeRatesDataType.md)
- [GETCustomExchangeRatesType](docs/GETCustomExchangeRatesType.md)
- [GETDMTaxItemType](docs/GETDMTaxItemType.md)
- [GETDMTaxItemTypeNew](docs/GETDMTaxItemTypeNew.md)
- [GETDebitMemoCollectionType](docs/GETDebitMemoCollectionType.md)
- [GETDebitMemoItemCollectionType](docs/GETDebitMemoItemCollectionType.md)
- [GETDebitMemoItemType](docs/GETDebitMemoItemType.md)
- [GETDebitMemoItemTypewithSuccess](docs/GETDebitMemoItemTypewithSuccess.md)
- [GETDebitMemoType](docs/GETDebitMemoType.md)
- [GETDebitMemoTypewithSuccess](docs/GETDebitMemoTypewithSuccess.md)
- [GETDeliveryScheduleType](docs/GETDeliveryScheduleType.md)
- [GETDiscountApplyDetailsType](docs/GETDiscountApplyDetailsType.md)
- [GETEmailHistoryVOType](docs/GETEmailHistoryVOType.md)
- [GETEmailHistoryVOsType](docs/GETEmailHistoryVOsType.md)
- [GETIntervalPriceTierType](docs/GETIntervalPriceTierType.md)
- [GETIntervalPriceType](docs/GETIntervalPriceType.md)
- [GETInvoiceFilesResponse](docs/GETInvoiceFilesResponse.md)
- [GETInvoiceItemsResponse](docs/GETInvoiceItemsResponse.md)
- [GETInvoiceTaxItemType](docs/GETInvoiceTaxItemType.md)
- [GETInvoiceTaxationItemsResponse](docs/GETInvoiceTaxationItemsResponse.md)
- [GETJournalEntriesInJournalRunType](docs/GETJournalEntriesInJournalRunType.md)
- [GETJournalEntryDetailType](docs/GETJournalEntryDetailType.md)
- [GETJournalEntryDetailTypeWithoutSuccess](docs/GETJournalEntryDetailTypeWithoutSuccess.md)
- [GETJournalEntryItemType](docs/GETJournalEntryItemType.md)
- [GETJournalEntrySegmentType](docs/GETJournalEntrySegmentType.md)
- [GETJournalRunTransactionType](docs/GETJournalRunTransactionType.md)
- [GETJournalRunType](docs/GETJournalRunType.md)
- [GETMassUpdateType](docs/GETMassUpdateType.md)
- [GETOfferChargeConfiguration](docs/GETOfferChargeConfiguration.md)
- [GETOfferIntervalPrice](docs/GETOfferIntervalPrice.md)
- [GETOfferPriceBookItem](docs/GETOfferPriceBookItem.md)
- [GETOfferProductRatePlanCharge](docs/GETOfferProductRatePlanCharge.md)
- [GETOfferResponse](docs/GETOfferResponse.md)
- [GETOfferTier](docs/GETOfferTier.md)
- [GETOpenPaymentMethodTypeRevisionResponse](docs/GETOpenPaymentMethodTypeRevisionResponse.md)
- [GETPMAccountHolderInfo](docs/GETPMAccountHolderInfo.md)
- [GETPaymentGatwaysResponse](docs/GETPaymentGatwaysResponse.md)
- [GETPaymentItemPartCollectionType](docs/GETPaymentItemPartCollectionType.md)
- [GETPaymentItemPartType](docs/GETPaymentItemPartType.md)
- [GETPaymentItemPartTypewithSuccess](docs/GETPaymentItemPartTypewithSuccess.md)
- [GETPaymentMethodResponse](docs/GETPaymentMethodResponse.md)
- [GETPaymentMethodResponseACH](docs/GETPaymentMethodResponseACH.md)
- [GETPaymentMethodResponseACHForAccount](docs/GETPaymentMethodResponseACHForAccount.md)
- [GETPaymentMethodResponseApplePay](docs/GETPaymentMethodResponseApplePay.md)
- [GETPaymentMethodResponseApplePayForAccount](docs/GETPaymentMethodResponseApplePayForAccount.md)
- [GETPaymentMethodResponseBankTransfer](docs/GETPaymentMethodResponseBankTransfer.md)
- [GETPaymentMethodResponseBankTransferForAccount](docs/GETPaymentMethodResponseBankTransferForAccount.md)
- [GETPaymentMethodResponseCreditCard](docs/GETPaymentMethodResponseCreditCard.md)
- [GETPaymentMethodResponseCreditCardForAccount](docs/GETPaymentMethodResponseCreditCardForAccount.md)
- [GETPaymentMethodResponseForAccount](docs/GETPaymentMethodResponseForAccount.md)
- [GETPaymentMethodResponseGooglePay](docs/GETPaymentMethodResponseGooglePay.md)
- [GETPaymentMethodResponseGooglePayForAccount](docs/GETPaymentMethodResponseGooglePayForAccount.md)
- [GETPaymentMethodResponsePayPal](docs/GETPaymentMethodResponsePayPal.md)
- [GETPaymentMethodResponsePayPalForAccount](docs/GETPaymentMethodResponsePayPalForAccount.md)
- [GETPaymentMethodUpdaterInstancesResponse](docs/GETPaymentMethodUpdaterInstancesResponse.md)
- [GETPaymentMethodUpdaterInstancesResponseUpdaters](docs/GETPaymentMethodUpdaterInstancesResponseUpdaters.md)
- [GETPaymentPartType](docs/GETPaymentPartType.md)
- [GETPaymentPartTypewithSuccess](docs/GETPaymentPartTypewithSuccess.md)
- [GETPaymentPartsCollectionType](docs/GETPaymentPartsCollectionType.md)
- [GETPaymentRunCollectionType](docs/GETPaymentRunCollectionType.md)
- [GETPaymentRunDataArrayResponse](docs/GETPaymentRunDataArrayResponse.md)
- [GETPaymentRunDataElementResponse](docs/GETPaymentRunDataElementResponse.md)
- [GETPaymentRunDataTransactionElementResponse](docs/GETPaymentRunDataTransactionElementResponse.md)
- [GETPaymentRunSummaryResponse](docs/GETPaymentRunSummaryResponse.md)
- [GETPaymentRunSummaryTotalValues](docs/GETPaymentRunSummaryTotalValues.md)
- [GETPaymentRunType](docs/GETPaymentRunType.md)
- [GETPaymentScheduleItemResponse](docs/GETPaymentScheduleItemResponse.md)
- [GETPaymentScheduleResponse](docs/GETPaymentScheduleResponse.md)
- [GETPaymentScheduleStatisticResponse](docs/GETPaymentScheduleStatisticResponse.md)
- [GETPaymentScheduleStatisticResponsePaymentScheduleItems](docs/GETPaymentScheduleStatisticResponsePaymentScheduleItems.md)
- [GETPaymentSchedulesResponse](docs/GETPaymentSchedulesResponse.md)
- [GETPriceBookItemIntervalPrice](docs/GETPriceBookItemIntervalPrice.md)
- [GETPriceBookItemResponse](docs/GETPriceBookItemResponse.md)
- [GETPriceBookItemTier](docs/GETPriceBookItemTier.md)
- [GETProductDiscountApplyDetailsType](docs/GETProductDiscountApplyDetailsType.md)
- [GETProductRatePlanChargeDeliverySchedule](docs/GETProductRatePlanChargeDeliverySchedule.md)
- [GETProductRatePlanChargePricingTierType](docs/GETProductRatePlanChargePricingTierType.md)
- [GETProductRatePlanChargePricingType](docs/GETProductRatePlanChargePricingType.md)
- [GETProductRatePlanChargeType](docs/GETProductRatePlanChargeType.md)
- [GETProductRatePlanType](docs/GETProductRatePlanType.md)
- [GETProductRatePlanWithExternalIdMultiResponse](docs/GETProductRatePlanWithExternalIdMultiResponse.md)
- [GETProductRatePlanWithExternalIdMultiResponseInner](docs/GETProductRatePlanWithExternalIdMultiResponseInner.md)
- [GETProductRatePlanWithExternalIdResponse](docs/GETProductRatePlanWithExternalIdResponse.md)
- [GETProductRatePlansResponse](docs/GETProductRatePlansResponse.md)
- [GETProductType](docs/GETProductType.md)
- [GETPublicEmailTemplateResponse](docs/GETPublicEmailTemplateResponse.md)
- [GETPublicNotificationDefinitionResponse](docs/GETPublicNotificationDefinitionResponse.md)
- [GETPublicNotificationDefinitionResponseCallout](docs/GETPublicNotificationDefinitionResponseCallout.md)
- [GETPublicNotificationDefinitionResponseFilterRule](docs/GETPublicNotificationDefinitionResponseFilterRule.md)
- [GETRampByRampNumberResponseType](docs/GETRampByRampNumberResponseType.md)
- [GETRampMetricsByOrderNumberResponseType](docs/GETRampMetricsByOrderNumberResponseType.md)
- [GETRampMetricsByRampNumberResponseType](docs/GETRampMetricsByRampNumberResponseType.md)
- [GETRampMetricsBySubscriptionKeyResponseType](docs/GETRampMetricsBySubscriptionKeyResponseType.md)
- [GETRampsBySubscriptionKeyResponseType](docs/GETRampsBySubscriptionKeyResponseType.md)
- [GETRefundCollectionType](docs/GETRefundCollectionType.md)
- [GETRefundCreditMemoType](docs/GETRefundCreditMemoType.md)
- [GETRefundItemPartCollectionType](docs/GETRefundItemPartCollectionType.md)
- [GETRefundItemPartType](docs/GETRefundItemPartType.md)
- [GETRefundItemPartTypewithSuccess](docs/GETRefundItemPartTypewithSuccess.md)
- [GETRefundPartCollectionType](docs/GETRefundPartCollectionType.md)
- [GETRefundPaymentType](docs/GETRefundPaymentType.md)
- [GETRefundType](docs/GETRefundType.md)
- [GETRefundTypewithSuccess](docs/GETRefundTypewithSuccess.md)
- [GETSequenceSetResponse](docs/GETSequenceSetResponse.md)
- [GETSequenceSetsResponse](docs/GETSequenceSetsResponse.md)
- [GETSubscriptionOfferType](docs/GETSubscriptionOfferType.md)
- [GETSubscriptionProductFeatureType](docs/GETSubscriptionProductFeatureType.md)
- [GETSubscriptionRatePlanChargesType](docs/GETSubscriptionRatePlanChargesType.md)
- [GETSubscriptionRatePlanType](docs/GETSubscriptionRatePlanType.md)
- [GETSubscriptionStatusHistoryType](docs/GETSubscriptionStatusHistoryType.md)
- [GETSubscriptionType](docs/GETSubscriptionType.md)
- [GETSubscriptionTypeWithSuccess](docs/GETSubscriptionTypeWithSuccess.md)
- [GETSubscriptionWrapper](docs/GETSubscriptionWrapper.md)
- [GETTaxationItemListType](docs/GETTaxationItemListType.md)
- [GETTaxationItemType](docs/GETTaxationItemType.md)
- [GETTaxationItemTypewithSuccess](docs/GETTaxationItemTypewithSuccess.md)
- [GETTaxationItemsOfCreditMemoItemType](docs/GETTaxationItemsOfCreditMemoItemType.md)
- [GETTaxationItemsOfDebitMemoItemType](docs/GETTaxationItemsOfDebitMemoItemType.md)
- [GETTierType](docs/GETTierType.md)
- [GETUsageRateDetailWrapper](docs/GETUsageRateDetailWrapper.md)
- [GETUsageRateDetailWrapperData](docs/GETUsageRateDetailWrapperData.md)
- [GETUsageType](docs/GETUsageType.md)
- [GETUsageWrapper](docs/GETUsageWrapper.md)
- [GenerateBillingDocumentResponseType](docs/GenerateBillingDocumentResponseType.md)
- [GetAggregateQueryJobResponse](docs/GetAggregateQueryJobResponse.md)
- [GetAllOrdersResponseType](docs/GetAllOrdersResponseType.md)
- [GetApiVolumeSummaryResponse](docs/GetApiVolumeSummaryResponse.md)
- [GetBillRunResponseType](docs/GetBillRunResponseType.md)
- [GetBillingDocVolumeSummaryResponse](docs/GetBillingDocVolumeSummaryResponse.md)
- [GetBillingPreviewRunResponse](docs/GetBillingPreviewRunResponse.md)
- [GetDataQueryJobResponse](docs/GetDataQueryJobResponse.md)
- [GetDataQueryJobsResponse](docs/GetDataQueryJobsResponse.md)
- [GetDebitMemoApplicationPartCollectionType](docs/GetDebitMemoApplicationPartCollectionType.md)
- [GetDebitMemoApplicationPartType](docs/GetDebitMemoApplicationPartType.md)
- [GetFulfillmentItemResponseType](docs/GetFulfillmentItemResponseType.md)
- [GetFulfillmentResponseType](docs/GetFulfillmentResponseType.md)
- [GetHostedPageType](docs/GetHostedPageType.md)
- [GetHostedPagesType](docs/GetHostedPagesType.md)
- [GetInvoiceApplicationPartCollectionType](docs/GetInvoiceApplicationPartCollectionType.md)
- [GetInvoiceApplicationPartType](docs/GetInvoiceApplicationPartType.md)
- [GetOfferRatePlanOverride](docs/GetOfferRatePlanOverride.md)
- [GetOfferRatePlanUpdate](docs/GetOfferRatePlanUpdate.md)
- [GetOperationJobResponseType](docs/GetOperationJobResponseType.md)
- [GetOrderActionRatePlanResponse](docs/GetOrderActionRatePlanResponse.md)
- [GetOrderLineItemResponseType](docs/GetOrderLineItemResponseType.md)
- [GetOrderResponse](docs/GetOrderResponse.md)
- [GetOrderResume](docs/GetOrderResume.md)
- [GetOrderSuspend](docs/GetOrderSuspend.md)
- [GetOrdersResponse](docs/GetOrdersResponse.md)
- [GetPaymentVolumeSummaryResponse](docs/GetPaymentVolumeSummaryResponse.md)
- [GetProductFeatureType](docs/GetProductFeatureType.md)
- [GetScheduledEventResponse](docs/GetScheduledEventResponse.md)
- [GetScheduledEventResponseParameters](docs/GetScheduledEventResponseParameters.md)
- [GetStoredCredentialProfilesResponse](docs/GetStoredCredentialProfilesResponse.md)
- [GetStoredCredentialProfilesResponseProfiles](docs/GetStoredCredentialProfilesResponseProfiles.md)
- [GetVersionsResponse](docs/GetVersionsResponse.md)
- [GetWorkflowResponse](docs/GetWorkflowResponse.md)
- [GetWorkflowResponseTasks](docs/GetWorkflowResponseTasks.md)
- [GetWorkflowsResponse](docs/GetWorkflowsResponse.md)
- [GetWorkflowsResponsePagination](docs/GetWorkflowsResponsePagination.md)
- [InitialTerm](docs/InitialTerm.md)
- [InlineResponse200](docs/InlineResponse200.md)
- [InlineResponse2001](docs/InlineResponse2001.md)
- [InlineResponse2002](docs/InlineResponse2002.md)
- [InlineResponse2003](docs/InlineResponse2003.md)
- [InlineResponse2004](docs/InlineResponse2004.md)
- [InlineResponse2005](docs/InlineResponse2005.md)
- [InlineResponse202](docs/InlineResponse202.md)
- [InlineResponse2021](docs/InlineResponse2021.md)
- [InlineResponse400](docs/InlineResponse400.md)
- [InlineResponse406](docs/InlineResponse406.md)
- [InvoiceEntityPrefix](docs/InvoiceEntityPrefix.md)
- [InvoiceFile](docs/InvoiceFile.md)
- [InvoiceItem](docs/InvoiceItem.md)
- [InvoiceItemObjectCustomFields](docs/InvoiceItemObjectCustomFields.md)
- [InvoiceItemObjectNSFields](docs/InvoiceItemObjectNSFields.md)
- [InvoiceItemPreviewResult](docs/InvoiceItemPreviewResult.md)
- [InvoiceItemPreviewResultAdditionalInfo](docs/InvoiceItemPreviewResultAdditionalInfo.md)
- [InvoiceItemPreviewResultTaxationItems](docs/InvoiceItemPreviewResultTaxationItems.md)
- [InvoiceObjectCustomFields](docs/InvoiceObjectCustomFields.md)
- [InvoiceObjectNSFields](docs/InvoiceObjectNSFields.md)
- [InvoicePostResponseType](docs/InvoicePostResponseType.md)
- [InvoicePostType](docs/InvoicePostType.md)
- [InvoiceResponseType](docs/InvoiceResponseType.md)
- [InvoiceScheduleCustomFields](docs/InvoiceScheduleCustomFields.md)
- [InvoiceScheduleItemCustomFields](docs/InvoiceScheduleItemCustomFields.md)
- [InvoiceScheduleResponses](docs/InvoiceScheduleResponses.md)
- [InvoiceScheduleSpecificSubscriptions](docs/InvoiceScheduleSpecificSubscriptions.md)
- [InvoiceWithCustomRatesType](docs/InvoiceWithCustomRatesType.md)
- [InvoicesBatchPostResponseType](docs/InvoicesBatchPostResponseType.md)
- [JobResult](docs/JobResult.md)
- [JobResultOrderLineItems](docs/JobResultOrderLineItems.md)
- [JobResultRamps](docs/JobResultRamps.md)
- [JobResultSubscriptions](docs/JobResultSubscriptions.md)
- [JournalEntryItemObjectCustomFields](docs/JournalEntryItemObjectCustomFields.md)
- [JournalEntryObjectCustomFields](docs/JournalEntryObjectCustomFields.md)
- [JsonNode](docs/JsonNode.md)
- [LastTerm](docs/LastTerm.md)
- [Linkage](docs/Linkage.md)
- [LinkedPaymentID](docs/LinkedPaymentID.md)
- [ListAllCatalogGroupsResponse](docs/ListAllCatalogGroupsResponse.md)
- [ListAllOffersResponse](docs/ListAllOffersResponse.md)
- [ListAllPriceBookItemsResponse](docs/ListAllPriceBookItemsResponse.md)
- [ListAllSettingsResponse](docs/ListAllSettingsResponse.md)
- [ListOfExchangeRates](docs/ListOfExchangeRates.md)
- [MigrationClientResponse](docs/MigrationClientResponse.md)
- [MigrationComponentContent](docs/MigrationComponentContent.md)
- [MigrationUpdateCustomObjectDefinitionsRequest](docs/MigrationUpdateCustomObjectDefinitionsRequest.md)
- [MigrationUpdateCustomObjectDefinitionsResponse](docs/MigrationUpdateCustomObjectDefinitionsResponse.md)
- [ModifiedStoredCredentialProfileResponse](docs/ModifiedStoredCredentialProfileResponse.md)
- [NextRunResponseType](docs/NextRunResponseType.md)
- [NotificationsHistoryDeletionTaskResponse](docs/NotificationsHistoryDeletionTaskResponse.md)
- [OfferOverride](docs/OfferOverride.md)
- [OfferUpdate](docs/OfferUpdate.md)
- [OneTimeFlatFeePricingOverride](docs/OneTimeFlatFeePricingOverride.md)
- [OneTimePerUnitPricingOverride](docs/OneTimePerUnitPricingOverride.md)
- [OneTimeTieredPricingOverride](docs/OneTimeTieredPricingOverride.md)
- [OneTimeVolumePricingOverride](docs/OneTimeVolumePricingOverride.md)
- [OpenPaymentMethodTypeRequestFields](docs/OpenPaymentMethodTypeRequestFields.md)
- [OpenPaymentMethodTypeResponseFields](docs/OpenPaymentMethodTypeResponseFields.md)
- [Options](docs/Options.md)
- [Order](docs/Order.md)
- [OrderAction](docs/OrderAction.md)
- [OrderActionAddProduct](docs/OrderActionAddProduct.md)
- [OrderActionCommon](docs/OrderActionCommon.md)
- [OrderActionCustomFields](docs/OrderActionCustomFields.md)
- [OrderActionObjectCustomFields](docs/OrderActionObjectCustomFields.md)
- [OrderActionPut](docs/OrderActionPut.md)
- [OrderActionRatePlanAmendment](docs/OrderActionRatePlanAmendment.md)
- [OrderActionRatePlanBillingUpdate](docs/OrderActionRatePlanBillingUpdate.md)
- [OrderActionRatePlanChargeModelDataOverride](docs/OrderActionRatePlanChargeModelDataOverride.md)
- [OrderActionRatePlanChargeModelDataOverrideChargeModelConfiguration](docs/OrderActionRatePlanChargeModelDataOverrideChargeModelConfiguration.md)
- [OrderActionRatePlanChargeOverride](docs/OrderActionRatePlanChargeOverride.md)
- [OrderActionRatePlanChargeOverridePricing](docs/OrderActionRatePlanChargeOverridePricing.md)
- [OrderActionRatePlanChargeTier](docs/OrderActionRatePlanChargeTier.md)
- [OrderActionRatePlanChargeUpdate](docs/OrderActionRatePlanChargeUpdate.md)
- [OrderActionRatePlanChargeUpdateBilling](docs/OrderActionRatePlanChargeUpdateBilling.md)
- [OrderActionRatePlanDiscountPricingOverride](docs/OrderActionRatePlanDiscountPricingOverride.md)
- [OrderActionRatePlanDiscountPricingUpdate](docs/OrderActionRatePlanDiscountPricingUpdate.md)
- [OrderActionRatePlanEndConditions](docs/OrderActionRatePlanEndConditions.md)
- [OrderActionRatePlanOneTimeFlatFeePricingOverride](docs/OrderActionRatePlanOneTimeFlatFeePricingOverride.md)
- [OrderActionRatePlanOneTimePerUnitPricingOverride](docs/OrderActionRatePlanOneTimePerUnitPricingOverride.md)
- [OrderActionRatePlanOneTimeTieredPricingOverride](docs/OrderActionRatePlanOneTimeTieredPricingOverride.md)
- [OrderActionRatePlanOneTimeVolumePricingOverride](docs/OrderActionRatePlanOneTimeVolumePricingOverride.md)
- [OrderActionRatePlanOrder](docs/OrderActionRatePlanOrder.md)
- [OrderActionRatePlanOrderAction](docs/OrderActionRatePlanOrderAction.md)
- [OrderActionRatePlanOrderActionObjectCustomFields](docs/OrderActionRatePlanOrderActionObjectCustomFields.md)
- [OrderActionRatePlanPriceChangeParams](docs/OrderActionRatePlanPriceChangeParams.md)
- [OrderActionRatePlanPricingUpdate](docs/OrderActionRatePlanPricingUpdate.md)
- [OrderActionRatePlanPricingUpdateChargeModelData](docs/OrderActionRatePlanPricingUpdateChargeModelData.md)
- [OrderActionRatePlanPricingUpdateRecurringDelivery](docs/OrderActionRatePlanPricingUpdateRecurringDelivery.md)
- [OrderActionRatePlanRatePlanChargeObjectCustomFields](docs/OrderActionRatePlanRatePlanChargeObjectCustomFields.md)
- [OrderActionRatePlanRatePlanObjectCustomFields](docs/OrderActionRatePlanRatePlanObjectCustomFields.md)
- [OrderActionRatePlanRatePlanOverride](docs/OrderActionRatePlanRatePlanOverride.md)
- [OrderActionRatePlanRatePlanUpdate](docs/OrderActionRatePlanRatePlanUpdate.md)
- [OrderActionRatePlanRecurringDeliveryPricingOverride](docs/OrderActionRatePlanRecurringDeliveryPricingOverride.md)
- [OrderActionRatePlanRecurringDeliveryPricingUpdate](docs/OrderActionRatePlanRecurringDeliveryPricingUpdate.md)
- [OrderActionRatePlanRecurringFlatFeePricingOverride](docs/OrderActionRatePlanRecurringFlatFeePricingOverride.md)
- [OrderActionRatePlanRecurringFlatFeePricingUpdate](docs/OrderActionRatePlanRecurringFlatFeePricingUpdate.md)
- [OrderActionRatePlanRecurringPerUnitPricingOverride](docs/OrderActionRatePlanRecurringPerUnitPricingOverride.md)
- [OrderActionRatePlanRecurringPerUnitPricingUpdate](docs/OrderActionRatePlanRecurringPerUnitPricingUpdate.md)
- [OrderActionRatePlanRecurringTieredPricingOverride](docs/OrderActionRatePlanRecurringTieredPricingOverride.md)
- [OrderActionRatePlanRecurringTieredPricingUpdate](docs/OrderActionRatePlanRecurringTieredPricingUpdate.md)
- [OrderActionRatePlanRecurringVolumePricingOverride](docs/OrderActionRatePlanRecurringVolumePricingOverride.md)
- [OrderActionRatePlanRecurringVolumePricingUpdate](docs/OrderActionRatePlanRecurringVolumePricingUpdate.md)
- [OrderActionRatePlanRemoveProduct](docs/OrderActionRatePlanRemoveProduct.md)
- [OrderActionRatePlanTriggerParams](docs/OrderActionRatePlanTriggerParams.md)
- [OrderActionRatePlanUsageFlatFeePricingOverride](docs/OrderActionRatePlanUsageFlatFeePricingOverride.md)
- [OrderActionRatePlanUsageFlatFeePricingUpdate](docs/OrderActionRatePlanUsageFlatFeePricingUpdate.md)
- [OrderActionRatePlanUsageOveragePricingOverride](docs/OrderActionRatePlanUsageOveragePricingOverride.md)
- [OrderActionRatePlanUsageOveragePricingUpdate](docs/OrderActionRatePlanUsageOveragePricingUpdate.md)
- [OrderActionRatePlanUsagePerUnitPricingOverride](docs/OrderActionRatePlanUsagePerUnitPricingOverride.md)
- [OrderActionRatePlanUsagePerUnitPricingUpdate](docs/OrderActionRatePlanUsagePerUnitPricingUpdate.md)
- [OrderActionRatePlanUsageTieredPricingOverride](docs/OrderActionRatePlanUsageTieredPricingOverride.md)
- [OrderActionRatePlanUsageTieredPricingUpdate](docs/OrderActionRatePlanUsageTieredPricingUpdate.md)
- [OrderActionRatePlanUsageTieredWithOveragePricingOverride](docs/OrderActionRatePlanUsageTieredWithOveragePricingOverride.md)
- [OrderActionRatePlanUsageTieredWithOveragePricingUpdate](docs/OrderActionRatePlanUsageTieredWithOveragePricingUpdate.md)
- [OrderActionRatePlanUsageVolumePricingOverride](docs/OrderActionRatePlanUsageVolumePricingOverride.md)
- [OrderActionRatePlanUsageVolumePricingUpdate](docs/OrderActionRatePlanUsageVolumePricingUpdate.md)
- [OrderActionUpdateProduct](docs/OrderActionUpdateProduct.md)
- [OrderDeltaMetric](docs/OrderDeltaMetric.md)
- [OrderDeltaMrr](docs/OrderDeltaMrr.md)
- [OrderDeltaTcb](docs/OrderDeltaTcb.md)
- [OrderDeltaTcv](docs/OrderDeltaTcv.md)
- [OrderItem](docs/OrderItem.md)
- [OrderLineItem](docs/OrderLineItem.md)
- [OrderLineItemCommon](docs/OrderLineItemCommon.md)
- [OrderLineItemCommonPostOrder](docs/OrderLineItemCommonPostOrder.md)
- [OrderLineItemCommonRetrieveOrder](docs/OrderLineItemCommonRetrieveOrder.md)
- [OrderLineItemCommonRetrieveOrderLineItem](docs/OrderLineItemCommonRetrieveOrderLineItem.md)
- [OrderLineItemCustomFields](docs/OrderLineItemCustomFields.md)
- [OrderLineItemCustomFieldsRetrieveOrderLineItem](docs/OrderLineItemCustomFieldsRetrieveOrderLineItem.md)
- [OrderLineItemRetrieveOrder](docs/OrderLineItemRetrieveOrder.md)
- [OrderMetric](docs/OrderMetric.md)
- [OrderObjectCustomFields](docs/OrderObjectCustomFields.md)
- [OrderRampIntervalMetrics](docs/OrderRampIntervalMetrics.md)
- [OrderRampMetrics](docs/OrderRampMetrics.md)
- [OrderSchedulingOptions](docs/OrderSchedulingOptions.md)
- [OrderSubscriptions](docs/OrderSubscriptions.md)
- [OrdersRatePlanObjectCustomFields](docs/OrdersRatePlanObjectCustomFields.md)
- [OwnerTransfer](docs/OwnerTransfer.md)
- [POSTAccountPMMandateInfo](docs/POSTAccountPMMandateInfo.md)
- [POSTAccountResponseType](docs/POSTAccountResponseType.md)
- [POSTAccountType](docs/POSTAccountType.md)
- [POSTAccountTypeBillToContact](docs/POSTAccountTypeBillToContact.md)
- [POSTAccountTypeCreditCard](docs/POSTAccountTypeCreditCard.md)
- [POSTAccountTypePaymentMethod](docs/POSTAccountTypePaymentMethod.md)
- [POSTAccountTypeSoldToContact](docs/POSTAccountTypeSoldToContact.md)
- [POSTAccountTypeSubscription](docs/POSTAccountTypeSubscription.md)
- [POSTAccountingCodeResponseType](docs/POSTAccountingCodeResponseType.md)
- [POSTAccountingCodeType](docs/POSTAccountingCodeType.md)
- [POSTAccountingPeriodResponseType](docs/POSTAccountingPeriodResponseType.md)
- [POSTAccountingPeriodType](docs/POSTAccountingPeriodType.md)
- [POSTAddItemsToPaymentScheduleRequest](docs/POSTAddItemsToPaymentScheduleRequest.md)
- [POSTAdjustmentResponseType](docs/POSTAdjustmentResponseType.md)
- [POSTAttachmentResponseType](docs/POSTAttachmentResponseType.md)
- [POSTAuthorizeResponse](docs/POSTAuthorizeResponse.md)
- [POSTAuthorizeResponsePaymentGatewayResponse](docs/POSTAuthorizeResponsePaymentGatewayResponse.md)
- [POSTAuthorizeResponseReasons](docs/POSTAuthorizeResponseReasons.md)
- [POSTBillingDocumentFilesDeletionJobRequest](docs/POSTBillingDocumentFilesDeletionJobRequest.md)
- [POSTBillingDocumentFilesDeletionJobResponse](docs/POSTBillingDocumentFilesDeletionJobResponse.md)
- [POSTBillingPreviewCreditMemoItem](docs/POSTBillingPreviewCreditMemoItem.md)
- [POSTBillingPreviewInvoiceItem](docs/POSTBillingPreviewInvoiceItem.md)
- [POSTBulkCreditMemoFromInvoiceType](docs/POSTBulkCreditMemoFromInvoiceType.md)
- [POSTBulkCreditMemosRequestType](docs/POSTBulkCreditMemosRequestType.md)
- [POSTBulkDebitMemoFromInvoiceType](docs/POSTBulkDebitMemoFromInvoiceType.md)
- [POSTBulkDebitMemosRequestType](docs/POSTBulkDebitMemosRequestType.md)
- [POSTCatalogGroupRequest](docs/POSTCatalogGroupRequest.md)
- [POSTContactType](docs/POSTContactType.md)
- [POSTCreateBillRunRequestType](docs/POSTCreateBillRunRequestType.md)
- [POSTCreateBillingAdjustmentRequestType](docs/POSTCreateBillingAdjustmentRequestType.md)
- [POSTCreateBillingAdjustmentRequestTypeExclusion](docs/POSTCreateBillingAdjustmentRequestTypeExclusion.md)
- [POSTCreateInvoiceScheduleRequest](docs/POSTCreateInvoiceScheduleRequest.md)
- [POSTCreateOpenPaymentMethodTypeRequest](docs/POSTCreateOpenPaymentMethodTypeRequest.md)
- [POSTCreateOpenPaymentMethodTypeResponse](docs/POSTCreateOpenPaymentMethodTypeResponse.md)
- [POSTCreateOrUpdateEmailTemplateRequest](docs/POSTCreateOrUpdateEmailTemplateRequest.md)
- [POSTCreateOrUpdateEmailTemplateRequestFormat](docs/POSTCreateOrUpdateEmailTemplateRequestFormat.md)
- [POSTCreatePaymentSessionRequest](docs/POSTCreatePaymentSessionRequest.md)
- [POSTCreatePaymentSessionResponse](docs/POSTCreatePaymentSessionResponse.md)
- [POSTDecryptResponseType](docs/POSTDecryptResponseType.md)
- [POSTDecryptionType](docs/POSTDecryptionType.md)
- [POSTDelayAuthorizeCapture](docs/POSTDelayAuthorizeCapture.md)
- [POSTDelayAuthorizeCaptureGatewayOptions](docs/POSTDelayAuthorizeCaptureGatewayOptions.md)
- [POSTEmailBillingDocfromBillRunType](docs/POSTEmailBillingDocfromBillRunType.md)
- [POSTExecuteInvoiceScheduleRequest](docs/POSTExecuteInvoiceScheduleRequest.md)
- [POSTIneligibleAdjustmentResponseType](docs/POSTIneligibleAdjustmentResponseType.md)
- [POSTInvoiceCollectCreditMemosType](docs/POSTInvoiceCollectCreditMemosType.md)
- [POSTInvoiceCollectInvoicesType](docs/POSTInvoiceCollectInvoicesType.md)
- [POSTInvoiceCollectResponseType](docs/POSTInvoiceCollectResponseType.md)
- [POSTInvoiceCollectType](docs/POSTInvoiceCollectType.md)
- [POSTInvoicesBatchPostType](docs/POSTInvoicesBatchPostType.md)
- [POSTJournalEntryItemType](docs/POSTJournalEntryItemType.md)
- [POSTJournalEntryResponseType](docs/POSTJournalEntryResponseType.md)
- [POSTJournalEntrySegmentType](docs/POSTJournalEntrySegmentType.md)
- [POSTJournalEntryType](docs/POSTJournalEntryType.md)
- [POSTJournalRunResponseType](docs/POSTJournalRunResponseType.md)
- [POSTJournalRunTransactionType](docs/POSTJournalRunTransactionType.md)
- [POSTJournalRunType](docs/POSTJournalRunType.md)
- [POSTMassUpdateResponseType](docs/POSTMassUpdateResponseType.md)
- [POSTMemoPdfResponse](docs/POSTMemoPdfResponse.md)
- [POSTOfferChargeConfiguration](docs/POSTOfferChargeConfiguration.md)
- [POSTOfferChargeOverride](docs/POSTOfferChargeOverride.md)
- [POSTOfferIntervalPrice](docs/POSTOfferIntervalPrice.md)
- [POSTOfferPriceBookItem](docs/POSTOfferPriceBookItem.md)
- [POSTOfferProductRatePlan](docs/POSTOfferProductRatePlan.md)
- [POSTOfferRequest](docs/POSTOfferRequest.md)
- [POSTOfferResponse](docs/POSTOfferResponse.md)
- [POSTOfferTier](docs/POSTOfferTier.md)
- [POSTOrderAsyncRequestType](docs/POSTOrderAsyncRequestType.md)
- [POSTOrderAsyncRequestTypeSubscriptions](docs/POSTOrderAsyncRequestTypeSubscriptions.md)
- [POSTOrderPreviewAsyncRequestType](docs/POSTOrderPreviewAsyncRequestType.md)
- [POSTOrderPreviewAsyncRequestTypeSubscriptions](docs/POSTOrderPreviewAsyncRequestTypeSubscriptions.md)
- [POSTOrderPreviewRequestType](docs/POSTOrderPreviewRequestType.md)
- [POSTOrderRequestType](docs/POSTOrderRequestType.md)
- [POSTOrderRequestTypeSchedulingOptions](docs/POSTOrderRequestTypeSchedulingOptions.md)
- [POSTPMMandateInfo](docs/POSTPMMandateInfo.md)
- [POSTPaymentMethodDecryption](docs/POSTPaymentMethodDecryption.md)
- [POSTPaymentMethodRequest](docs/POSTPaymentMethodRequest.md)
- [POSTPaymentMethodResponse](docs/POSTPaymentMethodResponse.md)
- [POSTPaymentMethodResponseDecryption](docs/POSTPaymentMethodResponseDecryption.md)
- [POSTPaymentMethodResponseReasons](docs/POSTPaymentMethodResponseReasons.md)
- [POSTPaymentMethodUpdaterBatchRequest](docs/POSTPaymentMethodUpdaterBatchRequest.md)
- [POSTPaymentMethodUpdaterResponse](docs/POSTPaymentMethodUpdaterResponse.md)
- [POSTPaymentMethodUpdaterResponseReasons](docs/POSTPaymentMethodUpdaterResponseReasons.md)
- [POSTPaymentRunDataElementRequest](docs/POSTPaymentRunDataElementRequest.md)
- [POSTPaymentRunRequest](docs/POSTPaymentRunRequest.md)
- [POSTPaymentScheduleRequest](docs/POSTPaymentScheduleRequest.md)
- [POSTPaymentScheduleResponse](docs/POSTPaymentScheduleResponse.md)
- [POSTPaymentSchedulesEach](docs/POSTPaymentSchedulesEach.md)
- [POSTPaymentSchedulesRequest](docs/POSTPaymentSchedulesRequest.md)
- [POSTPaymentSchedulesResponse](docs/POSTPaymentSchedulesResponse.md)
- [POSTPreviewBillingAdjustmentRequestType](docs/POSTPreviewBillingAdjustmentRequestType.md)
- [POSTPriceBookItemIntervalPrice](docs/POSTPriceBookItemIntervalPrice.md)
- [POSTPriceBookItemRequest](docs/POSTPriceBookItemRequest.md)
- [POSTPriceBookItemTier](docs/POSTPriceBookItemTier.md)
- [POSTPublicEmailTemplateRequest](docs/POSTPublicEmailTemplateRequest.md)
- [POSTPublicNotificationDefinitionRequest](docs/POSTPublicNotificationDefinitionRequest.md)
- [POSTPublicNotificationDefinitionRequestCallout](docs/POSTPublicNotificationDefinitionRequestCallout.md)
- [POSTPublicNotificationDefinitionRequestFilterRule](docs/POSTPublicNotificationDefinitionRequestFilterRule.md)
- [POSTRSASignatureResponseType](docs/POSTRSASignatureResponseType.md)
- [POSTRSASignatureType](docs/POSTRSASignatureType.md)
- [POSTReconcileRefundRequest](docs/POSTReconcileRefundRequest.md)
- [POSTReconcileRefundResponse](docs/POSTReconcileRefundResponse.md)
- [POSTReconcileRefundResponseFinanceInformation](docs/POSTReconcileRefundResponseFinanceInformation.md)
- [POSTRejectPaymentRequest](docs/POSTRejectPaymentRequest.md)
- [POSTRejectPaymentResponse](docs/POSTRejectPaymentResponse.md)
- [POSTResendCalloutNotifications](docs/POSTResendCalloutNotifications.md)
- [POSTResendEmailNotifications](docs/POSTResendEmailNotifications.md)
- [POSTRetryPaymentScheduleItemInfo](docs/POSTRetryPaymentScheduleItemInfo.md)
- [POSTRetryPaymentScheduleItemRequest](docs/POSTRetryPaymentScheduleItemRequest.md)
- [POSTRetryPaymentScheduleItemResponse](docs/POSTRetryPaymentScheduleItemResponse.md)
- [POSTReversePaymentRequest](docs/POSTReversePaymentRequest.md)
- [POSTReversePaymentResponse](docs/POSTReversePaymentResponse.md)
- [POSTScCreateType](docs/POSTScCreateType.md)
- [POSTScheduleItemType](docs/POSTScheduleItemType.md)
- [POSTSequenceSetRequest](docs/POSTSequenceSetRequest.md)
- [POSTSequenceSetsRequest](docs/POSTSequenceSetsRequest.md)
- [POSTSequenceSetsResponse](docs/POSTSequenceSetsResponse.md)
- [POSTSettlePaymentRequest](docs/POSTSettlePaymentRequest.md)
- [POSTSettlePaymentResponse](docs/POSTSettlePaymentResponse.md)
- [POSTSrpCreateType](docs/POSTSrpCreateType.md)
- [POSTSubscriptionCancellationResponseType](docs/POSTSubscriptionCancellationResponseType.md)
- [POSTSubscriptionCancellationType](docs/POSTSubscriptionCancellationType.md)
- [POSTSubscriptionPreviewCreditMemoItemsType](docs/POSTSubscriptionPreviewCreditMemoItemsType.md)
- [POSTSubscriptionPreviewInvoiceItemsType](docs/POSTSubscriptionPreviewInvoiceItemsType.md)
- [POSTSubscriptionPreviewResponseType](docs/POSTSubscriptionPreviewResponseType.md)
- [POSTSubscriptionPreviewResponseTypeChargeMetrics](docs/POSTSubscriptionPreviewResponseTypeChargeMetrics.md)
- [POSTSubscriptionPreviewResponseTypeCreditMemo](docs/POSTSubscriptionPreviewResponseTypeCreditMemo.md)
- [POSTSubscriptionPreviewResponseTypeInvoice](docs/POSTSubscriptionPreviewResponseTypeInvoice.md)
- [POSTSubscriptionPreviewTaxationItemsType](docs/POSTSubscriptionPreviewTaxationItemsType.md)
- [POSTSubscriptionPreviewType](docs/POSTSubscriptionPreviewType.md)
- [POSTSubscriptionPreviewTypePreviewAccountInfo](docs/POSTSubscriptionPreviewTypePreviewAccountInfo.md)
- [POSTSubscriptionResponseType](docs/POSTSubscriptionResponseType.md)
- [POSTSubscriptionType](docs/POSTSubscriptionType.md)
- [POSTTaxationItemForCMType](docs/POSTTaxationItemForCMType.md)
- [POSTTaxationItemForDMType](docs/POSTTaxationItemForDMType.md)
- [POSTTaxationItemList](docs/POSTTaxationItemList.md)
- [POSTTaxationItemListForCMType](docs/POSTTaxationItemListForCMType.md)
- [POSTTaxationItemListForDMType](docs/POSTTaxationItemListForDMType.md)
- [POSTTaxationItemTypeForInvoice](docs/POSTTaxationItemTypeForInvoice.md)
- [POSTTierType](docs/POSTTierType.md)
- [POSTUploadFileResponse](docs/POSTUploadFileResponse.md)
- [POSTUsageResponseType](docs/POSTUsageResponseType.md)
- [POSTVoidAuthorize](docs/POSTVoidAuthorize.md)
- [POSTVoidAuthorizeResponse](docs/POSTVoidAuthorizeResponse.md)
- [POSTWorkflowDefinitionImportRequest](docs/POSTWorkflowDefinitionImportRequest.md)
- [POSTorPUTCatalogGroupAddProductRatePlan](docs/POSTorPUTCatalogGroupAddProductRatePlan.md)
- [PUTAccountType](docs/PUTAccountType.md)
- [PUTAccountTypeBillToContact](docs/PUTAccountTypeBillToContact.md)
- [PUTAccountTypeSoldToContact](docs/PUTAccountTypeSoldToContact.md)
- [PUTAccountingCodeType](docs/PUTAccountingCodeType.md)
- [PUTAccountingPeriodType](docs/PUTAccountingPeriodType.md)
- [PUTAttachmentType](docs/PUTAttachmentType.md)
- [PUTBasicSummaryJournalEntryType](docs/PUTBasicSummaryJournalEntryType.md)
- [PUTBatchDebitMemosRequest](docs/PUTBatchDebitMemosRequest.md)
- [PUTBulkCreditMemosRequestType](docs/PUTBulkCreditMemosRequestType.md)
- [PUTBulkDebitMemosRequestType](docs/PUTBulkDebitMemosRequestType.md)
- [PUTCancelPaymentScheduleRequest](docs/PUTCancelPaymentScheduleRequest.md)
- [PUTCatalogGroup](docs/PUTCatalogGroup.md)
- [PUTCatalogGroupRemoveProductRatePlan](docs/PUTCatalogGroupRemoveProductRatePlan.md)
- [PUTContactType](docs/PUTContactType.md)
- [PUTCreditMemoItemType](docs/PUTCreditMemoItemType.md)
- [PUTCreditMemoType](docs/PUTCreditMemoType.md)
- [PUTCreditMemoWriteOff](docs/PUTCreditMemoWriteOff.md)
- [PUTCreditMemoWriteOffResponseType](docs/PUTCreditMemoWriteOffResponseType.md)
- [PUTCreditMemoWriteOffResponseTypeDebitMemo](docs/PUTCreditMemoWriteOffResponseTypeDebitMemo.md)
- [PUTCreditMemosWithIdType](docs/PUTCreditMemosWithIdType.md)
- [PUTDebitMemoItemType](docs/PUTDebitMemoItemType.md)
- [PUTDebitMemoType](docs/PUTDebitMemoType.md)
- [PUTDebitMemoWithIdType](docs/PUTDebitMemoWithIdType.md)
- [PUTDeleteSubscriptionResponseType](docs/PUTDeleteSubscriptionResponseType.md)
- [PUTJournalEntryItemType](docs/PUTJournalEntryItemType.md)
- [PUTOrderActionTriggerDatesRequestType](docs/PUTOrderActionTriggerDatesRequestType.md)
- [PUTOrderActionTriggerDatesRequestTypeCharges](docs/PUTOrderActionTriggerDatesRequestTypeCharges.md)
- [PUTOrderActionTriggerDatesRequestTypeOrderActions](docs/PUTOrderActionTriggerDatesRequestTypeOrderActions.md)
- [PUTOrderActionTriggerDatesRequestTypeSubscriptions](docs/PUTOrderActionTriggerDatesRequestTypeSubscriptions.md)
- [PUTOrderActionTriggerDatesRequestTypeTriggerDates](docs/PUTOrderActionTriggerDatesRequestTypeTriggerDates.md)
- [PUTOrderActionsRequestType](docs/PUTOrderActionsRequestType.md)
- [PUTOrderLineItemRequestType](docs/PUTOrderLineItemRequestType.md)
- [PUTOrderPatchRequestType](docs/PUTOrderPatchRequestType.md)
- [PUTOrderPatchRequestTypeOrderActions](docs/PUTOrderPatchRequestTypeOrderActions.md)
- [PUTOrderPatchRequestTypeSubscriptions](docs/PUTOrderPatchRequestTypeSubscriptions.md)
- [PUTOrderRequestType](docs/PUTOrderRequestType.md)
- [PUTOrderTriggerDatesResponseType](docs/PUTOrderTriggerDatesResponseType.md)
- [PUTOrderTriggerDatesResponseTypeSubscriptions](docs/PUTOrderTriggerDatesResponseTypeSubscriptions.md)
- [PUTPMAccountHolderInfo](docs/PUTPMAccountHolderInfo.md)
- [PUTPMCreditCardInfo](docs/PUTPMCreditCardInfo.md)
- [PUTPaymentMethodObjectCustomFields](docs/PUTPaymentMethodObjectCustomFields.md)
- [PUTPaymentMethodRequest](docs/PUTPaymentMethodRequest.md)
- [PUTPaymentMethodResponse](docs/PUTPaymentMethodResponse.md)
- [PUTPaymentRunRequest](docs/PUTPaymentRunRequest.md)
- [PUTPaymentScheduleItemRequest](docs/PUTPaymentScheduleItemRequest.md)
- [PUTPaymentScheduleItemResponse](docs/PUTPaymentScheduleItemResponse.md)
- [PUTPaymentScheduleRequest](docs/PUTPaymentScheduleRequest.md)
- [PUTPreviewPaymentScheduleRequest](docs/PUTPreviewPaymentScheduleRequest.md)
- [PUTPriceBookItemRequest](docs/PUTPriceBookItemRequest.md)
- [PUTPublicEmailTemplateRequest](docs/PUTPublicEmailTemplateRequest.md)
- [PUTPublicNotificationDefinitionRequest](docs/PUTPublicNotificationDefinitionRequest.md)
- [PUTPublicNotificationDefinitionRequestCallout](docs/PUTPublicNotificationDefinitionRequestCallout.md)
- [PUTPublicNotificationDefinitionRequestFilterRule](docs/PUTPublicNotificationDefinitionRequestFilterRule.md)
- [PUTPublishOpenPaymentMethodTypeResponse](docs/PUTPublishOpenPaymentMethodTypeResponse.md)
- [PUTRefundType](docs/PUTRefundType.md)
- [PUTRenewSubscriptionResponseType](docs/PUTRenewSubscriptionResponseType.md)
- [PUTRenewSubscriptionType](docs/PUTRenewSubscriptionType.md)
- [PUTRevproAccCodeResponse](docs/PUTRevproAccCodeResponse.md)
- [PUTScAddType](docs/PUTScAddType.md)
- [PUTScUpdateType](docs/PUTScUpdateType.md)
- [PUTSequenceSetRequest](docs/PUTSequenceSetRequest.md)
- [PUTSequenceSetResponse](docs/PUTSequenceSetResponse.md)
- [PUTSkipPaymentScheduleItemResponse](docs/PUTSkipPaymentScheduleItemResponse.md)
- [PUTSrpAddType](docs/PUTSrpAddType.md)
- [PUTSrpChangeType](docs/PUTSrpChangeType.md)
- [PUTSrpRemoveType](docs/PUTSrpRemoveType.md)
- [PUTSrpUpdateType](docs/PUTSrpUpdateType.md)
- [PUTSubscriptionPatchRequestType](docs/PUTSubscriptionPatchRequestType.md)
- [PUTSubscriptionPatchRequestTypeCharges](docs/PUTSubscriptionPatchRequestTypeCharges.md)
- [PUTSubscriptionPatchRequestTypeRatePlans](docs/PUTSubscriptionPatchRequestTypeRatePlans.md)
- [PUTSubscriptionPatchSpecificVersionRequestType](docs/PUTSubscriptionPatchSpecificVersionRequestType.md)
- [PUTSubscriptionPatchSpecificVersionRequestTypeCharges](docs/PUTSubscriptionPatchSpecificVersionRequestTypeCharges.md)
- [PUTSubscriptionPatchSpecificVersionRequestTypeRatePlans](docs/PUTSubscriptionPatchSpecificVersionRequestTypeRatePlans.md)
- [PUTSubscriptionPreviewInvoiceItemsType](docs/PUTSubscriptionPreviewInvoiceItemsType.md)
- [PUTSubscriptionResponseType](docs/PUTSubscriptionResponseType.md)
- [PUTSubscriptionResponseTypeChargeMetrics](docs/PUTSubscriptionResponseTypeChargeMetrics.md)
- [PUTSubscriptionResponseTypeCreditMemo](docs/PUTSubscriptionResponseTypeCreditMemo.md)
- [PUTSubscriptionResponseTypeInvoice](docs/PUTSubscriptionResponseTypeInvoice.md)
- [PUTSubscriptionResumeResponseType](docs/PUTSubscriptionResumeResponseType.md)
- [PUTSubscriptionResumeType](docs/PUTSubscriptionResumeType.md)
- [PUTSubscriptionSuspendResponseType](docs/PUTSubscriptionSuspendResponseType.md)
- [PUTSubscriptionSuspendType](docs/PUTSubscriptionSuspendType.md)
- [PUTSubscriptionType](docs/PUTSubscriptionType.md)
- [PUTTaxationItemType](docs/PUTTaxationItemType.md)
- [PUTUpdateInvoiceScheduleRequest](docs/PUTUpdateInvoiceScheduleRequest.md)
- [PUTUpdateOpenPaymentMethodTypeRequest](docs/PUTUpdateOpenPaymentMethodTypeRequest.md)
- [PUTUpdateOpenPaymentMethodTypeResponse](docs/PUTUpdateOpenPaymentMethodTypeResponse.md)
- [PUTVerifyPaymentMethodResponseType](docs/PUTVerifyPaymentMethodResponseType.md)
- [PUTVerifyPaymentMethodType](docs/PUTVerifyPaymentMethodType.md)
- [PUTWriteOffInvoiceRequest](docs/PUTWriteOffInvoiceRequest.md)
- [PUTWriteOffInvoiceResponse](docs/PUTWriteOffInvoiceResponse.md)
- [PUTWriteOffInvoiceResponseCreditMemo](docs/PUTWriteOffInvoiceResponseCreditMemo.md)
- [PaymentCollectionResponseType](docs/PaymentCollectionResponseType.md)
- [PaymentData](docs/PaymentData.md)
- [PaymentDebitMemoApplicationApplyRequestType](docs/PaymentDebitMemoApplicationApplyRequestType.md)
- [PaymentDebitMemoApplicationCreateRequestType](docs/PaymentDebitMemoApplicationCreateRequestType.md)
- [PaymentDebitMemoApplicationItemApplyRequestType](docs/PaymentDebitMemoApplicationItemApplyRequestType.md)
- [PaymentDebitMemoApplicationItemCreateRequestType](docs/PaymentDebitMemoApplicationItemCreateRequestType.md)
- [PaymentDebitMemoApplicationItemUnapplyRequestType](docs/PaymentDebitMemoApplicationItemUnapplyRequestType.md)
- [PaymentDebitMemoApplicationUnapplyRequestType](docs/PaymentDebitMemoApplicationUnapplyRequestType.md)
- [PaymentEntityPrefix](docs/PaymentEntityPrefix.md)
- [PaymentInvoiceApplicationApplyRequestType](docs/PaymentInvoiceApplicationApplyRequestType.md)
- [PaymentInvoiceApplicationCreateRequestType](docs/PaymentInvoiceApplicationCreateRequestType.md)
- [PaymentInvoiceApplicationItemApplyRequestType](docs/PaymentInvoiceApplicationItemApplyRequestType.md)
- [PaymentInvoiceApplicationItemCreateRequestType](docs/PaymentInvoiceApplicationItemCreateRequestType.md)
- [PaymentInvoiceApplicationItemUnapplyRequestType](docs/PaymentInvoiceApplicationItemUnapplyRequestType.md)
- [PaymentInvoiceApplicationUnapplyRequestType](docs/PaymentInvoiceApplicationUnapplyRequestType.md)
- [PaymentMethodObjectCustomFields](docs/PaymentMethodObjectCustomFields.md)
- [PaymentMethodObjectCustomFieldsForAccount](docs/PaymentMethodObjectCustomFieldsForAccount.md)
- [PaymentObjectCustomFields](docs/PaymentObjectCustomFields.md)
- [PaymentObjectNSFields](docs/PaymentObjectNSFields.md)
- [PaymentRunStatistic](docs/PaymentRunStatistic.md)
- [PaymentScheduleCommonResponse](docs/PaymentScheduleCommonResponse.md)
- [PaymentScheduleCustomFields](docs/PaymentScheduleCustomFields.md)
- [PaymentScheduleItemCommon](docs/PaymentScheduleItemCommon.md)
- [PaymentScheduleItemCommonResponse](docs/PaymentScheduleItemCommonResponse.md)
- [PaymentScheduleItemCustomFields](docs/PaymentScheduleItemCustomFields.md)
- [PaymentSchedulePaymentOptionFields](docs/PaymentSchedulePaymentOptionFields.md)
- [PaymentSchedulePaymentOptionFieldsDetail](docs/PaymentSchedulePaymentOptionFieldsDetail.md)
- [PaymentVolumeSummaryRecord](docs/PaymentVolumeSummaryRecord.md)
- [PaymentWithCustomRatesType](docs/PaymentWithCustomRatesType.md)
- [PostBatchInvoiceItemResponse](docs/PostBatchInvoiceItemResponse.md)
- [PostBatchInvoiceResponse](docs/PostBatchInvoiceResponse.md)
- [PostBatchInvoicesType](docs/PostBatchInvoicesType.md)
- [PostBillingPreviewParam](docs/PostBillingPreviewParam.md)
- [PostBillingPreviewRunParam](docs/PostBillingPreviewRunParam.md)
- [PostCreditMemoEmailRequestType](docs/PostCreditMemoEmailRequestType.md)
- [PostCustomObjectDefinitionFieldDefinitionRequest](docs/PostCustomObjectDefinitionFieldDefinitionRequest.md)
- [PostCustomObjectDefinitionFieldsDefinitionRequest](docs/PostCustomObjectDefinitionFieldsDefinitionRequest.md)
- [PostCustomObjectDefinitionsRequest](docs/PostCustomObjectDefinitionsRequest.md)
- [PostCustomObjectDefinitionsRequestDefinition](docs/PostCustomObjectDefinitionsRequestDefinition.md)
- [PostCustomObjectDefinitionsRequestDefinitions](docs/PostCustomObjectDefinitionsRequestDefinitions.md)
- [PostCustomObjectRecordsRequest](docs/PostCustomObjectRecordsRequest.md)
- [PostCustomObjectRecordsResponse](docs/PostCustomObjectRecordsResponse.md)
- [PostDebitMemoEmailType](docs/PostDebitMemoEmailType.md)
- [PostDiscountItemType](docs/PostDiscountItemType.md)
- [PostEventTriggerRequest](docs/PostEventTriggerRequest.md)
- [PostFulfillmentItemsRequestType](docs/PostFulfillmentItemsRequestType.md)
- [PostFulfillmentItemsResponseType](docs/PostFulfillmentItemsResponseType.md)
- [PostFulfillmentItemsResponseTypeFulfillmentItems](docs/PostFulfillmentItemsResponseTypeFulfillmentItems.md)
- [PostFulfillmentsRequestType](docs/PostFulfillmentsRequestType.md)
- [PostFulfillmentsResponseType](docs/PostFulfillmentsResponseType.md)
- [PostFulfillmentsResponseTypeFulfillments](docs/PostFulfillmentsResponseTypeFulfillments.md)
- [PostGenerateBillingDocumentType](docs/PostGenerateBillingDocumentType.md)
- [PostInvoiceEmailRequestType](docs/PostInvoiceEmailRequestType.md)
- [PostInvoiceItemType](docs/PostInvoiceItemType.md)
- [PostInvoiceResponse](docs/PostInvoiceResponse.md)
- [PostInvoiceType](docs/PostInvoiceType.md)
- [PostNonRefRefundType](docs/PostNonRefRefundType.md)
- [PostOrderAccountPaymentMethod](docs/PostOrderAccountPaymentMethod.md)
- [PostOrderLineItemUpdateType](docs/PostOrderLineItemUpdateType.md)
- [PostOrderLineItemsRequestType](docs/PostOrderLineItemsRequestType.md)
- [PostOrderPreviewResponseType](docs/PostOrderPreviewResponseType.md)
- [PostOrderResponseType](docs/PostOrderResponseType.md)
- [PostOrderResponseTypeRefunds](docs/PostOrderResponseTypeRefunds.md)
- [PostOrderResponseTypeSubscriptions](docs/PostOrderResponseTypeSubscriptions.md)
- [PostOrderResponseTypeWriteOff](docs/PostOrderResponseTypeWriteOff.md)
- [PostRefundType](docs/PostRefundType.md)
- [PostRefundwithAutoUnapplyType](docs/PostRefundwithAutoUnapplyType.md)
- [PostScheduledEventRequest](docs/PostScheduledEventRequest.md)
- [PostScheduledEventRequestParameters](docs/PostScheduledEventRequestParameters.md)
- [PostTaxationItemType](docs/PostTaxationItemType.md)
- [PreviewAccountInfo](docs/PreviewAccountInfo.md)
- [PreviewContactInfo](docs/PreviewContactInfo.md)
- [PreviewOptions](docs/PreviewOptions.md)
- [PreviewOrderChargeOverride](docs/PreviewOrderChargeOverride.md)
- [PreviewOrderChargeUpdate](docs/PreviewOrderChargeUpdate.md)
- [PreviewOrderCreateSubscription](docs/PreviewOrderCreateSubscription.md)
- [PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount](docs/PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount.md)
- [PreviewOrderOrderAction](docs/PreviewOrderOrderAction.md)
- [PreviewOrderPricingUpdate](docs/PreviewOrderPricingUpdate.md)
- [PreviewOrderRatePlanOverride](docs/PreviewOrderRatePlanOverride.md)
- [PreviewOrderRatePlanUpdate](docs/PreviewOrderRatePlanUpdate.md)
- [PreviewOrderTriggerParams](docs/PreviewOrderTriggerParams.md)
- [PreviewResult](docs/PreviewResult.md)
- [PreviewResultChargeMetrics](docs/PreviewResultChargeMetrics.md)
- [PreviewResultCreditMemos](docs/PreviewResultCreditMemos.md)
- [PreviewResultInvoices](docs/PreviewResultInvoices.md)
- [PreviewResultOrderActions](docs/PreviewResultOrderActions.md)
- [PreviewResultOrderDeltaMetrics](docs/PreviewResultOrderDeltaMetrics.md)
- [PreviewResultOrderMetrics](docs/PreviewResultOrderMetrics.md)
- [PriceChangeParams](docs/PriceChangeParams.md)
- [PriceIntervalWithPrice](docs/PriceIntervalWithPrice.md)
- [PriceIntervalWithTiers](docs/PriceIntervalWithTiers.md)
- [PricingUpdate](docs/PricingUpdate.md)
- [PricingUpdateRecurringDelivery](docs/PricingUpdateRecurringDelivery.md)
- [ProcessingOptions](docs/ProcessingOptions.md)
- [ProcessingOptionsOrders](docs/ProcessingOptionsOrders.md)
- [ProcessingOptionsOrdersAsync](docs/ProcessingOptionsOrdersAsync.md)
- [ProcessingOptionsOrdersBillingOptions](docs/ProcessingOptionsOrdersBillingOptions.md)
- [ProcessingOptionsOrdersElectronicPaymentOptions](docs/ProcessingOptionsOrdersElectronicPaymentOptions.md)
- [ProcessingOptionsOrdersWriteOffBehavior](docs/ProcessingOptionsOrdersWriteOffBehavior.md)
- [ProcessingOptionsOrdersWriteOffBehaviorFinanceInformation](docs/ProcessingOptionsOrdersWriteOffBehaviorFinanceInformation.md)
- [ProductFeatureObjectCustomFields](docs/ProductFeatureObjectCustomFields.md)
- [ProductObjectCustomFields](docs/ProductObjectCustomFields.md)
- [ProductObjectNSFields](docs/ProductObjectNSFields.md)
- [ProductRatePlanChargeObjectCustomFields](docs/ProductRatePlanChargeObjectCustomFields.md)
- [ProductRatePlanChargeObjectNSFields](docs/ProductRatePlanChargeObjectNSFields.md)
- [ProductRatePlanObjectCustomFields](docs/ProductRatePlanObjectCustomFields.md)
- [ProductRatePlanObjectNSFields](docs/ProductRatePlanObjectNSFields.md)
- [ProxyActioncreateRequest](docs/ProxyActioncreateRequest.md)
- [ProxyActiondeleteRequest](docs/ProxyActiondeleteRequest.md)
- [ProxyActionqueryMoreRequest](docs/ProxyActionqueryMoreRequest.md)
- [ProxyActionqueryMoreRequestConf](docs/ProxyActionqueryMoreRequestConf.md)
- [ProxyActionqueryMoreResponse](docs/ProxyActionqueryMoreResponse.md)
- [ProxyActionqueryRequest](docs/ProxyActionqueryRequest.md)
- [ProxyActionqueryResponse](docs/ProxyActionqueryResponse.md)
- [ProxyActionupdateRequest](docs/ProxyActionupdateRequest.md)
- [ProxyBadRequestResponse](docs/ProxyBadRequestResponse.md)
- [ProxyBadRequestResponseErrors](docs/ProxyBadRequestResponseErrors.md)
- [ProxyCreateOrModifyDeliverySchedule](docs/ProxyCreateOrModifyDeliverySchedule.md)
- [ProxyCreateOrModifyProductRatePlanChargeChargeModelConfiguration](docs/ProxyCreateOrModifyProductRatePlanChargeChargeModelConfiguration.md)
- [ProxyCreateOrModifyProductRatePlanChargeChargeModelConfigurationItem](docs/ProxyCreateOrModifyProductRatePlanChargeChargeModelConfigurationItem.md)
- [ProxyCreateOrModifyProductRatePlanChargeTierData](docs/ProxyCreateOrModifyProductRatePlanChargeTierData.md)
- [ProxyCreateOrModifyProductRatePlanChargeTierDataProductRatePlanChargeTier](docs/ProxyCreateOrModifyProductRatePlanChargeTierDataProductRatePlanChargeTier.md)
- [ProxyCreateOrModifyResponse](docs/ProxyCreateOrModifyResponse.md)
- [ProxyCreateProduct](docs/ProxyCreateProduct.md)
- [ProxyCreateProductRatePlan](docs/ProxyCreateProductRatePlan.md)
- [ProxyCreateProductRatePlanCharge](docs/ProxyCreateProductRatePlanCharge.md)
- [ProxyCreateTaxationItem](docs/ProxyCreateTaxationItem.md)
- [ProxyCreateUsage](docs/ProxyCreateUsage.md)
- [ProxyDeleteResponse](docs/ProxyDeleteResponse.md)
- [ProxyGetImport](docs/ProxyGetImport.md)
- [ProxyGetPaymentMethodSnapshot](docs/ProxyGetPaymentMethodSnapshot.md)
- [ProxyGetPaymentMethodTransactionLog](docs/ProxyGetPaymentMethodTransactionLog.md)
- [ProxyGetPaymentTransactionLog](docs/ProxyGetPaymentTransactionLog.md)
- [ProxyGetProduct](docs/ProxyGetProduct.md)
- [ProxyGetProductRatePlan](docs/ProxyGetProductRatePlan.md)
- [ProxyGetProductRatePlanCharge](docs/ProxyGetProductRatePlanCharge.md)
- [ProxyGetProductRatePlanChargeTier](docs/ProxyGetProductRatePlanChargeTier.md)
- [ProxyGetUsage](docs/ProxyGetUsage.md)
- [ProxyModifyProduct](docs/ProxyModifyProduct.md)
- [ProxyModifyProductRatePlan](docs/ProxyModifyProductRatePlan.md)
- [ProxyModifyProductRatePlanCharge](docs/ProxyModifyProductRatePlanCharge.md)
- [ProxyModifyProductRatePlanChargeTier](docs/ProxyModifyProductRatePlanChargeTier.md)
- [ProxyModifyUsage](docs/ProxyModifyUsage.md)
- [ProxyNoDataResponse](docs/ProxyNoDataResponse.md)
- [ProxyPostImport](docs/ProxyPostImport.md)
- [ProxyUnauthorizedResponse](docs/ProxyUnauthorizedResponse.md)
- [PutBatchInvoiceType](docs/PutBatchInvoiceType.md)
- [PutCreditMemoTaxItemType](docs/PutCreditMemoTaxItemType.md)
- [PutDebitMemoTaxItemType](docs/PutDebitMemoTaxItemType.md)
- [PutDiscountItemType](docs/PutDiscountItemType.md)
- [PutEventTriggerRequest](docs/PutEventTriggerRequest.md)
- [PutEventTriggerRequestEventType](docs/PutEventTriggerRequestEventType.md)
- [PutFulfillmentItemRequestType](docs/PutFulfillmentItemRequestType.md)
- [PutFulfillmentRequestType](docs/PutFulfillmentRequestType.md)
- [PutInvoiceItemType](docs/PutInvoiceItemType.md)
- [PutInvoiceResponseType](docs/PutInvoiceResponseType.md)
- [PutInvoiceType](docs/PutInvoiceType.md)
- [PutOrderCancelResponse](docs/PutOrderCancelResponse.md)
- [PutOrderLineItemResponseType](docs/PutOrderLineItemResponseType.md)
- [PutOrderLineItemUpdateType](docs/PutOrderLineItemUpdateType.md)
- [PutReverseCreditMemoResponseType](docs/PutReverseCreditMemoResponseType.md)
- [PutReverseCreditMemoResponseTypeCreditMemo](docs/PutReverseCreditMemoResponseTypeCreditMemo.md)
- [PutReverseCreditMemoResponseTypeDebitMemo](docs/PutReverseCreditMemoResponseTypeDebitMemo.md)
- [PutReverseCreditMemoType](docs/PutReverseCreditMemoType.md)
- [PutReverseInvoiceResponseType](docs/PutReverseInvoiceResponseType.md)
- [PutReverseInvoiceResponseTypeCreditMemo](docs/PutReverseInvoiceResponseTypeCreditMemo.md)
- [PutReverseInvoiceResponseTypeDebitMemo](docs/PutReverseInvoiceResponseTypeDebitMemo.md)
- [PutReverseInvoiceType](docs/PutReverseInvoiceType.md)
- [PutScheduledEventRequest](docs/PutScheduledEventRequest.md)
- [PutTasksRequest](docs/PutTasksRequest.md)
- [QueryCustomObjectRecordsResponse](docs/QueryCustomObjectRecordsResponse.md)
- [QuoteObjectFields](docs/QuoteObjectFields.md)
- [RampChargeRequest](docs/RampChargeRequest.md)
- [RampChargeResponse](docs/RampChargeResponse.md)
- [RampIntervalChargeDeltaMetrics](docs/RampIntervalChargeDeltaMetrics.md)
- [RampIntervalChargeDeltaMetricsDeltaMrr](docs/RampIntervalChargeDeltaMetricsDeltaMrr.md)
- [RampIntervalChargeDeltaMetricsDeltaQuantity](docs/RampIntervalChargeDeltaMetricsDeltaQuantity.md)
- [RampIntervalChargeMetrics](docs/RampIntervalChargeMetrics.md)
- [RampIntervalChargeMetricsMrr](docs/RampIntervalChargeMetricsMrr.md)
- [RampIntervalMetrics](docs/RampIntervalMetrics.md)
- [RampIntervalRequest](docs/RampIntervalRequest.md)
- [RampIntervalResponse](docs/RampIntervalResponse.md)
- [RampMetrics](docs/RampMetrics.md)
- [RampRequest](docs/RampRequest.md)
- [RampResponse](docs/RampResponse.md)
- [RatePlan](docs/RatePlan.md)
- [RatePlanChargeObjectCustomFields](docs/RatePlanChargeObjectCustomFields.md)
- [RatePlanFeatureOverride](docs/RatePlanFeatureOverride.md)
- [RatePlanFeatureOverrideCustomFields](docs/RatePlanFeatureOverrideCustomFields.md)
- [RatePlanObjectCustomFields](docs/RatePlanObjectCustomFields.md)
- [RatePlanOverride](docs/RatePlanOverride.md)
- [RatePlanUpdate](docs/RatePlanUpdate.md)
- [RatePlans](docs/RatePlans.md)
- [RecurringDeliveryPricingOverride](docs/RecurringDeliveryPricingOverride.md)
- [RecurringDeliveryPricingUpdate](docs/RecurringDeliveryPricingUpdate.md)
- [RecurringFlatFeePricingOverride](docs/RecurringFlatFeePricingOverride.md)
- [RecurringFlatFeePricingUpdate](docs/RecurringFlatFeePricingUpdate.md)
- [RecurringPerUnitPricingOverride](docs/RecurringPerUnitPricingOverride.md)
- [RecurringPerUnitPricingUpdate](docs/RecurringPerUnitPricingUpdate.md)
- [RecurringTieredPricingOverride](docs/RecurringTieredPricingOverride.md)
- [RecurringTieredPricingUpdate](docs/RecurringTieredPricingUpdate.md)
- [RecurringVolumePricingOverride](docs/RecurringVolumePricingOverride.md)
- [RecurringVolumePricingUpdate](docs/RecurringVolumePricingUpdate.md)
- [RefundCreditMemoItemType](docs/RefundCreditMemoItemType.md)
- [RefundEntityPrefix](docs/RefundEntityPrefix.md)
- [RefundObjectCustomFields](docs/RefundObjectCustomFields.md)
- [RefundObjectNSFields](docs/RefundObjectNSFields.md)
- [RefundPartResponseType](docs/RefundPartResponseType.md)
- [RefundPartResponseTypewithSuccess](docs/RefundPartResponseTypewithSuccess.md)
- [RemoveProduct](docs/RemoveProduct.md)
- [RenewSubscription](docs/RenewSubscription.md)
- [RenewalTerm](docs/RenewalTerm.md)
- [Request](docs/Request.md)
- [Request1](docs/Request1.md)
- [ResendCalloutNotificationsFailedResponse](docs/ResendCalloutNotificationsFailedResponse.md)
- [ResendEmailNotificationsFailedResponse](docs/ResendEmailNotificationsFailedResponse.md)
- [RevproAccountingCodes](docs/RevproAccountingCodes.md)
- [SaveResult](docs/SaveResult.md)
- [ScheduleItemsResponse](docs/ScheduleItemsResponse.md)
- [SettingComponentKeyValue](docs/SettingComponentKeyValue.md)
- [SettingItemHttpOperation](docs/SettingItemHttpOperation.md)
- [SettingItemHttpRequestParameter](docs/SettingItemHttpRequestParameter.md)
- [SettingItemWithOperationsInformation](docs/SettingItemWithOperationsInformation.md)
- [SettingSourceComponentResponse](docs/SettingSourceComponentResponse.md)
- [SettingValueRequest](docs/SettingValueRequest.md)
- [SettingValueResponse](docs/SettingValueResponse.md)
- [SettingValueResponseWrapper](docs/SettingValueResponseWrapper.md)
- [SettingsBatchRequest](docs/SettingsBatchRequest.md)
- [SettingsBatchResponse](docs/SettingsBatchResponse.md)
- [SignUpCreatePMPayPalECPayPalNativeEC](docs/SignUpCreatePMPayPalECPayPalNativeEC.md)
- [SignUpCreatePaymentMethodCardholderInfo](docs/SignUpCreatePaymentMethodCardholderInfo.md)
- [SignUpCreatePaymentMethodCommon](docs/SignUpCreatePaymentMethodCommon.md)
- [SignUpCreatePaymentMethodCreditCard](docs/SignUpCreatePaymentMethodCreditCard.md)
- [SignUpCreatePaymentMethodCreditCardReferenceTransaction](docs/SignUpCreatePaymentMethodCreditCardReferenceTransaction.md)
- [SignUpCreatePaymentMethodPayPalAdaptive](docs/SignUpCreatePaymentMethodPayPalAdaptive.md)
- [SignUpPaymentMethod](docs/SignUpPaymentMethod.md)
- [SignUpPaymentMethodObjectCustomFields](docs/SignUpPaymentMethodObjectCustomFields.md)
- [SignUpRequest](docs/SignUpRequest.md)
- [SignUpResponse](docs/SignUpResponse.md)
- [SignUpResponseReasons](docs/SignUpResponseReasons.md)
- [SignUpTaxInfo](docs/SignUpTaxInfo.md)
- [SoldToContact](docs/SoldToContact.md)
- [SoldToContactPostOrder](docs/SoldToContactPostOrder.md)
- [SubmitBatchQueryRequest](docs/SubmitBatchQueryRequest.md)
- [SubmitBatchQueryResponse](docs/SubmitBatchQueryResponse.md)
- [SubmitDataQueryRequest](docs/SubmitDataQueryRequest.md)
- [SubmitDataQueryRequestOutput](docs/SubmitDataQueryRequestOutput.md)
- [SubmitDataQueryResponse](docs/SubmitDataQueryResponse.md)
- [SubscribeToProduct](docs/SubscribeToProduct.md)
- [SubscriptionData](docs/SubscriptionData.md)
- [SubscriptionObjectCustomFields](docs/SubscriptionObjectCustomFields.md)
- [SubscriptionObjectNSFields](docs/SubscriptionObjectNSFields.md)
- [SubscriptionObjectQTFields](docs/SubscriptionObjectQTFields.md)
- [SubscriptionOfferObjectCustomFields](docs/SubscriptionOfferObjectCustomFields.md)
- [SystemHealthErrorResponse](docs/SystemHealthErrorResponse.md)
- [Task](docs/Task.md)
- [TasksResponse](docs/TasksResponse.md)
- [TasksResponsePagination](docs/TasksResponsePagination.md)
- [TaxInfo](docs/TaxInfo.md)
- [TaxationItemObjectCustomFields](docs/TaxationItemObjectCustomFields.md)
- [TemplateDetailResponse](docs/TemplateDetailResponse.md)
- [TemplateMigrationClientRequest](docs/TemplateMigrationClientRequest.md)
- [TemplateResponse](docs/TemplateResponse.md)
- [TermInfo](docs/TermInfo.md)
- [TermInfoInitialTerm](docs/TermInfoInitialTerm.md)
- [TermInfoRenewalTerms](docs/TermInfoRenewalTerms.md)
- [TermsAndConditions](docs/TermsAndConditions.md)
- [TimeSlicedElpNetMetrics](docs/TimeSlicedElpNetMetrics.md)
- [TimeSlicedMetrics](docs/TimeSlicedMetrics.md)
- [TimeSlicedNetMetrics](docs/TimeSlicedNetMetrics.md)
- [TimeSlicedTcbNetMetrics](docs/TimeSlicedTcbNetMetrics.md)
- [TokenResponse](docs/TokenResponse.md)
- [TransferPaymentType](docs/TransferPaymentType.md)
- [TriggerDate](docs/TriggerDate.md)
- [TriggerParams](docs/TriggerParams.md)
- [UnapplyCreditMemoType](docs/UnapplyCreditMemoType.md)
- [UnapplyPaymentType](docs/UnapplyPaymentType.md)
- [UpdateCustomObjectCusotmField](docs/UpdateCustomObjectCusotmField.md)
- [UpdatePaymentType](docs/UpdatePaymentType.md)
- [UpdateScheduleItems](docs/UpdateScheduleItems.md)
- [UpdateTask](docs/UpdateTask.md)
- [Usage](docs/Usage.md)
- [UsageFlatFeePricingOverride](docs/UsageFlatFeePricingOverride.md)
- [UsageFlatFeePricingUpdate](docs/UsageFlatFeePricingUpdate.md)
- [UsageObjectCustomFields](docs/UsageObjectCustomFields.md)
- [UsageOveragePricingOverride](docs/UsageOveragePricingOverride.md)
- [UsageOveragePricingUpdate](docs/UsageOveragePricingUpdate.md)
- [UsagePerUnitPricingOverride](docs/UsagePerUnitPricingOverride.md)
- [UsagePerUnitPricingUpdate](docs/UsagePerUnitPricingUpdate.md)
- [UsageTieredPricingOverride](docs/UsageTieredPricingOverride.md)
- [UsageTieredPricingUpdate](docs/UsageTieredPricingUpdate.md)
- [UsageTieredWithOveragePricingOverride](docs/UsageTieredWithOveragePricingOverride.md)
- [UsageTieredWithOveragePricingUpdate](docs/UsageTieredWithOveragePricingUpdate.md)
- [UsageValues](docs/UsageValues.md)
- [UsageVolumePricingOverride](docs/UsageVolumePricingOverride.md)
- [UsageVolumePricingUpdate](docs/UsageVolumePricingUpdate.md)
- [UsagesResponse](docs/UsagesResponse.md)
- [ValidationErrors](docs/ValidationErrors.md)
- [ValidationReasons](docs/ValidationReasons.md)
- [Workflow](docs/Workflow.md)
- [WorkflowDefinition](docs/WorkflowDefinition.md)
- [WorkflowDefinitionActiveVersion](docs/WorkflowDefinitionActiveVersion.md)
- [WorkflowDefinitionAndVersions](docs/WorkflowDefinitionAndVersions.md)
- [WorkflowError](docs/WorkflowError.md)
- [WorkflowInstance](docs/WorkflowInstance.md)
- [ZObject](docs/ZObject.md)
- [ZObjectUpdate](docs/ZObjectUpdate.md)
## Documentation For Authorization
All endpoints do not require authorization.
## Author
[email protected]
| zuora-swagger-client | /zuora-swagger-client-1.2.0.tar.gz/zuora-swagger-client-1.2.0/README.md | README.md |
from __future__ import absolute_import
import datetime
import json
import mimetypes
from multiprocessing.pool import ThreadPool
import os
import re
import tempfile
# python 2 and python 3 compatibility library
import six
from six.moves.urllib.parse import quote
from swagger_client.configuration import Configuration
import swagger_client.models
from swagger_client import rest
class ApiClient(object):
"""Generic API client for Swagger client library builds.
Swagger generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the Swagger
templates.
NOTE: This class is auto generated by the swagger code generator program.
Ref: https://github.com/swagger-api/swagger-codegen
Do not edit the class manually.
:param configuration: .Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
"""
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int if six.PY3 else long, # noqa: F821
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'object': object,
}
def __init__(self, configuration=None, header_name=None, header_value=None,
cookie=None):
if configuration is None:
configuration = Configuration()
self.configuration = configuration
# Use the pool property to lazily initialize the ThreadPool.
self._pool = None
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = {}
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = 'Swagger-Codegen/1.0.0/python'
self.client_side_validation = configuration.client_side_validation
def __del__(self):
if self._pool is not None:
self._pool.close()
self._pool.join()
@property
def pool(self):
if self._pool is None:
self._pool = ThreadPool()
return self._pool
@property
def user_agent(self):
"""User agent for this API client"""
return self.default_headers['User-Agent']
@user_agent.setter
def user_agent(self, value):
self.default_headers['User-Agent'] = value
def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value
def __call_api(
self, resource_path, method, path_params=None,
query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
config = self.configuration
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
header_params['Cookie'] = self.cookie
if header_params:
header_params = self.sanitize_for_serialization(header_params)
header_params = dict(self.parameters_to_tuples(header_params,
collection_formats))
# path parameters
if path_params:
path_params = self.sanitize_for_serialization(path_params)
path_params = self.parameters_to_tuples(path_params,
collection_formats)
for k, v in path_params:
# specified safe chars, encode everything
resource_path = resource_path.replace(
'{%s}' % k,
quote(str(v), safe=config.safe_chars_for_path_param)
)
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
query_params = self.parameters_to_tuples(query_params,
collection_formats)
# post parameters
if post_params or files:
post_params = self.prepare_post_parameters(post_params, files)
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(post_params,
collection_formats)
# auth setting
self.update_params_for_auth(header_params, query_params, auth_settings)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
url = self.configuration.host + resource_path
# perform request and return response
response_data = self.request(
method, url, query_params=query_params, headers=header_params,
post_params=post_params, body=body,
_preload_content=_preload_content,
_request_timeout=_request_timeout)
self.last_response = response_data
return_data = response_data
if _preload_content:
# deserialize response data
if response_type:
return_data = self.deserialize(response_data, response_type)
else:
return_data = None
if _return_http_data_only:
return (return_data)
else:
return (return_data, response_data.status,
response_data.getheaders())
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is swagger model, return the properties dict.
:param obj: The data to serialize.
:return: The serialized form of data.
"""
if obj is None:
return None
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj)
for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
if isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `swagger_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
for attr, _ in six.iteritems(obj.swagger_types)
if getattr(obj, attr) is not None}
return {key: self.sanitize_for_serialization(val)
for key, val in six.iteritems(obj_dict)}
def deserialize(self, response, response_type):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialized object, or string of class name.
:return: deserialized object.
"""
# handle file downloading
# save response body into a tmp file and return the instance
if response_type == "file":
return self.__deserialize_file(response)
# fetch data from response object
try:
data = json.loads(response.data)
except ValueError:
data = response.data
return self.__deserialize(data, response_type)
def __deserialize(self, data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if type(klass) == str:
if klass.startswith('list['):
sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('dict('):
sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in six.iteritems(data)}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(swagger_client.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
"""Makes the HTTP request (synchronous) and returns deserialized data.
To make an async request, set the async_req parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return:
If async_req parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter async_req is False or missing,
then the method will return the response directly.
"""
if not async_req:
return self.__call_api(resource_path, method,
path_params, query_params, header_params,
body, post_params, files,
response_type, auth_settings,
_return_http_data_only, collection_formats,
_preload_content, _request_timeout)
else:
thread = self.pool.apply_async(self.__call_api, (resource_path,
method, path_params, query_params,
header_params, body,
post_params, files,
response_type, auth_settings,
_return_http_data_only,
collection_formats,
_preload_content, _request_timeout))
return thread
def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None, _preload_content=True,
_request_timeout=None):
"""Makes the HTTP request using RESTClient."""
if method == "GET":
return self.rest_client.GET(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "HEAD":
return self.rest_client.HEAD(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "OPTIONS":
return self.rest_client.OPTIONS(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "POST":
return self.rest_client.POST(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PUT":
return self.rest_client.PUT(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PATCH":
return self.rest_client.PATCH(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "DELETE":
return self.rest_client.DELETE(url,
query_params=query_params,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
else:
raise ValueError(
"http method must be `GET`, `HEAD`, `OPTIONS`,"
" `POST`, `PATCH`, `PUT` or `DELETE`."
)
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collections formatted
"""
new_params = []
if collection_formats is None:
collection_formats = {}
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, value) for value in v)
else:
if collection_format == 'ssv':
delimiter = ' '
elif collection_format == 'tsv':
delimiter = '\t'
elif collection_format == 'pipes':
delimiter = '|'
else: # csv is the default
delimiter = ','
new_params.append(
(k, delimiter.join(str(value) for value in v)))
else:
new_params.append((k, v))
return new_params
def prepare_post_parameters(self, post_params=None, files=None):
"""Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
if post_params:
params = post_params
if files:
for k, v in six.iteritems(files):
if not v:
continue
file_names = v if type(v) is list else [v]
for n in file_names:
with open(n, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
mimetype = (mimetypes.guess_type(filename)[0] or
'application/octet-stream')
params.append(
tuple([k, tuple([filename, filedata, mimetype])]))
return params
def select_header_accept(self, accepts):
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return
accepts = [x.lower() for x in accepts]
if 'application/json' in accepts:
return 'application/json'
else:
return ', '.join(accepts)
def select_header_content_type(self, content_types):
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'application/json'
content_types = [x.lower() for x in content_types]
if 'application/json' in content_types or '*/*' in content_types:
return 'application/json'
else:
return content_types[0]
def update_params_for_auth(self, headers, querys, auth_settings):
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
"""
if not auth_settings:
return
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
if not auth_setting['value']:
continue
elif auth_setting['in'] == 'header':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
querys.append((auth_setting['key'], auth_setting['value']))
else:
raise ValueError(
'Authentication token must be in `query` or `header`'
)
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "w") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return six.text_type(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return a original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __hasattr(self, object, name):
return name in object.__class__.__dict__
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
if (not klass.swagger_types and
not self.__hasattr(klass, 'get_real_child_model')):
return data
kwargs = {}
if klass.swagger_types is not None:
for attr, attr_type in six.iteritems(klass.swagger_types):
if (data is not None and
klass.attribute_map[attr] in data and
isinstance(data, (list, dict))):
value = data[klass.attribute_map[attr]]
kwargs[attr] = self.__deserialize(value, attr_type)
instance = klass(**kwargs)
if (isinstance(instance, dict) and
klass.swagger_types is not None and
isinstance(data, dict)):
for key, value in data.items():
if key not in klass.swagger_types:
instance[key] = value
if self.__hasattr(instance, 'get_real_child_model'):
klass_name = instance.get_real_child_model(data)
if klass_name:
instance = self.__deserialize(data, klass_name)
return instance | zuora-swagger-client | /zuora-swagger-client-1.2.0.tar.gz/zuora-swagger-client-1.2.0/swagger_client/api_client.py | api_client.py |
from __future__ import absolute_import
import io
import json
import logging
import re
import ssl
import certifi
# python 2 and python 3 compatibility library
import six
from six.moves.urllib.parse import urlencode
try:
import urllib3
except ImportError:
raise ImportError('Swagger python client requires urllib3.')
logger = logging.getLogger(__name__)
class RESTResponse(io.IOBase):
def __init__(self, resp):
self.urllib3_response = resp
self.status = resp.status
self.reason = resp.reason
self.data = resp.data
def getheaders(self):
"""Returns a dictionary of the response headers."""
return self.urllib3_response.getheaders()
def getheader(self, name, default=None):
"""Returns a given response header."""
return self.urllib3_response.getheader(name, default)
class RESTClientObject(object):
def __init__(self, configuration, pools_size=4, maxsize=None):
# urllib3.PoolManager will pass all kw parameters to connectionpool
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501
# maxsize is the number of requests to host that are allowed in parallel # noqa: E501
# Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501
# cert_reqs
if configuration.verify_ssl:
cert_reqs = ssl.CERT_REQUIRED
else:
cert_reqs = ssl.CERT_NONE
# ca_certs
if configuration.ssl_ca_cert:
ca_certs = configuration.ssl_ca_cert
else:
# if not set certificate file, use Mozilla's root certificates.
ca_certs = certifi.where()
addition_pool_args = {}
if configuration.assert_hostname is not None:
addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501
if maxsize is None:
if configuration.connection_pool_maxsize is not None:
maxsize = configuration.connection_pool_maxsize
else:
maxsize = 4
# https pool manager
if configuration.proxy:
self.pool_manager = urllib3.ProxyManager(
num_pools=pools_size,
maxsize=maxsize,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
cert_file=configuration.cert_file,
key_file=configuration.key_file,
proxy_url=configuration.proxy,
**addition_pool_args
)
else:
self.pool_manager = urllib3.PoolManager(
num_pools=pools_size,
maxsize=maxsize,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
cert_file=configuration.cert_file,
key_file=configuration.key_file,
**addition_pool_args
)
def request(self, method, url, query_params=None, headers=None,
body=None, post_params=None, _preload_content=True,
_request_timeout=None):
"""Perform requests.
:param method: http request method
:param url: http request url
:param query_params: query parameters in the url
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencoded`
and `multipart/form-data`
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
"""
method = method.upper()
assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT',
'PATCH', 'OPTIONS']
if post_params and body:
raise ValueError(
"body parameter cannot be used with post_params parameter."
)
post_params = post_params or {}
headers = headers or {}
timeout = None
if _request_timeout:
if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821
timeout = urllib3.Timeout(total=_request_timeout)
elif (isinstance(_request_timeout, tuple) and
len(_request_timeout) == 2):
timeout = urllib3.Timeout(
connect=_request_timeout[0], read=_request_timeout[1])
if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json'
try:
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
if query_params:
url += '?' + urlencode(query_params)
if re.search('json', headers['Content-Type'], re.IGNORECASE):
request_body = '{}'
if body is not None:
request_body = json.dumps(body)
r = self.pool_manager.request(
method, url,
body=request_body,
preload_content=_preload_content,
timeout=timeout,
headers=headers)
elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501
r = self.pool_manager.request(
method, url,
fields=post_params,
encode_multipart=False,
preload_content=_preload_content,
timeout=timeout,
headers=headers)
elif headers['Content-Type'] == 'multipart/form-data':
# must del headers['Content-Type'], or the correct
# Content-Type which generated by urllib3 will be
# overwritten.
del headers['Content-Type']
r = self.pool_manager.request(
method, url,
fields=post_params,
encode_multipart=True,
preload_content=_preload_content,
timeout=timeout,
headers=headers)
# Pass a `string` parameter directly in the body to support
# other content types than Json when `body` argument is
# provided in serialized form
elif isinstance(body, str):
request_body = body
r = self.pool_manager.request(
method, url,
body=request_body,
preload_content=_preload_content,
timeout=timeout,
headers=headers)
else:
# Cannot generate the request from given parameters
msg = """Cannot prepare a request message for provided
arguments. Please check that your arguments match
declared content type."""
raise ApiException(status=0, reason=msg)
# For `GET`, `HEAD`
else:
r = self.pool_manager.request(method, url,
fields=query_params,
preload_content=_preload_content,
timeout=timeout,
headers=headers)
except urllib3.exceptions.SSLError as e:
msg = "{0}\n{1}".format(type(e).__name__, str(e))
raise ApiException(status=0, reason=msg)
if _preload_content:
r = RESTResponse(r)
# In the python 3, the response.data is bytes.
# we need to decode it to string.
if six.PY3:
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s", r.data)
if not 200 <= r.status <= 299:
raise ApiException(http_resp=r)
return r
def GET(self, url, headers=None, query_params=None, _preload_content=True,
_request_timeout=None):
return self.request("GET", url,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
query_params=query_params)
def HEAD(self, url, headers=None, query_params=None, _preload_content=True,
_request_timeout=None):
return self.request("HEAD", url,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
query_params=query_params)
def OPTIONS(self, url, headers=None, query_params=None, post_params=None,
body=None, _preload_content=True, _request_timeout=None):
return self.request("OPTIONS", url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
def DELETE(self, url, headers=None, query_params=None, body=None,
_preload_content=True, _request_timeout=None):
return self.request("DELETE", url,
headers=headers,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
def POST(self, url, headers=None, query_params=None, post_params=None,
body=None, _preload_content=True, _request_timeout=None):
return self.request("POST", url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
def PUT(self, url, headers=None, query_params=None, post_params=None,
body=None, _preload_content=True, _request_timeout=None):
return self.request("PUT", url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
def PATCH(self, url, headers=None, query_params=None, post_params=None,
body=None, _preload_content=True, _request_timeout=None):
return self.request("PATCH", url,
headers=headers,
query_params=query_params,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
class ApiException(Exception):
def __init__(self, status=None, reason=None, http_resp=None):
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
self.body = http_resp.data
self.headers = http_resp.getheaders()
else:
self.status = status
self.reason = reason
self.body = None
self.headers = None
def __str__(self):
"""Custom error messages for exception"""
error_message = "({0})\n"\
"Reason: {1}\n".format(self.status, self.reason)
if self.headers:
error_message += "HTTP response headers: {0}\n".format(
self.headers)
if self.body:
error_message += "HTTP response body: {0}\n".format(self.body)
return error_message | zuora-swagger-client | /zuora-swagger-client-1.2.0.tar.gz/zuora-swagger-client-1.2.0/swagger_client/rest.py | rest.py |
# flake8: noqa
"""
API Reference
# Introduction Welcome to the REST API reference for the Zuora Billing, Payments, and Central Platform! To learn about the common use cases of Zuora REST APIs, check out the [REST API Tutorials](https://www.zuora.com/developer/rest-api/api-guides/overview/). In addition to Zuora API Reference, we also provide API references for other Zuora products: * [Revenue API Reference](https://www.zuora.com/developer/api-references/revenue/overview/) * [Collections API Reference](https://www.zuora.com/developer/api-references/collections/overview/) The Zuora REST API provides a broad set of operations and resources that: * Enable Web Storefront integration from your website. * Support self-service subscriber sign-ups and account management. * Process revenue schedules through custom revenue rule models. * Enable manipulation of most objects in the Zuora Billing Object Model. Want to share your opinion on how our API works for you? <a href=\"https://community.zuora.com/t5/Developers/API-Feedback-Form/gpm-p/21399\" target=\"_blank\">Tell us how you feel </a>about using our API and what we can do to make it better. Some of our older APIs are no longer recommended but still available, not affecting any existing integration. To find related API documentation, see [Older API Reference](https://www.zuora.com/developer/api-references/older-api/overview/). ## Access to the API If you have a Zuora tenant, you can access the Zuora REST API via one of the following endpoints: | Tenant | Base URL for REST Endpoints | |-------------------------|-------------------------| |US Cloud 1 Production | https://rest.na.zuora.com | |US Cloud 1 API Sandbox | https://rest.sandbox.na.zuora.com | |US Cloud 2 Production | https://rest.zuora.com | |US Cloud 2 API Sandbox | https://rest.apisandbox.zuora.com| |US Central Sandbox | https://rest.test.zuora.com | |US Performance Test | https://rest.pt1.zuora.com | |US Production Copy | Submit a request at <a href=\"http://support.zuora.com/\" target=\"_blank\">Zuora Global Support</a> to enable the Zuora REST API in your tenant and obtain the base URL for REST endpoints. See [REST endpoint base URL of Production Copy (Service) Environment for existing and new customers](https://community.zuora.com/t5/API/REST-endpoint-base-URL-of-Production-Copy-Service-Environment/td-p/29611) for more information. | |EU Production | https://rest.eu.zuora.com | |EU API Sandbox | https://rest.sandbox.eu.zuora.com | |EU Central Sandbox | https://rest.test.eu.zuora.com | The Production endpoint provides access to your live user data. Sandbox tenants are a good place to test code without affecting real-world data. If you would like Zuora to provision a Sandbox tenant for you, contact your Zuora representative for assistance. If you do not have a Zuora tenant, go to <a href=\"https://www.zuora.com/resource/zuora-test-drive\" target=\"_blank\">https://www.zuora.com/resource/zuora-test-drive</a> and sign up for a Production Test Drive tenant. The tenant comes with seed data, including a sample product catalog. # Error Handling If a request to Zuora Billing REST API with an endpoint starting with `/v1` (except [Actions](https://www.zuora.com/developer/api-references/api/tag/Actions) and CRUD operations) fails, the response will contain an eight-digit error code with a corresponding error message to indicate the details of the error. The following code snippet is a sample error response that contains an error code and message pair: ``` { \"success\": false, \"processId\": \"CBCFED6580B4E076\", \"reasons\": [ { \"code\": 53100320, \"message\": \"'termType' value should be one of: TERMED, EVERGREEN\" } ] } ``` The `success` field indicates whether the API request has succeeded. The `processId` field is a Zuora internal ID that you can provide to Zuora Global Support for troubleshooting purposes. The `reasons` field contains the actual error code and message pair. The error code begins with `5` or `6` means that you encountered a certain issue that is specific to a REST API resource in Zuora Billing, Payments, and Central Platform. For example, `53100320` indicates that an invalid value is specified for the `termType` field of the `subscription` object. The error code beginning with `9` usually indicates that an authentication-related issue occurred, and it can also indicate other unexpected errors depending on different cases. For example, `90000011` indicates that an invalid credential is provided in the request header. When troubleshooting the error, you can divide the error code into two components: REST API resource code and error category code. See the following Zuora error code sample: <a href=\"https://www.zuora.com/developer/images/ZuoraErrorCode.jpeg\" target=\"_blank\"><img src=\"https://www.zuora.com/developer/images/ZuoraErrorCode.jpeg\" alt=\"Zuora Error Code Sample\"></a> **Note:** Zuora determines resource codes based on the request payload. Therefore, if GET and DELETE requests that do not contain payloads fail, you will get `500000` as the resource code, which indicates an unknown object and an unknown field. The error category code of these requests is valid and follows the rules described in the [Error Category Codes](https://www.zuora.com/developer/api-references/api/overview/#section/Error-Handling/Error-Category-Codes) section. In such case, you can refer to the returned error message to troubleshoot. ## REST API Resource Codes The 6-digit resource code indicates the REST API resource, typically a field of a Zuora object, on which the issue occurs. In the preceding example, `531003` refers to the `termType` field of the `subscription` object. The value range for all REST API resource codes is from `500000` to `679999`. See <a href=\"https://knowledgecenter.zuora.com/Central_Platform/API/AA_REST_API/Resource_Codes\" target=\"_blank\">Resource Codes</a> in the Knowledge Center for a full list of resource codes. ## Error Category Codes The 2-digit error category code identifies the type of error, for example, resource not found or missing required field. The following table describes all error categories and the corresponding resolution: | Code | Error category | Description | Resolution | |:--------|:--------|:--------|:--------| | 10 | Permission or access denied | The request cannot be processed because a certain tenant or user permission is missing. | Check the missing tenant or user permission in the response message and contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> for enablement. | | 11 | Authentication failed | Authentication fails due to invalid API authentication credentials. | Ensure that a valid API credential is specified. | | 20 | Invalid format or value | The request cannot be processed due to an invalid field format or value. | Check the invalid field in the error message, and ensure that the format and value of all fields you passed in are valid. | | 21 | Unknown field in request | The request cannot be processed because an unknown field exists in the request body. | Check the unknown field name in the response message, and ensure that you do not include any unknown field in the request body. | | 22 | Missing required field | The request cannot be processed because a required field in the request body is missing. | Check the missing field name in the response message, and ensure that you include all required fields in the request body. | | 23 | Missing required parameter | The request cannot be processed because a required query parameter is missing. | Check the missing parameter name in the response message, and ensure that you include the parameter in the query. | | 30 | Rule restriction | The request cannot be processed due to the violation of a Zuora business rule. | Check the response message and ensure that the API request meets the specified business rules. | | 40 | Not found | The specified resource cannot be found. | Check the response message and ensure that the specified resource exists in your Zuora tenant. | | 45 | Unsupported request | The requested endpoint does not support the specified HTTP method. | Check your request and ensure that the endpoint and method matches. | | 50 | Locking contention | This request cannot be processed because the objects this request is trying to modify are being modified by another API request, UI operation, or batch job process. | <p>Resubmit the request first to have another try.</p> <p>If this error still occurs, contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> with the returned `Zuora-Request-Id` value in the response header for assistance.</p> | | 60 | Internal error | The server encounters an internal error. | Contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> with the returned `Zuora-Request-Id` value in the response header for assistance. | | 61 | Temporary error | A temporary error occurs during request processing, for example, a database communication error. | <p>Resubmit the request first to have another try.</p> <p>If this error still occurs, contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> with the returned `Zuora-Request-Id` value in the response header for assistance. </p>| | 70 | Request exceeded limit | The total number of concurrent requests exceeds the limit allowed by the system. | <p>Resubmit the request after the number of seconds specified by the `Retry-After` value in the response header.</p> <p>Check [Concurrent request limits](https://www.zuora.com/developer/rest-api/general-concepts/rate-concurrency-limits/) for details about Zuora’s concurrent request limit policy.</p> | | 90 | Malformed request | The request cannot be processed due to JSON syntax errors. | Check the syntax error in the JSON request body and ensure that the request is in the correct JSON format. | | 99 | Integration error | The server encounters an error when communicating with an external system, for example, payment gateway, tax engine provider. | Check the response message and take action accordingly. | # API Versions The Zuora REST API are version controlled. Versioning ensures that Zuora REST API changes are backward compatible. Zuora uses a major and minor version nomenclature to manage changes. By specifying a version in a REST request, you can get expected responses regardless of future changes to the API. ## Major Version The major version number of the REST API appears in the REST URL. In this API reference, only the **v1** major version is available. For example, `POST https://rest.zuora.com/v1/subscriptions`. ## Minor Version Zuora uses minor versions for the REST API to control small changes. For example, a field in a REST method is deprecated and a new field is used to replace it. Some fields in the REST methods are supported as of minor versions. If a field is not noted with a minor version, this field is available for all minor versions. If a field is noted with a minor version, this field is in version control. You must specify the supported minor version in the request header to process without an error. If a field is in version control, it is either with a minimum minor version or a maximum minor version, or both of them. You can only use this field with the minor version between the minimum and the maximum minor versions. For example, the `invoiceCollect` field in the POST Subscription method is in version control and its maximum minor version is 189.0. You can only use this field with the minor version 189.0 or earlier. If you specify a version number in the request header that is not supported, Zuora will use the minimum minor version of the REST API. In our REST API documentation, if a field or feature requires a minor version number, we note that in the field description. You only need to specify the version number when you use the fields require a minor version. To specify the minor version, set the `zuora-version` parameter to the minor version number in the request header for the request call. For example, the `collect` field is in 196.0 minor version. If you want to use this field for the POST Subscription method, set the `zuora-version` parameter to `196.0` in the request header. The `zuora-version` parameter is case sensitive. For all the REST API fields, by default, if the minor version is not specified in the request header, Zuora will use the minimum minor version of the REST API to avoid breaking your integration. ### Minor Version History The supported minor versions are not serial. This section documents the changes made to each Zuora REST API minor version. The following table lists the supported versions and the fields that have a Zuora REST API minor version. | Fields | Minor Version | REST Methods | Description | |:--------|:--------|:--------|:--------| | invoiceCollect | 189.0 and earlier | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Generates an invoice and collects a payment for a subscription. | | collect | 196.0 and later | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Collects an automatic payment for a subscription. | | invoice | 196.0 and 207.0| [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Generates an invoice for a subscription. | | invoiceTargetDate | 206.0 and earlier | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\") |Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | invoiceTargetDate | 207.0 and earlier | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | targetDate | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\") |Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | targetDate | 211.0 and later | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | includeExisting DraftInvoiceItems | 206.0 and earlier| [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | Specifies whether to include draft invoice items in subscription previews. Specify it to be `true` (default) to include draft invoice items in the preview result. Specify it to be `false` to excludes draft invoice items in the preview result. | | includeExisting DraftDocItems | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | Specifies whether to include draft invoice items in subscription previews. Specify it to be `true` (default) to include draft invoice items in the preview result. Specify it to be `false` to excludes draft invoice items in the preview result. | | previewType | 206.0 and earlier| [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | The type of preview you will receive. The possible values are `InvoiceItem`(default), `ChargeMetrics`, and `InvoiceItemChargeMetrics`. | | previewType | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | The type of preview you will receive. The possible values are `LegalDoc`(default), `ChargeMetrics`, and `LegalDocChargeMetrics`. | | runBilling | 211.0 and later | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Generates an invoice or credit memo for a subscription. **Note:** Credit memos are only available if you have the Invoice Settlement feature enabled. | | invoiceDate | 214.0 and earlier | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date that should appear on the invoice being generated, as `yyyy-mm-dd`. | | invoiceTargetDate | 214.0 and earlier | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date through which to calculate charges on this account if an invoice is generated, as `yyyy-mm-dd`. | | documentDate | 215.0 and later | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date that should appear on the invoice and credit memo being generated, as `yyyy-mm-dd`. | | targetDate | 215.0 and later | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date through which to calculate charges on this account if an invoice or a credit memo is generated, as `yyyy-mm-dd`. | | memoItemAmount | 223.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | Amount of the memo item. | | amount | 224.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | Amount of the memo item. | | subscriptionNumbers | 222.4 and earlier | [Create order](https://www.zuora.com/developer/api-references/api/operation/POST_Order \"Create order\") | Container for the subscription numbers of the subscriptions in an order. | | subscriptions | 223.0 and later | [Create order](https://www.zuora.com/developer/api-references/api/operation/POST_Order \"Create order\") | Container for the subscription numbers and statuses in an order. | | creditTaxItems | 238.0 and earlier | [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\") | Container for the taxation items of the credit memo item. | | taxItems | 238.0 and earlier | [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Container for the taxation items of the debit memo item. | | taxationItems | 239.0 and later | [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\"); [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Container for the taxation items of the memo item. | | chargeId | 256.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | ID of the product rate plan charge that the memo is created from. | | productRatePlanChargeId | 257.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | ID of the product rate plan charge that the memo is created from. | | comment | 256.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\"); [Create credit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromInvoice \"Create credit memo from invoice\"); [Create debit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromInvoice \"Create debit memo from invoice\"); [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\"); [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Comments about the product rate plan charge, invoice item, or memo item. | | description | 257.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\"); [Create credit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromInvoice \"Create credit memo from invoice\"); [Create debit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromInvoice \"Create debit memo from invoice\"); [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\"); [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Description of the the product rate plan charge, invoice item, or memo item. | | taxationItems | 309.0 and later | [Preview an order](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewOrder \"Preview an order\") | List of taxation items for an invoice item or a credit memo item. | | batch | 309.0 and earlier | [Create a billing preview run](https://www.zuora.com/developer/api-references/api/operation/POST_BillingPreviewRun \"Create a billing preview run\") | The customer batches to include in the billing preview run. | | batches | 314.0 and later | [Create a billing preview run](https://www.zuora.com/developer/api-references/api/operation/POST_BillingPreviewRun \"Create a billing preview run\") | The customer batches to include in the billing preview run. | | taxationItems | 315.0 and later | [Preview a subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview a subscription\"); [Update a subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update a subscription\")| List of taxation items for an invoice item or a credit memo item. | | billingDocument | 330.0 and later | [Create a payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedule \"Create a payment schedule\"); [Create multiple payment schedules at once](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedules \"Create multiple payment schedules at once\")| The billing document with which the payment schedule item is associated. | | paymentId | 336.0 and earlier | [Add payment schedule items to a custom payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_AddItemsToCustomPaymentSchedule/ \"Add payment schedule items to a custom payment schedule\"); [Update a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentSchedule/ \"Update a payment schedule\"); [Update a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleItem/ \"Update a payment schedule item\"); [Preview the result of payment schedule update](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleUpdatePreview/ \"Preview the result of payment schedule update\"); [Retrieve a payment schedule](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedule/ \"Retrieve a payment schedule\"); [Retrieve a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentScheduleItem/ \"Retrieve a payment schedule item\"); [List payment schedules by customer account](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedules/ \"List payment schedules by customer account\"); [Cancel a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentSchedule/ \"Cancel a payment schedule\"); [Cancel a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentScheduleItem/ \"Cancel a payment schedule item\");[Skip a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_SkipPaymentScheduleItem/ \"Skip a payment schedule item\");[Retry failed payment schedule items](https://www.zuora.com/developer/api-references/api/operation/POST_RetryPaymentScheduleItem/ \"Retry failed payment schedule items\") | ID of the payment to be linked to the payment schedule item. | | paymentOption | 337.0 and later | [Create a payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedule/ \"Create a payment schedule\"); [Create multiple payment schedules at once](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedules/ \"Create multiple payment schedules at once\"); [Create a payment](https://www.zuora.com/developer/api-references/api/operation/POST_CreatePayment/ \"Create a payment\"); [Add payment schedule items to a custom payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_AddItemsToCustomPaymentSchedule/ \"Add payment schedule items to a custom payment schedule\"); [Update a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentSchedule/ \"Update a payment schedule\"); [Update a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleItem/ \"Update a payment schedule item\"); [Preview the result of payment schedule update](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleUpdatePreview/ \"Preview the result of payment schedule update\"); [Retrieve a payment schedule](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedule/ \"Retrieve a payment schedule\"); [Retrieve a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentScheduleItem/ \"Retrieve a payment schedule item\"); [List payment schedules by customer account](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedules/ \"List payment schedules by customer account\"); [Cancel a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentSchedule/ \"Cancel a payment schedule\"); [Cancel a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentScheduleItem/ \"Cancel a payment schedule item\"); [Skip a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_SkipPaymentScheduleItem/ \"Skip a payment schedule item\"); [Retry failed payment schedule items](https://www.zuora.com/developer/api-references/api/operation/POST_RetryPaymentScheduleItem/ \"Retry failed payment schedule items\"); [List payments](https://www.zuora.com/developer/api-references/api/operation/GET_RetrieveAllPayments/ \"List payments\") | Array of transactional level rules for processing payments. | #### Version 207.0 and Later The response structure of the [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription) and [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") methods are changed. The following invoice related response fields are moved to the invoice container: * amount * amountWithoutTax * taxAmount * invoiceItems * targetDate * chargeMetrics # API Names for Zuora Objects For information about the Zuora business object model, see [Zuora Business Object Model](https://www.zuora.com/developer/rest-api/general-concepts/object-model/). You can use the [Describe](https://www.zuora.com/developer/api-references/api/operation/GET_Describe) operation to list the fields of each Zuora object that is available in your tenant. When you call the operation, you must specify the API name of the Zuora object. The following table provides the API name of each Zuora object: | Object | API Name | |-----------------------------------------------|--------------------------------------------| | Account | `Account` | | Accounting Code | `AccountingCode` | | Accounting Period | `AccountingPeriod` | | Amendment | `Amendment` | | Application Group | `ApplicationGroup` | | Billing Run | <p>`BillingRun` - API name used in the [Describe](https://www.zuora.com/developer/api-references/api/operation/GET_Describe) operation, Export ZOQL queries, and Data Query.</p> <p>`BillRun` - API name used in the [Actions](https://www.zuora.com/developer/api-references/api/tag/Actions). See the CRUD oprations of [Bill Run](https://www.zuora.com/developer/api-references/api/tag/Bill-Run) for more information about the `BillRun` object. `BillingRun` and `BillRun` have different fields. | | Configuration Templates | `ConfigurationTemplates` | | Contact | `Contact` | | Contact Snapshot | `ContactSnapshot` | | Credit Balance Adjustment | `CreditBalanceAdjustment` | | Credit Memo | `CreditMemo` | | Credit Memo Application | `CreditMemoApplication` | | Credit Memo Application Item | `CreditMemoApplicationItem` | | Credit Memo Item | `CreditMemoItem` | | Credit Memo Part | `CreditMemoPart` | | Credit Memo Part Item | `CreditMemoPartItem` | | Credit Taxation Item | `CreditTaxationItem` | | Custom Exchange Rate | `FXCustomRate` | | Debit Memo | `DebitMemo` | | Debit Memo Item | `DebitMemoItem` | | Debit Taxation Item | `DebitTaxationItem` | | Discount Applied Metrics | `DiscountAppliedMetrics` | | Entity | `Tenant` | | Fulfillment | `Fulfillment` | | Feature | `Feature` | | Gateway Reconciliation Event | `PaymentGatewayReconciliationEventLog` | | Gateway Reconciliation Job | `PaymentReconciliationJob` | | Gateway Reconciliation Log | `PaymentReconciliationLog` | | Invoice | `Invoice` | | Invoice Adjustment | `InvoiceAdjustment` | | Invoice Item | `InvoiceItem` | | Invoice Item Adjustment | `InvoiceItemAdjustment` | | Invoice Payment | `InvoicePayment` | | Invoice Schedule | `InvoiceSchedule` | | Journal Entry | `JournalEntry` | | Journal Entry Item | `JournalEntryItem` | | Journal Run | `JournalRun` | | Notification History - Callout | `CalloutHistory` | | Notification History - Email | `EmailHistory` | | Offer | `Offer` | | Order | `Order` | | Order Action | `OrderAction` | | Order ELP | `OrderElp` | | Order Line Items | `OrderLineItems` | | Order Item | `OrderItem` | | Order MRR | `OrderMrr` | | Order Quantity | `OrderQuantity` | | Order TCB | `OrderTcb` | | Order TCV | `OrderTcv` | | Payment | `Payment` | | Payment Application | `PaymentApplication` | | Payment Application Item | `PaymentApplicationItem` | | Payment Method | `PaymentMethod` | | Payment Method Snapshot | `PaymentMethodSnapshot` | | Payment Method Transaction Log | `PaymentMethodTransactionLog` | | Payment Method Update | `UpdaterDetail` | | Payment Part | `PaymentPart` | | Payment Part Item | `PaymentPartItem` | | Payment Run | `PaymentRun` | | Payment Transaction Log | `PaymentTransactionLog` | | Price Book Item | `PriceBookItem` | | Processed Usage | `ProcessedUsage` | | Product | `Product` | | Product Feature | `ProductFeature` | | Product Rate Plan | `ProductRatePlan` | | Product Rate Plan Charge | `ProductRatePlanCharge` | | Product Rate Plan Charge Tier | `ProductRatePlanChargeTier` | | Rate Plan | `RatePlan` | | Rate Plan Charge | `RatePlanCharge` | | Rate Plan Charge Tier | `RatePlanChargeTier` | | Refund | `Refund` | | Refund Application | `RefundApplication` | | Refund Application Item | `RefundApplicationItem` | | Refund Invoice Payment | `RefundInvoicePayment` | | Refund Part | `RefundPart` | | Refund Part Item | `RefundPartItem` | | Refund Transaction Log | `RefundTransactionLog` | | Revenue Charge Summary | `RevenueChargeSummary` | | Revenue Charge Summary Item | `RevenueChargeSummaryItem` | | Revenue Event | `RevenueEvent` | | Revenue Event Credit Memo Item | `RevenueEventCreditMemoItem` | | Revenue Event Debit Memo Item | `RevenueEventDebitMemoItem` | | Revenue Event Invoice Item | `RevenueEventInvoiceItem` | | Revenue Event Invoice Item Adjustment | `RevenueEventInvoiceItemAdjustment` | | Revenue Event Item | `RevenueEventItem` | | Revenue Event Item Credit Memo Item | `RevenueEventItemCreditMemoItem` | | Revenue Event Item Debit Memo Item | `RevenueEventItemDebitMemoItem` | | Revenue Event Item Invoice Item | `RevenueEventItemInvoiceItem` | | Revenue Event Item Invoice Item Adjustment | `RevenueEventItemInvoiceItemAdjustment` | | Revenue Event Type | `RevenueEventType` | | Revenue Schedule | `RevenueSchedule` | | Revenue Schedule Credit Memo Item | `RevenueScheduleCreditMemoItem` | | Revenue Schedule Debit Memo Item | `RevenueScheduleDebitMemoItem` | | Revenue Schedule Invoice Item | `RevenueScheduleInvoiceItem` | | Revenue Schedule Invoice Item Adjustment | `RevenueScheduleInvoiceItemAdjustment` | | Revenue Schedule Item | `RevenueScheduleItem` | | Revenue Schedule Item Credit Memo Item | `RevenueScheduleItemCreditMemoItem` | | Revenue Schedule Item Debit Memo Item | `RevenueScheduleItemDebitMemoItem` | | Revenue Schedule Item Invoice Item | `RevenueScheduleItemInvoiceItem` | | Revenue Schedule Item Invoice Item Adjustment | `RevenueScheduleItemInvoiceItemAdjustment` | | Subscription | `Subscription` | | Subscription Product Feature | `SubscriptionProductFeature` | | Taxable Item Snapshot | `TaxableItemSnapshot` | | Taxation Item | `TaxationItem` | | Updater Batch | `UpdaterBatch` | | Usage | `Usage` | # noqa: E501
OpenAPI spec version: 2023-07-24
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import apis into sdk package
from swagger_client.api.api_health_api import APIHealthApi
from swagger_client.api.accounting_codes_api import AccountingCodesApi
from swagger_client.api.accounting_periods_api import AccountingPeriodsApi
from swagger_client.api.accounts_api import AccountsApi
from swagger_client.api.actions_api import ActionsApi
from swagger_client.api.adjustments_api import AdjustmentsApi
from swagger_client.api.aggregate_queries_api import AggregateQueriesApi
from swagger_client.api.attachments_api import AttachmentsApi
from swagger_client.api.bill_run_api import BillRunApi
from swagger_client.api.bill_run_health_api import BillRunHealthApi
from swagger_client.api.billing_documents_api import BillingDocumentsApi
from swagger_client.api.billing_preview_run_api import BillingPreviewRunApi
from swagger_client.api.catalog_api import CatalogApi
from swagger_client.api.catalog_groups_api import CatalogGroupsApi
from swagger_client.api.configuration_templates_api import ConfigurationTemplatesApi
from swagger_client.api.contact_snapshots_api import ContactSnapshotsApi
from swagger_client.api.contacts_api import ContactsApi
from swagger_client.api.credit_memos_api import CreditMemosApi
from swagger_client.api.custom_event_triggers_api import CustomEventTriggersApi
from swagger_client.api.custom_exchange_rates_api import CustomExchangeRatesApi
from swagger_client.api.custom_object_definitions_api import CustomObjectDefinitionsApi
from swagger_client.api.custom_object_jobs_api import CustomObjectJobsApi
from swagger_client.api.custom_object_records_api import CustomObjectRecordsApi
from swagger_client.api.custom_payment_method_types_api import CustomPaymentMethodTypesApi
from swagger_client.api.custom_scheduled_events_api import CustomScheduledEventsApi
from swagger_client.api.data_queries_api import DataQueriesApi
from swagger_client.api.debit_memos_api import DebitMemosApi
from swagger_client.api.describe_api import DescribeApi
from swagger_client.api.electronic_payments_health_api import ElectronicPaymentsHealthApi
from swagger_client.api.files_api import FilesApi
from swagger_client.api.fulfillments_api import FulfillmentsApi
from swagger_client.api.hosted_pages_api import HostedPagesApi
from swagger_client.api.imports_api import ImportsApi
from swagger_client.api.invoice_schedules_api import InvoiceSchedulesApi
from swagger_client.api.invoices_api import InvoicesApi
from swagger_client.api.journal_runs_api import JournalRunsApi
from swagger_client.api.mass_updater_api import MassUpdaterApi
from swagger_client.api.notifications_api import NotificationsApi
from swagger_client.api.o_auth_api import OAuthApi
from swagger_client.api.offers_api import OffersApi
from swagger_client.api.operations_api import OperationsApi
from swagger_client.api.order_actions_api import OrderActionsApi
from swagger_client.api.order_line_items_api import OrderLineItemsApi
from swagger_client.api.orders_api import OrdersApi
from swagger_client.api.payment_authorization_api import PaymentAuthorizationApi
from swagger_client.api.payment_gateway_reconciliation_api import PaymentGatewayReconciliationApi
from swagger_client.api.payment_gateways_api import PaymentGatewaysApi
from swagger_client.api.payment_method_snapshots_api import PaymentMethodSnapshotsApi
from swagger_client.api.payment_method_transaction_logs_api import PaymentMethodTransactionLogsApi
from swagger_client.api.payment_method_updater_api import PaymentMethodUpdaterApi
from swagger_client.api.payment_methods_api import PaymentMethodsApi
from swagger_client.api.payment_runs_api import PaymentRunsApi
from swagger_client.api.payment_schedules_api import PaymentSchedulesApi
from swagger_client.api.payment_transaction_logs_api import PaymentTransactionLogsApi
from swagger_client.api.payments_api import PaymentsApi
from swagger_client.api.price_book_items_api import PriceBookItemsApi
from swagger_client.api.product_rate_plan_charge_tiers_api import ProductRatePlanChargeTiersApi
from swagger_client.api.product_rate_plan_charges_api import ProductRatePlanChargesApi
from swagger_client.api.product_rate_plans_api import ProductRatePlansApi
from swagger_client.api.products_api import ProductsApi
from swagger_client.api.rsa_signatures_api import RSASignaturesApi
from swagger_client.api.ramps_api import RampsApi
from swagger_client.api.rate_plans_api import RatePlansApi
from swagger_client.api.refunds_api import RefundsApi
from swagger_client.api.sequence_sets_api import SequenceSetsApi
from swagger_client.api.settings_api import SettingsApi
from swagger_client.api.sign_up_api import SignUpApi
from swagger_client.api.subscriptions_api import SubscriptionsApi
from swagger_client.api.summary_journal_entries_api import SummaryJournalEntriesApi
from swagger_client.api.taxation_items_api import TaxationItemsApi
from swagger_client.api.usage_api import UsageApi
from swagger_client.api.workflows_api import WorkflowsApi
from swagger_client.api.zuora_revenue_integration_api import ZuoraRevenueIntegrationApi
# import ApiClient
from swagger_client.api_client import ApiClient
from swagger_client.configuration import Configuration
# import models into sdk package
from swagger_client.models.account import Account
from swagger_client.models.account_credit_card_holder import AccountCreditCardHolder
from swagger_client.models.account_data import AccountData
from swagger_client.models.account_object_custom_fields import AccountObjectCustomFields
from swagger_client.models.account_object_ns_fields import AccountObjectNSFields
from swagger_client.models.accounting_code_object_custom_fields import AccountingCodeObjectCustomFields
from swagger_client.models.accounting_period_object_custom_fields import AccountingPeriodObjectCustomFields
from swagger_client.models.actions_error_response import ActionsErrorResponse
from swagger_client.models.api_volume_summary_record import ApiVolumeSummaryRecord
from swagger_client.models.apply_credit_memo_type import ApplyCreditMemoType
from swagger_client.models.apply_payment_type import ApplyPaymentType
from swagger_client.models.bad_request_response import BadRequestResponse
from swagger_client.models.bad_request_response_errors import BadRequestResponseErrors
from swagger_client.models.batch_debit_memo_type import BatchDebitMemoType
from swagger_client.models.batch_invoice_type import BatchInvoiceType
from swagger_client.models.batch_queries import BatchQueries
from swagger_client.models.batch_query import BatchQuery
from swagger_client.models.batches_queries import BatchesQueries
from swagger_client.models.batches_queries_by_id import BatchesQueriesById
from swagger_client.models.bill_run_filter_request_type import BillRunFilterRequestType
from swagger_client.models.bill_run_filter_response_type import BillRunFilterResponseType
from swagger_client.models.bill_run_filters import BillRunFilters
from swagger_client.models.bill_run_schedule_request_type import BillRunScheduleRequestType
from swagger_client.models.bill_run_schedule_response_type import BillRunScheduleResponseType
from swagger_client.models.bill_to_contact import BillToContact
from swagger_client.models.bill_to_contact_post_order import BillToContactPostOrder
from swagger_client.models.billing_doc_volume_summary_record import BillingDocVolumeSummaryRecord
from swagger_client.models.billing_document_query_response_element_type import BillingDocumentQueryResponseElementType
from swagger_client.models.billing_options import BillingOptions
from swagger_client.models.billing_preview_result import BillingPreviewResult
from swagger_client.models.billing_update import BillingUpdate
from swagger_client.models.body import Body
from swagger_client.models.body_in_setting_value_reponse import BodyInSettingValueReponse
from swagger_client.models.body_in_setting_value_request import BodyInSettingValueRequest
from swagger_client.models.bulk_credit_memos_response_type import BulkCreditMemosResponseType
from swagger_client.models.bulk_debit_memos_response_type import BulkDebitMemosResponseType
from swagger_client.models.callout_auth import CalloutAuth
from swagger_client.models.callout_merge_fields import CalloutMergeFields
from swagger_client.models.cancel_bill_run_response_type import CancelBillRunResponseType
from swagger_client.models.cancel_subscription import CancelSubscription
from swagger_client.models.catalog_group_response import CatalogGroupResponse
from swagger_client.models.change_plan import ChangePlan
from swagger_client.models.change_plan_rate_plan_override import ChangePlanRatePlanOverride
from swagger_client.models.charge_model_configuration_type import ChargeModelConfigurationType
from swagger_client.models.charge_model_data_override import ChargeModelDataOverride
from swagger_client.models.charge_model_data_override_charge_model_configuration import ChargeModelDataOverrideChargeModelConfiguration
from swagger_client.models.charge_override import ChargeOverride
from swagger_client.models.charge_override_billing import ChargeOverrideBilling
from swagger_client.models.charge_override_pricing import ChargeOverridePricing
from swagger_client.models.charge_preview_metrics import ChargePreviewMetrics
from swagger_client.models.charge_preview_metrics_cmrr import ChargePreviewMetricsCmrr
from swagger_client.models.charge_preview_metrics_tax import ChargePreviewMetricsTax
from swagger_client.models.charge_preview_metrics_tcb import ChargePreviewMetricsTcb
from swagger_client.models.charge_preview_metrics_tcv import ChargePreviewMetricsTcv
from swagger_client.models.charge_tier import ChargeTier
from swagger_client.models.charge_update import ChargeUpdate
from swagger_client.models.charge_update_pricing import ChargeUpdatePricing
from swagger_client.models.children_setting_value_request import ChildrenSettingValueRequest
from swagger_client.models.common_error_response import CommonErrorResponse
from swagger_client.models.common_response_type import CommonResponseType
from swagger_client.models.common_response_type_reasons import CommonResponseTypeReasons
from swagger_client.models.compare_schema_info_response import CompareSchemaInfoResponse
from swagger_client.models.compare_schema_key_value import CompareSchemaKeyValue
from swagger_client.models.config_template_error_response import ConfigTemplateErrorResponse
from swagger_client.models.config_template_error_response_reasons import ConfigTemplateErrorResponseReasons
from swagger_client.models.configuration_template_content import ConfigurationTemplateContent
from swagger_client.models.contact_info import ContactInfo
from swagger_client.models.contact_object_custom_fields import ContactObjectCustomFields
from swagger_client.models.contact_response import ContactResponse
from swagger_client.models.contact_snapshot_object_custom_fields import ContactSnapshotObjectCustomFields
from swagger_client.models.create_change_plan import CreateChangePlan
from swagger_client.models.create_offer_rate_plan_override import CreateOfferRatePlanOverride
from swagger_client.models.create_or_update_email_templates_response import CreateOrUpdateEmailTemplatesResponse
from swagger_client.models.create_order_change_plan_rate_plan_override import CreateOrderChangePlanRatePlanOverride
from swagger_client.models.create_order_charge_override import CreateOrderChargeOverride
from swagger_client.models.create_order_charge_override_billing import CreateOrderChargeOverrideBilling
from swagger_client.models.create_order_charge_override_pricing import CreateOrderChargeOverridePricing
from swagger_client.models.create_order_charge_update import CreateOrderChargeUpdate
from swagger_client.models.create_order_create_subscription import CreateOrderCreateSubscription
from swagger_client.models.create_order_create_subscription_new_subscription_owner_account import CreateOrderCreateSubscriptionNewSubscriptionOwnerAccount
from swagger_client.models.create_order_create_subscription_terms import CreateOrderCreateSubscriptionTerms
from swagger_client.models.create_order_create_subscription_terms_initial_term import CreateOrderCreateSubscriptionTermsInitialTerm
from swagger_client.models.create_order_offer_update import CreateOrderOfferUpdate
from swagger_client.models.create_order_order_action import CreateOrderOrderAction
from swagger_client.models.create_order_order_action_add_product import CreateOrderOrderActionAddProduct
from swagger_client.models.create_order_order_action_update_product import CreateOrderOrderActionUpdateProduct
from swagger_client.models.create_order_order_line_item import CreateOrderOrderLineItem
from swagger_client.models.create_order_pricing_update import CreateOrderPricingUpdate
from swagger_client.models.create_order_pricing_update_charge_model_data import CreateOrderPricingUpdateChargeModelData
from swagger_client.models.create_order_pricing_update_discount import CreateOrderPricingUpdateDiscount
from swagger_client.models.create_order_pricing_update_recurring_delivery_based import CreateOrderPricingUpdateRecurringDeliveryBased
from swagger_client.models.create_order_pricing_update_recurring_flat_fee import CreateOrderPricingUpdateRecurringFlatFee
from swagger_client.models.create_order_pricing_update_recurring_per_unit import CreateOrderPricingUpdateRecurringPerUnit
from swagger_client.models.create_order_pricing_update_recurring_tiered import CreateOrderPricingUpdateRecurringTiered
from swagger_client.models.create_order_pricing_update_recurring_volume import CreateOrderPricingUpdateRecurringVolume
from swagger_client.models.create_order_pricing_update_usage_flat_fee import CreateOrderPricingUpdateUsageFlatFee
from swagger_client.models.create_order_pricing_update_usage_overage import CreateOrderPricingUpdateUsageOverage
from swagger_client.models.create_order_pricing_update_usage_per_unit import CreateOrderPricingUpdateUsagePerUnit
from swagger_client.models.create_order_pricing_update_usage_tiered import CreateOrderPricingUpdateUsageTiered
from swagger_client.models.create_order_pricing_update_usage_tiered_with_overage import CreateOrderPricingUpdateUsageTieredWithOverage
from swagger_client.models.create_order_pricing_update_usage_volume import CreateOrderPricingUpdateUsageVolume
from swagger_client.models.create_order_product_override import CreateOrderProductOverride
from swagger_client.models.create_order_rate_plan_feature_override import CreateOrderRatePlanFeatureOverride
from swagger_client.models.create_order_rate_plan_override import CreateOrderRatePlanOverride
from swagger_client.models.create_order_rate_plan_update import CreateOrderRatePlanUpdate
from swagger_client.models.create_order_resume import CreateOrderResume
from swagger_client.models.create_order_suspend import CreateOrderSuspend
from swagger_client.models.create_order_terms_and_conditions import CreateOrderTermsAndConditions
from swagger_client.models.create_order_trigger_params import CreateOrderTriggerParams
from swagger_client.models.create_order_update_product_trigger_params import CreateOrderUpdateProductTriggerParams
from swagger_client.models.create_pm_pay_pal_ec_pay_pal_native_ec_pay_pal_cp import CreatePMPayPalECPayPalNativeECPayPalCP
from swagger_client.models.create_payment_method_ach import CreatePaymentMethodACH
from swagger_client.models.create_payment_method_apple_pay_adyen import CreatePaymentMethodApplePayAdyen
from swagger_client.models.create_payment_method_bank_transfer import CreatePaymentMethodBankTransfer
from swagger_client.models.create_payment_method_bank_transfer_account_holder_info import CreatePaymentMethodBankTransferAccountHolderInfo
from swagger_client.models.create_payment_method_cc_reference_transaction import CreatePaymentMethodCCReferenceTransaction
from swagger_client.models.create_payment_method_cardholder_info import CreatePaymentMethodCardholderInfo
from swagger_client.models.create_payment_method_common import CreatePaymentMethodCommon
from swagger_client.models.create_payment_method_credit_card import CreatePaymentMethodCreditCard
from swagger_client.models.create_payment_method_google_pay_adyen_chase import CreatePaymentMethodGooglePayAdyenChase
from swagger_client.models.create_payment_method_pay_pal_adaptive import CreatePaymentMethodPayPalAdaptive
from swagger_client.models.create_payment_type import CreatePaymentType
from swagger_client.models.create_stored_credential_profile_request import CreateStoredCredentialProfileRequest
from swagger_client.models.create_subscribe_to_product import CreateSubscribeToProduct
from swagger_client.models.create_subscription import CreateSubscription
from swagger_client.models.create_subscription_new_subscription_owner_account import CreateSubscriptionNewSubscriptionOwnerAccount
from swagger_client.models.create_subscription_terms import CreateSubscriptionTerms
from swagger_client.models.create_template_request_content import CreateTemplateRequestContent
from swagger_client.models.credit_card import CreditCard
from swagger_client.models.credit_memo_apply_debit_memo_item_request_type import CreditMemoApplyDebitMemoItemRequestType
from swagger_client.models.credit_memo_apply_debit_memo_request_type import CreditMemoApplyDebitMemoRequestType
from swagger_client.models.credit_memo_apply_invoice_item_request_type import CreditMemoApplyInvoiceItemRequestType
from swagger_client.models.credit_memo_apply_invoice_request_type import CreditMemoApplyInvoiceRequestType
from swagger_client.models.credit_memo_entity_prefix import CreditMemoEntityPrefix
from swagger_client.models.credit_memo_from_charge_custom_rates_type import CreditMemoFromChargeCustomRatesType
from swagger_client.models.credit_memo_from_charge_detail_type import CreditMemoFromChargeDetailType
from swagger_client.models.credit_memo_from_charge_type import CreditMemoFromChargeType
from swagger_client.models.credit_memo_from_invoice_type import CreditMemoFromInvoiceType
from swagger_client.models.credit_memo_item_from_invoice_item_type import CreditMemoItemFromInvoiceItemType
from swagger_client.models.credit_memo_item_from_write_off_invoice import CreditMemoItemFromWriteOffInvoice
from swagger_client.models.credit_memo_item_object_custom_fields import CreditMemoItemObjectCustomFields
from swagger_client.models.credit_memo_object_custom_fields import CreditMemoObjectCustomFields
from swagger_client.models.credit_memo_object_ns_fields import CreditMemoObjectNSFields
from swagger_client.models.credit_memo_response_type import CreditMemoResponseType
from swagger_client.models.credit_memo_tax_item_from_invoice_tax_item_type import CreditMemoTaxItemFromInvoiceTaxItemType
from swagger_client.models.credit_memo_tax_item_from_invoice_tax_item_type_finance_information import CreditMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation
from swagger_client.models.credit_memo_unapply_debit_memo_item_request_type import CreditMemoUnapplyDebitMemoItemRequestType
from swagger_client.models.credit_memo_unapply_debit_memo_request_type import CreditMemoUnapplyDebitMemoRequestType
from swagger_client.models.credit_memo_unapply_invoice_item_request_type import CreditMemoUnapplyInvoiceItemRequestType
from swagger_client.models.credit_memo_unapply_invoice_request_type import CreditMemoUnapplyInvoiceRequestType
from swagger_client.models.credit_memos_from_charges import CreditMemosFromCharges
from swagger_client.models.credit_memos_from_invoices import CreditMemosFromInvoices
from swagger_client.models.credit_taxation_item_object_custom_fields import CreditTaxationItemObjectCustomFields
from swagger_client.models.custom_account_payment_method import CustomAccountPaymentMethod
from swagger_client.models.custom_fields import CustomFields
from swagger_client.models.custom_object_all_fields_definition import CustomObjectAllFieldsDefinition
from swagger_client.models.custom_object_bulk_delete_filter import CustomObjectBulkDeleteFilter
from swagger_client.models.custom_object_bulk_delete_filter_condition import CustomObjectBulkDeleteFilterCondition
from swagger_client.models.custom_object_bulk_job_error_response import CustomObjectBulkJobErrorResponse
from swagger_client.models.custom_object_bulk_job_error_response_collection import CustomObjectBulkJobErrorResponseCollection
from swagger_client.models.custom_object_bulk_job_request import CustomObjectBulkJobRequest
from swagger_client.models.custom_object_bulk_job_response import CustomObjectBulkJobResponse
from swagger_client.models.custom_object_bulk_job_response_collection import CustomObjectBulkJobResponseCollection
from swagger_client.models.custom_object_bulk_job_response_error import CustomObjectBulkJobResponseError
from swagger_client.models.custom_object_custom_field_definition import CustomObjectCustomFieldDefinition
from swagger_client.models.custom_object_custom_field_definition_update import CustomObjectCustomFieldDefinitionUpdate
from swagger_client.models.custom_object_custom_fields_definition import CustomObjectCustomFieldsDefinition
from swagger_client.models.custom_object_definition import CustomObjectDefinition
from swagger_client.models.custom_object_definition_schema import CustomObjectDefinitionSchema
from swagger_client.models.custom_object_definition_update_action_request import CustomObjectDefinitionUpdateActionRequest
from swagger_client.models.custom_object_definition_update_action_response import CustomObjectDefinitionUpdateActionResponse
from swagger_client.models.custom_object_definitions import CustomObjectDefinitions
from swagger_client.models.custom_object_record_batch_action import CustomObjectRecordBatchAction
from swagger_client.models.custom_object_record_batch_request import CustomObjectRecordBatchRequest
from swagger_client.models.custom_object_record_batch_update_mapping import CustomObjectRecordBatchUpdateMapping
from swagger_client.models.custom_object_record_with_all_fields import CustomObjectRecordWithAllFields
from swagger_client.models.custom_object_record_with_only_custom_fields import CustomObjectRecordWithOnlyCustomFields
from swagger_client.models.custom_object_records_batch_update_partial_success_response import CustomObjectRecordsBatchUpdatePartialSuccessResponse
from swagger_client.models.custom_object_records_error_response import CustomObjectRecordsErrorResponse
from swagger_client.models.custom_object_records_throttled_response import CustomObjectRecordsThrottledResponse
from swagger_client.models.custom_object_records_with_error import CustomObjectRecordsWithError
from swagger_client.models.data_access_control_field import DataAccessControlField
from swagger_client.models.data_query_error_response import DataQueryErrorResponse
from swagger_client.models.data_query_job import DataQueryJob
from swagger_client.models.data_query_job_cancelled import DataQueryJobCancelled
from swagger_client.models.data_query_job_common import DataQueryJobCommon
from swagger_client.models.debit_memo_collect_request import DebitMemoCollectRequest
from swagger_client.models.debit_memo_collect_request_payment import DebitMemoCollectRequestPayment
from swagger_client.models.debit_memo_collect_response import DebitMemoCollectResponse
from swagger_client.models.debit_memo_collect_response_applied_credit_memos import DebitMemoCollectResponseAppliedCreditMemos
from swagger_client.models.debit_memo_collect_response_applied_payments import DebitMemoCollectResponseAppliedPayments
from swagger_client.models.debit_memo_entity_prefix import DebitMemoEntityPrefix
from swagger_client.models.debit_memo_from_charge_custom_rates_type import DebitMemoFromChargeCustomRatesType
from swagger_client.models.debit_memo_from_charge_detail_type import DebitMemoFromChargeDetailType
from swagger_client.models.debit_memo_from_charge_type import DebitMemoFromChargeType
from swagger_client.models.debit_memo_from_invoice_type import DebitMemoFromInvoiceType
from swagger_client.models.debit_memo_item_from_invoice_item_type import DebitMemoItemFromInvoiceItemType
from swagger_client.models.debit_memo_item_object_custom_fields import DebitMemoItemObjectCustomFields
from swagger_client.models.debit_memo_object_custom_fields import DebitMemoObjectCustomFields
from swagger_client.models.debit_memo_object_custom_fields_cm_write_off import DebitMemoObjectCustomFieldsCMWriteOff
from swagger_client.models.debit_memo_object_ns_fields import DebitMemoObjectNSFields
from swagger_client.models.debit_memo_tax_item_from_invoice_tax_item_type import DebitMemoTaxItemFromInvoiceTaxItemType
from swagger_client.models.debit_memo_tax_item_from_invoice_tax_item_type_finance_information import DebitMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation
from swagger_client.models.debit_memos_from_charges import DebitMemosFromCharges
from swagger_client.models.debit_memos_from_invoices import DebitMemosFromInvoices
from swagger_client.models.debit_taxation_item_object_custom_fields import DebitTaxationItemObjectCustomFields
from swagger_client.models.delete_account_response_type import DeleteAccountResponseType
from swagger_client.models.delete_account_response_type_reasons import DeleteAccountResponseTypeReasons
from swagger_client.models.delete_batch_query_job_response import DeleteBatchQueryJobResponse
from swagger_client.models.delete_data_query_job_response import DeleteDataQueryJobResponse
from swagger_client.models.delete_invoice_response_type import DeleteInvoiceResponseType
from swagger_client.models.delete_result import DeleteResult
from swagger_client.models.delete_workflow_error import DeleteWorkflowError
from swagger_client.models.delete_workflow_success import DeleteWorkflowSuccess
from swagger_client.models.deleted_record import DeletedRecord
from swagger_client.models.deleted_record1 import DeletedRecord1
from swagger_client.models.delivery_schedule_params import DeliveryScheduleParams
from swagger_client.models.detailed_workflow import DetailedWorkflow
from swagger_client.models.discount_item_object_custom_fields import DiscountItemObjectCustomFields
from swagger_client.models.discount_item_object_ns_fields import DiscountItemObjectNSFields
from swagger_client.models.discount_pricing_override import DiscountPricingOverride
from swagger_client.models.discount_pricing_update import DiscountPricingUpdate
from swagger_client.models.end_conditions import EndConditions
from swagger_client.models.error401 import Error401
from swagger_client.models.error_response import ErrorResponse
from swagger_client.models.error_response401_record import ErrorResponse401Record
from swagger_client.models.error_response_reasons import ErrorResponseReasons
from swagger_client.models.event_trigger import EventTrigger
from swagger_client.models.event_type import EventType
from swagger_client.models.execute_invoice_schedule_bill_run_response import ExecuteInvoiceScheduleBillRunResponse
from swagger_client.models.export_workflow_version_response import ExportWorkflowVersionResponse
from swagger_client.models.fields_additional_properties import FieldsAdditionalProperties
from swagger_client.models.fields_additional_properties_for_post_definition import FieldsAdditionalPropertiesForPostDefinition
from swagger_client.models.filter_rule_parameter_definition import FilterRuleParameterDefinition
from swagger_client.models.filter_rule_parameter_definitions import FilterRuleParameterDefinitions
from swagger_client.models.filter_rule_parameter_values import FilterRuleParameterValues
from swagger_client.models.fulfillment_common import FulfillmentCommon
from swagger_client.models.fulfillment_custom_fields import FulfillmentCustomFields
from swagger_client.models.fulfillment_get import FulfillmentGet
from swagger_client.models.fulfillment_item_common import FulfillmentItemCommon
from swagger_client.models.fulfillment_item_custom_fields import FulfillmentItemCustomFields
from swagger_client.models.fulfillment_item_get import FulfillmentItemGet
from swagger_client.models.fulfillment_item_post import FulfillmentItemPost
from swagger_client.models.fulfillment_item_post_from_fulfillment_post import FulfillmentItemPostFromFulfillmentPost
from swagger_client.models.fulfillment_item_put import FulfillmentItemPut
from swagger_client.models.fulfillment_post import FulfillmentPost
from swagger_client.models.fulfillment_put import FulfillmentPut
from swagger_client.models.geta_payment_gatway_response import GETAPaymentGatwayResponse
from swagger_client.models.getar_payment_type import GETARPaymentType
from swagger_client.models.getar_payment_type_with_payment_option import GETARPaymentTypeWithPaymentOption
from swagger_client.models.getar_payment_typewith_success import GETARPaymentTypewithSuccess
from swagger_client.models.get_account_pm_account_holder_info import GETAccountPMAccountHolderInfo
from swagger_client.models.get_account_payment_method_type import GETAccountPaymentMethodType
from swagger_client.models.get_account_summary_invoice_type import GETAccountSummaryInvoiceType
from swagger_client.models.get_account_summary_payment_invoice_type import GETAccountSummaryPaymentInvoiceType
from swagger_client.models.get_account_summary_payment_type import GETAccountSummaryPaymentType
from swagger_client.models.get_account_summary_subscription_rate_plan_type import GETAccountSummarySubscriptionRatePlanType
from swagger_client.models.get_account_summary_subscription_type import GETAccountSummarySubscriptionType
from swagger_client.models.get_account_summary_type import GETAccountSummaryType
from swagger_client.models.get_account_summary_type_basic_info import GETAccountSummaryTypeBasicInfo
from swagger_client.models.get_account_summary_type_bill_to_contact import GETAccountSummaryTypeBillToContact
from swagger_client.models.get_account_summary_type_sold_to_contact import GETAccountSummaryTypeSoldToContact
from swagger_client.models.get_account_summary_type_tax_info import GETAccountSummaryTypeTaxInfo
from swagger_client.models.get_account_summary_usage_type import GETAccountSummaryUsageType
from swagger_client.models.get_account_type import GETAccountType
from swagger_client.models.get_account_type_basic_info import GETAccountTypeBasicInfo
from swagger_client.models.get_account_type_bill_to_contact import GETAccountTypeBillToContact
from swagger_client.models.get_account_type_billing_and_payment import GETAccountTypeBillingAndPayment
from swagger_client.models.get_account_type_metrics import GETAccountTypeMetrics
from swagger_client.models.get_account_type_sold_to_contact import GETAccountTypeSoldToContact
from swagger_client.models.get_accounting_code_item_type import GETAccountingCodeItemType
from swagger_client.models.get_accounting_code_item_without_success_type import GETAccountingCodeItemWithoutSuccessType
from swagger_client.models.get_accounting_codes_type import GETAccountingCodesType
from swagger_client.models.get_accounting_period_type import GETAccountingPeriodType
from swagger_client.models.get_accounting_period_without_success_type import GETAccountingPeriodWithoutSuccessType
from swagger_client.models.get_accounting_periods_type import GETAccountingPeriodsType
from swagger_client.models.get_adjustments_by_subscription_number_response_type import GETAdjustmentsBySubscriptionNumberResponseType
from swagger_client.models.get_adjustments_response_type import GETAdjustmentsResponseType
from swagger_client.models.get_all_custom_object_definitions_in_namespace_response import GETAllCustomObjectDefinitionsInNamespaceResponse
from swagger_client.models.get_attachment_response_type import GETAttachmentResponseType
from swagger_client.models.get_attachment_response_without_success_type import GETAttachmentResponseWithoutSuccessType
from swagger_client.models.get_attachments_response_type import GETAttachmentsResponseType
from swagger_client.models.get_billing_document_files_deletion_job_response import GETBillingDocumentFilesDeletionJobResponse
from swagger_client.models.get_billing_documents_response_type import GETBillingDocumentsResponseType
from swagger_client.models.getcm_tax_item_type import GETCMTaxItemType
from swagger_client.models.getcm_tax_item_type_new import GETCMTaxItemTypeNew
from swagger_client.models.get_callout_history_vo_type import GETCalloutHistoryVOType
from swagger_client.models.get_callout_history_vos_type import GETCalloutHistoryVOsType
from swagger_client.models.get_cancel_adjustment_response_type import GETCancelAdjustmentResponseType
from swagger_client.models.get_catalog_group_product_rate_plan_response import GETCatalogGroupProductRatePlanResponse
from swagger_client.models.get_catalog_type import GETCatalogType
from swagger_client.models.get_contact_snapshot_response import GETContactSnapshotResponse
from swagger_client.models.get_credit_memo_collection_type import GETCreditMemoCollectionType
from swagger_client.models.get_credit_memo_item_part_type import GETCreditMemoItemPartType
from swagger_client.models.get_credit_memo_item_part_typewith_success import GETCreditMemoItemPartTypewithSuccess
from swagger_client.models.get_credit_memo_item_parts_collection_type import GETCreditMemoItemPartsCollectionType
from swagger_client.models.get_credit_memo_item_type import GETCreditMemoItemType
from swagger_client.models.get_credit_memo_item_typewith_success import GETCreditMemoItemTypewithSuccess
from swagger_client.models.get_credit_memo_items_list_type import GETCreditMemoItemsListType
from swagger_client.models.get_credit_memo_part_type import GETCreditMemoPartType
from swagger_client.models.get_credit_memo_part_typewith_success import GETCreditMemoPartTypewithSuccess
from swagger_client.models.get_credit_memo_parts_collection_type import GETCreditMemoPartsCollectionType
from swagger_client.models.get_credit_memo_type import GETCreditMemoType
from swagger_client.models.get_credit_memo_typewith_success import GETCreditMemoTypewithSuccess
from swagger_client.models.get_custom_exchange_rates_data_type import GETCustomExchangeRatesDataType
from swagger_client.models.get_custom_exchange_rates_type import GETCustomExchangeRatesType
from swagger_client.models.getdm_tax_item_type import GETDMTaxItemType
from swagger_client.models.getdm_tax_item_type_new import GETDMTaxItemTypeNew
from swagger_client.models.get_debit_memo_collection_type import GETDebitMemoCollectionType
from swagger_client.models.get_debit_memo_item_collection_type import GETDebitMemoItemCollectionType
from swagger_client.models.get_debit_memo_item_type import GETDebitMemoItemType
from swagger_client.models.get_debit_memo_item_typewith_success import GETDebitMemoItemTypewithSuccess
from swagger_client.models.get_debit_memo_type import GETDebitMemoType
from swagger_client.models.get_debit_memo_typewith_success import GETDebitMemoTypewithSuccess
from swagger_client.models.get_delivery_schedule_type import GETDeliveryScheduleType
from swagger_client.models.get_discount_apply_details_type import GETDiscountApplyDetailsType
from swagger_client.models.get_email_history_vo_type import GETEmailHistoryVOType
from swagger_client.models.get_email_history_vos_type import GETEmailHistoryVOsType
from swagger_client.models.get_interval_price_tier_type import GETIntervalPriceTierType
from swagger_client.models.get_interval_price_type import GETIntervalPriceType
from swagger_client.models.get_invoice_files_response import GETInvoiceFilesResponse
from swagger_client.models.get_invoice_items_response import GETInvoiceItemsResponse
from swagger_client.models.get_invoice_tax_item_type import GETInvoiceTaxItemType
from swagger_client.models.get_invoice_taxation_items_response import GETInvoiceTaxationItemsResponse
from swagger_client.models.get_journal_entries_in_journal_run_type import GETJournalEntriesInJournalRunType
from swagger_client.models.get_journal_entry_detail_type import GETJournalEntryDetailType
from swagger_client.models.get_journal_entry_detail_type_without_success import GETJournalEntryDetailTypeWithoutSuccess
from swagger_client.models.get_journal_entry_item_type import GETJournalEntryItemType
from swagger_client.models.get_journal_entry_segment_type import GETJournalEntrySegmentType
from swagger_client.models.get_journal_run_transaction_type import GETJournalRunTransactionType
from swagger_client.models.get_journal_run_type import GETJournalRunType
from swagger_client.models.get_mass_update_type import GETMassUpdateType
from swagger_client.models.get_offer_charge_configuration import GETOfferChargeConfiguration
from swagger_client.models.get_offer_interval_price import GETOfferIntervalPrice
from swagger_client.models.get_offer_price_book_item import GETOfferPriceBookItem
from swagger_client.models.get_offer_product_rate_plan_charge import GETOfferProductRatePlanCharge
from swagger_client.models.get_offer_response import GETOfferResponse
from swagger_client.models.get_offer_tier import GETOfferTier
from swagger_client.models.get_open_payment_method_type_revision_response import GETOpenPaymentMethodTypeRevisionResponse
from swagger_client.models.getpm_account_holder_info import GETPMAccountHolderInfo
from swagger_client.models.get_payment_gatways_response import GETPaymentGatwaysResponse
from swagger_client.models.get_payment_item_part_collection_type import GETPaymentItemPartCollectionType
from swagger_client.models.get_payment_item_part_type import GETPaymentItemPartType
from swagger_client.models.get_payment_item_part_typewith_success import GETPaymentItemPartTypewithSuccess
from swagger_client.models.get_payment_method_response import GETPaymentMethodResponse
from swagger_client.models.get_payment_method_response_ach import GETPaymentMethodResponseACH
from swagger_client.models.get_payment_method_response_ach_for_account import GETPaymentMethodResponseACHForAccount
from swagger_client.models.get_payment_method_response_apple_pay import GETPaymentMethodResponseApplePay
from swagger_client.models.get_payment_method_response_apple_pay_for_account import GETPaymentMethodResponseApplePayForAccount
from swagger_client.models.get_payment_method_response_bank_transfer import GETPaymentMethodResponseBankTransfer
from swagger_client.models.get_payment_method_response_bank_transfer_for_account import GETPaymentMethodResponseBankTransferForAccount
from swagger_client.models.get_payment_method_response_credit_card import GETPaymentMethodResponseCreditCard
from swagger_client.models.get_payment_method_response_credit_card_for_account import GETPaymentMethodResponseCreditCardForAccount
from swagger_client.models.get_payment_method_response_for_account import GETPaymentMethodResponseForAccount
from swagger_client.models.get_payment_method_response_google_pay import GETPaymentMethodResponseGooglePay
from swagger_client.models.get_payment_method_response_google_pay_for_account import GETPaymentMethodResponseGooglePayForAccount
from swagger_client.models.get_payment_method_response_pay_pal import GETPaymentMethodResponsePayPal
from swagger_client.models.get_payment_method_response_pay_pal_for_account import GETPaymentMethodResponsePayPalForAccount
from swagger_client.models.get_payment_method_updater_instances_response import GETPaymentMethodUpdaterInstancesResponse
from swagger_client.models.get_payment_method_updater_instances_response_updaters import GETPaymentMethodUpdaterInstancesResponseUpdaters
from swagger_client.models.get_payment_part_type import GETPaymentPartType
from swagger_client.models.get_payment_part_typewith_success import GETPaymentPartTypewithSuccess
from swagger_client.models.get_payment_parts_collection_type import GETPaymentPartsCollectionType
from swagger_client.models.get_payment_run_collection_type import GETPaymentRunCollectionType
from swagger_client.models.get_payment_run_data_array_response import GETPaymentRunDataArrayResponse
from swagger_client.models.get_payment_run_data_element_response import GETPaymentRunDataElementResponse
from swagger_client.models.get_payment_run_data_transaction_element_response import GETPaymentRunDataTransactionElementResponse
from swagger_client.models.get_payment_run_summary_response import GETPaymentRunSummaryResponse
from swagger_client.models.get_payment_run_summary_total_values import GETPaymentRunSummaryTotalValues
from swagger_client.models.get_payment_run_type import GETPaymentRunType
from swagger_client.models.get_payment_schedule_item_response import GETPaymentScheduleItemResponse
from swagger_client.models.get_payment_schedule_response import GETPaymentScheduleResponse
from swagger_client.models.get_payment_schedule_statistic_response import GETPaymentScheduleStatisticResponse
from swagger_client.models.get_payment_schedule_statistic_response_payment_schedule_items import GETPaymentScheduleStatisticResponsePaymentScheduleItems
from swagger_client.models.get_payment_schedules_response import GETPaymentSchedulesResponse
from swagger_client.models.get_price_book_item_interval_price import GETPriceBookItemIntervalPrice
from swagger_client.models.get_price_book_item_response import GETPriceBookItemResponse
from swagger_client.models.get_price_book_item_tier import GETPriceBookItemTier
from swagger_client.models.get_product_discount_apply_details_type import GETProductDiscountApplyDetailsType
from swagger_client.models.get_product_rate_plan_charge_delivery_schedule import GETProductRatePlanChargeDeliverySchedule
from swagger_client.models.get_product_rate_plan_charge_pricing_tier_type import GETProductRatePlanChargePricingTierType
from swagger_client.models.get_product_rate_plan_charge_pricing_type import GETProductRatePlanChargePricingType
from swagger_client.models.get_product_rate_plan_charge_type import GETProductRatePlanChargeType
from swagger_client.models.get_product_rate_plan_type import GETProductRatePlanType
from swagger_client.models.get_product_rate_plan_with_external_id_multi_response import GETProductRatePlanWithExternalIdMultiResponse
from swagger_client.models.get_product_rate_plan_with_external_id_multi_response_inner import GETProductRatePlanWithExternalIdMultiResponseInner
from swagger_client.models.get_product_rate_plan_with_external_id_response import GETProductRatePlanWithExternalIdResponse
from swagger_client.models.get_product_rate_plans_response import GETProductRatePlansResponse
from swagger_client.models.get_product_type import GETProductType
from swagger_client.models.get_public_email_template_response import GETPublicEmailTemplateResponse
from swagger_client.models.get_public_notification_definition_response import GETPublicNotificationDefinitionResponse
from swagger_client.models.get_public_notification_definition_response_callout import GETPublicNotificationDefinitionResponseCallout
from swagger_client.models.get_public_notification_definition_response_filter_rule import GETPublicNotificationDefinitionResponseFilterRule
from swagger_client.models.get_ramp_by_ramp_number_response_type import GETRampByRampNumberResponseType
from swagger_client.models.get_ramp_metrics_by_order_number_response_type import GETRampMetricsByOrderNumberResponseType
from swagger_client.models.get_ramp_metrics_by_ramp_number_response_type import GETRampMetricsByRampNumberResponseType
from swagger_client.models.get_ramp_metrics_by_subscription_key_response_type import GETRampMetricsBySubscriptionKeyResponseType
from swagger_client.models.get_ramps_by_subscription_key_response_type import GETRampsBySubscriptionKeyResponseType
from swagger_client.models.get_refund_collection_type import GETRefundCollectionType
from swagger_client.models.get_refund_credit_memo_type import GETRefundCreditMemoType
from swagger_client.models.get_refund_item_part_collection_type import GETRefundItemPartCollectionType
from swagger_client.models.get_refund_item_part_type import GETRefundItemPartType
from swagger_client.models.get_refund_item_part_typewith_success import GETRefundItemPartTypewithSuccess
from swagger_client.models.get_refund_part_collection_type import GETRefundPartCollectionType
from swagger_client.models.get_refund_payment_type import GETRefundPaymentType
from swagger_client.models.get_refund_type import GETRefundType
from swagger_client.models.get_refund_typewith_success import GETRefundTypewithSuccess
from swagger_client.models.get_sequence_set_response import GETSequenceSetResponse
from swagger_client.models.get_sequence_sets_response import GETSequenceSetsResponse
from swagger_client.models.get_subscription_offer_type import GETSubscriptionOfferType
from swagger_client.models.get_subscription_product_feature_type import GETSubscriptionProductFeatureType
from swagger_client.models.get_subscription_rate_plan_charges_type import GETSubscriptionRatePlanChargesType
from swagger_client.models.get_subscription_rate_plan_type import GETSubscriptionRatePlanType
from swagger_client.models.get_subscription_status_history_type import GETSubscriptionStatusHistoryType
from swagger_client.models.get_subscription_type import GETSubscriptionType
from swagger_client.models.get_subscription_type_with_success import GETSubscriptionTypeWithSuccess
from swagger_client.models.get_subscription_wrapper import GETSubscriptionWrapper
from swagger_client.models.get_taxation_item_list_type import GETTaxationItemListType
from swagger_client.models.get_taxation_item_type import GETTaxationItemType
from swagger_client.models.get_taxation_item_typewith_success import GETTaxationItemTypewithSuccess
from swagger_client.models.get_taxation_items_of_credit_memo_item_type import GETTaxationItemsOfCreditMemoItemType
from swagger_client.models.get_taxation_items_of_debit_memo_item_type import GETTaxationItemsOfDebitMemoItemType
from swagger_client.models.get_tier_type import GETTierType
from swagger_client.models.get_usage_rate_detail_wrapper import GETUsageRateDetailWrapper
from swagger_client.models.get_usage_rate_detail_wrapper_data import GETUsageRateDetailWrapperData
from swagger_client.models.get_usage_type import GETUsageType
from swagger_client.models.get_usage_wrapper import GETUsageWrapper
from swagger_client.models.generate_billing_document_response_type import GenerateBillingDocumentResponseType
from swagger_client.models.get_aggregate_query_job_response import GetAggregateQueryJobResponse
from swagger_client.models.get_all_orders_response_type import GetAllOrdersResponseType
from swagger_client.models.get_api_volume_summary_response import GetApiVolumeSummaryResponse
from swagger_client.models.get_bill_run_response_type import GetBillRunResponseType
from swagger_client.models.get_billing_doc_volume_summary_response import GetBillingDocVolumeSummaryResponse
from swagger_client.models.get_billing_preview_run_response import GetBillingPreviewRunResponse
from swagger_client.models.get_data_query_job_response import GetDataQueryJobResponse
from swagger_client.models.get_data_query_jobs_response import GetDataQueryJobsResponse
from swagger_client.models.get_debit_memo_application_part_collection_type import GetDebitMemoApplicationPartCollectionType
from swagger_client.models.get_debit_memo_application_part_type import GetDebitMemoApplicationPartType
from swagger_client.models.get_fulfillment_item_response_type import GetFulfillmentItemResponseType
from swagger_client.models.get_fulfillment_response_type import GetFulfillmentResponseType
from swagger_client.models.get_hosted_page_type import GetHostedPageType
from swagger_client.models.get_hosted_pages_type import GetHostedPagesType
from swagger_client.models.get_invoice_application_part_collection_type import GetInvoiceApplicationPartCollectionType
from swagger_client.models.get_invoice_application_part_type import GetInvoiceApplicationPartType
from swagger_client.models.get_offer_rate_plan_override import GetOfferRatePlanOverride
from swagger_client.models.get_offer_rate_plan_update import GetOfferRatePlanUpdate
from swagger_client.models.get_operation_job_response_type import GetOperationJobResponseType
from swagger_client.models.get_order_action_rate_plan_response import GetOrderActionRatePlanResponse
from swagger_client.models.get_order_line_item_response_type import GetOrderLineItemResponseType
from swagger_client.models.get_order_response import GetOrderResponse
from swagger_client.models.get_order_resume import GetOrderResume
from swagger_client.models.get_order_suspend import GetOrderSuspend
from swagger_client.models.get_orders_response import GetOrdersResponse
from swagger_client.models.get_payment_volume_summary_response import GetPaymentVolumeSummaryResponse
from swagger_client.models.get_product_feature_type import GetProductFeatureType
from swagger_client.models.get_scheduled_event_response import GetScheduledEventResponse
from swagger_client.models.get_scheduled_event_response_parameters import GetScheduledEventResponseParameters
from swagger_client.models.get_stored_credential_profiles_response import GetStoredCredentialProfilesResponse
from swagger_client.models.get_stored_credential_profiles_response_profiles import GetStoredCredentialProfilesResponseProfiles
from swagger_client.models.get_versions_response import GetVersionsResponse
from swagger_client.models.get_workflow_response import GetWorkflowResponse
from swagger_client.models.get_workflow_response_tasks import GetWorkflowResponseTasks
from swagger_client.models.get_workflows_response import GetWorkflowsResponse
from swagger_client.models.get_workflows_response_pagination import GetWorkflowsResponsePagination
from swagger_client.models.initial_term import InitialTerm
from swagger_client.models.inline_response200 import InlineResponse200
from swagger_client.models.inline_response2001 import InlineResponse2001
from swagger_client.models.inline_response2002 import InlineResponse2002
from swagger_client.models.inline_response2003 import InlineResponse2003
from swagger_client.models.inline_response2004 import InlineResponse2004
from swagger_client.models.inline_response2005 import InlineResponse2005
from swagger_client.models.inline_response202 import InlineResponse202
from swagger_client.models.inline_response2021 import InlineResponse2021
from swagger_client.models.inline_response400 import InlineResponse400
from swagger_client.models.inline_response406 import InlineResponse406
from swagger_client.models.invoice_entity_prefix import InvoiceEntityPrefix
from swagger_client.models.invoice_file import InvoiceFile
from swagger_client.models.invoice_item import InvoiceItem
from swagger_client.models.invoice_item_object_custom_fields import InvoiceItemObjectCustomFields
from swagger_client.models.invoice_item_object_ns_fields import InvoiceItemObjectNSFields
from swagger_client.models.invoice_item_preview_result import InvoiceItemPreviewResult
from swagger_client.models.invoice_item_preview_result_additional_info import InvoiceItemPreviewResultAdditionalInfo
from swagger_client.models.invoice_item_preview_result_taxation_items import InvoiceItemPreviewResultTaxationItems
from swagger_client.models.invoice_object_custom_fields import InvoiceObjectCustomFields
from swagger_client.models.invoice_object_ns_fields import InvoiceObjectNSFields
from swagger_client.models.invoice_post_response_type import InvoicePostResponseType
from swagger_client.models.invoice_post_type import InvoicePostType
from swagger_client.models.invoice_response_type import InvoiceResponseType
from swagger_client.models.invoice_schedule_custom_fields import InvoiceScheduleCustomFields
from swagger_client.models.invoice_schedule_item_custom_fields import InvoiceScheduleItemCustomFields
from swagger_client.models.invoice_schedule_responses import InvoiceScheduleResponses
from swagger_client.models.invoice_schedule_specific_subscriptions import InvoiceScheduleSpecificSubscriptions
from swagger_client.models.invoice_with_custom_rates_type import InvoiceWithCustomRatesType
from swagger_client.models.invoices_batch_post_response_type import InvoicesBatchPostResponseType
from swagger_client.models.job_result import JobResult
from swagger_client.models.job_result_order_line_items import JobResultOrderLineItems
from swagger_client.models.job_result_ramps import JobResultRamps
from swagger_client.models.job_result_subscriptions import JobResultSubscriptions
from swagger_client.models.journal_entry_item_object_custom_fields import JournalEntryItemObjectCustomFields
from swagger_client.models.journal_entry_object_custom_fields import JournalEntryObjectCustomFields
from swagger_client.models.json_node import JsonNode
from swagger_client.models.last_term import LastTerm
from swagger_client.models.linkage import Linkage
from swagger_client.models.linked_payment_id import LinkedPaymentID
from swagger_client.models.list_all_catalog_groups_response import ListAllCatalogGroupsResponse
from swagger_client.models.list_all_offers_response import ListAllOffersResponse
from swagger_client.models.list_all_price_book_items_response import ListAllPriceBookItemsResponse
from swagger_client.models.list_all_settings_response import ListAllSettingsResponse
from swagger_client.models.list_of_exchange_rates import ListOfExchangeRates
from swagger_client.models.migration_client_response import MigrationClientResponse
from swagger_client.models.migration_component_content import MigrationComponentContent
from swagger_client.models.migration_update_custom_object_definitions_request import MigrationUpdateCustomObjectDefinitionsRequest
from swagger_client.models.migration_update_custom_object_definitions_response import MigrationUpdateCustomObjectDefinitionsResponse
from swagger_client.models.modified_stored_credential_profile_response import ModifiedStoredCredentialProfileResponse
from swagger_client.models.next_run_response_type import NextRunResponseType
from swagger_client.models.notifications_history_deletion_task_response import NotificationsHistoryDeletionTaskResponse
from swagger_client.models.offer_override import OfferOverride
from swagger_client.models.offer_update import OfferUpdate
from swagger_client.models.one_time_flat_fee_pricing_override import OneTimeFlatFeePricingOverride
from swagger_client.models.one_time_per_unit_pricing_override import OneTimePerUnitPricingOverride
from swagger_client.models.one_time_tiered_pricing_override import OneTimeTieredPricingOverride
from swagger_client.models.one_time_volume_pricing_override import OneTimeVolumePricingOverride
from swagger_client.models.open_payment_method_type_request_fields import OpenPaymentMethodTypeRequestFields
from swagger_client.models.open_payment_method_type_response_fields import OpenPaymentMethodTypeResponseFields
from swagger_client.models.options import Options
from swagger_client.models.order import Order
from swagger_client.models.order_action import OrderAction
from swagger_client.models.order_action_add_product import OrderActionAddProduct
from swagger_client.models.order_action_common import OrderActionCommon
from swagger_client.models.order_action_custom_fields import OrderActionCustomFields
from swagger_client.models.order_action_object_custom_fields import OrderActionObjectCustomFields
from swagger_client.models.order_action_put import OrderActionPut
from swagger_client.models.order_action_rate_plan_amendment import OrderActionRatePlanAmendment
from swagger_client.models.order_action_rate_plan_billing_update import OrderActionRatePlanBillingUpdate
from swagger_client.models.order_action_rate_plan_charge_model_data_override import OrderActionRatePlanChargeModelDataOverride
from swagger_client.models.order_action_rate_plan_charge_model_data_override_charge_model_configuration import OrderActionRatePlanChargeModelDataOverrideChargeModelConfiguration
from swagger_client.models.order_action_rate_plan_charge_override import OrderActionRatePlanChargeOverride
from swagger_client.models.order_action_rate_plan_charge_override_pricing import OrderActionRatePlanChargeOverridePricing
from swagger_client.models.order_action_rate_plan_charge_tier import OrderActionRatePlanChargeTier
from swagger_client.models.order_action_rate_plan_charge_update import OrderActionRatePlanChargeUpdate
from swagger_client.models.order_action_rate_plan_charge_update_billing import OrderActionRatePlanChargeUpdateBilling
from swagger_client.models.order_action_rate_plan_discount_pricing_override import OrderActionRatePlanDiscountPricingOverride
from swagger_client.models.order_action_rate_plan_discount_pricing_update import OrderActionRatePlanDiscountPricingUpdate
from swagger_client.models.order_action_rate_plan_end_conditions import OrderActionRatePlanEndConditions
from swagger_client.models.order_action_rate_plan_one_time_flat_fee_pricing_override import OrderActionRatePlanOneTimeFlatFeePricingOverride
from swagger_client.models.order_action_rate_plan_one_time_per_unit_pricing_override import OrderActionRatePlanOneTimePerUnitPricingOverride
from swagger_client.models.order_action_rate_plan_one_time_tiered_pricing_override import OrderActionRatePlanOneTimeTieredPricingOverride
from swagger_client.models.order_action_rate_plan_one_time_volume_pricing_override import OrderActionRatePlanOneTimeVolumePricingOverride
from swagger_client.models.order_action_rate_plan_order import OrderActionRatePlanOrder
from swagger_client.models.order_action_rate_plan_order_action import OrderActionRatePlanOrderAction
from swagger_client.models.order_action_rate_plan_order_action_object_custom_fields import OrderActionRatePlanOrderActionObjectCustomFields
from swagger_client.models.order_action_rate_plan_price_change_params import OrderActionRatePlanPriceChangeParams
from swagger_client.models.order_action_rate_plan_pricing_update import OrderActionRatePlanPricingUpdate
from swagger_client.models.order_action_rate_plan_pricing_update_charge_model_data import OrderActionRatePlanPricingUpdateChargeModelData
from swagger_client.models.order_action_rate_plan_pricing_update_recurring_delivery import OrderActionRatePlanPricingUpdateRecurringDelivery
from swagger_client.models.order_action_rate_plan_rate_plan_charge_object_custom_fields import OrderActionRatePlanRatePlanChargeObjectCustomFields
from swagger_client.models.order_action_rate_plan_rate_plan_object_custom_fields import OrderActionRatePlanRatePlanObjectCustomFields
from swagger_client.models.order_action_rate_plan_rate_plan_override import OrderActionRatePlanRatePlanOverride
from swagger_client.models.order_action_rate_plan_rate_plan_update import OrderActionRatePlanRatePlanUpdate
from swagger_client.models.order_action_rate_plan_recurring_delivery_pricing_override import OrderActionRatePlanRecurringDeliveryPricingOverride
from swagger_client.models.order_action_rate_plan_recurring_delivery_pricing_update import OrderActionRatePlanRecurringDeliveryPricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_flat_fee_pricing_override import OrderActionRatePlanRecurringFlatFeePricingOverride
from swagger_client.models.order_action_rate_plan_recurring_flat_fee_pricing_update import OrderActionRatePlanRecurringFlatFeePricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_per_unit_pricing_override import OrderActionRatePlanRecurringPerUnitPricingOverride
from swagger_client.models.order_action_rate_plan_recurring_per_unit_pricing_update import OrderActionRatePlanRecurringPerUnitPricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_tiered_pricing_override import OrderActionRatePlanRecurringTieredPricingOverride
from swagger_client.models.order_action_rate_plan_recurring_tiered_pricing_update import OrderActionRatePlanRecurringTieredPricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_volume_pricing_override import OrderActionRatePlanRecurringVolumePricingOverride
from swagger_client.models.order_action_rate_plan_recurring_volume_pricing_update import OrderActionRatePlanRecurringVolumePricingUpdate
from swagger_client.models.order_action_rate_plan_remove_product import OrderActionRatePlanRemoveProduct
from swagger_client.models.order_action_rate_plan_trigger_params import OrderActionRatePlanTriggerParams
from swagger_client.models.order_action_rate_plan_usage_flat_fee_pricing_override import OrderActionRatePlanUsageFlatFeePricingOverride
from swagger_client.models.order_action_rate_plan_usage_flat_fee_pricing_update import OrderActionRatePlanUsageFlatFeePricingUpdate
from swagger_client.models.order_action_rate_plan_usage_overage_pricing_override import OrderActionRatePlanUsageOveragePricingOverride
from swagger_client.models.order_action_rate_plan_usage_overage_pricing_update import OrderActionRatePlanUsageOveragePricingUpdate
from swagger_client.models.order_action_rate_plan_usage_per_unit_pricing_override import OrderActionRatePlanUsagePerUnitPricingOverride
from swagger_client.models.order_action_rate_plan_usage_per_unit_pricing_update import OrderActionRatePlanUsagePerUnitPricingUpdate
from swagger_client.models.order_action_rate_plan_usage_tiered_pricing_override import OrderActionRatePlanUsageTieredPricingOverride
from swagger_client.models.order_action_rate_plan_usage_tiered_pricing_update import OrderActionRatePlanUsageTieredPricingUpdate
from swagger_client.models.order_action_rate_plan_usage_tiered_with_overage_pricing_override import OrderActionRatePlanUsageTieredWithOveragePricingOverride
from swagger_client.models.order_action_rate_plan_usage_tiered_with_overage_pricing_update import OrderActionRatePlanUsageTieredWithOveragePricingUpdate
from swagger_client.models.order_action_rate_plan_usage_volume_pricing_override import OrderActionRatePlanUsageVolumePricingOverride
from swagger_client.models.order_action_rate_plan_usage_volume_pricing_update import OrderActionRatePlanUsageVolumePricingUpdate
from swagger_client.models.order_action_update_product import OrderActionUpdateProduct
from swagger_client.models.order_delta_metric import OrderDeltaMetric
from swagger_client.models.order_delta_mrr import OrderDeltaMrr
from swagger_client.models.order_delta_tcb import OrderDeltaTcb
from swagger_client.models.order_delta_tcv import OrderDeltaTcv
from swagger_client.models.order_item import OrderItem
from swagger_client.models.order_line_item import OrderLineItem
from swagger_client.models.order_line_item_common import OrderLineItemCommon
from swagger_client.models.order_line_item_common_post_order import OrderLineItemCommonPostOrder
from swagger_client.models.order_line_item_common_retrieve_order import OrderLineItemCommonRetrieveOrder
from swagger_client.models.order_line_item_common_retrieve_order_line_item import OrderLineItemCommonRetrieveOrderLineItem
from swagger_client.models.order_line_item_custom_fields import OrderLineItemCustomFields
from swagger_client.models.order_line_item_custom_fields_retrieve_order_line_item import OrderLineItemCustomFieldsRetrieveOrderLineItem
from swagger_client.models.order_line_item_retrieve_order import OrderLineItemRetrieveOrder
from swagger_client.models.order_metric import OrderMetric
from swagger_client.models.order_object_custom_fields import OrderObjectCustomFields
from swagger_client.models.order_ramp_interval_metrics import OrderRampIntervalMetrics
from swagger_client.models.order_ramp_metrics import OrderRampMetrics
from swagger_client.models.order_scheduling_options import OrderSchedulingOptions
from swagger_client.models.order_subscriptions import OrderSubscriptions
from swagger_client.models.orders_rate_plan_object_custom_fields import OrdersRatePlanObjectCustomFields
from swagger_client.models.owner_transfer import OwnerTransfer
from swagger_client.models.post_account_pm_mandate_info import POSTAccountPMMandateInfo
from swagger_client.models.post_account_response_type import POSTAccountResponseType
from swagger_client.models.post_account_type import POSTAccountType
from swagger_client.models.post_account_type_bill_to_contact import POSTAccountTypeBillToContact
from swagger_client.models.post_account_type_credit_card import POSTAccountTypeCreditCard
from swagger_client.models.post_account_type_payment_method import POSTAccountTypePaymentMethod
from swagger_client.models.post_account_type_sold_to_contact import POSTAccountTypeSoldToContact
from swagger_client.models.post_account_type_subscription import POSTAccountTypeSubscription
from swagger_client.models.post_accounting_code_response_type import POSTAccountingCodeResponseType
from swagger_client.models.post_accounting_code_type import POSTAccountingCodeType
from swagger_client.models.post_accounting_period_response_type import POSTAccountingPeriodResponseType
from swagger_client.models.post_accounting_period_type import POSTAccountingPeriodType
from swagger_client.models.post_add_items_to_payment_schedule_request import POSTAddItemsToPaymentScheduleRequest
from swagger_client.models.post_adjustment_response_type import POSTAdjustmentResponseType
from swagger_client.models.post_attachment_response_type import POSTAttachmentResponseType
from swagger_client.models.post_authorize_response import POSTAuthorizeResponse
from swagger_client.models.post_authorize_response_payment_gateway_response import POSTAuthorizeResponsePaymentGatewayResponse
from swagger_client.models.post_authorize_response_reasons import POSTAuthorizeResponseReasons
from swagger_client.models.post_billing_document_files_deletion_job_request import POSTBillingDocumentFilesDeletionJobRequest
from swagger_client.models.post_billing_document_files_deletion_job_response import POSTBillingDocumentFilesDeletionJobResponse
from swagger_client.models.post_billing_preview_credit_memo_item import POSTBillingPreviewCreditMemoItem
from swagger_client.models.post_billing_preview_invoice_item import POSTBillingPreviewInvoiceItem
from swagger_client.models.post_bulk_credit_memo_from_invoice_type import POSTBulkCreditMemoFromInvoiceType
from swagger_client.models.post_bulk_credit_memos_request_type import POSTBulkCreditMemosRequestType
from swagger_client.models.post_bulk_debit_memo_from_invoice_type import POSTBulkDebitMemoFromInvoiceType
from swagger_client.models.post_bulk_debit_memos_request_type import POSTBulkDebitMemosRequestType
from swagger_client.models.post_catalog_group_request import POSTCatalogGroupRequest
from swagger_client.models.post_contact_type import POSTContactType
from swagger_client.models.post_create_bill_run_request_type import POSTCreateBillRunRequestType
from swagger_client.models.post_create_billing_adjustment_request_type import POSTCreateBillingAdjustmentRequestType
from swagger_client.models.post_create_billing_adjustment_request_type_exclusion import POSTCreateBillingAdjustmentRequestTypeExclusion
from swagger_client.models.post_create_invoice_schedule_request import POSTCreateInvoiceScheduleRequest
from swagger_client.models.post_create_open_payment_method_type_request import POSTCreateOpenPaymentMethodTypeRequest
from swagger_client.models.post_create_open_payment_method_type_response import POSTCreateOpenPaymentMethodTypeResponse
from swagger_client.models.post_create_or_update_email_template_request import POSTCreateOrUpdateEmailTemplateRequest
from swagger_client.models.post_create_or_update_email_template_request_format import POSTCreateOrUpdateEmailTemplateRequestFormat
from swagger_client.models.post_create_payment_session_request import POSTCreatePaymentSessionRequest
from swagger_client.models.post_create_payment_session_response import POSTCreatePaymentSessionResponse
from swagger_client.models.post_decrypt_response_type import POSTDecryptResponseType
from swagger_client.models.post_decryption_type import POSTDecryptionType
from swagger_client.models.post_delay_authorize_capture import POSTDelayAuthorizeCapture
from swagger_client.models.post_delay_authorize_capture_gateway_options import POSTDelayAuthorizeCaptureGatewayOptions
from swagger_client.models.post_email_billing_docfrom_bill_run_type import POSTEmailBillingDocfromBillRunType
from swagger_client.models.post_execute_invoice_schedule_request import POSTExecuteInvoiceScheduleRequest
from swagger_client.models.post_ineligible_adjustment_response_type import POSTIneligibleAdjustmentResponseType
from swagger_client.models.post_invoice_collect_credit_memos_type import POSTInvoiceCollectCreditMemosType
from swagger_client.models.post_invoice_collect_invoices_type import POSTInvoiceCollectInvoicesType
from swagger_client.models.post_invoice_collect_response_type import POSTInvoiceCollectResponseType
from swagger_client.models.post_invoice_collect_type import POSTInvoiceCollectType
from swagger_client.models.post_invoices_batch_post_type import POSTInvoicesBatchPostType
from swagger_client.models.post_journal_entry_item_type import POSTJournalEntryItemType
from swagger_client.models.post_journal_entry_response_type import POSTJournalEntryResponseType
from swagger_client.models.post_journal_entry_segment_type import POSTJournalEntrySegmentType
from swagger_client.models.post_journal_entry_type import POSTJournalEntryType
from swagger_client.models.post_journal_run_response_type import POSTJournalRunResponseType
from swagger_client.models.post_journal_run_transaction_type import POSTJournalRunTransactionType
from swagger_client.models.post_journal_run_type import POSTJournalRunType
from swagger_client.models.post_mass_update_response_type import POSTMassUpdateResponseType
from swagger_client.models.post_memo_pdf_response import POSTMemoPdfResponse
from swagger_client.models.post_offer_charge_configuration import POSTOfferChargeConfiguration
from swagger_client.models.post_offer_charge_override import POSTOfferChargeOverride
from swagger_client.models.post_offer_interval_price import POSTOfferIntervalPrice
from swagger_client.models.post_offer_price_book_item import POSTOfferPriceBookItem
from swagger_client.models.post_offer_product_rate_plan import POSTOfferProductRatePlan
from swagger_client.models.post_offer_request import POSTOfferRequest
from swagger_client.models.post_offer_response import POSTOfferResponse
from swagger_client.models.post_offer_tier import POSTOfferTier
from swagger_client.models.post_order_async_request_type import POSTOrderAsyncRequestType
from swagger_client.models.post_order_async_request_type_subscriptions import POSTOrderAsyncRequestTypeSubscriptions
from swagger_client.models.post_order_preview_async_request_type import POSTOrderPreviewAsyncRequestType
from swagger_client.models.post_order_preview_async_request_type_subscriptions import POSTOrderPreviewAsyncRequestTypeSubscriptions
from swagger_client.models.post_order_preview_request_type import POSTOrderPreviewRequestType
from swagger_client.models.post_order_request_type import POSTOrderRequestType
from swagger_client.models.post_order_request_type_scheduling_options import POSTOrderRequestTypeSchedulingOptions
from swagger_client.models.postpm_mandate_info import POSTPMMandateInfo
from swagger_client.models.post_payment_method_decryption import POSTPaymentMethodDecryption
from swagger_client.models.post_payment_method_request import POSTPaymentMethodRequest
from swagger_client.models.post_payment_method_response import POSTPaymentMethodResponse
from swagger_client.models.post_payment_method_response_decryption import POSTPaymentMethodResponseDecryption
from swagger_client.models.post_payment_method_response_reasons import POSTPaymentMethodResponseReasons
from swagger_client.models.post_payment_method_updater_batch_request import POSTPaymentMethodUpdaterBatchRequest
from swagger_client.models.post_payment_method_updater_response import POSTPaymentMethodUpdaterResponse
from swagger_client.models.post_payment_method_updater_response_reasons import POSTPaymentMethodUpdaterResponseReasons
from swagger_client.models.post_payment_run_data_element_request import POSTPaymentRunDataElementRequest
from swagger_client.models.post_payment_run_request import POSTPaymentRunRequest
from swagger_client.models.post_payment_schedule_request import POSTPaymentScheduleRequest
from swagger_client.models.post_payment_schedule_response import POSTPaymentScheduleResponse
from swagger_client.models.post_payment_schedules_each import POSTPaymentSchedulesEach
from swagger_client.models.post_payment_schedules_request import POSTPaymentSchedulesRequest
from swagger_client.models.post_payment_schedules_response import POSTPaymentSchedulesResponse
from swagger_client.models.post_preview_billing_adjustment_request_type import POSTPreviewBillingAdjustmentRequestType
from swagger_client.models.post_price_book_item_interval_price import POSTPriceBookItemIntervalPrice
from swagger_client.models.post_price_book_item_request import POSTPriceBookItemRequest
from swagger_client.models.post_price_book_item_tier import POSTPriceBookItemTier
from swagger_client.models.post_public_email_template_request import POSTPublicEmailTemplateRequest
from swagger_client.models.post_public_notification_definition_request import POSTPublicNotificationDefinitionRequest
from swagger_client.models.post_public_notification_definition_request_callout import POSTPublicNotificationDefinitionRequestCallout
from swagger_client.models.post_public_notification_definition_request_filter_rule import POSTPublicNotificationDefinitionRequestFilterRule
from swagger_client.models.postrsa_signature_response_type import POSTRSASignatureResponseType
from swagger_client.models.postrsa_signature_type import POSTRSASignatureType
from swagger_client.models.post_reconcile_refund_request import POSTReconcileRefundRequest
from swagger_client.models.post_reconcile_refund_response import POSTReconcileRefundResponse
from swagger_client.models.post_reconcile_refund_response_finance_information import POSTReconcileRefundResponseFinanceInformation
from swagger_client.models.post_reject_payment_request import POSTRejectPaymentRequest
from swagger_client.models.post_reject_payment_response import POSTRejectPaymentResponse
from swagger_client.models.post_resend_callout_notifications import POSTResendCalloutNotifications
from swagger_client.models.post_resend_email_notifications import POSTResendEmailNotifications
from swagger_client.models.post_retry_payment_schedule_item_info import POSTRetryPaymentScheduleItemInfo
from swagger_client.models.post_retry_payment_schedule_item_request import POSTRetryPaymentScheduleItemRequest
from swagger_client.models.post_retry_payment_schedule_item_response import POSTRetryPaymentScheduleItemResponse
from swagger_client.models.post_reverse_payment_request import POSTReversePaymentRequest
from swagger_client.models.post_reverse_payment_response import POSTReversePaymentResponse
from swagger_client.models.postsc_create_type import POSTScCreateType
from swagger_client.models.post_schedule_item_type import POSTScheduleItemType
from swagger_client.models.post_sequence_set_request import POSTSequenceSetRequest
from swagger_client.models.post_sequence_sets_request import POSTSequenceSetsRequest
from swagger_client.models.post_sequence_sets_response import POSTSequenceSetsResponse
from swagger_client.models.post_settle_payment_request import POSTSettlePaymentRequest
from swagger_client.models.post_settle_payment_response import POSTSettlePaymentResponse
from swagger_client.models.post_srp_create_type import POSTSrpCreateType
from swagger_client.models.post_subscription_cancellation_response_type import POSTSubscriptionCancellationResponseType
from swagger_client.models.post_subscription_cancellation_type import POSTSubscriptionCancellationType
from swagger_client.models.post_subscription_preview_credit_memo_items_type import POSTSubscriptionPreviewCreditMemoItemsType
from swagger_client.models.post_subscription_preview_invoice_items_type import POSTSubscriptionPreviewInvoiceItemsType
from swagger_client.models.post_subscription_preview_response_type import POSTSubscriptionPreviewResponseType
from swagger_client.models.post_subscription_preview_response_type_charge_metrics import POSTSubscriptionPreviewResponseTypeChargeMetrics
from swagger_client.models.post_subscription_preview_response_type_credit_memo import POSTSubscriptionPreviewResponseTypeCreditMemo
from swagger_client.models.post_subscription_preview_response_type_invoice import POSTSubscriptionPreviewResponseTypeInvoice
from swagger_client.models.post_subscription_preview_taxation_items_type import POSTSubscriptionPreviewTaxationItemsType
from swagger_client.models.post_subscription_preview_type import POSTSubscriptionPreviewType
from swagger_client.models.post_subscription_preview_type_preview_account_info import POSTSubscriptionPreviewTypePreviewAccountInfo
from swagger_client.models.post_subscription_response_type import POSTSubscriptionResponseType
from swagger_client.models.post_subscription_type import POSTSubscriptionType
from swagger_client.models.post_taxation_item_for_cm_type import POSTTaxationItemForCMType
from swagger_client.models.post_taxation_item_for_dm_type import POSTTaxationItemForDMType
from swagger_client.models.post_taxation_item_list import POSTTaxationItemList
from swagger_client.models.post_taxation_item_list_for_cm_type import POSTTaxationItemListForCMType
from swagger_client.models.post_taxation_item_list_for_dm_type import POSTTaxationItemListForDMType
from swagger_client.models.post_taxation_item_type_for_invoice import POSTTaxationItemTypeForInvoice
from swagger_client.models.post_tier_type import POSTTierType
from swagger_client.models.post_upload_file_response import POSTUploadFileResponse
from swagger_client.models.post_usage_response_type import POSTUsageResponseType
from swagger_client.models.post_void_authorize import POSTVoidAuthorize
from swagger_client.models.post_void_authorize_response import POSTVoidAuthorizeResponse
from swagger_client.models.post_workflow_definition_import_request import POSTWorkflowDefinitionImportRequest
from swagger_client.models.pos_tor_put_catalog_group_add_product_rate_plan import POSTorPUTCatalogGroupAddProductRatePlan
from swagger_client.models.put_account_type import PUTAccountType
from swagger_client.models.put_account_type_bill_to_contact import PUTAccountTypeBillToContact
from swagger_client.models.put_account_type_sold_to_contact import PUTAccountTypeSoldToContact
from swagger_client.models.put_accounting_code_type import PUTAccountingCodeType
from swagger_client.models.put_accounting_period_type import PUTAccountingPeriodType
from swagger_client.models.put_attachment_type import PUTAttachmentType
from swagger_client.models.put_basic_summary_journal_entry_type import PUTBasicSummaryJournalEntryType
from swagger_client.models.put_batch_debit_memos_request import PUTBatchDebitMemosRequest
from swagger_client.models.put_bulk_credit_memos_request_type import PUTBulkCreditMemosRequestType
from swagger_client.models.put_bulk_debit_memos_request_type import PUTBulkDebitMemosRequestType
from swagger_client.models.put_cancel_payment_schedule_request import PUTCancelPaymentScheduleRequest
from swagger_client.models.put_catalog_group import PUTCatalogGroup
from swagger_client.models.put_catalog_group_remove_product_rate_plan import PUTCatalogGroupRemoveProductRatePlan
from swagger_client.models.put_contact_type import PUTContactType
from swagger_client.models.put_credit_memo_item_type import PUTCreditMemoItemType
from swagger_client.models.put_credit_memo_type import PUTCreditMemoType
from swagger_client.models.put_credit_memo_write_off import PUTCreditMemoWriteOff
from swagger_client.models.put_credit_memo_write_off_response_type import PUTCreditMemoWriteOffResponseType
from swagger_client.models.put_credit_memo_write_off_response_type_debit_memo import PUTCreditMemoWriteOffResponseTypeDebitMemo
from swagger_client.models.put_credit_memos_with_id_type import PUTCreditMemosWithIdType
from swagger_client.models.put_debit_memo_item_type import PUTDebitMemoItemType
from swagger_client.models.put_debit_memo_type import PUTDebitMemoType
from swagger_client.models.put_debit_memo_with_id_type import PUTDebitMemoWithIdType
from swagger_client.models.put_delete_subscription_response_type import PUTDeleteSubscriptionResponseType
from swagger_client.models.put_journal_entry_item_type import PUTJournalEntryItemType
from swagger_client.models.put_order_action_trigger_dates_request_type import PUTOrderActionTriggerDatesRequestType
from swagger_client.models.put_order_action_trigger_dates_request_type_charges import PUTOrderActionTriggerDatesRequestTypeCharges
from swagger_client.models.put_order_action_trigger_dates_request_type_order_actions import PUTOrderActionTriggerDatesRequestTypeOrderActions
from swagger_client.models.put_order_action_trigger_dates_request_type_subscriptions import PUTOrderActionTriggerDatesRequestTypeSubscriptions
from swagger_client.models.put_order_action_trigger_dates_request_type_trigger_dates import PUTOrderActionTriggerDatesRequestTypeTriggerDates
from swagger_client.models.put_order_actions_request_type import PUTOrderActionsRequestType
from swagger_client.models.put_order_line_item_request_type import PUTOrderLineItemRequestType
from swagger_client.models.put_order_patch_request_type import PUTOrderPatchRequestType
from swagger_client.models.put_order_patch_request_type_order_actions import PUTOrderPatchRequestTypeOrderActions
from swagger_client.models.put_order_patch_request_type_subscriptions import PUTOrderPatchRequestTypeSubscriptions
from swagger_client.models.put_order_request_type import PUTOrderRequestType
from swagger_client.models.put_order_trigger_dates_response_type import PUTOrderTriggerDatesResponseType
from swagger_client.models.put_order_trigger_dates_response_type_subscriptions import PUTOrderTriggerDatesResponseTypeSubscriptions
from swagger_client.models.putpm_account_holder_info import PUTPMAccountHolderInfo
from swagger_client.models.putpm_credit_card_info import PUTPMCreditCardInfo
from swagger_client.models.put_payment_method_object_custom_fields import PUTPaymentMethodObjectCustomFields
from swagger_client.models.put_payment_method_request import PUTPaymentMethodRequest
from swagger_client.models.put_payment_method_response import PUTPaymentMethodResponse
from swagger_client.models.put_payment_run_request import PUTPaymentRunRequest
from swagger_client.models.put_payment_schedule_item_request import PUTPaymentScheduleItemRequest
from swagger_client.models.put_payment_schedule_item_response import PUTPaymentScheduleItemResponse
from swagger_client.models.put_payment_schedule_request import PUTPaymentScheduleRequest
from swagger_client.models.put_preview_payment_schedule_request import PUTPreviewPaymentScheduleRequest
from swagger_client.models.put_price_book_item_request import PUTPriceBookItemRequest
from swagger_client.models.put_public_email_template_request import PUTPublicEmailTemplateRequest
from swagger_client.models.put_public_notification_definition_request import PUTPublicNotificationDefinitionRequest
from swagger_client.models.put_public_notification_definition_request_callout import PUTPublicNotificationDefinitionRequestCallout
from swagger_client.models.put_public_notification_definition_request_filter_rule import PUTPublicNotificationDefinitionRequestFilterRule
from swagger_client.models.put_publish_open_payment_method_type_response import PUTPublishOpenPaymentMethodTypeResponse
from swagger_client.models.put_refund_type import PUTRefundType
from swagger_client.models.put_renew_subscription_response_type import PUTRenewSubscriptionResponseType
from swagger_client.models.put_renew_subscription_type import PUTRenewSubscriptionType
from swagger_client.models.put_revpro_acc_code_response import PUTRevproAccCodeResponse
from swagger_client.models.putsc_add_type import PUTScAddType
from swagger_client.models.putsc_update_type import PUTScUpdateType
from swagger_client.models.put_sequence_set_request import PUTSequenceSetRequest
from swagger_client.models.put_sequence_set_response import PUTSequenceSetResponse
from swagger_client.models.put_skip_payment_schedule_item_response import PUTSkipPaymentScheduleItemResponse
from swagger_client.models.put_srp_add_type import PUTSrpAddType
from swagger_client.models.put_srp_change_type import PUTSrpChangeType
from swagger_client.models.put_srp_remove_type import PUTSrpRemoveType
from swagger_client.models.put_srp_update_type import PUTSrpUpdateType
from swagger_client.models.put_subscription_patch_request_type import PUTSubscriptionPatchRequestType
from swagger_client.models.put_subscription_patch_request_type_charges import PUTSubscriptionPatchRequestTypeCharges
from swagger_client.models.put_subscription_patch_request_type_rate_plans import PUTSubscriptionPatchRequestTypeRatePlans
from swagger_client.models.put_subscription_patch_specific_version_request_type import PUTSubscriptionPatchSpecificVersionRequestType
from swagger_client.models.put_subscription_patch_specific_version_request_type_charges import PUTSubscriptionPatchSpecificVersionRequestTypeCharges
from swagger_client.models.put_subscription_patch_specific_version_request_type_rate_plans import PUTSubscriptionPatchSpecificVersionRequestTypeRatePlans
from swagger_client.models.put_subscription_preview_invoice_items_type import PUTSubscriptionPreviewInvoiceItemsType
from swagger_client.models.put_subscription_response_type import PUTSubscriptionResponseType
from swagger_client.models.put_subscription_response_type_charge_metrics import PUTSubscriptionResponseTypeChargeMetrics
from swagger_client.models.put_subscription_response_type_credit_memo import PUTSubscriptionResponseTypeCreditMemo
from swagger_client.models.put_subscription_response_type_invoice import PUTSubscriptionResponseTypeInvoice
from swagger_client.models.put_subscription_resume_response_type import PUTSubscriptionResumeResponseType
from swagger_client.models.put_subscription_resume_type import PUTSubscriptionResumeType
from swagger_client.models.put_subscription_suspend_response_type import PUTSubscriptionSuspendResponseType
from swagger_client.models.put_subscription_suspend_type import PUTSubscriptionSuspendType
from swagger_client.models.put_subscription_type import PUTSubscriptionType
from swagger_client.models.put_taxation_item_type import PUTTaxationItemType
from swagger_client.models.put_update_invoice_schedule_request import PUTUpdateInvoiceScheduleRequest
from swagger_client.models.put_update_open_payment_method_type_request import PUTUpdateOpenPaymentMethodTypeRequest
from swagger_client.models.put_update_open_payment_method_type_response import PUTUpdateOpenPaymentMethodTypeResponse
from swagger_client.models.put_verify_payment_method_response_type import PUTVerifyPaymentMethodResponseType
from swagger_client.models.put_verify_payment_method_type import PUTVerifyPaymentMethodType
from swagger_client.models.put_write_off_invoice_request import PUTWriteOffInvoiceRequest
from swagger_client.models.put_write_off_invoice_response import PUTWriteOffInvoiceResponse
from swagger_client.models.put_write_off_invoice_response_credit_memo import PUTWriteOffInvoiceResponseCreditMemo
from swagger_client.models.payment_collection_response_type import PaymentCollectionResponseType
from swagger_client.models.payment_data import PaymentData
from swagger_client.models.payment_debit_memo_application_apply_request_type import PaymentDebitMemoApplicationApplyRequestType
from swagger_client.models.payment_debit_memo_application_create_request_type import PaymentDebitMemoApplicationCreateRequestType
from swagger_client.models.payment_debit_memo_application_item_apply_request_type import PaymentDebitMemoApplicationItemApplyRequestType
from swagger_client.models.payment_debit_memo_application_item_create_request_type import PaymentDebitMemoApplicationItemCreateRequestType
from swagger_client.models.payment_debit_memo_application_item_unapply_request_type import PaymentDebitMemoApplicationItemUnapplyRequestType
from swagger_client.models.payment_debit_memo_application_unapply_request_type import PaymentDebitMemoApplicationUnapplyRequestType
from swagger_client.models.payment_entity_prefix import PaymentEntityPrefix
from swagger_client.models.payment_invoice_application_apply_request_type import PaymentInvoiceApplicationApplyRequestType
from swagger_client.models.payment_invoice_application_create_request_type import PaymentInvoiceApplicationCreateRequestType
from swagger_client.models.payment_invoice_application_item_apply_request_type import PaymentInvoiceApplicationItemApplyRequestType
from swagger_client.models.payment_invoice_application_item_create_request_type import PaymentInvoiceApplicationItemCreateRequestType
from swagger_client.models.payment_invoice_application_item_unapply_request_type import PaymentInvoiceApplicationItemUnapplyRequestType
from swagger_client.models.payment_invoice_application_unapply_request_type import PaymentInvoiceApplicationUnapplyRequestType
from swagger_client.models.payment_method_object_custom_fields import PaymentMethodObjectCustomFields
from swagger_client.models.payment_method_object_custom_fields_for_account import PaymentMethodObjectCustomFieldsForAccount
from swagger_client.models.payment_object_custom_fields import PaymentObjectCustomFields
from swagger_client.models.payment_object_ns_fields import PaymentObjectNSFields
from swagger_client.models.payment_run_statistic import PaymentRunStatistic
from swagger_client.models.payment_schedule_common_response import PaymentScheduleCommonResponse
from swagger_client.models.payment_schedule_custom_fields import PaymentScheduleCustomFields
from swagger_client.models.payment_schedule_item_common import PaymentScheduleItemCommon
from swagger_client.models.payment_schedule_item_common_response import PaymentScheduleItemCommonResponse
from swagger_client.models.payment_schedule_item_custom_fields import PaymentScheduleItemCustomFields
from swagger_client.models.payment_schedule_payment_option_fields import PaymentSchedulePaymentOptionFields
from swagger_client.models.payment_schedule_payment_option_fields_detail import PaymentSchedulePaymentOptionFieldsDetail
from swagger_client.models.payment_volume_summary_record import PaymentVolumeSummaryRecord
from swagger_client.models.payment_with_custom_rates_type import PaymentWithCustomRatesType
from swagger_client.models.post_batch_invoice_item_response import PostBatchInvoiceItemResponse
from swagger_client.models.post_batch_invoice_response import PostBatchInvoiceResponse
from swagger_client.models.post_batch_invoices_type import PostBatchInvoicesType
from swagger_client.models.post_billing_preview_param import PostBillingPreviewParam
from swagger_client.models.post_billing_preview_run_param import PostBillingPreviewRunParam
from swagger_client.models.post_credit_memo_email_request_type import PostCreditMemoEmailRequestType
from swagger_client.models.post_custom_object_definition_field_definition_request import PostCustomObjectDefinitionFieldDefinitionRequest
from swagger_client.models.post_custom_object_definition_fields_definition_request import PostCustomObjectDefinitionFieldsDefinitionRequest
from swagger_client.models.post_custom_object_definitions_request import PostCustomObjectDefinitionsRequest
from swagger_client.models.post_custom_object_definitions_request_definition import PostCustomObjectDefinitionsRequestDefinition
from swagger_client.models.post_custom_object_definitions_request_definitions import PostCustomObjectDefinitionsRequestDefinitions
from swagger_client.models.post_custom_object_records_request import PostCustomObjectRecordsRequest
from swagger_client.models.post_custom_object_records_response import PostCustomObjectRecordsResponse
from swagger_client.models.post_debit_memo_email_type import PostDebitMemoEmailType
from swagger_client.models.post_discount_item_type import PostDiscountItemType
from swagger_client.models.post_event_trigger_request import PostEventTriggerRequest
from swagger_client.models.post_fulfillment_items_request_type import PostFulfillmentItemsRequestType
from swagger_client.models.post_fulfillment_items_response_type import PostFulfillmentItemsResponseType
from swagger_client.models.post_fulfillment_items_response_type_fulfillment_items import PostFulfillmentItemsResponseTypeFulfillmentItems
from swagger_client.models.post_fulfillments_request_type import PostFulfillmentsRequestType
from swagger_client.models.post_fulfillments_response_type import PostFulfillmentsResponseType
from swagger_client.models.post_fulfillments_response_type_fulfillments import PostFulfillmentsResponseTypeFulfillments
from swagger_client.models.post_generate_billing_document_type import PostGenerateBillingDocumentType
from swagger_client.models.post_invoice_email_request_type import PostInvoiceEmailRequestType
from swagger_client.models.post_invoice_item_type import PostInvoiceItemType
from swagger_client.models.post_invoice_response import PostInvoiceResponse
from swagger_client.models.post_invoice_type import PostInvoiceType
from swagger_client.models.post_non_ref_refund_type import PostNonRefRefundType
from swagger_client.models.post_order_account_payment_method import PostOrderAccountPaymentMethod
from swagger_client.models.post_order_line_item_update_type import PostOrderLineItemUpdateType
from swagger_client.models.post_order_line_items_request_type import PostOrderLineItemsRequestType
from swagger_client.models.post_order_preview_response_type import PostOrderPreviewResponseType
from swagger_client.models.post_order_response_type import PostOrderResponseType
from swagger_client.models.post_order_response_type_refunds import PostOrderResponseTypeRefunds
from swagger_client.models.post_order_response_type_subscriptions import PostOrderResponseTypeSubscriptions
from swagger_client.models.post_order_response_type_write_off import PostOrderResponseTypeWriteOff
from swagger_client.models.post_refund_type import PostRefundType
from swagger_client.models.post_refundwith_auto_unapply_type import PostRefundwithAutoUnapplyType
from swagger_client.models.post_scheduled_event_request import PostScheduledEventRequest
from swagger_client.models.post_scheduled_event_request_parameters import PostScheduledEventRequestParameters
from swagger_client.models.post_taxation_item_type import PostTaxationItemType
from swagger_client.models.preview_account_info import PreviewAccountInfo
from swagger_client.models.preview_contact_info import PreviewContactInfo
from swagger_client.models.preview_options import PreviewOptions
from swagger_client.models.preview_order_charge_override import PreviewOrderChargeOverride
from swagger_client.models.preview_order_charge_update import PreviewOrderChargeUpdate
from swagger_client.models.preview_order_create_subscription import PreviewOrderCreateSubscription
from swagger_client.models.preview_order_create_subscription_new_subscription_owner_account import PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount
from swagger_client.models.preview_order_order_action import PreviewOrderOrderAction
from swagger_client.models.preview_order_pricing_update import PreviewOrderPricingUpdate
from swagger_client.models.preview_order_rate_plan_override import PreviewOrderRatePlanOverride
from swagger_client.models.preview_order_rate_plan_update import PreviewOrderRatePlanUpdate
from swagger_client.models.preview_order_trigger_params import PreviewOrderTriggerParams
from swagger_client.models.preview_result import PreviewResult
from swagger_client.models.preview_result_charge_metrics import PreviewResultChargeMetrics
from swagger_client.models.preview_result_credit_memos import PreviewResultCreditMemos
from swagger_client.models.preview_result_invoices import PreviewResultInvoices
from swagger_client.models.preview_result_order_actions import PreviewResultOrderActions
from swagger_client.models.preview_result_order_delta_metrics import PreviewResultOrderDeltaMetrics
from swagger_client.models.preview_result_order_metrics import PreviewResultOrderMetrics
from swagger_client.models.price_change_params import PriceChangeParams
from swagger_client.models.price_interval_with_price import PriceIntervalWithPrice
from swagger_client.models.price_interval_with_tiers import PriceIntervalWithTiers
from swagger_client.models.pricing_update import PricingUpdate
from swagger_client.models.pricing_update_recurring_delivery import PricingUpdateRecurringDelivery
from swagger_client.models.processing_options import ProcessingOptions
from swagger_client.models.processing_options_orders import ProcessingOptionsOrders
from swagger_client.models.processing_options_orders_async import ProcessingOptionsOrdersAsync
from swagger_client.models.processing_options_orders_billing_options import ProcessingOptionsOrdersBillingOptions
from swagger_client.models.processing_options_orders_electronic_payment_options import ProcessingOptionsOrdersElectronicPaymentOptions
from swagger_client.models.processing_options_orders_write_off_behavior import ProcessingOptionsOrdersWriteOffBehavior
from swagger_client.models.processing_options_orders_write_off_behavior_finance_information import ProcessingOptionsOrdersWriteOffBehaviorFinanceInformation
from swagger_client.models.product_feature_object_custom_fields import ProductFeatureObjectCustomFields
from swagger_client.models.product_object_custom_fields import ProductObjectCustomFields
from swagger_client.models.product_object_ns_fields import ProductObjectNSFields
from swagger_client.models.product_rate_plan_charge_object_custom_fields import ProductRatePlanChargeObjectCustomFields
from swagger_client.models.product_rate_plan_charge_object_ns_fields import ProductRatePlanChargeObjectNSFields
from swagger_client.models.product_rate_plan_object_custom_fields import ProductRatePlanObjectCustomFields
from swagger_client.models.product_rate_plan_object_ns_fields import ProductRatePlanObjectNSFields
from swagger_client.models.proxy_actioncreate_request import ProxyActioncreateRequest
from swagger_client.models.proxy_actiondelete_request import ProxyActiondeleteRequest
from swagger_client.models.proxy_actionquery_more_request import ProxyActionqueryMoreRequest
from swagger_client.models.proxy_actionquery_more_request_conf import ProxyActionqueryMoreRequestConf
from swagger_client.models.proxy_actionquery_more_response import ProxyActionqueryMoreResponse
from swagger_client.models.proxy_actionquery_request import ProxyActionqueryRequest
from swagger_client.models.proxy_actionquery_response import ProxyActionqueryResponse
from swagger_client.models.proxy_actionupdate_request import ProxyActionupdateRequest
from swagger_client.models.proxy_bad_request_response import ProxyBadRequestResponse
from swagger_client.models.proxy_bad_request_response_errors import ProxyBadRequestResponseErrors
from swagger_client.models.proxy_create_or_modify_delivery_schedule import ProxyCreateOrModifyDeliverySchedule
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_charge_model_configuration import ProxyCreateOrModifyProductRatePlanChargeChargeModelConfiguration
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_charge_model_configuration_item import ProxyCreateOrModifyProductRatePlanChargeChargeModelConfigurationItem
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_tier_data import ProxyCreateOrModifyProductRatePlanChargeTierData
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_tier_data_product_rate_plan_charge_tier import ProxyCreateOrModifyProductRatePlanChargeTierDataProductRatePlanChargeTier
from swagger_client.models.proxy_create_or_modify_response import ProxyCreateOrModifyResponse
from swagger_client.models.proxy_create_product import ProxyCreateProduct
from swagger_client.models.proxy_create_product_rate_plan import ProxyCreateProductRatePlan
from swagger_client.models.proxy_create_product_rate_plan_charge import ProxyCreateProductRatePlanCharge
from swagger_client.models.proxy_create_taxation_item import ProxyCreateTaxationItem
from swagger_client.models.proxy_create_usage import ProxyCreateUsage
from swagger_client.models.proxy_delete_response import ProxyDeleteResponse
from swagger_client.models.proxy_get_import import ProxyGetImport
from swagger_client.models.proxy_get_payment_method_snapshot import ProxyGetPaymentMethodSnapshot
from swagger_client.models.proxy_get_payment_method_transaction_log import ProxyGetPaymentMethodTransactionLog
from swagger_client.models.proxy_get_payment_transaction_log import ProxyGetPaymentTransactionLog
from swagger_client.models.proxy_get_product import ProxyGetProduct
from swagger_client.models.proxy_get_product_rate_plan import ProxyGetProductRatePlan
from swagger_client.models.proxy_get_product_rate_plan_charge import ProxyGetProductRatePlanCharge
from swagger_client.models.proxy_get_product_rate_plan_charge_tier import ProxyGetProductRatePlanChargeTier
from swagger_client.models.proxy_get_usage import ProxyGetUsage
from swagger_client.models.proxy_modify_product import ProxyModifyProduct
from swagger_client.models.proxy_modify_product_rate_plan import ProxyModifyProductRatePlan
from swagger_client.models.proxy_modify_product_rate_plan_charge import ProxyModifyProductRatePlanCharge
from swagger_client.models.proxy_modify_product_rate_plan_charge_tier import ProxyModifyProductRatePlanChargeTier
from swagger_client.models.proxy_modify_usage import ProxyModifyUsage
from swagger_client.models.proxy_no_data_response import ProxyNoDataResponse
from swagger_client.models.proxy_post_import import ProxyPostImport
from swagger_client.models.proxy_unauthorized_response import ProxyUnauthorizedResponse
from swagger_client.models.put_batch_invoice_type import PutBatchInvoiceType
from swagger_client.models.put_credit_memo_tax_item_type import PutCreditMemoTaxItemType
from swagger_client.models.put_debit_memo_tax_item_type import PutDebitMemoTaxItemType
from swagger_client.models.put_discount_item_type import PutDiscountItemType
from swagger_client.models.put_event_trigger_request import PutEventTriggerRequest
from swagger_client.models.put_event_trigger_request_event_type import PutEventTriggerRequestEventType
from swagger_client.models.put_fulfillment_item_request_type import PutFulfillmentItemRequestType
from swagger_client.models.put_fulfillment_request_type import PutFulfillmentRequestType
from swagger_client.models.put_invoice_item_type import PutInvoiceItemType
from swagger_client.models.put_invoice_response_type import PutInvoiceResponseType
from swagger_client.models.put_invoice_type import PutInvoiceType
from swagger_client.models.put_order_cancel_response import PutOrderCancelResponse
from swagger_client.models.put_order_line_item_response_type import PutOrderLineItemResponseType
from swagger_client.models.put_order_line_item_update_type import PutOrderLineItemUpdateType
from swagger_client.models.put_reverse_credit_memo_response_type import PutReverseCreditMemoResponseType
from swagger_client.models.put_reverse_credit_memo_response_type_credit_memo import PutReverseCreditMemoResponseTypeCreditMemo
from swagger_client.models.put_reverse_credit_memo_response_type_debit_memo import PutReverseCreditMemoResponseTypeDebitMemo
from swagger_client.models.put_reverse_credit_memo_type import PutReverseCreditMemoType
from swagger_client.models.put_reverse_invoice_response_type import PutReverseInvoiceResponseType
from swagger_client.models.put_reverse_invoice_response_type_credit_memo import PutReverseInvoiceResponseTypeCreditMemo
from swagger_client.models.put_reverse_invoice_response_type_debit_memo import PutReverseInvoiceResponseTypeDebitMemo
from swagger_client.models.put_reverse_invoice_type import PutReverseInvoiceType
from swagger_client.models.put_scheduled_event_request import PutScheduledEventRequest
from swagger_client.models.put_tasks_request import PutTasksRequest
from swagger_client.models.query_custom_object_records_response import QueryCustomObjectRecordsResponse
from swagger_client.models.quote_object_fields import QuoteObjectFields
from swagger_client.models.ramp_charge_request import RampChargeRequest
from swagger_client.models.ramp_charge_response import RampChargeResponse
from swagger_client.models.ramp_interval_charge_delta_metrics import RampIntervalChargeDeltaMetrics
from swagger_client.models.ramp_interval_charge_delta_metrics_delta_mrr import RampIntervalChargeDeltaMetricsDeltaMrr
from swagger_client.models.ramp_interval_charge_delta_metrics_delta_quantity import RampIntervalChargeDeltaMetricsDeltaQuantity
from swagger_client.models.ramp_interval_charge_metrics import RampIntervalChargeMetrics
from swagger_client.models.ramp_interval_charge_metrics_mrr import RampIntervalChargeMetricsMrr
from swagger_client.models.ramp_interval_metrics import RampIntervalMetrics
from swagger_client.models.ramp_interval_request import RampIntervalRequest
from swagger_client.models.ramp_interval_response import RampIntervalResponse
from swagger_client.models.ramp_metrics import RampMetrics
from swagger_client.models.ramp_request import RampRequest
from swagger_client.models.ramp_response import RampResponse
from swagger_client.models.rate_plan import RatePlan
from swagger_client.models.rate_plan_charge_object_custom_fields import RatePlanChargeObjectCustomFields
from swagger_client.models.rate_plan_feature_override import RatePlanFeatureOverride
from swagger_client.models.rate_plan_feature_override_custom_fields import RatePlanFeatureOverrideCustomFields
from swagger_client.models.rate_plan_object_custom_fields import RatePlanObjectCustomFields
from swagger_client.models.rate_plan_override import RatePlanOverride
from swagger_client.models.rate_plan_update import RatePlanUpdate
from swagger_client.models.rate_plans import RatePlans
from swagger_client.models.recurring_delivery_pricing_override import RecurringDeliveryPricingOverride
from swagger_client.models.recurring_delivery_pricing_update import RecurringDeliveryPricingUpdate
from swagger_client.models.recurring_flat_fee_pricing_override import RecurringFlatFeePricingOverride
from swagger_client.models.recurring_flat_fee_pricing_update import RecurringFlatFeePricingUpdate
from swagger_client.models.recurring_per_unit_pricing_override import RecurringPerUnitPricingOverride
from swagger_client.models.recurring_per_unit_pricing_update import RecurringPerUnitPricingUpdate
from swagger_client.models.recurring_tiered_pricing_override import RecurringTieredPricingOverride
from swagger_client.models.recurring_tiered_pricing_update import RecurringTieredPricingUpdate
from swagger_client.models.recurring_volume_pricing_override import RecurringVolumePricingOverride
from swagger_client.models.recurring_volume_pricing_update import RecurringVolumePricingUpdate
from swagger_client.models.refund_credit_memo_item_type import RefundCreditMemoItemType
from swagger_client.models.refund_entity_prefix import RefundEntityPrefix
from swagger_client.models.refund_object_custom_fields import RefundObjectCustomFields
from swagger_client.models.refund_object_ns_fields import RefundObjectNSFields
from swagger_client.models.refund_part_response_type import RefundPartResponseType
from swagger_client.models.refund_part_response_typewith_success import RefundPartResponseTypewithSuccess
from swagger_client.models.remove_product import RemoveProduct
from swagger_client.models.renew_subscription import RenewSubscription
from swagger_client.models.renewal_term import RenewalTerm
from swagger_client.models.request import Request
from swagger_client.models.request1 import Request1
from swagger_client.models.resend_callout_notifications_failed_response import ResendCalloutNotificationsFailedResponse
from swagger_client.models.resend_email_notifications_failed_response import ResendEmailNotificationsFailedResponse
from swagger_client.models.revpro_accounting_codes import RevproAccountingCodes
from swagger_client.models.save_result import SaveResult
from swagger_client.models.schedule_items_response import ScheduleItemsResponse
from swagger_client.models.setting_component_key_value import SettingComponentKeyValue
from swagger_client.models.setting_item_http_operation import SettingItemHttpOperation
from swagger_client.models.setting_item_http_request_parameter import SettingItemHttpRequestParameter
from swagger_client.models.setting_item_with_operations_information import SettingItemWithOperationsInformation
from swagger_client.models.setting_source_component_response import SettingSourceComponentResponse
from swagger_client.models.setting_value_request import SettingValueRequest
from swagger_client.models.setting_value_response import SettingValueResponse
from swagger_client.models.setting_value_response_wrapper import SettingValueResponseWrapper
from swagger_client.models.settings_batch_request import SettingsBatchRequest
from swagger_client.models.settings_batch_response import SettingsBatchResponse
from swagger_client.models.sign_up_create_pm_pay_pal_ec_pay_pal_native_ec import SignUpCreatePMPayPalECPayPalNativeEC
from swagger_client.models.sign_up_create_payment_method_cardholder_info import SignUpCreatePaymentMethodCardholderInfo
from swagger_client.models.sign_up_create_payment_method_common import SignUpCreatePaymentMethodCommon
from swagger_client.models.sign_up_create_payment_method_credit_card import SignUpCreatePaymentMethodCreditCard
from swagger_client.models.sign_up_create_payment_method_credit_card_reference_transaction import SignUpCreatePaymentMethodCreditCardReferenceTransaction
from swagger_client.models.sign_up_create_payment_method_pay_pal_adaptive import SignUpCreatePaymentMethodPayPalAdaptive
from swagger_client.models.sign_up_payment_method import SignUpPaymentMethod
from swagger_client.models.sign_up_payment_method_object_custom_fields import SignUpPaymentMethodObjectCustomFields
from swagger_client.models.sign_up_request import SignUpRequest
from swagger_client.models.sign_up_response import SignUpResponse
from swagger_client.models.sign_up_response_reasons import SignUpResponseReasons
from swagger_client.models.sign_up_tax_info import SignUpTaxInfo
from swagger_client.models.sold_to_contact import SoldToContact
from swagger_client.models.sold_to_contact_post_order import SoldToContactPostOrder
from swagger_client.models.submit_batch_query_request import SubmitBatchQueryRequest
from swagger_client.models.submit_batch_query_response import SubmitBatchQueryResponse
from swagger_client.models.submit_data_query_request import SubmitDataQueryRequest
from swagger_client.models.submit_data_query_request_output import SubmitDataQueryRequestOutput
from swagger_client.models.submit_data_query_response import SubmitDataQueryResponse
from swagger_client.models.subscribe_to_product import SubscribeToProduct
from swagger_client.models.subscription_data import SubscriptionData
from swagger_client.models.subscription_object_custom_fields import SubscriptionObjectCustomFields
from swagger_client.models.subscription_object_ns_fields import SubscriptionObjectNSFields
from swagger_client.models.subscription_object_qt_fields import SubscriptionObjectQTFields
from swagger_client.models.subscription_offer_object_custom_fields import SubscriptionOfferObjectCustomFields
from swagger_client.models.system_health_error_response import SystemHealthErrorResponse
from swagger_client.models.task import Task
from swagger_client.models.tasks_response import TasksResponse
from swagger_client.models.tasks_response_pagination import TasksResponsePagination
from swagger_client.models.tax_info import TaxInfo
from swagger_client.models.taxation_item_object_custom_fields import TaxationItemObjectCustomFields
from swagger_client.models.template_detail_response import TemplateDetailResponse
from swagger_client.models.template_migration_client_request import TemplateMigrationClientRequest
from swagger_client.models.template_response import TemplateResponse
from swagger_client.models.term_info import TermInfo
from swagger_client.models.term_info_initial_term import TermInfoInitialTerm
from swagger_client.models.term_info_renewal_terms import TermInfoRenewalTerms
from swagger_client.models.terms_and_conditions import TermsAndConditions
from swagger_client.models.time_sliced_elp_net_metrics import TimeSlicedElpNetMetrics
from swagger_client.models.time_sliced_metrics import TimeSlicedMetrics
from swagger_client.models.time_sliced_net_metrics import TimeSlicedNetMetrics
from swagger_client.models.time_sliced_tcb_net_metrics import TimeSlicedTcbNetMetrics
from swagger_client.models.token_response import TokenResponse
from swagger_client.models.transfer_payment_type import TransferPaymentType
from swagger_client.models.trigger_date import TriggerDate
from swagger_client.models.trigger_params import TriggerParams
from swagger_client.models.unapply_credit_memo_type import UnapplyCreditMemoType
from swagger_client.models.unapply_payment_type import UnapplyPaymentType
from swagger_client.models.update_custom_object_cusotm_field import UpdateCustomObjectCusotmField
from swagger_client.models.update_payment_type import UpdatePaymentType
from swagger_client.models.update_schedule_items import UpdateScheduleItems
from swagger_client.models.update_task import UpdateTask
from swagger_client.models.usage import Usage
from swagger_client.models.usage_flat_fee_pricing_override import UsageFlatFeePricingOverride
from swagger_client.models.usage_flat_fee_pricing_update import UsageFlatFeePricingUpdate
from swagger_client.models.usage_object_custom_fields import UsageObjectCustomFields
from swagger_client.models.usage_overage_pricing_override import UsageOveragePricingOverride
from swagger_client.models.usage_overage_pricing_update import UsageOveragePricingUpdate
from swagger_client.models.usage_per_unit_pricing_override import UsagePerUnitPricingOverride
from swagger_client.models.usage_per_unit_pricing_update import UsagePerUnitPricingUpdate
from swagger_client.models.usage_tiered_pricing_override import UsageTieredPricingOverride
from swagger_client.models.usage_tiered_pricing_update import UsageTieredPricingUpdate
from swagger_client.models.usage_tiered_with_overage_pricing_override import UsageTieredWithOveragePricingOverride
from swagger_client.models.usage_tiered_with_overage_pricing_update import UsageTieredWithOveragePricingUpdate
from swagger_client.models.usage_values import UsageValues
from swagger_client.models.usage_volume_pricing_override import UsageVolumePricingOverride
from swagger_client.models.usage_volume_pricing_update import UsageVolumePricingUpdate
from swagger_client.models.usages_response import UsagesResponse
from swagger_client.models.validation_errors import ValidationErrors
from swagger_client.models.validation_reasons import ValidationReasons
from swagger_client.models.workflow import Workflow
from swagger_client.models.workflow_definition import WorkflowDefinition
from swagger_client.models.workflow_definition_active_version import WorkflowDefinitionActiveVersion
from swagger_client.models.workflow_definition_and_versions import WorkflowDefinitionAndVersions
from swagger_client.models.workflow_error import WorkflowError
from swagger_client.models.workflow_instance import WorkflowInstance
from swagger_client.models.z_object import ZObject
from swagger_client.models.z_object_update import ZObjectUpdate | zuora-swagger-client | /zuora-swagger-client-1.2.0.tar.gz/zuora-swagger-client-1.2.0/swagger_client/__init__.py | __init__.py |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from swagger_client.api.api_health_api import APIHealthApi
from swagger_client.api.accounting_codes_api import AccountingCodesApi
from swagger_client.api.accounting_periods_api import AccountingPeriodsApi
from swagger_client.api.accounts_api import AccountsApi
from swagger_client.api.actions_api import ActionsApi
from swagger_client.api.adjustments_api import AdjustmentsApi
from swagger_client.api.aggregate_queries_api import AggregateQueriesApi
from swagger_client.api.attachments_api import AttachmentsApi
from swagger_client.api.bill_run_api import BillRunApi
from swagger_client.api.bill_run_health_api import BillRunHealthApi
from swagger_client.api.billing_documents_api import BillingDocumentsApi
from swagger_client.api.billing_preview_run_api import BillingPreviewRunApi
from swagger_client.api.catalog_api import CatalogApi
from swagger_client.api.catalog_groups_api import CatalogGroupsApi
from swagger_client.api.configuration_templates_api import ConfigurationTemplatesApi
from swagger_client.api.contact_snapshots_api import ContactSnapshotsApi
from swagger_client.api.contacts_api import ContactsApi
from swagger_client.api.credit_memos_api import CreditMemosApi
from swagger_client.api.custom_event_triggers_api import CustomEventTriggersApi
from swagger_client.api.custom_exchange_rates_api import CustomExchangeRatesApi
from swagger_client.api.custom_object_definitions_api import CustomObjectDefinitionsApi
from swagger_client.api.custom_object_jobs_api import CustomObjectJobsApi
from swagger_client.api.custom_object_records_api import CustomObjectRecordsApi
from swagger_client.api.custom_payment_method_types_api import CustomPaymentMethodTypesApi
from swagger_client.api.custom_scheduled_events_api import CustomScheduledEventsApi
from swagger_client.api.data_queries_api import DataQueriesApi
from swagger_client.api.debit_memos_api import DebitMemosApi
from swagger_client.api.describe_api import DescribeApi
from swagger_client.api.electronic_payments_health_api import ElectronicPaymentsHealthApi
from swagger_client.api.files_api import FilesApi
from swagger_client.api.fulfillments_api import FulfillmentsApi
from swagger_client.api.hosted_pages_api import HostedPagesApi
from swagger_client.api.imports_api import ImportsApi
from swagger_client.api.invoice_schedules_api import InvoiceSchedulesApi
from swagger_client.api.invoices_api import InvoicesApi
from swagger_client.api.journal_runs_api import JournalRunsApi
from swagger_client.api.mass_updater_api import MassUpdaterApi
from swagger_client.api.notifications_api import NotificationsApi
from swagger_client.api.o_auth_api import OAuthApi
from swagger_client.api.offers_api import OffersApi
from swagger_client.api.operations_api import OperationsApi
from swagger_client.api.order_actions_api import OrderActionsApi
from swagger_client.api.order_line_items_api import OrderLineItemsApi
from swagger_client.api.orders_api import OrdersApi
from swagger_client.api.payment_authorization_api import PaymentAuthorizationApi
from swagger_client.api.payment_gateway_reconciliation_api import PaymentGatewayReconciliationApi
from swagger_client.api.payment_gateways_api import PaymentGatewaysApi
from swagger_client.api.payment_method_snapshots_api import PaymentMethodSnapshotsApi
from swagger_client.api.payment_method_transaction_logs_api import PaymentMethodTransactionLogsApi
from swagger_client.api.payment_method_updater_api import PaymentMethodUpdaterApi
from swagger_client.api.payment_methods_api import PaymentMethodsApi
from swagger_client.api.payment_runs_api import PaymentRunsApi
from swagger_client.api.payment_schedules_api import PaymentSchedulesApi
from swagger_client.api.payment_transaction_logs_api import PaymentTransactionLogsApi
from swagger_client.api.payments_api import PaymentsApi
from swagger_client.api.price_book_items_api import PriceBookItemsApi
from swagger_client.api.product_rate_plan_charge_tiers_api import ProductRatePlanChargeTiersApi
from swagger_client.api.product_rate_plan_charges_api import ProductRatePlanChargesApi
from swagger_client.api.product_rate_plans_api import ProductRatePlansApi
from swagger_client.api.products_api import ProductsApi
from swagger_client.api.rsa_signatures_api import RSASignaturesApi
from swagger_client.api.ramps_api import RampsApi
from swagger_client.api.rate_plans_api import RatePlansApi
from swagger_client.api.refunds_api import RefundsApi
from swagger_client.api.sequence_sets_api import SequenceSetsApi
from swagger_client.api.settings_api import SettingsApi
from swagger_client.api.sign_up_api import SignUpApi
from swagger_client.api.subscriptions_api import SubscriptionsApi
from swagger_client.api.summary_journal_entries_api import SummaryJournalEntriesApi
from swagger_client.api.taxation_items_api import TaxationItemsApi
from swagger_client.api.usage_api import UsageApi
from swagger_client.api.workflows_api import WorkflowsApi
from swagger_client.api.zuora_revenue_integration_api import ZuoraRevenueIntegrationApi | zuora-swagger-client | /zuora-swagger-client-1.2.0.tar.gz/zuora-swagger-client-1.2.0/swagger_client/api/__init__.py | __init__.py |
# flake8: noqa
"""
API Reference
# Introduction Welcome to the REST API reference for the Zuora Billing, Payments, and Central Platform! To learn about the common use cases of Zuora REST APIs, check out the [REST API Tutorials](https://www.zuora.com/developer/rest-api/api-guides/overview/). In addition to Zuora API Reference, we also provide API references for other Zuora products: * [Revenue API Reference](https://www.zuora.com/developer/api-references/revenue/overview/) * [Collections API Reference](https://www.zuora.com/developer/api-references/collections/overview/) The Zuora REST API provides a broad set of operations and resources that: * Enable Web Storefront integration from your website. * Support self-service subscriber sign-ups and account management. * Process revenue schedules through custom revenue rule models. * Enable manipulation of most objects in the Zuora Billing Object Model. Want to share your opinion on how our API works for you? <a href=\"https://community.zuora.com/t5/Developers/API-Feedback-Form/gpm-p/21399\" target=\"_blank\">Tell us how you feel </a>about using our API and what we can do to make it better. Some of our older APIs are no longer recommended but still available, not affecting any existing integration. To find related API documentation, see [Older API Reference](https://www.zuora.com/developer/api-references/older-api/overview/). ## Access to the API If you have a Zuora tenant, you can access the Zuora REST API via one of the following endpoints: | Tenant | Base URL for REST Endpoints | |-------------------------|-------------------------| |US Cloud 1 Production | https://rest.na.zuora.com | |US Cloud 1 API Sandbox | https://rest.sandbox.na.zuora.com | |US Cloud 2 Production | https://rest.zuora.com | |US Cloud 2 API Sandbox | https://rest.apisandbox.zuora.com| |US Central Sandbox | https://rest.test.zuora.com | |US Performance Test | https://rest.pt1.zuora.com | |US Production Copy | Submit a request at <a href=\"http://support.zuora.com/\" target=\"_blank\">Zuora Global Support</a> to enable the Zuora REST API in your tenant and obtain the base URL for REST endpoints. See [REST endpoint base URL of Production Copy (Service) Environment for existing and new customers](https://community.zuora.com/t5/API/REST-endpoint-base-URL-of-Production-Copy-Service-Environment/td-p/29611) for more information. | |EU Production | https://rest.eu.zuora.com | |EU API Sandbox | https://rest.sandbox.eu.zuora.com | |EU Central Sandbox | https://rest.test.eu.zuora.com | The Production endpoint provides access to your live user data. Sandbox tenants are a good place to test code without affecting real-world data. If you would like Zuora to provision a Sandbox tenant for you, contact your Zuora representative for assistance. If you do not have a Zuora tenant, go to <a href=\"https://www.zuora.com/resource/zuora-test-drive\" target=\"_blank\">https://www.zuora.com/resource/zuora-test-drive</a> and sign up for a Production Test Drive tenant. The tenant comes with seed data, including a sample product catalog. # Error Handling If a request to Zuora Billing REST API with an endpoint starting with `/v1` (except [Actions](https://www.zuora.com/developer/api-references/api/tag/Actions) and CRUD operations) fails, the response will contain an eight-digit error code with a corresponding error message to indicate the details of the error. The following code snippet is a sample error response that contains an error code and message pair: ``` { \"success\": false, \"processId\": \"CBCFED6580B4E076\", \"reasons\": [ { \"code\": 53100320, \"message\": \"'termType' value should be one of: TERMED, EVERGREEN\" } ] } ``` The `success` field indicates whether the API request has succeeded. The `processId` field is a Zuora internal ID that you can provide to Zuora Global Support for troubleshooting purposes. The `reasons` field contains the actual error code and message pair. The error code begins with `5` or `6` means that you encountered a certain issue that is specific to a REST API resource in Zuora Billing, Payments, and Central Platform. For example, `53100320` indicates that an invalid value is specified for the `termType` field of the `subscription` object. The error code beginning with `9` usually indicates that an authentication-related issue occurred, and it can also indicate other unexpected errors depending on different cases. For example, `90000011` indicates that an invalid credential is provided in the request header. When troubleshooting the error, you can divide the error code into two components: REST API resource code and error category code. See the following Zuora error code sample: <a href=\"https://www.zuora.com/developer/images/ZuoraErrorCode.jpeg\" target=\"_blank\"><img src=\"https://www.zuora.com/developer/images/ZuoraErrorCode.jpeg\" alt=\"Zuora Error Code Sample\"></a> **Note:** Zuora determines resource codes based on the request payload. Therefore, if GET and DELETE requests that do not contain payloads fail, you will get `500000` as the resource code, which indicates an unknown object and an unknown field. The error category code of these requests is valid and follows the rules described in the [Error Category Codes](https://www.zuora.com/developer/api-references/api/overview/#section/Error-Handling/Error-Category-Codes) section. In such case, you can refer to the returned error message to troubleshoot. ## REST API Resource Codes The 6-digit resource code indicates the REST API resource, typically a field of a Zuora object, on which the issue occurs. In the preceding example, `531003` refers to the `termType` field of the `subscription` object. The value range for all REST API resource codes is from `500000` to `679999`. See <a href=\"https://knowledgecenter.zuora.com/Central_Platform/API/AA_REST_API/Resource_Codes\" target=\"_blank\">Resource Codes</a> in the Knowledge Center for a full list of resource codes. ## Error Category Codes The 2-digit error category code identifies the type of error, for example, resource not found or missing required field. The following table describes all error categories and the corresponding resolution: | Code | Error category | Description | Resolution | |:--------|:--------|:--------|:--------| | 10 | Permission or access denied | The request cannot be processed because a certain tenant or user permission is missing. | Check the missing tenant or user permission in the response message and contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> for enablement. | | 11 | Authentication failed | Authentication fails due to invalid API authentication credentials. | Ensure that a valid API credential is specified. | | 20 | Invalid format or value | The request cannot be processed due to an invalid field format or value. | Check the invalid field in the error message, and ensure that the format and value of all fields you passed in are valid. | | 21 | Unknown field in request | The request cannot be processed because an unknown field exists in the request body. | Check the unknown field name in the response message, and ensure that you do not include any unknown field in the request body. | | 22 | Missing required field | The request cannot be processed because a required field in the request body is missing. | Check the missing field name in the response message, and ensure that you include all required fields in the request body. | | 23 | Missing required parameter | The request cannot be processed because a required query parameter is missing. | Check the missing parameter name in the response message, and ensure that you include the parameter in the query. | | 30 | Rule restriction | The request cannot be processed due to the violation of a Zuora business rule. | Check the response message and ensure that the API request meets the specified business rules. | | 40 | Not found | The specified resource cannot be found. | Check the response message and ensure that the specified resource exists in your Zuora tenant. | | 45 | Unsupported request | The requested endpoint does not support the specified HTTP method. | Check your request and ensure that the endpoint and method matches. | | 50 | Locking contention | This request cannot be processed because the objects this request is trying to modify are being modified by another API request, UI operation, or batch job process. | <p>Resubmit the request first to have another try.</p> <p>If this error still occurs, contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> with the returned `Zuora-Request-Id` value in the response header for assistance.</p> | | 60 | Internal error | The server encounters an internal error. | Contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> with the returned `Zuora-Request-Id` value in the response header for assistance. | | 61 | Temporary error | A temporary error occurs during request processing, for example, a database communication error. | <p>Resubmit the request first to have another try.</p> <p>If this error still occurs, contact <a href=\"https://support.zuora.com\" target=\"_blank\">Zuora Global Support</a> with the returned `Zuora-Request-Id` value in the response header for assistance. </p>| | 70 | Request exceeded limit | The total number of concurrent requests exceeds the limit allowed by the system. | <p>Resubmit the request after the number of seconds specified by the `Retry-After` value in the response header.</p> <p>Check [Concurrent request limits](https://www.zuora.com/developer/rest-api/general-concepts/rate-concurrency-limits/) for details about Zuora’s concurrent request limit policy.</p> | | 90 | Malformed request | The request cannot be processed due to JSON syntax errors. | Check the syntax error in the JSON request body and ensure that the request is in the correct JSON format. | | 99 | Integration error | The server encounters an error when communicating with an external system, for example, payment gateway, tax engine provider. | Check the response message and take action accordingly. | # API Versions The Zuora REST API are version controlled. Versioning ensures that Zuora REST API changes are backward compatible. Zuora uses a major and minor version nomenclature to manage changes. By specifying a version in a REST request, you can get expected responses regardless of future changes to the API. ## Major Version The major version number of the REST API appears in the REST URL. In this API reference, only the **v1** major version is available. For example, `POST https://rest.zuora.com/v1/subscriptions`. ## Minor Version Zuora uses minor versions for the REST API to control small changes. For example, a field in a REST method is deprecated and a new field is used to replace it. Some fields in the REST methods are supported as of minor versions. If a field is not noted with a minor version, this field is available for all minor versions. If a field is noted with a minor version, this field is in version control. You must specify the supported minor version in the request header to process without an error. If a field is in version control, it is either with a minimum minor version or a maximum minor version, or both of them. You can only use this field with the minor version between the minimum and the maximum minor versions. For example, the `invoiceCollect` field in the POST Subscription method is in version control and its maximum minor version is 189.0. You can only use this field with the minor version 189.0 or earlier. If you specify a version number in the request header that is not supported, Zuora will use the minimum minor version of the REST API. In our REST API documentation, if a field or feature requires a minor version number, we note that in the field description. You only need to specify the version number when you use the fields require a minor version. To specify the minor version, set the `zuora-version` parameter to the minor version number in the request header for the request call. For example, the `collect` field is in 196.0 minor version. If you want to use this field for the POST Subscription method, set the `zuora-version` parameter to `196.0` in the request header. The `zuora-version` parameter is case sensitive. For all the REST API fields, by default, if the minor version is not specified in the request header, Zuora will use the minimum minor version of the REST API to avoid breaking your integration. ### Minor Version History The supported minor versions are not serial. This section documents the changes made to each Zuora REST API minor version. The following table lists the supported versions and the fields that have a Zuora REST API minor version. | Fields | Minor Version | REST Methods | Description | |:--------|:--------|:--------|:--------| | invoiceCollect | 189.0 and earlier | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Generates an invoice and collects a payment for a subscription. | | collect | 196.0 and later | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Collects an automatic payment for a subscription. | | invoice | 196.0 and 207.0| [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Generates an invoice for a subscription. | | invoiceTargetDate | 206.0 and earlier | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\") |Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | invoiceTargetDate | 207.0 and earlier | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | targetDate | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\") |Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | targetDate | 211.0 and later | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Date through which charges are calculated on the invoice, as `yyyy-mm-dd`. | | includeExisting DraftInvoiceItems | 206.0 and earlier| [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | Specifies whether to include draft invoice items in subscription previews. Specify it to be `true` (default) to include draft invoice items in the preview result. Specify it to be `false` to excludes draft invoice items in the preview result. | | includeExisting DraftDocItems | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | Specifies whether to include draft invoice items in subscription previews. Specify it to be `true` (default) to include draft invoice items in the preview result. Specify it to be `false` to excludes draft invoice items in the preview result. | | previewType | 206.0 and earlier| [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | The type of preview you will receive. The possible values are `InvoiceItem`(default), `ChargeMetrics`, and `InvoiceItemChargeMetrics`. | | previewType | 207.0 and later | [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") | The type of preview you will receive. The possible values are `LegalDoc`(default), `ChargeMetrics`, and `LegalDocChargeMetrics`. | | runBilling | 211.0 and later | [Create Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_Subscription \"Create Subscription\"); [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\"); [Renew Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_RenewSubscription \"Renew Subscription\"); [Cancel Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelSubscription \"Cancel Subscription\"); [Suspend Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_SuspendSubscription \"Suspend Subscription\"); [Resume Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_ResumeSubscription \"Resume Subscription\"); [Create Account](https://www.zuora.com/developer/api-references/api/operation/POST_Account \"Create Account\")|Generates an invoice or credit memo for a subscription. **Note:** Credit memos are only available if you have the Invoice Settlement feature enabled. | | invoiceDate | 214.0 and earlier | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date that should appear on the invoice being generated, as `yyyy-mm-dd`. | | invoiceTargetDate | 214.0 and earlier | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date through which to calculate charges on this account if an invoice is generated, as `yyyy-mm-dd`. | | documentDate | 215.0 and later | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date that should appear on the invoice and credit memo being generated, as `yyyy-mm-dd`. | | targetDate | 215.0 and later | [Invoice and Collect](https://www.zuora.com/developer/api-references/api/operation/POST_TransactionInvoicePayment \"Invoice and Collect\") |Date through which to calculate charges on this account if an invoice or a credit memo is generated, as `yyyy-mm-dd`. | | memoItemAmount | 223.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | Amount of the memo item. | | amount | 224.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | Amount of the memo item. | | subscriptionNumbers | 222.4 and earlier | [Create order](https://www.zuora.com/developer/api-references/api/operation/POST_Order \"Create order\") | Container for the subscription numbers of the subscriptions in an order. | | subscriptions | 223.0 and later | [Create order](https://www.zuora.com/developer/api-references/api/operation/POST_Order \"Create order\") | Container for the subscription numbers and statuses in an order. | | creditTaxItems | 238.0 and earlier | [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\") | Container for the taxation items of the credit memo item. | | taxItems | 238.0 and earlier | [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Container for the taxation items of the debit memo item. | | taxationItems | 239.0 and later | [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\"); [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Container for the taxation items of the memo item. | | chargeId | 256.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | ID of the product rate plan charge that the memo is created from. | | productRatePlanChargeId | 257.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\") | ID of the product rate plan charge that the memo is created from. | | comment | 256.0 and earlier | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\"); [Create credit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromInvoice \"Create credit memo from invoice\"); [Create debit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromInvoice \"Create debit memo from invoice\"); [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\"); [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Comments about the product rate plan charge, invoice item, or memo item. | | description | 257.0 and later | [Create credit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromPrpc \"Create credit memo from charge\"); [Create debit memo from charge](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromPrpc \"Create debit memo from charge\"); [Create credit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_CreditMemoFromInvoice \"Create credit memo from invoice\"); [Create debit memo from invoice](https://www.zuora.com/developer/api-references/api/operation/POST_DebitMemoFromInvoice \"Create debit memo from invoice\"); [Get credit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItems \"Get credit memo items\"); [Get credit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_CreditMemoItem \"Get credit memo item\"); [Get debit memo items](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItems \"Get debit memo items\"); [Get debit memo item](https://www.zuora.com/developer/api-references/api/operation/GET_DebitMemoItem \"Get debit memo item\") | Description of the the product rate plan charge, invoice item, or memo item. | | taxationItems | 309.0 and later | [Preview an order](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewOrder \"Preview an order\") | List of taxation items for an invoice item or a credit memo item. | | batch | 309.0 and earlier | [Create a billing preview run](https://www.zuora.com/developer/api-references/api/operation/POST_BillingPreviewRun \"Create a billing preview run\") | The customer batches to include in the billing preview run. | | batches | 314.0 and later | [Create a billing preview run](https://www.zuora.com/developer/api-references/api/operation/POST_BillingPreviewRun \"Create a billing preview run\") | The customer batches to include in the billing preview run. | | taxationItems | 315.0 and later | [Preview a subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription \"Preview a subscription\"); [Update a subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update a subscription\")| List of taxation items for an invoice item or a credit memo item. | | billingDocument | 330.0 and later | [Create a payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedule \"Create a payment schedule\"); [Create multiple payment schedules at once](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedules \"Create multiple payment schedules at once\")| The billing document with which the payment schedule item is associated. | | paymentId | 336.0 and earlier | [Add payment schedule items to a custom payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_AddItemsToCustomPaymentSchedule/ \"Add payment schedule items to a custom payment schedule\"); [Update a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentSchedule/ \"Update a payment schedule\"); [Update a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleItem/ \"Update a payment schedule item\"); [Preview the result of payment schedule update](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleUpdatePreview/ \"Preview the result of payment schedule update\"); [Retrieve a payment schedule](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedule/ \"Retrieve a payment schedule\"); [Retrieve a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentScheduleItem/ \"Retrieve a payment schedule item\"); [List payment schedules by customer account](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedules/ \"List payment schedules by customer account\"); [Cancel a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentSchedule/ \"Cancel a payment schedule\"); [Cancel a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentScheduleItem/ \"Cancel a payment schedule item\");[Skip a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_SkipPaymentScheduleItem/ \"Skip a payment schedule item\");[Retry failed payment schedule items](https://www.zuora.com/developer/api-references/api/operation/POST_RetryPaymentScheduleItem/ \"Retry failed payment schedule items\") | ID of the payment to be linked to the payment schedule item. | | paymentOption | 337.0 and later | [Create a payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedule/ \"Create a payment schedule\"); [Create multiple payment schedules at once](https://www.zuora.com/developer/api-references/api/operation/POST_PaymentSchedules/ \"Create multiple payment schedules at once\"); [Create a payment](https://www.zuora.com/developer/api-references/api/operation/POST_CreatePayment/ \"Create a payment\"); [Add payment schedule items to a custom payment schedule](https://www.zuora.com/developer/api-references/api/operation/POST_AddItemsToCustomPaymentSchedule/ \"Add payment schedule items to a custom payment schedule\"); [Update a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentSchedule/ \"Update a payment schedule\"); [Update a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleItem/ \"Update a payment schedule item\"); [Preview the result of payment schedule update](https://www.zuora.com/developer/api-references/api/operation/PUT_PaymentScheduleUpdatePreview/ \"Preview the result of payment schedule update\"); [Retrieve a payment schedule](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedule/ \"Retrieve a payment schedule\"); [Retrieve a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentScheduleItem/ \"Retrieve a payment schedule item\"); [List payment schedules by customer account](https://www.zuora.com/developer/api-references/api/operation/GET_PaymentSchedules/ \"List payment schedules by customer account\"); [Cancel a payment schedule](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentSchedule/ \"Cancel a payment schedule\"); [Cancel a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_CancelPaymentScheduleItem/ \"Cancel a payment schedule item\"); [Skip a payment schedule item](https://www.zuora.com/developer/api-references/api/operation/PUT_SkipPaymentScheduleItem/ \"Skip a payment schedule item\"); [Retry failed payment schedule items](https://www.zuora.com/developer/api-references/api/operation/POST_RetryPaymentScheduleItem/ \"Retry failed payment schedule items\"); [List payments](https://www.zuora.com/developer/api-references/api/operation/GET_RetrieveAllPayments/ \"List payments\") | Array of transactional level rules for processing payments. | #### Version 207.0 and Later The response structure of the [Preview Subscription](https://www.zuora.com/developer/api-references/api/operation/POST_PreviewSubscription) and [Update Subscription](https://www.zuora.com/developer/api-references/api/operation/PUT_Subscription \"Update Subscription\") methods are changed. The following invoice related response fields are moved to the invoice container: * amount * amountWithoutTax * taxAmount * invoiceItems * targetDate * chargeMetrics # API Names for Zuora Objects For information about the Zuora business object model, see [Zuora Business Object Model](https://www.zuora.com/developer/rest-api/general-concepts/object-model/). You can use the [Describe](https://www.zuora.com/developer/api-references/api/operation/GET_Describe) operation to list the fields of each Zuora object that is available in your tenant. When you call the operation, you must specify the API name of the Zuora object. The following table provides the API name of each Zuora object: | Object | API Name | |-----------------------------------------------|--------------------------------------------| | Account | `Account` | | Accounting Code | `AccountingCode` | | Accounting Period | `AccountingPeriod` | | Amendment | `Amendment` | | Application Group | `ApplicationGroup` | | Billing Run | <p>`BillingRun` - API name used in the [Describe](https://www.zuora.com/developer/api-references/api/operation/GET_Describe) operation, Export ZOQL queries, and Data Query.</p> <p>`BillRun` - API name used in the [Actions](https://www.zuora.com/developer/api-references/api/tag/Actions). See the CRUD oprations of [Bill Run](https://www.zuora.com/developer/api-references/api/tag/Bill-Run) for more information about the `BillRun` object. `BillingRun` and `BillRun` have different fields. | | Configuration Templates | `ConfigurationTemplates` | | Contact | `Contact` | | Contact Snapshot | `ContactSnapshot` | | Credit Balance Adjustment | `CreditBalanceAdjustment` | | Credit Memo | `CreditMemo` | | Credit Memo Application | `CreditMemoApplication` | | Credit Memo Application Item | `CreditMemoApplicationItem` | | Credit Memo Item | `CreditMemoItem` | | Credit Memo Part | `CreditMemoPart` | | Credit Memo Part Item | `CreditMemoPartItem` | | Credit Taxation Item | `CreditTaxationItem` | | Custom Exchange Rate | `FXCustomRate` | | Debit Memo | `DebitMemo` | | Debit Memo Item | `DebitMemoItem` | | Debit Taxation Item | `DebitTaxationItem` | | Discount Applied Metrics | `DiscountAppliedMetrics` | | Entity | `Tenant` | | Fulfillment | `Fulfillment` | | Feature | `Feature` | | Gateway Reconciliation Event | `PaymentGatewayReconciliationEventLog` | | Gateway Reconciliation Job | `PaymentReconciliationJob` | | Gateway Reconciliation Log | `PaymentReconciliationLog` | | Invoice | `Invoice` | | Invoice Adjustment | `InvoiceAdjustment` | | Invoice Item | `InvoiceItem` | | Invoice Item Adjustment | `InvoiceItemAdjustment` | | Invoice Payment | `InvoicePayment` | | Invoice Schedule | `InvoiceSchedule` | | Journal Entry | `JournalEntry` | | Journal Entry Item | `JournalEntryItem` | | Journal Run | `JournalRun` | | Notification History - Callout | `CalloutHistory` | | Notification History - Email | `EmailHistory` | | Offer | `Offer` | | Order | `Order` | | Order Action | `OrderAction` | | Order ELP | `OrderElp` | | Order Line Items | `OrderLineItems` | | Order Item | `OrderItem` | | Order MRR | `OrderMrr` | | Order Quantity | `OrderQuantity` | | Order TCB | `OrderTcb` | | Order TCV | `OrderTcv` | | Payment | `Payment` | | Payment Application | `PaymentApplication` | | Payment Application Item | `PaymentApplicationItem` | | Payment Method | `PaymentMethod` | | Payment Method Snapshot | `PaymentMethodSnapshot` | | Payment Method Transaction Log | `PaymentMethodTransactionLog` | | Payment Method Update | `UpdaterDetail` | | Payment Part | `PaymentPart` | | Payment Part Item | `PaymentPartItem` | | Payment Run | `PaymentRun` | | Payment Transaction Log | `PaymentTransactionLog` | | Price Book Item | `PriceBookItem` | | Processed Usage | `ProcessedUsage` | | Product | `Product` | | Product Feature | `ProductFeature` | | Product Rate Plan | `ProductRatePlan` | | Product Rate Plan Charge | `ProductRatePlanCharge` | | Product Rate Plan Charge Tier | `ProductRatePlanChargeTier` | | Rate Plan | `RatePlan` | | Rate Plan Charge | `RatePlanCharge` | | Rate Plan Charge Tier | `RatePlanChargeTier` | | Refund | `Refund` | | Refund Application | `RefundApplication` | | Refund Application Item | `RefundApplicationItem` | | Refund Invoice Payment | `RefundInvoicePayment` | | Refund Part | `RefundPart` | | Refund Part Item | `RefundPartItem` | | Refund Transaction Log | `RefundTransactionLog` | | Revenue Charge Summary | `RevenueChargeSummary` | | Revenue Charge Summary Item | `RevenueChargeSummaryItem` | | Revenue Event | `RevenueEvent` | | Revenue Event Credit Memo Item | `RevenueEventCreditMemoItem` | | Revenue Event Debit Memo Item | `RevenueEventDebitMemoItem` | | Revenue Event Invoice Item | `RevenueEventInvoiceItem` | | Revenue Event Invoice Item Adjustment | `RevenueEventInvoiceItemAdjustment` | | Revenue Event Item | `RevenueEventItem` | | Revenue Event Item Credit Memo Item | `RevenueEventItemCreditMemoItem` | | Revenue Event Item Debit Memo Item | `RevenueEventItemDebitMemoItem` | | Revenue Event Item Invoice Item | `RevenueEventItemInvoiceItem` | | Revenue Event Item Invoice Item Adjustment | `RevenueEventItemInvoiceItemAdjustment` | | Revenue Event Type | `RevenueEventType` | | Revenue Schedule | `RevenueSchedule` | | Revenue Schedule Credit Memo Item | `RevenueScheduleCreditMemoItem` | | Revenue Schedule Debit Memo Item | `RevenueScheduleDebitMemoItem` | | Revenue Schedule Invoice Item | `RevenueScheduleInvoiceItem` | | Revenue Schedule Invoice Item Adjustment | `RevenueScheduleInvoiceItemAdjustment` | | Revenue Schedule Item | `RevenueScheduleItem` | | Revenue Schedule Item Credit Memo Item | `RevenueScheduleItemCreditMemoItem` | | Revenue Schedule Item Debit Memo Item | `RevenueScheduleItemDebitMemoItem` | | Revenue Schedule Item Invoice Item | `RevenueScheduleItemInvoiceItem` | | Revenue Schedule Item Invoice Item Adjustment | `RevenueScheduleItemInvoiceItemAdjustment` | | Subscription | `Subscription` | | Subscription Product Feature | `SubscriptionProductFeature` | | Taxable Item Snapshot | `TaxableItemSnapshot` | | Taxation Item | `TaxationItem` | | Updater Batch | `UpdaterBatch` | | Usage | `Usage` | # noqa: E501
OpenAPI spec version: 2023-07-24
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import models into model package
from swagger_client.models.account import Account
from swagger_client.models.account_credit_card_holder import AccountCreditCardHolder
from swagger_client.models.account_data import AccountData
from swagger_client.models.account_object_custom_fields import AccountObjectCustomFields
from swagger_client.models.account_object_ns_fields import AccountObjectNSFields
from swagger_client.models.accounting_code_object_custom_fields import AccountingCodeObjectCustomFields
from swagger_client.models.accounting_period_object_custom_fields import AccountingPeriodObjectCustomFields
from swagger_client.models.actions_error_response import ActionsErrorResponse
from swagger_client.models.api_volume_summary_record import ApiVolumeSummaryRecord
from swagger_client.models.apply_credit_memo_type import ApplyCreditMemoType
from swagger_client.models.apply_payment_type import ApplyPaymentType
from swagger_client.models.bad_request_response import BadRequestResponse
from swagger_client.models.bad_request_response_errors import BadRequestResponseErrors
from swagger_client.models.batch_debit_memo_type import BatchDebitMemoType
from swagger_client.models.batch_invoice_type import BatchInvoiceType
from swagger_client.models.batch_queries import BatchQueries
from swagger_client.models.batch_query import BatchQuery
from swagger_client.models.batches_queries import BatchesQueries
from swagger_client.models.batches_queries_by_id import BatchesQueriesById
from swagger_client.models.bill_run_filter_request_type import BillRunFilterRequestType
from swagger_client.models.bill_run_filter_response_type import BillRunFilterResponseType
from swagger_client.models.bill_run_filters import BillRunFilters
from swagger_client.models.bill_run_schedule_request_type import BillRunScheduleRequestType
from swagger_client.models.bill_run_schedule_response_type import BillRunScheduleResponseType
from swagger_client.models.bill_to_contact import BillToContact
from swagger_client.models.bill_to_contact_post_order import BillToContactPostOrder
from swagger_client.models.billing_doc_volume_summary_record import BillingDocVolumeSummaryRecord
from swagger_client.models.billing_document_query_response_element_type import BillingDocumentQueryResponseElementType
from swagger_client.models.billing_options import BillingOptions
from swagger_client.models.billing_preview_result import BillingPreviewResult
from swagger_client.models.billing_update import BillingUpdate
from swagger_client.models.body import Body
from swagger_client.models.body_in_setting_value_reponse import BodyInSettingValueReponse
from swagger_client.models.body_in_setting_value_request import BodyInSettingValueRequest
from swagger_client.models.bulk_credit_memos_response_type import BulkCreditMemosResponseType
from swagger_client.models.bulk_debit_memos_response_type import BulkDebitMemosResponseType
from swagger_client.models.callout_auth import CalloutAuth
from swagger_client.models.callout_merge_fields import CalloutMergeFields
from swagger_client.models.cancel_bill_run_response_type import CancelBillRunResponseType
from swagger_client.models.cancel_subscription import CancelSubscription
from swagger_client.models.catalog_group_response import CatalogGroupResponse
from swagger_client.models.change_plan import ChangePlan
from swagger_client.models.change_plan_rate_plan_override import ChangePlanRatePlanOverride
from swagger_client.models.charge_model_configuration_type import ChargeModelConfigurationType
from swagger_client.models.charge_model_data_override import ChargeModelDataOverride
from swagger_client.models.charge_model_data_override_charge_model_configuration import ChargeModelDataOverrideChargeModelConfiguration
from swagger_client.models.charge_override import ChargeOverride
from swagger_client.models.charge_override_billing import ChargeOverrideBilling
from swagger_client.models.charge_override_pricing import ChargeOverridePricing
from swagger_client.models.charge_preview_metrics import ChargePreviewMetrics
from swagger_client.models.charge_preview_metrics_cmrr import ChargePreviewMetricsCmrr
from swagger_client.models.charge_preview_metrics_tax import ChargePreviewMetricsTax
from swagger_client.models.charge_preview_metrics_tcb import ChargePreviewMetricsTcb
from swagger_client.models.charge_preview_metrics_tcv import ChargePreviewMetricsTcv
from swagger_client.models.charge_tier import ChargeTier
from swagger_client.models.charge_update import ChargeUpdate
from swagger_client.models.charge_update_pricing import ChargeUpdatePricing
from swagger_client.models.children_setting_value_request import ChildrenSettingValueRequest
from swagger_client.models.common_error_response import CommonErrorResponse
from swagger_client.models.common_response_type import CommonResponseType
from swagger_client.models.common_response_type_reasons import CommonResponseTypeReasons
from swagger_client.models.compare_schema_info_response import CompareSchemaInfoResponse
from swagger_client.models.compare_schema_key_value import CompareSchemaKeyValue
from swagger_client.models.config_template_error_response import ConfigTemplateErrorResponse
from swagger_client.models.config_template_error_response_reasons import ConfigTemplateErrorResponseReasons
from swagger_client.models.configuration_template_content import ConfigurationTemplateContent
from swagger_client.models.contact_info import ContactInfo
from swagger_client.models.contact_object_custom_fields import ContactObjectCustomFields
from swagger_client.models.contact_response import ContactResponse
from swagger_client.models.contact_snapshot_object_custom_fields import ContactSnapshotObjectCustomFields
from swagger_client.models.create_change_plan import CreateChangePlan
from swagger_client.models.create_offer_rate_plan_override import CreateOfferRatePlanOverride
from swagger_client.models.create_or_update_email_templates_response import CreateOrUpdateEmailTemplatesResponse
from swagger_client.models.create_order_change_plan_rate_plan_override import CreateOrderChangePlanRatePlanOverride
from swagger_client.models.create_order_charge_override import CreateOrderChargeOverride
from swagger_client.models.create_order_charge_override_billing import CreateOrderChargeOverrideBilling
from swagger_client.models.create_order_charge_override_pricing import CreateOrderChargeOverridePricing
from swagger_client.models.create_order_charge_update import CreateOrderChargeUpdate
from swagger_client.models.create_order_create_subscription import CreateOrderCreateSubscription
from swagger_client.models.create_order_create_subscription_new_subscription_owner_account import CreateOrderCreateSubscriptionNewSubscriptionOwnerAccount
from swagger_client.models.create_order_create_subscription_terms import CreateOrderCreateSubscriptionTerms
from swagger_client.models.create_order_create_subscription_terms_initial_term import CreateOrderCreateSubscriptionTermsInitialTerm
from swagger_client.models.create_order_offer_update import CreateOrderOfferUpdate
from swagger_client.models.create_order_order_action import CreateOrderOrderAction
from swagger_client.models.create_order_order_action_add_product import CreateOrderOrderActionAddProduct
from swagger_client.models.create_order_order_action_update_product import CreateOrderOrderActionUpdateProduct
from swagger_client.models.create_order_order_line_item import CreateOrderOrderLineItem
from swagger_client.models.create_order_pricing_update import CreateOrderPricingUpdate
from swagger_client.models.create_order_pricing_update_charge_model_data import CreateOrderPricingUpdateChargeModelData
from swagger_client.models.create_order_pricing_update_discount import CreateOrderPricingUpdateDiscount
from swagger_client.models.create_order_pricing_update_recurring_delivery_based import CreateOrderPricingUpdateRecurringDeliveryBased
from swagger_client.models.create_order_pricing_update_recurring_flat_fee import CreateOrderPricingUpdateRecurringFlatFee
from swagger_client.models.create_order_pricing_update_recurring_per_unit import CreateOrderPricingUpdateRecurringPerUnit
from swagger_client.models.create_order_pricing_update_recurring_tiered import CreateOrderPricingUpdateRecurringTiered
from swagger_client.models.create_order_pricing_update_recurring_volume import CreateOrderPricingUpdateRecurringVolume
from swagger_client.models.create_order_pricing_update_usage_flat_fee import CreateOrderPricingUpdateUsageFlatFee
from swagger_client.models.create_order_pricing_update_usage_overage import CreateOrderPricingUpdateUsageOverage
from swagger_client.models.create_order_pricing_update_usage_per_unit import CreateOrderPricingUpdateUsagePerUnit
from swagger_client.models.create_order_pricing_update_usage_tiered import CreateOrderPricingUpdateUsageTiered
from swagger_client.models.create_order_pricing_update_usage_tiered_with_overage import CreateOrderPricingUpdateUsageTieredWithOverage
from swagger_client.models.create_order_pricing_update_usage_volume import CreateOrderPricingUpdateUsageVolume
from swagger_client.models.create_order_product_override import CreateOrderProductOverride
from swagger_client.models.create_order_rate_plan_feature_override import CreateOrderRatePlanFeatureOverride
from swagger_client.models.create_order_rate_plan_override import CreateOrderRatePlanOverride
from swagger_client.models.create_order_rate_plan_update import CreateOrderRatePlanUpdate
from swagger_client.models.create_order_resume import CreateOrderResume
from swagger_client.models.create_order_suspend import CreateOrderSuspend
from swagger_client.models.create_order_terms_and_conditions import CreateOrderTermsAndConditions
from swagger_client.models.create_order_trigger_params import CreateOrderTriggerParams
from swagger_client.models.create_order_update_product_trigger_params import CreateOrderUpdateProductTriggerParams
from swagger_client.models.create_pm_pay_pal_ec_pay_pal_native_ec_pay_pal_cp import CreatePMPayPalECPayPalNativeECPayPalCP
from swagger_client.models.create_payment_method_ach import CreatePaymentMethodACH
from swagger_client.models.create_payment_method_apple_pay_adyen import CreatePaymentMethodApplePayAdyen
from swagger_client.models.create_payment_method_bank_transfer import CreatePaymentMethodBankTransfer
from swagger_client.models.create_payment_method_bank_transfer_account_holder_info import CreatePaymentMethodBankTransferAccountHolderInfo
from swagger_client.models.create_payment_method_cc_reference_transaction import CreatePaymentMethodCCReferenceTransaction
from swagger_client.models.create_payment_method_cardholder_info import CreatePaymentMethodCardholderInfo
from swagger_client.models.create_payment_method_common import CreatePaymentMethodCommon
from swagger_client.models.create_payment_method_credit_card import CreatePaymentMethodCreditCard
from swagger_client.models.create_payment_method_google_pay_adyen_chase import CreatePaymentMethodGooglePayAdyenChase
from swagger_client.models.create_payment_method_pay_pal_adaptive import CreatePaymentMethodPayPalAdaptive
from swagger_client.models.create_payment_type import CreatePaymentType
from swagger_client.models.create_stored_credential_profile_request import CreateStoredCredentialProfileRequest
from swagger_client.models.create_subscribe_to_product import CreateSubscribeToProduct
from swagger_client.models.create_subscription import CreateSubscription
from swagger_client.models.create_subscription_new_subscription_owner_account import CreateSubscriptionNewSubscriptionOwnerAccount
from swagger_client.models.create_subscription_terms import CreateSubscriptionTerms
from swagger_client.models.create_template_request_content import CreateTemplateRequestContent
from swagger_client.models.credit_card import CreditCard
from swagger_client.models.credit_memo_apply_debit_memo_item_request_type import CreditMemoApplyDebitMemoItemRequestType
from swagger_client.models.credit_memo_apply_debit_memo_request_type import CreditMemoApplyDebitMemoRequestType
from swagger_client.models.credit_memo_apply_invoice_item_request_type import CreditMemoApplyInvoiceItemRequestType
from swagger_client.models.credit_memo_apply_invoice_request_type import CreditMemoApplyInvoiceRequestType
from swagger_client.models.credit_memo_entity_prefix import CreditMemoEntityPrefix
from swagger_client.models.credit_memo_from_charge_custom_rates_type import CreditMemoFromChargeCustomRatesType
from swagger_client.models.credit_memo_from_charge_detail_type import CreditMemoFromChargeDetailType
from swagger_client.models.credit_memo_from_charge_type import CreditMemoFromChargeType
from swagger_client.models.credit_memo_from_invoice_type import CreditMemoFromInvoiceType
from swagger_client.models.credit_memo_item_from_invoice_item_type import CreditMemoItemFromInvoiceItemType
from swagger_client.models.credit_memo_item_from_write_off_invoice import CreditMemoItemFromWriteOffInvoice
from swagger_client.models.credit_memo_item_object_custom_fields import CreditMemoItemObjectCustomFields
from swagger_client.models.credit_memo_object_custom_fields import CreditMemoObjectCustomFields
from swagger_client.models.credit_memo_object_ns_fields import CreditMemoObjectNSFields
from swagger_client.models.credit_memo_response_type import CreditMemoResponseType
from swagger_client.models.credit_memo_tax_item_from_invoice_tax_item_type import CreditMemoTaxItemFromInvoiceTaxItemType
from swagger_client.models.credit_memo_tax_item_from_invoice_tax_item_type_finance_information import CreditMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation
from swagger_client.models.credit_memo_unapply_debit_memo_item_request_type import CreditMemoUnapplyDebitMemoItemRequestType
from swagger_client.models.credit_memo_unapply_debit_memo_request_type import CreditMemoUnapplyDebitMemoRequestType
from swagger_client.models.credit_memo_unapply_invoice_item_request_type import CreditMemoUnapplyInvoiceItemRequestType
from swagger_client.models.credit_memo_unapply_invoice_request_type import CreditMemoUnapplyInvoiceRequestType
from swagger_client.models.credit_memos_from_charges import CreditMemosFromCharges
from swagger_client.models.credit_memos_from_invoices import CreditMemosFromInvoices
from swagger_client.models.credit_taxation_item_object_custom_fields import CreditTaxationItemObjectCustomFields
from swagger_client.models.custom_account_payment_method import CustomAccountPaymentMethod
from swagger_client.models.custom_fields import CustomFields
from swagger_client.models.custom_object_all_fields_definition import CustomObjectAllFieldsDefinition
from swagger_client.models.custom_object_bulk_delete_filter import CustomObjectBulkDeleteFilter
from swagger_client.models.custom_object_bulk_delete_filter_condition import CustomObjectBulkDeleteFilterCondition
from swagger_client.models.custom_object_bulk_job_error_response import CustomObjectBulkJobErrorResponse
from swagger_client.models.custom_object_bulk_job_error_response_collection import CustomObjectBulkJobErrorResponseCollection
from swagger_client.models.custom_object_bulk_job_request import CustomObjectBulkJobRequest
from swagger_client.models.custom_object_bulk_job_response import CustomObjectBulkJobResponse
from swagger_client.models.custom_object_bulk_job_response_collection import CustomObjectBulkJobResponseCollection
from swagger_client.models.custom_object_bulk_job_response_error import CustomObjectBulkJobResponseError
from swagger_client.models.custom_object_custom_field_definition import CustomObjectCustomFieldDefinition
from swagger_client.models.custom_object_custom_field_definition_update import CustomObjectCustomFieldDefinitionUpdate
from swagger_client.models.custom_object_custom_fields_definition import CustomObjectCustomFieldsDefinition
from swagger_client.models.custom_object_definition import CustomObjectDefinition
from swagger_client.models.custom_object_definition_schema import CustomObjectDefinitionSchema
from swagger_client.models.custom_object_definition_update_action_request import CustomObjectDefinitionUpdateActionRequest
from swagger_client.models.custom_object_definition_update_action_response import CustomObjectDefinitionUpdateActionResponse
from swagger_client.models.custom_object_definitions import CustomObjectDefinitions
from swagger_client.models.custom_object_record_batch_action import CustomObjectRecordBatchAction
from swagger_client.models.custom_object_record_batch_request import CustomObjectRecordBatchRequest
from swagger_client.models.custom_object_record_batch_update_mapping import CustomObjectRecordBatchUpdateMapping
from swagger_client.models.custom_object_record_with_all_fields import CustomObjectRecordWithAllFields
from swagger_client.models.custom_object_record_with_only_custom_fields import CustomObjectRecordWithOnlyCustomFields
from swagger_client.models.custom_object_records_batch_update_partial_success_response import CustomObjectRecordsBatchUpdatePartialSuccessResponse
from swagger_client.models.custom_object_records_error_response import CustomObjectRecordsErrorResponse
from swagger_client.models.custom_object_records_throttled_response import CustomObjectRecordsThrottledResponse
from swagger_client.models.custom_object_records_with_error import CustomObjectRecordsWithError
from swagger_client.models.data_access_control_field import DataAccessControlField
from swagger_client.models.data_query_error_response import DataQueryErrorResponse
from swagger_client.models.data_query_job import DataQueryJob
from swagger_client.models.data_query_job_cancelled import DataQueryJobCancelled
from swagger_client.models.data_query_job_common import DataQueryJobCommon
from swagger_client.models.debit_memo_collect_request import DebitMemoCollectRequest
from swagger_client.models.debit_memo_collect_request_payment import DebitMemoCollectRequestPayment
from swagger_client.models.debit_memo_collect_response import DebitMemoCollectResponse
from swagger_client.models.debit_memo_collect_response_applied_credit_memos import DebitMemoCollectResponseAppliedCreditMemos
from swagger_client.models.debit_memo_collect_response_applied_payments import DebitMemoCollectResponseAppliedPayments
from swagger_client.models.debit_memo_entity_prefix import DebitMemoEntityPrefix
from swagger_client.models.debit_memo_from_charge_custom_rates_type import DebitMemoFromChargeCustomRatesType
from swagger_client.models.debit_memo_from_charge_detail_type import DebitMemoFromChargeDetailType
from swagger_client.models.debit_memo_from_charge_type import DebitMemoFromChargeType
from swagger_client.models.debit_memo_from_invoice_type import DebitMemoFromInvoiceType
from swagger_client.models.debit_memo_item_from_invoice_item_type import DebitMemoItemFromInvoiceItemType
from swagger_client.models.debit_memo_item_object_custom_fields import DebitMemoItemObjectCustomFields
from swagger_client.models.debit_memo_object_custom_fields import DebitMemoObjectCustomFields
from swagger_client.models.debit_memo_object_custom_fields_cm_write_off import DebitMemoObjectCustomFieldsCMWriteOff
from swagger_client.models.debit_memo_object_ns_fields import DebitMemoObjectNSFields
from swagger_client.models.debit_memo_tax_item_from_invoice_tax_item_type import DebitMemoTaxItemFromInvoiceTaxItemType
from swagger_client.models.debit_memo_tax_item_from_invoice_tax_item_type_finance_information import DebitMemoTaxItemFromInvoiceTaxItemTypeFinanceInformation
from swagger_client.models.debit_memos_from_charges import DebitMemosFromCharges
from swagger_client.models.debit_memos_from_invoices import DebitMemosFromInvoices
from swagger_client.models.debit_taxation_item_object_custom_fields import DebitTaxationItemObjectCustomFields
from swagger_client.models.delete_account_response_type import DeleteAccountResponseType
from swagger_client.models.delete_account_response_type_reasons import DeleteAccountResponseTypeReasons
from swagger_client.models.delete_batch_query_job_response import DeleteBatchQueryJobResponse
from swagger_client.models.delete_data_query_job_response import DeleteDataQueryJobResponse
from swagger_client.models.delete_invoice_response_type import DeleteInvoiceResponseType
from swagger_client.models.delete_result import DeleteResult
from swagger_client.models.delete_workflow_error import DeleteWorkflowError
from swagger_client.models.delete_workflow_success import DeleteWorkflowSuccess
from swagger_client.models.deleted_record import DeletedRecord
from swagger_client.models.deleted_record1 import DeletedRecord1
from swagger_client.models.delivery_schedule_params import DeliveryScheduleParams
from swagger_client.models.detailed_workflow import DetailedWorkflow
from swagger_client.models.discount_item_object_custom_fields import DiscountItemObjectCustomFields
from swagger_client.models.discount_item_object_ns_fields import DiscountItemObjectNSFields
from swagger_client.models.discount_pricing_override import DiscountPricingOverride
from swagger_client.models.discount_pricing_update import DiscountPricingUpdate
from swagger_client.models.end_conditions import EndConditions
from swagger_client.models.error401 import Error401
from swagger_client.models.error_response import ErrorResponse
from swagger_client.models.error_response401_record import ErrorResponse401Record
from swagger_client.models.error_response_reasons import ErrorResponseReasons
from swagger_client.models.event_trigger import EventTrigger
from swagger_client.models.event_type import EventType
from swagger_client.models.execute_invoice_schedule_bill_run_response import ExecuteInvoiceScheduleBillRunResponse
from swagger_client.models.export_workflow_version_response import ExportWorkflowVersionResponse
from swagger_client.models.fields_additional_properties import FieldsAdditionalProperties
from swagger_client.models.fields_additional_properties_for_post_definition import FieldsAdditionalPropertiesForPostDefinition
from swagger_client.models.filter_rule_parameter_definition import FilterRuleParameterDefinition
from swagger_client.models.filter_rule_parameter_definitions import FilterRuleParameterDefinitions
from swagger_client.models.filter_rule_parameter_values import FilterRuleParameterValues
from swagger_client.models.fulfillment_common import FulfillmentCommon
from swagger_client.models.fulfillment_custom_fields import FulfillmentCustomFields
from swagger_client.models.fulfillment_get import FulfillmentGet
from swagger_client.models.fulfillment_item_common import FulfillmentItemCommon
from swagger_client.models.fulfillment_item_custom_fields import FulfillmentItemCustomFields
from swagger_client.models.fulfillment_item_get import FulfillmentItemGet
from swagger_client.models.fulfillment_item_post import FulfillmentItemPost
from swagger_client.models.fulfillment_item_post_from_fulfillment_post import FulfillmentItemPostFromFulfillmentPost
from swagger_client.models.fulfillment_item_put import FulfillmentItemPut
from swagger_client.models.fulfillment_post import FulfillmentPost
from swagger_client.models.fulfillment_put import FulfillmentPut
from swagger_client.models.geta_payment_gatway_response import GETAPaymentGatwayResponse
from swagger_client.models.getar_payment_type import GETARPaymentType
from swagger_client.models.getar_payment_type_with_payment_option import GETARPaymentTypeWithPaymentOption
from swagger_client.models.getar_payment_typewith_success import GETARPaymentTypewithSuccess
from swagger_client.models.get_account_pm_account_holder_info import GETAccountPMAccountHolderInfo
from swagger_client.models.get_account_payment_method_type import GETAccountPaymentMethodType
from swagger_client.models.get_account_summary_invoice_type import GETAccountSummaryInvoiceType
from swagger_client.models.get_account_summary_payment_invoice_type import GETAccountSummaryPaymentInvoiceType
from swagger_client.models.get_account_summary_payment_type import GETAccountSummaryPaymentType
from swagger_client.models.get_account_summary_subscription_rate_plan_type import GETAccountSummarySubscriptionRatePlanType
from swagger_client.models.get_account_summary_subscription_type import GETAccountSummarySubscriptionType
from swagger_client.models.get_account_summary_type import GETAccountSummaryType
from swagger_client.models.get_account_summary_type_basic_info import GETAccountSummaryTypeBasicInfo
from swagger_client.models.get_account_summary_type_bill_to_contact import GETAccountSummaryTypeBillToContact
from swagger_client.models.get_account_summary_type_sold_to_contact import GETAccountSummaryTypeSoldToContact
from swagger_client.models.get_account_summary_type_tax_info import GETAccountSummaryTypeTaxInfo
from swagger_client.models.get_account_summary_usage_type import GETAccountSummaryUsageType
from swagger_client.models.get_account_type import GETAccountType
from swagger_client.models.get_account_type_basic_info import GETAccountTypeBasicInfo
from swagger_client.models.get_account_type_bill_to_contact import GETAccountTypeBillToContact
from swagger_client.models.get_account_type_billing_and_payment import GETAccountTypeBillingAndPayment
from swagger_client.models.get_account_type_metrics import GETAccountTypeMetrics
from swagger_client.models.get_account_type_sold_to_contact import GETAccountTypeSoldToContact
from swagger_client.models.get_accounting_code_item_type import GETAccountingCodeItemType
from swagger_client.models.get_accounting_code_item_without_success_type import GETAccountingCodeItemWithoutSuccessType
from swagger_client.models.get_accounting_codes_type import GETAccountingCodesType
from swagger_client.models.get_accounting_period_type import GETAccountingPeriodType
from swagger_client.models.get_accounting_period_without_success_type import GETAccountingPeriodWithoutSuccessType
from swagger_client.models.get_accounting_periods_type import GETAccountingPeriodsType
from swagger_client.models.get_adjustments_by_subscription_number_response_type import GETAdjustmentsBySubscriptionNumberResponseType
from swagger_client.models.get_adjustments_response_type import GETAdjustmentsResponseType
from swagger_client.models.get_all_custom_object_definitions_in_namespace_response import GETAllCustomObjectDefinitionsInNamespaceResponse
from swagger_client.models.get_attachment_response_type import GETAttachmentResponseType
from swagger_client.models.get_attachment_response_without_success_type import GETAttachmentResponseWithoutSuccessType
from swagger_client.models.get_attachments_response_type import GETAttachmentsResponseType
from swagger_client.models.get_billing_document_files_deletion_job_response import GETBillingDocumentFilesDeletionJobResponse
from swagger_client.models.get_billing_documents_response_type import GETBillingDocumentsResponseType
from swagger_client.models.getcm_tax_item_type import GETCMTaxItemType
from swagger_client.models.getcm_tax_item_type_new import GETCMTaxItemTypeNew
from swagger_client.models.get_callout_history_vo_type import GETCalloutHistoryVOType
from swagger_client.models.get_callout_history_vos_type import GETCalloutHistoryVOsType
from swagger_client.models.get_cancel_adjustment_response_type import GETCancelAdjustmentResponseType
from swagger_client.models.get_catalog_group_product_rate_plan_response import GETCatalogGroupProductRatePlanResponse
from swagger_client.models.get_catalog_type import GETCatalogType
from swagger_client.models.get_contact_snapshot_response import GETContactSnapshotResponse
from swagger_client.models.get_credit_memo_collection_type import GETCreditMemoCollectionType
from swagger_client.models.get_credit_memo_item_part_type import GETCreditMemoItemPartType
from swagger_client.models.get_credit_memo_item_part_typewith_success import GETCreditMemoItemPartTypewithSuccess
from swagger_client.models.get_credit_memo_item_parts_collection_type import GETCreditMemoItemPartsCollectionType
from swagger_client.models.get_credit_memo_item_type import GETCreditMemoItemType
from swagger_client.models.get_credit_memo_item_typewith_success import GETCreditMemoItemTypewithSuccess
from swagger_client.models.get_credit_memo_items_list_type import GETCreditMemoItemsListType
from swagger_client.models.get_credit_memo_part_type import GETCreditMemoPartType
from swagger_client.models.get_credit_memo_part_typewith_success import GETCreditMemoPartTypewithSuccess
from swagger_client.models.get_credit_memo_parts_collection_type import GETCreditMemoPartsCollectionType
from swagger_client.models.get_credit_memo_type import GETCreditMemoType
from swagger_client.models.get_credit_memo_typewith_success import GETCreditMemoTypewithSuccess
from swagger_client.models.get_custom_exchange_rates_data_type import GETCustomExchangeRatesDataType
from swagger_client.models.get_custom_exchange_rates_type import GETCustomExchangeRatesType
from swagger_client.models.getdm_tax_item_type import GETDMTaxItemType
from swagger_client.models.getdm_tax_item_type_new import GETDMTaxItemTypeNew
from swagger_client.models.get_debit_memo_collection_type import GETDebitMemoCollectionType
from swagger_client.models.get_debit_memo_item_collection_type import GETDebitMemoItemCollectionType
from swagger_client.models.get_debit_memo_item_type import GETDebitMemoItemType
from swagger_client.models.get_debit_memo_item_typewith_success import GETDebitMemoItemTypewithSuccess
from swagger_client.models.get_debit_memo_type import GETDebitMemoType
from swagger_client.models.get_debit_memo_typewith_success import GETDebitMemoTypewithSuccess
from swagger_client.models.get_delivery_schedule_type import GETDeliveryScheduleType
from swagger_client.models.get_discount_apply_details_type import GETDiscountApplyDetailsType
from swagger_client.models.get_email_history_vo_type import GETEmailHistoryVOType
from swagger_client.models.get_email_history_vos_type import GETEmailHistoryVOsType
from swagger_client.models.get_interval_price_tier_type import GETIntervalPriceTierType
from swagger_client.models.get_interval_price_type import GETIntervalPriceType
from swagger_client.models.get_invoice_files_response import GETInvoiceFilesResponse
from swagger_client.models.get_invoice_items_response import GETInvoiceItemsResponse
from swagger_client.models.get_invoice_tax_item_type import GETInvoiceTaxItemType
from swagger_client.models.get_invoice_taxation_items_response import GETInvoiceTaxationItemsResponse
from swagger_client.models.get_journal_entries_in_journal_run_type import GETJournalEntriesInJournalRunType
from swagger_client.models.get_journal_entry_detail_type import GETJournalEntryDetailType
from swagger_client.models.get_journal_entry_detail_type_without_success import GETJournalEntryDetailTypeWithoutSuccess
from swagger_client.models.get_journal_entry_item_type import GETJournalEntryItemType
from swagger_client.models.get_journal_entry_segment_type import GETJournalEntrySegmentType
from swagger_client.models.get_journal_run_transaction_type import GETJournalRunTransactionType
from swagger_client.models.get_journal_run_type import GETJournalRunType
from swagger_client.models.get_mass_update_type import GETMassUpdateType
from swagger_client.models.get_offer_charge_configuration import GETOfferChargeConfiguration
from swagger_client.models.get_offer_interval_price import GETOfferIntervalPrice
from swagger_client.models.get_offer_price_book_item import GETOfferPriceBookItem
from swagger_client.models.get_offer_product_rate_plan_charge import GETOfferProductRatePlanCharge
from swagger_client.models.get_offer_response import GETOfferResponse
from swagger_client.models.get_offer_tier import GETOfferTier
from swagger_client.models.get_open_payment_method_type_revision_response import GETOpenPaymentMethodTypeRevisionResponse
from swagger_client.models.getpm_account_holder_info import GETPMAccountHolderInfo
from swagger_client.models.get_payment_gatways_response import GETPaymentGatwaysResponse
from swagger_client.models.get_payment_item_part_collection_type import GETPaymentItemPartCollectionType
from swagger_client.models.get_payment_item_part_type import GETPaymentItemPartType
from swagger_client.models.get_payment_item_part_typewith_success import GETPaymentItemPartTypewithSuccess
from swagger_client.models.get_payment_method_response import GETPaymentMethodResponse
from swagger_client.models.get_payment_method_response_ach import GETPaymentMethodResponseACH
from swagger_client.models.get_payment_method_response_ach_for_account import GETPaymentMethodResponseACHForAccount
from swagger_client.models.get_payment_method_response_apple_pay import GETPaymentMethodResponseApplePay
from swagger_client.models.get_payment_method_response_apple_pay_for_account import GETPaymentMethodResponseApplePayForAccount
from swagger_client.models.get_payment_method_response_bank_transfer import GETPaymentMethodResponseBankTransfer
from swagger_client.models.get_payment_method_response_bank_transfer_for_account import GETPaymentMethodResponseBankTransferForAccount
from swagger_client.models.get_payment_method_response_credit_card import GETPaymentMethodResponseCreditCard
from swagger_client.models.get_payment_method_response_credit_card_for_account import GETPaymentMethodResponseCreditCardForAccount
from swagger_client.models.get_payment_method_response_for_account import GETPaymentMethodResponseForAccount
from swagger_client.models.get_payment_method_response_google_pay import GETPaymentMethodResponseGooglePay
from swagger_client.models.get_payment_method_response_google_pay_for_account import GETPaymentMethodResponseGooglePayForAccount
from swagger_client.models.get_payment_method_response_pay_pal import GETPaymentMethodResponsePayPal
from swagger_client.models.get_payment_method_response_pay_pal_for_account import GETPaymentMethodResponsePayPalForAccount
from swagger_client.models.get_payment_method_updater_instances_response import GETPaymentMethodUpdaterInstancesResponse
from swagger_client.models.get_payment_method_updater_instances_response_updaters import GETPaymentMethodUpdaterInstancesResponseUpdaters
from swagger_client.models.get_payment_part_type import GETPaymentPartType
from swagger_client.models.get_payment_part_typewith_success import GETPaymentPartTypewithSuccess
from swagger_client.models.get_payment_parts_collection_type import GETPaymentPartsCollectionType
from swagger_client.models.get_payment_run_collection_type import GETPaymentRunCollectionType
from swagger_client.models.get_payment_run_data_array_response import GETPaymentRunDataArrayResponse
from swagger_client.models.get_payment_run_data_element_response import GETPaymentRunDataElementResponse
from swagger_client.models.get_payment_run_data_transaction_element_response import GETPaymentRunDataTransactionElementResponse
from swagger_client.models.get_payment_run_summary_response import GETPaymentRunSummaryResponse
from swagger_client.models.get_payment_run_summary_total_values import GETPaymentRunSummaryTotalValues
from swagger_client.models.get_payment_run_type import GETPaymentRunType
from swagger_client.models.get_payment_schedule_item_response import GETPaymentScheduleItemResponse
from swagger_client.models.get_payment_schedule_response import GETPaymentScheduleResponse
from swagger_client.models.get_payment_schedule_statistic_response import GETPaymentScheduleStatisticResponse
from swagger_client.models.get_payment_schedule_statistic_response_payment_schedule_items import GETPaymentScheduleStatisticResponsePaymentScheduleItems
from swagger_client.models.get_payment_schedules_response import GETPaymentSchedulesResponse
from swagger_client.models.get_price_book_item_interval_price import GETPriceBookItemIntervalPrice
from swagger_client.models.get_price_book_item_response import GETPriceBookItemResponse
from swagger_client.models.get_price_book_item_tier import GETPriceBookItemTier
from swagger_client.models.get_product_discount_apply_details_type import GETProductDiscountApplyDetailsType
from swagger_client.models.get_product_rate_plan_charge_delivery_schedule import GETProductRatePlanChargeDeliverySchedule
from swagger_client.models.get_product_rate_plan_charge_pricing_tier_type import GETProductRatePlanChargePricingTierType
from swagger_client.models.get_product_rate_plan_charge_pricing_type import GETProductRatePlanChargePricingType
from swagger_client.models.get_product_rate_plan_charge_type import GETProductRatePlanChargeType
from swagger_client.models.get_product_rate_plan_type import GETProductRatePlanType
from swagger_client.models.get_product_rate_plan_with_external_id_multi_response import GETProductRatePlanWithExternalIdMultiResponse
from swagger_client.models.get_product_rate_plan_with_external_id_multi_response_inner import GETProductRatePlanWithExternalIdMultiResponseInner
from swagger_client.models.get_product_rate_plan_with_external_id_response import GETProductRatePlanWithExternalIdResponse
from swagger_client.models.get_product_rate_plans_response import GETProductRatePlansResponse
from swagger_client.models.get_product_type import GETProductType
from swagger_client.models.get_public_email_template_response import GETPublicEmailTemplateResponse
from swagger_client.models.get_public_notification_definition_response import GETPublicNotificationDefinitionResponse
from swagger_client.models.get_public_notification_definition_response_callout import GETPublicNotificationDefinitionResponseCallout
from swagger_client.models.get_public_notification_definition_response_filter_rule import GETPublicNotificationDefinitionResponseFilterRule
from swagger_client.models.get_ramp_by_ramp_number_response_type import GETRampByRampNumberResponseType
from swagger_client.models.get_ramp_metrics_by_order_number_response_type import GETRampMetricsByOrderNumberResponseType
from swagger_client.models.get_ramp_metrics_by_ramp_number_response_type import GETRampMetricsByRampNumberResponseType
from swagger_client.models.get_ramp_metrics_by_subscription_key_response_type import GETRampMetricsBySubscriptionKeyResponseType
from swagger_client.models.get_ramps_by_subscription_key_response_type import GETRampsBySubscriptionKeyResponseType
from swagger_client.models.get_refund_collection_type import GETRefundCollectionType
from swagger_client.models.get_refund_credit_memo_type import GETRefundCreditMemoType
from swagger_client.models.get_refund_item_part_collection_type import GETRefundItemPartCollectionType
from swagger_client.models.get_refund_item_part_type import GETRefundItemPartType
from swagger_client.models.get_refund_item_part_typewith_success import GETRefundItemPartTypewithSuccess
from swagger_client.models.get_refund_part_collection_type import GETRefundPartCollectionType
from swagger_client.models.get_refund_payment_type import GETRefundPaymentType
from swagger_client.models.get_refund_type import GETRefundType
from swagger_client.models.get_refund_typewith_success import GETRefundTypewithSuccess
from swagger_client.models.get_sequence_set_response import GETSequenceSetResponse
from swagger_client.models.get_sequence_sets_response import GETSequenceSetsResponse
from swagger_client.models.get_subscription_offer_type import GETSubscriptionOfferType
from swagger_client.models.get_subscription_product_feature_type import GETSubscriptionProductFeatureType
from swagger_client.models.get_subscription_rate_plan_charges_type import GETSubscriptionRatePlanChargesType
from swagger_client.models.get_subscription_rate_plan_type import GETSubscriptionRatePlanType
from swagger_client.models.get_subscription_status_history_type import GETSubscriptionStatusHistoryType
from swagger_client.models.get_subscription_type import GETSubscriptionType
from swagger_client.models.get_subscription_type_with_success import GETSubscriptionTypeWithSuccess
from swagger_client.models.get_subscription_wrapper import GETSubscriptionWrapper
from swagger_client.models.get_taxation_item_list_type import GETTaxationItemListType
from swagger_client.models.get_taxation_item_type import GETTaxationItemType
from swagger_client.models.get_taxation_item_typewith_success import GETTaxationItemTypewithSuccess
from swagger_client.models.get_taxation_items_of_credit_memo_item_type import GETTaxationItemsOfCreditMemoItemType
from swagger_client.models.get_taxation_items_of_debit_memo_item_type import GETTaxationItemsOfDebitMemoItemType
from swagger_client.models.get_tier_type import GETTierType
from swagger_client.models.get_usage_rate_detail_wrapper import GETUsageRateDetailWrapper
from swagger_client.models.get_usage_rate_detail_wrapper_data import GETUsageRateDetailWrapperData
from swagger_client.models.get_usage_type import GETUsageType
from swagger_client.models.get_usage_wrapper import GETUsageWrapper
from swagger_client.models.generate_billing_document_response_type import GenerateBillingDocumentResponseType
from swagger_client.models.get_aggregate_query_job_response import GetAggregateQueryJobResponse
from swagger_client.models.get_all_orders_response_type import GetAllOrdersResponseType
from swagger_client.models.get_api_volume_summary_response import GetApiVolumeSummaryResponse
from swagger_client.models.get_bill_run_response_type import GetBillRunResponseType
from swagger_client.models.get_billing_doc_volume_summary_response import GetBillingDocVolumeSummaryResponse
from swagger_client.models.get_billing_preview_run_response import GetBillingPreviewRunResponse
from swagger_client.models.get_data_query_job_response import GetDataQueryJobResponse
from swagger_client.models.get_data_query_jobs_response import GetDataQueryJobsResponse
from swagger_client.models.get_debit_memo_application_part_collection_type import GetDebitMemoApplicationPartCollectionType
from swagger_client.models.get_debit_memo_application_part_type import GetDebitMemoApplicationPartType
from swagger_client.models.get_fulfillment_item_response_type import GetFulfillmentItemResponseType
from swagger_client.models.get_fulfillment_response_type import GetFulfillmentResponseType
from swagger_client.models.get_hosted_page_type import GetHostedPageType
from swagger_client.models.get_hosted_pages_type import GetHostedPagesType
from swagger_client.models.get_invoice_application_part_collection_type import GetInvoiceApplicationPartCollectionType
from swagger_client.models.get_invoice_application_part_type import GetInvoiceApplicationPartType
from swagger_client.models.get_offer_rate_plan_override import GetOfferRatePlanOverride
from swagger_client.models.get_offer_rate_plan_update import GetOfferRatePlanUpdate
from swagger_client.models.get_operation_job_response_type import GetOperationJobResponseType
from swagger_client.models.get_order_action_rate_plan_response import GetOrderActionRatePlanResponse
from swagger_client.models.get_order_line_item_response_type import GetOrderLineItemResponseType
from swagger_client.models.get_order_response import GetOrderResponse
from swagger_client.models.get_order_resume import GetOrderResume
from swagger_client.models.get_order_suspend import GetOrderSuspend
from swagger_client.models.get_orders_response import GetOrdersResponse
from swagger_client.models.get_payment_volume_summary_response import GetPaymentVolumeSummaryResponse
from swagger_client.models.get_product_feature_type import GetProductFeatureType
from swagger_client.models.get_scheduled_event_response import GetScheduledEventResponse
from swagger_client.models.get_scheduled_event_response_parameters import GetScheduledEventResponseParameters
from swagger_client.models.get_stored_credential_profiles_response import GetStoredCredentialProfilesResponse
from swagger_client.models.get_stored_credential_profiles_response_profiles import GetStoredCredentialProfilesResponseProfiles
from swagger_client.models.get_versions_response import GetVersionsResponse
from swagger_client.models.get_workflow_response import GetWorkflowResponse
from swagger_client.models.get_workflow_response_tasks import GetWorkflowResponseTasks
from swagger_client.models.get_workflows_response import GetWorkflowsResponse
from swagger_client.models.get_workflows_response_pagination import GetWorkflowsResponsePagination
from swagger_client.models.initial_term import InitialTerm
from swagger_client.models.inline_response200 import InlineResponse200
from swagger_client.models.inline_response2001 import InlineResponse2001
from swagger_client.models.inline_response2002 import InlineResponse2002
from swagger_client.models.inline_response2003 import InlineResponse2003
from swagger_client.models.inline_response2004 import InlineResponse2004
from swagger_client.models.inline_response2005 import InlineResponse2005
from swagger_client.models.inline_response202 import InlineResponse202
from swagger_client.models.inline_response2021 import InlineResponse2021
from swagger_client.models.inline_response400 import InlineResponse400
from swagger_client.models.inline_response406 import InlineResponse406
from swagger_client.models.invoice_entity_prefix import InvoiceEntityPrefix
from swagger_client.models.invoice_file import InvoiceFile
from swagger_client.models.invoice_item import InvoiceItem
from swagger_client.models.invoice_item_object_custom_fields import InvoiceItemObjectCustomFields
from swagger_client.models.invoice_item_object_ns_fields import InvoiceItemObjectNSFields
from swagger_client.models.invoice_item_preview_result import InvoiceItemPreviewResult
from swagger_client.models.invoice_item_preview_result_additional_info import InvoiceItemPreviewResultAdditionalInfo
from swagger_client.models.invoice_item_preview_result_taxation_items import InvoiceItemPreviewResultTaxationItems
from swagger_client.models.invoice_object_custom_fields import InvoiceObjectCustomFields
from swagger_client.models.invoice_object_ns_fields import InvoiceObjectNSFields
from swagger_client.models.invoice_post_response_type import InvoicePostResponseType
from swagger_client.models.invoice_post_type import InvoicePostType
from swagger_client.models.invoice_response_type import InvoiceResponseType
from swagger_client.models.invoice_schedule_custom_fields import InvoiceScheduleCustomFields
from swagger_client.models.invoice_schedule_item_custom_fields import InvoiceScheduleItemCustomFields
from swagger_client.models.invoice_schedule_responses import InvoiceScheduleResponses
from swagger_client.models.invoice_schedule_specific_subscriptions import InvoiceScheduleSpecificSubscriptions
from swagger_client.models.invoice_with_custom_rates_type import InvoiceWithCustomRatesType
from swagger_client.models.invoices_batch_post_response_type import InvoicesBatchPostResponseType
from swagger_client.models.job_result import JobResult
from swagger_client.models.job_result_order_line_items import JobResultOrderLineItems
from swagger_client.models.job_result_ramps import JobResultRamps
from swagger_client.models.job_result_subscriptions import JobResultSubscriptions
from swagger_client.models.journal_entry_item_object_custom_fields import JournalEntryItemObjectCustomFields
from swagger_client.models.journal_entry_object_custom_fields import JournalEntryObjectCustomFields
from swagger_client.models.json_node import JsonNode
from swagger_client.models.last_term import LastTerm
from swagger_client.models.linkage import Linkage
from swagger_client.models.linked_payment_id import LinkedPaymentID
from swagger_client.models.list_all_catalog_groups_response import ListAllCatalogGroupsResponse
from swagger_client.models.list_all_offers_response import ListAllOffersResponse
from swagger_client.models.list_all_price_book_items_response import ListAllPriceBookItemsResponse
from swagger_client.models.list_all_settings_response import ListAllSettingsResponse
from swagger_client.models.list_of_exchange_rates import ListOfExchangeRates
from swagger_client.models.migration_client_response import MigrationClientResponse
from swagger_client.models.migration_component_content import MigrationComponentContent
from swagger_client.models.migration_update_custom_object_definitions_request import MigrationUpdateCustomObjectDefinitionsRequest
from swagger_client.models.migration_update_custom_object_definitions_response import MigrationUpdateCustomObjectDefinitionsResponse
from swagger_client.models.modified_stored_credential_profile_response import ModifiedStoredCredentialProfileResponse
from swagger_client.models.next_run_response_type import NextRunResponseType
from swagger_client.models.notifications_history_deletion_task_response import NotificationsHistoryDeletionTaskResponse
from swagger_client.models.offer_override import OfferOverride
from swagger_client.models.offer_update import OfferUpdate
from swagger_client.models.one_time_flat_fee_pricing_override import OneTimeFlatFeePricingOverride
from swagger_client.models.one_time_per_unit_pricing_override import OneTimePerUnitPricingOverride
from swagger_client.models.one_time_tiered_pricing_override import OneTimeTieredPricingOverride
from swagger_client.models.one_time_volume_pricing_override import OneTimeVolumePricingOverride
from swagger_client.models.open_payment_method_type_request_fields import OpenPaymentMethodTypeRequestFields
from swagger_client.models.open_payment_method_type_response_fields import OpenPaymentMethodTypeResponseFields
from swagger_client.models.options import Options
from swagger_client.models.order import Order
from swagger_client.models.order_action import OrderAction
from swagger_client.models.order_action_add_product import OrderActionAddProduct
from swagger_client.models.order_action_common import OrderActionCommon
from swagger_client.models.order_action_custom_fields import OrderActionCustomFields
from swagger_client.models.order_action_object_custom_fields import OrderActionObjectCustomFields
from swagger_client.models.order_action_put import OrderActionPut
from swagger_client.models.order_action_rate_plan_amendment import OrderActionRatePlanAmendment
from swagger_client.models.order_action_rate_plan_billing_update import OrderActionRatePlanBillingUpdate
from swagger_client.models.order_action_rate_plan_charge_model_data_override import OrderActionRatePlanChargeModelDataOverride
from swagger_client.models.order_action_rate_plan_charge_model_data_override_charge_model_configuration import OrderActionRatePlanChargeModelDataOverrideChargeModelConfiguration
from swagger_client.models.order_action_rate_plan_charge_override import OrderActionRatePlanChargeOverride
from swagger_client.models.order_action_rate_plan_charge_override_pricing import OrderActionRatePlanChargeOverridePricing
from swagger_client.models.order_action_rate_plan_charge_tier import OrderActionRatePlanChargeTier
from swagger_client.models.order_action_rate_plan_charge_update import OrderActionRatePlanChargeUpdate
from swagger_client.models.order_action_rate_plan_charge_update_billing import OrderActionRatePlanChargeUpdateBilling
from swagger_client.models.order_action_rate_plan_discount_pricing_override import OrderActionRatePlanDiscountPricingOverride
from swagger_client.models.order_action_rate_plan_discount_pricing_update import OrderActionRatePlanDiscountPricingUpdate
from swagger_client.models.order_action_rate_plan_end_conditions import OrderActionRatePlanEndConditions
from swagger_client.models.order_action_rate_plan_one_time_flat_fee_pricing_override import OrderActionRatePlanOneTimeFlatFeePricingOverride
from swagger_client.models.order_action_rate_plan_one_time_per_unit_pricing_override import OrderActionRatePlanOneTimePerUnitPricingOverride
from swagger_client.models.order_action_rate_plan_one_time_tiered_pricing_override import OrderActionRatePlanOneTimeTieredPricingOverride
from swagger_client.models.order_action_rate_plan_one_time_volume_pricing_override import OrderActionRatePlanOneTimeVolumePricingOverride
from swagger_client.models.order_action_rate_plan_order import OrderActionRatePlanOrder
from swagger_client.models.order_action_rate_plan_order_action import OrderActionRatePlanOrderAction
from swagger_client.models.order_action_rate_plan_order_action_object_custom_fields import OrderActionRatePlanOrderActionObjectCustomFields
from swagger_client.models.order_action_rate_plan_price_change_params import OrderActionRatePlanPriceChangeParams
from swagger_client.models.order_action_rate_plan_pricing_update import OrderActionRatePlanPricingUpdate
from swagger_client.models.order_action_rate_plan_pricing_update_charge_model_data import OrderActionRatePlanPricingUpdateChargeModelData
from swagger_client.models.order_action_rate_plan_pricing_update_recurring_delivery import OrderActionRatePlanPricingUpdateRecurringDelivery
from swagger_client.models.order_action_rate_plan_rate_plan_charge_object_custom_fields import OrderActionRatePlanRatePlanChargeObjectCustomFields
from swagger_client.models.order_action_rate_plan_rate_plan_object_custom_fields import OrderActionRatePlanRatePlanObjectCustomFields
from swagger_client.models.order_action_rate_plan_rate_plan_override import OrderActionRatePlanRatePlanOverride
from swagger_client.models.order_action_rate_plan_rate_plan_update import OrderActionRatePlanRatePlanUpdate
from swagger_client.models.order_action_rate_plan_recurring_delivery_pricing_override import OrderActionRatePlanRecurringDeliveryPricingOverride
from swagger_client.models.order_action_rate_plan_recurring_delivery_pricing_update import OrderActionRatePlanRecurringDeliveryPricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_flat_fee_pricing_override import OrderActionRatePlanRecurringFlatFeePricingOverride
from swagger_client.models.order_action_rate_plan_recurring_flat_fee_pricing_update import OrderActionRatePlanRecurringFlatFeePricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_per_unit_pricing_override import OrderActionRatePlanRecurringPerUnitPricingOverride
from swagger_client.models.order_action_rate_plan_recurring_per_unit_pricing_update import OrderActionRatePlanRecurringPerUnitPricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_tiered_pricing_override import OrderActionRatePlanRecurringTieredPricingOverride
from swagger_client.models.order_action_rate_plan_recurring_tiered_pricing_update import OrderActionRatePlanRecurringTieredPricingUpdate
from swagger_client.models.order_action_rate_plan_recurring_volume_pricing_override import OrderActionRatePlanRecurringVolumePricingOverride
from swagger_client.models.order_action_rate_plan_recurring_volume_pricing_update import OrderActionRatePlanRecurringVolumePricingUpdate
from swagger_client.models.order_action_rate_plan_remove_product import OrderActionRatePlanRemoveProduct
from swagger_client.models.order_action_rate_plan_trigger_params import OrderActionRatePlanTriggerParams
from swagger_client.models.order_action_rate_plan_usage_flat_fee_pricing_override import OrderActionRatePlanUsageFlatFeePricingOverride
from swagger_client.models.order_action_rate_plan_usage_flat_fee_pricing_update import OrderActionRatePlanUsageFlatFeePricingUpdate
from swagger_client.models.order_action_rate_plan_usage_overage_pricing_override import OrderActionRatePlanUsageOveragePricingOverride
from swagger_client.models.order_action_rate_plan_usage_overage_pricing_update import OrderActionRatePlanUsageOveragePricingUpdate
from swagger_client.models.order_action_rate_plan_usage_per_unit_pricing_override import OrderActionRatePlanUsagePerUnitPricingOverride
from swagger_client.models.order_action_rate_plan_usage_per_unit_pricing_update import OrderActionRatePlanUsagePerUnitPricingUpdate
from swagger_client.models.order_action_rate_plan_usage_tiered_pricing_override import OrderActionRatePlanUsageTieredPricingOverride
from swagger_client.models.order_action_rate_plan_usage_tiered_pricing_update import OrderActionRatePlanUsageTieredPricingUpdate
from swagger_client.models.order_action_rate_plan_usage_tiered_with_overage_pricing_override import OrderActionRatePlanUsageTieredWithOveragePricingOverride
from swagger_client.models.order_action_rate_plan_usage_tiered_with_overage_pricing_update import OrderActionRatePlanUsageTieredWithOveragePricingUpdate
from swagger_client.models.order_action_rate_plan_usage_volume_pricing_override import OrderActionRatePlanUsageVolumePricingOverride
from swagger_client.models.order_action_rate_plan_usage_volume_pricing_update import OrderActionRatePlanUsageVolumePricingUpdate
from swagger_client.models.order_action_update_product import OrderActionUpdateProduct
from swagger_client.models.order_delta_metric import OrderDeltaMetric
from swagger_client.models.order_delta_mrr import OrderDeltaMrr
from swagger_client.models.order_delta_tcb import OrderDeltaTcb
from swagger_client.models.order_delta_tcv import OrderDeltaTcv
from swagger_client.models.order_item import OrderItem
from swagger_client.models.order_line_item import OrderLineItem
from swagger_client.models.order_line_item_common import OrderLineItemCommon
from swagger_client.models.order_line_item_common_post_order import OrderLineItemCommonPostOrder
from swagger_client.models.order_line_item_common_retrieve_order import OrderLineItemCommonRetrieveOrder
from swagger_client.models.order_line_item_common_retrieve_order_line_item import OrderLineItemCommonRetrieveOrderLineItem
from swagger_client.models.order_line_item_custom_fields import OrderLineItemCustomFields
from swagger_client.models.order_line_item_custom_fields_retrieve_order_line_item import OrderLineItemCustomFieldsRetrieveOrderLineItem
from swagger_client.models.order_line_item_retrieve_order import OrderLineItemRetrieveOrder
from swagger_client.models.order_metric import OrderMetric
from swagger_client.models.order_object_custom_fields import OrderObjectCustomFields
from swagger_client.models.order_ramp_interval_metrics import OrderRampIntervalMetrics
from swagger_client.models.order_ramp_metrics import OrderRampMetrics
from swagger_client.models.order_scheduling_options import OrderSchedulingOptions
from swagger_client.models.order_subscriptions import OrderSubscriptions
from swagger_client.models.orders_rate_plan_object_custom_fields import OrdersRatePlanObjectCustomFields
from swagger_client.models.owner_transfer import OwnerTransfer
from swagger_client.models.post_account_pm_mandate_info import POSTAccountPMMandateInfo
from swagger_client.models.post_account_response_type import POSTAccountResponseType
from swagger_client.models.post_account_type import POSTAccountType
from swagger_client.models.post_account_type_bill_to_contact import POSTAccountTypeBillToContact
from swagger_client.models.post_account_type_credit_card import POSTAccountTypeCreditCard
from swagger_client.models.post_account_type_payment_method import POSTAccountTypePaymentMethod
from swagger_client.models.post_account_type_sold_to_contact import POSTAccountTypeSoldToContact
from swagger_client.models.post_account_type_subscription import POSTAccountTypeSubscription
from swagger_client.models.post_accounting_code_response_type import POSTAccountingCodeResponseType
from swagger_client.models.post_accounting_code_type import POSTAccountingCodeType
from swagger_client.models.post_accounting_period_response_type import POSTAccountingPeriodResponseType
from swagger_client.models.post_accounting_period_type import POSTAccountingPeriodType
from swagger_client.models.post_add_items_to_payment_schedule_request import POSTAddItemsToPaymentScheduleRequest
from swagger_client.models.post_adjustment_response_type import POSTAdjustmentResponseType
from swagger_client.models.post_attachment_response_type import POSTAttachmentResponseType
from swagger_client.models.post_authorize_response import POSTAuthorizeResponse
from swagger_client.models.post_authorize_response_payment_gateway_response import POSTAuthorizeResponsePaymentGatewayResponse
from swagger_client.models.post_authorize_response_reasons import POSTAuthorizeResponseReasons
from swagger_client.models.post_billing_document_files_deletion_job_request import POSTBillingDocumentFilesDeletionJobRequest
from swagger_client.models.post_billing_document_files_deletion_job_response import POSTBillingDocumentFilesDeletionJobResponse
from swagger_client.models.post_billing_preview_credit_memo_item import POSTBillingPreviewCreditMemoItem
from swagger_client.models.post_billing_preview_invoice_item import POSTBillingPreviewInvoiceItem
from swagger_client.models.post_bulk_credit_memo_from_invoice_type import POSTBulkCreditMemoFromInvoiceType
from swagger_client.models.post_bulk_credit_memos_request_type import POSTBulkCreditMemosRequestType
from swagger_client.models.post_bulk_debit_memo_from_invoice_type import POSTBulkDebitMemoFromInvoiceType
from swagger_client.models.post_bulk_debit_memos_request_type import POSTBulkDebitMemosRequestType
from swagger_client.models.post_catalog_group_request import POSTCatalogGroupRequest
from swagger_client.models.post_contact_type import POSTContactType
from swagger_client.models.post_create_bill_run_request_type import POSTCreateBillRunRequestType
from swagger_client.models.post_create_billing_adjustment_request_type import POSTCreateBillingAdjustmentRequestType
from swagger_client.models.post_create_billing_adjustment_request_type_exclusion import POSTCreateBillingAdjustmentRequestTypeExclusion
from swagger_client.models.post_create_invoice_schedule_request import POSTCreateInvoiceScheduleRequest
from swagger_client.models.post_create_open_payment_method_type_request import POSTCreateOpenPaymentMethodTypeRequest
from swagger_client.models.post_create_open_payment_method_type_response import POSTCreateOpenPaymentMethodTypeResponse
from swagger_client.models.post_create_or_update_email_template_request import POSTCreateOrUpdateEmailTemplateRequest
from swagger_client.models.post_create_or_update_email_template_request_format import POSTCreateOrUpdateEmailTemplateRequestFormat
from swagger_client.models.post_create_payment_session_request import POSTCreatePaymentSessionRequest
from swagger_client.models.post_create_payment_session_response import POSTCreatePaymentSessionResponse
from swagger_client.models.post_decrypt_response_type import POSTDecryptResponseType
from swagger_client.models.post_decryption_type import POSTDecryptionType
from swagger_client.models.post_delay_authorize_capture import POSTDelayAuthorizeCapture
from swagger_client.models.post_delay_authorize_capture_gateway_options import POSTDelayAuthorizeCaptureGatewayOptions
from swagger_client.models.post_email_billing_docfrom_bill_run_type import POSTEmailBillingDocfromBillRunType
from swagger_client.models.post_execute_invoice_schedule_request import POSTExecuteInvoiceScheduleRequest
from swagger_client.models.post_ineligible_adjustment_response_type import POSTIneligibleAdjustmentResponseType
from swagger_client.models.post_invoice_collect_credit_memos_type import POSTInvoiceCollectCreditMemosType
from swagger_client.models.post_invoice_collect_invoices_type import POSTInvoiceCollectInvoicesType
from swagger_client.models.post_invoice_collect_response_type import POSTInvoiceCollectResponseType
from swagger_client.models.post_invoice_collect_type import POSTInvoiceCollectType
from swagger_client.models.post_invoices_batch_post_type import POSTInvoicesBatchPostType
from swagger_client.models.post_journal_entry_item_type import POSTJournalEntryItemType
from swagger_client.models.post_journal_entry_response_type import POSTJournalEntryResponseType
from swagger_client.models.post_journal_entry_segment_type import POSTJournalEntrySegmentType
from swagger_client.models.post_journal_entry_type import POSTJournalEntryType
from swagger_client.models.post_journal_run_response_type import POSTJournalRunResponseType
from swagger_client.models.post_journal_run_transaction_type import POSTJournalRunTransactionType
from swagger_client.models.post_journal_run_type import POSTJournalRunType
from swagger_client.models.post_mass_update_response_type import POSTMassUpdateResponseType
from swagger_client.models.post_memo_pdf_response import POSTMemoPdfResponse
from swagger_client.models.post_offer_charge_configuration import POSTOfferChargeConfiguration
from swagger_client.models.post_offer_charge_override import POSTOfferChargeOverride
from swagger_client.models.post_offer_interval_price import POSTOfferIntervalPrice
from swagger_client.models.post_offer_price_book_item import POSTOfferPriceBookItem
from swagger_client.models.post_offer_product_rate_plan import POSTOfferProductRatePlan
from swagger_client.models.post_offer_request import POSTOfferRequest
from swagger_client.models.post_offer_response import POSTOfferResponse
from swagger_client.models.post_offer_tier import POSTOfferTier
from swagger_client.models.post_order_async_request_type import POSTOrderAsyncRequestType
from swagger_client.models.post_order_async_request_type_subscriptions import POSTOrderAsyncRequestTypeSubscriptions
from swagger_client.models.post_order_preview_async_request_type import POSTOrderPreviewAsyncRequestType
from swagger_client.models.post_order_preview_async_request_type_subscriptions import POSTOrderPreviewAsyncRequestTypeSubscriptions
from swagger_client.models.post_order_preview_request_type import POSTOrderPreviewRequestType
from swagger_client.models.post_order_request_type import POSTOrderRequestType
from swagger_client.models.post_order_request_type_scheduling_options import POSTOrderRequestTypeSchedulingOptions
from swagger_client.models.postpm_mandate_info import POSTPMMandateInfo
from swagger_client.models.post_payment_method_decryption import POSTPaymentMethodDecryption
from swagger_client.models.post_payment_method_request import POSTPaymentMethodRequest
from swagger_client.models.post_payment_method_response import POSTPaymentMethodResponse
from swagger_client.models.post_payment_method_response_decryption import POSTPaymentMethodResponseDecryption
from swagger_client.models.post_payment_method_response_reasons import POSTPaymentMethodResponseReasons
from swagger_client.models.post_payment_method_updater_batch_request import POSTPaymentMethodUpdaterBatchRequest
from swagger_client.models.post_payment_method_updater_response import POSTPaymentMethodUpdaterResponse
from swagger_client.models.post_payment_method_updater_response_reasons import POSTPaymentMethodUpdaterResponseReasons
from swagger_client.models.post_payment_run_data_element_request import POSTPaymentRunDataElementRequest
from swagger_client.models.post_payment_run_request import POSTPaymentRunRequest
from swagger_client.models.post_payment_schedule_request import POSTPaymentScheduleRequest
from swagger_client.models.post_payment_schedule_response import POSTPaymentScheduleResponse
from swagger_client.models.post_payment_schedules_each import POSTPaymentSchedulesEach
from swagger_client.models.post_payment_schedules_request import POSTPaymentSchedulesRequest
from swagger_client.models.post_payment_schedules_response import POSTPaymentSchedulesResponse
from swagger_client.models.post_preview_billing_adjustment_request_type import POSTPreviewBillingAdjustmentRequestType
from swagger_client.models.post_price_book_item_interval_price import POSTPriceBookItemIntervalPrice
from swagger_client.models.post_price_book_item_request import POSTPriceBookItemRequest
from swagger_client.models.post_price_book_item_tier import POSTPriceBookItemTier
from swagger_client.models.post_public_email_template_request import POSTPublicEmailTemplateRequest
from swagger_client.models.post_public_notification_definition_request import POSTPublicNotificationDefinitionRequest
from swagger_client.models.post_public_notification_definition_request_callout import POSTPublicNotificationDefinitionRequestCallout
from swagger_client.models.post_public_notification_definition_request_filter_rule import POSTPublicNotificationDefinitionRequestFilterRule
from swagger_client.models.postrsa_signature_response_type import POSTRSASignatureResponseType
from swagger_client.models.postrsa_signature_type import POSTRSASignatureType
from swagger_client.models.post_reconcile_refund_request import POSTReconcileRefundRequest
from swagger_client.models.post_reconcile_refund_response import POSTReconcileRefundResponse
from swagger_client.models.post_reconcile_refund_response_finance_information import POSTReconcileRefundResponseFinanceInformation
from swagger_client.models.post_reject_payment_request import POSTRejectPaymentRequest
from swagger_client.models.post_reject_payment_response import POSTRejectPaymentResponse
from swagger_client.models.post_resend_callout_notifications import POSTResendCalloutNotifications
from swagger_client.models.post_resend_email_notifications import POSTResendEmailNotifications
from swagger_client.models.post_retry_payment_schedule_item_info import POSTRetryPaymentScheduleItemInfo
from swagger_client.models.post_retry_payment_schedule_item_request import POSTRetryPaymentScheduleItemRequest
from swagger_client.models.post_retry_payment_schedule_item_response import POSTRetryPaymentScheduleItemResponse
from swagger_client.models.post_reverse_payment_request import POSTReversePaymentRequest
from swagger_client.models.post_reverse_payment_response import POSTReversePaymentResponse
from swagger_client.models.postsc_create_type import POSTScCreateType
from swagger_client.models.post_schedule_item_type import POSTScheduleItemType
from swagger_client.models.post_sequence_set_request import POSTSequenceSetRequest
from swagger_client.models.post_sequence_sets_request import POSTSequenceSetsRequest
from swagger_client.models.post_sequence_sets_response import POSTSequenceSetsResponse
from swagger_client.models.post_settle_payment_request import POSTSettlePaymentRequest
from swagger_client.models.post_settle_payment_response import POSTSettlePaymentResponse
from swagger_client.models.post_srp_create_type import POSTSrpCreateType
from swagger_client.models.post_subscription_cancellation_response_type import POSTSubscriptionCancellationResponseType
from swagger_client.models.post_subscription_cancellation_type import POSTSubscriptionCancellationType
from swagger_client.models.post_subscription_preview_credit_memo_items_type import POSTSubscriptionPreviewCreditMemoItemsType
from swagger_client.models.post_subscription_preview_invoice_items_type import POSTSubscriptionPreviewInvoiceItemsType
from swagger_client.models.post_subscription_preview_response_type import POSTSubscriptionPreviewResponseType
from swagger_client.models.post_subscription_preview_response_type_charge_metrics import POSTSubscriptionPreviewResponseTypeChargeMetrics
from swagger_client.models.post_subscription_preview_response_type_credit_memo import POSTSubscriptionPreviewResponseTypeCreditMemo
from swagger_client.models.post_subscription_preview_response_type_invoice import POSTSubscriptionPreviewResponseTypeInvoice
from swagger_client.models.post_subscription_preview_taxation_items_type import POSTSubscriptionPreviewTaxationItemsType
from swagger_client.models.post_subscription_preview_type import POSTSubscriptionPreviewType
from swagger_client.models.post_subscription_preview_type_preview_account_info import POSTSubscriptionPreviewTypePreviewAccountInfo
from swagger_client.models.post_subscription_response_type import POSTSubscriptionResponseType
from swagger_client.models.post_subscription_type import POSTSubscriptionType
from swagger_client.models.post_taxation_item_for_cm_type import POSTTaxationItemForCMType
from swagger_client.models.post_taxation_item_for_dm_type import POSTTaxationItemForDMType
from swagger_client.models.post_taxation_item_list import POSTTaxationItemList
from swagger_client.models.post_taxation_item_list_for_cm_type import POSTTaxationItemListForCMType
from swagger_client.models.post_taxation_item_list_for_dm_type import POSTTaxationItemListForDMType
from swagger_client.models.post_taxation_item_type_for_invoice import POSTTaxationItemTypeForInvoice
from swagger_client.models.post_tier_type import POSTTierType
from swagger_client.models.post_upload_file_response import POSTUploadFileResponse
from swagger_client.models.post_usage_response_type import POSTUsageResponseType
from swagger_client.models.post_void_authorize import POSTVoidAuthorize
from swagger_client.models.post_void_authorize_response import POSTVoidAuthorizeResponse
from swagger_client.models.post_workflow_definition_import_request import POSTWorkflowDefinitionImportRequest
from swagger_client.models.pos_tor_put_catalog_group_add_product_rate_plan import POSTorPUTCatalogGroupAddProductRatePlan
from swagger_client.models.put_account_type import PUTAccountType
from swagger_client.models.put_account_type_bill_to_contact import PUTAccountTypeBillToContact
from swagger_client.models.put_account_type_sold_to_contact import PUTAccountTypeSoldToContact
from swagger_client.models.put_accounting_code_type import PUTAccountingCodeType
from swagger_client.models.put_accounting_period_type import PUTAccountingPeriodType
from swagger_client.models.put_attachment_type import PUTAttachmentType
from swagger_client.models.put_basic_summary_journal_entry_type import PUTBasicSummaryJournalEntryType
from swagger_client.models.put_batch_debit_memos_request import PUTBatchDebitMemosRequest
from swagger_client.models.put_bulk_credit_memos_request_type import PUTBulkCreditMemosRequestType
from swagger_client.models.put_bulk_debit_memos_request_type import PUTBulkDebitMemosRequestType
from swagger_client.models.put_cancel_payment_schedule_request import PUTCancelPaymentScheduleRequest
from swagger_client.models.put_catalog_group import PUTCatalogGroup
from swagger_client.models.put_catalog_group_remove_product_rate_plan import PUTCatalogGroupRemoveProductRatePlan
from swagger_client.models.put_contact_type import PUTContactType
from swagger_client.models.put_credit_memo_item_type import PUTCreditMemoItemType
from swagger_client.models.put_credit_memo_type import PUTCreditMemoType
from swagger_client.models.put_credit_memo_write_off import PUTCreditMemoWriteOff
from swagger_client.models.put_credit_memo_write_off_response_type import PUTCreditMemoWriteOffResponseType
from swagger_client.models.put_credit_memo_write_off_response_type_debit_memo import PUTCreditMemoWriteOffResponseTypeDebitMemo
from swagger_client.models.put_credit_memos_with_id_type import PUTCreditMemosWithIdType
from swagger_client.models.put_debit_memo_item_type import PUTDebitMemoItemType
from swagger_client.models.put_debit_memo_type import PUTDebitMemoType
from swagger_client.models.put_debit_memo_with_id_type import PUTDebitMemoWithIdType
from swagger_client.models.put_delete_subscription_response_type import PUTDeleteSubscriptionResponseType
from swagger_client.models.put_journal_entry_item_type import PUTJournalEntryItemType
from swagger_client.models.put_order_action_trigger_dates_request_type import PUTOrderActionTriggerDatesRequestType
from swagger_client.models.put_order_action_trigger_dates_request_type_charges import PUTOrderActionTriggerDatesRequestTypeCharges
from swagger_client.models.put_order_action_trigger_dates_request_type_order_actions import PUTOrderActionTriggerDatesRequestTypeOrderActions
from swagger_client.models.put_order_action_trigger_dates_request_type_subscriptions import PUTOrderActionTriggerDatesRequestTypeSubscriptions
from swagger_client.models.put_order_action_trigger_dates_request_type_trigger_dates import PUTOrderActionTriggerDatesRequestTypeTriggerDates
from swagger_client.models.put_order_actions_request_type import PUTOrderActionsRequestType
from swagger_client.models.put_order_line_item_request_type import PUTOrderLineItemRequestType
from swagger_client.models.put_order_patch_request_type import PUTOrderPatchRequestType
from swagger_client.models.put_order_patch_request_type_order_actions import PUTOrderPatchRequestTypeOrderActions
from swagger_client.models.put_order_patch_request_type_subscriptions import PUTOrderPatchRequestTypeSubscriptions
from swagger_client.models.put_order_request_type import PUTOrderRequestType
from swagger_client.models.put_order_trigger_dates_response_type import PUTOrderTriggerDatesResponseType
from swagger_client.models.put_order_trigger_dates_response_type_subscriptions import PUTOrderTriggerDatesResponseTypeSubscriptions
from swagger_client.models.putpm_account_holder_info import PUTPMAccountHolderInfo
from swagger_client.models.putpm_credit_card_info import PUTPMCreditCardInfo
from swagger_client.models.put_payment_method_object_custom_fields import PUTPaymentMethodObjectCustomFields
from swagger_client.models.put_payment_method_request import PUTPaymentMethodRequest
from swagger_client.models.put_payment_method_response import PUTPaymentMethodResponse
from swagger_client.models.put_payment_run_request import PUTPaymentRunRequest
from swagger_client.models.put_payment_schedule_item_request import PUTPaymentScheduleItemRequest
from swagger_client.models.put_payment_schedule_item_response import PUTPaymentScheduleItemResponse
from swagger_client.models.put_payment_schedule_request import PUTPaymentScheduleRequest
from swagger_client.models.put_preview_payment_schedule_request import PUTPreviewPaymentScheduleRequest
from swagger_client.models.put_price_book_item_request import PUTPriceBookItemRequest
from swagger_client.models.put_public_email_template_request import PUTPublicEmailTemplateRequest
from swagger_client.models.put_public_notification_definition_request import PUTPublicNotificationDefinitionRequest
from swagger_client.models.put_public_notification_definition_request_callout import PUTPublicNotificationDefinitionRequestCallout
from swagger_client.models.put_public_notification_definition_request_filter_rule import PUTPublicNotificationDefinitionRequestFilterRule
from swagger_client.models.put_publish_open_payment_method_type_response import PUTPublishOpenPaymentMethodTypeResponse
from swagger_client.models.put_refund_type import PUTRefundType
from swagger_client.models.put_renew_subscription_response_type import PUTRenewSubscriptionResponseType
from swagger_client.models.put_renew_subscription_type import PUTRenewSubscriptionType
from swagger_client.models.put_revpro_acc_code_response import PUTRevproAccCodeResponse
from swagger_client.models.putsc_add_type import PUTScAddType
from swagger_client.models.putsc_update_type import PUTScUpdateType
from swagger_client.models.put_sequence_set_request import PUTSequenceSetRequest
from swagger_client.models.put_sequence_set_response import PUTSequenceSetResponse
from swagger_client.models.put_skip_payment_schedule_item_response import PUTSkipPaymentScheduleItemResponse
from swagger_client.models.put_srp_add_type import PUTSrpAddType
from swagger_client.models.put_srp_change_type import PUTSrpChangeType
from swagger_client.models.put_srp_remove_type import PUTSrpRemoveType
from swagger_client.models.put_srp_update_type import PUTSrpUpdateType
from swagger_client.models.put_subscription_patch_request_type import PUTSubscriptionPatchRequestType
from swagger_client.models.put_subscription_patch_request_type_charges import PUTSubscriptionPatchRequestTypeCharges
from swagger_client.models.put_subscription_patch_request_type_rate_plans import PUTSubscriptionPatchRequestTypeRatePlans
from swagger_client.models.put_subscription_patch_specific_version_request_type import PUTSubscriptionPatchSpecificVersionRequestType
from swagger_client.models.put_subscription_patch_specific_version_request_type_charges import PUTSubscriptionPatchSpecificVersionRequestTypeCharges
from swagger_client.models.put_subscription_patch_specific_version_request_type_rate_plans import PUTSubscriptionPatchSpecificVersionRequestTypeRatePlans
from swagger_client.models.put_subscription_preview_invoice_items_type import PUTSubscriptionPreviewInvoiceItemsType
from swagger_client.models.put_subscription_response_type import PUTSubscriptionResponseType
from swagger_client.models.put_subscription_response_type_charge_metrics import PUTSubscriptionResponseTypeChargeMetrics
from swagger_client.models.put_subscription_response_type_credit_memo import PUTSubscriptionResponseTypeCreditMemo
from swagger_client.models.put_subscription_response_type_invoice import PUTSubscriptionResponseTypeInvoice
from swagger_client.models.put_subscription_resume_response_type import PUTSubscriptionResumeResponseType
from swagger_client.models.put_subscription_resume_type import PUTSubscriptionResumeType
from swagger_client.models.put_subscription_suspend_response_type import PUTSubscriptionSuspendResponseType
from swagger_client.models.put_subscription_suspend_type import PUTSubscriptionSuspendType
from swagger_client.models.put_subscription_type import PUTSubscriptionType
from swagger_client.models.put_taxation_item_type import PUTTaxationItemType
from swagger_client.models.put_update_invoice_schedule_request import PUTUpdateInvoiceScheduleRequest
from swagger_client.models.put_update_open_payment_method_type_request import PUTUpdateOpenPaymentMethodTypeRequest
from swagger_client.models.put_update_open_payment_method_type_response import PUTUpdateOpenPaymentMethodTypeResponse
from swagger_client.models.put_verify_payment_method_response_type import PUTVerifyPaymentMethodResponseType
from swagger_client.models.put_verify_payment_method_type import PUTVerifyPaymentMethodType
from swagger_client.models.put_write_off_invoice_request import PUTWriteOffInvoiceRequest
from swagger_client.models.put_write_off_invoice_response import PUTWriteOffInvoiceResponse
from swagger_client.models.put_write_off_invoice_response_credit_memo import PUTWriteOffInvoiceResponseCreditMemo
from swagger_client.models.payment_collection_response_type import PaymentCollectionResponseType
from swagger_client.models.payment_data import PaymentData
from swagger_client.models.payment_debit_memo_application_apply_request_type import PaymentDebitMemoApplicationApplyRequestType
from swagger_client.models.payment_debit_memo_application_create_request_type import PaymentDebitMemoApplicationCreateRequestType
from swagger_client.models.payment_debit_memo_application_item_apply_request_type import PaymentDebitMemoApplicationItemApplyRequestType
from swagger_client.models.payment_debit_memo_application_item_create_request_type import PaymentDebitMemoApplicationItemCreateRequestType
from swagger_client.models.payment_debit_memo_application_item_unapply_request_type import PaymentDebitMemoApplicationItemUnapplyRequestType
from swagger_client.models.payment_debit_memo_application_unapply_request_type import PaymentDebitMemoApplicationUnapplyRequestType
from swagger_client.models.payment_entity_prefix import PaymentEntityPrefix
from swagger_client.models.payment_invoice_application_apply_request_type import PaymentInvoiceApplicationApplyRequestType
from swagger_client.models.payment_invoice_application_create_request_type import PaymentInvoiceApplicationCreateRequestType
from swagger_client.models.payment_invoice_application_item_apply_request_type import PaymentInvoiceApplicationItemApplyRequestType
from swagger_client.models.payment_invoice_application_item_create_request_type import PaymentInvoiceApplicationItemCreateRequestType
from swagger_client.models.payment_invoice_application_item_unapply_request_type import PaymentInvoiceApplicationItemUnapplyRequestType
from swagger_client.models.payment_invoice_application_unapply_request_type import PaymentInvoiceApplicationUnapplyRequestType
from swagger_client.models.payment_method_object_custom_fields import PaymentMethodObjectCustomFields
from swagger_client.models.payment_method_object_custom_fields_for_account import PaymentMethodObjectCustomFieldsForAccount
from swagger_client.models.payment_object_custom_fields import PaymentObjectCustomFields
from swagger_client.models.payment_object_ns_fields import PaymentObjectNSFields
from swagger_client.models.payment_run_statistic import PaymentRunStatistic
from swagger_client.models.payment_schedule_common_response import PaymentScheduleCommonResponse
from swagger_client.models.payment_schedule_custom_fields import PaymentScheduleCustomFields
from swagger_client.models.payment_schedule_item_common import PaymentScheduleItemCommon
from swagger_client.models.payment_schedule_item_common_response import PaymentScheduleItemCommonResponse
from swagger_client.models.payment_schedule_item_custom_fields import PaymentScheduleItemCustomFields
from swagger_client.models.payment_schedule_payment_option_fields import PaymentSchedulePaymentOptionFields
from swagger_client.models.payment_schedule_payment_option_fields_detail import PaymentSchedulePaymentOptionFieldsDetail
from swagger_client.models.payment_volume_summary_record import PaymentVolumeSummaryRecord
from swagger_client.models.payment_with_custom_rates_type import PaymentWithCustomRatesType
from swagger_client.models.post_batch_invoice_item_response import PostBatchInvoiceItemResponse
from swagger_client.models.post_batch_invoice_response import PostBatchInvoiceResponse
from swagger_client.models.post_batch_invoices_type import PostBatchInvoicesType
from swagger_client.models.post_billing_preview_param import PostBillingPreviewParam
from swagger_client.models.post_billing_preview_run_param import PostBillingPreviewRunParam
from swagger_client.models.post_credit_memo_email_request_type import PostCreditMemoEmailRequestType
from swagger_client.models.post_custom_object_definition_field_definition_request import PostCustomObjectDefinitionFieldDefinitionRequest
from swagger_client.models.post_custom_object_definition_fields_definition_request import PostCustomObjectDefinitionFieldsDefinitionRequest
from swagger_client.models.post_custom_object_definitions_request import PostCustomObjectDefinitionsRequest
from swagger_client.models.post_custom_object_definitions_request_definition import PostCustomObjectDefinitionsRequestDefinition
from swagger_client.models.post_custom_object_definitions_request_definitions import PostCustomObjectDefinitionsRequestDefinitions
from swagger_client.models.post_custom_object_records_request import PostCustomObjectRecordsRequest
from swagger_client.models.post_custom_object_records_response import PostCustomObjectRecordsResponse
from swagger_client.models.post_debit_memo_email_type import PostDebitMemoEmailType
from swagger_client.models.post_discount_item_type import PostDiscountItemType
from swagger_client.models.post_event_trigger_request import PostEventTriggerRequest
from swagger_client.models.post_fulfillment_items_request_type import PostFulfillmentItemsRequestType
from swagger_client.models.post_fulfillment_items_response_type import PostFulfillmentItemsResponseType
from swagger_client.models.post_fulfillment_items_response_type_fulfillment_items import PostFulfillmentItemsResponseTypeFulfillmentItems
from swagger_client.models.post_fulfillments_request_type import PostFulfillmentsRequestType
from swagger_client.models.post_fulfillments_response_type import PostFulfillmentsResponseType
from swagger_client.models.post_fulfillments_response_type_fulfillments import PostFulfillmentsResponseTypeFulfillments
from swagger_client.models.post_generate_billing_document_type import PostGenerateBillingDocumentType
from swagger_client.models.post_invoice_email_request_type import PostInvoiceEmailRequestType
from swagger_client.models.post_invoice_item_type import PostInvoiceItemType
from swagger_client.models.post_invoice_response import PostInvoiceResponse
from swagger_client.models.post_invoice_type import PostInvoiceType
from swagger_client.models.post_non_ref_refund_type import PostNonRefRefundType
from swagger_client.models.post_order_account_payment_method import PostOrderAccountPaymentMethod
from swagger_client.models.post_order_line_item_update_type import PostOrderLineItemUpdateType
from swagger_client.models.post_order_line_items_request_type import PostOrderLineItemsRequestType
from swagger_client.models.post_order_preview_response_type import PostOrderPreviewResponseType
from swagger_client.models.post_order_response_type import PostOrderResponseType
from swagger_client.models.post_order_response_type_refunds import PostOrderResponseTypeRefunds
from swagger_client.models.post_order_response_type_subscriptions import PostOrderResponseTypeSubscriptions
from swagger_client.models.post_order_response_type_write_off import PostOrderResponseTypeWriteOff
from swagger_client.models.post_refund_type import PostRefundType
from swagger_client.models.post_refundwith_auto_unapply_type import PostRefundwithAutoUnapplyType
from swagger_client.models.post_scheduled_event_request import PostScheduledEventRequest
from swagger_client.models.post_scheduled_event_request_parameters import PostScheduledEventRequestParameters
from swagger_client.models.post_taxation_item_type import PostTaxationItemType
from swagger_client.models.preview_account_info import PreviewAccountInfo
from swagger_client.models.preview_contact_info import PreviewContactInfo
from swagger_client.models.preview_options import PreviewOptions
from swagger_client.models.preview_order_charge_override import PreviewOrderChargeOverride
from swagger_client.models.preview_order_charge_update import PreviewOrderChargeUpdate
from swagger_client.models.preview_order_create_subscription import PreviewOrderCreateSubscription
from swagger_client.models.preview_order_create_subscription_new_subscription_owner_account import PreviewOrderCreateSubscriptionNewSubscriptionOwnerAccount
from swagger_client.models.preview_order_order_action import PreviewOrderOrderAction
from swagger_client.models.preview_order_pricing_update import PreviewOrderPricingUpdate
from swagger_client.models.preview_order_rate_plan_override import PreviewOrderRatePlanOverride
from swagger_client.models.preview_order_rate_plan_update import PreviewOrderRatePlanUpdate
from swagger_client.models.preview_order_trigger_params import PreviewOrderTriggerParams
from swagger_client.models.preview_result import PreviewResult
from swagger_client.models.preview_result_charge_metrics import PreviewResultChargeMetrics
from swagger_client.models.preview_result_credit_memos import PreviewResultCreditMemos
from swagger_client.models.preview_result_invoices import PreviewResultInvoices
from swagger_client.models.preview_result_order_actions import PreviewResultOrderActions
from swagger_client.models.preview_result_order_delta_metrics import PreviewResultOrderDeltaMetrics
from swagger_client.models.preview_result_order_metrics import PreviewResultOrderMetrics
from swagger_client.models.price_change_params import PriceChangeParams
from swagger_client.models.price_interval_with_price import PriceIntervalWithPrice
from swagger_client.models.price_interval_with_tiers import PriceIntervalWithTiers
from swagger_client.models.pricing_update import PricingUpdate
from swagger_client.models.pricing_update_recurring_delivery import PricingUpdateRecurringDelivery
from swagger_client.models.processing_options import ProcessingOptions
from swagger_client.models.processing_options_orders import ProcessingOptionsOrders
from swagger_client.models.processing_options_orders_async import ProcessingOptionsOrdersAsync
from swagger_client.models.processing_options_orders_billing_options import ProcessingOptionsOrdersBillingOptions
from swagger_client.models.processing_options_orders_electronic_payment_options import ProcessingOptionsOrdersElectronicPaymentOptions
from swagger_client.models.processing_options_orders_write_off_behavior import ProcessingOptionsOrdersWriteOffBehavior
from swagger_client.models.processing_options_orders_write_off_behavior_finance_information import ProcessingOptionsOrdersWriteOffBehaviorFinanceInformation
from swagger_client.models.product_feature_object_custom_fields import ProductFeatureObjectCustomFields
from swagger_client.models.product_object_custom_fields import ProductObjectCustomFields
from swagger_client.models.product_object_ns_fields import ProductObjectNSFields
from swagger_client.models.product_rate_plan_charge_object_custom_fields import ProductRatePlanChargeObjectCustomFields
from swagger_client.models.product_rate_plan_charge_object_ns_fields import ProductRatePlanChargeObjectNSFields
from swagger_client.models.product_rate_plan_object_custom_fields import ProductRatePlanObjectCustomFields
from swagger_client.models.product_rate_plan_object_ns_fields import ProductRatePlanObjectNSFields
from swagger_client.models.proxy_actioncreate_request import ProxyActioncreateRequest
from swagger_client.models.proxy_actiondelete_request import ProxyActiondeleteRequest
from swagger_client.models.proxy_actionquery_more_request import ProxyActionqueryMoreRequest
from swagger_client.models.proxy_actionquery_more_request_conf import ProxyActionqueryMoreRequestConf
from swagger_client.models.proxy_actionquery_more_response import ProxyActionqueryMoreResponse
from swagger_client.models.proxy_actionquery_request import ProxyActionqueryRequest
from swagger_client.models.proxy_actionquery_response import ProxyActionqueryResponse
from swagger_client.models.proxy_actionupdate_request import ProxyActionupdateRequest
from swagger_client.models.proxy_bad_request_response import ProxyBadRequestResponse
from swagger_client.models.proxy_bad_request_response_errors import ProxyBadRequestResponseErrors
from swagger_client.models.proxy_create_or_modify_delivery_schedule import ProxyCreateOrModifyDeliverySchedule
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_charge_model_configuration import ProxyCreateOrModifyProductRatePlanChargeChargeModelConfiguration
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_charge_model_configuration_item import ProxyCreateOrModifyProductRatePlanChargeChargeModelConfigurationItem
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_tier_data import ProxyCreateOrModifyProductRatePlanChargeTierData
from swagger_client.models.proxy_create_or_modify_product_rate_plan_charge_tier_data_product_rate_plan_charge_tier import ProxyCreateOrModifyProductRatePlanChargeTierDataProductRatePlanChargeTier
from swagger_client.models.proxy_create_or_modify_response import ProxyCreateOrModifyResponse
from swagger_client.models.proxy_create_product import ProxyCreateProduct
from swagger_client.models.proxy_create_product_rate_plan import ProxyCreateProductRatePlan
from swagger_client.models.proxy_create_product_rate_plan_charge import ProxyCreateProductRatePlanCharge
from swagger_client.models.proxy_create_taxation_item import ProxyCreateTaxationItem
from swagger_client.models.proxy_create_usage import ProxyCreateUsage
from swagger_client.models.proxy_delete_response import ProxyDeleteResponse
from swagger_client.models.proxy_get_import import ProxyGetImport
from swagger_client.models.proxy_get_payment_method_snapshot import ProxyGetPaymentMethodSnapshot
from swagger_client.models.proxy_get_payment_method_transaction_log import ProxyGetPaymentMethodTransactionLog
from swagger_client.models.proxy_get_payment_transaction_log import ProxyGetPaymentTransactionLog
from swagger_client.models.proxy_get_product import ProxyGetProduct
from swagger_client.models.proxy_get_product_rate_plan import ProxyGetProductRatePlan
from swagger_client.models.proxy_get_product_rate_plan_charge import ProxyGetProductRatePlanCharge
from swagger_client.models.proxy_get_product_rate_plan_charge_tier import ProxyGetProductRatePlanChargeTier
from swagger_client.models.proxy_get_usage import ProxyGetUsage
from swagger_client.models.proxy_modify_product import ProxyModifyProduct
from swagger_client.models.proxy_modify_product_rate_plan import ProxyModifyProductRatePlan
from swagger_client.models.proxy_modify_product_rate_plan_charge import ProxyModifyProductRatePlanCharge
from swagger_client.models.proxy_modify_product_rate_plan_charge_tier import ProxyModifyProductRatePlanChargeTier
from swagger_client.models.proxy_modify_usage import ProxyModifyUsage
from swagger_client.models.proxy_no_data_response import ProxyNoDataResponse
from swagger_client.models.proxy_post_import import ProxyPostImport
from swagger_client.models.proxy_unauthorized_response import ProxyUnauthorizedResponse
from swagger_client.models.put_batch_invoice_type import PutBatchInvoiceType
from swagger_client.models.put_credit_memo_tax_item_type import PutCreditMemoTaxItemType
from swagger_client.models.put_debit_memo_tax_item_type import PutDebitMemoTaxItemType
from swagger_client.models.put_discount_item_type import PutDiscountItemType
from swagger_client.models.put_event_trigger_request import PutEventTriggerRequest
from swagger_client.models.put_event_trigger_request_event_type import PutEventTriggerRequestEventType
from swagger_client.models.put_fulfillment_item_request_type import PutFulfillmentItemRequestType
from swagger_client.models.put_fulfillment_request_type import PutFulfillmentRequestType
from swagger_client.models.put_invoice_item_type import PutInvoiceItemType
from swagger_client.models.put_invoice_response_type import PutInvoiceResponseType
from swagger_client.models.put_invoice_type import PutInvoiceType
from swagger_client.models.put_order_cancel_response import PutOrderCancelResponse
from swagger_client.models.put_order_line_item_response_type import PutOrderLineItemResponseType
from swagger_client.models.put_order_line_item_update_type import PutOrderLineItemUpdateType
from swagger_client.models.put_reverse_credit_memo_response_type import PutReverseCreditMemoResponseType
from swagger_client.models.put_reverse_credit_memo_response_type_credit_memo import PutReverseCreditMemoResponseTypeCreditMemo
from swagger_client.models.put_reverse_credit_memo_response_type_debit_memo import PutReverseCreditMemoResponseTypeDebitMemo
from swagger_client.models.put_reverse_credit_memo_type import PutReverseCreditMemoType
from swagger_client.models.put_reverse_invoice_response_type import PutReverseInvoiceResponseType
from swagger_client.models.put_reverse_invoice_response_type_credit_memo import PutReverseInvoiceResponseTypeCreditMemo
from swagger_client.models.put_reverse_invoice_response_type_debit_memo import PutReverseInvoiceResponseTypeDebitMemo
from swagger_client.models.put_reverse_invoice_type import PutReverseInvoiceType
from swagger_client.models.put_scheduled_event_request import PutScheduledEventRequest
from swagger_client.models.put_tasks_request import PutTasksRequest
from swagger_client.models.query_custom_object_records_response import QueryCustomObjectRecordsResponse
from swagger_client.models.quote_object_fields import QuoteObjectFields
from swagger_client.models.ramp_charge_request import RampChargeRequest
from swagger_client.models.ramp_charge_response import RampChargeResponse
from swagger_client.models.ramp_interval_charge_delta_metrics import RampIntervalChargeDeltaMetrics
from swagger_client.models.ramp_interval_charge_delta_metrics_delta_mrr import RampIntervalChargeDeltaMetricsDeltaMrr
from swagger_client.models.ramp_interval_charge_delta_metrics_delta_quantity import RampIntervalChargeDeltaMetricsDeltaQuantity
from swagger_client.models.ramp_interval_charge_metrics import RampIntervalChargeMetrics
from swagger_client.models.ramp_interval_charge_metrics_mrr import RampIntervalChargeMetricsMrr
from swagger_client.models.ramp_interval_metrics import RampIntervalMetrics
from swagger_client.models.ramp_interval_request import RampIntervalRequest
from swagger_client.models.ramp_interval_response import RampIntervalResponse
from swagger_client.models.ramp_metrics import RampMetrics
from swagger_client.models.ramp_request import RampRequest
from swagger_client.models.ramp_response import RampResponse
from swagger_client.models.rate_plan import RatePlan
from swagger_client.models.rate_plan_charge_object_custom_fields import RatePlanChargeObjectCustomFields
from swagger_client.models.rate_plan_feature_override import RatePlanFeatureOverride
from swagger_client.models.rate_plan_feature_override_custom_fields import RatePlanFeatureOverrideCustomFields
from swagger_client.models.rate_plan_object_custom_fields import RatePlanObjectCustomFields
from swagger_client.models.rate_plan_override import RatePlanOverride
from swagger_client.models.rate_plan_update import RatePlanUpdate
from swagger_client.models.rate_plans import RatePlans
from swagger_client.models.recurring_delivery_pricing_override import RecurringDeliveryPricingOverride
from swagger_client.models.recurring_delivery_pricing_update import RecurringDeliveryPricingUpdate
from swagger_client.models.recurring_flat_fee_pricing_override import RecurringFlatFeePricingOverride
from swagger_client.models.recurring_flat_fee_pricing_update import RecurringFlatFeePricingUpdate
from swagger_client.models.recurring_per_unit_pricing_override import RecurringPerUnitPricingOverride
from swagger_client.models.recurring_per_unit_pricing_update import RecurringPerUnitPricingUpdate
from swagger_client.models.recurring_tiered_pricing_override import RecurringTieredPricingOverride
from swagger_client.models.recurring_tiered_pricing_update import RecurringTieredPricingUpdate
from swagger_client.models.recurring_volume_pricing_override import RecurringVolumePricingOverride
from swagger_client.models.recurring_volume_pricing_update import RecurringVolumePricingUpdate
from swagger_client.models.refund_credit_memo_item_type import RefundCreditMemoItemType
from swagger_client.models.refund_entity_prefix import RefundEntityPrefix
from swagger_client.models.refund_object_custom_fields import RefundObjectCustomFields
from swagger_client.models.refund_object_ns_fields import RefundObjectNSFields
from swagger_client.models.refund_part_response_type import RefundPartResponseType
from swagger_client.models.refund_part_response_typewith_success import RefundPartResponseTypewithSuccess
from swagger_client.models.remove_product import RemoveProduct
from swagger_client.models.renew_subscription import RenewSubscription
from swagger_client.models.renewal_term import RenewalTerm
from swagger_client.models.request import Request
from swagger_client.models.request1 import Request1
from swagger_client.models.resend_callout_notifications_failed_response import ResendCalloutNotificationsFailedResponse
from swagger_client.models.resend_email_notifications_failed_response import ResendEmailNotificationsFailedResponse
from swagger_client.models.revpro_accounting_codes import RevproAccountingCodes
from swagger_client.models.save_result import SaveResult
from swagger_client.models.schedule_items_response import ScheduleItemsResponse
from swagger_client.models.setting_component_key_value import SettingComponentKeyValue
from swagger_client.models.setting_item_http_operation import SettingItemHttpOperation
from swagger_client.models.setting_item_http_request_parameter import SettingItemHttpRequestParameter
from swagger_client.models.setting_item_with_operations_information import SettingItemWithOperationsInformation
from swagger_client.models.setting_source_component_response import SettingSourceComponentResponse
from swagger_client.models.setting_value_request import SettingValueRequest
from swagger_client.models.setting_value_response import SettingValueResponse
from swagger_client.models.setting_value_response_wrapper import SettingValueResponseWrapper
from swagger_client.models.settings_batch_request import SettingsBatchRequest
from swagger_client.models.settings_batch_response import SettingsBatchResponse
from swagger_client.models.sign_up_create_pm_pay_pal_ec_pay_pal_native_ec import SignUpCreatePMPayPalECPayPalNativeEC
from swagger_client.models.sign_up_create_payment_method_cardholder_info import SignUpCreatePaymentMethodCardholderInfo
from swagger_client.models.sign_up_create_payment_method_common import SignUpCreatePaymentMethodCommon
from swagger_client.models.sign_up_create_payment_method_credit_card import SignUpCreatePaymentMethodCreditCard
from swagger_client.models.sign_up_create_payment_method_credit_card_reference_transaction import SignUpCreatePaymentMethodCreditCardReferenceTransaction
from swagger_client.models.sign_up_create_payment_method_pay_pal_adaptive import SignUpCreatePaymentMethodPayPalAdaptive
from swagger_client.models.sign_up_payment_method import SignUpPaymentMethod
from swagger_client.models.sign_up_payment_method_object_custom_fields import SignUpPaymentMethodObjectCustomFields
from swagger_client.models.sign_up_request import SignUpRequest
from swagger_client.models.sign_up_response import SignUpResponse
from swagger_client.models.sign_up_response_reasons import SignUpResponseReasons
from swagger_client.models.sign_up_tax_info import SignUpTaxInfo
from swagger_client.models.sold_to_contact import SoldToContact
from swagger_client.models.sold_to_contact_post_order import SoldToContactPostOrder
from swagger_client.models.submit_batch_query_request import SubmitBatchQueryRequest
from swagger_client.models.submit_batch_query_response import SubmitBatchQueryResponse
from swagger_client.models.submit_data_query_request import SubmitDataQueryRequest
from swagger_client.models.submit_data_query_request_output import SubmitDataQueryRequestOutput
from swagger_client.models.submit_data_query_response import SubmitDataQueryResponse
from swagger_client.models.subscribe_to_product import SubscribeToProduct
from swagger_client.models.subscription_data import SubscriptionData
from swagger_client.models.subscription_object_custom_fields import SubscriptionObjectCustomFields
from swagger_client.models.subscription_object_ns_fields import SubscriptionObjectNSFields
from swagger_client.models.subscription_object_qt_fields import SubscriptionObjectQTFields
from swagger_client.models.subscription_offer_object_custom_fields import SubscriptionOfferObjectCustomFields
from swagger_client.models.system_health_error_response import SystemHealthErrorResponse
from swagger_client.models.task import Task
from swagger_client.models.tasks_response import TasksResponse
from swagger_client.models.tasks_response_pagination import TasksResponsePagination
from swagger_client.models.tax_info import TaxInfo
from swagger_client.models.taxation_item_object_custom_fields import TaxationItemObjectCustomFields
from swagger_client.models.template_detail_response import TemplateDetailResponse
from swagger_client.models.template_migration_client_request import TemplateMigrationClientRequest
from swagger_client.models.template_response import TemplateResponse
from swagger_client.models.term_info import TermInfo
from swagger_client.models.term_info_initial_term import TermInfoInitialTerm
from swagger_client.models.term_info_renewal_terms import TermInfoRenewalTerms
from swagger_client.models.terms_and_conditions import TermsAndConditions
from swagger_client.models.time_sliced_elp_net_metrics import TimeSlicedElpNetMetrics
from swagger_client.models.time_sliced_metrics import TimeSlicedMetrics
from swagger_client.models.time_sliced_net_metrics import TimeSlicedNetMetrics
from swagger_client.models.time_sliced_tcb_net_metrics import TimeSlicedTcbNetMetrics
from swagger_client.models.token_response import TokenResponse
from swagger_client.models.transfer_payment_type import TransferPaymentType
from swagger_client.models.trigger_date import TriggerDate
from swagger_client.models.trigger_params import TriggerParams
from swagger_client.models.unapply_credit_memo_type import UnapplyCreditMemoType
from swagger_client.models.unapply_payment_type import UnapplyPaymentType
from swagger_client.models.update_custom_object_cusotm_field import UpdateCustomObjectCusotmField
from swagger_client.models.update_payment_type import UpdatePaymentType
from swagger_client.models.update_schedule_items import UpdateScheduleItems
from swagger_client.models.update_task import UpdateTask
from swagger_client.models.usage import Usage
from swagger_client.models.usage_flat_fee_pricing_override import UsageFlatFeePricingOverride
from swagger_client.models.usage_flat_fee_pricing_update import UsageFlatFeePricingUpdate
from swagger_client.models.usage_object_custom_fields import UsageObjectCustomFields
from swagger_client.models.usage_overage_pricing_override import UsageOveragePricingOverride
from swagger_client.models.usage_overage_pricing_update import UsageOveragePricingUpdate
from swagger_client.models.usage_per_unit_pricing_override import UsagePerUnitPricingOverride
from swagger_client.models.usage_per_unit_pricing_update import UsagePerUnitPricingUpdate
from swagger_client.models.usage_tiered_pricing_override import UsageTieredPricingOverride
from swagger_client.models.usage_tiered_pricing_update import UsageTieredPricingUpdate
from swagger_client.models.usage_tiered_with_overage_pricing_override import UsageTieredWithOveragePricingOverride
from swagger_client.models.usage_tiered_with_overage_pricing_update import UsageTieredWithOveragePricingUpdate
from swagger_client.models.usage_values import UsageValues
from swagger_client.models.usage_volume_pricing_override import UsageVolumePricingOverride
from swagger_client.models.usage_volume_pricing_update import UsageVolumePricingUpdate
from swagger_client.models.usages_response import UsagesResponse
from swagger_client.models.validation_errors import ValidationErrors
from swagger_client.models.validation_reasons import ValidationReasons
from swagger_client.models.workflow import Workflow
from swagger_client.models.workflow_definition import WorkflowDefinition
from swagger_client.models.workflow_definition_active_version import WorkflowDefinitionActiveVersion
from swagger_client.models.workflow_definition_and_versions import WorkflowDefinitionAndVersions
from swagger_client.models.workflow_error import WorkflowError
from swagger_client.models.workflow_instance import WorkflowInstance
from swagger_client.models.z_object import ZObject
from swagger_client.models.z_object_update import ZObjectUpdate | zuora-swagger-client | /zuora-swagger-client-1.2.0.tar.gz/zuora-swagger-client-1.2.0/swagger_client/models/__init__.py | __init__.py |
ACTION = "/v1/action"
ACCOUNTING_CODE = "/v1/accounting-codes"
ACCOUNTING_PERIOD = "/v1/accounting-periods"
ACCOUNT_CRUD = "/v1/object/account"
ACCOUNT_SERVICE = "/v1/accounts"
AMENDMENT_CRUD = "/v1/object/amendment"
AMENDMENT_SERVICE = "/v1/amendments"
ATTACHMENT = "/v1/attachments"
BILL_RUN_CRUD = "/v1/object/bill-run"
BILL_RUN_SERVICE = "/v1/bill-runs"
BILLING_DOCUMENT = "/v1/billing-documents"
BILLING_PREVIEW_RUN = "/v1/billing-preview-runs"
CATALOG = "/v1/catalog/products"
CHARGE_REVENUE_SUMMARY = "/v1/charge-revenue-summaries"
COMMUNICATION_PROFILE = "/v1/object/communication-profile"
CONNECTIONS = "/v1/connections"
CONTACT = "/v1/object/contact"
CREDIT_BALANCE_ADJUSTMENT = "/v1/object/credit-balance-adjustment"
CREDIT_MEMO = "/v1/creditmemos"
CUSTOM_EXCHANGE_RATE = "/v1/custom-exchange-rates"
DEBIT_MEMO = "/v1/debitmemos"
DESCRIBE = "/v1/describe"
ENTITY = "/v1/entities"
ENTITY_CONNECTION = "/v1/entity-connections"
EVENT_TRIGGER = "/events/event-triggers"
EXPORT = "/v1/object/export"
FEATURE = "/v1/object/feature"
FILE = "/v1/files"
HMAC_SIGNATURE = "/v1/hmac-signatures"
HOSTED_PAGE = "/v1/hostedpages"
IMPORT = "/v1/object/import"
INVOICE_ADJUSTMENT = "/v1/object/invoice-adjustment"
INVOICE_ITEM_ADJUSTMENT = "/v1/object/invoice-item-adjustment"
INVOICE_ITEM = "/v1/object/invoice-item"
INVOICE_PAYMENT = "/v1/object/invoice-payment"
INVOICE_SPLIT_ITEM = "/v1/object/invoice-split-item"
INVOICE_SPLIT = "/v1/object/invoice-split"
INVOICE_CRUD = "/v1/object/invoice"
INVOICE_SERVICE = "/v1/invoices"
JOURNAL_RUN = "/v1/journal-runs"
MASS_UPDATER = "/v1/bulk"
NOTIFICATION = "/notifications"
NOTIFICATION_HISTORY = "/v1/notification-history"
OAUTH = "/oauth/token"
OPERATION = "/v1/operations"
ORDER = "/v1/orders"
PAYMENT_GATEWAY = "/v1/paymentgateways"
PAYMENT_METHOD_SNAPSHOT = "/v1/object/payment-method-snapshot"
PAYMENT_METHOD_TRANSACTION_LOG = "/v1/object/payment-method-transaction-log"
PAYMENT_METHOD_CRUD = "/v1/object/payment-method"
PAYMENT_METHOD_SERVICE = "/v1/payment-methods"
PAYMENT_RUN = "/v1/payment-runs"
PAYMENT_TRANSACTION_LOG = "/v1/object/payment-transaction-log"
PAYMENT_CRUD = "/v1/object/payment"
PAYMENT_SERVICE = "/v1/payments"
PRODUCT_FEATURE = "/v1/object/product-feature"
PRODUCT_RATE_PLAN_CHARGE_TIER = "/v1/object/product-rate-plan-charge-tier"
PRODUCT_RATE_PLAN_CHARGE = "/v1/object/product-rate-plan-charge"
PRODUCT_RATE_PLAN = "/v1/object/product-rate-plan"
PRODUCT = "/v1/object/product"
QUOTE_DOCUMENT = "/v1/quotes/document"
RATE_PLAN_CHARGE_TIER = "/v1/object/rate-plan-charge-tier"
RATE_PLAN_CHARGE = "/v1/object/rate-plan-charge"
RATE_PLAN = "/v1/object/rate-plan"
REFUND_INVOICE_PAYMENT = "/v1/object/refund-invoice-payment"
REFUND_TRANSACTION_LOG = "/v1/object/refund-transaction-log"
REFUND_CRUD = "/v1/object/refund"
REFUND_SERVICE = "/v1/refunds"
REVENUE_EVENT = "/v1/revenue-events"
REVENUE_ITEM = "/v1/revenue-items"
REVENUE_RULE = "/v1/revenue-recognition-rules"
REVENUE_SCHEDULE = "/v1/revenue-schedules"
RSA_SIGNATURE = "/v1/rsa-signatures"
SETTING = "/v1/settings"
SUBSCRIPTION_PRODUCT_FEATURE = "/v1/object/subscription-product-feature"
SUBSCRIPTION_CRUD = "/v1/object/subscription"
SUBSCRIPTION_SERVICE = "/v1/subscriptions"
SUMMARY_JOURNAL_ENTRY = "/v1/journal-entries"
TAXATION_ITEM_CRUD = "/v1/object/taxation-item"
TAXATION_ITEM_SERVICE = "/v1/taxationitems"
TRANSACTION = "/v1/transactions"
UNIT_OF_MEASURE = "/v1/object/unit-of-measure"
USAGE_CRUD = "/v1/usage"
USAGE_SERVICE = "/v1/object/usage"
USER = "/v1/users" | zuorapy | /zuorapy-0.0.4.tar.gz/zuorapy-0.0.4/consts/endpoint.py | endpoint.py |
# zup
### dependencies
* Python 3.8
### Installation
```bash
$ pip install zup
```
### Installing Zig
This will install latest master Zig release and set it as default `zig` command in your system.
Note that zup never modifies your system configuration and you must add the symlink directory that zup manages to your `%PATH%` on Windows or `$PATH` on other platforms.
```bash
zup install master -d
```
### Configuration
Config file is a python script that gets executed before any command is ran.
It can be opened with `zup config`. This uses your default program for a filetype; on windows the default is `python.exe`, please set it to a proper text editor or it won't open. Zup does not check or configure any system variables and can't know what the config will be opened with and it is your job as the owner of your system to configure it properly.
```python
# config.py
# windows: Path(os.getenv('APPDATA')) / 'zup/config.py'
# macos: Path.home() / 'Library/Preferences/zup/config.py'
# other: Path.home() / '.config/zup/config.py'
# url where index will be fetched from
# default: 'https://ziglang.org/download/index.json'
index_url = zup.config.default_index_url()
# directory where zig compilers are installed
# windows: Path(os.getenv('LOCALAPPDATA')) / 'zup'
# macos: Path.home() / 'Library/Application Support/zup'
# other: Path.home() / '.local/share/zup'
install_dir = zup.config.default_install_dir()
# directory where symlinks to compilers are created
# windows: install_dir
# macos: install_dir
# other: Path.home() / '.local/bin'
symlink_dir = zup.config.default_symlink_dir()
```
| zup | /zup-0.1.6.tar.gz/zup-0.1.6/README.md | README.md |
import sys
from pathlib import Path
from invoke import task
from jinja2 import Template
system = "zupa" # Directory name of the project
@task
def lint(c):
""""""
c.run(f"python3 -m black {system}")
c.run(f"python3 -m pylint {system}")
@task(name="docs", aliases=("html", "documentation"))
def docs_html(c, output_directory="build/html"):
"""Build the documentation in HTML form."""
c.run(f"python3 -m sphinx docs {output_directory}")
@task(name="preview", aliases=("rst",))
def preview(c):
"""Show a preview of the README file."""
rst_view = c.run(f"restview --listen=8888 --browser --pypi-strict README.rst", asynchronous=True, out_stream=sys.stdout)
print("Listening on http://localhost:8888/")
rst_view.join()
@task
def clean(c):
"""Remove all artefacts."""
patterns = ["build", "docs/build"]
for pattern in patterns:
c.run(f"rm -rf {pattern}")
@task
def test(c):
"""Run all tests under the 'tests' directory."""
c.run("python3 -m unittest discover tests 'test_*' -v")
@task
def coverage(c):
"""Run coverage from the 'tests' directory."""
c.run("coverage run --source . -m unittest discover tests 'test_*' -v")
c.run("coverage html")
@task
def minimum(c):
"""Check the minimum required python version for the project."""
c.run("vermin --no-parse-comments .")
@task(name="migrate")
def migrate_requirements(c):
"""Copy requirements from the requirements.txt file to pyproject.toml."""
lines = Path("requirements.txt").read_text().split("\n")
current = system.lower().replace("-", "_")
requirements = {current: [], "test": [], "doc": [], "graphical": [], "dev": []}
for line in lines:
if line.startswith("#"):
candidate = line[1:].lower().strip().replace(" ", "_").replace("-", "_")
if candidate in requirements.keys():
current = candidate
continue
if line.strip() == "" or ("=" in line and "#" in line):
continue
requirements[current].append("".join(line.split()))
template = Template(Path("docs/templates/pyproject.toml").read_text())
Path("pyproject.toml").write_text(template.render(requirements=requirements))
@task
def release(c, version):
""""""
if version not in ["minor", "major", "patch"]:
print("Version can be either major, minor or patch.")
return
import importlib
current_module = importlib.import_module(system)
__version_info__ = current_module.__version_info__
__version__ = current_module.__version__
_major, _minor, _patch = __version_info__
if version == "patch":
_patch = _patch + 1
elif version == "minor":
_minor = _minor + 1
_patch = 0
elif version == "major":
_major = _major + 1
_minor = 0
_patch = 0
c.run(f"git checkout -b release-{_major}.{_minor}.{_patch} dev")
c.run(f"sed -i 's/{__version__}/{_major}.{_minor}.{_patch}/g' {system}/__init__.py")
print(f"Update the readme for version {_major}.{_minor}.{_patch}.")
input("Press enter when ready.")
c.run(f"git add -u")
c.run(f'git commit -m "Update changelog version {_major}.{_minor}.{_patch}"')
c.run(f"git push --set-upstream origin release-{_major}.{_minor}.{_patch}")
c.run(f"git checkout main")
c.run(f"git merge --no-ff release-{_major}.{_minor}.{_patch}")
c.run(f'git tag -a {_major}.{_minor}.{_patch} -m "Release {_major}.{_minor}.{_patch}"')
c.run(f"git push")
c.run(f"git checkout dev")
c.run(f"git merge --no-ff release-{_major}.{_minor}.{_patch}")
c.run(f"git push")
c.run(f"git branch -d release-{_major}.{_minor}.{_patch}")
c.run(f"git push origin --tags") | zupa | /zupa-0.0.2.tar.gz/zupa-0.0.2/tasks.py | tasks.py |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import *
from zuper_commons.text.zc_wildcards import wildcard_to_regexp
from zuper_typing import debug_print
from .parsing import (AbilityMatch, AbilityMatchByPattern, Allow, Always, AndMatch, AttributeMatch, ByPattern, Comment,
ConditionMatch, HasAttributes, NewAbility, NewObject, NewOType, NewParentRelation, NewProperty,
parse_string, QueryGetProperties, QueryHAS, QueryIS, ResourceMatch, SetChildParentRelation,
SetProperty, ShowState, SingleResourceMatch, Statement)
@dataclass
class Object:
main_name: str
others: List[str]
type_name: str
parents: Dict[str, 'Object'] = field(default_factory=dict)
children: Dict[str, 'Object'] = field(default_factory=dict)
properties: Dict[str, List[ResourceMatch]] = field(default_factory=lambda: defaultdict(list))
@dataclass
class OType:
t_parents: Dict[str, bool] = field(default_factory=dict)
t_abilities: Dict[str, str] = field(default_factory=dict)
t_objects: Dict[str, Object] = field(default_factory=dict)
t_aliases: Dict[str, Object] = field(default_factory=dict)
t_properties: Dict[str, str] = field(default_factory=dict)
class AuthException(Exception):
pass
class Invalid(AuthException):
pass
class CouldNotFindResource(AuthException):
pass
@dataclass
class QResult:
ok: bool
line: str
query_result: Any
msg: Optional[str]
@dataclass
class Interpreter:
types: Dict[str, OType] = field(default_factory=dict)
allows: List[Allow] = field(default_factory=list)
statements_history: List[Statement] = field(default_factory=list)
results: List[QResult] = field(default_factory=list)
results_history: List[QResult] = field(default_factory=list)
last_line: str = None
functions: Dict[str, Callable] = field(default_factory=dict)
child_parent_relations: List[SetChildParentRelation] = field(default_factory=list)
# def __post_init__(self):
# # self.types = {}
# # self.allows = []
# # self.statements_history = []
# # self.results = []
# # self.results_history = []
# self.last_line = None
#
# self.functions = {}
def info(self) -> str:
s = []
for k, v in self.types.items():
s.append(k)
s.append(debug_print(v.t_objects))
return "\n".join(s)
def knows(self, type_name: str, object_identifier: str):
t = self._get_type(type_name)
return object_identifier in t.t_objects
def interpret(self, line: str, statement: Statement) -> QResult:
self.last_line = line
self.statements_history.append(statement)
t = type(statement).__name__
if t in self.functions:
ff = self.functions[t]
else:
f = f'interpret_{t}'
if not hasattr(self, f):
msg = f'Cannot find {f}'
raise NotImplementedError(msg)
ff = getattr(self, f)
self.functions[t] = ff
try:
r = ff(statement)
assert isinstance(r, QResult), statement
return r
except AuthException as e:
return self._mark_failure(str(e))
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as e:
msg = f'Cannot intepret statement {statement}'
raise ValueError(msg) from e
def _mark_ok(self, msg=None) -> QResult:
qr = QResult(ok=True, msg=msg, line=self.last_line, query_result=None)
self.results.append(qr)
self.results_history.append(qr)
return qr
def _mark_failure(self, msg) -> QResult:
qr = QResult(ok=False, msg=msg, line=self.last_line, query_result=None)
self.results.append(qr)
self.results_history.append(qr)
return qr
def _mark_query_result(self, res, msg=None) -> QResult:
qr = QResult(ok=True, msg=msg, line=self.last_line, query_result=res)
self.results.append(qr)
self.results_history.append(qr)
return qr
# def get_results(self) -> List[QResult]:
# """ Returns the last results and drops them. """
# r = self.results
# self.results = []
# return r
# def get_results_log_errors(self):
# for r in self.get_results():
# if not r.ok:
# logger.error(r)
def _get_type(self, type_name):
if type_name not in self.types:
msg = f'Could not find type {type_name!r}'
raise Invalid(msg)
return self.types[type_name]
def interpret_NewOType(self, s: NewOType) -> QResult:
if s.type_name in self.types:
msg = f'Already know find type {s.type_name!r}'
raise Invalid(msg)
self.types[s.type_name] = OType()
return self._mark_ok()
def interpret_NewParentRelation(self, s: NewParentRelation) -> QResult:
t = self._get_type(s.type_name)
if s.parent_name in t.t_parents:
msg = f'Already set relationship.'
raise Invalid(msg)
t.t_parents[s.parent_name] = s.compulsory
return self._mark_ok()
def interpret_Comment(self, s: Comment) -> QResult:
return self._mark_ok(s.line)
def interpret_ShowState(self, s: ShowState) -> QResult:
m = self.info()
return self._mark_ok(m)
def interpret_NewAbility(self, s: NewAbility) -> QResult:
t = self._get_type(s.type_name)
if s.ability_name in t.t_abilities:
msg = f'Already set ability {s.ability_name!r}.'
raise Invalid(msg)
t.t_abilities[s.ability_name] = s.title
return self._mark_ok()
def interpret_NewObject(self, s: NewObject) -> QResult:
t = self._get_type(s.type_name)
main_name = s.identifiers[0]
others = s.identifiers[1:]
if main_name in t.t_objects:
msg = f'Already know object {main_name!r}.'
raise Invalid(msg)
t.t_objects[main_name] = ob = Object(main_name=main_name, others=others, type_name=s.type_name)
for alias in others:
if alias in t.t_aliases:
msg = f'Already know alias {alias!r}.'
raise Invalid(msg)
t.t_aliases[alias] = ob
for scp in self.child_parent_relations:
if self.object_matches(ob, scp.child_match):
for parent in self.get_resources(scp.parent_match):
self.set_relationship(ob, parent)
if self.object_matches(ob, scp.parent_match):
for child in self.get_resources(scp.child_match):
self.set_relationship(child, ob)
return self._mark_ok()
def set_relationship(self, child: Object, parent: Object):
p = list(get_parents_and_self(parent))
if child in p:
msg = f'Cannot set parent-relation because child is a parent of parent.' \
f'\nParent: {parent}' \
f'\nChild: {child}'
raise Invalid(msg)
child.parents[parent.main_name] = parent
parent.children[child.main_name] = child
def interpret_SetChildParentRelation(self, s: SetChildParentRelation) -> QResult:
for parent in self.get_resources(s.parent_match):
for child in self.get_resources(s.child_match):
self.set_relationship(child, parent)
# make sure no recursion
# p = list(get_parents_and_self(parent))
# if child in p:
# msg = f'Cannot set parent-relation because child is a parent of parent.' \
# f'\nParent: {parent}' \
# f'\nChild: {child}' \
# f'\ns: {s}'
# raise Invalid(msg)
#
# child.parents[parent.main_name] = parent
# parent.children[child.main_name] = child
self.child_parent_relations.append(s)
return self._mark_ok()
def interpret_NewProperty(self, s: NewProperty) -> QResult:
t = self._get_type(s.type_name)
if s.property_name in t.t_properties:
msg = f'Already set property {s.property_name!r}.'
raise Invalid(msg)
t.t_properties[s.property_name] = s.title
return self._mark_ok()
def interpret_SetProperty(self, s: SetProperty) -> QResult:
for r in self.get_resources(s.resource_match):
t = self.types[r.type_name]
if s.property_name not in t.t_properties:
msg = f'Cannot set property {s.property_name!r} for object {r.main_name!r} of type {r.type_name!r}.'
raise Invalid(msg)
r.properties[s.property_name].append(s.context)
return self._mark_ok()
def interpret_Allow(self, s: Allow) -> QResult:
self.allows.append(s)
return self._mark_ok()
def object_matches(self, ob: Object, rm: ResourceMatch):
if isinstance(rm, ByPattern):
if (ob.type_name != rm.type_name):
return False
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
return True
return False
elif isinstance(rm, SingleResourceMatch):
if (ob.type_name != rm.type_name):
return False
return rm.identifier in [ob.main_name] + ob.others
else:
raise NotImplementedError(rm)
def get_resources(self, rm: ResourceMatch) -> Iterator[Object]:
if isinstance(rm, ByPattern):
t = self._get_type(rm.type_name)
for obname, ob in list(t.t_objects.items()):
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
yield ob
elif isinstance(rm, SingleResourceMatch):
t = self._get_type(rm.type_name)
if rm.identifier in t.t_objects:
yield t.t_objects[rm.identifier]
elif rm.identifier in t.t_aliases:
yield t.t_aliases[rm.identifier]
else:
raise NotImplementedError(rm)
def get_resource(self, rm: SingleResourceMatch) -> Object:
t = self.types[rm.type_name]
for obname, ob in list(t.t_objects.items()):
for identifier in [ob.main_name] + ob.others:
if rm.identifier == identifier:
return ob
msg = f'Could not find resource corresponding to {rm}'
raise CouldNotFindResource(msg)
def interpret_QueryIS(self, query: QueryIS) -> QResult:
# logger.debug(f'query {query}')
user = self.get_resource(query.user)
context = self.get_resource(query.context)
t = self._get_type(context.type_name)
ability = query.ability
if not ability in t.t_abilities:
msg = f'Unknown ability {ability!r} for object of type {context.type_name!r}.'
msg += f'\nKnown: {",".join(t.t_abilities)}.'
raise Invalid(msg)
properties = get_active_properties(user, context)
# logger.info('properties: %s' % properties)
context_parents = list(get_parents_and_self(context))
user_parents = list(get_parents_and_self(user))
msg = 'Active properties: %s' % properties
msg += f'\nuser hierarchy:'
for p in user_parents:
msg += f'\n - {p.type_name} : {p.main_name}'
msg += f'\nresource hierarchy: '
for p in context_parents:
msg += f'\n - {p.type_name} : {p.main_name}'
for allow in self.allows:
c1 = any(rmatch(allow.user_match, _) for _ in user_parents)
c2 = amatch(allow.ability_match, ability)
c3 = any(rmatch(allow.context_match, _) for _ in context_parents)
c4 = cmatch(allow.condition, properties)
ok = c1 and c2 and c3 and c4
if ok:
return self._mark_query_result(True)
else:
pass
msg += f'\nfalse (user match {c1}, amatch {c2}, context match {c3}, condition match{c4})\n for {allow}'
return self._mark_query_result(False, msg)
def interpret_QueryHAS(self, query: QueryHAS) -> QResult:
# logger.debug(f'query {query}')
user = self.get_resource(query.user)
context = self.get_resource(query.context)
properties = get_active_properties(user, context)
# logger.debug('properties: %s' % properties)
res = query.property in properties
return self._mark_query_result(res)
def interpret_QueryGetProperties(self, query: QueryGetProperties) -> QResult:
user = self.get_resource(query.user)
context = self.get_resource(query.context)
properties = get_active_properties(user, context)
return self._mark_query_result(properties)
def parse_and_interpret(self, src: str) -> List[QResult]:
res = []
for line, statement in parse_string(src):
r = self.interpret(line, statement)
assert isinstance(r, QResult), line
res.append(r)
return res
def get_history(self) -> str:
res = []
for s in reversed(self.results_history):
res.append(str(s))
return "\n".join(res)
def amatch(am: AbilityMatch, ability):
if isinstance(am, AbilityMatchByPattern):
if pattern_matches(am.pattern, ability):
return True
return False
else:
raise NotImplementedError(am)
def cmatch(cm: ConditionMatch, properties: Dict[str, bool]):
if isinstance(cm, Always):
return True
if isinstance(cm, AttributeMatch):
for p, v in properties.items():
if v and pattern_matches(cm.pattern, p):
return True
return False
raise NotImplementedError(cm)
def get_active_properties(user: Object, context: Object):
user_parents = list(get_parents_and_self(user))
context_parents = list(get_parents_and_self(context))
properties = {}
# Now set the properties
for cp in context_parents:
for up in user_parents:
for pname, matches in up.properties.items():
for match in matches:
if rmatch(match, cp):
properties[pname] = True
return properties
def get_parents_and_self(ob: Object) -> Iterator[Object]:
for parent in ob.parents.values():
yield from get_parents_and_self(parent)
yield ob
def rmatch(rm: ResourceMatch, ob: Object):
if isinstance(rm, ByPattern):
if rm.type_name != ob.type_name:
return False
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
return True
return False
if isinstance(rm, SingleResourceMatch):
if rm.type_name != ob.type_name:
return False
if rm.identifier == ob.main_name:
return True
if rm.identifier in ob.others:
return True
return False
elif isinstance(rm, AndMatch):
matches = (rmatch(_, ob) for _ in rm.ops)
return all(matches)
elif isinstance(rm, HasAttributes):
# XXX
matches = (_ in ob.properties for _ in rm.attributes)
return all(matches)
else:
raise NotImplementedError(rm)
def pattern_matches(pattern, identifier):
regexp = wildcard_to_regexp(pattern)
return regexp.match(identifier) | zuper-auth-z5 | /zuper-auth-z5-5.0.3.tar.gz/zuper-auth-z5-5.0.3/src/zuper_auth/interpret.py | interpret.py |
from dataclasses import dataclass
from typing import Callable, Iterator, List, Optional, Tuple
class Statement:
def to_line(self) -> str:
''' Returns the line that can be parsed to this statement. '''
return str(self)
class Storage:
parsing_functions = {}
def parse_function(f: Callable) -> Callable:
_, token = f.__name__.split('_', maxsplit=1)
Storage.parsing_functions[token] = f
return f
@dataclass
class NewOType(Statement):
type_name: str
title: Optional[str] = None
@dataclass
class Comment(Statement):
line: str
@parse_function
def parse_REM(rest: str) -> Tuple[Statement, str]:
return Comment(rest), ''
@dataclass
class ShowState(Statement):
pass
@parse_function
def parse_SHOW_STATE(rest: str) -> Tuple[Statement, str]:
return ShowState(), ''
@parse_function
def parse_TYPE(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
return NewOType(type_name=type_name), rest
@dataclass
class NewAbility(Statement):
'ABILITY domain domain-create-organization '
type_name: str
ability_name: str
title: Optional[str] = None
@parse_function
def parse_ABILITY(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
ability_name, rest = get_one_token(rest)
return NewAbility(type_name=type_name, ability_name=ability_name), rest
@dataclass
class NewParentRelation(Statement):
"PARENT type_name parent_name"
type_name: str
parent_name: str
compulsory: bool
@parse_function
def parse_PARENT(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
parent_name, rest = get_one_token(rest)
return NewParentRelation(type_name=type_name, parent_name=parent_name, compulsory=False), rest
@dataclass
class NewProperty(Statement):
''' PROPERTY type_name name title '''
type_name: str
property_name: str
title: Optional[str] = None
@parse_function
def parse_PROPERTY(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
property_name, rest = get_one_token(rest)
return NewProperty(type_name=type_name, property_name=property_name), rest
@dataclass
class SetProperty(Statement):
''' FOR <> SET property_name IN <> '''
resource_match: 'ResourceMatch'
property_name: str
context: 'ResourceMatch'
@parse_function
def parse_FOR(rest0: str) -> Tuple[Statement, str]:
resource_match, rest = parse_resource_match(rest0)
rest = skip_one_token('SET', rest)
property_name, rest = get_one_token(rest)
if rest:
rest = skip_one_token('IN', rest)
context, rest = parse_resource_match(rest)
else:
context = ByPattern('*', '*')
return SetProperty(resource_match, property_name, context), rest
@dataclass
class NewRelation(Statement):
relation_name: str
types: List[str]
@dataclass
class NewObject(Statement):
''' NEW challenge 12 aido-admin aido-admin '''
type_name: str
identifiers: List[str]
@parse_function
def parse_NEW(rest0: str) -> Tuple[NewObject, str]:
type_name, rest = parse_until(' ', rest0)
identifiers = rest.split(' ')
return NewObject(type_name, identifiers), ''
class ResourceMatch:
pass
@dataclass
class SingleResourceMatch(ResourceMatch):
type_name: str
identifier: str
def __post_init__(self):
if '*' in self.identifier:
msg = 'Expected a single resource, not a pattern here.'
raise ValueError(msg)
# class ByIdentifier(ResourceMatch):
# ''' challenge:12 '''
# type_name: str
# identifier: str
#
@dataclass
class ByPattern(ResourceMatch):
''' challenge:aido* '''
type_name: str
pattern: str
def __post_init__(self):
if not self.type_name or not self.pattern:
raise ValueError(self)
@dataclass
class HasAttributes(ResourceMatch):
attributes: List[str]
@dataclass
class AndMatch(ResourceMatch):
ops: List[ResourceMatch]
def parse_single_resource_match(rest0) -> Tuple[SingleResourceMatch, str]:
type_name, rest = parse_until(':', rest0, required=True)
identifier, rest = parse_until(' ', rest)
return SingleResourceMatch(type_name=type_name, identifier=identifier), rest
def parse_resource_match(rest0: str) -> Tuple[ResourceMatch, str]:
if not rest0:
raise ValueError(rest0)
type_name, rest = parse_until(':', rest0, required=True)
pattern, rest = parse_until(' ', rest)
if '*' in type_name or '*' in pattern:
bp = ByPattern(type_name, pattern)
else:
bp = SingleResourceMatch(type_name, pattern)
if rest.startswith('['):
n = rest.index(']')
interesting = rest[1:n]
attributes = interesting.strip().split()
rest = rest[n + 1:]
bp = AndMatch([HasAttributes(attributes), bp])
try:
return bp, rest
except ValueError as e:
msg = f'Cannot parse resource match {rest0!r}'
raise ValueError(msg) from e
@dataclass
class SetChildParentRelation(Statement):
''' SUB group:one organization:aido '''
child_match: ResourceMatch
parent_match: ResourceMatch
@parse_function
def parse_SUB(rest0) -> Tuple[Statement, str]:
child_match, rest = parse_resource_match(rest0)
parent_match, rest = parse_resource_match(rest)
return SetChildParentRelation(child_match, parent_match), rest
"""
SUB challenge:* domain:1
ALLOW <name> TO <Ability> IN <context> IF challenge-owner
"""
class Query0(Statement):
pass
@dataclass
class QueryIS(Query0):
''' IS <res> ALLOWED ability IN <context> '''
user: 'SingleResourceMatch'
ability: str
context: 'SingleResourceMatch'
@parse_function
def parse_IS(rest0) -> Tuple[QueryIS, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('ALLOWED', rest)
ability, rest = get_one_token(rest)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryIS(user, ability, context), rest
@dataclass
class QueryHAS(Query0):
''' HAS <res> PROPERTY ability IN <context> '''
user: 'SingleResourceMatch'
property: str
context: 'SingleResourceMatch'
@parse_function
def parse_HAS(rest0) -> Tuple[QueryHAS, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('PROPERTY', rest)
property, rest = get_one_token(rest)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryHAS(user, property, context), rest
@dataclass
class QueryGetProperties(Query0):
''' PROPERTIES <r> IN <context> '''
user: 'SingleResourceMatch'
context: 'SingleResourceMatch'
@parse_function
def parse_PROPERTIES(rest0) -> Tuple[QueryGetProperties, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryGetProperties(user, context), rest
class AbilityMatch:
pass
@dataclass
class AbilityMatchByPattern(AbilityMatch):
pattern: str
def __post_init__(self):
if ':' in self.pattern:
raise ValueError(self)
def parse_ability_match(rest) -> Tuple[AbilityMatch, str]:
pattern, rest = get_one_token(rest)
return AbilityMatchByPattern(pattern), rest
class ConditionMatch:
pass
@dataclass
class AttributeMatch(ConditionMatch):
pattern: str
def __post_init__(self):
if ':' in self.pattern:
raise ValueError(self)
def parse_condition_match(rest) -> Tuple[ConditionMatch, str]:
pattern, rest = get_one_token(rest)
return AttributeMatch(pattern), rest
class Always(ConditionMatch):
pass
@dataclass
class Allow(Statement):
''' ALLOW <user match> TO <ability match> IN <resource match> [IF <condition match>] '''
user_match: ResourceMatch
ability_match: AbilityMatch
context_match: ResourceMatch
condition: ConditionMatch
@parse_function
def parse_ALLOW(rest0) -> Tuple[Allow, str]:
user_match, rest = parse_resource_match(rest0)
rest = skip_one_token('TO', rest)
ability_match, rest = parse_ability_match(rest)
rest = skip_one_token('IN', rest)
context_match, rest = parse_resource_match(rest)
if rest:
rest = skip_one_token('IF', rest)
condition_match, rest = parse_condition_match(rest)
else:
condition_match = Always()
return Allow(user_match, ability_match, context_match, condition_match), rest
def remove_comment(line: str) -> str:
try:
i = line.index('#')
except:
return line
else:
return line[:i]
def parse_string(s) -> Iterator[Tuple[str, Statement]]:
s = s.strip()
lines = s.split('\n')
lines = [remove_comment(_) for _ in lines]
lines = [_.strip() for _ in lines]
lines = [_ for _ in lines if _]
for line in lines:
token, rest = get_one_token(line)
functions = Storage.parsing_functions
if token not in functions:
raise NotImplementedError((token, line))
f = functions[token]
try:
statement, rest = f(rest)
except ValueError as e:
msg = f'Cannot parse line {line!r}.'
raise ValueError(msg) from e
yield line, statement
def get_one_token(line: str):
line = line.lstrip()
return parse_until(' ', line)
def skip_one_token(expect: str, line: str):
token, rest = get_one_token(line)
if expect != token:
msg = f'Expected {expect!r} at the beginning of {line!r}.'
raise ValueError(msg)
return rest
def parse_until(sep: str, rest: str, required=False) -> Tuple[str, str]:
rest = rest.lstrip()
if not sep in rest:
if required:
msg = f'Could not find separator {sep!r} in {rest!r}.'
raise ValueError(msg)
return rest, ''
# msg = f'Cannot find separator {sep!r} in {rest!r}.'
# raise ValueError(msg)
tokens = rest.split(sep, maxsplit=1)
return tokens[0], tokens[1] | zuper-auth-z5 | /zuper-auth-z5-5.0.3.tar.gz/zuper-auth-z5-5.0.3/src/zuper_auth/parsing.py | parsing.py |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, List, Optional
from zuper_commons.text.zc_wildcards import wildcard_to_regexp
from zuper_typing import debug_print
from .parsing import (AbilityMatch, AbilityMatchByPattern, Allow, Always, AndMatch, AttributeMatch, ByPattern, Comment,
ConditionMatch, HasAttributes, NewAbility, NewObject, NewOType, NewParentRelation, NewProperty,
parse_string, QueryGetProperties, QueryHAS, QueryIS, ResourceMatch, SetChildParentRelation,
SetProperty, ShowState, SingleResourceMatch, Statement)
@dataclass
class Object:
main_name: str
others: List[str]
type_name: str
parents: Dict[str, 'Object'] = field(default_factory=dict)
children: Dict[str, 'Object'] = field(default_factory=dict)
properties: Dict[str, List[ResourceMatch]] = field(default_factory=lambda: defaultdict(list))
@dataclass
class OType:
t_parents: Dict[str, bool] = field(default_factory=dict)
t_abilities: Dict[str, str] = field(default_factory=dict)
t_objects: Dict[str, Object] = field(default_factory=dict)
t_aliases: Dict[str, Object] = field(default_factory=dict)
t_properties: Dict[str, str] = field(default_factory=dict)
class AuthException(Exception):
pass
class Invalid(AuthException):
pass
class CouldNotFindResource(AuthException):
pass
@dataclass
class QResult:
ok: bool
line: str
query_result: Any
msg: Optional[str]
@dataclass
class Interpreter:
types: Dict[str, OType] = field(default_factory=dict)
allows: List[Allow] = field(default_factory=list)
statements_history: List[Statement] = field(default_factory=list)
results: List[QResult] = field(default_factory=list)
results_history: List[QResult] = field(default_factory=list)
last_line: str = None
functions: Dict[str, Callable] = field(default_factory=dict)
child_parent_relations: List[SetChildParentRelation] = field(default_factory=list)
# def __post_init__(self):
# # self.types = {}
# # self.allows = []
# # self.statements_history = []
# # self.results = []
# # self.results_history = []
# self.last_line = None
#
# self.functions = {}
def info(self) -> str:
s = []
for k, v in self.types.items():
s.append(k)
s.append(debug_print(v.t_objects))
return "\n".join(s)
def knows(self, type_name: str, object_identifier: str):
t = self._get_type(type_name)
return object_identifier in t.t_objects
def interpret(self, line: str, statement: Statement) -> QResult:
self.last_line = line
self.statements_history.append(statement)
t = type(statement).__name__
if t in self.functions:
ff = self.functions[t]
else:
f = f'interpret_{t}'
if not hasattr(self, f):
msg = f'Cannot find {f}'
raise NotImplementedError(msg)
ff = getattr(self, f)
self.functions[t] = ff
try:
r = ff(statement)
assert isinstance(r, QResult), statement
return r
except AuthException as e:
return self._mark_failure(str(e))
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as e:
msg = f'Cannot intepret statement {statement}'
raise ValueError(msg) from e
def _mark_ok(self, msg=None) -> QResult:
qr = QResult(ok=True, msg=msg, line=self.last_line, query_result=None)
self.results.append(qr)
self.results_history.append(qr)
return qr
def _mark_failure(self, msg) -> QResult:
qr = QResult(ok=False, msg=msg, line=self.last_line, query_result=None)
self.results.append(qr)
self.results_history.append(qr)
return qr
def _mark_query_result(self, res, msg=None) -> QResult:
qr = QResult(ok=True, msg=msg, line=self.last_line, query_result=res)
self.results.append(qr)
self.results_history.append(qr)
return qr
# def get_results(self) -> List[QResult]:
# """ Returns the last results and drops them. """
# r = self.results
# self.results = []
# return r
# def get_results_log_errors(self):
# for r in self.get_results():
# if not r.ok:
# logger.error(r)
def _get_type(self, type_name):
if type_name not in self.types:
msg = f'Could not find type {type_name!r}'
raise Invalid(msg)
return self.types[type_name]
def interpret_NewOType(self, s: NewOType) -> QResult:
if s.type_name in self.types:
msg = f'Already know find type {s.type_name!r}'
raise Invalid(msg)
self.types[s.type_name] = OType()
return self._mark_ok()
def interpret_NewParentRelation(self, s: NewParentRelation) -> QResult:
t = self._get_type(s.type_name)
if s.parent_name in t.t_parents:
msg = f'Already set relationship.'
raise Invalid(msg)
t.t_parents[s.parent_name] = s.compulsory
return self._mark_ok()
def interpret_Comment(self, s: Comment) -> QResult:
return self._mark_ok(s.line)
def interpret_ShowState(self, s: ShowState) -> QResult:
m = self.info()
return self._mark_ok(m)
def interpret_NewAbility(self, s: NewAbility) -> QResult:
t = self._get_type(s.type_name)
if s.ability_name in t.t_abilities:
msg = f'Already set ability {s.ability_name!r}.'
raise Invalid(msg)
t.t_abilities[s.ability_name] = s.title
return self._mark_ok()
def interpret_NewObject(self, s: NewObject) -> QResult:
t = self._get_type(s.type_name)
main_name = s.identifiers[0]
others = s.identifiers[1:]
if main_name in t.t_objects:
msg = f'Already know object {main_name!r}.'
raise Invalid(msg)
t.t_objects[main_name] = ob = Object(main_name=main_name, others=others, type_name=s.type_name)
for alias in others:
if alias in t.t_aliases:
msg = f'Already know alias {alias!r}.'
raise Invalid(msg)
t.t_aliases[alias] = ob
for scp in self.child_parent_relations:
if self.object_matches(ob, scp.child_match):
for parent in self.get_resources(scp.parent_match):
self.set_relationship(ob, parent)
if self.object_matches(ob, scp.parent_match):
for child in self.get_resources(scp.child_match):
self.set_relationship(child, ob)
return self._mark_ok()
def set_relationship(self, child: Object, parent: Object):
p = list(get_parents_and_self(parent))
if child in p:
msg = f'Cannot set parent-relation because child is a parent of parent.' \
f'\nParent: {parent}' \
f'\nChild: {child}'
raise Invalid(msg)
child.parents[parent.main_name] = parent
parent.children[child.main_name] = child
def interpret_SetChildParentRelation(self, s: SetChildParentRelation) -> QResult:
for parent in self.get_resources(s.parent_match):
for child in self.get_resources(s.child_match):
self.set_relationship(child, parent)
# make sure no recursion
# p = list(get_parents_and_self(parent))
# if child in p:
# msg = f'Cannot set parent-relation because child is a parent of parent.' \
# f'\nParent: {parent}' \
# f'\nChild: {child}' \
# f'\ns: {s}'
# raise Invalid(msg)
#
# child.parents[parent.main_name] = parent
# parent.children[child.main_name] = child
self.child_parent_relations.append(s)
return self._mark_ok()
def interpret_NewProperty(self, s: NewProperty) -> QResult:
t = self._get_type(s.type_name)
if s.property_name in t.t_properties:
msg = f'Already set property {s.property_name!r}.'
raise Invalid(msg)
t.t_properties[s.property_name] = s.title
return self._mark_ok()
def interpret_SetProperty(self, s: SetProperty) -> QResult:
for r in self.get_resources(s.resource_match):
t = self.types[r.type_name]
if s.property_name not in t.t_properties:
msg = f'Cannot set property {s.property_name!r} for object {r.main_name!r} of type {r.type_name!r}.'
raise Invalid(msg)
r.properties[s.property_name].append(s.context)
return self._mark_ok()
def interpret_Allow(self, s: Allow) -> QResult:
self.allows.append(s)
return self._mark_ok()
def object_matches(self, ob: Object, rm: ResourceMatch):
if isinstance(rm, ByPattern):
if (ob.type_name != rm.type_name):
return False
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
return True
return False
elif isinstance(rm, SingleResourceMatch):
if (ob.type_name != rm.type_name):
return False
return rm.identifier in [ob.main_name] + ob.others
else:
raise NotImplementedError(rm)
def get_resources(self, rm: ResourceMatch) -> Iterator[Object]:
if isinstance(rm, ByPattern):
t = self._get_type(rm.type_name)
for obname, ob in list(t.t_objects.items()):
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
yield ob
elif isinstance(rm, SingleResourceMatch):
t = self._get_type(rm.type_name)
if rm.identifier in t.t_objects:
yield t.t_objects[rm.identifier]
elif rm.identifier in t.t_aliases:
yield t.t_aliases[rm.identifier]
else:
raise NotImplementedError(rm)
def get_resource(self, rm: SingleResourceMatch) -> Object:
t = self.types[rm.type_name]
for obname, ob in list(t.t_objects.items()):
for identifier in [ob.main_name] + ob.others:
if rm.identifier == identifier:
return ob
msg = f'Could not find resource corresponding to {rm}'
raise CouldNotFindResource(msg)
def interpret_QueryIS(self, query: QueryIS) -> QResult:
# logger.debug(f'query {query}')
user = self.get_resource(query.user)
context = self.get_resource(query.context)
t = self._get_type(context.type_name)
ability = query.ability
if not ability in t.t_abilities:
msg = f'Unknown ability {ability!r} for object of type {context.type_name!r}.'
msg += f'\nKnown: {",".join(t.t_abilities)}.'
raise Invalid(msg)
properties = get_active_properties(user, context)
# logger.info('properties: %s' % properties)
context_parents = list(get_parents_and_self(context))
user_parents = list(get_parents_and_self(user))
msg = 'Active properties: %s' % properties
msg += f'\nuser hierarchy:'
for p in user_parents:
msg += f'\n - {p.type_name} : {p.main_name}'
msg += f'\nresource hierarchy: '
for p in context_parents:
msg += f'\n - {p.type_name} : {p.main_name}'
for allow in self.allows:
c1 = any(rmatch(allow.user_match, _) for _ in user_parents)
c2 = amatch(allow.ability_match, ability)
c3 = any(rmatch(allow.context_match, _) for _ in context_parents)
c4 = cmatch(allow.condition, properties)
ok = c1 and c2 and c3 and c4
if ok:
return self._mark_query_result(True)
else:
pass
msg += f'\nfalse (user match {c1}, amatch {c2}, context match {c3}, condition match{c4})\n for {allow}'
return self._mark_query_result(False, msg)
def interpret_QueryHAS(self, query: QueryHAS) -> QResult:
# logger.debug(f'query {query}')
user = self.get_resource(query.user)
context = self.get_resource(query.context)
properties = get_active_properties(user, context)
# logger.debug('properties: %s' % properties)
res = query.property in properties
return self._mark_query_result(res)
def interpret_QueryGetProperties(self, query: QueryGetProperties) -> QResult:
user = self.get_resource(query.user)
context = self.get_resource(query.context)
properties = get_active_properties(user, context)
return self._mark_query_result(properties)
def parse_and_interpret(self, src: str) -> List[QResult]:
res = []
for line, statement in parse_string(src):
r = self.interpret(line, statement)
assert isinstance(r, QResult), line
res.append(r)
return res
def get_history(self) -> str:
res = []
for s in reversed(self.results_history):
res.append(str(s))
return "\n".join(res)
def amatch(am: AbilityMatch, ability):
if isinstance(am, AbilityMatchByPattern):
if pattern_matches(am.pattern, ability):
return True
return False
else:
raise NotImplementedError(am)
def cmatch(cm: ConditionMatch, properties: Dict[str, bool]):
if isinstance(cm, Always):
return True
if isinstance(cm, AttributeMatch):
for p, v in properties.items():
if v and pattern_matches(cm.pattern, p):
return True
return False
raise NotImplementedError(cm)
def get_active_properties(user: Object, context: Object):
user_parents = list(get_parents_and_self(user))
context_parents = list(get_parents_and_self(context))
properties = {}
# Now set the properties
for cp in context_parents:
for up in user_parents:
for pname, matches in up.properties.items():
for match in matches:
if rmatch(match, cp):
properties[pname] = True
return properties
def get_parents_and_self(ob: Object) -> Iterator[Object]:
for parent in ob.parents.values():
yield from get_parents_and_self(parent)
yield ob
def rmatch(rm: ResourceMatch, ob: Object):
if isinstance(rm, ByPattern):
if rm.type_name != ob.type_name:
return False
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
return True
return False
if isinstance(rm, SingleResourceMatch):
if rm.type_name != ob.type_name:
return False
if rm.identifier == ob.main_name:
return True
if rm.identifier in ob.others:
return True
return False
elif isinstance(rm, AndMatch):
matches = (rmatch(_, ob) for _ in rm.ops)
return all(matches)
elif isinstance(rm, HasAttributes):
# XXX
matches = (_ in ob.properties for _ in rm.attributes)
return all(matches)
else:
raise NotImplementedError(rm)
def pattern_matches(pattern, identifier):
regexp = wildcard_to_regexp(pattern)
return regexp.match(identifier) | zuper-auth-z6 | /zuper-auth-z6-6.0.1.tar.gz/zuper-auth-z6-6.0.1/src/zuper_auth/interpret.py | interpret.py |
from dataclasses import dataclass
from typing import Callable, Iterator, List, Optional, Tuple
class Statement:
def to_line(self) -> str:
''' Returns the line that can be parsed to this statement. '''
return str(self)
class Storage:
parsing_functions = {}
def parse_function(f: Callable) -> Callable:
_, token = f.__name__.split('_', maxsplit=1)
Storage.parsing_functions[token] = f
return f
@dataclass
class NewOType(Statement):
type_name: str
title: Optional[str] = None
@dataclass
class Comment(Statement):
line: str
@parse_function
def parse_REM(rest: str) -> Tuple[Statement, str]:
return Comment(rest), ''
@dataclass
class ShowState(Statement):
pass
@parse_function
def parse_SHOW_STATE(rest: str) -> Tuple[Statement, str]:
return ShowState(), ''
@parse_function
def parse_TYPE(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
return NewOType(type_name=type_name), rest
@dataclass
class NewAbility(Statement):
'ABILITY domain domain-create-organization '
type_name: str
ability_name: str
title: Optional[str] = None
@parse_function
def parse_ABILITY(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
ability_name, rest = get_one_token(rest)
return NewAbility(type_name=type_name, ability_name=ability_name), rest
@dataclass
class NewParentRelation(Statement):
"PARENT type_name parent_name"
type_name: str
parent_name: str
compulsory: bool
@parse_function
def parse_PARENT(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
parent_name, rest = get_one_token(rest)
return NewParentRelation(type_name=type_name, parent_name=parent_name, compulsory=False), rest
@dataclass
class NewProperty(Statement):
''' PROPERTY type_name name title '''
type_name: str
property_name: str
title: Optional[str] = None
@parse_function
def parse_PROPERTY(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
property_name, rest = get_one_token(rest)
return NewProperty(type_name=type_name, property_name=property_name), rest
@dataclass
class SetProperty(Statement):
''' FOR <> SET property_name IN <> '''
resource_match: 'ResourceMatch'
property_name: str
context: 'ResourceMatch'
@parse_function
def parse_FOR(rest0: str) -> Tuple[Statement, str]:
resource_match, rest = parse_resource_match(rest0)
rest = skip_one_token('SET', rest)
property_name, rest = get_one_token(rest)
if rest:
rest = skip_one_token('IN', rest)
context, rest = parse_resource_match(rest)
else:
context = ByPattern('*', '*')
return SetProperty(resource_match, property_name, context), rest
@dataclass
class NewRelation(Statement):
relation_name: str
types: List[str]
@dataclass
class NewObject(Statement):
''' NEW challenge 12 aido-admin aido-admin '''
type_name: str
identifiers: List[str]
@parse_function
def parse_NEW(rest0: str) -> Tuple[NewObject, str]:
type_name, rest = parse_until(' ', rest0)
identifiers = rest.split(' ')
return NewObject(type_name, identifiers), ''
class ResourceMatch:
pass
@dataclass
class SingleResourceMatch(ResourceMatch):
type_name: str
identifier: str
def __post_init__(self):
if '*' in self.identifier:
msg = 'Expected a single resource, not a pattern here.'
raise ValueError(msg)
# class ByIdentifier(ResourceMatch):
# ''' challenge:12 '''
# type_name: str
# identifier: str
#
@dataclass
class ByPattern(ResourceMatch):
''' challenge:aido* '''
type_name: str
pattern: str
def __post_init__(self):
if not self.type_name or not self.pattern:
raise ValueError(self)
@dataclass
class HasAttributes(ResourceMatch):
attributes: List[str]
@dataclass
class AndMatch(ResourceMatch):
ops: List[ResourceMatch]
def parse_single_resource_match(rest0) -> Tuple[SingleResourceMatch, str]:
type_name, rest = parse_until(':', rest0, required=True)
identifier, rest = parse_until(' ', rest)
return SingleResourceMatch(type_name=type_name, identifier=identifier), rest
def parse_resource_match(rest0: str) -> Tuple[ResourceMatch, str]:
if not rest0:
raise ValueError(rest0)
type_name, rest = parse_until(':', rest0, required=True)
pattern, rest = parse_until(' ', rest)
if '*' in type_name or '*' in pattern:
bp = ByPattern(type_name, pattern)
else:
bp = SingleResourceMatch(type_name, pattern)
if rest.startswith('['):
n = rest.index(']')
interesting = rest[1:n]
attributes = interesting.strip().split()
rest = rest[n + 1:]
bp = AndMatch([HasAttributes(attributes), bp])
try:
return bp, rest
except ValueError as e:
msg = f'Cannot parse resource match {rest0!r}'
raise ValueError(msg) from e
@dataclass
class SetChildParentRelation(Statement):
''' SUB group:one organization:aido '''
child_match: ResourceMatch
parent_match: ResourceMatch
@parse_function
def parse_SUB(rest0) -> Tuple[Statement, str]:
child_match, rest = parse_resource_match(rest0)
parent_match, rest = parse_resource_match(rest)
return SetChildParentRelation(child_match, parent_match), rest
"""
SUB challenge:* domain:1
ALLOW <name> TO <Ability> IN <context> IF challenge-owner
"""
class Query0(Statement):
pass
@dataclass
class QueryIS(Query0):
''' IS <res> ALLOWED ability IN <context> '''
user: 'SingleResourceMatch'
ability: str
context: 'SingleResourceMatch'
@parse_function
def parse_IS(rest0) -> Tuple[QueryIS, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('ALLOWED', rest)
ability, rest = get_one_token(rest)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryIS(user, ability, context), rest
@dataclass
class QueryHAS(Query0):
''' HAS <res> PROPERTY ability IN <context> '''
user: 'SingleResourceMatch'
property: str
context: 'SingleResourceMatch'
@parse_function
def parse_HAS(rest0) -> Tuple[QueryHAS, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('PROPERTY', rest)
property, rest = get_one_token(rest)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryHAS(user, property, context), rest
@dataclass
class QueryGetProperties(Query0):
''' PROPERTIES <r> IN <context> '''
user: 'SingleResourceMatch'
context: 'SingleResourceMatch'
@parse_function
def parse_PROPERTIES(rest0) -> Tuple[QueryGetProperties, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryGetProperties(user, context), rest
class AbilityMatch:
pass
@dataclass
class AbilityMatchByPattern(AbilityMatch):
pattern: str
def __post_init__(self):
if ':' in self.pattern:
raise ValueError(self)
def parse_ability_match(rest) -> Tuple[AbilityMatch, str]:
pattern, rest = get_one_token(rest)
return AbilityMatchByPattern(pattern), rest
class ConditionMatch:
pass
@dataclass
class AttributeMatch(ConditionMatch):
pattern: str
def __post_init__(self):
if ':' in self.pattern:
raise ValueError(self)
def parse_condition_match(rest) -> Tuple[ConditionMatch, str]:
pattern, rest = get_one_token(rest)
return AttributeMatch(pattern), rest
class Always(ConditionMatch):
pass
@dataclass
class Allow(Statement):
''' ALLOW <user match> TO <ability match> IN <resource match> [IF <condition match>] '''
user_match: ResourceMatch
ability_match: AbilityMatch
context_match: ResourceMatch
condition: ConditionMatch
@parse_function
def parse_ALLOW(rest0) -> Tuple[Allow, str]:
user_match, rest = parse_resource_match(rest0)
rest = skip_one_token('TO', rest)
ability_match, rest = parse_ability_match(rest)
rest = skip_one_token('IN', rest)
context_match, rest = parse_resource_match(rest)
if rest:
rest = skip_one_token('IF', rest)
condition_match, rest = parse_condition_match(rest)
else:
condition_match = Always()
return Allow(user_match, ability_match, context_match, condition_match), rest
def remove_comment(line: str) -> str:
try:
i = line.index('#')
except:
return line
else:
return line[:i]
def parse_string(s) -> Iterator[Tuple[str, Statement]]:
s = s.strip()
lines = s.split('\n')
lines = [remove_comment(_) for _ in lines]
lines = [_.strip() for _ in lines]
lines = [_ for _ in lines if _]
for line in lines:
token, rest = get_one_token(line)
functions = Storage.parsing_functions
if token not in functions:
raise NotImplementedError((token, line))
f = functions[token]
try:
statement, rest = f(rest)
except ValueError as e:
msg = f'Cannot parse line {line!r}.'
raise ValueError(msg) from e
yield line, statement
def get_one_token(line: str):
line = line.lstrip()
return parse_until(' ', line)
def skip_one_token(expect: str, line: str):
token, rest = get_one_token(line)
if expect != token:
msg = f'Expected {expect!r} at the beginning of {line!r}.'
raise ValueError(msg)
return rest
def parse_until(sep: str, rest: str, required=False) -> Tuple[str, str]:
rest = rest.lstrip()
if not sep in rest:
if required:
msg = f'Could not find separator {sep!r} in {rest!r}.'
raise ValueError(msg)
return rest, ''
# msg = f'Cannot find separator {sep!r} in {rest!r}.'
# raise ValueError(msg)
tokens = rest.split(sep, maxsplit=1)
return tokens[0], tokens[1] | zuper-auth-z6 | /zuper-auth-z6-6.0.1.tar.gz/zuper-auth-z6-6.0.1/src/zuper_auth/parsing.py | parsing.py |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import *
from zuper_commons.text.zc_wildcards import wildcard_to_regexp
from zuper_typing import debug_print
from .parsing import (AbilityMatch, AbilityMatchByPattern, Allow, Always, AndMatch, AttributeMatch, ByPattern, Comment,
ConditionMatch, HasAttributes, NewAbility, NewObject, NewOType, NewParentRelation, NewProperty,
parse_string, QueryGetProperties, QueryHAS, QueryIS, ResourceMatch, SetChildParentRelation,
SetProperty, ShowState, SingleResourceMatch, Statement)
@dataclass
class Object:
main_name: str
others: List[str]
type_name: str
parents: Dict[str, 'Object'] = field(default_factory=dict)
children: Dict[str, 'Object'] = field(default_factory=dict)
properties: Dict[str, List[ResourceMatch]] = field(default_factory=lambda: defaultdict(list))
@dataclass
class OType:
t_parents: Dict[str, bool] = field(default_factory=dict)
t_abilities: Dict[str, str] = field(default_factory=dict)
t_objects: Dict[str, Object] = field(default_factory=dict)
t_aliases: Dict[str, Object] = field(default_factory=dict)
t_properties: Dict[str, str] = field(default_factory=dict)
class AuthException(Exception):
pass
class Invalid(AuthException):
pass
class CouldNotFindResource(AuthException):
pass
@dataclass
class QResult:
ok: bool
line: str
query_result: Any
msg: Optional[str]
@dataclass
class Interpreter:
types: Dict[str, OType] = field(default_factory=dict)
allows: List[Allow] = field(default_factory=list)
statements_history: List[Statement] = field(default_factory=list)
results: List[QResult] = field(default_factory=list)
results_history: List[QResult] = field(default_factory=list)
last_line: str = None
functions: Dict[str, Callable] = field(default_factory=dict)
child_parent_relations: List[SetChildParentRelation] = field(default_factory=list)
# def __post_init__(self):
# # self.types = {}
# # self.allows = []
# # self.statements_history = []
# # self.results = []
# # self.results_history = []
# self.last_line = None
#
# self.functions = {}
def info(self) -> str:
s = []
for k, v in self.types.items():
s.append(k)
s.append(debug_print(v.t_objects))
return "\n".join(s)
def knows(self, type_name: str, object_identifier: str):
t = self._get_type(type_name)
return object_identifier in t.t_objects
def interpret(self, line: str, statement: Statement) -> QResult:
self.last_line = line
self.statements_history.append(statement)
t = type(statement).__name__
if t in self.functions:
ff = self.functions[t]
else:
f = f'interpret_{t}'
if not hasattr(self, f):
msg = f'Cannot find {f}'
raise NotImplementedError(msg)
ff = getattr(self, f)
self.functions[t] = ff
try:
r = ff(statement)
assert isinstance(r, QResult), statement
return r
except AuthException as e:
return self._mark_failure(str(e))
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as e:
msg = f'Cannot intepret statement {statement}'
raise ValueError(msg) from e
def _mark_ok(self, msg=None) -> QResult:
qr = QResult(ok=True, msg=msg, line=self.last_line, query_result=None)
self.results.append(qr)
self.results_history.append(qr)
return qr
def _mark_failure(self, msg) -> QResult:
qr = QResult(ok=False, msg=msg, line=self.last_line, query_result=None)
self.results.append(qr)
self.results_history.append(qr)
return qr
def _mark_query_result(self, res, msg=None) -> QResult:
qr = QResult(ok=True, msg=msg, line=self.last_line, query_result=res)
self.results.append(qr)
self.results_history.append(qr)
return qr
# def get_results(self) -> List[QResult]:
# """ Returns the last results and drops them. """
# r = self.results
# self.results = []
# return r
# def get_results_log_errors(self):
# for r in self.get_results():
# if not r.ok:
# logger.error(r)
def _get_type(self, type_name):
if type_name not in self.types:
msg = f'Could not find type {type_name!r}'
raise Invalid(msg)
return self.types[type_name]
def interpret_NewOType(self, s: NewOType) -> QResult:
if s.type_name in self.types:
msg = f'Already know find type {s.type_name!r}'
raise Invalid(msg)
self.types[s.type_name] = OType()
return self._mark_ok()
def interpret_NewParentRelation(self, s: NewParentRelation) -> QResult:
t = self._get_type(s.type_name)
if s.parent_name in t.t_parents:
msg = f'Already set relationship.'
raise Invalid(msg)
t.t_parents[s.parent_name] = s.compulsory
return self._mark_ok()
def interpret_Comment(self, s: Comment) -> QResult:
return self._mark_ok(s.line)
def interpret_ShowState(self, s: ShowState) -> QResult:
m = self.info()
return self._mark_ok(m)
def interpret_NewAbility(self, s: NewAbility) -> QResult:
t = self._get_type(s.type_name)
if s.ability_name in t.t_abilities:
msg = f'Already set ability {s.ability_name!r}.'
raise Invalid(msg)
t.t_abilities[s.ability_name] = s.title
return self._mark_ok()
def interpret_NewObject(self, s: NewObject) -> QResult:
t = self._get_type(s.type_name)
main_name = s.identifiers[0]
others = s.identifiers[1:]
if main_name in t.t_objects:
msg = f'Already know object {main_name!r}.'
raise Invalid(msg)
t.t_objects[main_name] = ob = Object(main_name=main_name, others=others, type_name=s.type_name)
for alias in others:
if alias in t.t_aliases:
msg = f'Already know alias {alias!r}.'
raise Invalid(msg)
t.t_aliases[alias] = ob
for scp in self.child_parent_relations:
if self.object_matches(ob, scp.child_match):
for parent in self.get_resources(scp.parent_match):
self.set_relationship(ob, parent)
if self.object_matches(ob, scp.parent_match):
for child in self.get_resources(scp.child_match):
self.set_relationship(child, ob)
return self._mark_ok()
def set_relationship(self, child: Object, parent: Object):
p = list(get_parents_and_self(parent))
if child in p:
msg = f'Cannot set parent-relation because child is a parent of parent.' \
f'\nParent: {parent}' \
f'\nChild: {child}'
raise Invalid(msg)
child.parents[parent.main_name] = parent
parent.children[child.main_name] = child
def interpret_SetChildParentRelation(self, s: SetChildParentRelation) -> QResult:
for parent in self.get_resources(s.parent_match):
for child in self.get_resources(s.child_match):
self.set_relationship(child, parent)
# make sure no recursion
# p = list(get_parents_and_self(parent))
# if child in p:
# msg = f'Cannot set parent-relation because child is a parent of parent.' \
# f'\nParent: {parent}' \
# f'\nChild: {child}' \
# f'\ns: {s}'
# raise Invalid(msg)
#
# child.parents[parent.main_name] = parent
# parent.children[child.main_name] = child
self.child_parent_relations.append(s)
return self._mark_ok()
def interpret_NewProperty(self, s: NewProperty) -> QResult:
t = self._get_type(s.type_name)
if s.property_name in t.t_properties:
msg = f'Already set property {s.property_name!r}.'
raise Invalid(msg)
t.t_properties[s.property_name] = s.title
return self._mark_ok()
def interpret_SetProperty(self, s: SetProperty) -> QResult:
for r in self.get_resources(s.resource_match):
t = self.types[r.type_name]
if s.property_name not in t.t_properties:
msg = f'Cannot set property {s.property_name!r} for object {r.main_name!r} of type {r.type_name!r}.'
raise Invalid(msg)
r.properties[s.property_name].append(s.context)
return self._mark_ok()
def interpret_Allow(self, s: Allow) -> QResult:
self.allows.append(s)
return self._mark_ok()
def object_matches(self, ob: Object, rm: ResourceMatch):
if isinstance(rm, ByPattern):
if (ob.type_name != rm.type_name):
return False
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
return True
return False
elif isinstance(rm, SingleResourceMatch):
if (ob.type_name != rm.type_name):
return False
return rm.identifier in [ob.main_name] + ob.others
else:
raise NotImplementedError(rm)
def get_resources(self, rm: ResourceMatch) -> Iterator[Object]:
if isinstance(rm, ByPattern):
t = self._get_type(rm.type_name)
for obname, ob in list(t.t_objects.items()):
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
yield ob
elif isinstance(rm, SingleResourceMatch):
t = self._get_type(rm.type_name)
if rm.identifier in t.t_objects:
yield t.t_objects[rm.identifier]
elif rm.identifier in t.t_aliases:
yield t.t_aliases[rm.identifier]
else:
raise NotImplementedError(rm)
def get_resource(self, rm: SingleResourceMatch) -> Object:
t = self.types[rm.type_name]
for obname, ob in list(t.t_objects.items()):
for identifier in [ob.main_name] + ob.others:
if rm.identifier == identifier:
return ob
msg = f'Could not find resource corresponding to {rm}'
raise CouldNotFindResource(msg)
def interpret_QueryIS(self, query: QueryIS) -> QResult:
# logger.debug(f'query {query}')
user = self.get_resource(query.user)
context = self.get_resource(query.context)
t = self._get_type(context.type_name)
ability = query.ability
if not ability in t.t_abilities:
msg = f'Unknown ability {ability!r} for object of type {context.type_name!r}.'
msg += f'\nKnown: {",".join(t.t_abilities)}.'
raise Invalid(msg)
properties = get_active_properties(user, context)
# logger.info('properties: %s' % properties)
context_parents = list(get_parents_and_self(context))
user_parents = list(get_parents_and_self(user))
msg = 'Active properties: %s' % properties
msg += f'\nuser hierarchy:'
for p in user_parents:
msg += f'\n - {p.type_name} : {p.main_name}'
msg += f'\nresource hierarchy: '
for p in context_parents:
msg += f'\n - {p.type_name} : {p.main_name}'
for allow in self.allows:
c1 = any(rmatch(allow.user_match, _) for _ in user_parents)
c2 = amatch(allow.ability_match, ability)
c3 = any(rmatch(allow.context_match, _) for _ in context_parents)
c4 = cmatch(allow.condition, properties)
ok = c1 and c2 and c3 and c4
if ok:
return self._mark_query_result(True)
else:
pass
msg += f'\nfalse (user match {c1}, amatch {c2}, context match {c3}, condition match{c4})\n for {allow}'
return self._mark_query_result(False, msg)
def interpret_QueryHAS(self, query: QueryHAS) -> QResult:
# logger.debug(f'query {query}')
user = self.get_resource(query.user)
context = self.get_resource(query.context)
properties = get_active_properties(user, context)
# logger.debug('properties: %s' % properties)
res = query.property in properties
return self._mark_query_result(res)
def interpret_QueryGetProperties(self, query: QueryGetProperties) -> QResult:
user = self.get_resource(query.user)
context = self.get_resource(query.context)
properties = get_active_properties(user, context)
return self._mark_query_result(properties)
def parse_and_interpret(self, src: str) -> List[QResult]:
res = []
for line, statement in parse_string(src):
r = self.interpret(line, statement)
assert isinstance(r, QResult), line
res.append(r)
return res
def get_history(self) -> str:
res = []
for s in reversed(self.results_history):
res.append(str(s))
return "\n".join(res)
def amatch(am: AbilityMatch, ability):
if isinstance(am, AbilityMatchByPattern):
if pattern_matches(am.pattern, ability):
return True
return False
else:
raise NotImplementedError(am)
def cmatch(cm: ConditionMatch, properties: Dict[str, bool]):
if isinstance(cm, Always):
return True
if isinstance(cm, AttributeMatch):
for p, v in properties.items():
if v and pattern_matches(cm.pattern, p):
return True
return False
raise NotImplementedError(cm)
def get_active_properties(user: Object, context: Object):
user_parents = list(get_parents_and_self(user))
context_parents = list(get_parents_and_self(context))
properties = {}
# Now set the properties
for cp in context_parents:
for up in user_parents:
for pname, matches in up.properties.items():
for match in matches:
if rmatch(match, cp):
properties[pname] = True
return properties
def get_parents_and_self(ob: Object) -> Iterator[Object]:
for parent in ob.parents.values():
yield from get_parents_and_self(parent)
yield ob
def rmatch(rm: ResourceMatch, ob: Object):
if isinstance(rm, ByPattern):
if rm.type_name != ob.type_name:
return False
for identifier in [ob.main_name] + ob.others:
if pattern_matches(rm.pattern, identifier):
return True
return False
if isinstance(rm, SingleResourceMatch):
if rm.type_name != ob.type_name:
return False
if rm.identifier == ob.main_name:
return True
if rm.identifier in ob.others:
return True
return False
elif isinstance(rm, AndMatch):
matches = (rmatch(_, ob) for _ in rm.ops)
return all(matches)
elif isinstance(rm, HasAttributes):
# XXX
matches = (_ in ob.properties for _ in rm.attributes)
return all(matches)
else:
raise NotImplementedError(rm)
def pattern_matches(pattern, identifier):
regexp = wildcard_to_regexp(pattern)
return regexp.match(identifier) | zuper-auth | /zuper-auth-2.0.1.tar.gz/zuper-auth-2.0.1/src/zuper_auth/interpret.py | interpret.py |
from dataclasses import dataclass
from typing import Callable, Iterator, List, Optional, Tuple
class Statement:
def to_line(self) -> str:
''' Returns the line that can be parsed to this statement. '''
return str(self)
class Storage:
parsing_functions = {}
def parse_function(f: Callable) -> Callable:
_, token = f.__name__.split('_', maxsplit=1)
Storage.parsing_functions[token] = f
return f
@dataclass
class NewOType(Statement):
type_name: str
title: Optional[str] = None
@dataclass
class Comment(Statement):
line: str
@parse_function
def parse_REM(rest: str) -> Tuple[Statement, str]:
return Comment(rest), ''
@dataclass
class ShowState(Statement):
pass
@parse_function
def parse_SHOW_STATE(rest: str) -> Tuple[Statement, str]:
return ShowState(), ''
@parse_function
def parse_TYPE(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
return NewOType(type_name=type_name), rest
@dataclass
class NewAbility(Statement):
'ABILITY domain domain-create-organization '
type_name: str
ability_name: str
title: Optional[str] = None
@parse_function
def parse_ABILITY(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
ability_name, rest = get_one_token(rest)
return NewAbility(type_name=type_name, ability_name=ability_name), rest
@dataclass
class NewParentRelation(Statement):
"PARENT type_name parent_name"
type_name: str
parent_name: str
compulsory: bool
@parse_function
def parse_PARENT(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
parent_name, rest = get_one_token(rest)
return NewParentRelation(type_name=type_name, parent_name=parent_name, compulsory=False), rest
@dataclass
class NewProperty(Statement):
''' PROPERTY type_name name title '''
type_name: str
property_name: str
title: Optional[str] = None
@parse_function
def parse_PROPERTY(rest: str) -> Tuple[Statement, str]:
type_name, rest = get_one_token(rest)
property_name, rest = get_one_token(rest)
return NewProperty(type_name=type_name, property_name=property_name), rest
@dataclass
class SetProperty(Statement):
''' FOR <> SET property_name IN <> '''
resource_match: 'ResourceMatch'
property_name: str
context: 'ResourceMatch'
@parse_function
def parse_FOR(rest0: str) -> Tuple[Statement, str]:
resource_match, rest = parse_resource_match(rest0)
rest = skip_one_token('SET', rest)
property_name, rest = get_one_token(rest)
if rest:
rest = skip_one_token('IN', rest)
context, rest = parse_resource_match(rest)
else:
context = ByPattern('*', '*')
return SetProperty(resource_match, property_name, context), rest
@dataclass
class NewRelation(Statement):
relation_name: str
types: List[str]
@dataclass
class NewObject(Statement):
''' NEW challenge 12 aido-admin aido-admin '''
type_name: str
identifiers: List[str]
@parse_function
def parse_NEW(rest0: str) -> Tuple[NewObject, str]:
type_name, rest = parse_until(' ', rest0)
identifiers = rest.split(' ')
return NewObject(type_name, identifiers), ''
class ResourceMatch:
pass
@dataclass
class SingleResourceMatch(ResourceMatch):
type_name: str
identifier: str
def __post_init__(self):
if '*' in self.identifier:
msg = 'Expected a single resource, not a pattern here.'
raise ValueError(msg)
# class ByIdentifier(ResourceMatch):
# ''' challenge:12 '''
# type_name: str
# identifier: str
#
@dataclass
class ByPattern(ResourceMatch):
''' challenge:aido* '''
type_name: str
pattern: str
def __post_init__(self):
if not self.type_name or not self.pattern:
raise ValueError(self)
@dataclass
class HasAttributes(ResourceMatch):
attributes: List[str]
@dataclass
class AndMatch(ResourceMatch):
ops: List[ResourceMatch]
def parse_single_resource_match(rest0) -> Tuple[SingleResourceMatch, str]:
type_name, rest = parse_until(':', rest0, required=True)
identifier, rest = parse_until(' ', rest)
return SingleResourceMatch(type_name=type_name, identifier=identifier), rest
def parse_resource_match(rest0: str) -> Tuple[ResourceMatch, str]:
if not rest0:
raise ValueError(rest0)
type_name, rest = parse_until(':', rest0, required=True)
pattern, rest = parse_until(' ', rest)
if '*' in type_name or '*' in pattern:
bp = ByPattern(type_name, pattern)
else:
bp = SingleResourceMatch(type_name, pattern)
if rest.startswith('['):
n = rest.index(']')
interesting = rest[1:n]
attributes = interesting.strip().split()
rest = rest[n + 1:]
bp = AndMatch([HasAttributes(attributes), bp])
try:
return bp, rest
except ValueError as e:
msg = f'Cannot parse resource match {rest0!r}'
raise ValueError(msg) from e
@dataclass
class SetChildParentRelation(Statement):
''' SUB group:one organization:aido '''
child_match: ResourceMatch
parent_match: ResourceMatch
@parse_function
def parse_SUB(rest0) -> Tuple[Statement, str]:
child_match, rest = parse_resource_match(rest0)
parent_match, rest = parse_resource_match(rest)
return SetChildParentRelation(child_match, parent_match), rest
"""
SUB challenge:* domain:1
ALLOW <name> TO <Ability> IN <context> IF challenge-owner
"""
class Query0(Statement):
pass
@dataclass
class QueryIS(Query0):
''' IS <res> ALLOWED ability IN <context> '''
user: 'SingleResourceMatch'
ability: str
context: 'SingleResourceMatch'
@parse_function
def parse_IS(rest0) -> Tuple[QueryIS, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('ALLOWED', rest)
ability, rest = get_one_token(rest)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryIS(user, ability, context), rest
@dataclass
class QueryHAS(Query0):
''' HAS <res> PROPERTY ability IN <context> '''
user: 'SingleResourceMatch'
property: str
context: 'SingleResourceMatch'
@parse_function
def parse_HAS(rest0) -> Tuple[QueryHAS, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('PROPERTY', rest)
property, rest = get_one_token(rest)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryHAS(user, property, context), rest
@dataclass
class QueryGetProperties(Query0):
''' PROPERTIES <r> IN <context> '''
user: 'SingleResourceMatch'
context: 'SingleResourceMatch'
@parse_function
def parse_PROPERTIES(rest0) -> Tuple[QueryGetProperties, str]:
user, rest = parse_single_resource_match(rest0)
rest = skip_one_token('IN', rest)
context, rest = parse_single_resource_match(rest)
return QueryGetProperties(user, context), rest
class AbilityMatch:
pass
@dataclass
class AbilityMatchByPattern(AbilityMatch):
pattern: str
def __post_init__(self):
if ':' in self.pattern:
raise ValueError(self)
def parse_ability_match(rest) -> Tuple[AbilityMatch, str]:
pattern, rest = get_one_token(rest)
return AbilityMatchByPattern(pattern), rest
class ConditionMatch:
pass
@dataclass
class AttributeMatch(ConditionMatch):
pattern: str
def __post_init__(self):
if ':' in self.pattern:
raise ValueError(self)
def parse_condition_match(rest) -> Tuple[ConditionMatch, str]:
pattern, rest = get_one_token(rest)
return AttributeMatch(pattern), rest
class Always(ConditionMatch):
pass
@dataclass
class Allow(Statement):
''' ALLOW <user match> TO <ability match> IN <resource match> [IF <condition match>] '''
user_match: ResourceMatch
ability_match: AbilityMatch
context_match: ResourceMatch
condition: ConditionMatch
@parse_function
def parse_ALLOW(rest0) -> Tuple[Allow, str]:
user_match, rest = parse_resource_match(rest0)
rest = skip_one_token('TO', rest)
ability_match, rest = parse_ability_match(rest)
rest = skip_one_token('IN', rest)
context_match, rest = parse_resource_match(rest)
if rest:
rest = skip_one_token('IF', rest)
condition_match, rest = parse_condition_match(rest)
else:
condition_match = Always()
return Allow(user_match, ability_match, context_match, condition_match), rest
def remove_comment(line: str) -> str:
try:
i = line.index('#')
except:
return line
else:
return line[:i]
def parse_string(s) -> Iterator[Tuple[str, Statement]]:
s = s.strip()
lines = s.split('\n')
lines = [remove_comment(_) for _ in lines]
lines = [_.strip() for _ in lines]
lines = [_ for _ in lines if _]
for line in lines:
token, rest = get_one_token(line)
functions = Storage.parsing_functions
if token not in functions:
raise NotImplementedError((token, line))
f = functions[token]
try:
statement, rest = f(rest)
except ValueError as e:
msg = f'Cannot parse line {line!r}.'
raise ValueError(msg) from e
yield line, statement
def get_one_token(line: str):
line = line.lstrip()
return parse_until(' ', line)
def skip_one_token(expect: str, line: str):
token, rest = get_one_token(line)
if expect != token:
msg = f'Expected {expect!r} at the beginning of {line!r}.'
raise ValueError(msg)
return rest
def parse_until(sep: str, rest: str, required=False) -> Tuple[str, str]:
rest = rest.lstrip()
if not sep in rest:
if required:
msg = f'Could not find separator {sep!r} in {rest!r}.'
raise ValueError(msg)
return rest, ''
# msg = f'Cannot find separator {sep!r} in {rest!r}.'
# raise ValueError(msg)
tokens = rest.split(sep, maxsplit=1)
return tokens[0], tokens[1] | zuper-auth | /zuper-auth-2.0.1.tar.gz/zuper-auth-2.0.1/src/zuper_auth/parsing.py | parsing.py |
import pickle
import traceback
from io import BytesIO
from pickle import (
Pickler,
SETITEM,
MARK,
SETITEMS,
EMPTY_TUPLE,
TUPLE,
POP,
_tuplesize2code,
POP_MARK,
)
from zuper_commons.types.zc_describe_type import describe_type
from . import logger
__all__ = ["find_pickling_error"]
def find_pickling_error(obj: object, protocol=pickle.HIGHEST_PROTOCOL):
sio = BytesIO()
try:
pickle.dumps(obj)
except BaseException:
se1 = traceback.format_exc()
pickler = MyPickler(sio, protocol)
try:
pickler.dump(obj)
except Exception:
se2 = traceback.format_exc()
msg = pickler.get_stack_description()
msg += "\n --- Current exception----\n%s" % se1
msg += "\n --- Old exception----\n%s" % se2
return msg
else:
msg = "I could not find the exact pickling error."
raise Exception(msg)
else:
msg = (
"Strange! I could not reproduce the pickling error "
"for the object of class %s" % describe_type(obj)
)
logger.info(msg)
class MyPickler(Pickler):
def __init__(self, *args, **kargs):
Pickler.__init__(self, *args, **kargs)
self.stack = []
def save(self, obj):
desc = "object of type %s" % (describe_type(obj))
# , describe_value(obj, 100))
# self.stack.append(describe_value(obj, 120))
self.stack.append(desc)
Pickler.save(self, obj)
self.stack.pop()
def get_stack_description(self):
s = "Pickling error occurred at:\n"
for i, context in enumerate(self.stack):
s += " " * i + "- %s\n" % context
return s
def save_pair(self, k, v):
self.stack.append("key %r = object of type %s" % (k, describe_type(v)))
self.save(k)
self.save(v)
self.stack.pop()
def _batch_setitems(self, items):
# Helper to batch up SETITEMS sequences; proto >= 1 only
# save = self.save
write = self.write
if not self.bin:
for k, v in items:
self.stack.append("entry %s" % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEM)
return
r = list(range(self._BATCHSIZE))
while items is not None:
tmp = []
for _ in r:
try:
tmp.append(items.next())
except StopIteration:
items = None
break
n = len(tmp)
if n > 1:
write(MARK)
for k, v in tmp:
self.stack.append("entry %s" % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEMS)
elif n:
k, v = tmp[0]
self.stack.append("entry %s" % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEM)
# else tmp is empty, and we're done
def save_tuple(self, obj):
write = self.write
proto = self.proto
n = len(obj)
if n == 0:
if proto:
write(EMPTY_TUPLE)
else:
write(MARK + TUPLE)
return
save = self.save
memo = self.memo
if n <= 3 and proto >= 2:
for i, element in enumerate(obj):
self.stack.append("tuple element %s" % i)
save(element)
self.stack.pop()
# Subtle. Same as in the big comment below.
if id(obj) in memo:
get = self.get(memo[id(obj)][0])
write(POP * n + get)
else:
write(_tuplesize2code[n])
self.memoize(obj)
return
# proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
# has more than 3 elements.
write(MARK)
for i, element in enumerate(obj):
self.stack.append("tuple element %s" % i)
save(element)
self.stack.pop()
if id(obj) in memo:
# Subtle. d was not in memo when we entered save_tuple(), so
# the process of saving the tuple's elements must have saved
# the tuple itself: the tuple is recursive. The proper action
# now is to throw away everything we put on the stack, and
# simply GET the tuple (it's already constructed). This check
# could have been done in the "for element" loop instead, but
# recursive tuples are a rare thing.
get = self.get(memo[id(obj)][0])
if proto:
write(POP_MARK + get)
else: # proto 0 -- POP_MARK not available
write(POP * (n + 1) + get)
return
# No recursion.
self.write(TUPLE)
self.memoize(obj) | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/fs/zc_debug_pickler.py | zc_debug_pickler.py |
import fnmatch
import os
import time
from collections import defaultdict
from typing import List, Optional, Sequence, Union
from zuper_commons.types import check_isinstance
from . import logger
__all__ = ["locate_files"]
# @contract(returns='list(str)', directory='str',
# pattern='str|seq(str)', followlinks='bool')
def locate_files(
directory: str,
pattern: Union[str, Sequence[str]],
followlinks: bool = True,
include_directories: bool = False,
include_files: bool = True,
normalize: bool = True,
ignore_patterns: Optional[Sequence[str]] = None,
):
"""
pattern is either a string or a sequence of strings
NOTE: if you do not pass ignore_patterns, it will use MCDPConstants.locate_files_ignore_patterns
ignore_patterns = ['*.bak']
normalize = uses realpath
"""
t0 = time.time()
if ignore_patterns is None:
ignore_patterns = []
if isinstance(pattern, str):
patterns = [pattern]
else:
patterns = list(pattern)
for p in patterns:
check_isinstance(p, str)
# directories visited
# visited = set()
# visited_basename = set()
# print('locate_files %r %r' % (directory, pattern))
filenames = []
def matches_pattern(x):
return any(fnmatch.fnmatch(x, _) or (x == _) for _ in patterns)
def should_ignore_resource(x):
return any(fnmatch.fnmatch(x, _) or (x == _) for _ in ignore_patterns)
def accept_dirname_to_go_inside(_root_, d_):
if should_ignore_resource(d_):
return False
# XXX
# dd = os.path.realpath(os.path.join(root_, d_))
# if dd in visited:
# return False
# visited.add(dd)
return True
def accept_dirname_as_match(_):
return (
include_directories and not should_ignore_resource(_) and matches_pattern(_)
)
def accept_filename_as_match(_):
return include_files and not should_ignore_resource(_) and matches_pattern(_)
ntraversed = 0
for root, dirnames, files in os.walk(directory, followlinks=followlinks):
ntraversed += 1
dirnames[:] = [_ for _ in dirnames if accept_dirname_to_go_inside(root, _)]
for f in files:
# logger.info('look ' + root + '/' + f)
if accept_filename_as_match(f):
filename = os.path.join(root, f)
filenames.append(filename)
for d in dirnames:
if accept_dirname_as_match(d):
filename = os.path.join(root, d)
filenames.append(filename)
if normalize:
real2norm = defaultdict(lambda: [])
for norm in filenames:
real = os.path.realpath(norm)
real2norm[real].append(norm)
# print('%s -> %s' % (real, norm))
for k, v in real2norm.items():
if len(v) > 1:
msg = "In directory:\n\t%s\n" % directory
msg += "I found %d paths that refer to the same file:\n" % len(v)
for n in v:
msg += "\t%s\n" % n
msg += "refer to the same file:\n\t%s\n" % k
msg += "I will silently eliminate redundancies."
# logger.warning(msg) # XXX
filenames = list(real2norm.keys())
seconds = time.time() - t0
if seconds > 5:
n = len(filenames)
nuniques = len(set(filenames))
logger.debug(
"%.4f s for locate_files(%s,%s): %d traversed, found %d filenames (%d uniques)"
% (seconds, directory, pattern, ntraversed, n, nuniques)
)
return filenames | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/fs/zc_locate_files_imp.py | zc_locate_files_imp.py |
import gzip
import os
import random
from contextlib import contextmanager
__all__ = ["safe_write", "safe_read"]
from .types import Path
def is_gzip_filename(filename: Path) -> bool:
return ".gz" in filename
@contextmanager
def safe_write(filename: Path, mode: str = "wb", compresslevel: int = 5):
"""
Makes atomic writes by writing to a temp filename.
Also if the filename ends in ".gz", writes to a compressed stream.
Yields a file descriptor.
It is thread safe because it renames the file.
If there is an error, the file will be removed if it exists.
"""
dirname = os.path.dirname(filename)
if dirname:
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
pass
# Dont do this!
# if os.path.exists(filename):
# os.unlink(filename)
# assert not os.path.exists(filename)
#
n = random.randint(0, 10000)
tmp_filename = "%s.tmp.%s.%s" % (filename, os.getpid(), n)
try:
if is_gzip_filename(filename):
fopen = lambda fname, fmode: gzip.open(
filename=fname, mode=fmode, compresslevel=compresslevel
)
else:
fopen = open
with fopen(tmp_filename, mode) as f:
yield f
f.close()
# if os.path.exists(filename):
# msg = 'Race condition for writing to %r.' % filename
# raise Exception(msg)
#
# On Unix, if dst exists and is a file, it will be replaced silently
# if the user has permission.
os.rename(tmp_filename, filename)
except:
if os.path.exists(tmp_filename):
os.unlink(tmp_filename)
if os.path.exists(filename):
os.unlink(filename)
raise
@contextmanager
def safe_read(filename: Path, mode="rb"):
"""
If the filename ends in ".gz", reads from a compressed stream.
Yields a file descriptor.
"""
try:
if is_gzip_filename(filename):
f = gzip.open(filename, mode)
try:
yield f
finally:
f.close()
else:
with open(filename, mode) as f:
yield f
except:
# TODO
raise | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/fs/zc_safe_write.py | zc_safe_write.py |
import codecs
import os
from zuper_commons.types import check_isinstance
from . import logger
from .zc_friendly_path import friendly_path
from .zc_mkdirs import make_sure_dir_exists
from .zc_path_utils import expand_all
__all__ = [
"read_bytes_from_file",
"write_bytes_to_file",
"read_ustring_from_utf8_file",
"read_ustring_from_utf8_file_lenient",
"write_ustring_to_utf8_file",
]
from .types import Path
def read_bytes_from_file(filename: Path) -> bytes:
""" Read binary data and returns bytes """
_check_exists(filename)
with open(filename, "rb") as f:
return f.read()
def read_ustring_from_utf8_file(filename: Path) -> str:
""" Returns a unicode/proper string """
_check_exists(filename)
with codecs.open(filename, encoding="utf-8") as f:
try:
return f.read()
except UnicodeDecodeError as e:
msg = "Could not successfully decode file %s" % filename
raise UnicodeError(msg) from e
def read_ustring_from_utf8_file_lenient(filename: Path) -> str:
""" Ignores decoding errors """
_check_exists(filename)
with codecs.open(filename, encoding="utf-8", errors="ignore") as f:
try:
return f.read()
except UnicodeDecodeError as e:
msg = "Could not successfully decode file %s" % filename
raise UnicodeError(msg) from e
def _check_exists(filename: Path) -> None:
if not os.path.exists(filename):
if os.path.lexists(filename):
msg = "The link %s does not exist." % filename
msg += " it links to %s" % os.readlink(filename)
raise ValueError(msg)
else:
msg = "Could not find file %r" % filename
msg += " from directory %s" % os.getcwd()
raise ValueError(msg)
def write_ustring_to_utf8_file(data: str, filename: Path, quiet: bool=False) -> None:
"""
It also creates the directory if it does not exist.
:param data:
:param filename:
:param quiet:
:return:
"""
check_isinstance(data, str)
b = data.encode("utf-8") # OK
return write_bytes_to_file(b, filename, quiet=quiet)
def write_bytes_to_file(data: bytes, filename: Path, quiet: bool = False) -> None:
"""
Writes the data to the given filename.
If the data did not change, the file is not touched.
"""
check_isinstance(data, bytes)
L = len(filename)
if L > 1024:
msg = f"Invalid argument filename: too long at {L}. Did you confuse it with data?\n{filename[:1024]}"
raise ValueError(msg)
filename = expand_all(filename)
make_sure_dir_exists(filename)
if os.path.exists(filename):
current = open(filename, "rb").read()
if current == data:
if not "assets" in filename:
if not quiet:
logger.debug("already up to date %s" % friendly_path(filename))
return
with open(filename, "wb") as f:
f.write(data)
if filename.startswith("/tmp"):
quiet = True
if not quiet:
size = "%.1fMB" % (len(data) / (1024 * 1024))
logger.debug("Written %s to: %s" % (size, friendly_path(filename))) | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/fs/zc_fileutils.py | zc_fileutils.py |
import math
__all__ = ["duration_compact"]
def duration_compact(seconds: float) -> str:
seconds = int(math.ceil(seconds))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
years, days = divmod(days, 365)
minutes = int(minutes)
hours = int(hours)
days = int(days)
years = int(years)
duration = []
if years > 0:
duration.append("%dy" % years)
else:
if days > 0:
duration.append("%dd" % days)
if (days < 3) and (years == 0):
if hours > 0:
duration.append("%dh" % hours)
if (hours < 3) and (days == 0):
if minutes > 0:
duration.append("%dm" % minutes)
if (minutes < 3) and (hours == 0):
if seconds > 0:
duration.append("%ds" % seconds)
return " ".join(duration)
#
# def duration_human(seconds):
# ''' Code modified from
# http://darklaunch.com/2009/10/06
# /python-time-duration-human-friendly-timestamp
# '''
# seconds = int(math.ceil(seconds))
# minutes, seconds = divmod(seconds, 60)
# hours, minutes = divmod(minutes, 60)
# days, hours = divmod(hours, 24)
# years, days = divmod(days, 365.242199)
#
# minutes = int(minutes)
# hours = int(hours)
# days = int(days)
# years = int(years)
#
# duration = []
# if years > 0:
# duration.append('%d year' % years + 's' * (years != 1))
# else:
# if days > 0:
# duration.append('%d day' % days + 's' * (days != 1))
# if (days < 3) and (years == 0):
# if hours > 0:
# duration.append('%d hour' % hours + 's' * (hours != 1))
# if (hours < 3) and (days == 0):
# if minutes > 0:
# duration.append('%d min' % minutes +
# 's' * (minutes != 1))
# if (minutes < 3) and (hours == 0):
# if seconds > 0:
# duration.append('%d sec' % seconds +
# 's' * (seconds != 1))
#
# return ' '.join(duration) | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/ui/zc_duration_hum.py | zc_duration_hum.py |
import traceback
from zuper_commons.text import indent
__all__ = ["import_name"]
def import_name(name: str)->object:
"""
Loads the python object with the given name.
Note that "name" might be "module.module.name" as well.
"""
try:
return __import__(name, fromlist=["dummy"])
except ImportError:
# split in (module, name) if we can
if "." in name:
tokens = name.split(".")
field = tokens[-1]
module_name = ".".join(tokens[:-1])
if False: # previous method
pass
# try:
# module = __import__(module_name, fromlist=['dummy'])
# except ImportError as e:
# msg = ('Cannot load %r (tried also with %r):\n' %
# (name, module_name))
# msg += '\n' + indent(
# '%s\n%s' % (e, traceback.format_exc(e)), '> ')
# raise ValueError(msg)
#
# if not field in module.__dict__:
# msg = 'No field %r\n' % field
# msg += ' found in %r.' % module
# raise ValueError(msg)
#
# return module.__dict__[field]
else:
# other method, don't assume that in "M.x", "M" is a module.
# It could be a class as well, and "x" be a staticmethod.
try:
module = import_name(module_name)
except ImportError as e:
msg = "Cannot load %r (tried also with %r):\n" % (name, module_name)
msg += "\n" + indent("%s\n%s" % (e, traceback.format_exc()), "> ")
raise ValueError(msg)
if isinstance(module, type):
if hasattr(module, field):
return getattr(module, field)
else:
msg = f"No field {field!r}\n"
msg += f" found in type {module!r}."
raise KeyError(msg)
if not field in module.__dict__:
msg = f"No field {field!r}\n"
msg += f" found in module {module!r}."
raise KeyError(msg)
f = module.__dict__[field]
# "staticmethod" are not functions but descriptors, we need
# extra magic
if isinstance(f, staticmethod):
return f.__get__(module, None)
else:
return f
else:
msg = "Cannot import name %r." % name
msg += indent(traceback.format_exc(), "> ")
raise ValueError(msg) | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/types/zc_import.py | zc_import.py |
import logging
from typing import cast
import termcolor
__all__ = ["setup_logging_color", "setup_logging_format", "setup_logging"]
def get_FORMAT_datefmt():
pre = "%(asctime)s|%(name)s|%(filename)s:%(lineno)s|%(funcName)s(): "
pre = termcolor.colored(pre, attrs=["dark"])
FORMAT = pre + "%(message)s"
datefmt = "%H:%M:%S"
return FORMAT, datefmt
def setup_logging_format():
from logging import Logger, StreamHandler, Formatter
import logging
FORMAT, datefmt = get_FORMAT_datefmt()
logging.basicConfig(format=FORMAT, datefmt=datefmt)
# noinspection PyUnresolvedReferences
root = cast(Logger, Logger.root)
if root.handlers:
for handler in root.handlers:
if isinstance(handler, StreamHandler):
formatter = Formatter(FORMAT, datefmt=datefmt)
handler.setFormatter(formatter)
else:
logging.basicConfig(format=FORMAT, datefmt=datefmt)
def add_coloring_to_emit_ansi(fn):
# add methods we need to the class
def new(*args):
levelno = args[1].levelno
if levelno >= 50:
color = "\x1b[31m" # red
elif levelno >= 40:
color = "\x1b[31m" # red
elif levelno >= 30:
color = "\x1b[33m" # yellow
elif levelno >= 20:
color = "\x1b[32m" # green
elif levelno >= 10:
color = "\x1b[35m" # pink
else:
color = "\x1b[0m" # normal
msg = str(args[1].msg)
lines = msg.split("\n")
def color_line(l):
return "%s%s%s" % (color, l, "\x1b[0m") # normal
lines = list(map(color_line, lines))
args[1].msg = "\n".join(lines)
return fn(*args)
return new
def setup_logging_color()->None:
import platform
if platform.system() != "Windows":
emit2 = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
logging.StreamHandler.emit = emit2
def setup_logging() -> None:
# logging.basicConfig()
setup_logging_color()
setup_logging_format() | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/logs/col_logging.py | col_logging.py |
from dataclasses import dataclass
from typing import Optional, List, Tuple
import termcolor
from zuper_commons.text.coloring import get_length_on_screen
from zuper_commons.text.text_sidebyside import pad
@dataclass
class TextDimensions:
nlines: int
max_width: int
def text_dimensions(s: str):
lines = s.split("\n")
max_width = max(get_length_on_screen(_) for _ in lines)
return TextDimensions(nlines=len(lines), max_width=max_width)
#
# U+250x ─ ━ │ ┃ ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ┌ ┍ ┎ ┏
# U+251x ┐ ┑ ┒ ┓ └ ┕ ┖ ┗ ┘ ┙ ┚ ┛ ├ ┝ ┞ ┟
# U+252x ┠ ┡ ┢ ┣ ┤ ┥ ┦ ┧ ┨ ┩ ┪ ┫ ┬ ┭ ┮ ┯
# U+253x ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻ ┼ ┽ ┾ ┿
# U+254x ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╌ ╍ ╎ ╏
# U+255x ═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟
# U+256x ╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬ ╭ ╮ ╯
# U+257x ╰ ╱ ╲ ╳ ╴ ╵ ╶ ╷ ╸ ╹ ╺ ╻ ╼ ╽ ╾ ╿
boxes = {
"pipes": "╔ ═ ╗ ║ ╝ ═ ╚ ║ ╬ ╠ ╣ ╦ ╩ ═ ║ ┼ ╟ ╢ ╤ ╧ ─ │".split(),
"heavy": "┏ ━ ┓ ┃ ┛ ━ ┗ ┃ ╋ ┣ ┫ ┳ ┻ ━ ┃ ┼ ┠ ┨ ┯ ┷ ─ │".split(),
"light": "┌ ─ ┐ │ ┘ ─ └ │ ┼ ├ ┤ ┬ ┴ ─ │ ┼ ├ ┤ ┬ ┴ ─ │".split(),
"circo": "╭ ─ ╮ │ ╯ ─ ╰ │ ┼ ├ ┤ ┬ ┴ ─ │ ┼ ├ ┤ ┬ ┴ ─ │".split(),
}
boxes["spaces"] = [" "] * len(boxes["pipes"])
CORNERS = ["corner"]
NEIGH = ((0, 0, 0), (0, None, 0), (0, 0, 0))
def box(
s: str,
style="pipes",
neighs=NEIGH,
draw_borders: Tuple[int, int, int, int] = (1, 1, 1, 1),
light_inside=True,
color: Optional[str] = None,
attrs: Optional[List[str]] = None,
) -> str:
dims = text_dimensions(s)
padded = pad(s, dims.nlines, dims.max_width)
(tl_n, tc_n, tr_n), (ml_n, _, mr_n), (bl_n, bc_n, br_n) = neighs
S = boxes[style]
assert len(S) == 22, len(S)
tl, tc, tr, mr, br, bc, bl, ml, Pc, Pr, Pl, Pd, Pu, H, V, Pc_light, Pr_light, Pl_light, Pd_light, Pu_light, H_light, V_light = (
S
)
if light_inside:
Pc = Pc_light
Pu = Pu_light
Pd = Pd_light
Pr = Pr_light
Pl = Pl_light
H = H_light
V = V_light
tl_use = {
(0, 0, 0): tl,
(0, 0, 1): Pd,
(0, 1, 0): Pr,
(0, 1, 1): Pc, # XXX
(1, 0, 0): Pc, # XXX
(1, 0, 1): Pc, # XXX
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(tl_n, tc_n, ml_n)]
tr_use = {
(0, 0, 0): tr,
(0, 0, 1): Pd,
(0, 1, 0): Pc,
(0, 1, 1): Pc,
(1, 0, 0): Pl,
(1, 0, 1): Pc,
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(tc_n, tr_n, mr_n)]
br_use = {
(0, 0, 0): br,
(0, 0, 1): Pc,
(0, 1, 0): Pl,
(0, 1, 1): Pc,
(1, 0, 0): Pu,
(1, 0, 1): Pc,
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(mr_n, bc_n, br_n)]
bl_use = {
(0, 0, 0): bl,
(0, 0, 1): Pr,
(0, 1, 0): Pc,
(0, 1, 1): Pc,
(1, 0, 0): Pu,
(1, 0, 1): Pc,
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(ml_n, bl_n, bc_n)]
mr_use = {0: mr, 1: V}[mr_n]
ml_use = {0: ml, 1: V}[ml_n]
tc_use = {0: tc, 1: H}[tc_n]
bc_use = {0: bc, 1: H}[bc_n]
draw_top, draw_right, draw_bottom, draw_left = draw_borders
if not draw_right:
tr_use = ""
mr_use = ""
br_use = ""
if not draw_left:
tl_use = ""
ml_use = ""
bl_use = ""
top = tl_use + tc_use * dims.max_width + tr_use
bot = bl_use + bc_use * dims.max_width + br_use
def f(_):
return termcolor.colored(_, color=color, attrs=attrs)
top_col = f(top)
bot_col = f(bot)
mr_use_col = f(mr_use)
ml_use_col = f(ml_use)
new_lines = []
if draw_top:
new_lines.append(top_col)
for l in padded:
new_lines.append(ml_use_col + l + mr_use_col)
if draw_bottom:
new_lines.append(bot_col)
return "\n".join(new_lines)
# begin = termcolor.colored('║', 'yellow', attrs=['dark'])
# ending = termcolor.colored('║', 'yellow', attrs=['dark']) # ↵┋ | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/text/boxing.py | boxing.py |
import re
from typing import List, Union, Iterator, Sequence
__all__ = ["expand_string", "get_wildcard_matches", "wildcard_to_regexp"]
def flatten(seq: Iterator) -> List:
res = []
for l in seq:
res.extend(l)
return res
def expand_string(x: Union[str, Sequence[str]], options: Sequence[str]) -> List[str]:
if isinstance(x, list):
return flatten(expand_string(y, options) for y in x)
elif isinstance(x, str):
x = x.strip()
if "," in x:
splat = [_ for _ in x.split(",") if _] # remove empty
return flatten(expand_string(y, options) for y in splat)
elif "*" in x:
xx = expand_wildcard(x, options)
expanded = list(xx)
return expanded
else:
return [x]
else:
assert False
def wildcard_to_regexp(arg: str):
""" Returns a regular expression from a shell wildcard expression. """
return re.compile("\A" + arg.replace("*", ".*") + "\Z")
def has_wildcard(s: str) -> bool:
return s.find("*") > -1
def expand_wildcard(wildcard: str, universe: Sequence[str]) -> Sequence[str]:
"""
Expands a wildcard expression against the given list.
Raises ValueError if none found.
:param wildcard: string with '*'
:param universe: a list of strings
"""
if not has_wildcard(wildcard):
msg = "No wildcards in %r." % wildcard
raise ValueError(msg)
matches = list(get_wildcard_matches(wildcard, universe))
if not matches:
msg = "Could not find matches for pattern %r in %s." % (wildcard, universe)
raise ValueError(msg)
return matches
def get_wildcard_matches(wildcard: str, universe: Sequence[str]) -> Iterator[str]:
"""
Expands a wildcard expression against the given list.
Yields a sequence of strings.
:param wildcard: string with '*'
:param universe: a list of strings
"""
regexp = wildcard_to_regexp(wildcard)
for x in universe:
if regexp.match(x):
yield x | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/text/zc_wildcards.py | zc_wildcards.py |
import itertools
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
from zuper_commons.text.boxing import box, text_dimensions
from zuper_commons.text.text_sidebyside import pad, side_by_side
try:
from typing import Literal
HAlign = Literal["left", "center", "right", "inherit"]
VAlign = Literal["top", "middle", "bottom", "inherit"]
except:
HAlign = VAlign = str
@dataclass
class Style:
halign: HAlign = "inherit"
valign: VAlign = "inherit"
def format_table(
cells: Dict[Tuple[int, int], str],
*,
draw_grid_v: bool = True,
draw_grid_h: bool = True,
style: str = "pipes",
light_inside: bool = True,
color: Optional[str] = None,
attrs: Optional[List[str]] = None,
col_style: Dict[int, Style] = None,
row_style: Dict[int, Style] = None,
cell_style: Dict[Tuple[int, int], Style] = None,
) -> str:
col_styles = col_style or {}
row_styles = row_style or {}
cell_styles = cell_style or {}
def get_row_style(row):
return row_styles.get(row, Style())
def get_col_style(col):
return col_styles.get(col, Style())
def get_cell_style(cell):
return cell_styles.get(cell, Style())
def resolve(a: List[str]) -> str:
cur = a[0]
for s in a:
if s == "inherit":
continue
else:
cur = s
return cur
def get_style(cell: Tuple[int, int]) -> Style:
row, col = cell
rows = get_row_style(row)
cols = get_col_style(col)
cels = get_cell_style(cell)
halign = resolve(["left", rows.halign, cols.halign, cels.halign])
valign = resolve(["top", rows.valign, cols.valign, cels.valign])
return Style(halign=halign, valign=valign)
cells = dict(cells)
# find all mentioned cells
mentioned_js = set()
mentioned_is = set()
for i, j in cells:
mentioned_is.add(i)
mentioned_js.add(j)
# add default = '' for missing cells
nrows = max(mentioned_is) + 1
ncols = max(mentioned_js) + 1
coords = list(itertools.product(range(nrows), range(ncols)))
for c in coords:
if c not in cells:
cells[c] = ""
# find max size for cells
row_heights = [0] * nrows
col_widths = [0] * ncols
for (i, j), s in list(cells.items()):
dims = text_dimensions(s)
col_widths[j] = max(col_widths[j], dims.max_width)
row_heights[i] = max(row_heights[i], dims.nlines)
# pad all cells
for (i, j), s in list(cells.items()):
linelength = col_widths[j]
nlines = row_heights[i]
cell_style = get_style((i, j))
padded = do_padding(
s,
linelength=linelength,
nlines=nlines,
halign=cell_style.halign,
valign=cell_style.valign,
)
ibef = int(i > 0)
iaft = int(i < nrows - 1)
jbef = int(j > 0)
jaft = int(j < ncols - 1)
neighs = (
(ibef * jbef, ibef, ibef * jaft),
(jbef, None, jaft),
(iaft * jbef, iaft, iaft * jaft),
)
draw_top = 1
draw_left = 1
draw_right = jaft == 0
draw_bottom = iaft == 0
if not draw_grid_v:
draw_bottom = draw_top = 0
if not draw_grid_h:
draw_left = draw_right = 0
d = draw_top, draw_right, draw_bottom, draw_left
s = box(
padded,
neighs=neighs,
style=style,
draw_borders=d,
light_inside=light_inside,
color=color,
attrs=attrs,
)
cells[(i, j)] = s
parts = []
for i in range(nrows):
ss = []
for j in range(ncols):
ss.append(cells[(i, j)])
s = side_by_side(ss, sep="")
parts.append(s)
whole = "\n".join(parts)
# res = box(whole, style=style)
return whole
def do_padding(
s: str, linelength: int, nlines: int, halign: HAlign, valign: VAlign
) -> str:
padded_lines = pad(
s, linelength=linelength, nlines=nlines, halign=halign, valign=valign
)
padded = "\n".join(padded_lines)
return padded | zuper-commons-z5 | /zuper-commons-z5-5.0.11.tar.gz/zuper-commons-z5-5.0.11/src/zuper_commons/text/table.py | table.py |
import pickle
import traceback
from io import BytesIO
from pickle import (
Pickler,
SETITEM,
MARK,
SETITEMS,
EMPTY_TUPLE,
TUPLE,
POP,
_tuplesize2code,
POP_MARK,
)
from zuper_commons.types.zc_describe_type import describe_type
from . import logger
__all__ = ["find_pickling_error"]
def find_pickling_error(obj: object, protocol=pickle.HIGHEST_PROTOCOL):
sio = BytesIO()
try:
pickle.dumps(obj)
except BaseException:
se1 = traceback.format_exc()
pickler = MyPickler(sio, protocol)
try:
pickler.dump(obj)
except Exception:
se2 = traceback.format_exc()
msg = pickler.get_stack_description()
msg += "\n --- Current exception----\n%s" % se1
msg += "\n --- Old exception----\n%s" % se2
return msg
else:
msg = "I could not find the exact pickling error."
raise Exception(msg)
else:
msg = (
"Strange! I could not reproduce the pickling error "
"for the object of class %s" % describe_type(obj)
)
logger.info(msg)
class MyPickler(Pickler):
def __init__(self, *args, **kargs):
Pickler.__init__(self, *args, **kargs)
self.stack = []
def save(self, obj):
desc = "object of type %s" % (describe_type(obj))
# , describe_value(obj, 100))
# self.stack.append(describe_value(obj, 120))
self.stack.append(desc)
Pickler.save(self, obj)
self.stack.pop()
def get_stack_description(self):
s = "Pickling error occurred at:\n"
for i, context in enumerate(self.stack):
s += " " * i + "- %s\n" % context
return s
def save_pair(self, k, v):
self.stack.append("key %r = object of type %s" % (k, describe_type(v)))
self.save(k)
self.save(v)
self.stack.pop()
def _batch_setitems(self, items):
# Helper to batch up SETITEMS sequences; proto >= 1 only
# save = self.save
write = self.write
if not self.bin:
for k, v in items:
self.stack.append("entry %s" % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEM)
return
r = list(range(self._BATCHSIZE))
while items is not None:
tmp = []
for _ in r:
try:
tmp.append(items.next())
except StopIteration:
items = None
break
n = len(tmp)
if n > 1:
write(MARK)
for k, v in tmp:
self.stack.append("entry %s" % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEMS)
elif n:
k, v = tmp[0]
self.stack.append("entry %s" % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEM)
# else tmp is empty, and we're done
def save_tuple(self, obj):
write = self.write
proto = self.proto
n = len(obj)
if n == 0:
if proto:
write(EMPTY_TUPLE)
else:
write(MARK + TUPLE)
return
save = self.save
memo = self.memo
if n <= 3 and proto >= 2:
for i, element in enumerate(obj):
self.stack.append("tuple element %s" % i)
save(element)
self.stack.pop()
# Subtle. Same as in the big comment below.
if id(obj) in memo:
get = self.get(memo[id(obj)][0])
write(POP * n + get)
else:
write(_tuplesize2code[n])
self.memoize(obj)
return
# proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
# has more than 3 elements.
write(MARK)
for i, element in enumerate(obj):
self.stack.append("tuple element %s" % i)
save(element)
self.stack.pop()
if id(obj) in memo:
# Subtle. d was not in memo when we entered save_tuple(), so
# the process of saving the tuple's elements must have saved
# the tuple itself: the tuple is recursive. The proper action
# now is to throw away everything we put on the stack, and
# simply GET the tuple (it's already constructed). This check
# could have been done in the "for element" loop instead, but
# recursive tuples are a rare thing.
get = self.get(memo[id(obj)][0])
if proto:
write(POP_MARK + get)
else: # proto 0 -- POP_MARK not available
write(POP * (n + 1) + get)
return
# No recursion.
self.write(TUPLE)
self.memoize(obj) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/fs/zc_debug_pickler.py | zc_debug_pickler.py |
import fnmatch
import os
import time
from collections import defaultdict
from typing import List, Optional, Sequence, Union
from zuper_commons.types import check_isinstance
from . import logger
from .types import DirPath, FilePath
__all__ = ["locate_files"]
# @contract(returns='list(str)', directory='str',
# pattern='str|seq(str)', followlinks='bool')
def locate_files(
directory: DirPath,
pattern: Union[str, Sequence[str]],
followlinks: bool = True,
include_directories: bool = False,
include_files: bool = True,
normalize: bool = True,
ignore_patterns: Optional[Sequence[str]] = None,
) -> List[FilePath]:
if not os.path.exists(directory):
msg = f'Root directory does not exist: {directory}'
logger.warning(msg)
return []
# raise ValueError(msg)
"""
pattern is either a string or a sequence of strings
NOTE: if you do not pass ignore_patterns, it will use MCDPConstants.locate_files_ignore_patterns
ignore_patterns = ['*.bak']
normalize = uses realpath
"""
t0 = time.time()
if ignore_patterns is None:
ignore_patterns = []
if isinstance(pattern, str):
patterns = [pattern]
else:
patterns = list(pattern)
for p in patterns:
check_isinstance(p, str)
# directories visited
# visited = set()
# visited_basename = set()
# print('locate_files %r %r' % (directory, pattern))
filenames = []
def matches_pattern(x):
return any(fnmatch.fnmatch(x, _) or (x == _) for _ in patterns)
def should_ignore_resource(x):
return any(fnmatch.fnmatch(x, _) or (x == _) for _ in ignore_patterns)
def accept_dirname_to_go_inside(_root_, d_):
if should_ignore_resource(d_):
return False
# XXX
# dd = os.path.realpath(os.path.join(root_, d_))
# if dd in visited:
# return False
# visited.add(dd)
return True
def accept_dirname_as_match(_):
return include_directories and not should_ignore_resource(_) and matches_pattern(_)
def accept_filename_as_match(_):
return include_files and not should_ignore_resource(_) and matches_pattern(_)
ntraversed = 0
for root, dirnames, files in os.walk(directory, followlinks=followlinks):
ntraversed += 1
dirnames[:] = [_ for _ in dirnames if accept_dirname_to_go_inside(root, _)]
for f in files:
# logger.info('look ' + root + '/' + f)
if accept_filename_as_match(f):
filename = os.path.join(root, f)
filenames.append(filename)
for d in dirnames:
if accept_dirname_as_match(d):
filename = os.path.join(root, d)
filenames.append(filename)
if normalize:
real2norm = defaultdict(lambda: [])
for norm in filenames:
real = os.path.realpath(norm)
real2norm[real].append(norm)
# print('%s -> %s' % (real, norm))
for k, v in real2norm.items():
if len(v) > 1:
msg = f"In directory:\n\t{directory}\n"
msg += f"I found {len(v)} paths that refer to the same file:\n"
for n in v:
msg += f"\t{n}\n"
msg += f"refer to the same file:\n\t{k}\n"
msg += "I will silently eliminate redundancies."
# logger.warning(msg) # XXX
filenames = list(real2norm.keys())
seconds = time.time() - t0
if seconds > 5:
n = len(filenames)
nuniques = len(set(filenames))
msg = (
f"{seconds:.1f} s for locate_files({directory},{pattern}): {ntraversed} traversed, "
f"found {n} filenames ({nuniques} uniques)")
logger.debug(msg)
return filenames | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/fs/zc_locate_files_imp.py | zc_locate_files_imp.py |
import gzip
import os
import random
from contextlib import contextmanager
from .types import Path
__all__ = ["safe_write", "safe_read"]
def is_gzip_filename(filename: Path) -> bool:
return ".gz" in filename
@contextmanager
def safe_write(filename: Path, mode: str = "wb", compresslevel: int = 5):
"""
Makes atomic writes by writing to a temp filename.
Also if the filename ends in ".gz", writes to a compressed stream.
Yields a file descriptor.
It is thread safe because it renames the file.
If there is an error, the file will be removed if it exists.
"""
dirname = os.path.dirname(filename)
if dirname:
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
pass
# Dont do this!
# if os.path.exists(filename):
# os.unlink(filename)
# assert not os.path.exists(filename)
#
n = random.randint(0, 10000)
tmp_filename = "%s.tmp.%s.%s" % (filename, os.getpid(), n)
try:
if is_gzip_filename(filename):
fopen = lambda fname, fmode: gzip.open(filename=fname, mode=fmode, compresslevel=compresslevel)
else:
fopen = open
with fopen(tmp_filename, mode) as f:
yield f
f.close()
# if os.path.exists(filename):
# msg = 'Race condition for writing to %r.' % filename
# raise Exception(msg)
#
# On Unix, if dst exists and is a file, it will be replaced silently
# if the user has permission.
os.rename(tmp_filename, filename)
except:
if os.path.exists(tmp_filename):
os.unlink(tmp_filename)
if os.path.exists(filename):
os.unlink(filename)
raise
@contextmanager
def safe_read(filename: Path, mode="rb"):
"""
If the filename ends in ".gz", reads from a compressed stream.
Yields a file descriptor.
"""
try:
if is_gzip_filename(filename):
f = gzip.open(filename, mode)
try:
yield f
finally:
f.close()
else:
with open(filename, mode) as f:
yield f
except:
# TODO
raise | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/fs/zc_safe_write.py | zc_safe_write.py |
import codecs
import os
from typing import cast
from zuper_commons.types import check_isinstance
from . import logger
from .types import FilePath
from .zc_friendly_path import friendly_path
from .zc_mkdirs import make_sure_dir_exists
from .zc_path_utils import expand_all
__all__ = [
"read_bytes_from_file",
"write_bytes_to_file",
"read_ustring_from_utf8_file",
"read_ustring_from_utf8_file_lenient",
"write_ustring_to_utf8_file",
]
def read_bytes_from_file(filename: FilePath) -> bytes:
""" Read binary data and returns bytes """
_check_exists(filename)
with open(filename, "rb") as f:
return f.read()
def read_ustring_from_utf8_file(filename: FilePath) -> str:
""" Returns a unicode/proper string """
_check_exists(filename)
with codecs.open(filename, encoding="utf-8") as f:
try:
return f.read()
except UnicodeDecodeError as e:
msg = f"Could not successfully decode file {filename!r}"
raise UnicodeError(msg) from e
def read_ustring_from_utf8_file_lenient(filename: FilePath) -> str:
""" Ignores decoding errors """
_check_exists(filename)
with codecs.open(filename, encoding="utf-8", errors="ignore") as f:
try:
return f.read()
except UnicodeDecodeError as e:
msg = f"Could not successfully decode file {filename!r}"
raise UnicodeError(msg) from e
def _check_exists(filename: FilePath) -> None:
if not os.path.exists(filename):
if os.path.lexists(filename):
msg = f"The link {filename} does not exist."
msg += f" it links to {os.readlink(filename)}"
raise ValueError(msg)
else:
msg = f"Could not find file {filename!r}"
msg += f" from directory {os.getcwd()}"
raise ValueError(msg)
def write_ustring_to_utf8_file(data: str, filename: FilePath, quiet: bool = False) -> None:
"""
It also creates the directory if it does not exist.
:param data:
:param filename:
:param quiet:
:return:
"""
check_isinstance(data, str)
b = data.encode("utf-8") # OK
return write_bytes_to_file(b, filename, quiet=quiet)
def write_bytes_to_file(data: bytes, filename: FilePath, quiet: bool = False) -> None:
"""
Writes the data to the given filename.
If the data did not change, the file is not touched.
"""
check_isinstance(data, bytes)
L = len(filename)
if L > 1024:
msg = f"Invalid argument filename: too long at {L}. Did you confuse it with data?\n{filename[:1024]}"
raise ValueError(msg)
filename = cast(FilePath, expand_all(filename))
make_sure_dir_exists(filename)
if os.path.exists(filename):
with open(filename, "rb") as _:
current = _.read()
if current == data:
if not "assets" in filename:
if not quiet:
logger.debug("already up to date %s" % friendly_path(filename))
return
with open(filename, "wb") as f:
f.write(data)
if filename.startswith("/tmp"):
quiet = True
if not quiet:
mbs = len(data) / (1024 * 1024)
size = f"{mbs:.1f}MB"
logger.debug(f"Written {size} to: {friendly_path(filename)}") | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/fs/zc_fileutils.py | zc_fileutils.py |
from typing import Callable, Optional
import termcolor
import webcolors
from xtermcolor import colorize
__all__ = [
"color_blue",
"color_blue_light",
"color_brown",
"color_constant",
"color_float",
"color_green",
"color_int",
"color_ops",
"color_orange",
"color_orange_dark",
"color_par",
"color_pink",
"color_synthetic_types",
"color_pink2",
"color_typename",
"color_typename2",
"colorize_rgb",
"get_colorize_function",
]
from zuper_commons.types import ZValueError, ZAssertionError
color_orange = "#ffb342"
color_orange_dark = "#cfa342"
color_blue = "#42a0ff"
# color_blue_light = "#62c0ff"
color_blue_light = "#c2a0ff"
color_green = "#42ffa0"
color_pink = "#FF69B4"
color_pink2 = "#FF1493"
color_magenta_1 = "#a000a0"
color_brown = "#b08100"
def colorize_rgb(x: str, rgb: str, bg_color: Optional[str] = None) -> str:
rgb = interpret_color(rgb)
bg_color = interpret_color(bg_color)
if rgb is None:
msg = "We do not support rgb=None"
raise ZAssertionError(msg, rgb=rgb, bg_color=bg_color)
if rgb is None and bg_color is None:
return x
fg_int = int(rgb[1:], 16) if rgb is not None else None
bg_int = int(bg_color[1:], 16) if bg_color is not None else None
if fg_int is None and bg_int is None:
return x
try:
r = colorize(x, rgb=fg_int, bg=bg_int)
except Exception as e:
raise ZValueError(x=x, rgb=rgb, bg_color=bg_color) from e
if r is None:
raise NotImplementedError()
return r
def interpret_color(x: Optional[str]) -> Optional[str]:
if not x:
return None
if x.startswith('#'):
return x
return webcolors.name_to_hex(x)
def get_colorize_function(rgb: str, bg_color: Optional[str] = None) -> Callable[[str], str]:
T = "template"
Tc = colorize_rgb(T, rgb, bg_color)
before, _, after = Tc.partition(T)
def f(s: str) -> str:
return before + s + after
return f
color_ops = get_colorize_function(color_blue)
color_ops_light = get_colorize_function(color_blue_light)
color_synthetic_types = get_colorize_function(color_green)
color_int = get_colorize_function(color_pink)
color_float = get_colorize_function(color_pink2)
color_typename = get_colorize_function(color_orange)
color_typename2 = get_colorize_function(color_orange_dark)
color_constant = get_colorize_function(color_pink2)
color_magenta = get_colorize_function(color_magenta_1)
#
# def color_ops(x):
# return colorize_rgb(x, color_blue)
#
#
# def color_synthetic_types(x):
# return colorize_rgb(x, color_green)
#
#
# def color_int(x):
# return colorize_rgb(x, color_pink)
#
#
# def color_float(x):
# return colorize_rgb(x, color_pink2)
#
#
# def color_typename(x):
# return colorize_rgb(x, color_orange)
def color_par(x):
return termcolor.colored(x, attrs=["dark"]) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/ui/colors.py | colors.py |
import math
__all__ = ["duration_compact"]
def duration_compact(seconds: float) -> str:
seconds = int(math.ceil(seconds))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
years, days = divmod(days, 365)
minutes = int(minutes)
hours = int(hours)
days = int(days)
years = int(years)
duration = []
if years > 0:
duration.append("%dy" % years)
else:
if days > 0:
duration.append("%dd" % days)
if (days < 3) and (years == 0):
if hours > 0:
duration.append("%dh" % hours)
if (hours < 3) and (days == 0):
if minutes > 0:
duration.append("%dm" % minutes)
if (minutes < 3) and (hours == 0):
if seconds > 0:
duration.append("%ds" % seconds)
return " ".join(duration)
#
# def duration_human(seconds):
# ''' Code modified from
# http://darklaunch.com/2009/10/06
# /python-time-duration-human-friendly-timestamp
# '''
# seconds = int(math.ceil(seconds))
# minutes, seconds = divmod(seconds, 60)
# hours, minutes = divmod(minutes, 60)
# days, hours = divmod(hours, 24)
# years, days = divmod(days, 365.242199)
#
# minutes = int(minutes)
# hours = int(hours)
# days = int(days)
# years = int(years)
#
# duration = []
# if years > 0:
# duration.append('%d year' % years + 's' * (years != 1))
# else:
# if days > 0:
# duration.append('%d day' % days + 's' * (days != 1))
# if (days < 3) and (years == 0):
# if hours > 0:
# duration.append('%d hour' % hours + 's' * (hours != 1))
# if (hours < 3) and (days == 0):
# if minutes > 0:
# duration.append('%d min' % minutes +
# 's' * (minutes != 1))
# if (minutes < 3) and (hours == 0):
# if seconds > 0:
# duration.append('%d sec' % seconds +
# 's' * (seconds != 1))
#
# return ' '.join(duration) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/ui/zc_duration_hum.py | zc_duration_hum.py |
import os
from typing import Callable, ClassVar, Dict, Optional
__all__ = [
"ZException",
"ZValueError",
"ZTypeError",
"ZAssertionError",
"ZNotImplementedError",
"ZKeyError",
]
PASS_THROUGH = (KeyboardInterrupt,)
class ZException(Exception):
msg: Optional[str] = None
info: Optional[Dict[str, object]] = None
entries_formatter: ClassVar[Callable[[object], str]] = repr
def __init__(self, msg: Optional[str] = None, **info: object):
self.st = None
assert isinstance(msg, (str, type(None))), msg
self.msg = msg
self.info = info
# self.__str__()
def __str__(self) -> str:
if self.st is None:
try:
self.st = self.get_str()
except PASS_THROUGH: # pragma: no cover
raise
#
# except BaseException as e:
# self.st = f"!!! could not print: {e}"
return self.st
def get_str(self) -> str:
entries = {}
for k, v in self.info.items():
try:
# noinspection PyCallByClass
entries[k] = ZException.entries_formatter(v)
except Exception as e:
try:
entries[k] = f"!!! cannot print: {e}"
except:
entries[k] = f"!!! cannot print, and cannot print exception."
if not self.msg:
self.msg = "\n"
from zuper_commons.text import pretty_dict
if len(entries) == 1:
first = list(entries)[0]
payload = entries[first]
s = self.msg + f'\n{first}:\n{payload}'
elif entries:
s = pretty_dict(self.msg, entries)
else:
s = self.msg
s = sanitize_circle_ci(s)
return s
def __repr__(self) -> str:
return self.__str__()
def disable_colored() -> bool:
circle_job = os.environ.get("CIRCLE_JOB", None)
return circle_job is not None
def sanitize_circle_ci(s: str) -> str:
if disable_colored():
from zuper_commons.text.coloring import remove_escapes
s = remove_escapes(s)
difficult = ["┋"]
for c in difficult:
s = s.replace(c, "")
return s
else:
return s
class ZTypeError(ZException, TypeError):
pass
class ZValueError(ZException, ValueError):
pass
class ZKeyError(ZException, KeyError):
pass
class ZAssertionError(ZException, AssertionError):
pass
class ZNotImplementedError(ZException, NotImplementedError):
pass | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/types/exceptions.py | exceptions.py |
import traceback
from zuper_commons.text import indent
__all__ = ["import_name"]
def import_name(name: str) -> object:
"""
Loads the python object with the given name.
Note that "name" might be "module.module.name" as well.
"""
try:
return __import__(name, fromlist=["dummy"])
except ImportError:
# split in (module, name) if we can
if "." in name:
tokens = name.split(".")
field = tokens[-1]
module_name = ".".join(tokens[:-1])
if False: # previous method
pass
# try:
# module = __import__(module_name, fromlist=['dummy'])
# except ImportError as e:
# msg = ('Cannot load %r (tried also with %r):\n' %
# (name, module_name))
# msg += '\n' + indent(
# '%s\n%s' % (e, traceback.format_exc(e)), '> ')
# raise ValueError(msg)
#
# if not field in module.__dict__:
# msg = 'No field %r\n' % field
# msg += ' found in %r.' % module
# raise ValueError(msg)
#
# return module.__dict__[field]
else:
# other method, don't assume that in "M.x", "M" is a module.
# It could be a class as well, and "x" be a staticmethod.
try:
module = import_name(module_name)
except ImportError as e:
msg = "Cannot load %r (tried also with %r):\n" % (name, module_name)
msg += "\n" + indent("%s\n%s" % (e, traceback.format_exc()), "> ")
raise ValueError(msg) from None
if isinstance(module, type):
if hasattr(module, field):
return getattr(module, field)
else:
msg = f"No field {field!r} found in type {module!r}."
raise KeyError(msg) from None
if not field in module.__dict__:
msg = f"No field {field!r} found in module {module!r}."
msg += f'Known: {sorted(module.__dict__)} '
raise KeyError(msg) from None
f = module.__dict__[field]
# "staticmethod" are not functions but descriptors, we need
# extra magic
if isinstance(f, staticmethod):
return f.__get__(module, None)
else:
return f
else:
msg = "Cannot import name %r." % name
msg += indent(traceback.format_exc(), "> ")
raise ValueError(msg) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/types/zc_import.py | zc_import.py |
import sys
from collections import defaultdict
from dataclasses import dataclass
from decimal import Decimal
from typing import Dict, Set, Tuple
__all__ = ["get_rec_size"]
from zuper_commons.types import ZException
@dataclass
class RSize:
nbytes: int = 0
nobjects: int = 0
max_size: int = 0
largest: object = -1
largest_prefix: Tuple[str, ...] = ()
@dataclass
class RecSize:
sizes: Dict[type, RSize]
def friendly_mb(s: int) -> str:
mb = Decimal(s) / Decimal(1024 * 1024)
mb = mb.quantize(Decimal(".001"))
return str(mb) + " MB"
def friendly_kb(s: int) -> str:
mb = Decimal(s) / Decimal(1024)
mb = mb.quantize(Decimal(".001"))
return str(mb) + " KB"
def visualize(rs: RecSize, percentile=0.95, min_rows: int = 5) -> str:
types = list(rs.sizes)
sizes = list(rs.sizes.values())
indices = list(range(len(types)))
# order the indices by size
def key(i: int) -> int:
if sizes[i] is object:
return -1
return sizes[i].nbytes
indices = sorted(indices, key=key, reverse=True)
tot_bytes = rs.sizes[object].nbytes
stop_at = percentile * tot_bytes
cells = {}
row = 0
so_far = 0
cells[(row, 0)] = "type"
cells[(row, 1)] = "# objects"
cells[(row, 2)] = "bytes"
cells[(row, 3)] = "max size of 1 ob"
row += 1
cells[(row, 0)] = "-"
cells[(row, 1)] = "-"
cells[(row, 2)] = "-"
cells[(row, 3)] = "-"
row += 1
for j, i in enumerate(indices):
Ti = types[i]
rsi = sizes[i]
db = ZException.entries_formatter
cells[(row, 0)] = db(Ti)
cells[(row, 1)] = db(rsi.nobjects)
# cells[(row, 2)] = db(rsi.nbytes)
cells[(row, 2)] = friendly_mb(rsi.nbytes)
cells[(row, 3)] = friendly_kb(rsi.max_size)
if Ti in (bytes, str):
cells[(row, 4)] = "/".join(rsi.largest_prefix)
cells[(row, 5)] = db(rsi.largest)[:100]
row += 1
if Ti is not object:
so_far += rsi.nbytes
if j > min_rows and so_far > stop_at:
break
from zuper_commons.text import format_table, Style
align_right = Style(halign="right")
col_style: Dict[int, Style] = {2: align_right, 3: align_right}
res = format_table(cells, style="spaces", draw_grid_v=False, col_style=col_style)
return res
def get_rec_size(ob: object) -> RecSize:
"""Recursively finds size of objects. Traverses mappings and iterables. """
seen = set()
sizes = defaultdict(RSize)
rec_size = RecSize(sizes)
_get_rec_size(rec_size, ob, seen, ())
return rec_size
def _get_rec_size(rs: RecSize, obj: object, seen: Set[int], prefix: Tuple[str, ...]) -> None:
size = sys.getsizeof(obj)
obj_id = id(obj)
if obj_id in seen:
return
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
T = type(obj)
bases = T.__bases__
Ks = bases + (T,)
for K in Ks:
_ = rs.sizes[K]
_.nbytes += size
_.nobjects += 1
if size > _.max_size:
_.max_size = size
_.largest = obj
_.largest_prefix = prefix
def rec(x: object, p: Tuple[str, ...]):
_get_rec_size(rs, x, seen, p)
if isinstance(obj, dict):
for i, (k, v) in enumerate(obj.items()):
rec(k, p=prefix + (f"key{i}",))
rec(v, p=prefix + (f"val{i}",))
elif hasattr(obj, "__dict__"):
for k, v in obj.__dict__.items():
rec(v, p=prefix + (k,))
elif hasattr(obj, "__iter__") and not isinstance(obj, (str, bytes, bytearray)):
# noinspection PyTypeChecker
for i, v in enumerate(obj):
rec(v, p=prefix + (str(i),)) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/types/recsize.py | recsize.py |
import logging
from typing import cast
import termcolor
__all__ = ["setup_logging_color", "setup_logging_format", "setup_logging"]
def get_FORMAT_datefmt():
pre = "%(asctime)s|%(name)s|%(filename)s:%(lineno)s|%(funcName)s:"
pre = termcolor.colored(pre, attrs=["dark"])
FORMAT = pre + "\n" + "%(message)s"
datefmt = "%H:%M:%S"
return FORMAT, datefmt
def setup_logging_format():
from logging import Logger, StreamHandler, Formatter
import logging
FORMAT, datefmt = get_FORMAT_datefmt()
logging.basicConfig(format=FORMAT, datefmt=datefmt)
# noinspection PyUnresolvedReferences
root = cast(Logger, Logger.root)
if root.handlers:
for handler in root.handlers:
if isinstance(handler, StreamHandler):
formatter = Formatter(FORMAT, datefmt=datefmt)
handler.setFormatter(formatter)
else:
logging.basicConfig(format=FORMAT, datefmt=datefmt)
def add_coloring_to_emit_ansi(fn):
# add methods we need to the class
from zuper_commons.text import get_length_on_screen
from zuper_commons.ui.colors import colorize_rgb, get_colorize_function
RED = "#ff0000"
GREEN = "#00ff00"
LGREEN = "#77ff77"
PINK = "#FFC0CB"
YELLOW = "#FFFF00"
colorizers = {
"red": get_colorize_function(RED),
"green": get_colorize_function(LGREEN),
"pink": get_colorize_function(PINK),
"yellow": get_colorize_function(YELLOW),
"normal": (lambda x: x),
}
prefixes = {
"red": colorize_rgb(" ", "#000000", bg_color=RED),
"green": colorize_rgb(" ", "#000000", bg_color=LGREEN),
"pink": colorize_rgb(" ", "#000000", bg_color=PINK),
"yellow": colorize_rgb(" ", "#000000", bg_color=YELLOW),
"normal": " ",
}
def new(*args):
levelno = args[1].levelno
if levelno >= 50:
ncolor = "red"
color = "\x1b[31m" # red
elif levelno >= 40:
ncolor = "red"
color = "\x1b[31m" # red
elif levelno >= 30:
ncolor = "yellow"
color = "\x1b[33m" # yellow
elif levelno >= 20:
ncolor = "green"
color = "\x1b[32m" # green
elif levelno >= 10:
ncolor = "pink"
color = "\x1b[35m" # pink
else:
ncolor = "normal"
color = "\x1b[0m" # normal
msg = str(args[1].msg)
lines = msg.split("\n")
any_color_inside = any(get_length_on_screen(l) != len(l) for l in lines)
#
# if any_color_inside:
# print(msg.__repr__())
do_color_lines_inside = False
def color_line(l):
if do_color_lines_inside and not any_color_inside:
return prefixes[ncolor] + " " + colorizers[ncolor](l)
else:
return prefixes[ncolor] + " " + l
# return "%s%s%s" % (color, levelno, "\x1b[0m") + ' ' + l # normal
lines = list(map(color_line, lines))
msg = "\n".join(lines)
# if len(lines) > 1:
# msg = "\n" + msg
args[1].msg = msg
return fn(*args)
return new
def setup_logging_color() -> None:
import platform
if platform.system() != "Windows":
emit1 = logging.StreamHandler.emit
if getattr(emit1, "__name__", "") != "new":
emit2 = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
# print(f'now changing {logging.StreamHandler.emit} -> {emit2}')
logging.StreamHandler.emit = emit2
def setup_logging() -> None:
# logging.basicConfig()
setup_logging_color()
setup_logging_format() | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/logs/col_logging.py | col_logging.py |
import inspect
import logging
from abc import ABC, abstractmethod
from typing import Dict, Union
import termcolor
__all__ = ["ZLogger", "ZLoggerInterface"]
class ZLoggerInterface(ABC):
@abstractmethod
def info(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
...
@abstractmethod
def debug(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
...
@abstractmethod
def warn(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs) -> None:
...
@abstractmethod
def warning(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs) -> None:
...
@abstractmethod
def error(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
...
@abstractmethod
def getChild(self, child_name: str) -> "ZLoggerInterface":
...
class ZLogger(ZLoggerInterface):
DEBUG = logging.DEBUG
INFO = logging.INFO
WARN = logging.WARN
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
logger: logging.Logger
debug_print = str
def __init__(self, logger: Union[str, logging.Logger]):
if isinstance(logger, str):
logger = logger.replace("zuper_", "")
logger = logging.getLogger(logger)
logger.setLevel(logging.DEBUG)
self.logger = logger
else:
self.logger = logger
from zuper_commons.text import pretty_dict
self.pretty_dict = pretty_dict
self.debug_print = None
# monkeypatch_findCaller()
def info(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
level = logging.INFO
return self._log(level=level, msg=_msg, args=args, stacklevel=stacklevel, kwargs=kwargs)
def debug(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
level = logging.DEBUG
return self._log(level=level, msg=_msg, args=args, stacklevel=stacklevel, kwargs=kwargs)
def warn(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs) -> None:
level = logging.WARN
return self._log(level=level, msg=_msg, args=args, stacklevel=stacklevel, kwargs=kwargs)
def warning(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs) -> None:
level = logging.WARN
return self._log(level=level, msg=_msg, args=args, stacklevel=stacklevel, kwargs=kwargs)
def error(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
level = logging.ERROR
return self._log(level=level, msg=_msg, args=args, stacklevel=stacklevel, kwargs=kwargs)
def _log(self, level: int, msg: str, args, stacklevel: int, kwargs: Dict[str, object]):
if self.debug_print is None:
try:
# noinspection PyUnresolvedReferences
from zuper_typing import debug_print
self.debug_print = debug_print
except ImportError:
self.debug_print = str
if not self.logger.isEnabledFor(level):
return
do_inspect = True
if do_inspect:
try:
# 0 is us
# 1 is one of our methods
stacklevel += 2
# for i, frame_i in enumerate(stack[:5]):
# x = '***' if i == stacklevel else ' '
# print(i, x, frame_i.filename, frame_i.function)
stack = inspect.stack()
frame = stack[stacklevel]
pathname = frame.filename
lineno = frame.lineno
funcname = str(frame.function)
locals = frame[0].f_locals
except KeyboardInterrupt:
raise
except:
locals = {}
funcname = "!!!could not inspect()!!!"
pathname = "!!!"
lineno = -1
# print(list(locals))
if "self" in locals:
# print(locals['self'])
typename = locals["self"].__class__.__name__
funcname = typename + ":" + funcname
else:
locals = {}
funcname = "n/a"
pathname = "n/a"
lineno = -1
res = {}
def lab(x):
return x
# return termcolor.colored(x, attrs=["dark"])
for i, a in enumerate(args):
for k, v in locals.items():
if a is v:
use = k
break
else:
use = str(i)
res[lab(use)] = ZLogger.debug_print(a)
for k, v in kwargs.items():
res[lab(k)] = ZLogger.debug_print(v)
if res:
s = self.pretty_dict(msg, res, leftmargin=" ")
# if not msg:
# s = "\n" + s
# if msg:
# s = msg + '\n' + indent(rest, ' ')
# else:
# s = rest
else:
s = msg
# funcname = termcolor.colored(funcname, "red")
record = self.logger.makeRecord(
self.logger.name,
level,
pathname,
lineno,
s,
(),
exc_info=None,
func=funcname,
extra=None,
sinfo=None,
)
self.logger.handle(record)
return record
# self.logger.log(level, s)
def getChild(self, child_name: str) -> "ZLogger":
logger_child = self.logger.getChild(child_name)
return ZLogger(logger_child)
def setLevel(self, level: int) -> None:
self.logger.setLevel(level) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/logs/zlogger.py | zlogger.py |
from typing import Optional
from zuper_commons.logs.zlogger import ZLoggerInterface
class ZLoggerStore(ZLoggerInterface):
def __init__(self, up: Optional[ZLoggerInterface]):
self.up = up
self.records = []
self.record = True
def info(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
from zuper_commons.timing import now_utc
record = {"msg": _msg, "args": list(args), "kwargs": kwargs, "t": now_utc()}
if self.up:
r = self.up.info(_msg=_msg, *args, stacklevel=stacklevel + 1, **kwargs)
record["record"] = r
if self.record:
self.records.append(record)
def debug(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
from zuper_commons.timing import now_utc
record = {"msg": _msg, "args": list(args), "kwargs": kwargs, "t": now_utc()}
if self.up:
r = self.up.debug(_msg=_msg, *args, stacklevel=stacklevel + 1, **kwargs)
record["record"] = r
if self.record:
self.records.append(record)
def warn(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs) -> None:
from zuper_commons.timing import now_utc
record = {"msg": _msg, "args": list(args), "kwargs": kwargs, "t": now_utc()}
if self.up:
r = self.up.warn(_msg=_msg, *args, stacklevel=stacklevel + 1, **kwargs)
record["record"] = r
if self.record:
self.records.append(record)
def warning(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs) -> None:
from zuper_commons.timing import now_utc
record = {"msg": _msg, "args": list(args), "kwargs": kwargs, "t": now_utc()}
if self.up:
r = self.up.warning(_msg=_msg, *args, stacklevel=stacklevel + 1, **kwargs)
record["record"] = r
if self.record:
self.records.append(record)
def error(self, _msg: str = None, *args, stacklevel: int = 0, **kwargs: object) -> None:
from zuper_commons.timing import now_utc
record = {"msg": _msg, "args": list(args), "kwargs": kwargs, "t": now_utc()}
if self.up:
r = self.up.error(_msg=_msg, *args, stacklevel=stacklevel + 1, **kwargs)
record["record"] = r
if self.record:
self.records.append(record)
def getChild(self, child_name: str) -> "ZLoggerInterface":
return self.up.getChild(child_name) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/logs/zlogger_store.py | zlogger_store.py |
from dataclasses import dataclass
from typing import Optional, List, Tuple
import termcolor
from zuper_commons.text.coloring import get_length_on_screen
from zuper_commons.text.text_sidebyside import pad
__all__ = ["box", "text_dimensions"]
@dataclass
class TextDimensions:
nlines: int
max_width: int
def text_dimensions(s: str):
lines = s.split("\n")
max_width = max(get_length_on_screen(_) for _ in lines)
return TextDimensions(nlines=len(lines), max_width=max_width)
#
# U+250x ─ ━ │ ┃ ┄ ┅ ┆ ┇ ┈ ┉ ┊ ┋ ┌ ┍ ┎ ┏
# U+251x ┐ ┑ ┒ ┓ └ ┕ ┖ ┗ ┘ ┙ ┚ ┛ ├ ┝ ┞ ┟
# U+252x ┠ ┡ ┢ ┣ ┤ ┥ ┦ ┧ ┨ ┩ ┪ ┫ ┬ ┭ ┮ ┯
# U+253x ┰ ┱ ┲ ┳ ┴ ┵ ┶ ┷ ┸ ┹ ┺ ┻ ┼ ┽ ┾ ┿
# U+254x ╀ ╁ ╂ ╃ ╄ ╅ ╆ ╇ ╈ ╉ ╊ ╋ ╌ ╍ ╎ ╏
# U+255x ═ ║ ╒ ╓ ╔ ╕ ╖ ╗ ╘ ╙ ╚ ╛ ╜ ╝ ╞ ╟
# U+256x ╠ ╡ ╢ ╣ ╤ ╥ ╦ ╧ ╨ ╩ ╪ ╫ ╬ ╭ ╮ ╯
# U+257x ╰ ╱ ╲ ╳ ╴ ╵ ╶ ╷ ╸ ╹ ╺ ╻ ╼ ╽ ╾ ╿
boxes = {
"pipes": "╔ ═ ╗ ║ ╝ ═ ╚ ║ ╬ ╠ ╣ ╦ ╩ ═ ║ ┼ ╟ ╢ ╤ ╧ ─ │".split(),
"heavy": "┏ ━ ┓ ┃ ┛ ━ ┗ ┃ ╋ ┣ ┫ ┳ ┻ ━ ┃ ┼ ┠ ┨ ┯ ┷ ─ │".split(),
"light": "┌ ─ ┐ │ ┘ ─ └ │ ┼ ├ ┤ ┬ ┴ ─ │ ┼ ├ ┤ ┬ ┴ ─ │".split(),
"circo": "╭ ─ ╮ │ ╯ ─ ╰ │ ┼ ├ ┤ ┬ ┴ ─ │ ┼ ├ ┤ ┬ ┴ ─ │".split(),
}
boxes["spaces"] = [" "] * len(boxes["pipes"])
CORNERS = ["corner"]
NEIGH = ((0, 0, 0), (0, None, 0), (0, 0, 0))
def box(
s: str,
style="pipes",
neighs=NEIGH,
draw_borders: Tuple[int, int, int, int] = (1, 1, 1, 1),
light_inside=True,
color: Optional[str] = None,
attrs: Optional[List[str]] = None,
style_fun=None,
) -> str:
dims = text_dimensions(s)
padded = pad(s, dims.nlines, dims.max_width, style_fun=style_fun)
(tl_n, tc_n, tr_n), (ml_n, _, mr_n), (bl_n, bc_n, br_n) = neighs
S = boxes[style]
assert len(S) == 22, len(S)
(
tl,
tc,
tr,
mr,
br,
bc,
bl,
ml,
Pc,
Pr,
Pl,
Pd,
Pu,
H,
V,
Pc_light,
Pr_light,
Pl_light,
Pd_light,
Pu_light,
H_light,
V_light,
) = S
if light_inside:
Pc = Pc_light
Pu = Pu_light
Pd = Pd_light
Pr = Pr_light
Pl = Pl_light
H = H_light
V = V_light
tl_use = {
(0, 0, 0): tl,
(0, 0, 1): Pd,
(0, 1, 0): Pr,
(0, 1, 1): Pc, # XXX
(1, 0, 0): Pc, # XXX
(1, 0, 1): Pc, # XXX
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(tl_n, tc_n, ml_n)]
tr_use = {
(0, 0, 0): tr,
(0, 0, 1): Pd,
(0, 1, 0): Pc,
(0, 1, 1): Pc,
(1, 0, 0): Pl,
(1, 0, 1): Pc,
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(tc_n, tr_n, mr_n)]
br_use = {
(0, 0, 0): br,
(0, 0, 1): Pc,
(0, 1, 0): Pl,
(0, 1, 1): Pc,
(1, 0, 0): Pu,
(1, 0, 1): Pc,
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(mr_n, bc_n, br_n)]
bl_use = {
(0, 0, 0): bl,
(0, 0, 1): Pr,
(0, 1, 0): Pc,
(0, 1, 1): Pc,
(1, 0, 0): Pu,
(1, 0, 1): Pc,
(1, 1, 0): Pc,
(1, 1, 1): Pc,
}[(ml_n, bl_n, bc_n)]
mr_use = {0: mr, 1: V}[mr_n]
ml_use = {0: ml, 1: V}[ml_n]
tc_use = {0: tc, 1: H}[tc_n]
bc_use = {0: bc, 1: H}[bc_n]
draw_top, draw_right, draw_bottom, draw_left = draw_borders
if not draw_right:
tr_use = ""
mr_use = ""
br_use = ""
if not draw_left:
tl_use = ""
ml_use = ""
bl_use = ""
top = tl_use + tc_use * dims.max_width + tr_use
bot = bl_use + bc_use * dims.max_width + br_use
def f(_):
if style_fun:
_ = style_fun(_)
if color is not None or attrs:
_ = termcolor.colored(_, color=color, attrs=attrs)
return _
top_col = f(top)
bot_col = f(bot)
mr_use_col = f(mr_use)
ml_use_col = f(ml_use)
new_lines = []
if draw_top:
new_lines.append(top_col)
for l in padded:
new_lines.append(ml_use_col + l + mr_use_col)
if draw_bottom:
new_lines.append(bot_col)
return "\n".join(new_lines)
# begin = termcolor.colored('║', 'yellow', attrs=['dark'])
# ending = termcolor.colored('║', 'yellow', attrs=['dark']) # ↵┋ | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/text/boxing.py | boxing.py |
from typing import Callable, List, Sequence
from .coloring import get_length_on_screen
__all__ = ["pad", "side_by_side"]
def pad(
text: str,
nlines: int,
linelength: int,
halign: str = "left",
valign: str = "top",
style_fun: Callable[[str], str] = None,
) -> List[str]:
lines: List[str] = text.split("\n")
if len(lines) < nlines:
extra = nlines - len(lines)
if valign == "top":
extra_top = 0
extra_bottom = extra
elif valign == "bottom":
extra_top = extra
extra_bottom = 0
elif valign == "middle":
extra_bottom = int(extra / 2)
extra_top = extra - extra_bottom
else:
raise ValueError(valign)
assert extra == extra_top + extra_bottom
lines_top = [""] * extra_top
lines_bottom = [""] * extra_bottom
lines = lines_top + lines + lines_bottom
res: List[str] = []
for l in lines:
extra = max(linelength - get_length_on_screen(l), 0)
if halign == "left":
extra_left = 0
extra_right = extra
elif halign == "right":
extra_left = extra
extra_right = 0
elif halign == "center":
extra_right = int(extra / 2)
extra_left = extra - extra_right
else:
raise ValueError(halign)
assert extra == extra_left + extra_right
left = " " * extra_left
right = " " * extra_right
if style_fun:
left = style_fun(left)
right = style_fun(right)
l = left + l + right
res.append(l)
return res
def side_by_side(args: Sequence[str], sep=" ", style_fun=None) -> str:
args = list(args)
lines: List[List[str]] = [_.split("\n") for _ in args]
nlines: int = max([len(_) for _ in lines])
linelengths: List[int] = [max(get_length_on_screen(line) for line in _) for _ in lines]
padded = [pad(_, nlines, linelength, style_fun=style_fun) for _, linelength in zip(args, linelengths)]
res = []
for i in range(nlines):
ls = [x[i] for x in padded]
l = sep.join(ls)
res.append(l)
return "\n".join(res) | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/text/text_sidebyside.py | text_sidebyside.py |
import re
from typing import Iterator, List, Sequence, Union
__all__ = ["expand_string", "get_wildcard_matches", "wildcard_to_regexp", 'expand_wildcard']
def flatten(seq: Iterator) -> List:
res = []
for l in seq:
res.extend(l)
return res
def expand_string(x: Union[str, Sequence[str]], options: Sequence[str]) -> List[str]:
if isinstance(x, list):
return flatten(expand_string(y, options) for y in x)
elif isinstance(x, str):
x = x.strip()
if "," in x:
splat = [_ for _ in x.split(",") if _] # remove empty
return flatten(expand_string(y, options) for y in splat)
elif "*" in x:
xx = expand_wildcard(x, options)
expanded = list(xx)
return expanded
else:
return [x]
else:
assert False, x
def wildcard_to_regexp(arg: str):
""" Returns a regular expression from a shell wildcard expression. """
return re.compile("\A" + arg.replace("*", ".*") + "\Z")
def has_wildcard(s: str) -> bool:
return s.find("*") > -1
def expand_wildcard(wildcard: str, universe: Sequence[str]) -> Sequence[str]:
"""
Expands a wildcard expression against the given list.
Raises ValueError if none found.
:param wildcard: string with '*'
:param universe: a list of strings
"""
if not has_wildcard(wildcard):
msg = "No wildcards in %r." % wildcard
raise ValueError(msg)
matches = list(get_wildcard_matches(wildcard, universe))
if not matches:
msg = "Could not find matches for pattern %r in %s." % (wildcard, universe)
raise ValueError(msg)
return matches
def get_wildcard_matches(wildcard: str, universe: Sequence[str]) -> Iterator[str]:
"""
Expands a wildcard expression against the given list.
Yields a sequence of strings.
:param wildcard: string with '*'
:param universe: a list of strings
"""
regexp = wildcard_to_regexp(wildcard)
for x in universe:
if regexp.match(x):
yield x | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/text/zc_wildcards.py | zc_wildcards.py |
import itertools
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Tuple, TypeVar
from .boxing import box, text_dimensions
from .coloring import get_length_on_screen
from .text_sidebyside import pad, side_by_side
try:
from typing import Literal
HAlign = Literal["left", "center", "right", "inherit"]
VAlign = Literal["top", "middle", "bottom", "inherit"]
except ImportError:
HAlign = VAlign = str
__all__ = ["Style", "format_table", "wrap_lines"]
@dataclass
class Style:
halign: HAlign = "inherit"
valign: VAlign = "inherit"
padding_right: int = "inherit"
padding_left: int = "inherit"
def format_table(
cells: Dict[Tuple[int, int], str],
*,
draw_grid_v: bool = True,
draw_grid_h: bool = True,
style: str = "pipes",
light_inside: bool = True,
color: Optional[str] = None,
attrs: Optional[List[str]] = None,
col_style: Dict[int, Style] = None,
row_style: Dict[int, Style] = None,
cell_style: Dict[Tuple[int, int], Style] = None,
table_style: Style = None,
style_fun=None
) -> str:
"""
Styles: "none", "pipes", ...
"""
table_style = table_style or Style()
col_styles = col_style or {}
row_styles = row_style or {}
cell_styles = cell_style or {}
def get_row_style(row: int) -> Style:
return row_styles.get(row, Style())
def get_col_style(col: int) -> Style:
return col_styles.get(col, Style())
def get_cell_style(cell: Tuple[int, int]) -> Style:
return cell_styles.get(cell, Style())
X = TypeVar("X")
def resolve(a: List[X]) -> X:
cur = a[0]
for _ in a:
if _ == "inherit":
continue
else:
cur = _
return cur
def get_style(cell: Tuple[int, int]) -> Style:
row, col = cell
rows = get_row_style(row)
cols = get_col_style(col)
cels = get_cell_style(cell)
halign = resolve(["left", table_style.halign, rows.halign, cols.halign, cels.halign])
valign = resolve(["top", table_style.valign, rows.valign, cols.valign, cels.valign])
padding_left = resolve(
[0, table_style.padding_left, rows.padding_left, cols.padding_left, cels.padding_left]
)
padding_right = resolve(
[0, table_style.padding_right, rows.padding_right, cols.padding_right, cels.padding_right]
)
return Style(halign=halign, valign=valign, padding_left=padding_left, padding_right=padding_right)
cells = dict(cells)
# find all mentioned cells
mentioned_js = set()
mentioned_is = set()
for i, j in cells:
mentioned_is.add(i)
mentioned_js.add(j)
# add default = '' for missing cells
nrows = max(mentioned_is) + 1 if mentioned_is else 1
ncols = max(mentioned_js) + 1 if mentioned_js else 1
coords = list(itertools.product(range(nrows), range(ncols)))
for c in coords:
if c not in cells:
cells[c] = ""
# find max size for cells
row_heights = [0] * nrows
col_widths = [0] * ncols
for (i, j), s in list(cells.items()):
dims = text_dimensions(s)
col_widths[j] = max(col_widths[j], dims.max_width)
row_heights[i] = max(row_heights[i], dims.nlines)
# pad all cells
for (i, j), s in list(cells.items()):
linelength = col_widths[j]
nlines = row_heights[i]
cell_style = get_style((i, j))
padded = do_padding(
s,
linelength=linelength,
nlines=nlines,
halign=cell_style.halign,
valign=cell_style.valign,
padding_left=cell_style.padding_left,
padding_right=cell_style.padding_right,
style_fun=style_fun,
)
ibef = int(i > 0)
iaft = int(i < nrows - 1)
jbef = int(j > 0)
jaft = int(j < ncols - 1)
neighs = (
(ibef * jbef, ibef, ibef * jaft),
(jbef, None, jaft),
(iaft * jbef, iaft, iaft * jaft),
)
draw_top = 1
draw_left = 1
draw_right = jaft == 0
draw_bottom = iaft == 0
if not draw_grid_v:
draw_bottom = draw_top = 0
if not draw_grid_h:
draw_left = draw_right = 0
d = draw_top, draw_right, draw_bottom, draw_left
if style == "none":
s = " " + padded
else:
s = box(
padded,
neighs=neighs,
style=style,
draw_borders=d,
light_inside=light_inside,
color=color,
attrs=attrs,
style_fun=style_fun,
)
cells[(i, j)] = s
parts = []
for i in range(nrows):
ss = []
for j in range(ncols):
ss.append(cells[(i, j)])
s = side_by_side(ss, sep="")
parts.append(s)
whole = "\n".join(parts)
# res = box(whole, style=style)
# logger.info(f'table {cells!r}')
return whole
def wrap_lines(s: str, max_width: int):
lines = s.split("\n")
res = []
while lines:
l = lines.pop(0)
n = get_length_on_screen(l)
if n <= max_width:
res.append(l)
else:
a = l[:max_width]
b = "$" + l[max_width:]
res.append(a)
lines.insert(0, b)
return "\n".join(res)
def do_padding(
s: str,
linelength: int,
nlines: int,
halign: HAlign,
valign: VAlign,
padding_left: int,
padding_right: int,
style_fun: Callable[[str], str] = None,
pad_char=" ",
) -> str:
padded_lines = pad(
s, linelength=linelength, nlines=nlines, halign=halign, valign=valign, style_fun=style_fun
)
pl = pad_char * padding_left
pr = pad_char * padding_right
if style_fun is not None:
pl = style_fun(pl)
pr = style_fun(pr)
padded_lines = [pl + _ + pr for _ in padded_lines]
padded = "\n".join(padded_lines)
return padded | zuper-commons-z6 | /zuper-commons-z6-6.2.4.tar.gz/zuper-commons-z6-6.2.4/src/zuper_commons/text/table.py | table.py |
import pickle
import traceback
from io import BytesIO
from pickle import (Pickler, SETITEM, MARK, SETITEMS, EMPTY_TUPLE, TUPLE, POP,
_tuplesize2code, POP_MARK)
from zuper_commons.types.zc_describe_type import describe_type
from . import logger
__all__ = ['find_pickling_error']
def find_pickling_error(obj, protocol=pickle.HIGHEST_PROTOCOL):
sio = BytesIO()
try:
pickle.dumps(obj)
except BaseException:
se1 = traceback.format_exc()
pickler = MyPickler(sio, protocol)
try:
pickler.dump(obj)
except Exception:
se2 = traceback.format_exc()
msg = pickler.get_stack_description()
msg += '\n --- Current exception----\n%s' % se1
msg += '\n --- Old exception----\n%s' % se2
return msg
else:
msg = 'I could not find the exact pickling error.'
raise Exception(msg)
else:
msg = ('Strange! I could not reproduce the pickling error '
'for the object of class %s' % describe_type(obj))
logger.info(msg)
class MyPickler(Pickler):
def __init__(self, *args, **kargs):
Pickler.__init__(self, *args, **kargs)
self.stack = []
def save(self, obj):
desc = 'object of type %s' % (describe_type(obj))
# , describe_value(obj, 100))
# self.stack.append(describe_value(obj, 120))
self.stack.append(desc)
Pickler.save(self, obj)
self.stack.pop()
def get_stack_description(self):
s = 'Pickling error occurred at:\n'
for i, context in enumerate(self.stack):
s += ' ' * i + '- %s\n' % context
return s
def save_pair(self, k, v):
self.stack.append('key %r = object of type %s' % (k, describe_type(v)))
self.save(k)
self.save(v)
self.stack.pop()
def _batch_setitems(self, items):
# Helper to batch up SETITEMS sequences; proto >= 1 only
# save = self.save
write = self.write
if not self.bin:
for k, v in items:
self.stack.append('entry %s' % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEM)
return
r = list(range(self._BATCHSIZE))
while items is not None:
tmp = []
for _ in r:
try:
tmp.append(items.next())
except StopIteration:
items = None
break
n = len(tmp)
if n > 1:
write(MARK)
for k, v in tmp:
self.stack.append('entry %s' % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEMS)
elif n:
k, v = tmp[0]
self.stack.append('entry %s' % str(k))
self.save_pair(k, v)
self.stack.pop()
write(SETITEM)
# else tmp is empty, and we're done
def save_tuple(self, obj):
write = self.write
proto = self.proto
n = len(obj)
if n == 0:
if proto:
write(EMPTY_TUPLE)
else:
write(MARK + TUPLE)
return
save = self.save
memo = self.memo
if n <= 3 and proto >= 2:
for i, element in enumerate(obj):
self.stack.append('tuple element %s' % i)
save(element)
self.stack.pop()
# Subtle. Same as in the big comment below.
if id(obj) in memo:
get = self.get(memo[id(obj)][0])
write(POP * n + get)
else:
write(_tuplesize2code[n])
self.memoize(obj)
return
# proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
# has more than 3 elements.
write(MARK)
for i, element in enumerate(obj):
self.stack.append('tuple element %s' % i)
save(element)
self.stack.pop()
if id(obj) in memo:
# Subtle. d was not in memo when we entered save_tuple(), so
# the process of saving the tuple's elements must have saved
# the tuple itself: the tuple is recursive. The proper action
# now is to throw away everything we put on the stack, and
# simply GET the tuple (it's already constructed). This check
# could have been done in the "for element" loop instead, but
# recursive tuples are a rare thing.
get = self.get(memo[id(obj)][0])
if proto:
write(POP_MARK + get)
else: # proto 0 -- POP_MARK not available
write(POP * (n + 1) + get)
return
# No recursion.
self.write(TUPLE)
self.memoize(obj) | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/fs/zc_debug_pickler.py | zc_debug_pickler.py |
import fnmatch
import os
import time
from typing import *
from collections import defaultdict
from contracts import contract
from contracts.utils import check_isinstance
from . import logger
__all__ = [
'locate_files',
]
@contract(returns='list(str)', directory='str',
pattern='str|seq(str)', followlinks='bool')
def locate_files(directory, pattern, followlinks=True,
include_directories=False,
include_files=True,
normalize=True,
ignore_patterns: Optional[List[str]]=None):
"""
pattern is either a string or a sequence of strings
NOTE: if you do not pass ignore_patterns, it will use MCDPConstants.locate_files_ignore_patterns
ignore_patterns = ['*.bak']
normalize = uses realpath
"""
t0 = time.time()
if ignore_patterns is None:
ignore_patterns = []
if isinstance(pattern, str):
patterns = [pattern]
else:
patterns = list(pattern)
for p in patterns:
check_isinstance(p, str)
# directories visited
# visited = set()
# visited_basename = set()
# print('locate_files %r %r' % (directory, pattern))
filenames = []
def matches_pattern(x):
return any(fnmatch.fnmatch(x, _) or (x == _) for _ in patterns)
def should_ignore_resource(x):
return any(fnmatch.fnmatch(x, _) or (x == _) for _ in ignore_patterns)
def accept_dirname_to_go_inside(_root_, d_):
if should_ignore_resource(d_):
return False
# XXX
# dd = os.path.realpath(os.path.join(root_, d_))
# if dd in visited:
# return False
# visited.add(dd)
return True
def accept_dirname_as_match(_):
return include_directories and \
not should_ignore_resource(_) and \
matches_pattern(_)
def accept_filename_as_match(_):
return include_files and \
not should_ignore_resource(_) and \
matches_pattern(_)
ntraversed = 0
for root, dirnames, files in os.walk(directory, followlinks=followlinks):
ntraversed += 1
dirnames[:] = [_ for _ in dirnames if accept_dirname_to_go_inside(root, _)]
for f in files:
# logger.info('look ' + root + '/' + f)
if accept_filename_as_match(f):
filename = os.path.join(root, f)
filenames.append(filename)
for d in dirnames:
if accept_dirname_as_match(d):
filename = os.path.join(root, d)
filenames.append(filename)
if normalize:
real2norm = defaultdict(lambda: [])
for norm in filenames:
real = os.path.realpath(norm)
real2norm[real].append(norm)
# print('%s -> %s' % (real, norm))
for k, v in real2norm.items():
if len(v) > 1:
msg = 'In directory:\n\t%s\n' % directory
msg += 'I found %d paths that refer to the same file:\n' % len(v)
for n in v:
msg += '\t%s\n' % n
msg += 'refer to the same file:\n\t%s\n' % k
msg += 'I will silently eliminate redundancies.'
# logger.warning(msg) # XXX
filenames = list(real2norm.keys())
seconds = time.time() - t0
if seconds > 5:
n = len(filenames)
nuniques = len(set(filenames))
logger.debug('%.4f s for locate_files(%s,%s): %d traversed, found %d filenames (%d uniques)' %
(seconds, directory, pattern, ntraversed, n, nuniques))
return filenames | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/fs/zc_locate_files_imp.py | zc_locate_files_imp.py |
import gzip
import os
import random
from contextlib import contextmanager
__all__ = [
'safe_write',
'safe_read',
]
def is_gzip_filename(filename):
return '.gz' in filename
@contextmanager
def safe_write(filename, mode='wb', compresslevel=5):
"""
Makes atomic writes by writing to a temp filename.
Also if the filename ends in ".gz", writes to a compressed stream.
Yields a file descriptor.
It is thread safe because it renames the file.
If there is an error, the file will be removed if it exists.
"""
dirname = os.path.dirname(filename)
if dirname:
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
pass
# Dont do this!
# if os.path.exists(filename):
# os.unlink(filename)
# assert not os.path.exists(filename)
#
n = random.randint(0, 10000)
tmp_filename = '%s.tmp.%s.%s' % (filename, os.getpid(), n)
try:
if is_gzip_filename(filename):
fopen = lambda fname, fmode: gzip.open(filename=fname, mode=fmode,
compresslevel=compresslevel)
else:
fopen = open
with fopen(tmp_filename, mode) as f:
yield f
f.close()
# if os.path.exists(filename):
# msg = 'Race condition for writing to %r.' % filename
# raise Exception(msg)
#
# On Unix, if dst exists and is a file, it will be replaced silently
# if the user has permission.
os.rename(tmp_filename, filename)
except:
if os.path.exists(tmp_filename):
os.unlink(tmp_filename)
if os.path.exists(filename):
os.unlink(filename)
raise
@contextmanager
def safe_read(filename, mode='rb'):
"""
If the filename ends in ".gz", reads from a compressed stream.
Yields a file descriptor.
"""
try:
if is_gzip_filename(filename):
f = gzip.open(filename, mode)
try:
yield f
finally:
f.close()
else:
with open(filename, mode) as f:
yield f
except:
# TODO
raise | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/fs/zc_safe_write.py | zc_safe_write.py |
import codecs
import os
from zuper_commons.types import check_isinstance
from . import logger
from .zc_friendly_path import friendly_path
from .zc_mkdirs import make_sure_dir_exists
from .zc_path_utils import expand_all
__all__ = [
'read_bytes_from_file',
'read_ustring_from_utf8_file',
'read_ustring_from_utf8_file_lenient',
'write_bytes_to_file',
'write_ustring_to_utf8_file',
]
def read_bytes_from_file(filename: str) -> bytes:
""" Read binary data and returns bytes """
_check_exists(filename)
with open(filename, 'rb') as f:
return f.read()
def read_ustring_from_utf8_file(filename: str) -> str:
""" Returns a unicode/proper string """
_check_exists(filename)
with codecs.open(filename, encoding='utf-8') as f:
try:
return f.read()
except UnicodeDecodeError as e:
msg = 'Could not successfully decode file %s' % filename
raise UnicodeError(msg) from e
def read_ustring_from_utf8_file_lenient(filename) -> str:
""" Ignores errors """
_check_exists(filename)
with codecs.open(filename, encoding='utf-8', errors='ignore') as f:
try:
return f.read()
except UnicodeDecodeError as e:
msg = 'Could not successfully decode file %s' % filename
raise UnicodeError(msg) from e
def _check_exists(filename):
if not os.path.exists(filename):
if os.path.lexists(filename):
msg = 'The link %s does not exist.' % filename
msg += ' it links to %s' % os.readlink(filename)
raise ValueError(msg)
else:
msg = 'Could not find file %r' % filename
msg += ' from directory %s' % os.getcwd()
raise ValueError(msg)
def write_ustring_to_utf8_file(data: str, filename, quiet=False):
"""
It also creates the directory if it does not exist.
:param data:
:param filename:
:param quiet:
:return:
"""
check_isinstance(data, str)
b = data.encode('utf-8') # OK
return write_bytes_to_file(b, filename, quiet=quiet)
def write_bytes_to_file(data: bytes, filename: str, quiet=False):
"""
Writes the data to the given filename.
If the data did not change, the file is not touched.
"""
check_isinstance(data, bytes)
L = len(filename)
if L > 1024:
msg = f'Invalid argument filename: too long at {L}. Did you confuse it with data?\n{filename[:1024]}'
raise ValueError(msg)
filename = expand_all(filename)
make_sure_dir_exists(filename)
if os.path.exists(filename):
current = open(filename, 'rb').read()
if current == data:
if not 'assets' in filename:
if not quiet:
logger.debug('already up to date %s' % friendly_path(filename))
return
with open(filename, 'wb') as f:
f.write(data)
if filename.startswith('/tmp'):
quiet = True
if not quiet:
size = '%.1fMB' % (len(data) / (1024 * 1024))
logger.debug('Written %s to: %s' % (size, friendly_path(filename))) | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/fs/zc_fileutils.py | zc_fileutils.py |
import math
__all__ = [
'duration_compact',
]
def duration_compact(seconds):
seconds = int(math.ceil(seconds))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
years, days = divmod(days, 365)
minutes = int(minutes)
hours = int(hours)
days = int(days)
years = int(years)
duration = []
if years > 0:
duration.append('%dy' % years)
else:
if days > 0:
duration.append('%dd' % days)
if (days < 3) and (years == 0):
if hours > 0:
duration.append('%dh' % hours)
if (hours < 3) and (days == 0):
if minutes > 0:
duration.append('%dm' % minutes)
if (minutes < 3) and (hours == 0):
if seconds > 0:
duration.append('%ds' % seconds)
return ' '.join(duration)
#
# def duration_human(seconds):
# ''' Code modified from
# http://darklaunch.com/2009/10/06
# /python-time-duration-human-friendly-timestamp
# '''
# seconds = int(math.ceil(seconds))
# minutes, seconds = divmod(seconds, 60)
# hours, minutes = divmod(minutes, 60)
# days, hours = divmod(hours, 24)
# years, days = divmod(days, 365.242199)
#
# minutes = int(minutes)
# hours = int(hours)
# days = int(days)
# years = int(years)
#
# duration = []
# if years > 0:
# duration.append('%d year' % years + 's' * (years != 1))
# else:
# if days > 0:
# duration.append('%d day' % days + 's' * (days != 1))
# if (days < 3) and (years == 0):
# if hours > 0:
# duration.append('%d hour' % hours + 's' * (hours != 1))
# if (hours < 3) and (days == 0):
# if minutes > 0:
# duration.append('%d min' % minutes +
# 's' * (minutes != 1))
# if (minutes < 3) and (hours == 0):
# if seconds > 0:
# duration.append('%d sec' % seconds +
# 's' * (seconds != 1))
#
# return ' '.join(duration) | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/ui/zc_duration_hum.py | zc_duration_hum.py |
import logging
import termcolor
__all__ = ['setup_logging_color', 'setup_logging_format', 'setup_logging']
def get_FORMAT_datefmt():
pre = '%(asctime)s|%(name)s|%(filename)s:%(lineno)s|%(funcName)s(): '
pre = termcolor.colored(pre, attrs=['dark'])
FORMAT = pre + "%(message)s"
datefmt = "%H:%M:%S"
return FORMAT, datefmt
def setup_logging_format():
from logging import Logger, StreamHandler, Formatter
import logging
FORMAT, datefmt = get_FORMAT_datefmt()
logging.basicConfig(format=FORMAT, datefmt=datefmt)
if Logger.root.handlers: # @UndefinedVariable
for handler in Logger.root.handlers: # @UndefinedVariable
if isinstance(handler, StreamHandler):
formatter = Formatter(FORMAT, datefmt=datefmt)
handler.setFormatter(formatter)
else:
logging.basicConfig(format=FORMAT, datefmt=datefmt)
def add_coloring_to_emit_ansi(fn):
# add methods we need to the class
def new(*args):
levelno = args[1].levelno
if levelno >= 50:
color = '\x1b[31m' # red
elif levelno >= 40:
color = '\x1b[31m' # red
elif levelno >= 30:
color = '\x1b[33m' # yellow
elif levelno >= 20:
color = '\x1b[32m' # green
elif levelno >= 10:
color = '\x1b[35m' # pink
else:
color = '\x1b[0m' # normal
msg = str(args[1].msg)
lines = msg.split('\n')
def color_line(l):
return "%s%s%s" % (color, l, '\x1b[0m') # normal
lines = list(map(color_line, lines))
args[1].msg = "\n".join(lines)
return fn(*args)
return new
def setup_logging_color():
import platform
if platform.system() != 'Windows':
emit2 = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
logging.StreamHandler.emit = emit2
def setup_logging():
# logging.basicConfig()
setup_logging_color()
setup_logging_format() | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/logs/col_logging.py | col_logging.py |
import re
from typing import List, Union, Iterator
__all__ = [
'expand_string',
'get_wildcard_matches',
'wildcard_to_regexp',
]
def flatten(seq):
res = []
for l in seq:
res.extend(l)
return res
def expand_string(x: Union[str, List[str]], options: List[str]) -> List[str]:
if isinstance(x, list):
return flatten(expand_string(y, options) for y in x)
elif isinstance(x, str):
x = x.strip()
if ',' in x:
splat = [_ for _ in x.split(',') if _] # remove empty
return flatten(expand_string(y, options) for y in splat)
elif '*' in x:
xx = expand_wildcard(x, options)
expanded = list(xx)
return expanded
else:
return [x]
else:
assert False
def wildcard_to_regexp(arg: str):
""" Returns a regular expression from a shell wildcard expression. """
return re.compile('\A' + arg.replace('*', '.*') + '\Z')
def has_wildcard(s: str) -> bool:
return s.find('*') > -1
def expand_wildcard(wildcard: str, universe: List[str]) -> List[str]:
'''
Expands a wildcard expression against the given list.
Raises ValueError if none found.
:param wildcard: string with '*'
:param universe: a list of strings
'''
if not has_wildcard(wildcard):
msg = 'No wildcards in %r.' % wildcard
raise ValueError(msg)
matches = list(get_wildcard_matches(wildcard, universe))
if not matches:
msg = ('Could not find matches for pattern %r in %s.' %
(wildcard, universe))
raise ValueError(msg)
return matches
def get_wildcard_matches(wildcard: str, universe: List[str]) -> Iterator[str]:
'''
Expands a wildcard expression against the given list.
Yields a sequence of strings.
:param wildcard: string with '*'
:param universe: a list of strings
'''
regexp = wildcard_to_regexp(wildcard)
for x in universe:
if regexp.match(x):
yield x | zuper-commons | /zuper-commons-3.0.4.tar.gz/zuper-commons-3.0.4/src/zuper_commons/text/zc_wildcards.py | zc_wildcards.py |
import io
import json
import select
import time
import traceback
from io import BufferedReader
from json import JSONDecodeError
from typing import Iterator
import base58
import cbor2
from . import logger
from .json_utils import (
decode_bytes_before_json_deserialization,
encode_bytes_before_json_serialization,
)
from .utils_text import oyaml_dump
__all__ = [
"read_cbor_or_json_objects",
"json2cbor_main",
"cbor2json_main",
"cbor2yaml_main",
"read_next_cbor",
"read_next_either_json_or_cbor",
]
def json2cbor_main() -> None:
fo = open("/dev/stdout", "wb", buffering=0)
fi = open("/dev/stdin", "rb", buffering=0)
# noinspection PyTypeChecker
fi = BufferedReader(fi, buffer_size=1)
for j in read_cbor_or_json_objects(fi):
c = cbor2.dumps(j)
fo.write(c)
fo.flush()
def cbor2json_main() -> None:
fo = open("/dev/stdout", "wb", buffering=0)
fi = open("/dev/stdin", "rb", buffering=0)
for j in read_cbor_objects(fi):
j = encode_bytes_before_json_serialization(j)
ob = json.dumps(j)
ob = ob.encode("utf-8")
fo.write(ob)
fo.write(b"\n")
fo.flush()
def cbor2yaml_main() -> None:
fo = open("/dev/stdout", "wb")
fi = open("/dev/stdin", "rb")
for j in read_cbor_objects(fi):
ob = oyaml_dump(j)
ob = ob.encode("utf-8")
fo.write(ob)
fo.write(b"\n")
fo.flush()
def read_cbor_or_json_objects(f, timeout=None) -> Iterator:
""" Reads cbor or line-separated json objects from the binary file f."""
while True:
try:
ob = read_next_either_json_or_cbor(f, timeout=timeout)
yield ob
except StopIteration:
break
except TimeoutError:
raise
def read_cbor_objects(f, timeout=None) -> Iterator:
""" Reads cbor or line-separated json objects from the binary file f."""
while True:
try:
ob = read_next_cbor(f, timeout=timeout)
yield ob
except StopIteration:
break
except TimeoutError:
raise
def read_next_either_json_or_cbor(f, timeout=None, waiting_for: str = None) -> dict:
""" Raises StopIteration if it is EOF.
Raises TimeoutError if over timeout"""
fs = [f]
t0 = time.time()
intermediate_timeout = 3.0
while True:
try:
readyr, readyw, readyx = select.select(fs, [], fs, intermediate_timeout)
except io.UnsupportedOperation:
break
if readyr:
break
elif readyx:
logger.warning("Exceptional condition on input channel %s" % readyx)
else:
delta = time.time() - t0
if (timeout is not None) and (delta > timeout):
msg = "Timeout after %.1f s." % delta
logger.error(msg)
raise TimeoutError(msg)
else:
msg = "I have been waiting %.1f s." % delta
if timeout is None:
msg += " I will wait indefinitely."
else:
msg += " Timeout will occurr at %.1f s." % timeout
if waiting_for:
msg += " " + waiting_for
logger.warning(msg)
first = f.peek(1)[:1]
if len(first) == 0:
msg = "Detected EOF on %s." % f
if waiting_for:
msg += " " + waiting_for
raise StopIteration(msg)
# logger.debug(f'first char is {first}')
if first in [b" ", b"\n", b"{"]:
line = f.readline()
line = line.strip()
if not line:
msg = "Read empty line. Re-trying."
logger.warning(msg)
return read_next_either_json_or_cbor(f)
# logger.debug(f'line is {line!r}')
try:
j = json.loads(line)
except JSONDecodeError:
msg = f"Could not decode line {line!r}: {traceback.format_exc()}"
logger.error(msg)
return read_next_either_json_or_cbor(f)
j = decode_bytes_before_json_deserialization(j)
return j
else:
j = cbor2.load(f, tag_hook=tag_hook)
return j
def tag_hook(decoder, tag, shareable_index=None) -> dict:
if tag.tag != 42:
return tag
d = tag.value
val = base58.b58encode(d).decode("ascii")
val = "z" + val[1:]
return {"/": val}
def wait_for_data(f, timeout=None, waiting_for: str = None):
""" Raises StopIteration if it is EOF.
Raises TimeoutError if over timeout"""
# XXX: StopIteration not implemented
fs = [f]
t0 = time.time()
intermediate_timeout = 3.0
while True:
try:
readyr, readyw, readyx = select.select(fs, [], fs, intermediate_timeout)
except io.UnsupportedOperation:
break
if readyr:
break
elif readyx:
logger.warning("Exceptional condition on input channel %s" % readyx)
else:
delta = time.time() - t0
if (timeout is not None) and (delta > timeout):
msg = "Timeout after %.1f s." % delta
logger.error(msg)
raise TimeoutError(msg)
else:
msg = "I have been waiting %.1f s." % delta
if timeout is None:
msg += " I will wait indefinitely."
else:
msg += " Timeout will occurr at %.1f s." % timeout
if waiting_for:
msg += " " + waiting_for
logger.warning(msg)
def read_next_cbor(f, timeout=None, waiting_for: str = None) -> dict:
""" Raises StopIteration if it is EOF.
Raises TimeoutError if over timeout"""
wait_for_data(f, timeout, waiting_for)
try:
j = cbor2.load(f, tag_hook=tag_hook)
return j
except OSError as e:
if e.errno == 29:
raise StopIteration from None
raise | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/json2cbor.py | json2cbor.py |
import datetime
from dataclasses import is_dataclass
from decimal import Decimal
from numbers import Number
from typing import (
Callable,
cast,
ClassVar,
Dict,
List,
NewType,
Optional,
Set,
Tuple,
Type,
)
import numpy as np
from zuper_typing.aliases import TypeLike
from zuper_typing.annotations_tricks import (
get_Callable_info,
get_ClassVar_arg,
get_Dict_args,
get_FixedTupleLike_args,
get_List_arg,
get_NewType_arg,
get_NewType_name,
get_Optional_arg,
get_Set_arg,
get_Type_arg,
get_Union_args,
get_VarTuple_arg,
is_Any,
is_Callable,
is_ClassVar,
is_Dict,
is_FixedTupleLike,
is_ForwardRef,
is_List,
is_NewType,
is_Optional,
is_Set,
is_TupleLike,
is_Type,
is_TypeVar,
is_Union,
is_VarTuple,
make_Tuple,
make_Union,
)
from zuper_typing.monkey_patching_typing import my_dataclass, original_dict_getitem
from zuper_typing.my_dict import (
CustomDict,
CustomList,
CustomSet,
get_CustomDict_args,
get_CustomList_arg,
get_CustomSet_arg,
is_CustomDict,
is_CustomList,
is_CustomSet,
make_dict,
make_list,
make_set,
)
# def resolve_all(T, globals_):
# """
# Returns either a type or a generic alias
#
#
# :return:
# """
# if isinstance(T, type):
# return T
#
# if is_Optional(T):
# t = get_Optional_arg(T)
# t = resolve_all(t, globals_)
# return Optional[t]
#
# # logger.debug(f'no thing to do for {T}')
# return T
def recursive_type_subst(
T: TypeLike, f: Callable[[TypeLike], TypeLike], ignore: tuple = ()
) -> TypeLike:
if T in ignore:
# logger.info(f'ignoring {T} in {ignore}')
return T
r = lambda _: recursive_type_subst(_, f, ignore + (T,))
if is_Optional(T):
a = get_Optional_arg(T)
a2 = r(a)
if a == a2:
return T
# logger.info(f'Optional unchanged under {f.__name__}: {a} == {a2}')
return Optional[a2]
elif is_ForwardRef(T):
return f(T)
elif is_Union(T):
ts0 = get_Union_args(T)
ts = tuple(r(_) for _ in ts0)
if ts0 == ts:
# logger.info(f'Union unchanged under {f.__name__}: {ts0} == {ts}')
return T
return make_Union(*ts)
elif is_TupleLike(T):
if is_VarTuple(T):
X = get_VarTuple_arg(T)
X2 = r(X)
if X == X2:
return T
return Tuple[X2, ...]
elif is_FixedTupleLike(T):
args = get_FixedTupleLike_args(T)
ts = tuple(r(_) for _ in args)
if args == ts:
return T
return make_Tuple(*ts)
else:
assert False
elif is_Dict(T):
T = cast(Type[Dict], T)
K, V = get_Dict_args(T)
K2, V2 = r(K), r(V)
if (K, V) == (K2, V2):
return T
return original_dict_getitem((K, V))
elif is_CustomDict(T):
T = cast(Type[CustomDict], T)
K, V = get_CustomDict_args(T)
K2, V2 = r(K), r(V)
if (K, V) == (K2, V2):
return T
return make_dict(K2, V2)
elif is_List(T):
T = cast(Type[List], T)
V = get_List_arg(T)
V2 = r(V)
if V == V2:
return T
return List[V2]
elif is_ClassVar(T):
V = get_ClassVar_arg(T)
V2 = r(V)
if V == V2:
return T
return ClassVar[V2]
elif is_CustomList(T):
T = cast(Type[CustomList], T)
V = get_CustomList_arg(T)
V2 = r(V)
if V == V2:
return T
return make_list(V2)
elif is_Set(T):
T = cast(Type[Set], T)
V = get_Set_arg(T)
V2 = r(V)
if V == V2:
return T
return make_set(V2)
elif is_CustomSet(T):
T = cast(Type[CustomSet], T)
V = get_CustomSet_arg(T)
V2 = r(V)
if V == V2:
return T
return make_set(V2)
elif is_NewType(T):
name = get_NewType_name(T)
a = get_NewType_arg(T)
a2 = r(a)
if a == a2:
return T
return NewType(name, a2)
elif is_dataclass(T):
annotations = dict(getattr(T, "__annotations__", {}))
annotations2 = {}
nothing_changed = True
for k, v0 in list(annotations.items()):
v2 = r(v0)
nothing_changed &= v0 == v2
annotations2[k] = v2
if nothing_changed:
# logger.info(f'Union unchanged under {f.__name__}: {ts0} == {ts}')
return T
T2 = my_dataclass(
type(
T.__name__,
(),
{
"__annotations__": annotations2,
"__module__": T.__module__,
"__doc__": getattr(T, "__doc__", None),
"__qualname__": getattr(T, "__qualname__"),
},
)
)
return T2
elif T in (
int,
bool,
float,
Decimal,
datetime.datetime,
bytes,
str,
type(None),
type,
np.ndarray,
Number,
object,
):
return f(T)
elif is_TypeVar(T):
return f(T)
elif is_Type(T):
V = get_Type_arg(T)
V2 = r(V)
if V == V2:
return T
return Type[V2]
elif is_Any(T):
return f(T)
elif is_Callable(T):
info = get_Callable_info(T)
args = []
for k, v in info.parameters_by_name.items():
# if is_MyNamedArg(v):
# # try:
# v = v.original
# TODO: add MyNamedArg
args.append(f(v))
fret = f(info.returns)
args = list(args)
# noinspection PyTypeHints
return Callable[args, fret]
# noinspection PyTypeHints
elif isinstance(T, type) and "Placeholder" in T.__name__:
return f(T)
else: # pragma: no cover
raise NotImplementedError(T) | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/assorted_recursive_type_subst.py | assorted_recursive_type_subst.py |
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import cast, Dict, NewType, Tuple
from zuper_typing.my_dict import make_dict
JSONSchema = NewType("JSONSchema", dict)
GlobalsDict = Dict[str, object]
ProcessingDict = Dict[str, str]
EncounteredDict = Dict[str, object]
# _SpecialForm = Any
SCHEMA_ID = "http://json-schema.org/draft-07/schema#"
SCHEMA_ATT = "$schema"
HINTS_ATT = "$hints"
ANY_OF = "anyOf"
ALL_OF = "allOf"
ID_ATT = "$id"
REF_ATT = "$ref"
X_CLASSVARS = "classvars"
X_CLASSATTS = "classatts"
X_ORDER = "order"
JSC_FORMAT = "format"
JSC_REQUIRED = "required"
JSC_TYPE = "type"
JSC_ITEMS = "items"
JSC_DEFAULT = "default"
JSC_TITLE = "title"
JSC_NUMBER = "number"
JSC_INTEGER = "integer"
JSC_ARRAY = "array"
JSC_OBJECT = "object"
JSC_ADDITIONAL_PROPERTIES = "additionalProperties"
JSC_PROPERTY_NAMES = "propertyNames"
JSC_DESCRIPTION = "description"
JSC_STRING = "string"
JSC_NULL = "null"
JSC_BOOL = "boolean"
JSC_PROPERTIES = "properties"
JSC_DEFINITIONS = "definitions"
JSC_ALLOF = "allOf"
JSC_ANYOF = "anyOf"
Z_ATT_LSIZE = "lsize"
Z_ATT_TSIZE = "tsize"
X_PYTHON_MODULE_ATT = "__module__"
ATT_PYTHON_NAME = "__qualname__"
JSC_TITLE_NUMPY = "numpy"
JSC_TITLE_SLICE = "slice"
JSC_TITLE_BYTES = "bytes"
JSC_TITLE_DECIMAL = "decimal"
JSC_TITLE_FLOAT = "float"
JSC_TITLE_DATETIME = "datetime"
JSC_TITLE_CALLABLE = "Callable"
JSC_TITLE_TYPE = "type"
JSC_TITLE_CID = "cid"
# JSC_TITLE_TUPLE = 'Tuple'
# JSC_TITLE_LIST = 'List'
JSC_FORMAT_CID = "cid"
SCHEMA_BYTES = cast(
JSONSchema,
{JSC_TYPE: JSC_STRING, JSC_TITLE: JSC_TITLE_BYTES, SCHEMA_ATT: SCHEMA_ID},
)
SCHEMA_CID = cast(
JSONSchema,
{
JSC_TYPE: JSC_STRING,
JSC_TITLE: JSC_TITLE_CID,
JSC_FORMAT: JSC_FORMAT_CID,
SCHEMA_ATT: SCHEMA_ID,
},
)
IPCE_SCALARS = (int, str, float, bytes, datetime, bool, Decimal, type(None))
# check_types = False
CALLABLE_ORDERING = "ordering"
CALLABLE_RETURN = "return"
@dataclass
class IEDO:
use_remembered_classes: bool
remember_deserialized_classes: bool
ModuleName = QualName = str
n = 0
@dataclass
class IEDS:
global_symbols: Dict[str, type]
encountered: Dict
klasses: Dict[Tuple[ModuleName, QualName], type] = None
def __post_init__(self):
pass
if self.klasses is None:
self.klasses = make_dict(str, type)()
# from .logging import logger
# logger.info('IEDS new')
# global n
# n += 1
# if n == 5:
# raise NotImplementedError()
@dataclass
class IESO:
use_ipce_from_typelike_cache: bool = True
with_schema: bool = True
IPCE_PASS_THROUGH = (
NotImplementedError,
KeyboardInterrupt,
MemoryError,
AttributeError,
NameError,
) | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/constants.py | constants.py |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Dict, Tuple
from zuper_typing.exceptions import ZValueError
from .constants import JSONSchema, REF_ATT, SCHEMA_ATT, SCHEMA_ID
from .ipce_attr import make_key
from .ipce_spec import assert_canonical_ipce
def assert_canonical_schema(x: JSONSchema):
assert isinstance(x, dict)
if SCHEMA_ATT in x:
assert x[SCHEMA_ATT] in [SCHEMA_ID]
elif REF_ATT in x:
pass
else:
msg = f"No {SCHEMA_ATT} or {REF_ATT}"
raise ZValueError(msg, x=x)
assert_canonical_ipce(x)
# json.dumps(x) # try no bytes
@dataclass
class TRE:
schema: JSONSchema
used: Dict[str, str] = field(default_factory=dict)
def __post_init__(self) -> None:
try:
assert_canonical_schema(self.schema)
except ValueError as e: # pragma: no cover
msg = f"Invalid schema"
raise ZValueError(msg, schema=self.schema) from e
class IPCETypelikeCache:
c: Dict[Tuple, Dict[Tuple, JSONSchema]] = defaultdict(dict)
# def get_cached():
# return {k[1]: [x for x, _ in v.items()] for k, v in IPCETypelikeCache.c.items()}
def get_ipce_from_typelike_cache(T, context: Dict[str, str]) -> TRE:
k = make_key(T)
if k not in IPCETypelikeCache.c:
raise KeyError()
items = list(IPCETypelikeCache.c[k].items())
# actually first look for the ones with more context
items.sort(key=lambda x: len(x[1]), reverse=True)
for context0, schema in items:
if compatible(context0, context):
# if context0:
# logger.debug(f'Returning cached {T} with context {context0}')
return TRE(schema, dict(context0))
raise KeyError()
def compatible(c0: Tuple[Tuple[str, str]], context: Dict[str, str]) -> bool:
for k, v in c0:
if k not in context or context[k] != v:
return False
return True
def set_ipce_from_typelike_cache(T, context: Dict[str, str], schema: JSONSchema):
k = make_key(T)
ci = tuple(sorted(context.items()))
IPCETypelikeCache.c[k][ci] = schema | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/schema_caching.py | schema_caching.py |
import dataclasses
import datetime
from dataclasses import dataclass, field, make_dataclass
from decimal import Decimal
from numbers import Number
from typing import (
Any,
Callable,
cast,
ClassVar,
Dict,
List,
NewType,
Optional,
Tuple,
Type,
TypeVar,
)
from zuper_commons.types.exceptions import ZException
from zuper_typing.logging_util import ztinfo
from zuper_typing.zeneric2 import MyABC
_X = TypeVar("_X")
import numpy as np
from zuper_commons.types import check_isinstance
from zuper_typing.annotations_tricks import (
is_ForwardRef,
make_Tuple,
make_Union,
make_VarTuple,
is_ClassVar,
)
from zuper_typing.constants import PYTHON_36
from zuper_typing.exceptions import ZTypeError, ZValueError
from zuper_typing.monkey_patching_typing import (
get_remembered_class,
MyNamedArg,
remember_created_class,
)
from zuper_typing.my_dict import make_dict, make_list, make_set
from zuper_typing.my_intersection import make_Intersection
from .assorted_recursive_type_subst import recursive_type_subst
from .constants import (
ATT_PYTHON_NAME,
CALLABLE_ORDERING,
CALLABLE_RETURN,
IEDO,
ID_ATT,
IEDS,
JSC_ADDITIONAL_PROPERTIES,
JSC_ALLOF,
JSC_ANYOF,
JSC_ARRAY,
JSC_BOOL,
JSC_DEFAULT,
JSC_DEFINITIONS,
JSC_DESCRIPTION,
JSC_INTEGER,
JSC_NULL,
JSC_NUMBER,
JSC_OBJECT,
JSC_PROPERTIES,
JSC_REQUIRED,
JSC_STRING,
JSC_TITLE,
JSC_TITLE_BYTES,
JSC_TITLE_CALLABLE,
JSC_TITLE_DATETIME,
JSC_TITLE_DECIMAL,
JSC_TITLE_FLOAT,
JSC_TITLE_NUMPY,
JSC_TITLE_SLICE,
JSC_TYPE,
JSONSchema,
REF_ATT,
SCHEMA_ATT,
SCHEMA_ID,
X_CLASSATTS,
X_CLASSVARS,
X_ORDER,
X_PYTHON_MODULE_ATT,
)
from .structures import CannotFindSchemaReference
from .types import TypeLike, IPCE, is_unconstrained
@dataclass
class SRE:
res: TypeLike
used: Dict[str, object] = dataclasses.field(default_factory=dict)
@dataclass
class SRO:
res: object
used: Dict[str, object] = dataclasses.field(default_factory=dict)
def typelike_from_ipce(schema0: JSONSchema, *, iedo: Optional[IEDO] = None) -> TypeLike:
if iedo is None:
iedo = IEDO(use_remembered_classes=False, remember_deserialized_classes=False)
ieds = IEDS({}, {})
sre = typelike_from_ipce_sr(schema0, ieds=ieds, iedo=iedo)
return sre.res
def typelike_from_ipce_sr(schema0: JSONSchema, *, ieds: IEDS, iedo: IEDO) -> SRE:
try:
sre = typelike_from_ipce_sr_(schema0, ieds=ieds, iedo=iedo)
assert isinstance(sre, SRE), (schema0, sre)
res = sre.res
except (TypeError, ValueError) as e: # pragma: no cover
msg = "Cannot interpret schema as a type."
raise ZTypeError(msg, schema0=schema0) from e
if ID_ATT in schema0:
schema_id = schema0[ID_ATT]
ieds.encountered[schema_id] = res
return sre
def typelike_from_ipce_sr_(schema0: JSONSchema, *, ieds: IEDS, iedo: IEDO) -> SRE:
# pprint('schema_to_type_', schema0=schema0)
# encountered = encountered or {}
check_isinstance(schema0, dict)
schema = cast(JSONSchema, dict(schema0))
# noinspection PyUnusedLocal
metaschema = schema.pop(SCHEMA_ATT, None)
schema_id = schema.pop(ID_ATT, None)
if schema_id:
if not JSC_TITLE in schema:
pass
else:
cls_name = schema[JSC_TITLE]
ieds.encountered[schema_id] = cls_name
if schema == {JSC_TITLE: "Any"}:
return SRE(Any)
if schema == {}:
return SRE(object)
if schema == {JSC_TITLE: "object"}:
return SRE(object)
if REF_ATT in schema:
r = schema[REF_ATT]
if r == SCHEMA_ID:
if schema.get(JSC_TITLE, "") == "type":
return SRE(type)
else: # pragma: no cover
raise NotImplementedError(schema)
# return SRE(Type)
if r in ieds.encountered:
res = ieds.encountered[r]
return SRE(res, {r: res})
else:
msg = f"Cannot evaluate reference {r!r}"
raise CannotFindSchemaReference(msg, ieds=ieds)
if JSC_ANYOF in schema:
return typelike_from_ipce_Union(schema, ieds=ieds, iedo=iedo)
if JSC_ALLOF in schema:
return typelike_from_ipce_Intersection(schema, ieds=ieds, iedo=iedo)
jsc_type = schema.get(JSC_TYPE, None)
jsc_title = schema.get(JSC_TITLE, "-not-provided-")
if jsc_title == JSC_TITLE_NUMPY:
res = np.ndarray
return SRE(res)
if jsc_type == "NewType":
kt = KeepTrackDes(ieds, iedo)
if "newtype" not in schema:
original = object
else:
nt = schema["newtype"]
tre = typelike_from_ipce_sr(nt, ieds=ieds, iedo=iedo)
original = tre.res
res = NewType(jsc_title, original)
return kt.sre(res)
if jsc_type == JSC_STRING:
if jsc_title == JSC_TITLE_BYTES:
return SRE(bytes)
elif jsc_title == JSC_TITLE_DATETIME:
return SRE(datetime.datetime)
elif jsc_title == JSC_TITLE_DECIMAL:
return SRE(Decimal)
else:
return SRE(str)
elif jsc_type == JSC_NULL:
return SRE(type(None))
elif jsc_type == JSC_BOOL:
return SRE(bool)
elif jsc_type == JSC_NUMBER:
if jsc_title == JSC_TITLE_FLOAT:
return SRE(float)
else:
return SRE(Number)
elif jsc_type == JSC_INTEGER:
return SRE(int)
elif jsc_type == "subtype":
s = schema["subtype"]
r = typelike_from_ipce_sr(s, ieds=ieds, iedo=iedo)
T = Type[r.res]
return SRE(T, r.used)
elif jsc_type == JSC_OBJECT:
if jsc_title == JSC_TITLE_CALLABLE:
return typelike_from_ipce_Callable(schema, ieds=ieds, iedo=iedo)
elif jsc_title.startswith("Dict["):
return typelike_from_ipce_DictType(schema, ieds=ieds, iedo=iedo)
elif jsc_title.startswith("Set["):
return typelike_from_ipce_SetType(schema, ieds=ieds, iedo=iedo)
elif jsc_title == JSC_TITLE_SLICE:
return SRE(slice)
else:
return typelike_from_ipce_dataclass(
schema, schema_id=schema_id, ieds=ieds, iedo=iedo
)
elif jsc_type == JSC_ARRAY:
return typelike_from_ipce_array(schema, ieds=ieds, iedo=iedo)
msg = "Cannot recover schema"
raise ZValueError(msg, schema=schema)
# assert False, schema # pragma: no cover
def typelike_from_ipce_Union(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
options = schema[JSC_ANYOF]
kt = KeepTrackDes(ieds, iedo)
args = [kt.typelike_from_ipce(_) for _ in options]
if args and args[-1] is type(None):
V = args[0]
res = Optional[V]
else:
res = make_Union(*args)
return kt.sre(res)
def typelike_from_ipce_Intersection(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
options = schema[JSC_ALLOF]
kt = KeepTrackDes(ieds, iedo)
args = [kt.typelike_from_ipce(_) for _ in options]
res = make_Intersection(tuple(args))
return kt.sre(res)
class KeepTrackDes:
def __init__(self, ieds: IEDS, iedo: IEDO):
self.ieds = ieds
self.iedo = iedo
self.used = {}
def typelike_from_ipce(self, x: IPCE):
sre = typelike_from_ipce_sr(x, ieds=self.ieds, iedo=self.iedo)
self.used.update(sre.used)
return sre.res
def object_from_ipce(self, x: IPCE, st: Type[_X] = object) -> _X:
from zuper_ipce.conv_object_from_ipce import object_from_ipce_
res = object_from_ipce_(x, st, ieds=self.ieds, iedo=self.iedo)
return res
def sre(self, x: IPCE) -> SRE:
return SRE(x, self.used)
def typelike_from_ipce_array(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
assert schema[JSC_TYPE] == JSC_ARRAY
items = schema["items"]
kt = KeepTrackDes(ieds, iedo)
if isinstance(items, list):
# assert len(items) > 0
args = tuple([kt.typelike_from_ipce(_) for _ in items])
res = make_Tuple(*args)
else:
if schema[JSC_TITLE].startswith("Tuple["):
V = kt.typelike_from_ipce(items)
res = make_VarTuple(V)
else:
V = kt.typelike_from_ipce(items)
res = make_list(V)
# logger.info(f'found list like: {res}')
return kt.sre(res)
def typelike_from_ipce_DictType(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
K = str
kt = KeepTrackDes(ieds, iedo)
V = kt.typelike_from_ipce(schema[JSC_ADDITIONAL_PROPERTIES])
# pprint(f'here:', d=dict(V.__dict__))
# if issubclass(V, FakeValues):
if isinstance(V, type) and V.__name__.startswith("FakeValues"):
K = V.__annotations__["real_key"]
V = V.__annotations__["value"]
try:
D = make_dict(K, V)
except (TypeError, ValueError) as e: # pragma: no cover
msg = f"Cannot reconstruct dict type."
raise ZTypeError(msg, K=K, V=V, ieds=ieds) from e
return kt.sre(D)
def typelike_from_ipce_SetType(schema, *, ieds: IEDS, iedo: IEDO):
if not JSC_ADDITIONAL_PROPERTIES in schema: # pragma: no cover
msg = f"Expected {JSC_ADDITIONAL_PROPERTIES!r} in @schema."
raise ZValueError(msg, schema=schema)
kt = KeepTrackDes(ieds, iedo)
V = kt.typelike_from_ipce(schema[JSC_ADDITIONAL_PROPERTIES])
res = make_set(V)
return kt.sre(res)
def typelike_from_ipce_Callable(schema: JSONSchema, *, ieds: IEDS, iedo: IEDO):
kt = KeepTrackDes(ieds, iedo)
schema = dict(schema)
definitions = dict(schema[JSC_DEFINITIONS])
ret = kt.typelike_from_ipce(definitions.pop(CALLABLE_RETURN))
others = []
for k in schema[CALLABLE_ORDERING]:
d = kt.typelike_from_ipce(definitions[k])
if not looks_like_int(k):
d = MyNamedArg(d, k)
others.append(d)
# noinspection PyTypeHints
res = Callable[others, ret]
# logger.info(f'typelike_from_ipce_Callable: {schema} \n others = {others}\n res = {res}')
return kt.sre(res)
def looks_like_int(k: str) -> bool:
try:
int(k)
except:
return False
else:
return True
def typelike_from_ipce_dataclass(
res: JSONSchema, schema_id: Optional[str], *, ieds: IEDS, iedo: IEDO
) -> SRE:
kt = KeepTrackDes(ieds, iedo)
assert res[JSC_TYPE] == JSC_OBJECT
cls_name = res[JSC_TITLE]
definitions = res.get(JSC_DEFINITIONS, {})
required = res.get(JSC_REQUIRED, [])
properties = res.get(JSC_PROPERTIES, {})
classvars = res.get(X_CLASSVARS, {})
classatts = res.get(X_CLASSATTS, {})
if (
not X_PYTHON_MODULE_ATT in res
) or not ATT_PYTHON_NAME in res: # pragma: no cover
msg = f"Cannot find attributes for {cls_name!r}."
raise ZValueError(msg, res=res)
module_name = res[X_PYTHON_MODULE_ATT]
qual_name = res[ATT_PYTHON_NAME]
key = (module_name, qual_name)
if iedo.use_remembered_classes:
try:
res = get_remembered_class(module_name, qual_name)
return SRE(res)
except KeyError:
pass
if key in ieds.klasses:
return SRE(ieds.klasses[key], {})
typevars: List[TypeVar] = []
for tname, t in definitions.items():
bound = kt.typelike_from_ipce(t)
# noinspection PyTypeHints
if is_unconstrained(bound):
bound = None
# noinspection PyTypeHints
tv = TypeVar(tname, bound=bound)
typevars.append(tv)
if ID_ATT in t:
ieds.encountered[t[ID_ATT]] = tv
if typevars:
typevars2: Tuple[TypeVar, ...] = tuple(typevars)
from zuper_typing import Generic
# TODO: typevars
if PYTHON_36: # pragma: no cover
# noinspection PyUnresolvedReferences
# base = Generic.__getitem__(typevars2)
base = Generic.__class_getitem__(typevars2)
else:
# noinspection PyUnresolvedReferences
base = Generic.__class_getitem__(typevars2)
# ztinfo("", base=base, type_base=type(base))
bases = (base,)
else:
class B(metaclass=MyABC):
pass
bases = (B,)
Placeholder = type(f"PlaceholderFor{cls_name}", (), {})
ieds.encountered[schema_id] = Placeholder
fields_triples: List[Tuple[str, TypeLike, Field]] = [] # (name, type, Field)
if X_ORDER in res:
ordered = res[X_ORDER]
else:
ordered = list(properties) + list(classvars) + list(classatts)
# assert_equal(set(names), set(properties), msg=yaml.dump(res))
# else:
# names = list(properties)
#
# logger.info(f'reading {cls_name} names {names}')
# other_set_attr = {}
for pname in ordered:
if pname in properties:
v = properties[pname]
ptype = kt.typelike_from_ipce(v)
_Field = field()
_Field.name = pname
has_default = JSC_DEFAULT in v
if has_default:
default_value = kt.object_from_ipce(v[JSC_DEFAULT], ptype)
if isinstance(default_value, (list, dict, set)):
_Field.default_factory = MyDefaultFactory(default_value)
else:
_Field.default = default_value
assert not isinstance(default_value, dataclasses.Field)
# other_set_attr[pname] = default_value
else:
if not pname in required:
msg = (
f"Field {pname!r} is not required but I did not find a default"
)
raise ZException(msg, res=res)
fields_triples.append((pname, ptype, _Field))
elif pname in classvars:
v = classvars[pname]
ptype = kt.typelike_from_ipce(v)
# logger.info(f'ipce classvar: {pname} {ptype}')
f = field()
if pname in classatts:
f.default = kt.object_from_ipce(classatts[pname], object)
fields_triples.append((pname, ClassVar[ptype], f))
elif pname in classatts: # pragma: no cover
msg = f"Found {pname!r} in @classatts but not in @classvars"
raise ZValueError(msg, res=res, classatts=classatts, classvars=classvars)
else: # pragma: no cover
msg = f"Cannot find {pname!r} either in @properties or @classvars or @classatts."
raise ZValueError(
msg, properties=properties, classvars=classvars, classatts=classatts
)
check_fields_order(fields_triples)
# ztinfo('fields', fields_triples=fields_triples)
unsafe_hash = True
try:
T = make_dataclass(
cls_name,
fields_triples,
bases=bases,
namespace=None,
init=True,
repr=True,
eq=True,
order=True,
unsafe_hash=unsafe_hash,
frozen=False,
)
except TypeError: # pragma: no cover
#
# msg = "Cannot make dataclass with fields:"
# for f in fields:
# msg += f"\n {f}"
# logger.error(msg)
raise
fix_annotations_with_self_reference(T, cls_name, Placeholder)
for pname, v in classatts.items():
if isinstance(v, dict) and SCHEMA_ATT in v and v[SCHEMA_ATT] == SCHEMA_ID:
interpreted = kt.typelike_from_ipce(cast(JSONSchema, v))
else:
interpreted = kt.object_from_ipce(v, object)
assert not isinstance(interpreted, dataclasses.Field)
ztinfo("setting class att", pname=pname, interpreted=interpreted)
setattr(T, pname, interpreted)
if JSC_DESCRIPTION in res:
setattr(T, "__doc__", res[JSC_DESCRIPTION])
else:
# the original one did not have it
setattr(T, "__doc__", None)
setattr(T, "__module__", module_name)
setattr(T, "__qualname__", qual_name)
used = kt.used
if schema_id in used:
used.pop(schema_id)
if not used:
if iedo.remember_deserialized_classes:
remember_created_class(T, "typelike_from_ipce")
ieds.klasses[key] = T
else:
msg = f"Cannot remember {key} because used = {used}"
logger.warning(msg)
# logger.info(f"Estimated class {key} used = {used} ")
# assert not "varargs" in T.__dict__, T
# ztinfo("typelike_from_ipce", T=T, type_T=type(T), bases=bases)
return SRE(T, used)
from .logging import logger
from dataclasses import Field, MISSING
def field_has_default(f: Field) -> bool:
if f.default != MISSING:
return True
elif f.default_factory != MISSING:
return True
else:
return False
def check_fields_order(fields_triples: List[Tuple[str, TypeLike, Field]]):
found_default = None
for name, type_, f in fields_triples:
if is_ClassVar(type_):
continue
if field_has_default(f):
found_default = name
else:
if found_default:
msg = f"Found out of order fields. Field {name!r} without default found after {found_default!r}."
raise ZValueError(msg, fields_triples=fields_triples)
def fix_annotations_with_self_reference(
T: Type[dataclass], cls_name: str, Placeholder: type
) -> None:
# print('fix_annotations_with_self_reference')
# logger.info(f'fix_annotations_with_self_reference {cls_name}, placeholder: {Placeholder}')
# logger.info(f'encountered: {encountered}')
# logger.info(f'global_symbols: {global_symbols}')
def f(M: TypeLike) -> TypeLike:
assert not is_ForwardRef(M)
if M is Placeholder:
return T
# elif hasattr(M, '__name__') and M.__name__ == Placeholder.__name__:
# return T
else:
return M
f.__name__ = f"replacer_for_{cls_name}"
anns2 = {}
anns: dict = T.__annotations__
for k, v0 in anns.items():
v = recursive_type_subst(v0, f)
anns2[k] = v
T.__annotations__ = anns2
for f in dataclasses.fields(T):
f.type = T.__annotations__[f.name]
class MyDefaultFactory:
def __init__(self, value: object):
self.value = value
def __call__(self) -> object:
v = self.value
return type(v)(v) | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/conv_typelike_from_ipce.py | conv_typelike_from_ipce.py |
from typing import cast, Dict, List, Set, Tuple, Type, TypeVar
from zuper_ipce.types import is_unconstrained
from zuper_typing.aliases import TypeLike
from zuper_typing.annotations_tricks import (
get_FixedTupleLike_args,
get_Optional_arg,
get_Union_args,
get_VarTuple_arg,
is_FixedTupleLike,
is_Optional,
is_Union,
is_VarTuple,
)
from zuper_typing.exceptions import ZTypeError, ZValueError
from zuper_typing.my_dict import (
CustomDict,
CustomList,
CustomTuple,
get_CustomDict_args,
get_CustomList_arg,
get_CustomSet_arg,
get_CustomTuple_args,
get_DictLike_args,
get_ListLike_arg,
get_SetLike_arg,
is_CustomDict,
is_CustomList,
is_CustomSet,
is_CustomTuple,
is_DictLike,
is_ListLike,
is_SetLike,
)
X_ = TypeVar('X_')
def get_set_type_suggestion(x: set, st: TypeLike) -> TypeLike:
T = type(x)
if is_CustomSet(T):
return get_CustomSet_arg(T)
if is_SetLike(st):
st = cast(Type[Set], st)
V = get_SetLike_arg(st)
return V
elif is_unconstrained(st):
return object
else:
msg = "suggest_type does not make sense for a list"
raise ZTypeError(msg, suggest_type=st)
def get_list_type_suggestion(x: list, st: TypeLike) -> TypeLike:
T = type(x)
if is_CustomList(T):
T = cast(Type[CustomList], T)
return get_CustomList_arg(T)
# TODO: if it is custom dict
if is_unconstrained(st):
return object
elif is_ListLike(st):
T = cast(Type[List], st)
V = get_ListLike_arg(T)
return V
else:
msg = "suggest_type does not make sense for a list"
raise ZTypeError(msg, suggest_type=st, x=type(st))
def get_dict_type_suggestion(ob: dict, st: TypeLike) -> Tuple[TypeLike, TypeLike]:
""" Gets the type to use to serialize a dict.
Returns Dict[K, V], K, V
"""
T = type(ob)
if is_CustomDict(T):
# if it has the type information, then go for it
T = cast(Type[CustomDict], T)
K, V = get_CustomDict_args(T)
return K, V
if is_DictLike(st):
# There was a suggestion of Dict-like
st = cast(Type[Dict], st)
K, V = get_DictLike_args(st)
return K, V
elif is_unconstrained(st):
# Guess from the dictionary itself
K, V = guess_type_for_naked_dict(ob)
return K, V
else: # pragma: no cover
msg = f"@suggest_type does not make sense for a dict"
raise ZValueError(msg, ob=ob, suggest_type=st)
def is_UnionLike(x: TypeLike) -> bool:
return is_Union(x) or is_Optional(x)
def get_UnionLike_args(x: TypeLike) -> Tuple[TypeLike, ...]:
if is_Union(x):
return get_Union_args(x)
elif is_Optional(x):
y = get_Optional_arg(x)
if is_UnionLike(y):
return get_UnionLike_args(y) + (type(None),)
else:
assert False
def get_tuple_type_suggestion(x: tuple, st: TypeLike) -> Tuple[TypeLike, ...]:
if isinstance(x, CustomTuple):
return type(x).__tuple_types__
if is_CustomTuple(st):
st = cast(Type[CustomTuple], st)
return get_CustomTuple_args(st)
n = len(x)
if is_UnionLike(st):
options = get_UnionLike_args(st)
else:
options = (st,)
# first look for any tuple-like
for op in options:
if is_VarTuple(op):
op = cast(Type[Tuple[X_, ...]], op)
V = get_VarTuple_arg(op)
return tuple([V] * n)
if is_FixedTupleLike(op):
ts = get_FixedTupleLike_args(op)
return ts
for op in options:
if is_unconstrained(op):
return tuple([object] * n)
msg = f"@suggest_type does not make sense for a tuple"
raise ZValueError(msg, suggest_type=st)
def guess_type_for_naked_dict(ob: dict) -> Tuple[type, type]:
if not ob:
return object, object
type_values = tuple(type(_) for _ in ob.values())
type_keys = tuple(type(_) for _ in ob.keys())
if len(set(type_keys)) == 1:
K = type_keys[0]
else:
K = object
if len(set(type_values)) == 1:
V = type_values[0]
else:
V = object
return K, V | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/guesses.py | guesses.py |
import datetime
import inspect
import traceback
from dataclasses import Field, fields, is_dataclass, MISSING, replace
from decimal import Decimal
from typing import cast, Dict, Optional, Set, Type, TypeVar
import numpy as np
import yaml
from zuper_commons.fs import write_ustring_to_utf8_file
from zuper_ipce.constants import IPCE_PASS_THROUGH, REF_ATT
from zuper_ipce.conv_typelike_from_ipce import typelike_from_ipce_sr
from zuper_ipce.exceptions import ZDeserializationErrorSchema
from zuper_ipce.types import is_unconstrained
from zuper_typing.annotations_tricks import (
get_FixedTupleLike_args,
get_Optional_arg,
get_Union_args,
get_VarTuple_arg,
is_ClassVar,
is_FixedTupleLike,
is_Optional,
is_TupleLike,
is_TypeVar,
is_Union,
is_VarTuple,
)
from zuper_typing.exceptions import ZTypeError, ZValueError
from zuper_typing.my_dict import (
get_DictLike_args,
get_ListLike_arg,
get_SetLike_arg,
is_DictLike,
is_ListLike,
is_SetLike,
make_CustomTuple,
make_dict,
make_list,
make_set,
)
from zuper_typing.my_intersection import get_Intersection_args, is_Intersection
from .constants import (
HINTS_ATT,
IEDO,
IEDS,
JSC_TITLE,
JSC_TITLE_TYPE,
JSONSchema,
SCHEMA_ATT,
SCHEMA_ID,
)
from .numpy_encoding import numpy_array_from_ipce
from .structures import FakeValues
from .types import IPCE, TypeLike
DEBUGGING = False
_X = TypeVar("_X")
def object_from_ipce(
mj: IPCE, expect_type: Type[_X] = object, *, iedo: Optional[IEDO] = None
) -> _X:
assert expect_type is not None
if iedo is None:
iedo = IEDO(use_remembered_classes=False, remember_deserialized_classes=False)
ieds = IEDS({}, {})
try:
res = object_from_ipce_(mj, expect_type, ieds=ieds, iedo=iedo)
return res
except IPCE_PASS_THROUGH:
raise
except ZValueError as e:
msg = f"Cannot deserialize object"
if isinstance(mj, dict) and "$schema" in mj:
schema = mj["$schema"]
else:
schema = None
if DEBUGGING:
prefix = f"object_{id(mj)}"
fn = write_out_yaml(prefix + "_data", mj)
msg += f"\n object data in {fn}"
if schema:
fn = write_out_yaml(prefix + "_schema", schema)
msg += f"\n object schema in {fn}"
raise ZValueError(msg, expect_type=expect_type) from e
def object_from_ipce_(mj: IPCE, st: Type[_X] = object, *, ieds: IEDS, iedo: IEDO) -> _X:
# ztinfo('object_from_ipce_', mj=mj, st=st)
# if mj == {'ob': []}:
# raise ZException(mj=mj, st=st)
if is_Optional(st):
return object_from_ipce_optional(mj, st, ieds=ieds, iedo=iedo)
if is_Union(st):
return object_from_ipce_union(mj, st, ieds=ieds, iedo=iedo)
if is_Intersection(st):
return object_from_ipce_intersection(mj, st, ieds=ieds, iedo=iedo)
trivial = (int, float, bool, bytes, str, datetime.datetime, Decimal)
if st in trivial:
if not isinstance(mj, st):
msg = "Type mismatch for a simple type."
raise ZValueError(msg, expected=st, given_object=mj)
else:
return mj
if isinstance(mj, trivial):
T = type(mj)
if not is_unconstrained(st) and not is_TypeVar(st):
msg = f"Type mismatch"
raise ZValueError(msg, expected=st, given_object=mj)
return mj
if isinstance(mj, list):
return object_from_ipce_list(mj, st, ieds=ieds, iedo=iedo)
if mj is None:
if st is type(None):
return None
elif is_unconstrained(st):
return None
else:
msg = f"The value is None but the expected type is @expect_type."
raise ZValueError(msg, st=st)
assert isinstance(mj, dict), type(mj)
from .conv_typelike_from_ipce import typelike_from_ipce_sr
if mj.get(SCHEMA_ATT, "") == SCHEMA_ID or REF_ATT in mj:
schema = cast(JSONSchema, mj)
sr = typelike_from_ipce_sr(schema, ieds=ieds, iedo=iedo)
return sr.res
if mj.get(JSC_TITLE, None) == JSC_TITLE_TYPE:
schema = cast(JSONSchema, mj)
sr = typelike_from_ipce_sr(schema, ieds=ieds, iedo=iedo)
return sr.res
if SCHEMA_ATT in mj:
sa = mj[SCHEMA_ATT]
R = typelike_from_ipce_sr(sa, ieds=ieds, iedo=iedo)
K = R.res
# logger.debug(f' loaded K = {K} from {mj}')
else:
K = st
if K is np.ndarray:
return numpy_array_from_ipce(mj)
if is_DictLike(K):
K = cast(Type[Dict], K)
return object_from_ipce_dict(mj, K, ieds=ieds, iedo=iedo)
if is_SetLike(K):
K = cast(Type[Set], K)
res = object_from_ipce_SetLike(mj, K, ieds=ieds, iedo=iedo)
return res
if is_dataclass(K):
return object_from_ipce_dataclass_instance(mj, K, ieds=ieds, iedo=iedo)
if K is slice:
return object_from_ipce_slice(mj)
if is_unconstrained(K):
if looks_like_set(mj):
st = Set[object]
res = object_from_ipce_SetLike(mj, st, ieds=ieds, iedo=iedo)
return res
else:
msg = "No schema found and very ambiguous."
raise ZDeserializationErrorSchema(msg=msg, mj=mj, ieds=ieds)
# st = Dict[str, object]
#
# return object_from_ipce_dict(mj, st, ieds=ieds, opt=opt)
msg = f"Invalid type or type suggestion."
raise ZValueError(msg, K=K)
def looks_like_set(d: dict):
return len(d) > 0 and all(k.startswith("set:") for k in d)
def object_from_ipce_slice(mj) -> slice:
start = mj["start"]
stop = mj["stop"]
step = mj["step"]
return slice(start, stop, step)
def object_from_ipce_list(mj: IPCE, expect_type, *, ieds: IEDS, iedo: IEDO) -> IPCE:
def rec(x, TT: TypeLike) -> object:
return object_from_ipce_(x, TT, ieds=ieds, iedo=iedo)
# logger.info(f'expect_type for list is {expect_type}')
from zuper_ipce.conv_ipce_from_object import is_unconstrained
if is_unconstrained(expect_type):
suggest = object
seq = [rec(_, suggest) for _ in mj]
T = make_list(object)
return T(seq)
elif is_TupleLike(expect_type):
return object_from_ipce_tuple(mj, expect_type, ieds=ieds, iedo=iedo)
elif is_ListLike(expect_type):
suggest = get_ListLike_arg(expect_type)
seq = [rec(_, suggest) for _ in mj]
T = make_list(suggest)
return T(seq)
else:
msg = f"The object is a list, but expected different"
raise ZValueError(msg, expect_type=expect_type, mj=mj)
def object_from_ipce_optional(
mj: IPCE, expect_type: TypeLike, *, ieds: IEDS, iedo: IEDO
) -> IPCE:
if mj is None:
return mj
K = get_Optional_arg(expect_type)
return object_from_ipce_(mj, K, ieds=ieds, iedo=iedo)
def object_from_ipce_union(
mj: IPCE, expect_type: TypeLike, *, ieds: IEDS, iedo: IEDO
) -> IPCE:
errors = []
ts = get_Union_args(expect_type)
for T in ts:
try:
return object_from_ipce_(mj, T, ieds=ieds, iedo=iedo)
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException:
errors.append(dict(T=T, e=traceback.format_exc()))
msg = f"Cannot deserialize with any type."
fn = write_out_yaml(f"object{id(mj)}", mj)
msg += f"\n ipce in {fn}"
raise ZValueError(msg, ts=ts, errors=errors)
def object_from_ipce_intersection(
mj: IPCE, expect_type: TypeLike, *, ieds: IEDS, iedo: IEDO
) -> IPCE:
errors = {}
ts = get_Intersection_args(expect_type)
for T in ts:
try:
return object_from_ipce_(mj, T, ieds=ieds, iedo=iedo)
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException:
errors[str(T)] = traceback.format_exc()
msg = f"Cannot deserialize with any of @ts"
fn = write_out_yaml(f"object{id(mj)}", mj)
msg += f"\n ipce in {fn}"
raise ZValueError(msg, errors=errors, ts=ts)
def object_from_ipce_tuple(mj: IPCE, st: TypeLike, *, ieds: IEDS, iedo: IEDO):
if is_FixedTupleLike(st):
seq = []
ts = get_FixedTupleLike_args(st)
for st_i, ob in zip(ts, mj):
st_i = cast(Type[_X], st_i) # XXX should not be necessary
r = object_from_ipce_(ob, st_i, ieds=ieds, iedo=iedo)
seq.append(r)
T = make_CustomTuple(ts)
return T(seq)
elif is_VarTuple(st):
T = get_VarTuple_arg(st)
seq = []
for i, ob in enumerate(mj):
r = object_from_ipce_(ob, T, ieds=ieds, iedo=iedo)
seq.append(r)
return tuple(seq)
else:
assert False
def get_class_fields(K) -> Dict[str, Field]:
class_fields: Dict[str, Field] = {}
for f in fields(K):
class_fields[f.name] = f
return class_fields
def add_to_globals(ieds: IEDS, name: str, val: object) -> IEDS:
g = dict(ieds.global_symbols)
g[name] = val
return replace(ieds, global_symbols=g)
def object_from_ipce_dataclass_instance(
mj: IPCE, K: TypeLike, *, ieds: IEDS, iedo: IEDO
):
ieds = add_to_globals(ieds, K.__name__, K)
anns = getattr(K, "__annotations__", {})
attrs = {}
hints = mj.get(HINTS_ATT, {})
# ztinfo('hints', mj=mj, h=hints)
# logger.info(f'hints for {K.__name__} = {hints}')
for k, v in mj.items():
if k not in anns:
continue
et_k = anns[k]
if inspect.isabstract(et_k): # pragma: no cover
msg = f"Trying to instantiate abstract class for field {k!r} of class {K.__name__}."
raise ZValueError(msg, K=K, expect_type=et_k, mj=mj, annotation=anns[k])
if k in hints:
R = typelike_from_ipce_sr(hints[k], ieds=ieds, iedo=iedo)
hint = R.res
et_k = hint
else:
hint = None
try:
attrs[k] = object_from_ipce_(v, et_k, ieds=ieds, iedo=iedo)
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except ZValueError as e: # pragma: no cover
msg = f"Cannot deserialize attribute {k!r} of {K.__name__}."
raise ZValueError(
msg,
K_annotations=K.__annotations__,
expect_type=et_k,
ann_K=anns[k],
K_name=K.__name__,
) from e
# ztinfo(f'result for {k}', raw=v, hint = hint, et_k=et_k, attrs_k=attrs[k])
class_fields = get_class_fields(K)
for k, T in anns.items():
if is_ClassVar(T):
continue
if not k in mj:
f = class_fields[k]
if f.default != MISSING:
attrs[k] = f.default
elif f.default_factory != MISSING:
attrs[k] = f.default_factory()
else:
msg = (
f"Cannot find field {k!r} in data for class {K.__name__} "
f"and no default available"
)
raise ZValueError(msg, anns=anns, T=T, known=sorted(mj), f=f)
for k, v in attrs.items():
assert not isinstance(v, Field), (k, v)
try:
return K(**attrs)
except TypeError as e: # pragma: no cover
msg = f"Cannot instantiate type {K.__name__}."
raise ZTypeError(msg, K=K, attrs=attrs, bases=K.__bases__, fields=anns) from e
def ignore_aliases(self, data) -> bool:
_ = self
if data is None:
return True
if isinstance(data, tuple) and data == ():
return True
if isinstance(data, list) and len(data) == 0:
return True
if isinstance(data, (bool, int, float)):
return True
if isinstance(data, str) and len(data) < 10:
return True
safe = ["additionalProperties", "properties", "__module__"]
if isinstance(data, str) and data in safe:
return True
def write_out_yaml(prefix: str, v: object, no_aliases: bool = False) -> str:
if no_aliases:
yaml.Dumper.ignore_aliases = lambda _, data: True
else:
yaml.Dumper.ignore_aliases = ignore_aliases
# d = oyaml_dump(v)
d = yaml.dump(v)
fn = f"errors/{prefix}.yaml"
write_ustring_to_utf8_file(d, fn)
return fn
def object_from_ipce_dict(mj: IPCE, D: Type[Dict], *, ieds: IEDS, iedo: IEDO):
assert is_DictLike(D), D
K, V = get_DictLike_args(D)
D = make_dict(K, V)
ob = D()
attrs = {}
FV = FakeValues[K, V]
if isinstance(K, type) and (issubclass(K, str) or issubclass(K, int)):
et_V = V
else:
et_V = FV
for k, v in mj.items():
if k == SCHEMA_ATT:
continue
try:
attrs[k] = object_from_ipce_(v, et_V, ieds=ieds, iedo=iedo)
except (TypeError, NotImplementedError) as e: # pragma: no cover
msg = f'Cannot deserialize element at index "{k}".'
raise ZTypeError(msg, expect_type_V=et_V, v=v, D=D, mj_yaml=mj) from e
if isinstance(K, type) and issubclass(K, str):
ob.update(attrs)
return ob
elif isinstance(K, type) and issubclass(K, int):
attrs = {int(k): v for k, v in attrs.items()}
ob.update(attrs)
return ob
else:
for k, v in attrs.items():
# noinspection PyUnresolvedReferences
ob[v.real_key] = v.value
return ob
def object_from_ipce_SetLike(mj: IPCE, D: Type[Set], *, ieds: IEDS, iedo: IEDO):
V = get_SetLike_arg(D)
res = set()
# logger.info(f'loading SetLike wiht V = {V}')
for k, v in mj.items():
if k == SCHEMA_ATT:
continue
vob = object_from_ipce_(v, V, ieds=ieds, iedo=iedo)
# logger.info(f'loaded k = {k} vob = {vob}')
res.add(vob)
T = make_set(V)
return T(res) | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/conv_object_from_ipce.py | conv_object_from_ipce.py |
import copy
import dataclasses
import datetime
import warnings
from dataclasses import Field, is_dataclass, replace
from decimal import Decimal
from numbers import Number
from typing import (
cast,
Dict,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
)
import numpy as np
from zuper_ipce import IPCE
from zuper_typing import dataclass
from zuper_typing.aliases import TypeLike
from zuper_typing.annotations_tricks import (
get_Callable_info,
get_ClassVar_arg,
get_Dict_name_K_V,
get_fields_including_static,
get_FixedTupleLike_args,
get_FixedTupleLike_name,
get_ForwardRef_arg,
get_NewType_arg,
get_NewType_name,
get_Optional_arg,
get_Sequence_arg,
get_Set_name_V,
get_Tuple_name,
get_Type_arg,
get_TypeVar_bound,
get_TypeVar_name,
get_Union_args,
get_VarTuple_arg,
is_Any,
is_Callable,
is_ClassVar,
is_FixedTupleLike,
is_ForwardRef,
is_NewType,
is_Optional,
is_Sequence,
is_TupleLike,
is_Type,
is_TypeLike,
is_TypeVar,
is_Union,
is_VarTuple,
)
from zuper_typing.constants import BINDINGS_ATT, GENERIC_ATT2
from zuper_typing.exceptions import (
ZAssertionError,
ZNotImplementedError,
ZTypeError,
ZValueError,
)
from zuper_typing.my_dict import (
get_DictLike_args,
get_ListLike_arg,
get_ListLike_name,
get_SetLike_arg,
is_DictLike,
is_ListLike,
is_SetLike,
)
from zuper_typing.my_intersection import get_Intersection_args, is_Intersection
from zuper_typing.recursive_tricks import get_name_without_brackets
from .constants import (
ALL_OF,
ANY_OF,
ATT_PYTHON_NAME,
CALLABLE_ORDERING,
CALLABLE_RETURN,
ID_ATT,
IESO,
IPCE_PASS_THROUGH,
JSC_ADDITIONAL_PROPERTIES,
JSC_ARRAY,
JSC_BOOL,
JSC_DEFINITIONS,
JSC_DESCRIPTION,
JSC_INTEGER,
JSC_ITEMS,
JSC_NULL,
JSC_NUMBER,
JSC_OBJECT,
JSC_PROPERTIES,
JSC_PROPERTY_NAMES,
JSC_REQUIRED,
JSC_STRING,
JSC_TITLE,
JSC_TITLE_CALLABLE,
JSC_TITLE_DATETIME,
JSC_TITLE_DECIMAL,
JSC_TITLE_FLOAT,
JSC_TITLE_NUMPY,
JSC_TITLE_SLICE,
JSC_TITLE_TYPE,
JSC_TYPE,
JSONSchema,
ProcessingDict,
REF_ATT,
SCHEMA_ATT,
SCHEMA_BYTES,
SCHEMA_CID,
SCHEMA_ID,
X_CLASSATTS,
X_CLASSVARS,
X_ORDER,
X_PYTHON_MODULE_ATT,
)
from .ipce_spec import assert_canonical_ipce, sorted_dict_cbor_ord
from .schema_caching import (
get_ipce_from_typelike_cache,
set_ipce_from_typelike_cache,
TRE,
)
from .schema_utils import make_ref, make_url
from .structures import FakeValues
def ipce_from_typelike(
T: TypeLike,
*,
globals0: Optional[dict] = None,
processing: Optional[ProcessingDict] = None,
ieso: Optional[IESO] = None,
) -> JSONSchema:
if ieso is None:
ieso = IESO(with_schema=True)
if processing is None:
processing = {}
if globals0 is None:
globals0 = {}
c = IFTContext(globals0, processing, ())
tr = ipce_from_typelike_tr(T, c, ieso=ieso)
schema = tr.schema
assert_canonical_ipce(schema)
return schema
@dataclass
class IFTContext:
globals_: dict
processing: ProcessingDict
context: Tuple[str, ...]
def ipce_from_typelike_tr(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
if not is_TypeLike(T):
raise ValueError(T)
if hasattr(T, "__name__"):
if T.__name__ in c.processing:
ref = c.processing[T.__name__]
res = make_ref(ref)
return TRE(res, {T.__name__: ref})
if ieso.use_ipce_from_typelike_cache:
try:
return get_ipce_from_typelike_cache(T, c.processing)
except KeyError:
pass
try:
if T is type:
res = cast(
JSONSchema,
{
REF_ATT: SCHEMA_ID,
JSC_TITLE: JSC_TITLE_TYPE
# JSC_DESCRIPTION: T.__doc__
},
)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is type(None):
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TYPE: JSC_NULL})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if isinstance(T, type):
for klass in T.mro():
if klass.__name__.startswith("Generic"):
continue
if klass is object:
continue
globals2 = dict(c.globals_)
globals2[get_name_without_brackets(klass.__name__)] = klass
bindings = getattr(klass, BINDINGS_ATT, {})
for k, v in bindings.items():
if hasattr(v, "__name__") and v.__name__ not in globals2:
globals2[v.__name__] = v
globals2[k.__name__] = v
c = dataclasses.replace(c, globals_=globals2)
tr: TRE = ipce_from_typelike_tr_(T, c=c, ieso=ieso)
if ieso.use_ipce_from_typelike_cache:
set_ipce_from_typelike_cache(T, tr.used, tr.schema)
return tr
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except ValueError as e:
msg = "Cannot get schema for type @T"
raise ZValueError(msg, T=T, T_type=type(T), c=c) from e
except AssertionError as e:
msg = "Cannot get schema for type @T"
raise ZAssertionError(msg, T=T, T_type=type(T), c=c) from e
except BaseException as e:
msg = "Cannot get schema for @T"
raise ZTypeError(msg, T=T, c=c) from e
def ipce_from_typelike_DictLike(T: Type[Dict], c: IFTContext, ieso: IESO) -> TRE:
assert is_DictLike(T), T
K, V = get_DictLike_args(T)
res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT})
res[JSC_TITLE] = get_Dict_name_K_V(K, V)
if isinstance(K, type) and issubclass(K, str):
res[JSC_PROPERTIES] = {SCHEMA_ATT: {}} # XXX
tr = ipce_from_typelike_tr(V, c=c, ieso=ieso)
res[JSC_ADDITIONAL_PROPERTIES] = tr.schema
res[SCHEMA_ATT] = SCHEMA_ID
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
else:
res[JSC_PROPERTIES] = {SCHEMA_ATT: {}} # XXX
props = FakeValues[K, V]
tr = ipce_from_typelike_tr(props, c=c, ieso=ieso)
# logger.warning(f'props IPCE:\n\n {yaml.dump(tr.schema)}')
res[JSC_ADDITIONAL_PROPERTIES] = tr.schema
res[SCHEMA_ATT] = SCHEMA_ID
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
def ipce_from_typelike_SetLike(T: Type[Set], c: IFTContext, ieso: IESO) -> TRE:
assert is_SetLike(T), T
V = get_SetLike_arg(T)
res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT})
res[JSC_TITLE] = get_Set_name_V(V)
res[JSC_PROPERTY_NAMES] = SCHEMA_CID
tr = ipce_from_typelike_tr(V, c=c, ieso=ieso)
res[JSC_ADDITIONAL_PROPERTIES] = tr.schema
res[SCHEMA_ATT] = SCHEMA_ID
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
def ipce_from_typelike_TupleLike(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
assert is_TupleLike(T), T
used = {}
def f(x: TypeLike) -> JSONSchema:
tr = ipce_from_typelike_tr(x, c=c, ieso=ieso)
used.update(tr.used)
return tr.schema
if is_VarTuple(T):
T = cast(Type[Tuple], T)
items = get_VarTuple_arg(T)
res = cast(JSONSchema, {})
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_ARRAY
res[JSC_ITEMS] = f(items)
res[JSC_TITLE] = get_Tuple_name(T)
res = sorted_dict_cbor_ord(res)
return TRE(res, used)
elif is_FixedTupleLike(T):
T = cast(Type[Tuple], T)
args = get_FixedTupleLike_args(T)
res = cast(JSONSchema, {})
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_ARRAY
res[JSC_ITEMS] = []
res[JSC_TITLE] = get_FixedTupleLike_name(T)
for a in args:
res[JSC_ITEMS].append(f(a))
res = sorted_dict_cbor_ord(res)
return TRE(res, used)
else:
assert False
class KeepTrackSer:
def __init__(self, c: IFTContext, ieso: IESO):
self.c = c
self.ieso = ieso
self.used = {}
def ipce_from_typelike(self, T: TypeLike) -> JSONSchema:
tre = ipce_from_typelike_tr(T, c=self.c, ieso=self.ieso)
self.used.update(tre.used)
return tre.schema
# def ipce_from_object(self, x: IPCE, st: TypeLike) -> IPCE:
# from zuper_ipce.conv_ipce_from_object import ipce_from_object_
# res = object_from_ipce_(x, st, ieds=self.ieds, iedo=self.iedo)
# return res
def tre(self, x: IPCE) -> TRE:
return TRE(x, self.used)
def ipce_from_typelike_NewType(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
_ = c, ieso
name = get_NewType_name(T)
T0 = get_NewType_arg(T)
kt = KeepTrackSer(c, ieso)
res = cast(JSONSchema, {})
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = "NewType"
res["newtype"] = kt.ipce_from_typelike(T0)
res[JSC_TITLE] = name
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def ipce_from_typelike_ListLike(T: Type[List], c: IFTContext, ieso: IESO) -> TRE:
assert is_ListLike(T), T
items = get_ListLike_arg(T)
res = cast(JSONSchema, {})
kt = KeepTrackSer(c, ieso)
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_ARRAY
res[JSC_ITEMS] = kt.ipce_from_typelike(items)
res[JSC_TITLE] = get_ListLike_name(T)
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def ipce_from_typelike_Callable(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
assert is_Callable(T), T
cinfo = get_Callable_info(T)
kt = KeepTrackSer(c, ieso)
res = cast(
JSONSchema,
{
JSC_TYPE: JSC_OBJECT,
SCHEMA_ATT: SCHEMA_ID,
JSC_TITLE: JSC_TITLE_CALLABLE,
"special": "callable",
},
)
p = res[JSC_DEFINITIONS] = {}
for k, v in cinfo.parameters_by_name.items():
p[k] = kt.ipce_from_typelike(v)
p[CALLABLE_RETURN] = kt.ipce_from_typelike(cinfo.returns)
res[CALLABLE_ORDERING] = list(cinfo.ordering)
# print(res)
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def ipce_from_typelike_tr_(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
if T is None:
msg = "None is not a type!"
raise ZValueError(msg)
# This can actually happen inside a Tuple (or Dict, etc.) even though
# we have a special case for dataclass
if is_ForwardRef(T): # pragma: no cover
msg = "It is not supported to have an ForwardRef here yet."
raise ZValueError(msg, T=T)
if isinstance(T, str): # pragma: no cover
msg = "It is not supported to have a string here."
raise ZValueError(msg, T=T)
if T is str:
res = cast(JSONSchema, {JSC_TYPE: JSC_STRING, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is bool:
res = cast(JSONSchema, {JSC_TYPE: JSC_BOOL, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is Number:
res = cast(JSONSchema, {JSC_TYPE: JSC_NUMBER, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is float:
res = cast(
JSONSchema,
{JSC_TYPE: JSC_NUMBER, SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: JSC_TITLE_FLOAT},
)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is int:
res = cast(JSONSchema, {JSC_TYPE: JSC_INTEGER, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is slice:
return ipce_from_typelike_slice(ieso=ieso)
if T is Decimal:
res = cast(
JSONSchema,
{JSC_TYPE: JSC_STRING, JSC_TITLE: JSC_TITLE_DECIMAL, SCHEMA_ATT: SCHEMA_ID},
)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is datetime.datetime:
res = cast(
JSONSchema,
{
JSC_TYPE: JSC_STRING,
JSC_TITLE: JSC_TITLE_DATETIME,
SCHEMA_ATT: SCHEMA_ID,
},
)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is bytes:
res = SCHEMA_BYTES
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is object:
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: "object"})
res = sorted_dict_cbor_ord(res)
return TRE(res)
# we cannot use isinstance on typing.Any
if is_Any(T): # XXX not possible...
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: "Any"})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if is_Union(T):
return ipce_from_typelike_Union(T, c=c, ieso=ieso)
if is_Optional(T):
return ipce_from_typelike_Optional(T, c=c, ieso=ieso)
if is_DictLike(T):
T = cast(Type[Dict], T)
return ipce_from_typelike_DictLike(T, c=c, ieso=ieso)
if is_SetLike(T):
T = cast(Type[Set], T)
return ipce_from_typelike_SetLike(T, c=c, ieso=ieso)
if is_Intersection(T):
return ipce_from_typelike_Intersection(T, c=c, ieso=ieso)
if is_Callable(T):
return ipce_from_typelike_Callable(T, c=c, ieso=ieso)
if is_NewType(T):
return ipce_from_typelike_NewType(T, c=c, ieso=ieso)
if is_Sequence(T):
msg = "Translating Sequence into List"
warnings.warn(msg)
T = cast(Type[Sequence], T)
# raise ValueError(msg)
V = get_Sequence_arg(T)
T = List[V]
return ipce_from_typelike_ListLike(T, c=c, ieso=ieso)
if is_ListLike(T):
T = cast(Type[List], T)
return ipce_from_typelike_ListLike(T, c=c, ieso=ieso)
if is_TupleLike(T):
# noinspection PyTypeChecker
return ipce_from_typelike_TupleLike(T, c=c, ieso=ieso)
if is_Type(T):
TT = get_Type_arg(T)
r = ipce_from_typelike_tr(TT, c, ieso=ieso)
res = cast(
JSONSchema,
{SCHEMA_ATT: SCHEMA_ID, JSC_TYPE: "subtype", "subtype": r.schema},
)
res = sorted_dict_cbor_ord(res)
return TRE(res, r.used)
# raise NotImplementedError(T)
assert isinstance(T, type), (T, type(T), is_Optional(T), is_Union(T))
if is_dataclass(T):
return ipce_from_typelike_dataclass(T, c=c, ieso=ieso)
if T is np.ndarray:
return ipce_from_typelike_ndarray()
msg = "Cannot interpret the type @T"
raise ZValueError(msg, T=T, c=c)
def ipce_from_typelike_ndarray() -> TRE:
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID})
res[JSC_TYPE] = JSC_OBJECT
res[JSC_TITLE] = JSC_TITLE_NUMPY
properties = {"shape": {}, "dtype": {}, "data": SCHEMA_BYTES} # TODO # TODO
properties = sorted_dict_cbor_ord(properties)
res[JSC_PROPERTIES] = properties
res = sorted_dict_cbor_ord(res)
return TRE(res)
def ipce_from_typelike_slice(ieso: IESO) -> TRE:
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID})
res[JSC_TYPE] = JSC_OBJECT
res[JSC_TITLE] = JSC_TITLE_SLICE
c = IFTContext({}, {}, ())
tr = ipce_from_typelike_tr(Optional[int], c=c, ieso=ieso)
properties = {
"start": tr.schema, # TODO
"stop": tr.schema, # TODO
"step": tr.schema,
}
res[JSC_PROPERTIES] = sorted_dict_cbor_ord(properties)
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
def ipce_from_typelike_Intersection(T: TypeLike, c: IFTContext, ieso: IESO):
args = get_Intersection_args(T)
kt = KeepTrackSer(c, ieso)
options = [kt.ipce_from_typelike(t) for t in args]
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ALL_OF: options})
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def get_mentioned_names(T: TypeLike, context=()) -> Iterator[str]:
if T in context:
return
c2 = context + (T,)
if is_dataclass(T):
if context:
yield T.__name__
annotations = getattr(T, "__annotations__", {})
for v in annotations.values():
yield from get_mentioned_names(v, c2)
elif is_Type(T):
v = get_Type_arg(T)
yield from get_mentioned_names(v, c2)
elif is_TypeVar(T):
yield get_TypeVar_name(T)
elif is_FixedTupleLike(T):
for t in get_FixedTupleLike_args(T):
yield from get_mentioned_names(t, c2)
elif is_VarTuple(T):
t = get_VarTuple_arg(T)
yield from get_mentioned_names(t, c2)
elif is_ListLike(T):
T = cast(Type[List], T)
t = get_ListLike_arg(T)
yield from get_mentioned_names(t, c2)
elif is_DictLike(T):
T = cast(Type[Dict], T)
K, V = get_DictLike_args(T)
yield from get_mentioned_names(K, c2)
yield from get_mentioned_names(V, c2)
elif is_SetLike(T):
T = cast(Type[Set], T)
t = get_SetLike_arg(T)
yield from get_mentioned_names(t, c2)
elif is_ForwardRef(T):
return get_ForwardRef_arg(T)
elif is_Optional(T):
t = get_Optional_arg(T)
yield from get_mentioned_names(t, c2)
elif is_Union(T):
for t in get_Union_args(T):
yield from get_mentioned_names(t, c2)
else:
pass
def ipce_from_typelike_dataclass(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
assert is_dataclass(T), T
# noinspection PyDataclass
c = replace(
c,
globals_=dict(c.globals_),
processing=dict(c.processing),
context=c.context + (T.__name__,),
)
used = {}
def ftl(x: TypeLike) -> JSONSchema:
if not is_TypeLike(x):
raise ValueError(x)
tr = ipce_from_typelike_tr(x, c=c, ieso=ieso)
used.update(tr.used)
return tr.schema
def fob(x: object) -> IPCE:
return ipce_from_object(x, globals_=c.globals_, ieso=ieso)
def f(x: object) -> IPCE:
if is_TypeLike(x):
x = cast(TypeLike, x)
return ftl(x)
else:
return fob(x)
res = cast(JSONSchema, {})
mentioned = set(get_mentioned_names(T, ()))
relevant = [x for x in c.context if x in mentioned and x != T.__name__]
relevant.append(T.__qualname__)
url_name = "_".join(relevant)
my_ref = make_url(url_name)
res[ID_ATT] = my_ref
res[JSC_TITLE] = T.__name__
c.processing[T.__name__] = my_ref
res[ATT_PYTHON_NAME] = T.__qualname__
res[X_PYTHON_MODULE_ATT] = T.__module__
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_OBJECT
if hasattr(T, "__doc__") and T.__doc__:
res[JSC_DESCRIPTION] = T.__doc__
if hasattr(T, GENERIC_ATT2):
definitions = {}
types2 = getattr(T, GENERIC_ATT2)
for t2 in types2:
if not isinstance(t2, TypeVar):
continue
url = make_url(f"{T.__qualname__}/{t2.__name__}")
c.processing[f"{t2.__name__}"] = url
# noinspection PyTypeHints
t2_name = get_TypeVar_name(t2)
c.globals_[t2_name] = t2
bound = get_TypeVar_bound(t2)
# bound = t2.__bound__ or object
schema = ftl(bound)
schema = copy.copy(schema)
schema[ID_ATT] = url
schema = sorted_dict_cbor_ord(schema)
definitions[t2.__name__] = schema
c.globals_[t2.__name__] = t2
if definitions:
res[JSC_DEFINITIONS] = sorted_dict_cbor_ord(definitions)
properties = {}
classvars = {}
classatts = {}
required = []
all_fields: Dict[str, Field] = get_fields_including_static(T)
from .conv_ipce_from_object import ipce_from_object
original_order = list(all_fields)
ordered = sorted(all_fields)
for name in ordered:
afield = all_fields[name]
t = afield.type
try:
if isinstance(t, str): # pragma: no cover
# t = eval_just_string(t, c.globals_)
msg = "Before serialization, need to have all text references substituted."
msg += f"\n found reference {t!r} in class {T}."
raise Exception(msg)
if is_ClassVar(t):
tt = get_ClassVar_arg(t)
# logger.info(f'ClassVar found : {tt}')
if False and is_Type(tt):
u = get_Type_arg(tt)
if is_TypeVar(u):
tn = get_TypeVar_name(u)
if tn in c.processing:
ref = c.processing[tn]
schema = make_ref(ref)
classvars[name] = schema
used.update({tn: ref})
classatts[name] = ftl(type)
else: # pragma: no cover
msg = "Unknown typevar @tn in class @T"
raise ZNotImplementedError(msg, tn=tn, T=T, c=c)
else:
classvars[name] = ftl(u)
try:
the_att = get_T_attribute(T, name)
except AttributeError:
pass
else:
classatts[name] = f(the_att)
else:
classvars[name] = ftl(tt)
try:
the_att = get_T_attribute(T, name)
except AttributeError:
pass
else:
classatts[name] = f(the_att)
else: # not classvar
schema = ftl(t)
try:
default = get_field_default(afield)
except KeyError:
required.append(name)
else:
schema = make_schema_with_default(schema, default, c, ieso)
properties[name] = schema
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException as e:
msg = "Cannot write schema for attribute @name -> @t of type @T."
raise ZTypeError(msg, name=name, t=t, T=T) from e
if required: # empty is error
res[JSC_REQUIRED] = sorted(required)
if classvars:
res[X_CLASSVARS] = classvars
if classatts:
res[X_CLASSATTS] = classatts
assert len(classvars) >= len(classatts), (classvars, classatts)
if properties:
res[JSC_PROPERTIES] = sorted_dict_cbor_ord(properties)
res[X_ORDER] = original_order
if sorted_dict_cbor_ord:
res = sorted_dict_cbor_ord(res)
if T.__name__ in used:
used.pop(T.__name__)
return TRE(res, used)
def get_T_attribute(T: TypeLike, n: str) -> object:
if hasattr(T, n):
# special case
the_att2 = getattr(T, n)
if isinstance(the_att2, Field):
# actually attribute not there
raise AttributeError()
else:
return the_att2
else:
raise AttributeError()
def make_schema_with_default(
schema: JSONSchema, default: object, c: IFTContext, ieso: IESO
) -> JSONSchema:
from zuper_ipce import ipce_from_object
options = [schema]
s_u_one = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ANY_OF: options})
ipce_default = ipce_from_object(default, globals_=c.globals_, ieso=ieso)
s_u_one["default"] = ipce_default
s_u_one = sorted_dict_cbor_ord(s_u_one)
return s_u_one
from dataclasses import MISSING
def get_field_default(f: Field) -> object:
if f.default != MISSING:
return f.default
elif f.default_factory != MISSING:
return f.default_factory()
else:
raise KeyError("no default")
def ipce_from_typelike_Union(t: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
types = get_Union_args(t)
used = {}
def f(x: TypeLike) -> JSONSchema:
tr = ipce_from_typelike_tr(x, c=c, ieso=ieso)
used.update(tr.used)
return tr.schema
options = [f(t) for t in types]
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ANY_OF: options})
res = sorted_dict_cbor_ord(res)
return TRE(res, used)
def ipce_from_typelike_Optional(t: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
types = [get_Optional_arg(t), type(None)]
kt = KeepTrackSer(c, ieso)
options = [kt.ipce_from_typelike(t) for t in types]
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ANY_OF: options})
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
#
# def ipce_from_typelike_generic(T: Type, globals_: GlobalsDict, processing_: ProcessingDict) -> JSONSchema:
# assert hasattr(T, GENERIC_ATT2)
#
# types2 = getattr(T, GENERIC_ATT2)
# processing2 = dict(processing_)
# globals2 = dict(globals_)
#
# res = cast(JSONSchema, {})
# res[SCHEMA_ATT] = SCHEMA_ID
#
# res[JSC_TITLE] = T.__name__
# # res[ATT_PYTHON_NAME] = T.__qualname__
# res[X_PYTHON_MODULE_ATT] = T.__module__
#
# res[ID_ATT] = make_url(T.__name__)
#
# res[JSC_TYPE] = JSC_OBJECT
#
# processing2[f'{T.__name__}'] = make_ref(res[ID_ATT])
#
# # print(f'T: {T.__name__} ')
# definitions = {}
#
# if hasattr(T, '__doc__') and T.__doc__:
# res[JSC_DESCRIPTION] = T.__doc__
# globals_ = dict(globals_)
# for t2 in types2:
# if not isinstance(t2, TypeVar):
# continue
#
# url = make_url(f'{T.__name__}/{t2.__name__}')
#
# # processing2[f'~{name}'] = {'$ref': url}
# processing2[f'{t2.__name__}'] = make_ref(url)
# # noinspection PyTypeHints
# globals2[t2.__name__] = t2
#
# bound = t2.__bound__ or Any
# schema = ipce_from_typelike(bound, globals2, processing2)
# schema = copy.copy(schema)
# schema[ID_ATT] = url
#
# definitions[t2.__name__] = schema
#
# globals_[t2.__name__] = t2
#
# if definitions:
# res[JSC_DEFINITIONS] = definitions
# properties = {}
# required = []
#
# # names = list(T.__annotations__)
# # ordered = sorted(names)
# original_order = []
# for name, t in T.__annotations__.items():
# t = replace_typevars(t, bindings={}, symbols=globals_, rl=None)
# if is_ClassVar(t):
# continue
# try:
# result = eval_field(t, globals2, processing2)
# except PASS_THROUGH:
# raise
# except BaseException as e:
# msg = f'Cannot evaluate field "{name}" of class {T} annotated as {t}'
# raise Exception(msg) from e
# assert isinstance(result, Result), result
# properties[name] = result.schema
# original_order.append(name)
# if not result.optional:
# required.append(name)
# if required:
# res[JSC_REQUIRED] = sorted(required)
#
# sorted_vars = sorted(original_order)
# res[JSC_PROPERTIES] = {k: properties[k] for k in sorted_vars}
# res['order'] = original_order
# res = sorted_dict_with_cbor_ordering(res)
# return res
# @dataclasses.dataclass
# class Result:
# tre: TRE
# optional: Optional[bool] = False
#
# def __post_init__(self):
# assert isinstance(self.tre, TRE), self
# #
# # def __init__(self, tr: TRE, optional: bool = None):
# # self.schema = schema
# # self.optional = optional
#
# def eval_field(t, globals_: GlobalsDict, processing: ProcessingDict) -> Result:
# debug_info2 = lambda: dict(globals_=globals_, processing=processing)
#
# c = IFTContext(globals_=globals_, processing=processing, context=())
# if isinstance(t, str):
# te = eval_type_string(t, globals_, processing)
# return te
#
# if is_Type(t):
# res = cast(JSONSchema, make_ref(SCHEMA_ID))
# return Result(TRE(res))
#
# if is_TupleLike(t):
# tr = ipce_from_typelike_TupleLike(t, c)
# return Result(tr)
#
# if is_ListLike(t):
# tr = ipce_from_typelike_ListLike(t, c)
# return Result(tr)
#
# if is_DictLike(t):
# tr = ipce_from_typelike_dict(t, c)
# return Result(tr)
#
# if is_SetLike(t):
# tr = ipce_from_typelike_SetLike(t, c)
# return Result(tr)
#
# if is_ForwardRef(t):
# tn = get_ForwardRef_arg(t)
# return eval_type_string(tn, globals_, processing)
#
# if is_Optional(t):
# tt = get_Optional_arg(t)
# result = eval_field(tt, globals_, processing)
# return Result(result.tre, optional=True)
#
# if is_Union(t):
# return Result(ipce_from_typelike_Union(t, c))
#
# if is_Any(t):
# res = cast(JSONSchema, {'$schema': 'http://json-schema.org/draft-07/schema#'})
# return Result(TRE(res))
#
# if isinstance(t, TypeVar):
# l = t.__name__
# if l in processing:
# ref = processing[l]
# schema = make_ref(ref)
# return Result(TRE(schema, {l: ref}))
# # I am not sure why this is different in Python 3.6
# if PYTHON_36 and (l in globals_): # pragma: no cover
# T = globals_[l]
# tr = ipce_from_typelike_tr(T, c)
# return Result(tr)
#
# m = f'Could not resolve the TypeVar {t}'
# msg = pretty_dict(m, debug_info2())
# raise CannotResolveTypeVar(msg)
#
# if isinstance(t, type):
# # catch recursion here
# if t.__name__ in processing:
# return eval_field(t.__name__, globals_, processing)
# else:
# tr = ipce_from_typelike_tr(t, c)
# return Result(tr)
#
# msg = f'Could not deal with {t}'
# msg += f'\nglobals: {globals_}'
# msg += f'\nprocessing: {processing}'
# raise NotImplementedError(msg)
#
# def eval_type_string(t: str, globals_: GlobalsDict, processing: ProcessingDict) -> Result:
# check_isinstance(t, str)
# globals2 = dict(globals_)
# debug_info = lambda: dict(t=t, globals2=pretty_dict("", globals2), processing=pretty_dict("", processing))
#
# if t in processing:
# url = make_url(t)
# schema: JSONSchema = make_ref(url)
# return Result(TRE(schema, {t: url})) # XXX not sure
#
# elif t in globals2:
# return eval_field(globals2[t], globals2, processing)
# else:
# try:
# res = eval_just_string(t, globals2)
# return eval_field(res, globals2, processing)
# except NotImplementedError as e: # pragma: no cover
# m = 'While evaluating string'
# msg = pretty_dict(m, debug_info())
# raise NotImplementedError(msg) from e
# except PASS_THROUGH:
# raise
# except BaseException as e: # pragma: no cover
# m = 'Could not evaluate type string'
# msg = pretty_dict(m, debug_info())
# raise ValueError(msg) from e
#
#
# def eval_just_string(t: str, globals_):
# from typing import Optional
# eval_locals = {
# 'Optional': Optional, 'List': List,
# 'Dict': Dict, 'Union': Union, 'Set': typing.Set, 'Any': Any
# }
# # TODO: put more above?
# # do not pollute environment
# if t in globals_:
# return globals_[t]
# eval_globals = dict(globals_)
# try:
# res = eval(t, eval_globals, eval_locals)
# return res
# except PASS_THROUGH:
# raise
# except BaseException as e:
# m = f'Error while evaluating the string {t!r} using eval().'
# msg = pretty_dict(m, dict(eval_locals=eval_locals, eval_globals=eval_globals))
# raise type(e)(msg) from e | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/conv_ipce_from_typelike.py | conv_ipce_from_typelike.py |
import datetime
import traceback
from dataclasses import dataclass, Field, fields, is_dataclass, MISSING
from decimal import Decimal
from typing import cast, Dict, Iterator, Optional, Set, TypeVar
import numpy as np
from frozendict import frozendict
from zuper_ipce.guesses import (
get_dict_type_suggestion,
get_list_type_suggestion,
get_set_type_suggestion,
get_tuple_type_suggestion,
)
from zuper_ipce.types import is_unconstrained
from zuper_typing.my_dict import make_dict
X = TypeVar("X")
from zuper_typing.annotations_tricks import (
get_Optional_arg,
get_Union_args,
is_Optional,
is_SpecialForm,
is_Union,
)
from zuper_typing.exceptions import ZNotImplementedError, ZTypeError, ZValueError
from .constants import GlobalsDict, HINTS_ATT, SCHEMA_ATT, IESO, IPCE_PASS_THROUGH
from .conv_ipce_from_typelike import ipce_from_typelike, ipce_from_typelike_ndarray
from .ipce_spec import assert_canonical_ipce, sorted_dict_cbor_ord
from .structures import FakeValues
from .types import IPCE, TypeLike
def ipce_from_object(
ob: object,
suggest_type: TypeLike = object,
*,
globals_: GlobalsDict = None,
ieso: Optional[IESO] = None,
# with_schema: bool = True,
) -> IPCE:
# logger.debug(f'ipce_from_object({ob})')
if ieso is None:
ieso = IESO(with_schema=True)
if globals_ is None:
globals_ = {}
try:
res = ipce_from_object_(ob, suggest_type, globals_=globals_, ieso=ieso)
except TypeError as e:
msg = "ipce_from_object() for type @t failed."
raise ZTypeError(msg, ob=ob, T=type(ob)) from e
assert_canonical_ipce(res)
return res
def ipce_from_object_(
ob: object, st: TypeLike, *, globals_: GlobalsDict, ieso: IESO
) -> IPCE:
unconstrained = is_unconstrained(st)
if ob is None:
if unconstrained or (st is type(None)) or is_Optional(st):
return ob
else:
msg = f"ob is None but suggest_type is @suggest_type"
raise ZTypeError(msg, suggest_type=st)
if is_Optional(st):
assert ob is not None # from before
T = get_Optional_arg(st)
return ipce_from_object_(ob, T, globals_=globals_, ieso=ieso)
if is_Union(st):
return ipce_from_object_union(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, datetime.datetime):
if not ob.tzinfo:
msg = "Cannot serialize dates without a timezone."
raise ZValueError(msg, ob=ob)
trivial = (bool, int, str, float, bytes, Decimal, datetime.datetime)
if st in trivial:
if not isinstance(ob, st):
msg = "Expected this to be @suggest_type."
raise ZTypeError(msg, st=st, ob=ob, T=type(ob))
return ob
if isinstance(ob, trivial):
return ob
if isinstance(ob, list):
return ipce_from_object_list(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, tuple):
return ipce_from_object_tuple(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, slice):
return ipce_from_object_slice(ob, ieso=ieso)
if isinstance(ob, set):
return ipce_from_object_set(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, (dict, frozendict)):
return ipce_from_object_dict(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, type):
return ipce_from_typelike(ob, globals0=globals_, processing={}, ieso=ieso)
if is_SpecialForm(ob):
ob = cast(TypeLike, ob)
return ipce_from_typelike(ob, globals0=globals_, processing={}, ieso=ieso)
if isinstance(ob, np.ndarray):
return ipce_from_object_numpy(ob, ieso=ieso)
assert not isinstance(ob, type), ob
if is_dataclass(ob):
return ipce_from_object_dataclass_instance(ob, globals_=globals_, ieso=ieso)
msg = "I do not know a way to convert object @ob of type @T."
raise ZNotImplementedError(msg, ob=ob, T=type(ob))
def ipce_from_object_numpy(ob, *, ieso: IESO) -> IPCE:
from .numpy_encoding import ipce_from_numpy_array
res = ipce_from_numpy_array(ob)
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike_ndarray().schema
return res
def ipce_from_object_slice(ob, *, ieso: IESO):
from .conv_ipce_from_typelike import ipce_from_typelike_slice
res = {"start": ob.start, "step": ob.step, "stop": ob.stop}
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike_slice(ieso=ieso).schema
res = sorted_dict_cbor_ord(res)
return res
def ipce_from_object_union(ob: object, st: TypeLike, *, globals_, ieso: IESO) -> IPCE:
ts = get_Union_args(st)
errors = []
for Ti in ts:
try:
return ipce_from_object(ob, Ti, globals_=globals_, ieso=ieso)
except IPCE_PASS_THROUGH:
raise
except BaseException:
errors.append((Ti, traceback.format_exc()))
msg = "Cannot save union."
raise ZTypeError(msg, suggest_type=st, value=ob, errors=errors)
def ipce_from_object_list(ob, st: TypeLike, *, globals_: dict, ieso: IESO) -> IPCE:
assert st is not None
V = get_list_type_suggestion(ob, st)
def rec(x: X) -> X:
return ipce_from_object(x, V, globals_=globals_, ieso=ieso)
return [rec(_) for _ in ob]
def ipce_from_object_tuple(ob: tuple, st: TypeLike, *, globals_, ieso: IESO) -> IPCE:
ts = get_tuple_type_suggestion(ob, st)
res = []
for _, T in zip(ob, ts):
x = ipce_from_object(_, T, globals_=globals_, ieso=ieso)
res.append(x)
return res
@dataclass
class IterAtt:
attr: str
T: TypeLike
value: object
def has_default(f: Field):
if f.default != MISSING:
return True
elif f.default_factory != MISSING:
return True
else:
return False
def get_default(f: Field) -> object:
assert has_default(f)
if f.default != MISSING:
return f.default
elif f.default_factory != MISSING:
return f.default_factory()
assert False
def same_as_default(f: Field, value: object) -> bool:
if f.default != MISSING:
return f.default == value
elif f.default_factory != MISSING:
default = f.default_factory()
return default == value
else:
return False
def iterate_resolved_type_values_without_default(x: dataclass) -> Iterator[IterAtt]:
for f in fields(type(x)):
k = f.name
v0 = getattr(x, k)
if same_as_default(f, v0):
continue
k_st = f.type
yield IterAtt(k, k_st, v0)
def get_fields_values(x: dataclass) -> Dict[str, object]:
res = {}
T = type(x)
try:
fields_ = fields(T)
except:
raise ZValueError(T=T)
for f in fields_:
k = f.name
v0 = getattr(x, k)
res[k] = v0
return res
def ipce_from_object_dataclass_instance(ob: dataclass, *, globals_, ieso: IESO) -> IPCE:
globals_ = dict(globals_)
res = {}
T = type(ob)
from .conv_ipce_from_typelike import ipce_from_typelike
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike(T, globals0=globals_, ieso=ieso)
globals_[T.__name__] = T
H = make_dict(str, type)
hints = H()
for ia in iterate_resolved_type_values_without_default(ob):
k = ia.attr
v = ia.value
T = ia.T
try:
res[k] = ipce_from_object(v, T, globals_=globals_, ieso=ieso)
needs_schema = isinstance(v, (list, tuple))
if ieso.with_schema and needs_schema and is_unconstrained(T):
# hints[k] = ipce_from_typelike(type(v), globals0=globals_, ieso=ieso)
hints[k] = type(v)
except IPCE_PASS_THROUGH:
raise
except BaseException as e:
msg = (
f"Could not serialize an object. Problem "
f"occurred with the attribute {k!r}. It is supposed to be of type @expected."
)
raise ZValueError(msg, expected=T, ob=ob) from e
if hints:
res[HINTS_ATT] = ipce_from_object(hints, ieso=ieso)
res = sorted_dict_cbor_ord(res)
return res
def ipce_from_object_dict(ob: dict, st: TypeLike, *, globals_: GlobalsDict, ieso: IESO):
K, V = get_dict_type_suggestion(ob, st)
DT = Dict[K, V]
res = {}
from .conv_ipce_from_typelike import ipce_from_typelike
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike(DT, globals0=globals_, ieso=ieso)
if isinstance(K, type) and issubclass(K, str):
for k, v in ob.items():
res[k] = ipce_from_object(v, V, globals_=globals_, ieso=ieso)
elif isinstance(K, type) and issubclass(K, int):
for k, v in ob.items():
res[str(k)] = ipce_from_object(v, V, globals_=globals_, ieso=ieso)
else:
FV = FakeValues[K, V]
# group first by the type name, then sort by key
items = [(type(k).__name__, k, v) for k, v in ob.items()]
items = sorted(items)
for i, (_, k, v) in enumerate(items):
h = get_key_for_set_entry(i, len(ob))
fv = FV(k, v)
res[h] = ipce_from_object(fv, globals_=globals_, ieso=ieso)
res = sorted_dict_cbor_ord(res)
return res
def ipce_from_object_set(ob: set, st: TypeLike, *, globals_: GlobalsDict, ieso: IESO):
from .conv_ipce_from_typelike import ipce_from_typelike
V = get_set_type_suggestion(ob, st)
ST = Set[V]
res = {}
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike(ST, globals0=globals_, ieso=ieso)
# group first by the type name, then sort by key
items = [(type(v).__name__, v) for v in ob]
items = sorted(items)
for i, (_, v) in enumerate(items):
vj = ipce_from_object(v, V, globals_=globals_, ieso=ieso)
h = get_key_for_set_entry(i, len(ob))
res[h] = vj
res = sorted_dict_cbor_ord(res)
return res
def get_key_for_set_entry(i: int, n: int):
ndigits = len(str(n))
format = f"%0{ndigits}d"
x = format % i
return f"set:{x}" | zuper-ipce-z5 | /zuper-ipce-z5-5.3.0.tar.gz/zuper-ipce-z5-5.3.0/src/zuper_ipce/conv_ipce_from_object.py | conv_ipce_from_object.py |
import io
import json
import select
import time
import traceback
from io import BufferedReader
from json import JSONDecodeError
from typing import Iterator
import base58
import cbor2
from cbor2 import CBORDecodeEOF
from . import logger
from .json_utils import (
decode_bytes_before_json_deserialization,
encode_bytes_before_json_serialization,
)
from .utils_text import oyaml_dump
__all__ = [
"read_cbor_or_json_objects",
"json2cbor_main",
"cbor2json_main",
"cbor2yaml_main",
"read_next_cbor",
"read_next_either_json_or_cbor",
"tag_hook",
]
def json2cbor_main() -> None:
fo = open("/dev/stdout", "wb", buffering=0)
fi = open("/dev/stdin", "rb", buffering=0)
# noinspection PyTypeChecker
fi = BufferedReader(fi, buffer_size=1)
for j in read_cbor_or_json_objects(fi):
c = cbor2.dumps(j)
fo.write(c)
fo.flush()
def cbor2json_main() -> None:
fo = open("/dev/stdout", "wb", buffering=0)
fi = open("/dev/stdin", "rb", buffering=0)
for j in read_cbor_objects(fi):
j = encode_bytes_before_json_serialization(j)
ob = json.dumps(j)
ob = ob.encode("utf-8")
fo.write(ob)
fo.write(b"\n")
fo.flush()
def cbor2yaml_main() -> None:
fo = open("/dev/stdout", "wb")
fi = open("/dev/stdin", "rb")
for j in read_cbor_objects(fi):
ob = oyaml_dump(j)
ob = ob.encode("utf-8")
fo.write(ob)
fo.write(b"\n")
fo.flush()
def read_cbor_or_json_objects(f, timeout=None) -> Iterator:
""" Reads cbor or line-separated json objects from the binary file f."""
while True:
try:
ob = read_next_either_json_or_cbor(f, timeout=timeout)
yield ob
except StopIteration:
break
except TimeoutError:
raise
def read_cbor_objects(f, timeout=None) -> Iterator:
""" Reads cbor or line-separated json objects from the binary file f."""
while True:
try:
ob = read_next_cbor(f, timeout=timeout)
yield ob
except StopIteration:
break
except TimeoutError:
raise
def read_next_either_json_or_cbor(f, timeout=None, waiting_for: str = None) -> dict:
""" Raises StopIteration if it is EOF.
Raises TimeoutError if over timeout"""
fs = [f]
t0 = time.time()
intermediate_timeout = 3.0
while True:
try:
readyr, readyw, readyx = select.select(fs, [], fs, intermediate_timeout)
except io.UnsupportedOperation:
break
if readyr:
break
elif readyx:
logger.warning("Exceptional condition on input channel %s" % readyx)
else:
delta = time.time() - t0
if (timeout is not None) and (delta > timeout):
msg = "Timeout after %.1f s." % delta
logger.error(msg)
raise TimeoutError(msg)
else:
msg = "I have been waiting %.1f s." % delta
if timeout is None:
msg += " I will wait indefinitely."
else:
msg += " Timeout will occurr at %.1f s." % timeout
if waiting_for:
msg += " " + waiting_for
logger.warning(msg)
first = f.peek(1)[:1]
if len(first) == 0:
msg = "Detected EOF on %s." % f
if waiting_for:
msg += " " + waiting_for
raise StopIteration(msg)
# logger.debug(f'first char is {first}')
if first in [b" ", b"\n", b"{"]:
line = f.readline()
line = line.strip()
if not line:
msg = "Read empty line. Re-trying."
logger.warning(msg)
return read_next_either_json_or_cbor(f)
# logger.debug(f'line is {line!r}')
try:
j = json.loads(line)
except JSONDecodeError:
msg = f"Could not decode line {line!r}: {traceback.format_exc()}"
logger.error(msg)
return read_next_either_json_or_cbor(f)
j = decode_bytes_before_json_deserialization(j)
return j
else:
j = cbor2.load(f, tag_hook=tag_hook)
return j
def tag_hook(decoder, tag, shareable_index=None) -> dict:
if tag.tag != 42:
return tag
d = tag.value
val = base58.b58encode(d).decode("ascii")
val = "z" + val[1:]
return {"/": val}
def wait_for_data(f, timeout=None, waiting_for: str = None):
""" Raises StopIteration if it is EOF.
Raises TimeoutError if over timeout"""
# XXX: StopIteration not implemented
fs = [f]
t0 = time.time()
intermediate_timeout = 3.0
while True:
try:
readyr, readyw, readyx = select.select(fs, [], fs, intermediate_timeout)
except io.UnsupportedOperation:
break
if readyr:
break
elif readyx:
logger.warning(f"Exceptional condition on input channel {readyx}")
else:
delta = time.time() - t0
if (timeout is not None) and (delta > timeout):
msg = f"Timeout after {delta:.1f} s."
logger.error(msg)
raise TimeoutError(msg)
else:
msg = f"I have been waiting {delta:.1f} s."
if timeout is None:
msg += " I will wait indefinitely."
else:
msg += f" Timeout will occurr at {timeout:.1f} s."
if waiting_for:
msg += " " + waiting_for
logger.warning(msg)
def read_next_cbor(f, timeout=None, waiting_for: str = None) -> dict:
""" Raises StopIteration if it is EOF.
Raises TimeoutError if over timeout"""
wait_for_data(f, timeout, waiting_for)
try:
j = cbor2.load(f, tag_hook=tag_hook)
return j
except CBORDecodeEOF:
raise StopIteration from None
except OSError as e:
if e.errno == 29:
raise StopIteration from None
raise | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/json2cbor.py | json2cbor.py |
from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal
from typing import cast, Dict, NewType, Tuple
from zuper_typing import DictStrType, MyBytes
from .types import ModuleName, QualName
JSONSchema = NewType("JSONSchema", dict)
GlobalsDict = Dict[str, object]
ProcessingDict = Dict[str, str]
# EncounteredDict = Dict[str, object]
SCHEMA_ID = "http://json-schema.org/draft-07/schema#"
SCHEMA_ATT = "$schema"
HINTS_ATT = "$hints"
ANY_OF = "anyOf"
ALL_OF = "allOf"
ID_ATT = "$id"
REF_ATT = "$ref"
X_CLASSVARS = "classvars"
X_CLASSATTS = "classatts"
X_ORDER = "order"
JSC_FORMAT = "format"
JSC_REQUIRED = "required"
JSC_TYPE = "type"
JSC_ITEMS = "items"
JSC_DEFAULT = "default"
JSC_ENUM = "enum"
JSC_TITLE = "title"
JSC_NUMBER = "number"
JSC_INTEGER = "integer"
JSC_ARRAY = "array"
JSC_OBJECT = "object"
JSC_ADDITIONAL_PROPERTIES = "additionalProperties"
JSC_PROPERTY_NAMES = "propertyNames"
JSC_DESCRIPTION = "description"
JSC_STRING = "string"
JSC_NULL = "null"
JSC_BOOL = "boolean"
JSC_PROPERTIES = "properties"
JSC_DEFINITIONS = "definitions"
JSC_ALLOF = "allOf"
JSC_ANYOF = "anyOf"
# Z_ATT_LSIZE = "lsize"
# Z_ATT_TSIZE = "tsize"
X_ORIG = "__orig__"
# X_EXTRA = "__extra__"
# X_BINDINGS = "__bindings__"
X_PYTHON_MODULE_ATT = "__module__"
ATT_PYTHON_NAME = "__qualname__"
JSC_TITLE_NUMPY = "numpy"
JSC_TITLE_SLICE = "slice"
JSC_TITLE_BYTES = "bytes"
JSC_TITLE_DECIMAL = "decimal"
JSC_TITLE_FLOAT = "float"
JSC_TITLE_DATETIME = "datetime"
JSC_TITLE_CALLABLE = "Callable"
JSC_TITLE_TYPE = "type"
JSC_TITLE_CID = "cid"
# JSC_TITLE_TUPLE = 'Tuple'
# JSC_TITLE_LIST = 'List'
JSC_FORMAT_CID = "cid"
SCHEMA_BYTES = cast(
JSONSchema, {JSC_TYPE: JSC_STRING, JSC_TITLE: JSC_TITLE_BYTES, SCHEMA_ATT: SCHEMA_ID},
)
SCHEMA_CID = cast(
JSONSchema,
{
JSC_TYPE: JSC_STRING,
JSC_TITLE: JSC_TITLE_CID,
JSC_FORMAT: JSC_FORMAT_CID,
SCHEMA_ATT: SCHEMA_ID,
},
)
# IPCE_SCALARS = (bool, int, str, float, bytes, datetime, Decimal, type(None))
IPCE_TRIVIAL = (bool, int, str, float, bytes, datetime, Decimal, MyBytes)
IPCE_TRIVIAL_NONE = IPCE_TRIVIAL + (type(None),)
# check_types = False
CALLABLE_ORDERING = "ordering"
CALLABLE_RETURN = "return"
@dataclass
class IEDO:
use_remembered_classes: bool
remember_deserialized_classes: bool
@dataclass
class IEDS:
global_symbols: Dict[str, type]
encountered: Dict
klasses: Dict[Tuple[ModuleName, QualName], type] = field(default_factory=DictStrType)
@dataclass
class IESO:
use_ipce_from_typelike_cache: bool = True
with_schema: bool = True
IPCE_PASS_THROUGH = (
NotImplementedError,
KeyboardInterrupt,
MemoryError,
AttributeError,
NameError,
AttributeError,
# TypeError,
RecursionError,
RuntimeError,
) | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/constants.py | constants.py |
from dataclasses import is_dataclass
from typing import Dict, List, overload, Tuple, TypeVar
from zuper_commons.types import ZAssertionError, ZValueError
from .constants import JSONSchema
from .types import IPCE
D = TypeVar("D")
_V = TypeVar("_V")
__all__ = ["assert_canonical_ipce"]
@overload
def sorted_dict_cbor_ord(x: JSONSchema) -> JSONSchema:
...
@overload
def sorted_dict_cbor_ord(x: Dict[str, _V]) -> Dict[str, _V]:
...
def sorted_dict_cbor_ord(x: Dict[str, _V]) -> Dict[str, _V]:
if not isinstance(x, dict):
raise ZAssertionError(x=x)
res = dict(sorted(x.items(), key=key_dict))
# TODO
# assert_sorted_dict_cbor_ord(res)
return res
def key_dict(item: Tuple[str, object]) -> Tuple[int, str]:
k, v = item
return (len(k), k)
def key_list(k: str) -> Tuple[int, str]:
return (len(k), k)
def sorted_list_cbor_ord(x: List[str]) -> List[str]:
return sorted(x, key=key_list)
def assert_sorted_dict_cbor_ord(x: dict):
keys = list(x.keys())
keys2 = sorted_list_cbor_ord(keys)
if keys != keys2:
msg = f"x not sorted"
raise ZValueError(msg, keys=keys, keys2=keys2)
def assert_canonical_ipce(ob_ipce: IPCE, max_rec=2) -> None:
IPCL_LINKS = "$links"
IPCL_SELF = "$self"
if isinstance(ob_ipce, dict):
if "/" in ob_ipce:
msg = 'Cannot have "/" in here '
raise ZValueError(msg, ob_ipce=ob_ipce)
assert_sorted_dict_cbor_ord(ob_ipce)
if IPCL_LINKS in ob_ipce:
msg = f"Should have dropped the {IPCL_LINKS} part."
raise ZValueError(msg, ob_ipce=ob_ipce)
if IPCL_SELF in ob_ipce:
msg = f"Re-processing the {IPCL_LINKS}."
raise ZValueError(msg, ob_ipce=ob_ipce)
for k, v in ob_ipce.items():
assert not is_dataclass(v), ob_ipce
if max_rec > 0:
assert_canonical_ipce(v, max_rec=max_rec - 1)
elif isinstance(ob_ipce, list):
pass
elif isinstance(ob_ipce, tuple):
msg = "Tuple is not valid."
raise ZValueError(msg, ob_ipce=ob_ipce) | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/ipce_spec.py | ipce_spec.py |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Dict, Tuple
from zuper_commons.types import ZValueError
from .constants import JSONSchema, REF_ATT, SCHEMA_ATT, SCHEMA_ID
from .ipce_attr import make_key
from .ipce_spec import assert_canonical_ipce
def assert_canonical_schema(x: JSONSchema):
assert isinstance(x, dict)
if SCHEMA_ATT in x:
assert x[SCHEMA_ATT] in [SCHEMA_ID]
elif REF_ATT in x:
pass
else:
msg = f"No {SCHEMA_ATT} or {REF_ATT}"
raise ZValueError(msg, x=x)
assert_canonical_ipce(x)
# json.dumps(x) # try no bytes
@dataclass
class TRE:
schema: JSONSchema
used: Dict[str, str] = field(default_factory=dict)
def __post_init__(self) -> None:
try:
assert_canonical_schema(self.schema)
except ValueError as e: # pragma: no cover
msg = f"Invalid schema"
raise ZValueError(msg, schema=self.schema) from e
class IPCETypelikeCache:
c: Dict[Tuple, Dict[Tuple, JSONSchema]] = defaultdict(dict)
# def get_cached():
# return {k[1]: [x for x, _ in v.items()] for k, v in IPCETypelikeCache.c.items()}
def get_ipce_from_typelike_cache(T, context: Dict[str, str]) -> TRE:
k = make_key(T)
if k not in IPCETypelikeCache.c:
raise KeyError()
items = list(IPCETypelikeCache.c[k].items())
# actually first look for the ones with more context
items.sort(key=lambda x: len(x[1]), reverse=True)
for context0, schema in items:
if compatible(context0, context):
# if context0:
# logger.debug(f'Returning cached {T} with context {context0}')
return TRE(schema, dict(context0))
raise KeyError()
def compatible(c0: Tuple[Tuple[str, str]], context: Dict[str, str]) -> bool:
for k, v in c0:
if k not in context or context[k] != v:
return False
return True
def set_ipce_from_typelike_cache(T, context: Dict[str, str], schema: JSONSchema):
k = make_key(T)
ci = tuple(sorted(context.items()))
IPCETypelikeCache.c[k][ci] = schema | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/schema_caching.py | schema_caching.py |
import dataclasses
import datetime
from dataclasses import dataclass, field, Field, make_dataclass, MISSING
from decimal import Decimal
from numbers import Number
from typing import (
Any,
Callable,
cast,
ClassVar,
Dict,
List,
NewType,
Optional,
Tuple,
Type,
TypeVar,
)
import numpy as np
from zuper_commons.types import (
check_isinstance,
ZException,
ZNotImplementedError,
ZTypeError,
ZValueError,
)
from zuper_typing import (
DataclassInfo,
get_remembered_class,
is_ClassVar,
is_ForwardRef,
is_placeholder,
make_dict,
make_Intersection,
make_list,
make_Literal,
make_set,
make_Tuple,
make_Union,
make_VarTuple,
MyABC,
MyNamedArg,
PYTHON_36,
recursive_type_subst,
remember_created_class,
set_dataclass_info,
)
from . import logger
from .constants import (
ATT_PYTHON_NAME,
CALLABLE_ORDERING,
CALLABLE_RETURN,
ID_ATT,
IEDO,
IEDS,
JSC_ADDITIONAL_PROPERTIES,
JSC_ALLOF,
JSC_ANYOF,
JSC_ARRAY,
JSC_BOOL,
JSC_DEFAULT,
JSC_DEFINITIONS,
JSC_DESCRIPTION,
JSC_ENUM,
JSC_INTEGER,
JSC_NULL,
JSC_NUMBER,
JSC_OBJECT,
JSC_PROPERTIES,
JSC_REQUIRED,
JSC_STRING,
JSC_TITLE,
JSC_TITLE_BYTES,
JSC_TITLE_CALLABLE,
JSC_TITLE_DATETIME,
JSC_TITLE_DECIMAL,
JSC_TITLE_FLOAT,
JSC_TITLE_NUMPY,
JSC_TITLE_SLICE,
JSC_TYPE,
JSONSchema,
REF_ATT,
SCHEMA_ATT,
SCHEMA_ID,
X_CLASSATTS,
X_CLASSVARS,
X_ORDER,
X_ORIG,
X_PYTHON_MODULE_ATT,
)
from .structures import CannotFindSchemaReference
from .types import IPCE, is_unconstrained, TypeLike
_X = TypeVar("_X")
@dataclass
class SRE:
res: TypeLike
used: Dict[str, object] = dataclasses.field(default_factory=dict)
# XXX: same class?
@dataclass
class SRO:
res: object
used: Dict[str, object] = dataclasses.field(default_factory=dict)
def typelike_from_ipce(schema0: JSONSchema, *, iedo: Optional[IEDO] = None) -> TypeLike:
if iedo is None:
iedo = IEDO(use_remembered_classes=False, remember_deserialized_classes=False)
ieds = IEDS({}, {})
sre = typelike_from_ipce_sr(schema0, ieds=ieds, iedo=iedo)
#
# try:
# assert_equivalent_types(sre.res, sre.res)
# except Exception as e:
# raise ZValueError(sre=sre) from e
return sre.res
def typelike_from_ipce_sr(schema0: JSONSchema, *, ieds: IEDS, iedo: IEDO) -> SRE:
try:
sre = typelike_from_ipce_sr_(schema0, ieds=ieds, iedo=iedo)
assert isinstance(sre, SRE), (schema0, sre)
res = sre.res
except (TypeError, ValueError) as e: # pragma: no cover
msg = "Cannot interpret schema as a type."
raise ZTypeError(msg, schema0=schema0) from e
if ID_ATT in schema0:
schema_id = schema0[ID_ATT]
ieds.encountered[schema_id] = res
return sre
def typelike_from_ipce_sr_(schema0: JSONSchema, *, ieds: IEDS, iedo: IEDO) -> SRE:
# pprint('schema_to_type_', schema0=schema0)
# encountered = encountered or {}
check_isinstance(schema0, dict)
schema = cast(JSONSchema, dict(schema0))
# noinspection PyUnusedLocal
metaschema = schema.pop(SCHEMA_ATT, None)
schema_id = schema.pop(ID_ATT, None)
if schema_id:
if not JSC_TITLE in schema:
pass
else:
cls_name = schema[JSC_TITLE]
ieds.encountered[schema_id] = cls_name
if JSC_ENUM in schema0:
schema1 = dict(schema0)
enum = schema1.pop(JSC_ENUM)
schema1 = cast(JSONSchema, schema1)
return typelike_from_ipce_enum(schema1, enum, ieds=ieds, iedo=iedo)
if schema == {JSC_TITLE: "Any"}:
return SRE(Any)
if schema == {}:
return SRE(object)
if schema == {JSC_TITLE: "object"}:
return SRE(object)
if REF_ATT in schema:
r = schema[REF_ATT]
if r == SCHEMA_ID:
if schema.get(JSC_TITLE, "") == "type":
return SRE(type)
else: # pragma: no cover
raise ZNotImplementedError(schema=schema)
# return SRE(Type)
if r in ieds.encountered:
res = ieds.encountered[r]
if is_placeholder(res):
used = {r: res}
else:
used = {}
return SRE(res, used=used)
else:
msg = f"Cannot evaluate reference {r!r}"
raise CannotFindSchemaReference(msg, ieds=ieds)
if JSC_ANYOF in schema:
return typelike_from_ipce_Union(schema, ieds=ieds, iedo=iedo)
if JSC_ALLOF in schema:
return typelike_from_ipce_Intersection(schema, ieds=ieds, iedo=iedo)
jsc_type = schema.get(JSC_TYPE, None)
jsc_title = schema.get(JSC_TITLE, "-not-provided-")
if jsc_title == JSC_TITLE_NUMPY:
res = np.ndarray
return SRE(res)
if jsc_type == "NewType":
kt = KeepTrackDes(ieds, iedo)
if "newtype" not in schema:
original = object
else:
nt = schema["newtype"]
tre = typelike_from_ipce_sr(nt, ieds=ieds, iedo=iedo)
original = tre.res
res = NewType(jsc_title, original)
return kt.sre(res)
if jsc_type == JSC_STRING:
if jsc_title == JSC_TITLE_BYTES:
return SRE(bytes)
elif jsc_title == JSC_TITLE_DATETIME:
return SRE(datetime.datetime)
elif jsc_title == JSC_TITLE_DECIMAL:
return SRE(Decimal)
else:
return SRE(str)
elif jsc_type == JSC_NULL:
return SRE(type(None))
elif jsc_type == JSC_BOOL:
return SRE(bool)
elif jsc_type == JSC_NUMBER:
if jsc_title == JSC_TITLE_FLOAT:
return SRE(float)
else:
return SRE(Number)
elif jsc_type == JSC_INTEGER:
return SRE(int)
elif jsc_type == "subtype":
s = schema["subtype"]
r = typelike_from_ipce_sr(s, ieds=ieds, iedo=iedo)
T = Type[r.res]
return SRE(T, r.used)
elif jsc_type == JSC_OBJECT:
if jsc_title == JSC_TITLE_CALLABLE:
return typelike_from_ipce_Callable(schema, ieds=ieds, iedo=iedo)
elif jsc_title.startswith("Dict["):
return typelike_from_ipce_DictType(schema, ieds=ieds, iedo=iedo)
elif jsc_title.startswith("Set["):
return typelike_from_ipce_SetType(schema, ieds=ieds, iedo=iedo)
elif jsc_title == JSC_TITLE_SLICE:
return SRE(slice)
else:
return typelike_from_ipce_dataclass(schema, schema_id=schema_id, ieds=ieds, iedo=iedo)
elif jsc_type == JSC_ARRAY:
return typelike_from_ipce_array(schema, ieds=ieds, iedo=iedo)
msg = "Cannot recover schema"
raise ZValueError(msg, schema=schema)
# assert False, schema # pragma: no cover
def typelike_from_ipce_enum(schema: JSONSchema, enum: List[object], *, ieds: IEDS, iedo: IEDO):
kt = KeepTrackDes(ieds, iedo)
T = kt.typelike_from_ipce(schema)
values = [kt.object_from_ipce(_, T) for _ in enum]
res = make_Literal(*tuple(values))
return kt.sre(res)
def typelike_from_ipce_Union(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
options = schema[JSC_ANYOF]
kt = KeepTrackDes(ieds, iedo)
args = [kt.typelike_from_ipce(_) for _ in options]
if args and args[-1] is type(None):
V = args[0]
res = Optional[V]
else:
res = make_Union(*args)
return kt.sre(res)
def typelike_from_ipce_Intersection(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
options = schema[JSC_ALLOF]
kt = KeepTrackDes(ieds, iedo)
args = [kt.typelike_from_ipce(_) for _ in options]
res = make_Intersection(tuple(args))
return kt.sre(res)
class KeepTrackDes:
def __init__(self, ieds: IEDS, iedo: IEDO):
self.ieds = ieds
self.iedo = iedo
self.used = {}
def typelike_from_ipce(self, x: IPCE):
sre = typelike_from_ipce_sr(x, ieds=self.ieds, iedo=self.iedo)
self.used.update(sre.used)
return sre.res
def object_from_ipce(self, x: IPCE, st: Type[_X] = object) -> _X:
from .conv_object_from_ipce import object_from_ipce_
res = object_from_ipce_(x, st, ieds=self.ieds, iedo=self.iedo)
return res
def sre(self, x: IPCE) -> SRE:
return SRE(x, self.used)
def typelike_from_ipce_array(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
assert schema[JSC_TYPE] == JSC_ARRAY
items = schema["items"]
kt = KeepTrackDes(ieds, iedo)
if isinstance(items, list):
# assert len(items) > 0
args = tuple([kt.typelike_from_ipce(_) for _ in items])
res = make_Tuple(*args)
else:
if schema[JSC_TITLE].startswith("Tuple["):
V = kt.typelike_from_ipce(items)
res = make_VarTuple(V)
else:
V = kt.typelike_from_ipce(items)
res = make_list(V)
# logger.info(f'found list like: {res}')
return kt.sre(res)
def typelike_from_ipce_DictType(schema, *, ieds: IEDS, iedo: IEDO) -> SRE:
K = str
kt = KeepTrackDes(ieds, iedo)
V = kt.typelike_from_ipce(schema[JSC_ADDITIONAL_PROPERTIES])
# pprint(f'here:', d=dict(V.__dict__))
# if issubclass(V, FakeValues):
if isinstance(V, type) and V.__name__.startswith("FakeValues"):
K = V.__annotations__["real_key"]
V = V.__annotations__["value"]
try:
D = make_dict(K, V)
except (TypeError, ValueError) as e: # pragma: no cover
msg = f"Cannot reconstruct dict type."
raise ZTypeError(msg, K=K, V=V, ieds=ieds) from e
return kt.sre(D)
def typelike_from_ipce_SetType(schema, *, ieds: IEDS, iedo: IEDO):
if not JSC_ADDITIONAL_PROPERTIES in schema: # pragma: no cover
msg = f"Expected {JSC_ADDITIONAL_PROPERTIES!r} in @schema."
raise ZValueError(msg, schema=schema)
kt = KeepTrackDes(ieds, iedo)
V = kt.typelike_from_ipce(schema[JSC_ADDITIONAL_PROPERTIES])
res = make_set(V)
return kt.sre(res)
def typelike_from_ipce_Callable(schema: JSONSchema, *, ieds: IEDS, iedo: IEDO):
kt = KeepTrackDes(ieds, iedo)
schema = dict(schema)
definitions = dict(schema[JSC_DEFINITIONS])
ret = kt.typelike_from_ipce(definitions.pop(CALLABLE_RETURN))
others = []
for k in schema[CALLABLE_ORDERING]:
d = kt.typelike_from_ipce(definitions[k])
if not looks_like_int(k):
d = MyNamedArg(d, k)
others.append(d)
# noinspection PyTypeHints
res = Callable[others, ret]
# logger.info(f'typelike_from_ipce_Callable: {schema} \n others = {others}\n res = {res}')
return kt.sre(res)
def looks_like_int(k: str) -> bool:
try:
int(k)
except:
return False
else:
return True
def typelike_from_ipce_dataclass(
res: JSONSchema, schema_id: Optional[str], *, ieds: IEDS, iedo: IEDO
) -> SRE:
kt = KeepTrackDes(ieds, iedo)
assert res[JSC_TYPE] == JSC_OBJECT
cls_name = res[JSC_TITLE]
definitions = res.get(JSC_DEFINITIONS, {})
# bindings_ipce = res.get(X_BINDINGS, {})
required = res.get(JSC_REQUIRED, [])
properties = res.get(JSC_PROPERTIES, {})
classvars = res.get(X_CLASSVARS, {})
classatts = res.get(X_CLASSATTS, {})
if (not X_PYTHON_MODULE_ATT in res) or (not ATT_PYTHON_NAME in res): # pragma: no cover
msg = f"Cannot find attributes for {cls_name!r}."
raise ZValueError(msg, res=res)
module_name = res[X_PYTHON_MODULE_ATT]
qual_name = res[ATT_PYTHON_NAME]
key = (module_name, qual_name)
if iedo.use_remembered_classes:
try:
res = get_remembered_class(module_name, qual_name)
return SRE(res)
except KeyError:
pass
if key in ieds.klasses:
return SRE(ieds.klasses[key], {})
typevars: List[TypeVar] = []
typevars_dict: Dict[str, type] = {}
for tname, t in definitions.items():
bound = kt.typelike_from_ipce(t)
# noinspection PyTypeHints
if is_unconstrained(bound):
bound = None
# noinspection PyTypeHints
tv = TypeVar(tname, bound=bound)
typevars_dict[tname] = tv
typevars.append(tv)
if ID_ATT in t:
ieds.encountered[t[ID_ATT]] = tv
if typevars:
typevars2: Tuple[TypeVar, ...] = tuple(typevars)
from zuper_typing import Generic
# TODO: typevars
if PYTHON_36: # pragma: no cover
# noinspection PyUnresolvedReferences
# base = Generic.__getitem__(typevars2)
base = Generic.__class_getitem__(typevars2)
else:
# noinspection PyUnresolvedReferences
base = Generic.__class_getitem__(typevars2)
# ztinfo("", base=base, type_base=type(base))
bases = (base,)
else:
class B(metaclass=MyABC):
pass
bases = (B,)
Placeholder = type(f"PlaceholderFor{cls_name}", (), {})
ieds.encountered[schema_id] = Placeholder
fields_triples: List[Tuple[str, TypeLike, Field]] = [] # (name, type, Field)
if X_ORDER in res:
ordered = res[X_ORDER]
else:
ordered = list(properties) + list(classvars) + list(classatts)
# assert_equal(set(names), set(properties), msg=yaml.dump(res))
# else:
# names = list(properties)
#
# logger.info(f'reading {cls_name} names {names}')
# other_set_attr = {}
for pname in ordered:
if pname in properties:
v = properties[pname]
ptype = kt.typelike_from_ipce(v)
_Field = field()
_Field.name = pname
has_default = JSC_DEFAULT in v
if has_default:
default_value = kt.object_from_ipce(v[JSC_DEFAULT], ptype)
if isinstance(default_value, (list, dict, set)):
_Field.default_factory = MyDefaultFactory(default_value)
else:
_Field.default = default_value
assert not isinstance(default_value, dataclasses.Field)
# other_set_attr[pname] = default_value
else:
if not pname in required:
msg = f"Field {pname!r} is not required but I did not find a default"
raise ZException(msg, res=res)
fields_triples.append((pname, ptype, _Field))
elif pname in classvars:
v = classvars[pname]
ptype = kt.typelike_from_ipce(v)
# logger.info(f'ipce classvar: {pname} {ptype}')
f = field()
if pname in classatts:
f.default = kt.object_from_ipce(classatts[pname], object)
fields_triples.append((pname, ClassVar[ptype], f))
elif pname in classatts: # pragma: no cover
msg = f"Found {pname!r} in @classatts but not in @classvars"
raise ZValueError(msg, res=res, classatts=classatts, classvars=classvars)
else: # pragma: no cover
msg = f"Cannot find {pname!r} either in @properties or @classvars or @classatts."
raise ZValueError(msg, properties=properties, classvars=classvars, classatts=classatts)
check_fields_order(fields_triples)
# ztinfo('fields', fields_triples=fields_triples)
unsafe_hash = True
try:
T = make_dataclass(
cls_name,
fields_triples,
bases=bases,
namespace=None,
init=True,
repr=True,
eq=True,
order=True,
unsafe_hash=unsafe_hash,
frozen=False,
)
except TypeError: # pragma: no cover
#
# msg = "Cannot make dataclass with fields:"
# for f in fields:
# msg += f"\n {f}"
# logger.error(msg)
raise
setattr(T, "__name__", cls_name)
# logger.info("before fix_anno\n" + debug_print(dict(T=T, ieds=ieds)))
fix_annotations_with_self_reference(T, cls_name, Placeholder)
for pname, v in classatts.items():
if isinstance(v, dict) and SCHEMA_ATT in v and v[SCHEMA_ATT] == SCHEMA_ID:
interpreted = kt.typelike_from_ipce(cast(JSONSchema, v))
else:
interpreted = kt.object_from_ipce(v, object)
assert not isinstance(interpreted, dataclasses.Field)
# logger.info("setting class att", pname, interpreted)
setattr(T, pname, interpreted)
if JSC_DESCRIPTION in res:
setattr(T, "__doc__", res[JSC_DESCRIPTION])
else:
# we don't want the stock dataclass
setattr(T, "__doc__", None)
# logger.info(f"Did find __doc__ for {T.__name__} {id(T)}")
# else:
# logger.error(f"Did not find __doc__ for {T.__name__} {id(T)}", res=res)
# # the original one did not have it
# # setattr(T, "__doc__", None)
# raise ValueError()
setattr(T, "__module__", module_name)
setattr(T, "__qualname__", qual_name)
used = kt.used
if schema_id in used:
used.pop(schema_id)
if not used:
if iedo.remember_deserialized_classes:
remember_created_class(T, "typelike_from_ipce")
ieds.klasses[key] = T
else:
msg = f"Cannot remember {key} because used = {used}"
logger.warning(msg)
# logger.info(f"Estimated class {key} used = {used} ")
# assert not "varargs" in T.__dict__, T
# ztinfo("typelike_from_ipce", T=T, type_T=type(T), bases=bases)
# bindings = {}
# for tname, t in bindings_ipce.items():
# u = make_TypeVar(tname)
# bindings[u] = kt.typelike_from_ipce(t)
orig = res.get(X_ORIG, [])
# extra = res.get(X_EXTRA, [])
#
# def make_tv(tname: str) -> type:
# if tname in typevars_dict:
# return typevars_dict[tname]
# else:
# return make_TypeVar(tname)
clsi_orig = []
for o in orig:
oT = kt.typelike_from_ipce(o)
clsi_orig.append(oT)
# clsi_orig = tuple(make_tv(_) for _ in orig)
clsi_orig = tuple(clsi_orig)
# clsi_extra = tuple(make_tv(_) for _ in extra)
clsi = DataclassInfo(
name=cls_name,
# bindings=bindings,
orig=clsi_orig,
)
# extra=clsi_extra)
set_dataclass_info(T, clsi)
# try:
# assert_equivalent_types(T,T)
# except Exception as e:
# msg = 'I did not create a well-formed class'
# raise ZAssertionError(msg, T=T, used=used, ieds=ieds) from e
return SRE(T, used)
def field_has_default(f: Field) -> bool:
if f.default != MISSING:
return True
elif f.default_factory != MISSING:
return True
else:
return False
def check_fields_order(fields_triples: List[Tuple[str, TypeLike, Field]]):
found_default = None
for name, type_, f in fields_triples:
if is_ClassVar(type_):
continue
if field_has_default(f):
found_default = name
else:
if found_default:
msg = (
f"Found out of order fields. Field {name!r} without default found after "
f"{found_default!r}."
)
raise ZValueError(msg, fields_triples=fields_triples)
def fix_annotations_with_self_reference(
T: Type[dataclass], cls_name: str, Placeholder: type
) -> None:
# print('fix_annotations_with_self_reference')
# logger.info(f'fix_annotations_with_self_reference {cls_name}, placeholder: {Placeholder}')
# logger.info(f'encountered: {encountered}')
# logger.info(f'global_symbols: {global_symbols}')
def f(M: TypeLike) -> TypeLike:
assert not is_ForwardRef(M)
if M is Placeholder:
return T
if hasattr(M, "__name__") and "Placeholder" in M.__name__:
pass
# logger.debug('Found this placeholder', M=M, T=T, Placeholder=Placeholder)
if hasattr(M, "__name__") and M.__name__ == Placeholder.__name__:
# logger.debug('Placeholder of different class')
return T
# elif hasattr(M, '__name__') and M.__name__ == Placeholder.__name__:
# return T
else:
return M
f.__name__ = f"replacer_for_{cls_name}"
anns2 = {}
anns: dict = T.__annotations__
items = list(anns.items())
for k, v0 in items:
anns2[k] = recursive_type_subst(v0, f)
del k, v0
T.__annotations__ = anns2
for fi in dataclasses.fields(T):
fi.type = T.__annotations__[fi.name]
# if T.__name__ == 'FailedResult':
#
# logger.info('substituted', anns=anns, anns2=anns2)
class MyDefaultFactory:
def __init__(self, value: object):
self.value = value
def __call__(self) -> object:
v = self.value
return type(v)(v) | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/conv_typelike_from_ipce.py | conv_typelike_from_ipce.py |
from typing import cast, Dict, List, Set, Tuple, Type, TypeVar
from zuper_commons.types import ZTypeError, ZValueError
from zuper_typing import (
CustomDict,
CustomList,
CustomSet,
CustomTuple,
get_CustomDict_args,
get_CustomList_arg,
get_CustomSet_arg,
get_CustomTuple_args,
get_DictLike_args,
get_FixedTupleLike_args,
get_ListLike_arg,
get_Optional_arg,
get_SetLike_arg,
get_Union_args,
get_VarTuple_arg,
is_CustomDict,
is_CustomList,
is_CustomSet,
is_CustomTuple,
is_DictLike,
is_FixedTupleLike,
is_ListLike,
is_Optional,
is_SetLike,
is_Union,
is_VarTuple,
TypeLike,
)
from .types import is_unconstrained
X_ = TypeVar("X_")
def get_set_type_suggestion(x: set, st: TypeLike) -> TypeLike:
T = type(x)
if is_CustomSet(T):
T = cast(Type[CustomSet], T)
return get_CustomSet_arg(T)
if is_SetLike(st):
st = cast(Type[Set], st)
V = get_SetLike_arg(st)
return V
elif is_unconstrained(st):
return object
else: # pragma: no cover
msg = "suggest_type does not make sense for a list"
raise ZTypeError(msg, suggest_type=st)
def get_list_type_suggestion(x: list, st: TypeLike) -> TypeLike:
T = type(x)
if is_CustomList(T):
T = cast(Type[CustomList], T)
return get_CustomList_arg(T)
# TODO: if it is custom dict
if is_unconstrained(st):
return object
elif is_ListLike(st):
T = cast(Type[List], st)
V = get_ListLike_arg(T)
return V
else:
msg = "suggest_type does not make sense for a list"
raise ZTypeError(msg, suggest_type=st, x=type(st))
def get_dict_type_suggestion(ob: dict, st: TypeLike) -> Tuple[type, type]:
""" Gets the type to use to serialize a dict.
Returns Dict[K, V], K, V
"""
T = type(ob)
if is_CustomDict(T):
# if it has the type information, then go for it
T = cast(Type[CustomDict], T)
K, V = get_CustomDict_args(T)
return K, V
if is_DictLike(st):
# There was a suggestion of Dict-like
st = cast(Type[Dict], st)
K, V = get_DictLike_args(st)
return K, V
elif is_unconstrained(st):
# Guess from the dictionary itself
K, V = guess_type_for_naked_dict(ob)
return K, V
else: # pragma: no cover
msg = f"@suggest_type does not make sense for a dict"
raise ZValueError(msg, ob=ob, suggest_type=st)
def is_UnionLike(x: TypeLike) -> bool:
return is_Union(x) or is_Optional(x)
def get_UnionLike_args(x: TypeLike) -> Tuple[TypeLike, ...]:
if is_Union(x):
return get_Union_args(x)
elif is_Optional(x):
y = get_Optional_arg(x)
if is_UnionLike(y):
return get_UnionLike_args(y) + (type(None),)
return (y,)
else:
assert False
def get_tuple_type_suggestion(x: tuple, st: TypeLike) -> Tuple[TypeLike, ...]:
if is_UnionLike(st):
raise ZValueError("Does not support unions here", x=x, st=st)
# if isinstance(x, CustomTuple):
# return type(x).__tuple_types__
if is_CustomTuple(st):
st = cast(Type[CustomTuple], st)
return get_CustomTuple_args(st)
n = len(x)
# options = get_UnionLike_args(st)
# else:
# options = (st,)
# first look for any tufor op in options:
if is_VarTuple(st):
st = cast(Type[Tuple[X_, ...]], st)
V = get_VarTuple_arg(st)
return tuple([V] * n)
if is_FixedTupleLike(st):
st = cast(Type[Tuple], st)
ts = get_FixedTupleLike_args(st)
return ts
if is_unconstrained(st):
return tuple([object] * n)
msg = f"@suggest_type does not make sense for a tuple"
raise ZValueError(msg, suggest_type=st)
def guess_type_for_naked_dict(ob: dict) -> Tuple[type, type]:
if not ob:
return object, object
type_values = tuple(type(_) for _ in ob.values())
type_keys = tuple(type(_) for _ in ob.keys())
if len(set(type_keys)) == 1:
K = type_keys[0]
else:
K = object
if len(set(type_values)) == 1:
V = type_values[0]
else:
V = object
return K, V | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/guesses.py | guesses.py |
import inspect
import traceback
from dataclasses import Field, fields, is_dataclass, MISSING, replace
from typing import cast, Dict, Optional, Set, Tuple, Type, TypeVar
import numpy as np
import yaml
from zuper_commons.fs import write_ustring_to_utf8_file
from zuper_commons.types import ZTypeError, ZValueError
from zuper_ipce.types import get_effective_type
from zuper_typing import (
get_DictLike_args,
get_FixedTupleLike_args,
get_Intersection_args,
get_ListLike_arg,
get_Literal_args,
get_NewType_arg,
get_Optional_arg,
get_SetLike_arg,
get_Union_args,
get_VarTuple_arg,
is_ClassVar,
is_DictLike,
is_FixedTupleLike,
is_Intersection,
is_ListLike,
is_Literal,
is_NewType,
is_Optional,
is_SetLike,
is_TupleLike,
is_TypeVar,
is_Union,
is_VarTuple,
lift_to_customtuple_type,
make_CustomTuple,
make_dict,
make_list,
make_set,
)
from .constants import (
HINTS_ATT,
IEDO,
IEDS,
IPCE_PASS_THROUGH,
IPCE_TRIVIAL,
JSC_TITLE,
JSC_TITLE_TYPE,
JSONSchema,
REF_ATT,
SCHEMA_ATT,
SCHEMA_ID,
)
from .conv_typelike_from_ipce import typelike_from_ipce_sr
from .exceptions import ZDeserializationErrorSchema
from .numpy_encoding import numpy_array_from_ipce
from .structures import FakeValues
from .types import IPCE, is_unconstrained, TypeLike
DEBUGGING = False
_X = TypeVar("_X")
def object_from_ipce(
mj: IPCE, expect_type: Type[_X] = object, *, iedo: Optional[IEDO] = None
) -> _X:
assert expect_type is not None
if iedo is None:
iedo = IEDO(use_remembered_classes=False, remember_deserialized_classes=False)
ieds = IEDS({}, {})
try:
res = object_from_ipce_(mj, expect_type, ieds=ieds, iedo=iedo)
return res
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except ZValueError as e:
msg = f"Cannot deserialize object"
if isinstance(mj, dict) and "$schema" in mj:
schema = mj["$schema"]
else:
schema = None
if DEBUGGING: # pragma: no cover
prefix = f"object_{id(mj)}"
fn = write_out_yaml(prefix + "_data", mj)
msg += f"\n object data in {fn}"
if schema:
fn = write_out_yaml(prefix + "_schema", schema)
msg += f"\n object schema in {fn}"
raise ZValueError(msg, expect_type=expect_type, mj=mj) from e
def object_from_ipce_(mj: IPCE, st: Type[_X], *, ieds: IEDS, iedo: IEDO) -> _X:
# ztinfo('object_from_ipce_', mj=mj, st=st)
# if mj == {'ob': []}:
# raise ZException(mj=mj, st=st)
if is_NewType(st):
st = get_NewType_arg(st)
if is_Optional(st):
return object_from_ipce_optional(mj, st, ieds=ieds, iedo=iedo)
if is_Union(st):
return object_from_ipce_union(mj, st, ieds=ieds, iedo=iedo)
if is_Intersection(st):
return object_from_ipce_intersection(mj, st, ieds=ieds, iedo=iedo)
if st in IPCE_TRIVIAL:
if not isinstance(mj, st):
msg = "Type mismatch for a simple type."
raise ZValueError(msg, expected=st, given_object=mj)
else:
return mj
if isinstance(mj, IPCE_TRIVIAL):
# T = type(mj)
if is_Literal(st): # TODO: put in IPCL as well
values = get_Literal_args(st)
if not mj in values:
msg = "mismatch"
raise ZValueError(msg, expected=st, given=mj)
else:
if not is_unconstrained(st) and not is_TypeVar(st):
msg = f"Type mismatch"
raise ZValueError(msg, expected=st, given_object=mj)
return mj
if isinstance(mj, list):
return object_from_ipce_list(mj, st, ieds=ieds, iedo=iedo)
if mj is None:
if st is type(None):
return None
elif is_unconstrained(st):
return None
else:
msg = f"The value is None but the expected type is @expect_type."
raise ZValueError(msg, st=st)
assert isinstance(mj, dict), type(mj)
from .conv_typelike_from_ipce import typelike_from_ipce_sr
if mj.get(SCHEMA_ATT, "") == SCHEMA_ID or REF_ATT in mj:
schema = cast(JSONSchema, mj)
sr = typelike_from_ipce_sr(schema, ieds=ieds, iedo=iedo)
return sr.res
if mj.get(JSC_TITLE, None) == JSC_TITLE_TYPE:
schema = cast(JSONSchema, mj)
sr = typelike_from_ipce_sr(schema, ieds=ieds, iedo=iedo)
return sr.res
if SCHEMA_ATT in mj:
sa = mj[SCHEMA_ATT]
R = typelike_from_ipce_sr(sa, ieds=ieds, iedo=iedo)
K = R.res
if R.used:
msg = "An open type - not good."
raise ZValueError(msg, sre=R)
# logger.debug(f' loaded K = {K} from {mj}')
else:
K = st
if K is np.ndarray:
return numpy_array_from_ipce(mj)
if is_DictLike(K):
K = cast(Type[Dict], K)
return object_from_ipce_dict(mj, K, ieds=ieds, iedo=iedo)
if is_SetLike(K):
K = cast(Type[Set], K)
res = object_from_ipce_SetLike(mj, K, ieds=ieds, iedo=iedo)
return res
if is_dataclass(K):
return object_from_ipce_dataclass_instance(mj, K, ieds=ieds, iedo=iedo)
if K is slice:
return object_from_ipce_slice(mj)
if is_unconstrained(K):
if looks_like_set(mj):
st = Set[object]
res = object_from_ipce_SetLike(mj, st, ieds=ieds, iedo=iedo)
return res
else:
msg = "No schema found and very ambiguous."
raise ZDeserializationErrorSchema(msg=msg, mj=mj, ieds=ieds, st=st)
# st = Dict[str, object]
#
# return object_from_ipce_dict(mj, st, ieds=ieds, opt=opt)
msg = f"Invalid type or type suggestion."
raise ZValueError(msg, K=K)
def looks_like_set(d: dict):
return len(d) > 0 and all(k.startswith("set:") for k in d)
def object_from_ipce_slice(mj) -> slice:
start = mj["start"]
stop = mj["stop"]
step = mj["step"]
return slice(start, stop, step)
def object_from_ipce_list(mj: IPCE, expect_type, *, ieds: IEDS, iedo: IEDO) -> IPCE:
def rec(x, TT: TypeLike) -> object:
return object_from_ipce_(x, TT, ieds=ieds, iedo=iedo)
# logger.info(f'expect_type for list is {expect_type}')
from .conv_ipce_from_object import is_unconstrained
if is_unconstrained(expect_type):
suggest = object
seq = [rec(_, suggest) for _ in mj]
T = make_list(object)
# noinspection PyArgumentList
return T(seq)
elif is_TupleLike(expect_type):
return object_from_ipce_tuple(mj, expect_type, ieds=ieds, iedo=iedo)
elif is_ListLike(expect_type):
suggest = get_ListLike_arg(expect_type)
seq = [rec(_, suggest) for _ in mj]
T = make_list(suggest)
# noinspection PyArgumentList
return T(seq)
else:
msg = f"The object is a list, but expected different"
raise ZValueError(msg, expect_type=expect_type, mj=mj)
def object_from_ipce_optional(mj: IPCE, expect_type: TypeLike, *, ieds: IEDS, iedo: IEDO) -> IPCE:
if mj is None:
return mj
K = get_Optional_arg(expect_type)
return object_from_ipce_(mj, K, ieds=ieds, iedo=iedo)
def object_from_ipce_union(mj: IPCE, expect_type: TypeLike, *, ieds: IEDS, iedo: IEDO) -> IPCE:
errors = []
ts = get_Union_args(expect_type)
for T in ts:
try:
return object_from_ipce_(mj, T, ieds=ieds, iedo=iedo)
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException:
errors.append(dict(T=T, e=traceback.format_exc()))
msg = f"Cannot deserialize with any type."
fn = write_out_yaml(f"object{id(mj)}", mj)
msg += f"\n ipce in {fn}"
raise ZValueError(msg, ts=ts, errors=errors)
def object_from_ipce_intersection(
mj: IPCE, expect_type: TypeLike, *, ieds: IEDS, iedo: IEDO
) -> IPCE:
errors = {}
ts = get_Intersection_args(expect_type)
for T in ts:
try:
return object_from_ipce_(mj, T, ieds=ieds, iedo=iedo)
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException:
errors[str(T)] = traceback.format_exc()
if True: # pragma: no cover
msg = f"Cannot deserialize with any of @ts"
fn = write_out_yaml(f"object{id(mj)}", mj)
msg += f"\n ipce in {fn}"
raise ZValueError(msg, errors=errors, ts=ts)
def object_from_ipce_tuple(mj: IPCE, st: TypeLike, *, ieds: IEDS, iedo: IEDO) -> Tuple:
if is_FixedTupleLike(st):
st = cast(Type[Tuple], st)
seq = []
ts = get_FixedTupleLike_args(st)
for st_i, ob in zip(ts, mj):
st_i = cast(Type[_X], st_i) # XXX should not be necessary
r = object_from_ipce_(ob, st_i, ieds=ieds, iedo=iedo)
seq.append(r)
T = make_CustomTuple(ts)
# noinspection PyArgumentList
return T(seq)
elif is_VarTuple(st):
st = cast(Type[Tuple], st)
T = get_VarTuple_arg(st)
seq = []
for i, ob in enumerate(mj):
r = object_from_ipce_(ob, T, ieds=ieds, iedo=iedo)
seq.append(r)
r = tuple(seq)
try:
return lift_to_customtuple_type(r, T)
except BaseException as e:
raise ZValueError(mj=mj, st=st) from e
else:
assert False
def get_class_fields(K) -> Dict[str, Field]:
class_fields: Dict[str, Field] = {}
for f in fields(K):
class_fields[f.name] = f
return class_fields
def add_to_globals(ieds: IEDS, name: str, val: object) -> IEDS:
g = dict(ieds.global_symbols)
g[name] = val
return replace(ieds, global_symbols=g)
def object_from_ipce_dataclass_instance(mj: IPCE, K: TypeLike, *, ieds: IEDS, iedo: IEDO):
ieds = add_to_globals(ieds, K.__name__, K)
anns = getattr(K, "__annotations__", {})
attrs = {}
hints = mj.get(HINTS_ATT, {})
# ztinfo('hints', mj=mj, h=hints)
# logger.info(f'hints for {K.__name__} = {hints}')
for k, v in mj.items():
if k not in anns:
continue
et_k = anns[k]
if inspect.isabstract(et_k): # pragma: no cover
msg = f"Trying to instantiate abstract class for field {k!r} of class {K.__name__}."
raise ZValueError(msg, K=K, expect_type=et_k, mj=mj, annotation=anns[k])
if k in hints:
R = typelike_from_ipce_sr(hints[k], ieds=ieds, iedo=iedo)
hint = R.res
et_k = hint
#
# else:
# hint = None
try:
attrs[k] = object_from_ipce_(v, et_k, ieds=ieds, iedo=iedo)
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except ZValueError as e: # pragma: no cover
msg = f"Cannot deserialize attribute {k!r} of {K.__name__}."
raise ZValueError(
msg,
K_annotations=K.__annotations__,
expect_type=et_k,
ann_K=anns[k],
K_name=K.__name__,
) from e
# ztinfo(f'result for {k}', raw=v, hint = hint, et_k=et_k, attrs_k=attrs[k])
class_fields = get_class_fields(K)
for k, T in anns.items():
if is_ClassVar(T):
continue
if not k in mj:
f = class_fields[k]
if f.default != MISSING:
attrs[k] = f.default
elif f.default_factory != MISSING:
attrs[k] = f.default_factory()
else:
msg = (
f"Cannot find field {k!r} in data for class {K.__name__} "
f"and no default available"
)
raise ZValueError(msg, anns=anns, T=T, known=sorted(mj), f=f)
for k, v in attrs.items():
assert not isinstance(v, Field), (k, v)
try:
return K(**attrs)
except TypeError as e: # pragma: no cover
msg = f"Cannot instantiate type {K.__name__}."
raise ZTypeError(msg, K=K, attrs=attrs, bases=K.__bases__, fields=anns) from e
def ignore_aliases(self, data) -> bool:
_ = self
if data is None:
return True
if isinstance(data, tuple) and data == ():
return True
if isinstance(data, list) and len(data) == 0:
return True
if isinstance(data, (bool, int, float)):
return True
if isinstance(data, str) and len(data) < 10:
return True
safe = ["additionalProperties", "properties", "__module__"]
if isinstance(data, str) and data in safe:
return True
return False
def write_out_yaml(prefix: str, v: object, no_aliases: bool = False, ansi=False) -> str:
if no_aliases:
yaml.Dumper.ignore_aliases = lambda _, data: True
else:
yaml.Dumper.ignore_aliases = ignore_aliases
# d = oyaml_dump(v)
if isinstance(v, str):
d = v
else:
d = yaml.dump(v)
if ansi:
fn = f"errors/{prefix}.ansi"
else:
fn = f"errors/{prefix}.yaml"
write_ustring_to_utf8_file(d, fn)
return fn
def object_from_ipce_dict(mj: IPCE, D: Type[Dict], *, ieds: IEDS, iedo: IEDO):
assert is_DictLike(D), D
K, V = get_DictLike_args(D)
D = make_dict(K, V)
ob = D()
attrs = {}
# TODO: reflect in ipcl
if is_NewType(K):
K = get_NewType_arg(K)
FV = FakeValues[K, V]
if isinstance(K, type) and (issubclass(K, str) or issubclass(K, int)):
et_V = V
else:
et_V = FV
for k, v in mj.items():
if k == SCHEMA_ATT:
continue
try:
attrs[k] = object_from_ipce_(v, et_V, ieds=ieds, iedo=iedo)
except (TypeError, NotImplementedError) as e: # pragma: no cover
msg = f'Cannot deserialize element at index "{k}".'
raise ZTypeError(msg, expect_type_V=et_V, v=v, D=D, mj_yaml=mj) from e
K = get_effective_type(K)
if isinstance(K, type) and issubclass(K, str):
ob.update(attrs)
return ob
elif isinstance(K, type) and issubclass(K, int):
attrs = {int(k): v for k, v in attrs.items()}
ob.update(attrs)
return ob
else:
for k, v in attrs.items():
# noinspection PyUnresolvedReferences
ob[v.real_key] = v.value
return ob
def object_from_ipce_SetLike(mj: IPCE, D: Type[Set], *, ieds: IEDS, iedo: IEDO):
V = get_SetLike_arg(D)
res = set()
# logger.info(f'loading SetLike wiht V = {V}')
for k, v in mj.items():
if k == SCHEMA_ATT:
continue
vob = object_from_ipce_(v, V, ieds=ieds, iedo=iedo)
# logger.info(f'loaded k = {k} vob = {vob}')
res.add(vob)
T = make_set(V)
return T(res) | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/conv_object_from_ipce.py | conv_object_from_ipce.py |
import hashlib
import json
import os
from typing import Optional
import cbor2
import multihash
import numpy as np
from cid import make_cid
from nose.tools import assert_equal
from zuper_commons.fs import write_bytes_to_file, write_ustring_to_utf8_file
from zuper_commons.text import pretty_dict
from zuper_commons.types import ZAssertionError, ZValueError
from zuper_typing import assert_equivalent_types, debug_print, get_patches
from . import logger
from .constants import IEDO, IEDS, IESO
from .conv_ipce_from_object import ipce_from_object
from .conv_ipce_from_typelike import ipce_from_typelike
from .conv_object_from_ipce import object_from_ipce, object_from_ipce_
from .conv_typelike_from_ipce import typelike_from_ipce
from .json_utils import (
decode_bytes_before_json_deserialization,
encode_bytes_before_json_serialization,
)
# from .pretty import pretty_dict
from .utils_text import oyaml_dump
def get_cbor_dag_hash_bytes__(ob_cbor: bytes) -> str:
if not isinstance(ob_cbor, bytes):
msg = "Expected bytes."
raise ZValueError(msg, ob_cbor=ob_cbor)
ob_cbor_hash = hashlib.sha256(ob_cbor).digest()
mh = multihash.encode(digest=ob_cbor_hash, code=18)
# the above returns a bytearray
mh = bytes(mh)
cid = make_cid(1, "dag-cbor", mh)
res = cid.encode().decode("ascii")
return res
def save_object(x: object, ipce: object):
# noinspection PyBroadException
# try:
# import zuper_ipcl
# except:
# return
# print(f"saving {x}")
_x2 = object_from_ipce(ipce)
ipce_bytes = cbor2.dumps(ipce, canonical=True, value_sharing=True)
# from zuper_ipcl.debug_print_ import debug_print
digest = get_cbor_dag_hash_bytes__(ipce_bytes)
dn = "test_objects"
# if not os.path.exists(dn):
# os.makedirs(dn)
fn = os.path.join(dn, digest + ".ipce.cbor.gz")
if os.path.exists(fn):
pass
else: # pragma: no cover
fn = os.path.join(dn, digest + ".ipce.cbor")
write_bytes_to_file(ipce_bytes, fn)
# fn = os.path.join(dn, digest + '.ipce.yaml')
# write_ustring_to_utf8_file(yaml.dump(y1), fn)
fn = os.path.join(dn, digest + ".object.ansi")
s = debug_print(x) # '\n\n as ipce: \n\n' + debug_print(ipce) \
write_ustring_to_utf8_file(s, fn)
fn = os.path.join(dn, digest + ".ipce.yaml")
s = oyaml_dump(ipce)
write_ustring_to_utf8_file(s, fn)
def assert_type_roundtrip(T, *, use_globals: Optional[dict] = None, expect_type_equal: bool = True):
assert_equivalent_types(T, T)
if use_globals is None:
use_globals = {}
schema0 = ipce_from_typelike(T, globals0=use_globals)
# why 2?
schema = ipce_from_typelike(T, globals0=use_globals)
save_object(T, ipce=schema)
# logger.info(debug_print('schema', schema=schema))
iedo = IEDO(use_remembered_classes=False, remember_deserialized_classes=False)
T2 = typelike_from_ipce(schema, iedo=iedo)
# TODO: in 3.6 does not hold for Dict, Union, etc.
# if hasattr(T, '__qualname__'):
# assert hasattr(T, '__qualname__')
# assert T2.__qualname__ == T.__qualname__, (T2.__qualname__, T.__qualname__)
# if False:
# rl.pp('\n\nschema', schema=json.dumps(schema, indent=2))
# rl.pp(f"\n\nT ({T}) the original one", **getattr(T, '__dict__', {}))
# rl.pp(f"\n\nT2 ({T2}) - reconstructed from schema ", **getattr(T2, '__dict__', {}))
# pprint("schema", schema=json.dumps(schema, indent=2))
try:
assert_equal(schema, schema0)
if expect_type_equal:
# assert_same_types(T, T)
# assert_same_types(T2, T)
assert_equivalent_types(T, T2, assume_yes=set())
except: # pragma: no cover
logger.info("assert_type_roundtrip", T=T, schema=schema, T2=T2)
raise
schema2 = ipce_from_typelike(T2, globals0=use_globals)
if schema != schema2: # pragma: no cover
msg = "Different schemas"
d = {
"T": T,
"T.qual": T.__qualname__,
"TAnn": T.__annotations__,
"Td": T.__dict__,
"schema": schema0,
"T2": T2,
"T2.qual": T2.__qualname__,
"TAnn2": T2.__annotations__,
"Td2": T2.__dict__,
"schema2": schema2,
"patches": get_patches(schema, schema2),
}
# msg = pretty_dict(msg, d)
# print(msg)
# with open("tmp1.json", "w") as f:
# f.write(json.dumps(schema, indent=2))
# with open("tmp2.json", "w") as f:
# f.write(json.dumps(schema2, indent=2))
# assert_equal(schema, schema2)
raise ZAssertionError(msg, **d)
return T2
def assert_object_roundtrip(
x1, *, use_globals: Optional[dict] = None, expect_equality=True, works_without_schema=True,
):
"""
expect_equality: if __eq__ is preserved
Will not be preserved if use_globals = {}
because a new Dataclass will be created
and different Dataclasses with the same fields do not compare equal.
"""
if use_globals is None:
use_globals = {}
ieds = IEDS(use_globals, {})
iedo = IEDO(use_remembered_classes=False, remember_deserialized_classes=False)
# dumps = lambda x: yaml.dump(x)
y1 = ipce_from_object(x1, globals_=use_globals)
y1_cbor: bytes = cbor2.dumps(y1)
save_object(x1, ipce=y1)
y1 = cbor2.loads(y1_cbor)
y1e = encode_bytes_before_json_serialization(y1)
y1es = json.dumps(y1e, indent=2)
y1esl = decode_bytes_before_json_deserialization(json.loads(y1es))
y1eslo = object_from_ipce_(y1esl, object, ieds=ieds, iedo=iedo)
x1b = object_from_ipce_(y1, object, ieds=ieds, iedo=iedo)
x1bj = ipce_from_object(x1b, globals_=use_globals)
check_equality(x1, x1b, expect_equality)
patches = get_patches(y1, x1bj)
if not patches and y1 != x1bj:
pass # something weird
if patches: # pragma: no cover
# patches = get_patches(y1, x1bj)
# if patches:
# msg = "The objects are not equivalent"
# raise ZValueError(msg, y1=y1, x1bj=x1bj, patches=patches)
msg = "Round trip not obtained"
# if not patches:
# msg += " but no patches??? "
# msg = pretty_dict(
# "Round trip not obtained",
# # dict(x1bj_json=oyaml_dump(x1bj), y1_json=oyaml_dump(y1)),
# )
# assert_equal(y1, x1bj, msg=msg)
if "propertyNames" in y1["$schema"]:
assert_equal(
y1["$schema"]["propertyNames"], x1bj["$schema"]["propertyNames"], msg=msg,
)
#
# with open("y1.json", "w") as f:
# f.write(oyaml_dump(y1))
# with open("x1bj.json", "w") as f:
# f.write(oyaml_dump(x1bj))
raise ZAssertionError(msg, y1=y1, x1bj=x1bj, patches=patches)
# once again, without schema
ieso_false = IESO(with_schema=False)
if works_without_schema:
z1 = ipce_from_object(x1, globals_=use_globals, ieso=ieso_false)
z2 = cbor2.loads(cbor2.dumps(z1))
u1 = object_from_ipce_(z2, type(x1), ieds=ieds, iedo=iedo)
check_equality(x1, u1, expect_equality)
return locals()
def check_equality(x1: object, x1b: object, expect_equality: bool) -> None:
if isinstance(x1b, type) and isinstance(x1, type):
# logger.warning("Skipping type equality check for %s and %s" % (x1b, x1))
pass
else:
if isinstance(x1, np.ndarray): # pragma: no cover
pass
else:
eq1 = x1b == x1
eq2 = x1 == x1b
if expect_equality: # pragma: no cover
if not eq1:
m = "Object equality (next == orig) not preserved"
msg = pretty_dict(
m, dict(x1b=x1b, x1b_=type(x1b), x1=x1, x1_=type(x1), x1b_eq=x1b.__eq__,),
)
raise AssertionError(msg)
if not eq2:
m = "Object equality (orig == next) not preserved"
msg = pretty_dict(
m, dict(x1b=x1b, x1b_=type(x1b), x1=x1, x1_=type(x1), x1_eq=x1.__eq__,),
)
raise AssertionError(msg)
else:
if eq1 and eq2: # pragma: no cover
msg = "You did not expect equality but they actually are"
logger.info(msg)
# raise Exception(msg) | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/utils_others.py | utils_others.py |
import copy
import dataclasses
import datetime
import warnings
from dataclasses import Field, is_dataclass, replace
from decimal import Decimal
from numbers import Number
from typing import (
cast,
Dict,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
)
import numpy as np
from zuper_commons.types import (
ZAssertionError,
ZTypeError,
ZValueError,
)
from zuper_ipce.types import get_effective_type
from zuper_typing import (
dataclass,
get_Callable_info,
get_ClassVar_arg,
get_dataclass_info,
get_Dict_name_K_V,
get_DictLike_args,
get_fields_including_static,
get_FixedTupleLike_args,
get_FixedTupleLike_name,
get_ForwardRef_arg,
get_Intersection_args,
get_ListLike_arg,
get_ListLike_name,
get_Literal_args,
get_name_without_brackets,
get_NewType_arg,
get_NewType_name,
get_Optional_arg,
get_Sequence_arg,
get_Set_name_V,
get_SetLike_arg,
get_Tuple_name,
get_Type_arg,
get_TypeVar_bound,
get_TypeVar_name,
get_Union_args,
get_VarTuple_arg,
is_Any,
is_Callable,
is_ClassVar,
is_FixedTupleLike,
is_ForwardRef,
is_DictLike,
is_Intersection,
is_ListLike,
is_Literal,
is_NewType,
is_Optional,
is_Sequence,
is_SetLike,
is_TupleLike,
is_Type,
is_TypeLike,
is_TypeVar,
is_Union,
is_VarTuple,
key_for_sorting_types,
MyBytes,
MyStr,
TypeLike,
)
from .constants import (
ALL_OF,
ANY_OF,
ATT_PYTHON_NAME,
CALLABLE_ORDERING,
CALLABLE_RETURN,
ID_ATT,
IESO,
IPCE_PASS_THROUGH,
JSC_ADDITIONAL_PROPERTIES,
JSC_ARRAY,
JSC_BOOL,
JSC_DEFINITIONS,
JSC_DESCRIPTION,
JSC_INTEGER,
JSC_ITEMS,
JSC_NULL,
JSC_NUMBER,
JSC_OBJECT,
JSC_PROPERTIES,
JSC_PROPERTY_NAMES,
JSC_REQUIRED,
JSC_STRING,
JSC_TITLE,
JSC_TITLE_CALLABLE,
JSC_TITLE_DATETIME,
JSC_TITLE_DECIMAL,
JSC_TITLE_FLOAT,
JSC_TITLE_NUMPY,
JSC_TITLE_SLICE,
JSC_TITLE_TYPE,
JSC_TYPE,
JSONSchema,
ProcessingDict,
REF_ATT,
SCHEMA_ATT,
SCHEMA_BYTES,
SCHEMA_CID,
SCHEMA_ID,
X_CLASSATTS,
X_CLASSVARS,
X_ORDER,
X_ORIG,
X_PYTHON_MODULE_ATT,
)
from .ipce_spec import assert_canonical_ipce, sorted_dict_cbor_ord
from .schema_caching import (
get_ipce_from_typelike_cache,
set_ipce_from_typelike_cache,
TRE,
)
from .schema_utils import make_ref, make_url
from .structures import FakeValues
from .types import IPCE
def is_placeholder(x):
return hasattr(x, "__name__") and "Placeholder" in x.__name__
def ipce_from_typelike(
T: TypeLike,
*,
globals0: Optional[dict] = None,
processing: Optional[ProcessingDict] = None,
ieso: Optional[IESO] = None,
) -> JSONSchema:
if ieso is None:
ieso = IESO(with_schema=True)
if processing is None:
processing = {}
if globals0 is None:
globals0 = {}
c = IFTContext(globals0, processing, ())
tr = ipce_from_typelike_tr(T, c, ieso=ieso)
schema = tr.schema
assert_canonical_ipce(schema)
return schema
@dataclass
class IFTContext:
globals_: dict
processing: ProcessingDict
context: Tuple[str, ...]
def ipce_from_typelike_tr(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
if is_placeholder(T):
raise ZValueError(T=T)
if not is_TypeLike(T):
raise ValueError(T)
if hasattr(T, "__name__"):
if T.__name__ in c.processing:
ref = c.processing[T.__name__]
res = make_ref(ref)
return TRE(res, {T.__name__: ref})
if ieso.use_ipce_from_typelike_cache:
try:
return get_ipce_from_typelike_cache(T, c.processing)
except KeyError:
pass
try:
if T is type:
res = cast(
JSONSchema,
{
REF_ATT: SCHEMA_ID,
JSC_TITLE: JSC_TITLE_TYPE
# JSC_DESCRIPTION: T.__doc__
},
)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is type(None):
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TYPE: JSC_NULL})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if isinstance(T, type):
for klass in T.mro():
if klass.__name__.startswith("Generic"):
continue
if klass is object:
continue
globals2 = dict(c.globals_)
globals2[get_name_without_brackets(klass.__name__)] = klass
# clsi = get_dataclass_info(klass)
# bindings = getattr(klass, BINDINGS_ATT, {})
# for k, v in clsi.bindings.items():
# if hasattr(v, "__name__") and v.__name__ not in globals2:
# globals2[v.__name__] = v
# globals2[k.__name__] = v
c = dataclasses.replace(c, globals_=globals2)
tr: TRE = ipce_from_typelike_tr_(T, c=c, ieso=ieso)
if ieso.use_ipce_from_typelike_cache:
set_ipce_from_typelike_cache(T, tr.used, tr.schema)
return tr
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except ValueError as e:
msg = "Cannot get schema for type @T"
raise ZValueError(msg, T=T, T_type=type(T), c=c) from e
except AssertionError as e:
msg = "Cannot get schema for type @T"
raise ZAssertionError(msg, T=T, T_type=type(T), c=c) from e
except BaseException as e:
msg = "Cannot get schema for @T"
raise ZTypeError(msg, T=T, c=c) from e
def ipce_from_typelike_DictLike(T: Type[Dict], c: IFTContext, ieso: IESO) -> TRE:
assert is_DictLike(T), T
K, V = get_DictLike_args(T)
res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT})
res[JSC_TITLE] = get_Dict_name_K_V(K, V)
K = get_effective_type(K)
if isinstance(K, type) and issubclass(K, str):
res[JSC_PROPERTIES] = {SCHEMA_ATT: {}} # XXX
tr = ipce_from_typelike_tr(V, c=c, ieso=ieso)
res[JSC_ADDITIONAL_PROPERTIES] = tr.schema
res[SCHEMA_ATT] = SCHEMA_ID
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
else:
res[JSC_PROPERTIES] = {SCHEMA_ATT: {}} # XXX
props = FakeValues[K, V]
tr = ipce_from_typelike_tr(props, c=c, ieso=ieso)
# logger.warning(f'props IPCE:\n\n {yaml.dump(tr.schema)}')
res[JSC_ADDITIONAL_PROPERTIES] = tr.schema
res[SCHEMA_ATT] = SCHEMA_ID
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
def ipce_from_typelike_SetLike(T: Type[Set], c: IFTContext, ieso: IESO) -> TRE:
assert is_SetLike(T), T
V = get_SetLike_arg(T)
res = cast(JSONSchema, {JSC_TYPE: JSC_OBJECT})
res[JSC_TITLE] = get_Set_name_V(V)
res[JSC_PROPERTY_NAMES] = SCHEMA_CID
tr = ipce_from_typelike_tr(V, c=c, ieso=ieso)
res[JSC_ADDITIONAL_PROPERTIES] = tr.schema
res[SCHEMA_ATT] = SCHEMA_ID
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
def ipce_from_typelike_TupleLike(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
assert is_TupleLike(T), T
used = {}
def f(x: TypeLike) -> JSONSchema:
tr = ipce_from_typelike_tr(x, c=c, ieso=ieso)
used.update(tr.used)
return tr.schema
if is_VarTuple(T):
T = cast(Type[Tuple], T)
items = get_VarTuple_arg(T)
res = cast(JSONSchema, {})
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_ARRAY
res[JSC_ITEMS] = f(items)
res[JSC_TITLE] = get_Tuple_name(T)
res = sorted_dict_cbor_ord(res)
return TRE(res, used)
elif is_FixedTupleLike(T):
T = cast(Type[Tuple], T)
args = get_FixedTupleLike_args(T)
res = cast(JSONSchema, {})
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_ARRAY
res[JSC_ITEMS] = []
res[JSC_TITLE] = get_FixedTupleLike_name(T)
for a in args:
res[JSC_ITEMS].append(f(a))
res = sorted_dict_cbor_ord(res)
return TRE(res, used)
else:
assert False
class KeepTrackSer:
def __init__(self, c: IFTContext, ieso: IESO):
self.c = c
self.ieso = ieso
self.used = {}
def ipce_from_typelike(self, T: TypeLike) -> JSONSchema:
tre = ipce_from_typelike_tr(T, c=self.c, ieso=self.ieso)
self.used.update(tre.used)
return tre.schema
# def ipce_from_object(self, x: IPCE, st: TypeLike) -> IPCE:
# from .conv_ipce_from_object import ipce_from_object_
# res = object_from_ipce_(x, st, ieds=self.ieds, iedo=self.iedo)
# return res
def tre(self, x: IPCE) -> TRE:
return TRE(x, self.used)
def ipce_from_typelike_NewType(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
_ = c, ieso
name = get_NewType_name(T)
T0 = get_NewType_arg(T)
kt = KeepTrackSer(c, ieso)
res = cast(JSONSchema, {})
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = "NewType"
res["newtype"] = kt.ipce_from_typelike(T0)
res[JSC_TITLE] = name
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def ipce_from_typelike_ListLike(T: Type[List], c: IFTContext, ieso: IESO) -> TRE:
assert is_ListLike(T), T
items = get_ListLike_arg(T)
res = cast(JSONSchema, {})
kt = KeepTrackSer(c, ieso)
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_ARRAY
res[JSC_ITEMS] = kt.ipce_from_typelike(items)
res[JSC_TITLE] = get_ListLike_name(T)
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def ipce_from_typelike_Callable(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
assert is_Callable(T), T
cinfo = get_Callable_info(T)
kt = KeepTrackSer(c, ieso)
res = cast(
JSONSchema,
{
JSC_TYPE: JSC_OBJECT,
SCHEMA_ATT: SCHEMA_ID,
JSC_TITLE: JSC_TITLE_CALLABLE,
"special": "callable",
},
)
p = res[JSC_DEFINITIONS] = {}
for k, v in cinfo.parameters_by_name.items():
p[k] = kt.ipce_from_typelike(v)
p[CALLABLE_RETURN] = kt.ipce_from_typelike(cinfo.returns)
res[CALLABLE_ORDERING] = list(cinfo.ordering)
# print(res)
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def ipce_from_typelike_tr_(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
if T is None:
msg = "None is not a type!"
raise ZValueError(msg)
# This can actually happen inside a Tuple (or Dict, etc.) even though
# we have a special case for dataclass
if is_ForwardRef(T): # pragma: no cover
msg = "It is not supported to have an ForwardRef here yet."
raise ZValueError(msg, T=T)
if isinstance(T, str): # pragma: no cover
msg = "It is not supported to have a string here."
raise ZValueError(msg, T=T)
if T is str or T is MyStr:
res = cast(JSONSchema, {JSC_TYPE: JSC_STRING, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is bool:
res = cast(JSONSchema, {JSC_TYPE: JSC_BOOL, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is Number:
res = cast(JSONSchema, {JSC_TYPE: JSC_NUMBER, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is float:
res = {JSC_TYPE: JSC_NUMBER, SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: JSC_TITLE_FLOAT}
res = cast(JSONSchema, res,)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is int:
res = cast(JSONSchema, {JSC_TYPE: JSC_INTEGER, SCHEMA_ATT: SCHEMA_ID})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is slice:
return ipce_from_typelike_slice(ieso=ieso)
if T is Decimal:
res = {JSC_TYPE: JSC_STRING, JSC_TITLE: JSC_TITLE_DECIMAL, SCHEMA_ATT: SCHEMA_ID}
res = cast(JSONSchema, res,)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is datetime.datetime:
res = {
JSC_TYPE: JSC_STRING,
JSC_TITLE: JSC_TITLE_DATETIME,
SCHEMA_ATT: SCHEMA_ID,
}
res = cast(JSONSchema, res)
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is bytes or T is MyBytes:
res = SCHEMA_BYTES
res = sorted_dict_cbor_ord(res)
return TRE(res)
if T is object:
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: "object"})
res = sorted_dict_cbor_ord(res)
return TRE(res)
# we cannot use isinstance on typing.Any
if is_Any(T): # XXX not possible...
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, JSC_TITLE: "Any"})
res = sorted_dict_cbor_ord(res)
return TRE(res)
if is_Union(T):
return ipce_from_typelike_Union(T, c=c, ieso=ieso)
if is_Optional(T):
return ipce_from_typelike_Optional(T, c=c, ieso=ieso)
if is_DictLike(T):
T = cast(Type[Dict], T)
return ipce_from_typelike_DictLike(T, c=c, ieso=ieso)
if is_SetLike(T):
T = cast(Type[Set], T)
return ipce_from_typelike_SetLike(T, c=c, ieso=ieso)
if is_Intersection(T):
return ipce_from_typelike_Intersection(T, c=c, ieso=ieso)
if is_Callable(T):
return ipce_from_typelike_Callable(T, c=c, ieso=ieso)
if is_NewType(T):
return ipce_from_typelike_NewType(T, c=c, ieso=ieso)
if is_Sequence(T):
msg = "Translating Sequence into List"
warnings.warn(msg)
T = cast(Type[Sequence], T)
# raise ValueError(msg)
V = get_Sequence_arg(T)
T = List[V]
return ipce_from_typelike_ListLike(T, c=c, ieso=ieso)
if is_ListLike(T):
T = cast(Type[List], T)
return ipce_from_typelike_ListLike(T, c=c, ieso=ieso)
if is_TupleLike(T):
# noinspection PyTypeChecker
return ipce_from_typelike_TupleLike(T, c=c, ieso=ieso)
if is_Type(T):
TT = get_Type_arg(T)
r = ipce_from_typelike_tr(TT, c, ieso=ieso)
res = {SCHEMA_ATT: SCHEMA_ID, JSC_TYPE: "subtype", "subtype": r.schema}
res = cast(JSONSchema, res)
res = sorted_dict_cbor_ord(res)
return TRE(res, r.used)
# raise NotImplementedError(T)
if is_Literal(T):
values = get_Literal_args(T)
T0 = type(values[0])
r = ipce_from_typelike_tr(T0, c, ieso=ieso)
from .conv_ipce_from_object import ipce_from_object # ok-ish
enum = [ipce_from_object(_, T0) for _ in values]
res = cast(JSONSchema, dict(r.schema))
res["enum"] = enum
res = sorted_dict_cbor_ord(res)
return TRE(res, r.used)
assert isinstance(T, type), (T, type(T), is_Optional(T), is_Union(T), is_Literal(T))
if is_dataclass(T):
return ipce_from_typelike_dataclass(T, c=c, ieso=ieso)
if T is np.ndarray:
return ipce_from_typelike_ndarray()
msg = "Cannot interpret the type @T"
raise ZValueError(msg, T=T, c=c)
def ipce_from_typelike_ndarray() -> TRE:
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID})
res[JSC_TYPE] = JSC_OBJECT
res[JSC_TITLE] = JSC_TITLE_NUMPY
properties = {"shape": {}, "dtype": {}, "data": SCHEMA_BYTES} # TODO # TODO
properties = sorted_dict_cbor_ord(properties)
res[JSC_PROPERTIES] = properties
res = sorted_dict_cbor_ord(res)
return TRE(res)
def ipce_from_typelike_slice(ieso: IESO) -> TRE:
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID})
res[JSC_TYPE] = JSC_OBJECT
res[JSC_TITLE] = JSC_TITLE_SLICE
c = IFTContext({}, {}, ())
tr = ipce_from_typelike_tr(Optional[int], c=c, ieso=ieso)
properties = {
"start": tr.schema, # TODO
"stop": tr.schema, # TODO
"step": tr.schema,
}
res[JSC_PROPERTIES] = sorted_dict_cbor_ord(properties)
res = sorted_dict_cbor_ord(res)
return TRE(res, tr.used)
def ipce_from_typelike_Intersection(T: TypeLike, c: IFTContext, ieso: IESO):
args = get_Intersection_args(T)
kt = KeepTrackSer(c, ieso)
options = [kt.ipce_from_typelike(t) for t in args]
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ALL_OF: options})
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
def get_mentioned_names(T: TypeLike, context=()) -> Iterator[str]:
if T in context:
return
c2 = context + (T,)
if is_dataclass(T):
if context:
yield T.__name__
annotations = getattr(T, "__annotations__", {})
for v in annotations.values():
yield from get_mentioned_names(v, c2)
elif is_Type(T):
v = get_Type_arg(T)
yield from get_mentioned_names(v, c2)
elif is_TypeVar(T):
yield get_TypeVar_name(T)
elif is_FixedTupleLike(T):
T = cast(Type[Tuple], T)
for t in get_FixedTupleLike_args(T):
yield from get_mentioned_names(t, c2)
elif is_VarTuple(T):
T = cast(Type[Tuple], T)
t = get_VarTuple_arg(T)
yield from get_mentioned_names(t, c2)
elif is_ListLike(T):
T = cast(Type[List], T)
t = get_ListLike_arg(T)
yield from get_mentioned_names(t, c2)
elif is_DictLike(T):
T = cast(Type[Dict], T)
K, V = get_DictLike_args(T)
yield from get_mentioned_names(K, c2)
yield from get_mentioned_names(V, c2)
elif is_SetLike(T):
T = cast(Type[Set], T)
t = get_SetLike_arg(T)
yield from get_mentioned_names(t, c2)
elif is_ForwardRef(T):
return get_ForwardRef_arg(T)
elif is_Optional(T):
t = get_Optional_arg(T)
yield from get_mentioned_names(t, c2)
elif is_Union(T):
for t in get_Union_args(T):
yield from get_mentioned_names(t, c2)
else:
pass
def ipce_from_typelike_dataclass(T: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
assert is_dataclass(T), T
# noinspection PyDataclass
c = replace(
c,
globals_=dict(c.globals_),
processing=dict(c.processing),
context=c.context + (T.__name__,),
)
used = {}
def ftl(x: TypeLike) -> JSONSchema:
if not is_TypeLike(x):
raise ValueError(x)
tr = ipce_from_typelike_tr(x, c=c, ieso=ieso)
used.update(tr.used)
return tr.schema
def fob(x: object) -> IPCE:
return ipce_from_object(x, globals_=c.globals_, ieso=ieso)
def f(x: object) -> IPCE:
if is_TypeLike(x):
x = cast(TypeLike, x)
return ftl(x)
else:
return fob(x)
res = cast(JSONSchema, {})
mentioned = set(get_mentioned_names(T, ()))
relevant = [x for x in c.context if x in mentioned and x != T.__name__]
relevant.append(T.__qualname__)
url_name = "_".join(relevant)
my_ref = make_url(url_name)
res[ID_ATT] = my_ref
res[JSC_TITLE] = T.__name__
c.processing[T.__name__] = my_ref
res[ATT_PYTHON_NAME] = T.__qualname__
res[X_PYTHON_MODULE_ATT] = T.__module__
res[SCHEMA_ATT] = SCHEMA_ID
res[JSC_TYPE] = JSC_OBJECT
if hasattr(T, "__doc__") and T.__doc__ is not None:
res[JSC_DESCRIPTION] = T.__doc__
Ti = get_dataclass_info(T)
definitions = {}
# bindings: Dict[str, type] = {}
types2: Tuple[type, ...] = Ti.get_open()
to_add: Dict[type, type] = {}
for tx in types2:
if not isinstance(tx, TypeVar):
continue
abound = get_TypeVar_bound(tx)
to_add[tx] = abound
c.globals_[tx] = tx
#
# for tx, val in Ti.bindings.items():
# to_add[tx] = val
def get_schema_with_url(url, bound):
schema = ftl(bound)
schema = copy.copy(schema)
schema[ID_ATT] = url
schema = sorted_dict_cbor_ord(schema)
return schema
for t2, bound in to_add.items():
t2_name = get_TypeVar_name(t2)
url = make_url(f"{T.__qualname__}/{t2_name}")
schema = get_schema_with_url(url, bound)
c.processing[t2_name] = url
if t2 in Ti.get_open():
definitions[t2_name] = schema
# if t2 in Ti.bindings:
# bindings[t2_name] = schema
if Ti.orig:
# res[X_ORIG] = list(get_TypeVar_name(_) for _ in Ti.orig)
def ff(_) -> JSONSchema:
if is_TypeVar(_):
_name = get_TypeVar_name(_)
url = make_url(f"{T.__qualname__}/{_name}")
return make_ref(url)
else:
return ftl(_)
res[X_ORIG] = [ff(_) for _ in Ti.orig]
# if Ti.extra:
# res[X_EXTRA] = list(get_TypeVar_name(_) for _ in Ti.extra)
if definitions:
res[JSC_DEFINITIONS] = sorted_dict_cbor_ord(definitions)
# if bindings:
# res[X_BINDINGS] = sorted_dict_cbor_ord(bindings)
properties = {}
classvars = {}
classatts = {}
required = []
all_fields: Dict[str, Field] = get_fields_including_static(T)
from .conv_ipce_from_object import ipce_from_object
original_order = list(all_fields)
ordered = sorted(all_fields)
for name in ordered:
afield = all_fields[name]
t = afield.type
try:
if isinstance(t, str): # pragma: no cover
# t = eval_just_string(t, c.globals_)
msg = "Before serialization, need to have all text references substituted."
msg += f"\n found reference {t!r} in class {T}."
raise Exception(msg)
if is_ClassVar(t):
tt = get_ClassVar_arg(t)
classvars[name] = ftl(tt)
try:
the_att = get_T_attribute(T, name)
except AttributeError:
pass
else:
classatts[name] = f(the_att)
else: # not classvar
schema = ftl(t)
try:
default = get_field_default(afield)
except KeyError:
required.append(name)
else:
schema = make_schema_with_default(schema, default, c, ieso)
properties[name] = schema
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException as e:
msg = "Cannot write schema for attribute @name -> @t of type @T."
raise ZTypeError(msg, name=name, t=t, T=T) from e
if required: # empty is error
res[JSC_REQUIRED] = sorted(required)
if classvars:
res[X_CLASSVARS] = classvars
if classatts:
res[X_CLASSATTS] = classatts
assert len(classvars) >= len(classatts), (classvars, classatts)
if properties:
res[JSC_PROPERTIES] = sorted_dict_cbor_ord(properties)
res[X_ORDER] = original_order
if sorted_dict_cbor_ord:
res = sorted_dict_cbor_ord(res)
if T.__name__ in used:
used.pop(T.__name__)
return TRE(res, used)
def get_T_attribute(T: TypeLike, n: str) -> object:
if hasattr(T, n):
# special case
the_att2 = getattr(T, n)
if isinstance(the_att2, Field):
# actually attribute not there
raise AttributeError()
else:
return the_att2
else:
raise AttributeError()
def make_schema_with_default(
schema: JSONSchema, default: object, c: IFTContext, ieso: IESO
) -> JSONSchema:
from .conv_ipce_from_object import ipce_from_object # ok-ish
options = [schema]
s_u_one = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ANY_OF: options})
ipce_default = ipce_from_object(default, globals_=c.globals_, ieso=ieso)
s_u_one["default"] = ipce_default
s_u_one = sorted_dict_cbor_ord(s_u_one)
return s_u_one
from dataclasses import MISSING
def get_field_default(f: Field) -> object:
if f.default != MISSING:
return f.default
elif f.default_factory != MISSING:
return f.default_factory()
else:
raise KeyError("no default")
def ipce_from_typelike_Union(t: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
types = get_Union_args(t)
used = {}
def f(x: TypeLike) -> JSONSchema:
tr = ipce_from_typelike_tr(x, c=c, ieso=ieso)
used.update(tr.used)
return tr.schema
types = tuple(sorted(types, key=key_for_sorting_types))
options = [f(t) for t in types]
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ANY_OF: options})
res = sorted_dict_cbor_ord(res)
return TRE(res, used)
def ipce_from_typelike_Optional(t: TypeLike, c: IFTContext, ieso: IESO) -> TRE:
types = [get_Optional_arg(t), type(None)]
kt = KeepTrackSer(c, ieso)
options = [kt.ipce_from_typelike(t) for t in types]
res = cast(JSONSchema, {SCHEMA_ATT: SCHEMA_ID, ANY_OF: options})
res = sorted_dict_cbor_ord(res)
return kt.tre(res)
# | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/conv_ipce_from_typelike.py | conv_ipce_from_typelike.py |
import datetime
from dataclasses import dataclass, Field, fields, is_dataclass
from typing import cast, Iterator, Optional, Set, TypeVar
import numpy as np
from frozendict import frozendict
from zuper_commons.types import ZNotImplementedError, ZTypeError, ZValueError
from zuper_ipce.types import get_effective_type
from zuper_typing import (DictStrType, get_Optional_arg, get_Union_args, is_Optional,
is_SpecialForm,
is_Union,
lift_to_customtuple, make_dict, same_as_default, value_liskov)
from .constants import (GlobalsDict, HINTS_ATT, IESO, IPCE_PASS_THROUGH, IPCE_TRIVIAL, SCHEMA_ATT)
from .conv_ipce_from_typelike import ipce_from_typelike, ipce_from_typelike_ndarray
from .guesses import (
get_dict_type_suggestion,
get_list_type_suggestion,
get_set_type_suggestion,
get_tuple_type_suggestion,
)
from .ipce_spec import sorted_dict_cbor_ord
from .structures import FakeValues
from .types import IPCE, is_unconstrained, TypeLike
X = TypeVar("X")
def ipce_from_object(
ob: object,
suggest_type: TypeLike = object,
*,
globals_: GlobalsDict = None,
ieso: Optional[IESO] = None,
) -> IPCE:
# logger.debug(f'ipce_from_object({ob})')
if ieso is None:
ieso = IESO(with_schema=True)
if globals_ is None:
globals_ = {}
try:
res = ipce_from_object_(ob, suggest_type, globals_=globals_, ieso=ieso)
except TypeError as e:
msg = "ipce_from_object() for type @t failed."
raise ZTypeError(msg, ob=ob, T=type(ob)) from e
# assert_canonical_ipce(res)
return res
def ipce_from_object_(ob: object, st: TypeLike, *, globals_: GlobalsDict, ieso: IESO) -> IPCE:
unconstrained = is_unconstrained(st)
if ob is None:
if unconstrained or (st is type(None)) or is_Optional(st):
return ob
else: # pragma: no cover
msg = f"ob is None but suggest_type is @suggest_type"
raise ZTypeError(msg, suggest_type=st)
if is_Optional(st):
assert ob is not None # from before
T = get_Optional_arg(st)
return ipce_from_object_(ob, T, globals_=globals_, ieso=ieso)
if is_Union(st):
return ipce_from_object_union(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, datetime.datetime):
if not ob.tzinfo:
msg = "Cannot serialize dates without a timezone."
raise ZValueError(msg, ob=ob)
if st in IPCE_TRIVIAL:
if not isinstance(ob, st):
msg = "Expected this to be @suggest_type."
raise ZTypeError(msg, st=st, ob=ob, T=type(ob))
return ob
if isinstance(ob, IPCE_TRIVIAL):
return ob
if isinstance(ob, list):
return ipce_from_object_list(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, tuple):
return ipce_from_object_tuple(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, slice):
return ipce_from_object_slice(ob, ieso=ieso)
if isinstance(ob, set):
return ipce_from_object_set(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, (dict, frozendict)):
return ipce_from_object_dict(ob, st, globals_=globals_, ieso=ieso)
if isinstance(ob, type):
return ipce_from_typelike(ob, globals0=globals_, processing={}, ieso=ieso)
if is_SpecialForm(cast(TypeLike, ob)):
ob = cast(TypeLike, ob)
return ipce_from_typelike(ob, globals0=globals_, processing={}, ieso=ieso)
if isinstance(ob, np.ndarray):
return ipce_from_object_numpy(ob, ieso=ieso)
assert not isinstance(ob, type), ob
if is_dataclass(ob):
return ipce_from_object_dataclass_instance(ob, globals_=globals_, ieso=ieso)
msg = "I do not know a way to convert object @ob of type @T."
raise ZNotImplementedError(msg, ob=ob, T=type(ob))
def ipce_from_object_numpy(ob, *, ieso: IESO) -> IPCE:
from .numpy_encoding import ipce_from_numpy_array
res = ipce_from_numpy_array(ob)
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike_ndarray().schema
return res
def ipce_from_object_slice(ob, *, ieso: IESO):
from .conv_ipce_from_typelike import ipce_from_typelike_slice
res = {"start": ob.start, "step": ob.step, "stop": ob.stop}
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike_slice(ieso=ieso).schema
res = sorted_dict_cbor_ord(res)
return res
def ipce_from_object_union(ob: object, st: TypeLike, *, globals_, ieso: IESO) -> IPCE:
ts = get_Union_args(st)
errors = []
for Ti in ts:
can = value_liskov(ob, Ti)
if can:
return ipce_from_object(ob, Ti, globals_=globals_, ieso=ieso)
else:
errors.append(can)
msg = "Cannot save union."
raise ZTypeError(msg, suggest_type=st, value=ob, errors=errors)
def ipce_from_object_list(ob, st: TypeLike, *, globals_: dict, ieso: IESO) -> IPCE:
assert st is not None
V = get_list_type_suggestion(ob, st)
def rec(x: X) -> X:
return ipce_from_object(x, V, globals_=globals_, ieso=ieso)
return [rec(_) for _ in ob]
def ipce_from_object_tuple(ob: tuple, st: TypeLike, *, globals_, ieso: IESO) -> IPCE:
ts = get_tuple_type_suggestion(ob, st)
res = []
for _, T in zip(ob, ts):
x = ipce_from_object(_, T, globals_=globals_, ieso=ieso)
res.append(x)
return res
@dataclass
class IterAtt:
attr: str
T: TypeLike
value: object
def iterate_resolved_type_values_without_default(x: dataclass) -> Iterator[IterAtt]:
for f in fields(type(x)):
assert isinstance(f, Field), list(fields(type(x)))
k = f.name
v0 = getattr(x, k)
if same_as_default(f, v0):
continue
k_st = f.type
yield IterAtt(k, k_st, v0)
def ipce_from_object_dataclass_instance(ob: dataclass, *, globals_, ieso: IESO) -> IPCE:
globals_ = dict(globals_)
res = {}
T0 = type(ob)
from .conv_ipce_from_typelike import ipce_from_typelike
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike(T0, globals0=globals_, ieso=ieso)
globals_[T0.__name__] = T0
hints = DictStrType()
attrs = list(iterate_resolved_type_values_without_default(ob))
if ieso.with_schema:
for ia in attrs:
if isinstance(ia.value, tuple) and is_unconstrained(ia.T):
v2 = lift_to_customtuple(ia.value)
hints[ia.attr] = type(v2)
elif isinstance(ia.value, list) and is_unconstrained(ia.T):
hints[ia.attr] = type(ia.value)
for ia in attrs:
k = ia.attr
v = ia.value
T = ia.T
try:
res[k] = ipce_from_object(v, T, globals_=globals_, ieso=ieso)
# needs_schema = isinstance(v, (list, tuple))
# if ieso.with_schema and needs_schema and is_unconstrained(T):
# if isinstance(v, tuple):
# Ti = make_Tuple(*get_tuple_type_suggestion(v, T))
# else:
# Ti = type(v)
# hints[k] = Ti
except IPCE_PASS_THROUGH: # pragma: no cover
raise
except BaseException as e:
msg = (
f"Could not serialize an object. Problem "
f"occurred with the attribute {k!r}. It is supposed to be of type @expected."
)
raise ZValueError(msg, expected=T, ob=ob) from e
if hints:
# logger.info(hints=hints)
res[HINTS_ATT] = ipce_from_object(hints, ieso=ieso)
res = sorted_dict_cbor_ord(res)
return res
def ipce_from_object_dict(ob: dict, st: TypeLike, *, globals_: GlobalsDict, ieso: IESO):
K, V = get_dict_type_suggestion(ob, st)
DT = make_dict(K, V)
res = {}
from .conv_ipce_from_typelike import ipce_from_typelike
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike(DT, globals0=globals_, ieso=ieso)
K = get_effective_type(K)
if isinstance(K, type) and issubclass(K, str):
for k, v in ob.items():
res[k] = ipce_from_object(v, V, globals_=globals_, ieso=ieso)
elif isinstance(K, type) and issubclass(K, int):
for k, v in ob.items():
res[str(k)] = ipce_from_object(v, V, globals_=globals_, ieso=ieso)
else:
FV = FakeValues[K, V]
# group first by the type name, then sort by key
items = [(type(k).__name__, k, v) for k, v in ob.items()]
items = sorted(items)
for i, (_, k, v) in enumerate(items):
h = get_key_for_set_entry(i, len(ob))
fv = FV(k, v)
res[h] = ipce_from_object(fv, globals_=globals_, ieso=ieso)
res = sorted_dict_cbor_ord(res)
return res
def ipce_from_object_set(ob: set, st: TypeLike, *, globals_: GlobalsDict, ieso: IESO):
from .conv_ipce_from_typelike import ipce_from_typelike
V = get_set_type_suggestion(ob, st)
ST = Set[V]
res = {}
if ieso.with_schema:
res[SCHEMA_ATT] = ipce_from_typelike(ST, globals0=globals_, ieso=ieso)
# group first by the type name, then sort by key
items = [(type(v).__name__, v) for v in ob]
items = sorted(items)
for i, (_, v) in enumerate(items):
vj = ipce_from_object(v, V, globals_=globals_, ieso=ieso)
h = get_key_for_set_entry(i, len(ob))
res[h] = vj
res = sorted_dict_cbor_ord(res)
return res
def get_key_for_set_entry(i: int, n: int):
ndigits = len(str(n))
format0 = f"%0{ndigits}d"
x = format0 % i
return f"set:{x}" | zuper-ipce-z6 | /zuper-ipce-z6-6.1.2.tar.gz/zuper-ipce-z6-6.1.2/src/zuper_ipce/conv_ipce_from_object.py | conv_ipce_from_object.py |
from __future__ import unicode_literals
import os
import socket
import time
import traceback
from collections import namedtuple
import cbor2 as cbor
from . import logger
from .constants import *
from .reading import read_next_cbor
from .utils import indent
# Python 2 compatibility.
try:
TimeoutError
except NameError:
import socket
TimeoutError = socket.timeout
__all__ = ['ComponentInterface']
class ExternalProtocolViolation(Exception):
pass
class ExternalNodeDidNotUnderstand(Exception):
pass
class RemoteNodeAborted(Exception):
pass
TimeoutError = socket.timeout
class Malformed(Exception):
pass
MsgReceived = namedtuple('MsgReceived', 'topic data')
class ComponentInterface(object):
def __init__(self, fnin, fnout, nickname, timeout=None):
self.nickname = nickname
try:
os.mkfifo(fnin)
except BaseException as e:
msg = 'Cannot create fifo {}'.format(fnin)
msg += '\n\n%s' % traceback.format_exc()
raise Exception(msg)
self.fpin = open(fnin, 'wb', buffering=0)
wait_for_creation(fnout)
self.fnout = fnout
f = open(fnout, 'rb', buffering=0)
# noinspection PyTypeChecker
self.fpout = f # BufferedReader(f, buffer_size=1)
self.nreceived = 0
self.node_protocol = None
self.data_protocol = None
self.timeout = timeout
def close(self):
self.fpin.close()
self.fpout.close()
def write_topic_and_expect(self, topic, data=None,
timeout=None,
timing=None,
expect=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, timing=timing)
ob = self.read_one(expect_topic=expect, timeout=timeout)
return ob
def write_topic_and_expect_zero(self, topic, data=None,
timeout=None,
timing=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, timing=timing)
msgs = read_reply(self.fpout, timeout=timeout,
nickname=self.nickname)
if msgs:
msg = 'Expecting zero, got %s' % msgs
raise ExternalProtocolViolation(msg)
def _write_topic(self, topic, data=None, timing=None):
msg = {FIELD_COMPAT: [PROTOCOL],
FIELD_TOPIC: topic,
FIELD_DATA: data,
FIELD_TIMING: timing}
j = self._serialize(msg)
self._write(j)
# logger.info('Written to topic "{topic}" >> {name}.'.format(topic=topic, name=self.nickname))
def _write(self, j):
try:
self.fpin.write(j)
self.fpin.flush()
except BrokenPipeError as e:
msg = ('While attempting to write to node "{nickname}", '
'I reckon that the pipe is closed and the node exited.').format(nickname=self.nickname)
try:
received = self.read_one(expect_topic=TOPIC_ABORTED)
if received.topic == TOPIC_ABORTED:
msg += '\n\nThis is the aborted message:'
msg += '\n\n' + received.data
except BaseException as e2:
msg += '\n\nI could not read any aborted message: {e2}'.format(e2=e2)
raise RemoteNodeAborted(msg)
def _serialize(self, msg):
j = cbor.dumps(msg)
return j
def read_one(self, expect_topic=None, timeout=None):
timeout = timeout or self.timeout
try:
if expect_topic:
waiting_for = 'Expecting topic "{expect_topic}" << {nickname}.'.format(expect_topic=expect_topic,
nickname=self.nickname)
else:
waiting_for = None
msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for,
nickname=self.nickname)
if len(msgs) == 0:
msg = 'Expected one message from node "{}". Got zero.'.format(self.nickname)
if expect_topic:
msg += '\nExpecting topic "{}".'.format(expect_topic)
raise ExternalProtocolViolation(msg)
if len(msgs) > 1:
msg = 'Expected only one message. Got {}.'.format(len(msgs))
raise ExternalProtocolViolation(msg)
msg = msgs[0]
if FIELD_TOPIC not in msg:
m = 'Invalid message does not contain the field "{}".'.format(FIELD_TOPIC)
m += '\n {}'.format(msg)
raise ExternalProtocolViolation(m)
topic = msg[FIELD_TOPIC]
if expect_topic:
if topic != expect_topic:
msg = 'I expected topic "{expect_topic}" but received "{topic}".'.format(expect_topic=expect_topic,
topic=topic)
raise ExternalProtocolViolation(msg)
if self.nreceived == 0:
msg1 = 'Received first message of topic %s' % topic
logger.info(msg1)
self.nreceived += 1
return MsgReceived(topic, msg[FIELD_DATA])
except StopIteration as e:
msg = 'EOF detected on %s after %d messages.' % (self.fnout, self.nreceived)
if expect_topic:
msg += ' Expected topic "{}".'.format(expect_topic)
raise StopIteration(msg)
except TimeoutError as e:
msg = 'Timeout declared after waiting %s sec on %s after having received %d messages.' % (timeout,
self.fnout,
self.nreceived)
if expect_topic:
msg += ' Expected topic "{}".'.format(expect_topic)
raise TimeoutError(msg)
def wait_for_creation(fn):
while not os.path.exists(fn):
msg = 'waiting for creation of %s' % fn
logger.info(msg)
time.sleep(1)
def read_reply(fpout, nickname, timeout=None, waiting_for=None):
""" Reads a control message. Returns if it is CTRL_UNDERSTOOD.
Raises:
TimeoutError
RemoteNodeAborted
ExternalNodeDidNotUnderstand
ExternalProtocolViolation otherwise. """
try:
wm = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
except StopIteration:
msg = 'Remote node closed communication (%s)' % waiting_for
raise RemoteNodeAborted(msg)
cm = interpret_control_message(wm)
if cm.code == CTRL_UNDERSTOOD:
others = read_until_over(fpout, timeout=timeout, nickname=nickname)
return others
elif cm.code == CTRL_ABORTED:
msg = 'The remote node "{}" aborted with the following error:'.format(nickname)
msg += '\n\n' + indent(cm.msg, "|", "error in {} |".format(nickname))
# others = self.read_until_over()
raise RemoteNodeAborted(msg)
elif cm.code == CTRL_NOT_UNDERSTOOD:
_others = read_until_over(fpout, timeout=timeout, nickname=nickname)
msg = 'The remote node "{nickname}" reports that it did not understand the message:'.format(nickname=nickname)
msg += '\n\n' + indent(cm.msg, "|", "reported by {} |".format(nickname))
raise ExternalNodeDidNotUnderstand(msg)
else:
msg = 'Remote node raised unknown code %s: %s' % (cm, cm.code)
raise ExternalProtocolViolation(msg)
ControlMessage = namedtuple('ControlMessage', 'code msg')
def interpret_control_message(m):
if not isinstance(m, dict):
msg = 'Expected dictionary, not {}.'.format(type(m))
raise Malformed(msg)
if not FIELD_CONTROL in m:
msg = 'Expected field {}, obtained {}'.format(FIELD_CONTROL, list(m))
raise Malformed(msg)
code = m[FIELD_CONTROL]
msg = m.get(FIELD_DATA, None)
return ControlMessage(code, msg)
def read_until_over(fpout, timeout, nickname):
""" Raises RemoteNodeAborted, TimeoutError """
res = []
waiting_for = 'Reading reply of {}.'.format(nickname)
while True:
try:
wm = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
if wm.get(FIELD_CONTROL, '') == CTRL_ABORTED:
m = 'External node "{}" aborted:'.format(nickname)
m += '\n\n' + indent(wm.get(FIELD_DATA, None), "|",
"error in {} |".format(nickname))
raise RemoteNodeAborted(m)
if wm.get(FIELD_CONTROL, '') == CTRL_OVER:
# logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res))
break
# logger.info(f'Node "{nickname}" sent %s.' % len(wm))
except StopIteration:
msg = 'External node "{}" closed communication.'.format(nickname)
raise RemoteNodeAborted(msg)
except TimeoutError:
msg = 'Timeout while reading output of node "{}".'.format(nickname)
raise TimeoutError(msg)
res.append(wm)
return res | zuper-nodes-python2-daffy | /zuper-nodes-python2-daffy-5.0.3.tar.gz/zuper-nodes-python2-daffy-5.0.3/src/zuper_nodes_python2/outside.py | outside.py |
from __future__ import unicode_literals
import os
import sys
import time
import traceback
import cbor2 as cbor
from . import logger
from .constants import *
# Python 2 compatibility.
try:
TimeoutError
except NameError:
import socket
TimeoutError = socket.timeout
__all__ = ['wrap_direct', 'Context']
class Context:
def info(self, s):
pass
def error(self, s):
pass
def debug(self, s):
pass
def warning(self, s):
pass
def write(self, topic, data):
pass
# noinspection PyBroadException
def wrap_direct(agent):
logger.info('python %s' % ".".join(map(str, sys.version_info)))
data_in = os.environ.get('AIDONODE_DATA_IN', '/dev/stdin')
data_out = os.environ.get('AIDONODE_DATA_OUT', '/dev/stdout')
while not os.path.exists(data_in):
logger.info('Waiting for %s to be created.' % data_in)
time.sleep(1)
if data_in == '/dev/stdin':
f_in = sys.stdin
else:
f_in = open(data_in, 'rb')
# f_in = io.BufferedReader(io.open(f_in.fileno()))
# f_in = sys.stdin
if data_out.startswith('fifo:'):
data_out = data_out.lstrip('fifo:')
os.mkfifo(data_out)
logger.info('Opening fifo %s for writing. Will block until reader appears.' % data_out)
f_out = open(data_out, 'wb')
logger.info('Starting reading from %s' % data_in)
try:
while True:
# whatever
# logger.info('Reading...')
try:
msg = cbor.load(f_in)
except IOError as e:
if e.errno == 29:
break
raise
if not isinstance(msg, dict) or ((FIELD_CONTROL not in msg) and (FIELD_TOPIC not in msg)):
# ignore things that we do not understand
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, "Protocol mismatch")
send_control_message(f_out, CTRL_OVER)
if FIELD_CONTROL in msg:
c = msg[FIELD_CONTROL]
if c == CTRL_CAPABILITIES:
his = msg[FIELD_DATA]
logger.info('His capabilities: %s' % his)
capabilities = {
'z2': {}
}
logger.info('My capabilities: %s' % capabilities)
send_control_message(f_out, CTRL_UNDERSTOOD)
send_control_message(f_out, CTRL_CAPABILITIES, capabilities)
send_control_message(f_out, CTRL_OVER)
else:
msg = 'Could not deal with control message "%s".' % c
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, msg)
send_control_message(f_out, CTRL_OVER)
elif FIELD_TOPIC in msg:
topic = msg[FIELD_TOPIC]
data = msg.get(FIELD_DATA, None)
fn = 'on_received_%s' % topic
if not hasattr(agent, fn):
msg = 'Could not deal with topic %s' % topic
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, msg)
send_control_message(f_out, CTRL_OVER)
else:
send_control_message(f_out, CTRL_UNDERSTOOD)
context = ConcreteContext(f_out)
f = getattr(agent, fn)
try:
f(context=context, data=data)
except BaseException:
s = traceback.format_exc()
logger.error(s)
try:
s = s.decode('utf-8')
except:
pass
send_control_message(f_out, CTRL_ABORTED, s)
raise
finally:
send_control_message(f_out, CTRL_OVER)
else:
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, "I expect a topic message")
send_control_message(f_out, CTRL_OVER)
logger.info('Graceful exit.')
except BaseException:
f_out.flush()
logger.error(traceback.format_exc())
sys.exit(1)
finally:
f_out.flush()
def send_control_message(f_out, c, msg=None):
m = {}
m[FIELD_COMPAT] = [PROTOCOL]
m[FIELD_CONTROL] = unicode(c)
m[FIELD_DATA] = msg
cbor.dump(m, f_out)
logger.info('Sending control %s' % c)
f_out.flush()
def send_topic_message(f_out, topic, data):
m = {}
m[FIELD_COMPAT] = [PROTOCOL]
m[FIELD_TOPIC] = unicode(topic)
m[FIELD_DATA] = data
cbor.dump(m, f_out)
logger.info('Sending topic %s' % topic)
f_out.flush()
class ConcreteContext(Context):
def __init__(self, f_out):
self.f_out = f_out
def info(self, s):
logger.info(s)
def error(self, s):
logger.error(s)
def debug(self, s):
logger.debug(s)
def warning(self, s):
logger.warning(s)
def write(self, topic, data=None):
send_topic_message(self.f_out, topic, data) | zuper-nodes-python2-daffy | /zuper-nodes-python2-daffy-5.0.3.tar.gz/zuper-nodes-python2-daffy-5.0.3/src/zuper_nodes_python2/imp.py | imp.py |
from __future__ import unicode_literals
import os
import socket
import time
import traceback
from collections import namedtuple
import cbor2 as cbor
from . import logger
from .constants import *
from .reading import read_next_cbor
from .utils import indent
# Python 2 compatibility.
try:
TimeoutError
except NameError:
import socket
TimeoutError = socket.timeout
__all__ = ['ComponentInterface']
class ExternalProtocolViolation(Exception):
pass
class ExternalNodeDidNotUnderstand(Exception):
pass
class RemoteNodeAborted(Exception):
pass
TimeoutError = socket.timeout
class Malformed(Exception):
pass
MsgReceived = namedtuple('MsgReceived', 'topic data')
class ComponentInterface(object):
def __init__(self, fnin, fnout, nickname, timeout=None):
self.nickname = nickname
try:
os.mkfifo(fnin)
except BaseException as e:
msg = 'Cannot create fifo {}'.format(fnin)
msg += '\n\n%s' % traceback.format_exc()
raise Exception(msg)
self.fpin = open(fnin, 'wb', buffering=0)
wait_for_creation(fnout)
self.fnout = fnout
f = open(fnout, 'rb', buffering=0)
# noinspection PyTypeChecker
self.fpout = f # BufferedReader(f, buffer_size=1)
self.nreceived = 0
self.node_protocol = None
self.data_protocol = None
self.timeout = timeout
def close(self):
self.fpin.close()
self.fpout.close()
def write_topic_and_expect(self, topic, data=None,
timeout=None,
timing=None,
expect=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, timing=timing)
ob = self.read_one(expect_topic=expect, timeout=timeout)
return ob
def write_topic_and_expect_zero(self, topic, data=None,
timeout=None,
timing=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, timing=timing)
msgs = read_reply(self.fpout, timeout=timeout,
nickname=self.nickname)
if msgs:
msg = 'Expecting zero, got %s' % msgs
raise ExternalProtocolViolation(msg)
def _write_topic(self, topic, data=None, timing=None):
msg = {FIELD_COMPAT: [PROTOCOL],
FIELD_TOPIC: topic,
FIELD_DATA: data,
FIELD_TIMING: timing}
j = self._serialize(msg)
self._write(j)
# logger.info('Written to topic "{topic}" >> {name}.'.format(topic=topic, name=self.nickname))
def _write(self, j):
try:
self.fpin.write(j)
self.fpin.flush()
except BaseException as e:
msg = ('While attempting to write to node "{nickname}", '
'I reckon that the pipe is closed and the node exited.').format(nickname=self.nickname)
try:
received = self.read_one(expect_topic=TOPIC_ABORTED)
if received.topic == TOPIC_ABORTED:
msg += '\n\nThis is the aborted message:'
msg += '\n\n' + received.data
except BaseException as e2:
msg += '\n\nI could not read any aborted message: {e2}'.format(e2=e2)
raise RemoteNodeAborted(msg)
def _serialize(self, msg):
j = cbor.dumps(msg)
return j
def read_one(self, expect_topic=None, timeout=None):
timeout = timeout or self.timeout
try:
if expect_topic:
waiting_for = 'Expecting topic "{expect_topic}" << {nickname}.'.format(expect_topic=expect_topic,
nickname=self.nickname)
else:
waiting_for = None
msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for,
nickname=self.nickname)
if len(msgs) == 0:
msg = 'Expected one message from node "{}". Got zero.'.format(self.nickname)
if expect_topic:
msg += '\nExpecting topic "{}".'.format(expect_topic)
raise ExternalProtocolViolation(msg)
if len(msgs) > 1:
msg = 'Expected only one message. Got {}.'.format(len(msgs))
raise ExternalProtocolViolation(msg)
msg = msgs[0]
if FIELD_TOPIC not in msg:
m = 'Invalid message does not contain the field "{}".'.format(FIELD_TOPIC)
m += '\n {}'.format(msg)
raise ExternalProtocolViolation(m)
topic = msg[FIELD_TOPIC]
if expect_topic:
if topic != expect_topic:
msg = 'I expected topic "{expect_topic}" but received "{topic}".'.format(expect_topic=expect_topic,
topic=topic)
raise ExternalProtocolViolation(msg)
if self.nreceived == 0:
msg1 = 'Received first message of topic %s' % topic
logger.info(msg1)
self.nreceived += 1
return MsgReceived(topic, msg[FIELD_DATA])
except StopIteration as e:
msg = 'EOF detected on %s after %d messages.' % (self.fnout, self.nreceived)
if expect_topic:
msg += ' Expected topic "{}".'.format(expect_topic)
raise StopIteration(msg)
except TimeoutError as e:
msg = 'Timeout declared after waiting %s sec on %s after having received %d messages.' % (timeout,
self.fnout,
self.nreceived)
if expect_topic:
msg += ' Expected topic "{}".'.format(expect_topic)
raise TimeoutError(msg)
def wait_for_creation(fn):
while not os.path.exists(fn):
msg = 'waiting for creation of %s' % fn
logger.info(msg)
time.sleep(1)
def read_reply(fpout, nickname, timeout=None, waiting_for=None):
""" Reads a control message. Returns if it is CTRL_UNDERSTOOD.
Raises:
TimeoutError
RemoteNodeAborted
ExternalNodeDidNotUnderstand
ExternalProtocolViolation otherwise. """
try:
wm = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
except StopIteration:
msg = 'Remote node closed communication (%s)' % waiting_for
raise RemoteNodeAborted(msg)
cm = interpret_control_message(wm)
if cm.code == CTRL_UNDERSTOOD:
others = read_until_over(fpout, timeout=timeout, nickname=nickname)
return others
elif cm.code == CTRL_ABORTED:
msg = 'The remote node "{}" aborted with the following error:'.format(nickname)
msg += '\n\n' + indent(cm.msg, "|", "error in {} |".format(nickname))
# others = self.read_until_over()
raise RemoteNodeAborted(msg)
elif cm.code == CTRL_NOT_UNDERSTOOD:
_others = read_until_over(fpout, timeout=timeout, nickname=nickname)
msg = 'The remote node "{nickname}" reports that it did not understand the message:'.format(nickname=nickname)
msg += '\n\n' + indent(cm.msg, "|", "reported by {} |".format(nickname))
raise ExternalNodeDidNotUnderstand(msg)
else:
msg = 'Remote node raised unknown code %s: %s' % (cm, cm.code)
raise ExternalProtocolViolation(msg)
ControlMessage = namedtuple('ControlMessage', 'code msg')
def interpret_control_message(m):
if not isinstance(m, dict):
msg = 'Expected dictionary, not {}.'.format(type(m))
raise Malformed(msg)
if not FIELD_CONTROL in m:
msg = 'Expected field {}, obtained {}'.format(FIELD_CONTROL, list(m))
raise Malformed(msg)
code = m[FIELD_CONTROL]
msg = m.get(FIELD_DATA, None)
return ControlMessage(code, msg)
def read_until_over(fpout, timeout, nickname):
""" Raises RemoteNodeAborted, TimeoutError """
res = []
waiting_for = 'Reading reply of {}.'.format(nickname)
while True:
try:
wm = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
if wm.get(FIELD_CONTROL, '') == CTRL_ABORTED:
m = 'External node "{}" aborted:'.format(nickname)
m += '\n\n' + indent(wm.get(FIELD_DATA, None), "|",
"error in {} |".format(nickname))
raise RemoteNodeAborted(m)
if wm.get(FIELD_CONTROL, '') == CTRL_OVER:
# logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res))
break
# logger.info(f'Node "{nickname}" sent %s.' % len(wm))
except StopIteration:
msg = 'External node "{}" closed communication.'.format(nickname)
raise RemoteNodeAborted(msg)
except TimeoutError:
msg = 'Timeout while reading output of node "{}".'.format(nickname)
raise TimeoutError(msg)
res.append(wm)
return res | zuper-nodes-python2-z5 | /zuper-nodes-python2-z5-5.0.14.tar.gz/zuper-nodes-python2-z5-5.0.14/src/zuper_nodes_python2/outside.py | outside.py |
from __future__ import unicode_literals
import os
import sys
import time
import traceback
import cbor2 as cbor
from . import logger
from .constants import *
# Python 2 compatibility.
try:
TimeoutError
except NameError:
import socket
TimeoutError = socket.timeout
__all__ = ['wrap_direct', 'Context']
class Context:
def info(self, s):
pass
def error(self, s):
pass
def debug(self, s):
pass
def warning(self, s):
pass
def write(self, topic, data):
pass
# noinspection PyBroadException
def wrap_direct(agent):
logger.info('python %s' % ".".join(map(str, sys.version_info)))
data_in = os.environ.get('AIDONODE_DATA_IN', '/dev/stdin')
data_out = os.environ.get('AIDONODE_DATA_OUT', '/dev/stdout')
while not os.path.exists(data_in):
logger.info('Waiting for %s to be created.' % data_in)
time.sleep(1)
if data_in == '/dev/stdin':
f_in = sys.stdin
else:
f_in = open(data_in, 'rb')
# f_in = io.BufferedReader(io.open(f_in.fileno()))
# f_in = sys.stdin
if data_out.startswith('fifo:'):
data_out = data_out.lstrip('fifo:')
os.mkfifo(data_out)
logger.info('Opening fifo %s for writing. Will block until reader appears.' % data_out)
f_out = open(data_out, 'wb')
logger.info('Starting reading from %s' % data_in)
try:
while True:
# whatever
# logger.info('Reading...')
try:
msg = cbor.load(f_in)
except IOError as e:
if e.errno == 29:
break
raise
if not isinstance(msg, dict) or ((FIELD_CONTROL not in msg) and (FIELD_TOPIC not in msg)):
# ignore things that we do not understand
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, "Protocol mismatch")
send_control_message(f_out, CTRL_OVER)
if FIELD_CONTROL in msg:
c = msg[FIELD_CONTROL]
if c == CTRL_CAPABILITIES:
his = msg[FIELD_DATA]
logger.info('His capabilities: %s' % his)
capabilities = {
'z2': {}
}
logger.info('My capabilities: %s' % capabilities)
send_control_message(f_out, CTRL_UNDERSTOOD)
send_control_message(f_out, CTRL_CAPABILITIES, capabilities)
send_control_message(f_out, CTRL_OVER)
else:
msg = 'Could not deal with control message "%s".' % c
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, msg)
send_control_message(f_out, CTRL_OVER)
elif FIELD_TOPIC in msg:
topic = msg[FIELD_TOPIC]
data = msg.get(FIELD_DATA, None)
fn = 'on_received_%s' % topic
if not hasattr(agent, fn):
msg = 'Could not deal with topic %s' % topic
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, msg)
send_control_message(f_out, CTRL_OVER)
else:
send_control_message(f_out, CTRL_UNDERSTOOD)
context = ConcreteContext(f_out)
f = getattr(agent, fn)
try:
f(context=context, data=data)
except BaseException:
s = traceback.format_exc()
logger.error(s)
try:
s = s.decode('utf-8')
except:
pass
send_control_message(f_out, CTRL_ABORTED, s)
raise
finally:
send_control_message(f_out, CTRL_OVER)
else:
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, "I expect a topic message")
send_control_message(f_out, CTRL_OVER)
logger.info('Graceful exit.')
except BaseException:
f_out.flush()
logger.error(traceback.format_exc())
sys.exit(1)
finally:
f_out.flush()
def send_control_message(f_out, c, msg=None):
m = {}
m[FIELD_COMPAT] = [PROTOCOL]
m[FIELD_CONTROL] = unicode(c)
m[FIELD_DATA] = msg
cbor.dump(m, f_out)
# logger.info('Sending control %s' % c)
f_out.flush()
def send_topic_message(f_out, topic, data):
m = {}
m[FIELD_COMPAT] = [PROTOCOL]
m[FIELD_TOPIC] = unicode(topic)
m[FIELD_DATA] = data
cbor.dump(m, f_out)
# logger.info('Sending topic %s' % topic)
f_out.flush()
class ConcreteContext(Context):
def __init__(self, f_out):
self.f_out = f_out
def info(self, s):
logger.info(s)
def error(self, s):
logger.error(s)
def debug(self, s):
logger.debug(s)
def warning(self, s):
logger.warning(s)
def write(self, topic, data=None):
send_topic_message(self.f_out, topic, data) | zuper-nodes-python2-z5 | /zuper-nodes-python2-z5-5.0.14.tar.gz/zuper-nodes-python2-z5-5.0.14/src/zuper_nodes_python2/imp.py | imp.py |
from __future__ import unicode_literals
import os
import socket
import time
import traceback
from collections import namedtuple
import cbor2 as cbor
from . import logger
from .constants import *
from .reading import read_next_cbor
from .utils import indent
# Python 2 compatibility.
try:
TimeoutError
except NameError:
import socket
TimeoutError = socket.timeout
__all__ = ['ComponentInterface']
class ExternalProtocolViolation(Exception):
pass
class ExternalNodeDidNotUnderstand(Exception):
pass
class RemoteNodeAborted(Exception):
pass
TimeoutError = socket.timeout
class Malformed(Exception):
pass
MsgReceived = namedtuple('MsgReceived', 'topic data')
class ComponentInterface(object):
def __init__(self, fnin, fnout, nickname, timeout=None):
self.nickname = nickname
try:
os.mkfifo(fnin)
except BaseException as e:
msg = 'Cannot create fifo {}'.format(fnin)
msg += '\n\n%s' % traceback.format_exc()
raise Exception(msg)
self.fpin = open(fnin, 'wb', buffering=0)
wait_for_creation(fnout)
self.fnout = fnout
f = open(fnout, 'rb', buffering=0)
# noinspection PyTypeChecker
self.fpout = f # BufferedReader(f, buffer_size=1)
self.nreceived = 0
self.node_protocol = None
self.data_protocol = None
self.timeout = timeout
def close(self):
self.fpin.close()
self.fpout.close()
def write_topic_and_expect(self, topic, data=None,
timeout=None,
timing=None,
expect=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, timing=timing)
ob = self.read_one(expect_topic=expect, timeout=timeout)
return ob
def write_topic_and_expect_zero(self, topic, data=None,
timeout=None,
timing=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, timing=timing)
msgs = read_reply(self.fpout, timeout=timeout,
nickname=self.nickname)
if msgs:
msg = 'Expecting zero, got %s' % msgs
raise ExternalProtocolViolation(msg)
def _write_topic(self, topic, data=None, timing=None):
msg = {FIELD_COMPAT: [PROTOCOL],
FIELD_TOPIC: topic,
FIELD_DATA: data,
FIELD_TIMING: timing}
j = self._serialize(msg)
self._write(j)
# logger.info('Written to topic "{topic}" >> {name}.'.format(topic=topic, name=self.nickname))
def _write(self, j):
try:
self.fpin.write(j)
self.fpin.flush()
except BrokenPipeError as e:
msg = ('While attempting to write to node "{nickname}", '
'I reckon that the pipe is closed and the node exited.').format(nickname=self.nickname)
try:
received = self.read_one(expect_topic=TOPIC_ABORTED)
if received.topic == TOPIC_ABORTED:
msg += '\n\nThis is the aborted message:'
msg += '\n\n' + received.data
except BaseException as e2:
msg += '\n\nI could not read any aborted message: {e2}'.format(e2=e2)
raise RemoteNodeAborted(msg)
def _serialize(self, msg):
j = cbor.dumps(msg)
return j
def read_one(self, expect_topic=None, timeout=None):
timeout = timeout or self.timeout
try:
if expect_topic:
waiting_for = 'Expecting topic "{expect_topic}" << {nickname}.'.format(expect_topic=expect_topic,
nickname=self.nickname)
else:
waiting_for = None
msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for,
nickname=self.nickname)
if len(msgs) == 0:
msg = 'Expected one message from node "{}". Got zero.'.format(self.nickname)
if expect_topic:
msg += '\nExpecting topic "{}".'.format(expect_topic)
raise ExternalProtocolViolation(msg)
if len(msgs) > 1:
msg = 'Expected only one message. Got {}.'.format(len(msgs))
raise ExternalProtocolViolation(msg)
msg = msgs[0]
if FIELD_TOPIC not in msg:
m = 'Invalid message does not contain the field "{}".'.format(FIELD_TOPIC)
m += '\n {}'.format(msg)
raise ExternalProtocolViolation(m)
topic = msg[FIELD_TOPIC]
if expect_topic:
if topic != expect_topic:
msg = 'I expected topic "{expect_topic}" but received "{topic}".'.format(expect_topic=expect_topic,
topic=topic)
raise ExternalProtocolViolation(msg)
if self.nreceived == 0:
msg1 = 'Received first message of topic %s' % topic
logger.info(msg1)
self.nreceived += 1
return MsgReceived(topic, msg[FIELD_DATA])
except StopIteration as e:
msg = 'EOF detected on %s after %d messages.' % (self.fnout, self.nreceived)
if expect_topic:
msg += ' Expected topic "{}".'.format(expect_topic)
raise StopIteration(msg)
except TimeoutError as e:
msg = 'Timeout declared after waiting %s sec on %s after having received %d messages.' % (timeout,
self.fnout,
self.nreceived)
if expect_topic:
msg += ' Expected topic "{}".'.format(expect_topic)
raise TimeoutError(msg)
def wait_for_creation(fn):
while not os.path.exists(fn):
msg = 'waiting for creation of %s' % fn
logger.info(msg)
time.sleep(1)
def read_reply(fpout, nickname, timeout=None, waiting_for=None):
""" Reads a control message. Returns if it is CTRL_UNDERSTOOD.
Raises:
TimeoutError
RemoteNodeAborted
ExternalNodeDidNotUnderstand
ExternalProtocolViolation otherwise. """
try:
wm = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
except StopIteration:
msg = 'Remote node closed communication (%s)' % waiting_for
raise RemoteNodeAborted(msg)
cm = interpret_control_message(wm)
if cm.code == CTRL_UNDERSTOOD:
others = read_until_over(fpout, timeout=timeout, nickname=nickname)
return others
elif cm.code == CTRL_ABORTED:
msg = 'The remote node "{}" aborted with the following error:'.format(nickname)
msg += '\n\n' + indent(cm.msg, "|", "error in {} |".format(nickname))
# others = self.read_until_over()
raise RemoteNodeAborted(msg)
elif cm.code == CTRL_NOT_UNDERSTOOD:
_others = read_until_over(fpout, timeout=timeout, nickname=nickname)
msg = 'The remote node "{nickname}" reports that it did not understand the message:'.format(nickname=nickname)
msg += '\n\n' + indent(cm.msg, "|", "reported by {} |".format(nickname))
raise ExternalNodeDidNotUnderstand(msg)
else:
msg = 'Remote node raised unknown code %s: %s' % (cm, cm.code)
raise ExternalProtocolViolation(msg)
ControlMessage = namedtuple('ControlMessage', 'code msg')
def interpret_control_message(m):
if not isinstance(m, dict):
msg = 'Expected dictionary, not {}.'.format(type(m))
raise Malformed(msg)
if not FIELD_CONTROL in m:
msg = 'Expected field {}, obtained {}'.format(FIELD_CONTROL, list(m))
raise Malformed(msg)
code = m[FIELD_CONTROL]
msg = m.get(FIELD_DATA, None)
return ControlMessage(code, msg)
def read_until_over(fpout, timeout, nickname):
""" Raises RemoteNodeAborted, TimeoutError """
res = []
waiting_for = 'Reading reply of {}.'.format(nickname)
while True:
try:
wm = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
if wm.get(FIELD_CONTROL, '') == CTRL_ABORTED:
m = 'External node "{}" aborted:'.format(nickname)
m += '\n\n' + indent(wm.get(FIELD_DATA, None), "|",
"error in {} |".format(nickname))
raise RemoteNodeAborted(m)
if wm.get(FIELD_CONTROL, '') == CTRL_OVER:
# logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res))
break
# logger.info(f'Node "{nickname}" sent %s.' % len(wm))
except StopIteration:
msg = 'External node "{}" closed communication.'.format(nickname)
raise RemoteNodeAborted(msg)
except TimeoutError:
msg = 'Timeout while reading output of node "{}".'.format(nickname)
raise TimeoutError(msg)
res.append(wm)
return res | zuper-nodes-python2 | /zuper-nodes-python2-2.1.5.tar.gz/zuper-nodes-python2-2.1.5/src/zuper_nodes_python2/outside.py | outside.py |
from __future__ import unicode_literals
import os
import sys
import time
import traceback
import cbor2 as cbor
from . import logger
from .constants import *
# Python 2 compatibility.
try:
TimeoutError
except NameError:
import socket
TimeoutError = socket.timeout
__all__ = ['wrap_direct', 'Context']
class Context:
def info(self, s):
pass
def error(self, s):
pass
def debug(self, s):
pass
def warning(self, s):
pass
def write(self, topic, data):
pass
# noinspection PyBroadException
def wrap_direct(agent):
logger.info('python %s' % ".".join(map(str, sys.version_info)))
data_in = os.environ.get('AIDONODE_DATA_IN', '/dev/stdin')
data_out = os.environ.get('AIDONODE_DATA_OUT', '/dev/stdout')
while not os.path.exists(data_in):
logger.info('Waiting for %s to be created.' % data_in)
time.sleep(1)
if data_in == '/dev/stdin':
f_in = sys.stdin
else:
f_in = open(data_in, 'rb')
# f_in = io.BufferedReader(io.open(f_in.fileno()))
# f_in = sys.stdin
if data_out.startswith('fifo:'):
data_out = data_out.lstrip('fifo:')
os.mkfifo(data_out)
logger.info('Opening fifo %s for writing. Will block until reader appears.' % data_out)
f_out = open(data_out, 'wb')
logger.info('Starting reading from %s' % data_in)
try:
while True:
# whatever
# logger.info('Reading...')
try:
msg = cbor.load(f_in)
except IOError as e:
if e.errno == 29:
break
raise
if not isinstance(msg, dict) or ((FIELD_CONTROL not in msg) and (FIELD_TOPIC not in msg)):
# ignore things that we do not understand
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, "Protocol mismatch")
send_control_message(f_out, CTRL_OVER)
if FIELD_CONTROL in msg:
c = msg[FIELD_CONTROL]
if c == CTRL_CAPABILITIES:
his = msg[FIELD_DATA]
logger.info('His capabilities: %s' % his)
capabilities = {
'z2': {}
}
logger.info('My capabilities: %s' % capabilities)
send_control_message(f_out, CTRL_UNDERSTOOD)
send_control_message(f_out, CTRL_CAPABILITIES, capabilities)
send_control_message(f_out, CTRL_OVER)
else:
msg = 'Could not deal with control message "%s".' % c
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, msg)
send_control_message(f_out, CTRL_OVER)
elif FIELD_TOPIC in msg:
topic = msg[FIELD_TOPIC]
data = msg.get(FIELD_DATA, None)
fn = 'on_received_%s' % topic
if not hasattr(agent, fn):
msg = 'Could not deal with topic %s' % topic
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, msg)
send_control_message(f_out, CTRL_OVER)
else:
send_control_message(f_out, CTRL_UNDERSTOOD)
context = ConcreteContext(f_out)
f = getattr(agent, fn)
try:
f(context=context, data=data)
except BaseException:
s = traceback.format_exc()
logger.error(s)
try:
s = s.decode('utf-8')
except:
pass
send_control_message(f_out, CTRL_ABORTED, s)
raise
finally:
send_control_message(f_out, CTRL_OVER)
else:
send_control_message(f_out, CTRL_NOT_UNDERSTOOD, "I expect a topic message")
send_control_message(f_out, CTRL_OVER)
logger.info('Graceful exit.')
except BaseException:
f_out.flush()
logger.error(traceback.format_exc())
sys.exit(1)
finally:
f_out.flush()
def send_control_message(f_out, c, msg=None):
m = {}
m[FIELD_COMPAT] = [PROTOCOL]
m[FIELD_CONTROL] = unicode(c)
m[FIELD_DATA] = msg
cbor.dump(m, f_out)
logger.info('Sending control %s' % c)
f_out.flush()
def send_topic_message(f_out, topic, data):
m = {}
m[FIELD_COMPAT] = [PROTOCOL]
m[FIELD_TOPIC] = unicode(topic)
m[FIELD_DATA] = data
cbor.dump(m, f_out)
logger.info('Sending topic %s' % topic)
f_out.flush()
class ConcreteContext(Context):
def __init__(self, f_out):
self.f_out = f_out
def info(self, s):
logger.info(s)
def error(self, s):
logger.error(s)
def debug(self, s):
logger.debug(s)
def warning(self, s):
logger.warning(s)
def write(self, topic, data=None):
send_topic_message(self.f_out, topic, data) | zuper-nodes-python2 | /zuper-nodes-python2-2.1.5.tar.gz/zuper-nodes-python2-2.1.5/src/zuper_nodes_python2/imp.py | imp.py |
import termcolor
__all__ = ['setup_logging_color', 'setup_logging_format', 'setup_logging']
def get_FORMAT_datefmt():
def dark(s):
return termcolor.colored(s, attrs=['dark'])
pre = dark('%(asctime)s|')
pre += '%(name)s'
pre += dark('|%(filename)s:%(lineno)s|%(funcName)s(): ')
FORMAT = pre + "%(message)s"
datefmt = "%H:%M:%S"
return FORMAT, datefmt
# noinspection PyUnresolvedReferences
def setup_logging_format():
from logging import Logger, StreamHandler, Formatter
import logging
FORMAT, datefmt = get_FORMAT_datefmt()
logging.basicConfig(format=FORMAT, datefmt=datefmt)
if Logger.root.handlers: # @UndefinedVariable
for handler in Logger.root.handlers: # @UndefinedVariable
if isinstance(handler, StreamHandler):
formatter = Formatter(FORMAT, datefmt=datefmt)
handler.setFormatter(formatter)
else:
logging.basicConfig(format=FORMAT, datefmt=datefmt)
def add_coloring_to_emit_ansi(fn):
# add methods we need to the class
def new(*args):
levelno = args[1].levelno
if levelno >= 50:
color = '\x1b[31m' # red
elif levelno >= 40:
color = '\x1b[31m' # red
elif levelno >= 30:
color = '\x1b[33m' # yellow
elif levelno >= 20:
color = '\x1b[32m' # green
elif levelno >= 10:
color = '\x1b[35m' # pink
else:
color = '\x1b[0m' # normal
msg = str(args[1].msg)
lines = msg.split('\n')
def color_line(l):
return "%s%s%s" % (color, l, '\x1b[0m') # normal
lines = list(map(color_line, lines))
args[1].msg = "\n".join(lines)
return fn(*args)
return new
def setup_logging_color():
import platform
if platform.system() != 'Windows':
emit2 = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
logging.StreamHandler.emit = emit2
def setup_logging():
# logging.basicConfig()
setup_logging_color()
setup_logging_format()
import logging
logging.basicConfig()
setup_logging() | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes/col_logging.py | col_logging.py |
from pyparsing import Suppress, Literal, Keyword, ParserElement, pyparsing_common, opAssoc, operatorPrecedence
from .language import ExpectInputReceived, ExpectOutputProduced, InSequence, ZeroOrMore, ZeroOrOne, Either, Language, \
OneOrMore
__all__ = [
'parse_language',
'language_to_str',
'Syntax',
]
ParserElement.enablePackrat()
S = Suppress
L = Literal
K = Keyword
def parse_language(s: str) -> Language:
res = Syntax.language.parseString(s, parseAll=True)
res = res[0]
return res
def language_to_str(l: Language):
def quote_if(s):
if ';' in s or '|' in s:
return "(" + s + ')'
else:
return s
if isinstance(l, ExpectInputReceived):
return f"in:{l.channel}"
if isinstance(l, ExpectOutputProduced):
return f"out:{l.channel}"
if isinstance(l, InSequence):
return " ; ".join(quote_if(language_to_str(_)) for _ in l.ls)
if isinstance(l, Either):
return " | ".join(quote_if(language_to_str(_)) for _ in l.ls)
if isinstance(l, ZeroOrMore):
return "(" + language_to_str(l.l) + ")" + '*'
if isinstance(l, OneOrMore):
return "(" + language_to_str(l.l) + ")" + '+'
if isinstance(l, ZeroOrOne):
return "(" + language_to_str(l.l) + ")" + '?'
raise NotImplementedError(type(l))
def on_input_received(s, loc, tokens):
return ExpectInputReceived(tokens[0])
def on_output_produced(s, loc, tokens):
return ExpectOutputProduced(tokens[0])
def on_in_sequence(tokens):
return InSequence(tuple(tokens[0]))
def on_either(tokens):
return Either(tuple(tokens[0]))
def on_zero_or_one(tokens):
return ZeroOrOne(tokens[0][0])
def on_zero_or_more(tokens):
return ZeroOrMore(tokens[0][0])
def on_one_or_more(tokens):
return OneOrMore(tokens[0][0])
class Syntax:
input_received = S(K("in") + L(":")) + pyparsing_common.identifier
output_produced = S(K("out") + L(":")) + pyparsing_common.identifier
basic = input_received | output_produced
language = operatorPrecedence(basic,
[
(S(L('*')), 1, opAssoc.LEFT, on_zero_or_more),
(S(L('+')), 1, opAssoc.LEFT, on_one_or_more),
(S(L('?')), 1, opAssoc.LEFT, on_zero_or_one),
(S(L(';')), 2, opAssoc.LEFT, on_in_sequence),
(S(L('|')), 2, opAssoc.LEFT, on_either),
])
input_received.setParseAction(on_input_received)
output_produced.setParseAction(on_output_produced) | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes/language_parse.py | language_parse.py |
from dataclasses import dataclass
from typing import Union, Tuple, Optional, Set
from .language import Language, OutputProduced, InputReceived, Event, ExpectInputReceived, ExpectOutputProduced, \
InSequence, ZeroOrMore, Either, OneOrMore, ZeroOrOne
from contracts.utils import indent
class Result:
pass
@dataclass
class Enough(Result):
pass
@dataclass
class Unexpected(Result):
msg: str
def __repr__(self):
return 'Unexpected:' + indent(self.msg, ' ')
@dataclass
class NeedMore(Result):
pass
import networkx as nx
NodeName = Tuple[str, ...]
class Always:
pass
def get_nfa(g: Optional[nx.DiGraph], start_node: NodeName, accept_node: NodeName, l: Language,
prefix: Tuple[str, ...] = ()):
# assert start_node != accept_node
if not start_node in g:
g.add_node(start_node, label="/".join(start_node))
if not accept_node in g:
g.add_node(accept_node, label="/".join(accept_node))
if isinstance(l, ExpectOutputProduced):
g.add_edge(start_node, accept_node, event_match=l, label=f'out/{l.channel}')
elif isinstance(l, ExpectInputReceived):
g.add_edge(start_node, accept_node, event_match=l, label=f'in/{l.channel}')
elif isinstance(l, InSequence):
current = start_node
for i, li in enumerate(l.ls):
# if i == len(l.ls) - 1:
# n = accept_node
# else:
n = prefix + (f'after{i}',)
g.add_node(n)
# logger.debug(f'sequence {i} start {current} to {n}')
get_nfa(g, start_node=current, accept_node=n, prefix=prefix + (f'{i}',), l=li)
current = n
g.add_edge(current, accept_node, event_match=Always(), label='always')
elif isinstance(l, ZeroOrMore):
# logger.debug(f'zeroormore {start_node} -> {accept_node}')
g.add_edge(start_node, accept_node, event_match=Always(), label='always')
get_nfa(g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ('zero_or_more',))
elif isinstance(l, OneOrMore):
# start to accept
get_nfa(g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ('one_or_more', '1'))
# accept to accept
get_nfa(g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ('one_or_more', '2'))
elif isinstance(l, ZeroOrOne):
g.add_edge(start_node, accept_node, event_match=Always(), label='always')
get_nfa(g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ('zero_or_one',))
elif isinstance(l, Either):
for i, li in enumerate(l.ls):
get_nfa(g, start_node=start_node, accept_node=accept_node, l=li, prefix=prefix + (f'either{i}',))
else:
assert False, type(l)
def event_matches(l: Language, event: Event):
if isinstance(l, ExpectInputReceived):
return isinstance(event, InputReceived) and event.channel == l.channel
if isinstance(l, ExpectOutputProduced):
return isinstance(event, OutputProduced) and event.channel == l.channel
if isinstance(l, Always):
return False
raise NotImplementedError(l)
START = ('start',)
ACCEPT = ('accept',)
class LanguageChecker:
g: nx.DiGraph
active: Set[NodeName]
def __init__(self, language: Language):
self.g = nx.MultiDiGraph()
self.start_node = START
self.accept_node = ACCEPT
get_nfa(g=self.g, l=language, start_node=self.start_node, accept_node=self.accept_node, prefix=())
# for (a, b, data) in self.g.out_edges(data=True):
# print(f'{a} -> {b} {data["event_match"]}')
a = 2
for n in self.g:
if n not in [START, ACCEPT]:
# noinspection PyUnresolvedReferences
self.g.node[n]['label'] = f'S{a}'
a += 1
elif n == START:
# noinspection PyUnresolvedReferences
self.g.node[n]['label'] = 'start'
elif n == ACCEPT:
# noinspection PyUnresolvedReferences
self.g.node[n]['label'] = 'accept'
self.active = {self.start_node}
# logger.debug(f'active {self.active}')
self._evolve_empty()
def _evolve_empty(self):
while True:
now_active = set()
for node in self.active:
nalways = 0
nother = 0
for (_, neighbor, data) in self.g.out_edges([node], data=True):
# print(f'-> {neighbor} {data["event_match"]}')
if isinstance(data['event_match'], Always):
now_active.add(neighbor)
nalways += 1
else:
nother += 1
if nother or (nalways == 0):
now_active.add(node)
if self.active == now_active:
break
self.active = now_active
def push(self, event) -> Result:
now_active = set()
# print(f'push: active is {self.active}')
# print(f'push: considering {event}')
for node in self.active:
for (_, neighbor, data) in self.g.out_edges([node], data=True):
if event_matches(data['event_match'], event):
# print(f'now activating {neighbor}')
now_active.add(neighbor)
# else:
# print(f"event_match {event} does not match {data['event_match']}")
#
# if not now_active:
# return Unexpected('')
self.active = now_active
# print(f'push: now active is {self.active}')
self._evolve_empty()
# print(f'push: now active is {self.active}')
return self.finish()
def finish(self) -> Union[NeedMore, Enough, Unexpected]:
# print(f'finish: active is {self.active}')
if not self.active:
return Unexpected('no active')
if self.accept_node in self.active:
return Enough()
return NeedMore()
def get_active_states_names(self):
return [self.g.nodes[_]['label'] for _ in self.active]
def get_expected_events(self) -> Set:
events = set()
for state in self.active:
for (_, neighbor, data) in self.g.out_edges([state], data=True):
em = data['event_match']
if not isinstance(em, Always):
events.add(em)
return events | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes/language_recognize.py | language_recognize.py |
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import Dict, Iterator, Optional, Tuple
# Events
ChannelName = str
class Event:
pass
@dataclass(frozen=True, unsafe_hash=True)
class InputReceived(Event):
channel: ChannelName
@dataclass(frozen=True, unsafe_hash=True)
class OutputProduced(Event):
channel: ChannelName
# Language over events
class Language(metaclass=ABCMeta):
@abstractmethod
def collect_simple_events(self) -> Iterator[Event]:
pass
@dataclass(frozen=True, unsafe_hash=True)
class ExpectInputReceived(Language):
channel: ChannelName
def collect_simple_events(self):
yield InputReceived(self.channel)
@dataclass(frozen=True, unsafe_hash=True)
class ExpectOutputProduced(Language):
channel: ChannelName
def collect_simple_events(self):
yield OutputProduced(self.channel)
@dataclass(frozen=True, unsafe_hash=True)
class InSequence(Language):
ls: Tuple[Language, ...]
def collect_simple_events(self):
for l in self.ls:
yield from l.collect_simple_events()
@dataclass(frozen=True, unsafe_hash=True)
class ZeroOrOne(Language):
l: Language
def collect_simple_events(self):
yield from self.l.collect_simple_events()
@dataclass(frozen=True, unsafe_hash=True)
class ZeroOrMore(Language):
l: Language
def collect_simple_events(self):
yield from self.l.collect_simple_events()
@dataclass(frozen=True, unsafe_hash=True)
class OneOrMore(Language):
l: Language
def collect_simple_events(self):
yield from self.l.collect_simple_events()
@dataclass(frozen=True, unsafe_hash=True)
class Either(Language):
ls: Tuple[Language, ...]
def collect_simple_events(self):
for l in self.ls:
yield from l.collect_simple_events()
# Interaction protocol
@dataclass
class InteractionProtocol:
# Description
description: str
# Type for each input or output
inputs: Dict[ChannelName, type]
outputs: Dict[ChannelName, type]
# The interaction language
language: str
# interaction: Language = None
def __post_init__(self):
from .language_parse import parse_language, language_to_str
self.interaction = parse_language(self.language)
simple_events = list(self.interaction.collect_simple_events())
for e in simple_events:
if isinstance(e, InputReceived):
if e.channel not in self.inputs:
msg = f'Could not find input channel "{e.channel}" among {sorted(self.inputs)}.'
raise ValueError(msg)
if isinstance(e, OutputProduced):
if e.channel not in self.outputs:
msg = f'Could not find output channel "{e.channel}" among {sorted(self.outputs)}.'
raise ValueError(msg)
self.language = language_to_str(self.interaction)
def particularize(ip: InteractionProtocol,
description: Optional[str] = None,
inputs: Optional[Dict[str, type]] = None,
outputs: Optional[Dict[str, type]] = None) -> InteractionProtocol:
inputs2 = dict(ip.inputs)
inputs2.update(inputs or {})
outputs2 = dict(ip.outputs)
outputs2.update(outputs or {})
language = ip.language
description = description or ip.description
protocol2 = InteractionProtocol(description, inputs2, outputs2, language)
from .compatibility import check_compatible_protocol
check_compatible_protocol(protocol2, ip)
return protocol2 | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes/language.py | language.py |
import argparse
import json
import os
import socket
import time
import traceback
from dataclasses import dataclass
from typing import *
import yaml
from zuper_ipce import object_from_ipce, ipce_from_object, IESO
from contracts.utils import format_obs
from zuper_commons.text import indent
from zuper_commons.types import check_isinstance
from zuper_nodes import InteractionProtocol, InputReceived, OutputProduced, Unexpected, LanguageChecker
from zuper_nodes.structures import TimingInfo, local_time, TimeSpec, timestamp_from_seconds, DecodingError, \
ExternalProtocolViolation, NotConforming, ExternalTimeout, InternalProblem
from .reading import inputs
from .streams import open_for_read, open_for_write
from .struct import RawTopicMessage, ControlMessage
from .utils import call_if_fun_exists
from .writing import Sink
from . import logger, logger_interaction
from .interface import Context
from .meta_protocol import basic_protocol, SetConfig, ProtocolDescription, ConfigDescription, \
BuildDescription, NodeDescription
class ConcreteContext(Context):
protocol: InteractionProtocol
to_write: List[RawTopicMessage]
def __init__(self, sink: Sink, protocol: InteractionProtocol,
node_name: str, tout: Dict[str, str]):
self.sink = sink
self.protocol = protocol
self.pc = LanguageChecker(protocol.interaction)
self.node_name = node_name
self.hostname = socket.gethostname()
self.tout = tout
self.to_write = []
self.last_timing = None
def set_last_timing(self, timing: TimingInfo):
self.last_timing = timing
def get_hostname(self):
return self.hostname
def write(self, topic, data, timing=None, with_schema=False):
if topic not in self.protocol.outputs:
msg = f'Output channel "{topic}" not found in protocol; know {sorted(self.protocol.outputs)}.'
raise Exception(msg)
# logger.info(f'Writing output "{topic}".')
klass = self.protocol.outputs[topic]
if isinstance(klass, type):
check_isinstance(data, klass)
event = OutputProduced(topic)
res = self.pc.push(event)
if isinstance(res, Unexpected):
msg = f'Unexpected output {topic}: {res}'
logger.error(msg)
return
klass = self.protocol.outputs[topic]
if isinstance(data, dict):
data = object_from_ipce(data, klass)
if timing is None:
timing = self.last_timing
if timing is not None:
s = time.time()
if timing.received is None:
# XXX
time1 = timestamp_from_seconds(s)
else:
time1 = timing.received.time
processed = TimeSpec(time=time1,
time2=timestamp_from_seconds(s),
frame='epoch',
clock=socket.gethostname())
timing.processed[self.node_name] = processed
timing.received = None
topic_o = self.tout.get(topic, topic)
ieso = IESO(use_ipce_from_typelike_cache=True, with_schema=with_schema)
data = ipce_from_object(data, ieso=ieso)
if timing is not None:
ieso = IESO(use_ipce_from_typelike_cache=True, with_schema=False)
timing_o = ipce_from_object(timing, ieso=ieso)
else:
timing_o = None
rtm = RawTopicMessage(topic_o, data, timing_o)
self.to_write.append(rtm)
def get_to_write(self) -> List[RawTopicMessage]:
""" Returns the messages to send and resets the queue"""
res = self.to_write
self.to_write = []
return res
def log(self, s):
prefix = f'{self.hostname}:{self.node_name}: '
logger.info(prefix + s)
def info(self, s):
prefix = f'{self.hostname}:{self.node_name}: '
logger.info(prefix + s)
def debug(self, s):
prefix = f'{self.hostname}:{self.node_name}: '
logger.debug(prefix + s)
def warning(self, s):
prefix = f'{self.hostname}:{self.node_name}: '
logger.warning(prefix + s)
def error(self, s):
prefix = f'{self.hostname}:{self.node_name}: '
logger.error(prefix + s)
def get_translation_table(t: str) -> Tuple[Dict[str, str], Dict[str, str]]:
tout = {}
tin = {}
for t in t.split(','):
ts = t.split(':')
if ts[0] == 'in':
tin[ts[1]] = ts[2]
if ts[0] == 'out':
tout[ts[1]] = ts[2]
return tin, tout
def check_variables():
for k, v in os.environ.items():
if k.startswith('AIDO') and k not in KNOWN:
msg = f'I do not expect variable "{k}" set in environment with value "{v}".'
msg += ' I expect: %s' % ", ".join(KNOWN)
logger.warn(msg)
from .constants import *
def run_loop(node: object, protocol: InteractionProtocol, args: Optional[List[str]] = None):
parser = argparse.ArgumentParser()
check_variables()
data_in = os.environ.get(ENV_DATA_IN, '/dev/stdin')
data_out = os.environ.get(ENV_DATA_OUT, '/dev/stdout')
default_name = os.environ.get(ENV_NAME, None)
translate = os.environ.get(ENV_TRANSLATE, '')
config = os.environ.get(ENV_CONFIG, '{}')
parser.add_argument('--data-in', default=data_in)
parser.add_argument('--data-out', default=data_out)
parser.add_argument('--name', default=default_name)
parser.add_argument('--config', default=config)
parser.add_argument('--translate', default=translate)
parser.add_argument('--loose', default=False, action='store_true')
parsed = parser.parse_args(args)
tin, tout = get_translation_table(parsed.translate)
# expect in:name1:name2, out:name2:name1
fin = parsed.data_in
fout = parsed.data_out
fi = open_for_read(fin)
fo = open_for_write(fout)
node_name = parsed.name or type(node).__name__
logger.name = node_name
config = yaml.load(config, Loader=yaml.SafeLoader)
try:
loop(node_name, fi, fo, node, protocol, tin, tout,
config=config)
except BaseException as e:
msg = f'Error in node {node_name}'
logger.error(f'Error in node {node_name}: \n{traceback.format_exc()}')
raise Exception(msg) from e
finally:
fo.flush()
fo.close()
fi.close()
def loop(node_name: str, fi, fo, node, protocol: InteractionProtocol, tin, tout, config: dict):
logger.info(f'Starting reading')
initialized = False
context_data = None
sink = Sink(fo)
try:
context_data = ConcreteContext(sink=sink, protocol=protocol,
node_name=node_name, tout=tout)
context_meta = ConcreteContext(sink=sink, protocol=basic_protocol,
node_name=node_name + '.wrapper', tout=tout)
wrapper = MetaHandler(node, protocol)
for k, v in config.items():
wrapper.set_config(k, v)
waiting_for = 'Expecting control message or one of: %s' % context_data.pc.get_expected_events()
for parsed in inputs(fi, waiting_for=waiting_for):
if isinstance(parsed, ControlMessage):
expect = [CTRL_CAPABILITIES]
if parsed.code not in expect:
msg = f'I expect any of {expect}, not "{parsed.code}".'
sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg)
sink.write_control_message(CTRL_OVER)
else:
if parsed.code == CTRL_CAPABILITIES:
my_capabilities = {
'z2': {
CAPABILITY_PROTOCOL_REFLECTION: True
}
}
sink.write_control_message(CTRL_UNDERSTOOD)
sink.write_control_message(CTRL_CAPABILITIES, my_capabilities)
sink.write_control_message(CTRL_OVER)
else:
assert False
elif isinstance(parsed, RawTopicMessage):
parsed.topic = tin.get(parsed.topic, parsed.topic)
logger_interaction.info(f'Received message of topic "{parsed.topic}".')
if parsed.topic.startswith('wrapper.'):
parsed.topic = parsed.topic.replace('wrapper.', '')
receiver0 = wrapper
context0 = context_meta
else:
receiver0 = node
context0 = context_data
if receiver0 is node and not initialized:
try:
call_if_fun_exists(node, 'init', context=context_data)
except BaseException as e:
msg = "Exception while calling the node's init() function."
msg += '\n\n' + indent(traceback.format_exc(), '| ')
context_meta.write('aborted', msg)
raise Exception(msg) from e
initialized = True
if parsed.topic not in context0.protocol.inputs:
msg = f'Input channel "{parsed.topic}" not found in protocol. '
msg += f'\n\nKnown channels: {sorted(context0.protocol.inputs)}'
sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg)
sink.write_control_message(CTRL_OVER)
raise ExternalProtocolViolation(msg)
sink.write_control_message(CTRL_UNDERSTOOD)
try:
handle_message_node(parsed, receiver0, context0)
to_write = context0.get_to_write()
# msg = f'I wrote {len(to_write)} messages.'
# logger.info(msg)
for rtm in to_write:
sink.write_topic_message(rtm.topic, rtm.data, rtm.timing)
sink.write_control_message(CTRL_OVER)
except BaseException as e:
msg = f'Exception while handling a message on topic "{parsed.topic}".'
msg += '\n\n' + indent(traceback.format_exc(), '| ')
sink.write_control_message(CTRL_ABORTED, msg)
sink.write_control_message(CTRL_OVER)
raise InternalProblem(msg) from e # XXX
else:
assert False
res = context_data.pc.finish()
if isinstance(res, Unexpected):
msg = f'Protocol did not finish: {res}'
logger_interaction.error(msg)
if initialized:
try:
call_if_fun_exists(node, 'finish', context=context_data)
except BaseException as e:
msg = "Exception while calling the node's finish() function."
msg += '\n\n' + indent(traceback.format_exc(), '| ')
context_meta.write('aborted', msg)
raise Exception(msg) from e
except BrokenPipeError:
msg = 'The other side closed communication.'
logger.info(msg)
return
except ExternalTimeout as e:
msg = 'Could not receive any other messages.'
if context_data:
msg += '\n Expecting one of: %s' % context_data.pc.get_expected_events()
sink.write_control_message(CTRL_ABORTED, msg)
sink.write_control_message(CTRL_OVER)
raise ExternalTimeout(msg) from e
except InternalProblem:
raise
except BaseException as e:
msg = f"Unexpected error:"
msg += '\n\n' + indent(traceback.format_exc(), '| ')
sink.write_control_message(CTRL_ABORTED, msg)
sink.write_control_message(CTRL_OVER)
raise InternalProblem(msg) from e # XXX
class MetaHandler:
def __init__(self, node, protocol):
self.node = node
self.protocol = protocol
def set_config(self, key, value):
if hasattr(self.node, ATT_CONFIG):
config = self.node.config
if hasattr(config, key):
setattr(self.node.config, key, value)
else:
msg = f'Could not find config key {key}'
raise ValueError(msg)
else:
msg = 'Node does not have the "config" attribute.'
raise ValueError(msg)
def on_received_set_config(self, context, data: SetConfig):
key = data.key
value = data.value
try:
self.set_config(key, value)
except ValueError as e:
context.write('set_config_error', str(e))
else:
context.write('set_config_ack', None)
def on_received_describe_protocol(self, context):
desc = ProtocolDescription(data=self.protocol, meta=basic_protocol)
context.write('protocol_description', desc)
def on_received_describe_config(self, context):
K = type(self.node)
if hasattr(K, '__annotations__') and ATT_CONFIG in K.__annotations__:
config_type = K.__annotations__[ATT_CONFIG]
config_current = getattr(self.node, ATT_CONFIG)
else:
@dataclass
class NoConfig:
pass
config_type = NoConfig
config_current = NoConfig()
desc = ConfigDescription(config=config_type, current=config_current)
context.write('config_description', desc, with_schema=True)
def on_received_describe_node(self, context):
desc = NodeDescription(self.node.__doc__)
context.write('node_description', desc, with_schema=True)
def on_received_describe_build(self, context):
desc = BuildDescription()
context.write('build_description', desc, with_schema=True)
def handle_message_node(parsed: RawTopicMessage,
agent, context: ConcreteContext):
protocol = context.protocol
topic = parsed.topic
data = parsed.data
pc = context.pc
klass = protocol.inputs[topic]
try:
ob = object_from_ipce(data, klass)
except BaseException as e:
msg = f'Cannot deserialize object for topic "{topic}" expecting {klass}.'
try:
parsed = json.dumps(parsed, indent=2)
except:
parsed = str(parsed)
msg += '\n\n' + indent(parsed, '|', 'parsed: |')
raise DecodingError(msg) from e
if parsed.timing is not None:
timing = object_from_ipce(parsed.timing, TimingInfo)
else:
timing = TimingInfo()
timing.received = local_time()
context.set_last_timing(timing)
# logger.info(f'Before push the state is\n{pc}')
event = InputReceived(topic)
expected = pc.get_expected_events()
res = pc.push(event)
# names = pc.get_active_states_names()
# logger.info(f'After push of {event}: result \n{res} active {names}' )
if isinstance(res, Unexpected):
msg = f'Unexpected input "{topic}": {res}'
msg += f'\nI expected: {expected}'
msg += '\n' + format_obs(dict(pc=pc))
logger.error(msg)
raise ExternalProtocolViolation(msg)
else:
expect_fn = f'on_received_{topic}'
call_if_fun_exists(agent, expect_fn, data=ob, context=context, timing=timing)
def check_implementation(node, protocol: InteractionProtocol):
logger.info('checking implementation')
for n in protocol.inputs:
expect_fn = f'on_received_{n}'
if not hasattr(node, expect_fn):
msg = f'Missing function {expect_fn}'
msg += f'\nI know {sorted(type(node).__dict__)}'
raise NotConforming(msg)
for x in type(node).__dict__:
if x.startswith('on_received_'):
input_name = x.replace('on_received_', '')
if input_name not in protocol.inputs:
msg = f'The node has function "{x}" but there is no input "{input_name}".'
raise NotConforming(msg) | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes_wrapper/wrapper.py | wrapper.py |
import os
import stat
import time
from io import BufferedReader
from zuper_commons.fs import make_sure_dir_exists
from . import logger_interaction
from . import logger
def wait_for_creation(fn):
while not os.path.exists(fn):
msg = 'waiting for creation of %s' % fn
logger.info(msg)
time.sleep(1)
def open_for_read(fin, timeout=None):
t0 = time.time()
# first open reader file in case somebody is waiting for it
while not os.path.exists(fin):
delta = time.time() - t0
if timeout is not None and (delta > timeout):
msg = f'The file {fin} was not created before {timeout} seconds. I give up.'
raise EnvironmentError(msg)
logger_interaction.info(f'waiting for file {fin} to be created')
time.sleep(1)
logger_interaction.info(f'Opening input {fin}')
fi = open(fin, 'rb', buffering=0)
# noinspection PyTypeChecker
fi = BufferedReader(fi, buffer_size=1)
return fi
def open_for_write(fout):
if fout == '/dev/stdout':
return open('/dev/stdout', 'wb', buffering=0)
else:
wants_fifo = fout.startswith('fifo:')
fout = fout.replace('fifo:', '')
logger_interaction.info(f'Opening output file {fout} (wants fifo: {wants_fifo})')
if not os.path.exists(fout):
if wants_fifo:
make_sure_dir_exists(fout)
os.mkfifo(fout)
logger_interaction.info('Fifo created.')
else:
is_fifo = stat.S_ISFIFO(os.stat(fout).st_mode)
if wants_fifo and not is_fifo:
logger_interaction.info(f'Recreating {fout} as a fifo.')
os.unlink(fout)
os.mkfifo(fout)
if wants_fifo:
logger_interaction.info('Fifo detected. Opening will block until a reader appears.')
make_sure_dir_exists(fout)
fo = open(fout, 'wb', buffering=0)
if wants_fifo:
logger_interaction.info('Reader has connected to my fifo')
return fo | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes_wrapper/streams.py | streams.py |
from dataclasses import dataclass
from typing import *
from zuper_nodes import InteractionProtocol
@dataclass
class SetConfig:
key: str
value: Any
@dataclass
class ConfigDescription:
config: type
current: Any
@dataclass
class NodeDescription:
description: str
@dataclass
class BuildDescription:
pass
@dataclass
class ProtocolDescription:
data: InteractionProtocol
meta: InteractionProtocol
@dataclass
class CommsHealth:
# ignored because not compatible
ignored: Dict[str, int]
# unexpected topics
unexpected: Dict[str, int]
# malformed data
malformed: Dict[str, int]
# if we are completely lost
unrecoverable_protocol_error: bool
@dataclass
class NodeHealth:
# there is a critical error that makes it useless to continue
critical: bool
# severe problem but we can continue
severe: bool
# a minor problem to report
minor: bool
details: str
LogEntry = str
basic_protocol = InteractionProtocol(
description="""\
Basic interaction protocol for nodes spoken by the node wrapper.
""",
inputs={
"describe_config": type(None),
"set_config": SetConfig,
"describe_protocol": type(None),
"describe_node": type(None),
"describe_build": type(None),
"get_state": type(None),
"set_state": Any,
"get_logs": type(None),
},
language="""\
(
(in:describe_config ; out:config_description) |
(in:set_config ; (out:set_config_ack | out:set_config_error)) |
(in:describe_protocol ; out:protocol_description) |
(in:describe_node ; out:node_description) |
(in:describe_build ; out:build_description) |
(in:get_state ; out:node_state) |
(in:set_state ; (out:set_state_ack| out:set_state_error) ) |
(in:get_logs ; out:logs) |
out:aborted
)*
""",
outputs={
"config_description": ConfigDescription,
'set_config_ack': type(None),
'set_config_error': str,
'protocol_description': ProtocolDescription,
'node_description': NodeDescription,
'build_description': BuildDescription,
'node_state': Any,
'set_state_ack': type(None),
'set_state_error': str,
'logs': List[LogEntry],
'aborted': str,
}) | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes_wrapper/meta_protocol.py | meta_protocol.py |
import os
from io import BufferedReader
from typing import *
import cbor2 as cbor
from zuper_commons.text import indent
from zuper_commons.types import ZException
from zuper_ipce import IESO, ipce_from_object, object_from_ipce
from zuper_ipce.json2cbor import read_next_cbor
from zuper_nodes import ExternalProtocolViolation, InteractionProtocol
from zuper_nodes.compatibility import check_compatible_protocol
from zuper_nodes.structures import ExternalNodeDidNotUnderstand, RemoteNodeAborted, TimingInfo
from zuper_nodes_wrapper.meta_protocol import basic_protocol, ProtocolDescription
from zuper_nodes_wrapper.streams import wait_for_creation
from zuper_nodes_wrapper.struct import interpret_control_message, MsgReceived, WireMessage
from . import logger, logger_interaction
from .constants import *
class ComponentInterface:
def __init__(self, fnin: str, fnout: str,
expect_protocol: InteractionProtocol, nickname: str,
timeout=None):
self.nickname = nickname
self._cc = None
try:
os.mkfifo(fnin)
except BaseException as e:
msg = f'Cannot create fifo {fnin}'
raise Exception(msg) from e
self.fpin = open(fnin, 'wb', buffering=0)
wait_for_creation(fnout)
self.fnout = fnout
f = open(fnout, 'rb', buffering=0)
# noinspection PyTypeChecker
self.fpout = BufferedReader(f, buffer_size=1)
self.nreceived = 0
self.expect_protocol = expect_protocol
self.node_protocol = None
self.data_protocol = None
self.timeout = timeout
def close(self):
self.fpin.close()
self.fpout.close()
def cc(self, f):
""" CC-s everything that is read or written to this file. """
self._cc = f
def _get_node_protocol(self, timeout: float = None):
self.my_capabilities = {'z2': {CAPABILITY_PROTOCOL_REFLECTION: True}}
msg = {
FIELD_CONTROL: CTRL_CAPABILITIES,
FIELD_DATA: self.my_capabilities
}
j = self._serialize(msg)
self._write(j)
msgs = read_reply(self.fpout, timeout=timeout, waiting_for=f"Reading {self.nickname} capabilities",
nickname=self.nickname)
self.node_capabilities = msgs[0]['data']
logger.info('My capabilities: %s' % self.my_capabilities)
logger.info('Found capabilities: %s' % self.node_capabilities)
if 'z2' not in self.node_capabilities:
msg = 'Incompatible node; capabilities %s' % self.node_capabilities
raise ExternalProtocolViolation(msg)
z = self.node_capabilities['z2']
if not z.get(CAPABILITY_PROTOCOL_REFLECTION, False):
logger.info('Node does not support reflection.')
if self.expect_protocol is None:
msg = 'Node does not support reflection - need to provide protocol.'
raise Exception(msg)
else:
ob: MsgReceived[ProtocolDescription] = \
self.write_topic_and_expect('wrapper.describe_protocol',
expect='protocol_description',
timeout=timeout)
self.node_protocol = ob.data.data
self.data_protocol = ob.data.meta
if self.expect_protocol is not None:
check_compatible_protocol(self.node_protocol, self.expect_protocol)
def write_topic_and_expect(self, topic: str, data=None, with_schema: bool = False,
timeout: float = None,
timing=None,
expect: str = None) -> MsgReceived:
timeout = timeout or self.timeout
self._write_topic(topic, data=data, with_schema=with_schema, timing=timing)
ob: MsgReceived = self.read_one(expect_topic=expect, timeout=timeout)
return ob
def write_topic_and_expect_zero(self, topic: str, data=None, with_schema=False,
timeout=None,
timing=None):
timeout = timeout or self.timeout
self._write_topic(topic, data=data, with_schema=with_schema, timing=timing)
msgs = read_reply(self.fpout, timeout=timeout,
nickname=self.nickname)
if msgs:
msg = 'Expecting zero, got %s' % msgs
raise ExternalProtocolViolation(msg)
def _write_topic(self, topic, data=None, with_schema=False, timing=None):
suggest_type = object
if self.node_protocol:
if topic in self.node_protocol.inputs:
suggest_type = self.node_protocol.inputs[topic]
ieso = IESO(with_schema=with_schema)
ieso_true = IESO(with_schema=True)
ipce = ipce_from_object(data, suggest_type, ieso=ieso)
# try to re-read
if suggest_type is not object:
try:
_ = object_from_ipce(ipce, suggest_type)
except BaseException as e:
msg = f'While attempting to write on topic "{topic}", cannot ' \
f'interpret the value as {suggest_type}.\nValue: {data}'
raise ZException(msg, data=data, ipce=ipce, suggest_type=suggest_type) from e # XXX
msg = {
FIELD_COMPAT: [CUR_PROTOCOL],
FIELD_TOPIC: topic,
FIELD_DATA: ipce,
FIELD_TIMING: timing
}
j = self._serialize(msg)
self._write(j)
# make sure we write the schema when we copy it
if not with_schema:
msg[FIELD_DATA] = ipce_from_object(data, ieso=ieso_true)
j = self._serialize(msg)
if self._cc:
self._cc.write(j)
self._cc.flush()
logger_interaction.info(f'Written to topic "{topic}" >> {self.nickname}.')
def _write(self, j):
try:
self.fpin.write(j)
self.fpin.flush()
except BrokenPipeError as e:
msg = f'While attempting to write to node "{self.nickname}", ' \
f'I reckon that the pipe is closed and the node exited.'
try:
received = self.read_one(expect_topic=TOPIC_ABORTED)
if received.topic == TOPIC_ABORTED:
msg += '\n\nThis is the aborted message:'
msg += '\n\n' + indent(received.data, ' |')
except BaseException as e2:
msg += f'\n\nI could not read any aborted message: {e2}'
raise RemoteNodeAborted(msg) from e
def _serialize(self, msg) -> bytes:
j = cbor.dumps(msg)
return j
def read_one(self, expect_topic: str = None, timeout: float = None) -> MsgReceived:
timeout = timeout or self.timeout
try:
if expect_topic:
waiting_for = f'Expecting topic "{expect_topic}" << {self.nickname}.'
else:
waiting_for = None
msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for,
nickname=self.nickname)
if len(msgs) == 0:
msg = f'Expected one message from node "{self.nickname}". Got zero.'
if expect_topic:
msg += f'\nExpecting topic "{expect_topic}".'
raise ExternalProtocolViolation(msg)
if len(msgs) > 1:
msg = f'Expected only one message. Got {msgs}'
raise ExternalProtocolViolation(msg)
msg = msgs[0]
if FIELD_TOPIC not in msg:
m = f'Invalid message does not contain the field "{FIELD_TOPIC}".'
m += f'\n {msg}'
raise ExternalProtocolViolation(m)
topic = msg[FIELD_TOPIC]
if expect_topic:
if topic != expect_topic:
msg = f'I expected topic "{expect_topic}" but received "{topic}".'
raise ExternalProtocolViolation(msg)
if topic in basic_protocol.outputs:
klass = basic_protocol.outputs[topic]
else:
if self.node_protocol:
if topic not in self.node_protocol.outputs:
msg = f'Cannot find topic "{topic}" in outputs of detected node protocol.'
msg += '\nI know: %s' % sorted(self.node_protocol.outputs)
raise ExternalProtocolViolation(msg)
else:
klass = self.node_protocol.outputs[topic]
else:
if not topic in self.expect_protocol.outputs:
msg = f'Cannot find topic "{topic}".'
raise ExternalProtocolViolation(msg)
else:
klass = self.expect_protocol.outputs[topic]
data = object_from_ipce(msg[FIELD_DATA], klass)
ieso_true = IESO(with_schema=True)
if self._cc:
msg[FIELD_DATA] = ipce_from_object(data, ieso=ieso_true)
msg_b = self._serialize(msg)
self._cc.write(msg_b)
self._cc.flush()
if FIELD_TIMING not in msg:
timing = TimingInfo()
else:
timing = object_from_ipce(msg[FIELD_TIMING], TimingInfo)
self.nreceived += 1
return MsgReceived[klass](topic, data, timing)
except StopIteration as e:
msg = 'EOF detected on %s after %d messages.' % (self.fnout, self.nreceived)
if expect_topic:
msg += f' Expected topic "{expect_topic}".'
raise StopIteration(msg) from e
except TimeoutError as e:
msg = 'Timeout detected on %s after %d messages.' % (self.fnout, self.nreceived)
if expect_topic:
msg += f' Expected topic "{expect_topic}".'
raise TimeoutError(msg) from e
def read_reply(fpout, nickname: str, timeout=None, waiting_for=None, ) -> List:
""" Reads a control message. Returns if it is CTRL_UNDERSTOOD.
Raises:
TimeoutError
RemoteNodeAborted
ExternalNodeDidNotUnderstand
ExternalProtocolViolation otherwise. """
try:
wm: WireMessage = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
# logger.debug(f'{nickname} sent {wm}')
except StopIteration:
msg = 'Remote node closed communication (%s)' % waiting_for
raise RemoteNodeAborted(msg) from None
cm = interpret_control_message(wm)
if cm.code == CTRL_UNDERSTOOD:
others = read_until_over(fpout, timeout=timeout, nickname=nickname)
return others
elif cm.code == CTRL_ABORTED:
msg = f'The remote node "{nickname}" aborted with the following error:'
msg += '\n\n' + indent(cm.msg, "|", f"error in {nickname} |")
# others = self.read_until_over()
raise RemoteNodeAborted(msg)
elif cm.code == CTRL_NOT_UNDERSTOOD:
_others = read_until_over(fpout, timeout=timeout, nickname=nickname)
msg = f'The remote node "{nickname}" reports that it did not understand the message:'
msg += '\n\n' + indent(cm.msg, "|", f"reported by {nickname} |")
raise ExternalNodeDidNotUnderstand(msg)
else:
msg = 'Remote node raised unknown code %s: %s' % (cm, cm.code)
raise ExternalProtocolViolation(msg)
def read_until_over(fpout, timeout, nickname) -> List[WireMessage]:
""" Raises RemoteNodeAborted, TimeoutError """
res = []
waiting_for = f'Reading reply of {nickname}.'
while True:
try:
wm: WireMessage = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
if wm.get(FIELD_CONTROL, '') == CTRL_ABORTED:
m = f'External node "{nickname}" aborted:'
m += '\n\n' + indent(wm.get(FIELD_DATA, None), "|",
f"error in {nickname} |")
raise RemoteNodeAborted(m)
if wm.get(FIELD_CONTROL, '') == CTRL_OVER:
# logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res))
break
# logger.info(f'Node "{nickname}" sent %s.' % len(wm))
except StopIteration:
msg = f'External node "{nickname}" closed communication.'
raise RemoteNodeAborted(msg) from None
except TimeoutError:
msg = f'Timeout while reading output of node "{nickname}".'
raise TimeoutError(msg) from None
res.append(wm)
return res | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes_wrapper/wrapper_outside.py | wrapper_outside.py |
import select
import time
from typing import Optional, Union, Iterator
from zuper_ipce.json2cbor import read_next_cbor
from zuper_commons.text import indent
from zuper_nodes.structures import ExternalTimeout
from zuper_nodes_wrapper.struct import interpret_control_message, RawTopicMessage, ControlMessage
from . import logger
from .constants import *
M = Union[RawTopicMessage, ControlMessage]
def inputs(f, give_up: Optional[float] = None, waiting_for: str = None) -> Iterator[M]:
last = time.time()
intermediate_timeout = 3.0
intermediate_timeout_multiplier = 1.5
while True:
readyr, readyw, readyx = select.select([f], [], [f], intermediate_timeout)
if readyr:
try:
parsed = read_next_cbor(f, waiting_for=waiting_for)
except StopIteration:
return
if not isinstance(parsed, dict):
msg = f'Expected a dictionary, obtained {parsed!r}'
logger.error(msg)
continue
if FIELD_CONTROL in parsed:
m = interpret_control_message(parsed)
yield m
elif FIELD_TOPIC in parsed:
if not FIELD_COMPAT in parsed:
msg = f'Could not find field "compat" in structure "{parsed}".'
logger.error(msg)
continue
l = parsed[FIELD_COMPAT]
if not isinstance(l, list):
msg = f'Expected a list for compatibility value, found {l!r}'
logger.error(msg)
continue
if not CUR_PROTOCOL in parsed[FIELD_COMPAT]:
msg = f'Skipping message because could not find {CUR_PROTOCOL} in {l}.'
logger.warn(msg)
continue
rtm = RawTopicMessage(parsed[FIELD_TOPIC],
parsed.get(FIELD_DATA, None),
parsed.get(FIELD_TIMING, None))
yield rtm
elif readyx:
logger.warning('Exceptional condition on input channel %s' % readyx)
else:
delta = time.time() - last
if give_up is not None and (delta > give_up):
msg = f'I am giving up after %.1f seconds.' % delta
raise ExternalTimeout(msg)
else:
intermediate_timeout *= intermediate_timeout_multiplier
msg = f'Input channel not ready after %.1f seconds. Will re-try.' % delta
if waiting_for:
msg += '\n' + indent(waiting_for, '> ')
msg = 'I will warn again in %.1f seconds.' % intermediate_timeout
logger.warning(msg) | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes_wrapper/reading.py | reading.py |
import argparse
import dataclasses
import subprocess
import sys
from dataclasses import dataclass
from io import BufferedReader, BytesIO
import cbor2
import yaml
from zuper_ipce import object_from_ipce
from zuper_ipce.json2cbor import read_cbor_or_json_objects
from contracts import indent
from zuper_nodes import InteractionProtocol
from zuper_nodes_wrapper.meta_protocol import (BuildDescription, ConfigDescription, NodeDescription,
ProtocolDescription,
cast)
from . import logger
def identify_main():
usage = None
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('--image', default=None)
parser.add_argument('--command', default=None)
parsed = parser.parse_args()
image = parsed.image
if image is not None:
ni: NodeInfo = identify_image2(image)
elif parsed.command is not None:
command = parsed.command.split()
ni: NodeInfo = identify_command(command)
else:
msg = 'Please specify either --image or --command'
logger.error(msg)
sys.exit(1)
print('\n\n')
print(indent(describe_nd(ni.nd), '', 'desc: '))
print('\n\n')
print(indent(describe_bd(ni.bd), '', 'build: '))
print('\n\n')
print(indent(describe_cd(ni.cd), '', 'config: '))
print('\n\n')
print(indent(describe(ni.pd.data), '', 'data: '))
print('\n\n')
print(indent(describe(ni.pd.meta), '', 'meta: '))
def describe_nd(nd: NodeDescription):
return str(nd.description)
def describe_bd(nd: BuildDescription):
return str(nd)
def describe_cd(nd: ConfigDescription):
s = []
# noinspection PyDataclass
for f in dataclasses.fields(nd.config):
# for k, v in nd.config.__annotations__.items():
s.append('%20s: %s = %s' % (f.name, f.type, f.default))
if not s:
return 'No configuration switches available.'
if hasattr(nd.config, '__doc__'):
s.insert(0, nd.config.__doc__)
return "\n".join(s)
def describe(ip: InteractionProtocol):
s = "InteractionProtocol"
s += '\n\n' + '* Description:'
s += '\n\n' + indent(ip.description.strip(), ' ')
s += '\n\n' + '* Inputs:'
for name, type_ in ip.inputs.items():
s += '\n %25s: %s' % (name, type_)
s += '\n\n' + '* Outputs:'
for name, type_ in ip.outputs.items():
s += '\n %25s: %s' % (name, type_)
s += '\n\n' + '* Language:'
s += '\n\n' + ip.language
return s
@dataclass
class NodeInfo:
pd: ProtocolDescription
nd: NodeDescription
bd: BuildDescription
cd: ConfigDescription
def identify_command(command) -> NodeInfo:
d = [{'topic': 'wrapper.describe_protocol'},
{'topic': 'wrapper.describe_config'},
{'topic': 'wrapper.describe_node'},
{'topic': 'wrapper.describe_build'}
]
to_send = b''
for p in d:
p['compat'] = ['aido2']
# to_send += (json.dumps(p) + '\n').encode('utf-8')
to_send += cbor2.dumps(p)
cp = subprocess.run(command, input=to_send, capture_output=True)
s = cp.stderr.decode('utf-8')
sys.stderr.write(indent(s.strip(), '|', ' stderr: |') + '\n\n')
# noinspection PyTypeChecker
f = BufferedReader(BytesIO(cp.stdout))
stream = read_cbor_or_json_objects(f)
res = stream.__next__()
logger.debug(yaml.dump(res))
pd = cast(ProtocolDescription, object_from_ipce(res['data'], ProtocolDescription))
res = stream.__next__()
logger.debug(yaml.dump(res))
cd = cast(ConfigDescription, object_from_ipce(res['data'], ConfigDescription))
res = stream.__next__()
logger.debug(yaml.dump(res))
nd = cast(NodeDescription, object_from_ipce(res['data'], NodeDescription))
res = stream.__next__()
logger.debug(yaml.dump(res))
bd = cast(BuildDescription, object_from_ipce(res['data'], BuildDescription))
logger.debug(yaml.dump(res))
return NodeInfo(pd, nd, bd, cd)
def identify_image2(image) -> NodeInfo:
cmd = ['docker', 'run', '--rm', '-i', image]
return identify_command(cmd)
# def identify_image(image):
# import docker
# client = docker.from_env()
#
#
# container: Container = client.containers.create(image, detach=True, stdin_open=True)
# print(container)
# # time.sleep(4)
# # attach to the container stdin socket
# container.start()
# # s = container.exec_run()
# s: SocketIO = container.attach_socket(params={'stdin': 1, 'stream': 1, 'stderr': 0, 'stdout': 0})
# s_out: SocketIO = container.attach_socket(params={ 'stream': 1, 'stdout': 1, 'stderr': 0, 'stdin': 0})
# s_stderr: SocketIO = container.attach_socket(params={'stream': 1, 'stdout': 0, 'stderr': 1, 'stdin': 0})
# print(s.__dict__)
# print(s_out.__dict__)
# # send text
# # s.write(j)
# os.write(s._sock.fileno(), j)
# os.close(s._sock.fileno())
# s._sock.close()
# # s.close()
#
# f = os.fdopen(s_out._sock.fileno(), 'rb')
# # there is some garbage: b'\x01\x00\x00\x00\x00\x00\x1e|{
# f.read(8)
#
# for x in read_cbor_or_json_objects(f):
# print(x)
# print(f.read(10))
# # print(os.read(s_out._sock.fileno(), 100))
#
# print(os.read(s_stderr._sock.fileno(), 100))
# # close, stop and disconnect
# s.close() | zuper-nodes-z5 | /zuper-nodes-z5-5.0.9.tar.gz/zuper-nodes-z5-5.0.9/src/zuper_nodes_wrapper/identify.py | identify.py |
import pyparsing
from pyparsing import (
Suppress,
Literal,
Keyword,
ParserElement,
pyparsing_common,
opAssoc,
)
try:
from pyparsing import operatorPrecedence
except ImportError: # pragma: no cover
from pyparsing import infixNotation as operatorPrecedence
from .language import (
ExpectInputReceived,
ExpectOutputProduced,
InSequence,
ZeroOrMore,
ZeroOrOne,
Either,
Language,
OneOrMore,
)
__all__ = [
"parse_language",
"language_to_str",
"Syntax",
]
ParserElement.enablePackrat()
S = Suppress
L = Literal
K = Keyword
def parse_language(s: str) -> Language:
try:
res = Syntax.language.parseString(s, parseAll=True)
except pyparsing.ParseException as e:
msg = f"Cannot parse the language:\n\n{s}"
raise Exception(msg) from e
res = res[0]
return res
def language_to_str(l: Language):
def quote_if(s):
if ";" in s or "|" in s:
return "(" + s + ")"
else:
return s
if isinstance(l, ExpectInputReceived):
return f"in:{l.channel}"
if isinstance(l, ExpectOutputProduced):
return f"out:{l.channel}"
if isinstance(l, InSequence):
return " ; ".join(quote_if(language_to_str(_)) for _ in l.ls)
if isinstance(l, Either):
return " | ".join(quote_if(language_to_str(_)) for _ in l.ls)
if isinstance(l, ZeroOrMore):
return "(" + language_to_str(l.l) + ")" + "*"
if isinstance(l, OneOrMore):
return "(" + language_to_str(l.l) + ")" + "+"
if isinstance(l, ZeroOrOne):
return "(" + language_to_str(l.l) + ")" + "?"
raise NotImplementedError(type(l))
def on_input_received(s, loc, tokens):
return ExpectInputReceived(tokens[0])
def on_output_produced(s, loc, tokens):
return ExpectOutputProduced(tokens[0])
def on_in_sequence(tokens):
return InSequence(tuple(tokens[0]))
def on_either(tokens):
return Either(tuple(tokens[0]))
def on_zero_or_one(tokens):
return ZeroOrOne(tokens[0][0])
def on_zero_or_more(tokens):
return ZeroOrMore(tokens[0][0])
def on_one_or_more(tokens):
return OneOrMore(tokens[0][0])
class Syntax:
input_received = S(K("in") + L(":")) + pyparsing_common.identifier
output_produced = S(K("out") + L(":")) + pyparsing_common.identifier
basic = input_received | output_produced
language = operatorPrecedence(
basic,
[
(S(L("*")), 1, opAssoc.LEFT, on_zero_or_more),
(S(L("+")), 1, opAssoc.LEFT, on_one_or_more),
(S(L("?")), 1, opAssoc.LEFT, on_zero_or_one),
(S(L(";")), 2, opAssoc.LEFT, on_in_sequence),
(S(L("|")), 2, opAssoc.LEFT, on_either),
],
)
input_received.setParseAction(on_input_received)
output_produced.setParseAction(on_output_produced) | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes/language_parse.py | language_parse.py |
from zuper_commons.types import ZException
from zuper_typing import can_be_used_as2
from .language import InteractionProtocol
__all__ = ["IncompatibleProtocol", "check_compatible_protocol"]
class IncompatibleProtocol(ZException):
pass
def check_compatible_protocol(p1: InteractionProtocol, p2: InteractionProtocol):
"""
Checks that p1 is a subprotocol of p2, that is, we can use a p1-node
wherever a p2-node fits.
:raises: IncompatibleProtocol
"""
try:
# check input compatibility
# p1 should not need more input
p1_needs_more = set(p1.inputs) - set(p2.inputs)
if p1_needs_more:
msg = f"P1 needs more inputs."
raise IncompatibleProtocol(
msg, p1_inputs=sorted(p1.inputs), p2_inputs=sorted(p2.inputs), p1_needs_more=p1_needs_more
)
# p1 should have all the outputs
p1_missing_output = set(p2.outputs) - set(p1.outputs)
if p1_missing_output:
msg = f"P1 has missing outputs."
raise IncompatibleProtocol(
msg,
p1_outputs=sorted(p1.outputs),
p2_outputs=sorted(p2.outputs),
p1_missing_output=p1_missing_output,
)
common_inputs = set(p1.inputs) & set(p2.inputs)
for k in common_inputs:
v1 = p1.inputs[k]
v2 = p2.inputs[k]
r = can_be_used_as2(v2, v1)
if not r:
msg = f'For input "{k}", cannot use type v2 as v1'
raise IncompatibleProtocol(
msg, k=k, v1=v1, v2=v2, r=r, p1_inputs=p1.inputs, p2_inputs=p2.inputs
)
# check output compatibility
common_ouputs = set(p1.outputs) & set(p2.outputs)
for k in common_ouputs:
v1 = p1.outputs[k]
v2 = p2.outputs[k]
r = can_be_used_as2(v1, v2)
if not r:
msg = f'For output "{k}", cannot use type v1 as v2.'
raise IncompatibleProtocol(
msg, k=k, v1=v1, v2=v2, r=r, p1_outputs=p1.outputs, p2_outputs=p2.outputs
)
# XXX: to finish
except IncompatibleProtocol as e:
msg = "Cannot say that p1 is a sub-protocol of p2"
raise IncompatibleProtocol(msg, p1=p1, p2=p2) from e | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes/compatibility.py | compatibility.py |
from dataclasses import dataclass
from typing import Union, Tuple, Optional, Set
from .language import (
Language,
OutputProduced,
InputReceived,
Event,
ExpectInputReceived,
ExpectOutputProduced,
InSequence,
ZeroOrMore,
Either,
OneOrMore,
ZeroOrOne,
)
from zuper_commons.text import indent
__all__ = ["Enough", "Unexpected", "Always", "LanguageChecker", "NeedMore"]
class Result:
pass
@dataclass
class Enough(Result):
pass
@dataclass
class Unexpected(Result):
msg: str
def __repr__(self):
return "Unexpected:" + indent(self.msg, " ")
@dataclass
class NeedMore(Result):
pass
import networkx as nx
NodeName = Tuple[str, ...]
class Always:
pass
def get_nfa(
g: Optional[nx.DiGraph],
start_node: NodeName,
accept_node: NodeName,
l: Language,
prefix: Tuple[str, ...] = (),
):
# assert start_node != accept_node
if not start_node in g:
g.add_node(start_node, label="/".join(start_node))
if not accept_node in g:
g.add_node(accept_node, label="/".join(accept_node))
if isinstance(l, ExpectOutputProduced):
g.add_edge(start_node, accept_node, event_match=l, label=f"out/{l.channel}")
elif isinstance(l, ExpectInputReceived):
g.add_edge(start_node, accept_node, event_match=l, label=f"in/{l.channel}")
elif isinstance(l, InSequence):
current = start_node
for i, li in enumerate(l.ls):
# if i == len(l.ls) - 1:
# n = accept_node
# else:
n = prefix + (f"after{i}",)
g.add_node(n)
# logger.debug(f'sequence {i} start {current} to {n}')
get_nfa(g, start_node=current, accept_node=n, prefix=prefix + (f"{i}",), l=li)
current = n
g.add_edge(current, accept_node, event_match=Always(), label="always")
elif isinstance(l, ZeroOrMore):
# logger.debug(f'zeroormore {start_node} -> {accept_node}')
g.add_edge(start_node, accept_node, event_match=Always(), label="always")
get_nfa(
g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ("zero_or_more",),
)
elif isinstance(l, OneOrMore):
# start to accept
get_nfa(
g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ("one_or_more", "1"),
)
# accept to accept
get_nfa(
g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ("one_or_more", "2"),
)
elif isinstance(l, ZeroOrOne):
g.add_edge(start_node, accept_node, event_match=Always(), label="always")
get_nfa(
g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ("zero_or_one",),
)
elif isinstance(l, Either):
for i, li in enumerate(l.ls):
get_nfa(
g, start_node=start_node, accept_node=accept_node, l=li, prefix=prefix + (f"either{i}",),
)
else:
assert False, type(l)
def event_matches(l: Language, event: Event):
if isinstance(l, ExpectInputReceived):
return isinstance(event, InputReceived) and event.channel == l.channel
if isinstance(l, ExpectOutputProduced):
return isinstance(event, OutputProduced) and event.channel == l.channel
if isinstance(l, Always):
return False
raise NotImplementedError(l)
START = ("start",)
ACCEPT = ("accept",)
class LanguageChecker:
g: nx.DiGraph
active: Set[NodeName]
def __init__(self, language: Language):
self.g = nx.MultiDiGraph()
self.start_node = START
self.accept_node = ACCEPT
get_nfa(
g=self.g, l=language, start_node=self.start_node, accept_node=self.accept_node, prefix=(),
)
# for (a, b, data) in self.g.out_edges(data=True):
# print(f'{a} -> {b} {data["event_match"]}')
a = 2
for n in self.g:
if n not in [START, ACCEPT]:
# noinspection PyUnresolvedReferences
self.g.nodes[n]["label"] = f"S{a}"
a += 1
elif n == START:
# noinspection PyUnresolvedReferences
self.g.nodes[n]["label"] = "start"
elif n == ACCEPT:
# noinspection PyUnresolvedReferences
self.g.nodes[n]["label"] = "accept"
self.active = {self.start_node}
# logger.debug(f'active {self.active}')
self._evolve_empty()
def _evolve_empty(self):
while True:
now_active = set()
for node in self.active:
nalways = 0
nother = 0
for (_, neighbor, data) in self.g.out_edges([node], data=True):
# print(f'-> {neighbor} {data["event_match"]}')
if isinstance(data["event_match"], Always):
now_active.add(neighbor)
nalways += 1
else:
nother += 1
if nother or (nalways == 0):
now_active.add(node)
if self.active == now_active:
break
self.active = now_active
def push(self, event) -> Result:
now_active = set()
# print(f'push: active is {self.active}')
# print(f'push: considering {event}')
for node in self.active:
for (_, neighbor, data) in self.g.out_edges([node], data=True):
if event_matches(data["event_match"], event):
# print(f'now activating {neighbor}')
now_active.add(neighbor)
# else:
# print(f"event_match {event} does not match {data['event_match']}")
#
# if not now_active:
# return Unexpected('')
self.active = now_active
# print(f'push: now active is {self.active}')
self._evolve_empty()
# print(f'push: now active is {self.active}')
return self.finish()
def finish(self) -> Union[NeedMore, Enough, Unexpected]:
# print(f'finish: active is {self.active}')
if not self.active:
return Unexpected("no active")
if self.accept_node in self.active:
return Enough()
return NeedMore()
def get_active_states_names(self):
return [self.g.nodes[_]["label"] for _ in self.active]
def get_expected_events(self) -> Set:
events = set()
for state in self.active:
for (_, neighbor, data) in self.g.out_edges([state], data=True):
em = data["event_match"]
if not isinstance(em, Always):
events.add(em)
return events | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes/language_recognize.py | language_recognize.py |
import socket
import time
from dataclasses import dataclass, field
from typing import Dict, Optional
import numpy as np
__all__ = [
"AIDONodesException",
"ProtocolViolation",
"ExternalProtocolViolation",
"InternalProtocolViolation",
"DecodingError",
"EncodingError",
"Timestamp",
"timestamp_from_seconds",
"TimeSpec",
"local_time",
"TimingInfo",
# "EnvironmentError",
"NotConforming",
"ExternalTimeout",
"ExternalNodeDidNotUnderstand",
"RemoteNodeAborted",
"InternalProblem",
]
class AIDONodesException(Exception):
pass
class ProtocolViolation(AIDONodesException):
pass
class ExternalProtocolViolation(ProtocolViolation):
pass
class ExternalNodeDidNotUnderstand(ExternalProtocolViolation):
pass
class RemoteNodeAborted(ExternalProtocolViolation):
pass
class ExternalTimeout(ExternalProtocolViolation):
pass
class InternalProblem(AIDONodesException):
pass
class InternalProtocolViolation(ProtocolViolation):
pass
class DecodingError(AIDONodesException):
pass
class EncodingError(AIDONodesException):
pass
class NotConforming(AIDONodesException):
""" The node is not conforming to the protocol. """
pass
#
#
# class EnvironmentError(AIDONodesException):
# """ Things such as files not existing. """
#
# pass
@dataclass
class Timestamp:
s: int
us: int
def timestamp_from_seconds(f: float) -> Timestamp:
s = int(np.floor(f))
extra = f - s
us = int(extra * 1000 * 1000 * 1000)
return Timestamp(s, us)
@dataclass
class TimeSpec:
time: Timestamp
frame: str
clock: str
time2: Optional[Timestamp] = None
def local_time() -> TimeSpec:
s = time.time()
hostname = socket.gethostname()
return TimeSpec(time=timestamp_from_seconds(s), frame="epoch", clock=hostname)
@dataclass
class TimingInfo:
acquired: Optional[Dict[str, TimeSpec]] = field(default_factory=dict)
processed: Optional[Dict[str, TimeSpec]] = field(default_factory=dict)
received: Optional[TimeSpec] = None | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes/structures.py | structures.py |
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import Dict, Iterator, NewType, Optional, Tuple, TYPE_CHECKING
__all__ = [
"InteractionProtocol",
"particularize",
"opposite",
"ChannelName",
"Either",
"ExpectInputReceived",
"ExpectOutputProduced",
"InSequence",
"Language",
"ZeroOrOne",
"OneOrMore",
"ZeroOrMore",
"OutputProduced",
"InputReceived",
"Event",
"particularize_no_check",
]
if TYPE_CHECKING:
ChannelName = NewType("ChannelName", str)
else:
ChannelName = str
class Event:
pass
@dataclass(frozen=True, unsafe_hash=True)
class InputReceived(Event):
channel: ChannelName
@dataclass(frozen=True, unsafe_hash=True)
class OutputProduced(Event):
channel: ChannelName
# Language over events
class Language(metaclass=ABCMeta):
@abstractmethod
def collect_simple_events(self) -> Iterator[Event]:
...
@abstractmethod
def opposite(self) -> "Language":
...
@dataclass(frozen=True, unsafe_hash=True)
class ExpectInputReceived(Language):
channel: ChannelName
def collect_simple_events(self):
yield InputReceived(self.channel)
def opposite(self) -> "Language":
return ExpectOutputProduced(self.channel)
@dataclass(frozen=True, unsafe_hash=True)
class ExpectOutputProduced(Language):
channel: ChannelName
def collect_simple_events(self):
yield OutputProduced(self.channel)
def opposite(self) -> "Language":
return ExpectInputReceived(self.channel)
@dataclass(frozen=True, unsafe_hash=True)
class InSequence(Language):
ls: Tuple[Language, ...]
def collect_simple_events(self):
for l in self.ls:
yield from l.collect_simple_events()
def opposite(self) -> "Language":
ls = tuple(_.opposite() for _ in self.ls)
return InSequence(ls)
@dataclass(frozen=True, unsafe_hash=True)
class ZeroOrOne(Language):
l: Language
def collect_simple_events(self):
yield from self.l.collect_simple_events()
def opposite(self) -> "Language":
return ZeroOrOne(self.l.opposite())
@dataclass(frozen=True, unsafe_hash=True)
class ZeroOrMore(Language):
l: Language
def collect_simple_events(self):
yield from self.l.collect_simple_events()
def opposite(self) -> "Language":
return ZeroOrMore(self.l.opposite())
@dataclass(frozen=True, unsafe_hash=True)
class OneOrMore(Language):
l: Language
def collect_simple_events(self):
yield from self.l.collect_simple_events()
def opposite(self) -> "Language":
return OneOrMore(self.l.opposite())
@dataclass(frozen=True, unsafe_hash=True)
class Either(Language):
ls: Tuple[Language, ...]
def collect_simple_events(self):
for l in self.ls:
yield from l.collect_simple_events()
def opposite(self) -> "Language":
ls = tuple(_.opposite() for _ in self.ls)
return Either(ls)
# Interaction protocol
@dataclass(unsafe_hash=True)
class InteractionProtocol:
# Description
description: str
# Type for each input or output
inputs: Dict[ChannelName, type]
outputs: Dict[ChannelName, type]
# The interaction language
language: str
# interaction: Language = None
def __post_init__(self):
from .language_parse import parse_language, language_to_str
self.interaction = parse_language(self.language)
simple_events = list(self.interaction.collect_simple_events())
for e in simple_events:
if isinstance(e, InputReceived):
if e.channel not in self.inputs: # pragma: no cover
msg = f'Could not find input channel "{e.channel}" among {sorted(self.inputs)}.'
raise ValueError(msg)
if isinstance(e, OutputProduced):
if e.channel not in self.outputs: # pragma: no cover
msg = f'Could not find output channel "{e.channel}" among {sorted(self.outputs)}.'
raise ValueError(msg)
self.language = language_to_str(self.interaction)
def opposite(ip: InteractionProtocol) -> InteractionProtocol:
from .language_parse import language_to_str, parse_language
outputs = ip.inputs # switch
inputs = ip.outputs # switch
l = parse_language(ip.language)
l_op = l.opposite()
language = language_to_str(l_op)
description = ip.description
return InteractionProtocol(outputs=outputs, inputs=inputs, language=language, description=description)
def particularize(
ip: InteractionProtocol,
description: Optional[str] = None,
inputs: Optional[Dict[ChannelName, type]] = None,
outputs: Optional[Dict[ChannelName, type]] = None,
) -> InteractionProtocol:
inputs2 = dict(ip.inputs)
inputs2.update(inputs or {})
outputs2 = dict(ip.outputs)
outputs2.update(outputs or {})
language = ip.language
description = description or ip.description
protocol2 = InteractionProtocol(description, inputs2, outputs2, language)
from .compatibility import check_compatible_protocol
check_compatible_protocol(protocol2, ip)
return protocol2
def particularize_no_check(
ip: InteractionProtocol,
description: Optional[str] = None,
inputs: Optional[Dict[ChannelName, type]] = None,
outputs: Optional[Dict[ChannelName, type]] = None,
) -> InteractionProtocol:
inputs2 = dict(ip.inputs)
inputs2.update(inputs or {})
outputs2 = dict(ip.outputs)
outputs2.update(outputs or {})
language = ip.language
description = description or ip.description
protocol2 = InteractionProtocol(description, inputs2, outputs2, language)
return protocol2 | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes/language.py | language.py |
import argparse
import json
import os
import socket
import time
import traceback
from contextlib import contextmanager
from dataclasses import dataclass
from io import BufferedReader, BufferedWriter
from typing import Dict, Iterator, List, Optional, Tuple
import yaml
from zuper_commons.logs import ZLoggerInterface
from zuper_commons.text import indent
from zuper_commons.types import check_isinstance, ZValueError
from zuper_ipce import IEDO, IESO, ipce_from_object, object_from_ipce
from zuper_nodes import (
ChannelName,
InputReceived,
InteractionProtocol,
LanguageChecker,
OutputProduced,
Unexpected,
)
from zuper_nodes.structures import (
DecodingError,
ExternalProtocolViolation,
ExternalTimeout,
InternalProblem,
local_time,
NotConforming,
TimeSpec,
timestamp_from_seconds,
TimingInfo,
)
from . import logger as logger0, logger_interaction
from .constants import (
ATT_CONFIG,
CAPABILITY_PROTOCOL_REFLECTION,
CTRL_ABORTED,
CTRL_CAPABILITIES,
CTRL_NOT_UNDERSTOOD,
CTRL_OVER,
CTRL_UNDERSTOOD,
ENV_CONFIG,
ENV_DATA_IN,
ENV_DATA_OUT,
ENV_NAME,
ENV_TRANSLATE,
KNOWN, TOPIC_ABORTED,
)
from .interface import Context
from .meta_protocol import (
basic_protocol,
BuildDescription,
ConfigDescription,
NodeDescription,
ProtocolDescription,
SetConfig,
)
from .profiler import Profiler, ProfilerImp
from .reading import inputs
from .streams import open_for_read, open_for_write
from .struct import ControlMessage, RawTopicMessage
from .utils import call_if_fun_exists
from .writing import Sink
iedo = IEDO(True, True)
class ConcreteContext(Context):
protocol: InteractionProtocol
to_write: List[RawTopicMessage]
pc: LanguageChecker
node_name: str
hostname: str
tout: Dict[str, str]
def __init__(
self, sink: Sink, protocol: InteractionProtocol, node_name: str, tout: Dict[str, str],
logger: ZLoggerInterface
):
self.sink = sink
self.protocol = protocol
self.pc = LanguageChecker(protocol.interaction)
self.node_name = node_name
self.hostname = socket.gethostname()
self.tout = tout
self.to_write = []
self.last_timing = None
self.profiler = ProfilerImp()
self.logger = logger
def get_profiler(self) -> Profiler:
return self.profiler
def set_last_timing(self, timing: TimingInfo):
self.last_timing = timing
def get_hostname(self):
return self.hostname
def write(
self, topic: ChannelName, data: object, timing: Optional[TimingInfo] = None, with_schema: bool = False
):
self._write(topic, data, timing, with_schema)
def _write(
self, topic: ChannelName, data: object, timing: Optional[TimingInfo] = None, with_schema: bool = False
) -> None:
if topic not in self.protocol.outputs:
msg = f'Output channel "{topic}" not found in protocol; know {sorted(self.protocol.outputs)}.'
raise Exception(msg)
# logger.info(f'Writing output "{topic}".')
klass = self.protocol.outputs[topic]
if isinstance(klass, type):
check_isinstance(data, klass)
event = OutputProduced(topic)
res = self.pc.push(event)
if isinstance(res, Unexpected):
msg = f"Unexpected output {topic}: {res}"
self.logger.error(msg)
return
klass = self.protocol.outputs[topic]
if isinstance(data, dict):
with self.profiler.prof(':serialization'):
# noinspection PyTypeChecker
data = object_from_ipce(data, klass, iedo=iedo)
if timing is None:
timing = self.last_timing
if timing is not None:
s = time.time()
if timing.received is None:
# XXX
time1 = timestamp_from_seconds(s)
else:
time1 = timing.received.time
processed = TimeSpec(
time=time1, time2=timestamp_from_seconds(s), frame="epoch", clock=socket.gethostname(),
)
timing.processed[self.node_name] = processed
timing.received = None
topic_o = self.tout.get(topic, topic)
ieso = IESO(use_ipce_from_typelike_cache=True, with_schema=with_schema)
with self.profiler.prof(':serialization'):
data = ipce_from_object(data, ieso=ieso)
if timing is not None:
with self.profiler.prof(':timing-serialization'):
ieso2 = IESO(use_ipce_from_typelike_cache=True, with_schema=False)
timing_o = ipce_from_object(timing, ieso=ieso2)
else:
timing_o = None
rtm = RawTopicMessage(topic_o, data, timing_o)
self.to_write.append(rtm)
def get_to_write(self) -> List[RawTopicMessage]:
""" Returns the messages to send and resets the queue"""
res = self.to_write
self.to_write = []
return res
def log(self, s: str):
prefix = f"{self.hostname}:{self.node_name}: "
self.logger.info(prefix + s)
def info(self, s: str):
prefix = f"{self.hostname}:{self.node_name}: "
self.logger.info(prefix + s)
def debug(self, s: str):
prefix = f"{self.hostname}:{self.node_name}: "
self.logger.debug(prefix + s)
def warning(self, s: str):
prefix = f"{self.hostname}:{self.node_name}: "
self.logger.warning(prefix + s)
def error(self, s: str):
prefix = f"{self.hostname}:{self.node_name}: "
self.logger.error(prefix + s)
def get_translation_table(t: str) -> Tuple[Dict[str, str], Dict[str, str]]:
tout = {}
tin = {}
for t in t.split(","):
ts = t.split(":")
if ts[0] == "in":
tin[ts[1]] = ts[2]
if ts[0] == "out":
tout[ts[1]] = ts[2]
return tin, tout
def check_variables():
for k, v in os.environ.items():
if k.startswith("AIDONODE") and k not in KNOWN:
msg = f'I do not expect variable "{k}" set in environment with value "{v}".'
msg += f" I expect: {', '.join(KNOWN)}"
logger0.warn(msg)
@dataclass
class CommContext:
fi: BufferedReader
fo: BufferedWriter
fo_sink: Sink
context_meta: ConcreteContext
@contextmanager
def open_comms(node_name: str, logger_meta: ZLoggerInterface) -> Iterator[CommContext]:
data_in = os.environ.get(ENV_DATA_IN, "/dev/stdin")
data_out = os.environ.get(ENV_DATA_OUT, "/dev/stdout")
fi = open_for_read(data_in)
fo = open_for_write(data_out)
sink = Sink(fo)
context_meta = ConcreteContext(
sink=sink, protocol=basic_protocol, node_name=node_name, tout={},
logger=logger_meta
)
cc = CommContext(fi, fo, sink, context_meta)
try:
yield cc
except:
# sink.write_control_message()
context_meta.write(TOPIC_ABORTED, traceback.format_exc())
raise
def run_loop(node: object, protocol: InteractionProtocol, args: Optional[List[str]] = None):
parser = argparse.ArgumentParser()
check_variables()
data_in = os.environ.get(ENV_DATA_IN, "/dev/stdin")
data_out = os.environ.get(ENV_DATA_OUT, "/dev/stdout")
default_name = os.environ.get(ENV_NAME, None)
translate = os.environ.get(ENV_TRANSLATE, "")
config = os.environ.get(ENV_CONFIG, "{}")
parser.add_argument("--data-in", default=data_in)
parser.add_argument("--data-out", default=data_out)
parser.add_argument("--name", default=default_name)
parser.add_argument("--config", default=config)
parser.add_argument("--translate", default=translate)
parser.add_argument("--loose", default=False, action="store_true")
parsed = parser.parse_args(args)
tin, tout = get_translation_table(parsed.translate)
# expect in:name1:name2, out:name2:name1
fin = parsed.data_in
fout = parsed.data_out
node_name = parsed.name or type(node).__name__
my_logger = logger0.getChild(node_name)
my_logger.debug("run_loop", fin=fin, fout=fout)
fi = open_for_read(fin)
fo = open_for_write(fout)
# logger.name = node_name
try:
config = yaml.load(config, Loader=yaml.SafeLoader)
loop(my_logger, node_name, fi, fo, node, protocol, tin, tout, config=config, fi_desc=fin,
fo_desc=fout)
except RuntimeError as e:
s = str(e).lower()
if ("gpu" in s) or ("cuda" in s) or ("CUDA" in s) or ("bailing" in s):
raise SystemExit(138)
if 'CUDNN_STATUS_INTERNAL_ERROR' in s:
raise SystemExit(138)
except BaseException as e:
if "I need a GPU".lower() in str(e).lower():
raise SystemExit(138)
msg = f"Error in node {node_name}"
my_logger.error(f"Error in node {node_name}",
ET=type(e).__name__,
tb=traceback.format_exc())
raise Exception(msg) from e
finally:
fo.flush()
fo.close()
fi.close()
# noinspection PyBroadException
@contextmanager
def suppress_exception_logit():
""" Will suppress any exception """
try:
yield
except BaseException:
logger0.error("cannot write sink control messages", bt=traceback.format_exc())
finally:
pass
# noinspection PyBroadException
def loop(
logger: ZLoggerInterface,
node_name: str,
fi: BufferedReader,
fo,
node: object,
protocol: InteractionProtocol,
tin: Dict[str, str],
tout: Dict[str, str],
config: dict,
fi_desc: str,
fo_desc: str,
):
logger.debug(f"Starting reading", fi_desc=fi_desc, fo_desc=fo_desc)
initialized = False
context_data = None
sink = Sink(fo)
PASSTHROUGH = (RuntimeError,)
logger_data = logger.getChild('data')
logger_meta = logger.getChild('meta')
try:
context_data = ConcreteContext(sink=sink, protocol=protocol, node_name=node_name, tout=tout,
logger=logger_data)
context_meta = ConcreteContext(
sink=sink, protocol=basic_protocol, node_name=node_name + ".wrapper", tout=tout,
logger=logger_meta
)
wrapper = MetaHandler(node, protocol)
for k, v in config.items():
wrapper.set_config(k, v)
waiting_for = f"Expecting control message or one of: {context_data.pc.get_expected_events()}"
for parsed in inputs(fi, waiting_for=waiting_for):
if isinstance(parsed, ControlMessage):
expect = [CTRL_CAPABILITIES]
if parsed.code not in expect:
msg = f'I expect any of {expect}, not "{parsed.code}".'
sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg)
sink.write_control_message(CTRL_OVER)
else:
if parsed.code == CTRL_CAPABILITIES:
my_capabilities = {"z2": {CAPABILITY_PROTOCOL_REFLECTION: True}}
sink.write_control_message(CTRL_UNDERSTOOD)
sink.write_control_message(CTRL_CAPABILITIES, my_capabilities)
sink.write_control_message(CTRL_OVER)
else:
assert False
elif isinstance(parsed, RawTopicMessage):
parsed.topic = tin.get(parsed.topic, parsed.topic)
logger_interaction.info(f'Received message of topic "{parsed.topic}".')
if parsed.topic.startswith("wrapper."):
parsed.topic = parsed.topic.replace("wrapper.", "")
receiver0 = wrapper
context0 = context_meta
else:
receiver0 = node
context0 = context_data
if receiver0 is node and not initialized:
try:
with context_data.profiler.prof('init'):
call_if_fun_exists(node, "init", context=context_data)
except PASSTHROUGH:
with suppress_exception_logit():
context_meta.write(TOPIC_ABORTED, traceback.format_exc())
raise
except BaseException as e:
msg = type(e).__name__
msg += '\n'
msg = "Exception while calling the node's init() function."
msg += '\n'
msg += indent(traceback.format_exc(), "| ")
with suppress_exception_logit():
context_meta.write(TOPIC_ABORTED, msg)
raise InternalProblem(msg) from e # XXX
initialized = True
if parsed.topic not in context0.protocol.inputs:
msg = f'Input channel "{parsed.topic}" not found in protocol. '
msg += f"\n\nKnown channels: {sorted(context0.protocol.inputs)}"
with suppress_exception_logit():
sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg)
sink.write_control_message(CTRL_OVER)
raise ExternalProtocolViolation(msg)
sink.write_control_message(CTRL_UNDERSTOOD)
try:
handle_message_node(parsed, receiver0, context0)
to_write = context0.get_to_write()
# msg = f'I wrote {len(to_write)} messages.'
# logger.info(msg)
for rtm in to_write:
sink.write_topic_message(rtm.topic, rtm.data, rtm.timing)
sink.write_control_message(CTRL_OVER)
except PASSTHROUGH:
with suppress_exception_logit():
context_meta.write(TOPIC_ABORTED, traceback.format_exc())
raise
except BaseException as e:
msg = f'Exception while handling a message on topic "{parsed.topic}".'
msg += "\n\n" + indent(traceback.format_exc(), "| ")
with suppress_exception_logit():
sink.write_control_message(CTRL_ABORTED, msg)
sink.write_control_message(CTRL_OVER)
raise InternalProblem(msg) from e # XXX
else:
assert False, parsed
res = context_data.pc.finish()
if isinstance(res, Unexpected):
msg = f"Protocol did not finish: {res}"
logger_interaction.error(msg)
if initialized:
try:
with context_data.profiler.prof('finish'):
call_if_fun_exists(node, "finish", context=context_data)
except PASSTHROUGH:
context_meta.write(TOPIC_ABORTED, traceback.format_exc())
raise
except BaseException as e:
msg = "Exception while calling the node's finish() function."
msg += "\n\n" + indent(traceback.format_exc(), "| ")
context_meta.write(TOPIC_ABORTED, msg)
raise InternalProblem(msg) from e # XXX
logger.info("benchmark data", stats=context_data.profiler.show_stats())
logger.info("benchmark meta", stats=context_meta.profiler.show_stats())
except BrokenPipeError:
msg = "The other side closed communication."
logger.info(msg)
return
except ExternalTimeout as e:
msg = "Could not receive any other messages."
if context_data:
msg += f"\n Expecting one of: {context_data.pc.get_expected_events()}"
with suppress_exception_logit():
sink.write_control_message(CTRL_ABORTED, msg)
sink.write_control_message(CTRL_OVER)
raise ExternalTimeout(msg) from e
except InternalProblem:
raise
except BaseException as e:
msg = f"Unexpected error:"
msg += "\n\n" + indent(traceback.format_exc(), "| ")
with suppress_exception_logit():
sink.write_control_message(CTRL_ABORTED, msg)
sink.write_control_message(CTRL_OVER)
raise InternalProblem(msg) from e # XXX
class MetaHandler:
def __init__(self, node, protocol):
self.node = node
self.protocol = protocol
def set_config(self, key: str, value):
if hasattr(self.node, ATT_CONFIG):
config = self.node.config
if hasattr(config, key):
setattr(self.node.config, key, value)
else:
msg = f"Could not find config key {key}"
raise ZValueError(msg, config=config)
else:
msg = 'Node does not have the "config" attribute.'
raise ValueError(msg)
def on_received_set_config(self, context, data: SetConfig):
key = data.key
value = data.value
try:
self.set_config(key, value)
except ValueError as e:
context.write("set_config_error", str(e))
else:
context.write("set_config_ack", None)
def on_received_describe_protocol(self, context):
desc = ProtocolDescription(data=self.protocol, meta=basic_protocol)
context.write("protocol_description", desc)
def on_received_describe_config(self, context):
K = type(self.node)
if hasattr(K, "__annotations__") and ATT_CONFIG in K.__annotations__:
config_type = K.__annotations__[ATT_CONFIG]
config_current = getattr(self.node, ATT_CONFIG)
else:
@dataclass
class NoConfig:
pass
config_type = NoConfig
config_current = NoConfig()
desc = ConfigDescription(config=config_type, current=config_current)
context.write("config_description", desc, with_schema=True)
def on_received_describe_node(self, context):
desc = NodeDescription(self.node.__doc__)
context.write("node_description", desc, with_schema=True)
def on_received_describe_build(self, context):
desc = BuildDescription()
context.write("build_description", desc, with_schema=True)
def handle_message_node(parsed: RawTopicMessage, agent, context: ConcreteContext):
protocol = context.protocol
topic = parsed.topic
data = parsed.data
pc = context.pc
klass = protocol.inputs[topic]
with context.profiler.prof(':deserialization'):
try:
# noinspection PyTypeChecker
ob = object_from_ipce(data, klass, iedo=iedo)
except BaseException as e:
msg = f'Cannot deserialize object for topic "{topic}" expecting {klass}.'
try:
parsed = json.dumps(parsed, indent=2)
except:
parsed = str(parsed)
msg += "\n\n" + indent(parsed, "|", "parsed: |")
raise DecodingError(msg) from e
if parsed.timing is not None:
timing = object_from_ipce(parsed.timing, TimingInfo, iedo=iedo)
else:
timing = TimingInfo()
timing.received = local_time()
context.set_last_timing(timing)
# logger.info(f'Before push the state is\n{pc}')
event = InputReceived(topic)
expected = pc.get_expected_events()
res = pc.push(event)
# names = pc.get_active_states_names()
# logger.info(f'After push of {event}: result \n{res} active {names}' )
if isinstance(res, Unexpected):
msg = f'Unexpected input "{topic}": {res}'
msg += f"\nI expected: {expected}"
msg += f"\n {pc}"
context.error(msg)
raise ExternalProtocolViolation(msg)
else:
expect_fn = f"on_received_{topic}"
with context.profiler.prof(topic):
call_if_fun_exists(agent, expect_fn, data=ob, context=context, timing=timing)
def check_implementation(node, protocol: InteractionProtocol):
logger0.debug("checking implementation")
for n in protocol.inputs:
expect_fn = f"on_received_{n}"
if not hasattr(node, expect_fn):
msg = f"The class {type(node).__name__} misses the function {expect_fn}"
msg += f"\nI know {sorted(_ for _ in type(node).__dict__ if _.startswith('on'))}"
raise NotConforming(msg)
for x in type(node).__dict__:
if x.startswith("on_received_"):
input_name = x.replace("on_received_", "")
if input_name not in protocol.inputs:
msg = f'The node has function "{x}" but there is no input "{input_name}".'
raise NotConforming(msg)
logger0.debug("checking implementation OK") | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/wrapper.py | wrapper.py |
import os
import stat
import time
from io import BufferedReader
from zuper_commons.fs import make_sure_dir_exists
from . import logger, logger_interaction
def wait_for_creation(fn: str, wait: float = 3.0):
t0 = time.time()
if os.path.exists(fn):
# logger.info(f"Found {fn} right away.")
return
while not os.path.exists(fn):
time.sleep(wait)
dt = int(time.time() - t0)
msg = f"Waiting for creation of {fn} since {dt} seconds."
logger.debug(msg)
dt = int(time.time() - t0)
logger.debug(f"Found {fn} after {dt} seconds waiting.")
def open_for_read(fin: str, timeout: float = None) -> BufferedReader:
t0 = time.time()
# first open reader file in case somebody is waiting for it
if os.path.exists(fin):
logger_interaction.info(f"Found file {fin} right away")
else:
while not os.path.exists(fin):
delta = time.time() - t0
if timeout is not None and (delta > timeout):
msg = f"The file {fin!r} was not created before {timeout:.1f} seconds. I give up."
raise EnvironmentError(msg)
logger_interaction.info(f"waiting for file {fin} to be created since {int(delta)} seconds.")
time.sleep(1)
delta = time.time() - t0
logger_interaction.info(f"Waited for file {fin} for a total of {int(delta)} seconds")
logger_interaction.info(f"Opening input {fin} for reading.")
fi = open(fin, "rb", buffering=0)
# noinspection PyTypeChecker
fi = BufferedReader(fi, buffer_size=1)
return fi
def open_for_write(fout: str):
if fout == "/dev/stdout":
logger_interaction.info("Opening stdout for writing")
return open("/dev/stdout", "wb", buffering=0)
else:
wants_fifo = fout.startswith("fifo:")
fout = fout.replace("fifo:", "")
logger_interaction.info(f"Opening output file {fout} (wants fifo: {wants_fifo})")
if not os.path.exists(fout):
if wants_fifo:
make_sure_dir_exists(fout)
os.mkfifo(fout)
logger_interaction.info(f"Fifo {fout} created.")
else:
is_fifo = stat.S_ISFIFO(os.stat(fout).st_mode)
if wants_fifo and not is_fifo:
logger_interaction.info(f"Recreating {fout} as a fifo.")
os.unlink(fout)
os.mkfifo(fout)
if wants_fifo:
logger_interaction.info(f"Fifo {fout} created. Opening will block until a reader appears.")
logger.debug(f"Fifo {fout} created. I will block until a reader appears.")
make_sure_dir_exists(fout)
fo = open(fout, "wb", buffering=0)
logger.debug(f"Fifo reader appeared for {fout}.")
if wants_fifo:
logger_interaction.info(f"A reader has connected to my fifo {fout}")
return fo | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/streams.py | streams.py |
import time
from abc import ABC, abstractmethod
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from typing import ContextManager, Dict, List, Optional, Tuple
__all__ = ['ProfilerImp', 'Profiler', 'fake_profiler']
from zuper_commons.types import ZException
@dataclass
class FinishedIteration:
dt: float
@dataclass
class Iteration:
tname: str
children: "Dict[str, List[FinishedIteration]]"
class Profiler(ABC):
@abstractmethod
def prof(self, s: str) -> ContextManager[None]:
yield
@abstractmethod
def show_stats(self, prefix: Optional[Tuple[str, ...]] = None) -> str:
pass
class ProfilerImp(Profiler):
context: List[Iteration]
stats: Dict[Tuple[str, ...], List[float]]
def __init__(self):
self.context = [Iteration('root', defaultdict(list))]
self.stats = defaultdict(list)
self.t0 = time.time()
@contextmanager
def prof(self, s: str):
it = Iteration(s, defaultdict(list))
self.context.append(it)
current_context = list(self.context)
my_id = tuple(_.tname for _ in current_context)
t0 = time.time()
yield
self.context.pop()
dt = time.time() - t0
s = '/'.join(my_id)
if self.context:
last = self.context[-1]
last.children[s].append(FinishedIteration(dt))
if it.children:
explained = sum(sum(x.dt for x in _) for _ in it.children.values())
unexplained = dt - explained
# perc = int(100 * unexplained / dt)
# logger.debug(f'timer: {dt:10.4f} {s} / {unexplained:.4f} {perc}% unexp ')
self.stats[my_id + ('self',)].append(unexplained)
else:
pass
# logger.debug(f'timer: {dt:10.4f} {s}')
self.stats[my_id].append(dt)
def show_stats(self, prefix: Tuple[str, ...] = ('root',)) -> str:
# logger.info(str(list(self.stats)))
tottime = time.time() - self.t0
lines = self.show_stats_(prefix, 1, tottime)
if not lines:
lines.append(f'Could not find any *completed* children for prefix {prefix}.')
# raise ZException(msg, prefix=prefix, lines=lines,
# known=list(self.stats))
return "\n".join(lines)
def show_stats_(self, prefix: Tuple[str, ...], ntot: int, tottime: float) -> List[str]:
# logger.info(f'Searching while {prefix}')
lines = []
for k, v in self.stats.items():
if k[:len(prefix)] != prefix:
# logger.info(f'excluding {k}')
continue
if len(k) == len(prefix) + 1:
n = len(v)
total = sum(v)
rn = n / ntot
dt = total / n
perc = 100 * total / tottime
s = f'┌ {perc:4.1f}% ' + k[-1] + f' {dt:6.3f}'
if rn != 1:
s += f' {rn:6.1f}x'
lines.append(s)
for _ in self.show_stats_(prefix=k, ntot=n, tottime=total):
lines.append('│ ' + _)
# else:
# logger.info(f'excluding {k} not child')
# logger.info(f'lines for {prefix}: {lines}')
return lines
class FakeProfiler(Profiler):
@contextmanager
def prof(self, s: str):
yield
def show_stats(self, prefix: Optional[Tuple[str, ...]] = None) -> str:
return '(fake)'
fake_profiler = FakeProfiler() | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/profiler.py | profiler.py |
from dataclasses import dataclass
from typing import Any, Dict, List
from zuper_nodes import InteractionProtocol
@dataclass
class SetConfig:
key: str
value: Any
@dataclass
class ConfigDescription:
config: type
current: Any
@dataclass
class NodeDescription:
description: str
@dataclass
class BuildDescription:
pass
@dataclass
class ProtocolDescription:
data: InteractionProtocol
meta: InteractionProtocol
@dataclass
class CommsHealth:
# ignored because not compatible
ignored: Dict[str, int]
# unexpected topics
unexpected: Dict[str, int]
# malformed data
malformed: Dict[str, int]
# if we are completely lost
unrecoverable_protocol_error: bool
@dataclass
class NodeHealth:
# there is a critical error that makes it useless to continue
critical: bool
# severe problem but we can continue
severe: bool
# a minor problem to report
minor: bool
details: str
LogEntry = str
basic_protocol = InteractionProtocol(
description="""\
Basic interaction protocol for nodes spoken by the node wrapper.
""",
inputs={
"describe_config": type(None),
"set_config": SetConfig,
"describe_protocol": type(None),
"describe_node": type(None),
"describe_build": type(None),
"get_state": type(None),
"set_state": Any,
"get_logs": type(None),
},
language="""\
(
(in:describe_config ; out:config_description) |
(in:set_config ; (out:set_config_ack | out:set_config_error)) |
(in:describe_protocol ; out:protocol_description) |
(in:describe_node ; out:node_description) |
(in:describe_build ; out:build_description) |
(in:get_state ; out:node_state) |
(in:set_state ; (out:set_state_ack| out:set_state_error) ) |
(in:get_logs ; out:logs) |
out:aborted
)*
""",
outputs={
"config_description": ConfigDescription,
"set_config_ack": type(None),
"set_config_error": str,
"protocol_description": ProtocolDescription,
"node_description": NodeDescription,
"build_description": BuildDescription,
"node_state": Any,
"set_state_ack": type(None),
"set_state_error": str,
"logs": List[LogEntry],
"aborted": str,
},
) | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/meta_protocol.py | meta_protocol.py |
import os
from io import BufferedReader
from typing import cast, List, Optional
import cbor2 as cbor
from zuper_commons.text import indent
from zuper_commons.types import ZException
from zuper_ipce import IEDO, IESO, ipce_from_object, object_from_ipce
from zuper_ipce.json2cbor import read_next_cbor
from zuper_nodes import (
check_compatible_protocol,
ExternalNodeDidNotUnderstand,
ExternalProtocolViolation,
ExternalTimeout,
InteractionProtocol,
RemoteNodeAborted,
TimingInfo,
)
from . import logger, logger_interaction
from .constants import (
CAPABILITY_PROTOCOL_REFLECTION,
CTRL_ABORTED,
CTRL_CAPABILITIES,
CTRL_NOT_UNDERSTOOD,
CTRL_OVER,
CTRL_UNDERSTOOD,
CUR_PROTOCOL,
FIELD_COMPAT,
FIELD_CONTROL,
FIELD_DATA,
FIELD_TIMING,
FIELD_TOPIC,
TAG_Z2,
TOPIC_ABORTED,
)
from .meta_protocol import basic_protocol, ProtocolDescription
from .profiler import fake_profiler, Profiler
from .streams import wait_for_creation
from .struct import interpret_control_message, MsgReceived, WireMessage
__all__ = ["ComponentInterface", "MsgReceived", "read_reply"]
iedo = IEDO(True, True)
class ComponentInterface:
node_protocol: Optional[InteractionProtocol]
data_protocol: Optional[InteractionProtocol]
nreceived: int
expect_protocol: Optional[InteractionProtocol]
def __init__(
self,
fnin: str,
fnout: str,
expect_protocol: Optional[InteractionProtocol],
nickname: str,
timeout=None,
):
self.nickname = nickname
self._cc = None
try:
os.mkfifo(fnin)
except BaseException as e:
msg = f"Cannot create fifo {fnin}"
raise Exception(msg) from e
### FIXME: this is blocking, throw exception
self.fpin = open(fnin, "wb", buffering=0)
wait_for_creation(fnout)
self.fnout = fnout
f = open(fnout, "rb", buffering=0)
# noinspection PyTypeChecker
self.fpout = BufferedReader(f, buffer_size=1)
self.nreceived = 0
self.expect_protocol = expect_protocol
self.node_protocol = None
self.data_protocol = None
self.timeout = timeout
def close(self):
self.fpin.close()
self.fpout.close()
def cc(self, f):
""" CC-s everything that is read or written to this file. """
self._cc = f
def _get_node_protocol(self, timeout: float = None):
"""
raises ExternalProtocolViolation, indirectly IncompatibleProtocol
:param timeout:
:return:
"""
self.my_capabilities = {TAG_Z2: {CAPABILITY_PROTOCOL_REFLECTION: True}}
msg = {FIELD_CONTROL: CTRL_CAPABILITIES, FIELD_DATA: self.my_capabilities}
j = self._serialize(msg)
self._write(j)
msgs = read_reply(
self.fpout,
timeout=timeout,
waiting_for=f"Reading {self.nickname} capabilities",
nickname=self.nickname,
)
self.node_capabilities = msgs[0]["data"]
# logger.info("My capabilities: %s" % self.my_capabilities)
# logger.info("Found capabilities: %s" % self.node_capabilities)
if TAG_Z2 not in self.node_capabilities:
msg = f"Incompatible node; capabilities {self.node_capabilities}"
raise ExternalProtocolViolation(msg)
z = self.node_capabilities[TAG_Z2]
if not z.get(CAPABILITY_PROTOCOL_REFLECTION, False):
logger.debug("Node does not support reflection.")
if self.expect_protocol is None:
msg = "Node does not support reflection - need to provide protocol."
raise Exception(msg)
else:
ob: MsgReceived[ProtocolDescription]
ob = self.write_topic_and_expect(
"wrapper.describe_protocol", expect="protocol_description", timeout=timeout,
)
self.node_protocol = ob.data.data
self.data_protocol = ob.data.meta
if self.expect_protocol is not None:
check_compatible_protocol(self.node_protocol, self.expect_protocol)
def write_topic_and_expect(
self,
topic: str,
data=None,
with_schema: bool = False,
timeout: float = None,
timing=None,
expect: str = None,
profiler: Profiler = fake_profiler
) -> MsgReceived:
timeout = timeout or self.timeout
with profiler.prof(f':write-{topic}'):
self._write_topic(topic, data=data, with_schema=with_schema, timing=timing, profiler=profiler)
with profiler.prof(f':write-{topic}-expect-{expect}'):
ob: MsgReceived = self.read_one(expect_topic=expect, timeout=timeout, profiler=profiler)
return ob
def write_topic_and_expect_zero(
self, topic: str, data=None, with_schema=False, timeout=None, timing=None,
profiler: Profiler = fake_profiler
):
timeout = timeout or self.timeout
with profiler.prof(f':write-{topic}'):
self._write_topic(topic, data=data, with_schema=with_schema, timing=timing, profiler=profiler)
with profiler.prof(f':write-{topic}-wait-reply'):
msgs = read_reply(self.fpout, timeout=timeout, nickname=self.nickname)
if msgs:
msg = f"Expecting zero, got {msgs}"
raise ExternalProtocolViolation(msg)
def _write_topic(self, topic: str, data=None, with_schema: bool = False, timing=None,
profiler: Profiler = fake_profiler):
suggest_type = object
if self.node_protocol:
if topic in self.node_protocol.inputs:
suggest_type = self.node_protocol.inputs[topic]
ieso = IESO(with_schema=with_schema)
ieso_true = IESO(with_schema=True)
with profiler.prof(':serialization'):
ipce = ipce_from_object(data, suggest_type, ieso=ieso)
# try to re-read
if suggest_type is not object:
try:
with profiler.prof(':double-check'):
_ = object_from_ipce(ipce, suggest_type, iedo=iedo)
except BaseException as e:
msg = (
f'While attempting to write on topic "{topic}", cannot '
f"interpret the value as {suggest_type}.\nValue: {data}"
)
raise ZException(msg, data=data, ipce=ipce, suggest_type=suggest_type) from e # XXX
msg = {
FIELD_COMPAT: [CUR_PROTOCOL],
FIELD_TOPIC: topic,
FIELD_DATA: ipce,
FIELD_TIMING: timing,
}
with profiler.prof(':cbor-dump1'):
j = self._serialize(msg)
with profiler.prof(':write'):
self._write(j)
# make sure we write the schema when we copy it
if not with_schema:
with profiler.prof(':re-serializing-for-log'):
msg[FIELD_DATA] = ipce_from_object(data, ieso=ieso_true)
with profiler.prof(':cbor-dump2'):
j = self._serialize(msg)
if self._cc:
with profiler.prof(':write-cc'):
self._cc.write(j)
self._cc.flush()
logger_interaction.info(f'Written to topic "{topic}" >> {self.nickname}.')
def _write(self, j):
try:
self.fpin.write(j)
self.fpin.flush()
except BrokenPipeError as e:
msg = (
f'While attempting to write to node "{self.nickname}", '
f"I reckon that the pipe is closed and the node exited."
)
try:
received = self.read_one(expect_topic=TOPIC_ABORTED)
if received.topic == TOPIC_ABORTED:
msg += "\n\nThis is the aborted message:"
msg += "\n\n" + indent(received.data, " |")
except BaseException as e2:
msg += f"\n\nI could not read any aborted message: {e2}"
raise RemoteNodeAborted(msg) from e
def _serialize(self, msg: object) -> bytes:
j = cbor.dumps(msg)
return j
def read_one(self, expect_topic: str = None, timeout: float = None,
profiler: Profiler = fake_profiler) -> MsgReceived:
timeout = timeout or self.timeout
try:
if expect_topic:
waiting_for = f'Expecting topic "{expect_topic}" << {self.nickname}.'
else:
waiting_for = None
msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for, nickname=self.nickname,
profiler=profiler)
if len(msgs) == 0:
msg = f'Expected one message from node "{self.nickname}". Got zero.'
if expect_topic:
msg += f'\nExpecting topic "{expect_topic}".'
raise ExternalProtocolViolation(msg)
if len(msgs) > 1:
msg = f"Expected only one message. Got {msgs}"
raise ExternalProtocolViolation(msg)
msg = msgs[0]
if FIELD_TOPIC not in msg:
m = f'Invalid message does not contain the field "{FIELD_TOPIC}".'
m += f"\n {msg}"
raise ExternalProtocolViolation(m)
topic = msg[FIELD_TOPIC]
if expect_topic:
if topic != expect_topic:
msg = f'I expected topic "{expect_topic}" but received "{topic}".'
raise ExternalProtocolViolation(msg)
if topic in basic_protocol.outputs:
klass = basic_protocol.outputs[topic]
else:
if self.node_protocol:
if topic not in self.node_protocol.outputs:
msg = f'Cannot find topic "{topic}" in outputs of detected node protocol.'
msg += f"\nI know: {sorted(self.node_protocol.outputs)}"
raise ExternalProtocolViolation(msg)
else:
klass = self.node_protocol.outputs[topic]
else:
if not topic in self.expect_protocol.outputs:
msg = f'Cannot find topic "{topic}".'
raise ExternalProtocolViolation(msg)
else:
klass = self.expect_protocol.outputs[topic]
data = object_from_ipce(msg[FIELD_DATA], klass, iedo=iedo)
ieso_true = IESO(with_schema=True)
if self._cc:
# need to revisit this
msg[FIELD_DATA] = ipce_from_object(data, ieso=ieso_true)
msg_b = self._serialize(msg)
self._cc.write(msg_b)
self._cc.flush()
if FIELD_TIMING not in msg:
timing = TimingInfo()
else:
timing = object_from_ipce(msg[FIELD_TIMING], TimingInfo, iedo=iedo)
self.nreceived += 1
return MsgReceived[klass](topic, data, timing)
except StopIteration as e:
msg = f"EOF detected on {self.fnout} after {self.nreceived} messages."
if expect_topic:
msg += f' Expected topic "{expect_topic}".'
raise StopIteration(msg) from e
except TimeoutError as e:
msg = f"Timeout detected on {self.fnout} after {self.nreceived} messages."
if expect_topic:
msg += f' Expected topic "{expect_topic}".'
raise ExternalTimeout(msg) from e
def read_reply(fpout, nickname: str, timeout: float = None, waiting_for: str = None,
profiler: Profiler = fake_profiler) -> List:
""" Reads a control message. Returns if it is CTRL_UNDERSTOOD.
Raises:
ExternalTimeout
RemoteNodeAborted
ExternalNodeDidNotUnderstand
ExternalProtocolViolation otherwise. """
try:
with profiler.prof(':read_next_cbor'):
c = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
wm = cast(WireMessage, c)
# logger.debug(f'{nickname} sent {wm}')
except TimeoutError:
msg = f"Timeout of {timeout} violated while waiting for {waiting_for!r}."
raise ExternalTimeout(msg) from None
except StopIteration:
msg = f"Remote node closed communication ({waiting_for})"
raise RemoteNodeAborted(msg) from None
cm = interpret_control_message(wm)
if cm.code == CTRL_UNDERSTOOD:
with profiler.prof(':read_until_over'):
others = read_until_over(fpout, timeout=timeout, nickname=nickname)
return others
elif cm.code == CTRL_ABORTED:
msg = f'The remote node "{nickname}" aborted with the following error:'
msg += "\n\n" + indent(cm.msg, "|", f"error in {nickname} |")
raise RemoteNodeAborted(msg)
elif cm.code == CTRL_NOT_UNDERSTOOD:
_others = read_until_over(fpout, timeout=timeout, nickname=nickname)
msg = f'The remote node "{nickname}" reports that it did not understand the message:'
msg += "\n\n" + indent(cm.msg, "|", f"reported by {nickname} |")
raise ExternalNodeDidNotUnderstand(msg)
else:
msg = f"Remote node raised unknown code {cm}: {cm.code}"
raise ExternalProtocolViolation(msg)
def read_until_over(fpout, timeout: float, nickname: str) -> List[WireMessage]:
""" Raises RemoteNodeAborted, ExternalTimeout """
res = []
waiting_for = f"Reading reply of {nickname}."
while True:
try:
c = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for)
wm = cast(WireMessage, c)
if wm.get(FIELD_CONTROL, "") == CTRL_ABORTED:
m = f'External node "{nickname}" aborted:'
m += "\n\n" + indent(wm.get(FIELD_DATA, None), "|", f"error in {nickname} |")
raise RemoteNodeAborted(m)
if wm.get(FIELD_CONTROL, "") == CTRL_OVER:
# logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res))
break
# logger.info(f'Node "{nickname}" sent %s.' % len(wm))
except StopIteration:
msg = f'External node "{nickname}" closed communication.'
raise RemoteNodeAborted(msg) from None
except TimeoutError:
msg = f'Timeout while reading output of node "{nickname}" after {timeout} s.'
raise ExternalTimeout(msg) from None
res.append(wm)
return res | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/wrapper_outside.py | wrapper_outside.py |
import time
from typing import Iterator, Optional, Union
import select
from zuper_commons.text import indent
from zuper_ipce.json2cbor import read_next_cbor
from zuper_nodes.structures import ExternalTimeout
from . import logger
from .constants import CUR_PROTOCOL, FIELD_COMPAT, FIELD_CONTROL, FIELD_DATA, FIELD_TIMING, FIELD_TOPIC
from .struct import ControlMessage, interpret_control_message, RawTopicMessage, WireMessage
M = Union[RawTopicMessage, ControlMessage]
def inputs(f, give_up: Optional[float] = None, waiting_for: str = None) -> Iterator[M]:
last = time.time()
intermediate_timeout = 3.0
intermediate_timeout_multiplier = 1.5
while True:
readyr, readyw, readyx = select.select([f], [], [f], intermediate_timeout)
if readyr:
try:
parsed = read_next_cbor(f, waiting_for=waiting_for)
except StopIteration:
return
if not isinstance(parsed, dict):
msg = f"Expected a dictionary, obtained {parsed!r}"
logger.error(msg)
continue
if FIELD_CONTROL in parsed:
m = interpret_control_message(WireMessage(parsed))
yield m
elif FIELD_TOPIC in parsed:
if not FIELD_COMPAT in parsed:
msg = f'Could not find field "compat" in structure "{parsed}".'
logger.error(msg)
continue
l = parsed[FIELD_COMPAT]
if not isinstance(l, list):
msg = f"Expected a list for compatibility value, found {l!r}"
logger.error(msg)
continue
if not CUR_PROTOCOL in parsed[FIELD_COMPAT]:
msg = f"Skipping message because could not find {CUR_PROTOCOL} in {l}."
logger.warn(msg)
continue
rtm = RawTopicMessage(
parsed[FIELD_TOPIC], parsed.get(FIELD_DATA, None), parsed.get(FIELD_TIMING, None),
)
yield rtm
elif readyx:
logger.warning(f"Exceptional condition on input channel {readyx}")
else:
delta = time.time() - last
if give_up is not None and (delta > give_up):
msg = f"I am giving up after {delta:.1f} seconds."
raise ExternalTimeout(msg)
else:
intermediate_timeout *= intermediate_timeout_multiplier
msg = f"Input channel not ready after {delta:.1f} seconds. Will re-try."
if waiting_for:
msg += "\n" + indent(waiting_for, "> ")
msg += f"\n I will warn again in {intermediate_timeout:.1f} seconds."
logger.warning(msg) | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/reading.py | reading.py |
import argparse
import dataclasses
import subprocess
import sys
from dataclasses import dataclass
from io import BufferedReader, BytesIO
from typing import cast
import cbor2
import yaml
from zuper_commons.text import indent
from zuper_ipce import object_from_ipce
from zuper_ipce.json2cbor import read_cbor_or_json_objects
from zuper_nodes import InteractionProtocol
from . import logger
from .meta_protocol import (
BuildDescription,
ConfigDescription,
NodeDescription,
ProtocolDescription,
)
def identify_main():
usage = None
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument("--image", default=None)
parser.add_argument("--command", default=None)
parsed = parser.parse_args()
image = parsed.image
if image is not None:
ni: NodeInfo = identify_image2(image)
elif parsed.command is not None:
command = parsed.command.split()
ni: NodeInfo = identify_command(command)
else:
msg = "Please specify either --image or --command"
logger.error(msg)
sys.exit(1)
print("\n\n")
print(indent(describe_nd(ni.nd), "", "desc: "))
print("\n\n")
print(indent(describe_bd(ni.bd), "", "build: "))
print("\n\n")
print(indent(describe_cd(ni.cd), "", "config: "))
print("\n\n")
print(indent(describe(ni.pd.data), "", "data: "))
print("\n\n")
print(indent(describe(ni.pd.meta), "", "meta: "))
def describe_nd(nd: NodeDescription):
return str(nd.description)
def describe_bd(nd: BuildDescription):
return str(nd)
def describe_cd(nd: ConfigDescription):
s = []
# noinspection PyDataclass
for f in dataclasses.fields(nd.config):
# for k, v in nd.config.__annotations__.items():
s.append(f"{f.name:>20}: {f.type} = {f.default}")
if not s:
return "No configuration switches available."
if hasattr(nd.config, "__doc__"):
s.insert(0, nd.config.__doc__)
return "\n".join(s)
def describe(ip: InteractionProtocol):
s = "InteractionProtocol"
s += "\n\n" + "* Description:"
s += "\n\n" + indent(ip.description.strip(), " ")
s += "\n\n" + "* Inputs:"
for name, type_ in ip.inputs.items():
s += f"\n {name:>25}: {type_}"
s += "\n\n" + "* Outputs:"
for name, type_ in ip.outputs.items():
s += f"\n {name:>25}: {type_}"
s += "\n\n" + "* Language:"
s += "\n\n" + ip.language
return s
@dataclass
class NodeInfo:
pd: ProtocolDescription
nd: NodeDescription
bd: BuildDescription
cd: ConfigDescription
def identify_command(command) -> NodeInfo:
d = [
{"topic": "wrapper.describe_protocol"},
{"topic": "wrapper.describe_config"},
{"topic": "wrapper.describe_node"},
{"topic": "wrapper.describe_build"},
]
to_send = b""
for p in d:
p["compat"] = ["aido2"]
# to_send += (json.dumps(p) + '\n').encode('utf-8')
to_send += cbor2.dumps(p)
cp = subprocess.run(command, input=to_send, capture_output=True)
s = cp.stderr.decode("utf-8")
sys.stderr.write(indent(s.strip(), "|", " stderr: |") + "\n\n")
# noinspection PyTypeChecker
f = BufferedReader(BytesIO(cp.stdout))
stream = read_cbor_or_json_objects(f)
res = stream.__next__()
logger.debug(yaml.dump(res))
pd = cast(ProtocolDescription, object_from_ipce(res["data"], ProtocolDescription))
res = stream.__next__()
logger.debug(yaml.dump(res))
cd = cast(ConfigDescription, object_from_ipce(res["data"], ConfigDescription))
res = stream.__next__()
logger.debug(yaml.dump(res))
nd = cast(NodeDescription, object_from_ipce(res["data"], NodeDescription))
res = stream.__next__()
logger.debug(yaml.dump(res))
bd = cast(BuildDescription, object_from_ipce(res["data"], BuildDescription))
logger.debug(yaml.dump(res))
return NodeInfo(pd, nd, bd, cd)
def identify_image2(image) -> NodeInfo:
cmd = ["docker", "run", "--rm", "-i", image]
return identify_command(cmd)
# def identify_image(image):
# import docker
# client = docker.from_env()
#
#
# container: Container = client.containers.create(image, detach=True, stdin_open=True)
# print(container)
# # time.sleep(4)
# # attach to the container stdin socket
# container.start()
# # s = container.exec_run()
# s: SocketIO = container.attach_socket(params={'stdin': 1, 'stream': 1, 'stderr': 0, 'stdout': 0})
# s_out: SocketIO = container.attach_socket(params={ 'stream': 1, 'stdout': 1, 'stderr': 0, 'stdin': 0})
# s_stderr: SocketIO = container.attach_socket(params={'stream': 1, 'stdout': 0, 'stderr': 1, 'stdin': 0})
# print(s.__dict__)
# print(s_out.__dict__)
# # send text
# # s.write(j)
# os.write(s._sock.fileno(), j)
# os.close(s._sock.fileno())
# s._sock.close()
# # s.close()
#
# f = os.fdopen(s_out._sock.fileno(), 'rb')
# # there is some garbage: b'\x01\x00\x00\x00\x00\x00\x1e|{
# f.read(8)
#
# for x in read_cbor_or_json_objects(f):
# print(x)
# print(f.read(10))
# # print(os.read(s_out._sock.fileno(), 100))
#
# print(os.read(s_stderr._sock.fileno(), 100))
# # close, stop and disconnect
# s.close() | zuper-nodes-z6 | /zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/identify.py | identify.py |
Subsets and Splits