feat: first generated version

This commit is contained in:
Adam Uhlíř 2024-08-23 16:22:29 +02:00
parent 6b483a7802
commit bc41cb9d6a
No known key found for this signature in database
GPG Key ID: 1D17A9E81F76155B
97 changed files with 13354 additions and 1 deletions

38
.github/workflows/python.yml vendored Normal file
View File

@ -0,0 +1,38 @@
# NOTE: This file is auto generated by OpenAPI Generator.
# URL: https://openapi-generator.tech
#
# ref: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
name: codex_client Python package
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f test-requirements.txt ]; then pip install -r test-requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest

66
.gitignore vendored Normal file
View File

@ -0,0 +1,66 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
venv/
.venv/
.python-version
.pytest_cache
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
#Ipython Notebook
.ipynb_checkpoints

31
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,31 @@
# NOTE: This file is auto generated by OpenAPI Generator.
# URL: https://openapi-generator.tech
#
# ref: https://docs.gitlab.com/ee/ci/README.html
# ref: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml
stages:
- test
.pytest:
stage: test
script:
- pip install -r requirements.txt
- pip install -r test-requirements.txt
- pytest --cov=codex_client
pytest-3.7:
extends: .pytest
image: python:3.7-alpine
pytest-3.8:
extends: .pytest
image: python:3.8-alpine
pytest-3.9:
extends: .pytest
image: python:3.9-alpine
pytest-3.10:
extends: .pytest
image: python:3.10-alpine
pytest-3.11:
extends: .pytest
image: python:3.11-alpine

23
.openapi-generator-ignore Normal file
View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

68
.openapi-generator/FILES Normal file
View File

@ -0,0 +1,68 @@
.github/workflows/python.yml
.gitignore
.gitlab-ci.yml
.travis.yml
README.md
codex_client/__init__.py
codex_client/api/__init__.py
codex_client/api/data_api.py
codex_client/api/debug_api.py
codex_client/api/marketplace_api.py
codex_client/api/node_api.py
codex_client/api_client.py
codex_client/api_response.py
codex_client/configuration.py
codex_client/exceptions.py
codex_client/models/__init__.py
codex_client/models/content.py
codex_client/models/data_item.py
codex_client/models/data_list.py
codex_client/models/debug_info.py
codex_client/models/erasure_parameters.py
codex_client/models/manifest_item.py
codex_client/models/peer_id_read.py
codex_client/models/po_r_parameters.py
codex_client/models/purchase.py
codex_client/models/reservation.py
codex_client/models/sales_availability.py
codex_client/models/sales_availability_create.py
codex_client/models/sales_availability_read.py
codex_client/models/slot.py
codex_client/models/space.py
codex_client/models/spr_read.py
codex_client/models/storage_ask.py
codex_client/models/storage_request.py
codex_client/models/storage_request_creation.py
codex_client/py.typed
codex_client/rest.py
docs/Content.md
docs/DataApi.md
docs/DataItem.md
docs/DataList.md
docs/DebugApi.md
docs/DebugInfo.md
docs/ErasureParameters.md
docs/ManifestItem.md
docs/MarketplaceApi.md
docs/NodeApi.md
docs/PeerIdRead.md
docs/PoRParameters.md
docs/Purchase.md
docs/Reservation.md
docs/SPRRead.md
docs/SalesAvailability.md
docs/SalesAvailabilityCREATE.md
docs/SalesAvailabilityREAD.md
docs/Slot.md
docs/Space.md
docs/StorageAsk.md
docs/StorageRequest.md
docs/StorageRequestCreation.md
git_push.sh
pyproject.toml
requirements.txt
setup.cfg
setup.py
test-requirements.txt
test/__init__.py
tox.ini

View File

@ -0,0 +1 @@
7.8.0

17
.travis.yml Normal file
View File

@ -0,0 +1,17 @@
# ref: https://docs.travis-ci.com/user/languages/python
language: python
python:
- "3.7"
- "3.8"
- "3.9"
- "3.10"
- "3.11"
# uncomment the following if needed
#- "3.11-dev" # 3.11 development branch
#- "nightly" # nightly build
# command to install dependencies
install:
- "pip install -r requirements.txt"
- "pip install -r test-requirements.txt"
# command to run tests
script: pytest --cov=codex_client

143
README.md
View File

@ -1 +1,142 @@
# py-codex-api
# Codex API Client
List of endpoints and interfaces available to Codex API users
This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: 0.0.1
- Package version: 1.0.0
- Generator version: 7.8.0
- Build package: org.openapitools.codegen.languages.PythonClientCodegen
## Requirements.
Python 3.7+
## Installation & Usage
### pip install
If the python package is hosted on a repository, you can install directly using:
```sh
pip install git+https://github.com/auhau/py-codex-api.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/auhau/py-codex-api.git`)
Then import the package:
```python
import codex_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 codex_client
```
### Tests
Execute `pytest` to run the tests.
## Getting Started
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DataApi(api_client)
cid = 'cid_example' # str | File to be downloaded.
try:
# Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned.
api_response = api_instance.download_local(cid)
print("The response of DataApi->download_local:\n")
pprint(api_response)
except ApiException as e:
print("Exception when calling DataApi->download_local: %s\n" % e)
```
## Documentation for API Endpoints
All URIs are relative to *http://localhost:8080/api/codex/v1*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*DataApi* | [**download_local**](docs/DataApi.md#download_local) | **GET** /data/{cid} | Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned.
*DataApi* | [**download_network**](docs/DataApi.md#download_network) | **GET** /data/{cid}/network | Download a file from the network in a streaming manner. If the file is not available locally, it will be retrieved from other nodes in the network if able.
*DataApi* | [**list_data**](docs/DataApi.md#list_data) | **GET** /data | Lists manifest CIDs stored locally in node.
*DataApi* | [**space**](docs/DataApi.md#space) | **GET** /space | Gets a summary of the storage space allocation of the node.
*DataApi* | [**upload**](docs/DataApi.md#upload) | **POST** /data | Upload a file in a streaming manner. Once finished, the file is stored in the node and can be retrieved by any node in the network using the returned CID.
*DebugApi* | [**get_debug_info**](docs/DebugApi.md#get_debug_info) | **GET** /debug/info | Gets node information
*DebugApi* | [**set_debug_log_level**](docs/DebugApi.md#set_debug_log_level) | **POST** /debug/chronicles/loglevel | Set log level at run time
*MarketplaceApi* | [**create_storage_request**](docs/MarketplaceApi.md#create_storage_request) | **POST** /storage/request/{cid} | Creates a new Request for storage
*MarketplaceApi* | [**get_active_slot_by_id**](docs/MarketplaceApi.md#get_active_slot_by_id) | **GET** /sales/slots/{slotId} | Returns active slot with id {slotId} for the host
*MarketplaceApi* | [**get_active_slots**](docs/MarketplaceApi.md#get_active_slots) | **GET** /sales/slots | Returns active slots
*MarketplaceApi* | [**get_offered_storage**](docs/MarketplaceApi.md#get_offered_storage) | **GET** /sales/availability | Returns storage that is for sale
*MarketplaceApi* | [**get_purchase**](docs/MarketplaceApi.md#get_purchase) | **GET** /storage/purchases/{id} | Returns purchase details
*MarketplaceApi* | [**get_purchases**](docs/MarketplaceApi.md#get_purchases) | **GET** /storage/purchases | Returns list of purchase IDs
*MarketplaceApi* | [**get_reservations**](docs/MarketplaceApi.md#get_reservations) | **PATCH** /sales/availability/{id}/reservations | Get availability's reservations
*MarketplaceApi* | [**offer_storage**](docs/MarketplaceApi.md#offer_storage) | **POST** /sales/availability | Offers storage for sale
*MarketplaceApi* | [**update_offered_storage**](docs/MarketplaceApi.md#update_offered_storage) | **PATCH** /sales/availability/{id} | Updates availability
*NodeApi* | [**connect_peer**](docs/NodeApi.md#connect_peer) | **GET** /connect/{peerId} | Connect to a peer
*NodeApi* | [**get_peer_id**](docs/NodeApi.md#get_peer_id) | **GET** /node/peerid | Get Node's PeerID
*NodeApi* | [**get_spr**](docs/NodeApi.md#get_spr) | **GET** /node/spr | Get Node's SPR
## Documentation For Models
- [Content](docs/Content.md)
- [DataItem](docs/DataItem.md)
- [DataList](docs/DataList.md)
- [DebugInfo](docs/DebugInfo.md)
- [ErasureParameters](docs/ErasureParameters.md)
- [ManifestItem](docs/ManifestItem.md)
- [PeerIdRead](docs/PeerIdRead.md)
- [PoRParameters](docs/PoRParameters.md)
- [Purchase](docs/Purchase.md)
- [Reservation](docs/Reservation.md)
- [SPRRead](docs/SPRRead.md)
- [SalesAvailability](docs/SalesAvailability.md)
- [SalesAvailabilityCREATE](docs/SalesAvailabilityCREATE.md)
- [SalesAvailabilityREAD](docs/SalesAvailabilityREAD.md)
- [Slot](docs/Slot.md)
- [Space](docs/Space.md)
- [StorageAsk](docs/StorageAsk.md)
- [StorageRequest](docs/StorageRequest.md)
- [StorageRequestCreation](docs/StorageRequestCreation.md)
<a id="documentation-for-authorization"></a>
## Documentation For Authorization
Endpoints do not require authorization.
## Author

773
codex.yaml Normal file
View File

@ -0,0 +1,773 @@
openapi: 3.0.3
info:
version: 0.0.1
title: Codex API
description: "List of endpoints and interfaces available to Codex API users"
security:
- { }
components:
schemas:
MultiAddress:
type: string
description: Address of node as specified by the multi-address specification https://multiformats.io/multiaddr/
example: /ip4/127.0.0.1/tcp/8080
PeerId:
type: string
description: Peer Identity reference as specified at https://docs.libp2p.io/concepts/fundamentals/peers/
example: QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N
Id:
type: string
description: 32bits identifier encoded in hex-decimal string.
example: 0x...
BigInt:
type: string
description: Integer represented as decimal string
Cid:
type: string
description: Content Identifier as specified at https://github.com/multiformats/cid
example: QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N
SlotId:
type: string
description: Keccak hash of the abi encoded tuple (RequestId, slot index)
example: 268a781e0db3f7cf36b18e5f4fdb7f586ec9edd08e5500b17c0e518a769f114a
LogLevel:
type: string
description: "One of the log levels: TRACE, DEBUG, INFO, NOTICE, WARN, ERROR or FATAL"
example: DEBUG
EthereumAddress:
type: string
description: Address of Ethereum address
Reward:
type: string
description: The maximum amount of tokens paid per second per slot to hosts the client is willing to pay
Duration:
type: string
description: The duration of the request in seconds as decimal string
ProofProbability:
type: string
description: How often storage proofs are required as decimal string
Expiry:
type: string
description: A timestamp as seconds since unix epoch at which this request expires if the Request does not find requested amount of nodes to host the data.
default: 10 minutes
SPR:
type: string
description: Signed Peer Record (libp2p)
SPRRead:
type: object
properties:
spr:
$ref: "#/components/schemas/SPR"
PeerIdRead:
type: object
properties:
id:
$ref: "#/components/schemas/PeerId"
ErasureParameters:
type: object
properties:
totalChunks:
type: integer
PoRParameters:
description: Parameters for Proof of Retrievability
type: object
properties:
u:
type: string
publicKey:
type: string
name:
type: string
Content:
type: object
description: Parameters specifying the content
properties:
cid:
$ref: "#/components/schemas/Cid"
erasure:
$ref: "#/components/schemas/ErasureParameters"
por:
$ref: "#/components/schemas/PoRParameters"
DebugInfo:
type: object
properties:
id:
$ref: "#/components/schemas/PeerId"
addrs:
type: array
items:
$ref: "#/components/schemas/MultiAddress"
repo:
type: string
description: Path of the data repository where all nodes data are stored
spr:
$ref: "#/components/schemas/SPR"
SalesAvailability:
type: object
properties:
id:
$ref: "#/components/schemas/Id"
totalSize:
type: string
description: Total size of availability's storage in bytes as decimal string
duration:
$ref: "#/components/schemas/Duration"
minPrice:
type: string
description: Minimum price to be paid (in amount of tokens) as decimal string
maxCollateral:
type: string
description: Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string
SalesAvailabilityREAD:
allOf:
- $ref: "#/components/schemas/SalesAvailability"
- type: object
properties:
freeSize:
type: string
description: Unused size of availability's storage in bytes as decimal string
SalesAvailabilityCREATE:
allOf:
- $ref: "#/components/schemas/SalesAvailability"
- required:
- totalSize
- minPrice
- maxCollateral
- duration
Slot:
type: object
properties:
id:
$ref: "#/components/schemas/SlotId"
request:
$ref: "#/components/schemas/StorageRequest"
slotIndex:
type: string
description: Slot Index as hexadecimal string
Reservation:
type: object
properties:
id:
$ref: "#/components/schemas/Id"
availabilityId:
$ref: "#/components/schemas/Id"
size:
$ref: "#/components/schemas/BigInt"
requestId:
$ref: "#/components/schemas/Id"
slotIndex:
type: string
description: Slot Index as hexadecimal string
StorageRequestCreation:
type: object
required:
- reward
- duration
- proofProbability
- collateral
- expiry
properties:
duration:
$ref: "#/components/schemas/Duration"
reward:
$ref: "#/components/schemas/Reward"
proofProbability:
$ref: "#/components/schemas/ProofProbability"
nodes:
description: Minimal number of nodes the content should be stored on
type: integer
default: 1
tolerance:
description: Additional number of nodes on top of the `nodes` property that can be lost before pronouncing the content lost
type: integer
default: 0
collateral:
type: string
description: Number as decimal string that represents how much collateral is asked from hosts that wants to fill a slots
expiry:
type: string
description: Number as decimal string that represents expiry threshold in seconds from when the Request is submitted. When the threshold is reached and the Request does not find requested amount of nodes to host the data, the Request is voided. The number of seconds can not be higher then the Request's duration itself.
StorageAsk:
type: object
required:
- reward
properties:
slots:
description: Number of slots (eq. hosts) that the Request want to have the content spread over
type: integer
slotSize:
type: string
description: Amount of storage per slot (in bytes) as decimal string
duration:
$ref: "#/components/schemas/Duration"
proofProbability:
$ref: "#/components/schemas/ProofProbability"
reward:
$ref: "#/components/schemas/Reward"
maxSlotLoss:
type: integer
description: Max slots that can be lost without data considered to be lost
StorageRequest:
type: object
properties:
id:
type: string
description: Request ID
client:
$ref: "#/components/schemas/EthereumAddress"
ask:
$ref: "#/components/schemas/StorageAsk"
content:
$ref: "#/components/schemas/Content"
expiry:
$ref: "#/components/schemas/Expiry"
nonce:
type: string
description: Random data
Purchase:
type: object
properties:
state:
type: string
description: Description of the Request's state
error:
type: string
description: If Request failed, then here is presented the error message
request:
$ref: "#/components/schemas/StorageRequest"
DataList:
type: object
properties:
content:
type: array
items:
$ref: "#/components/schemas/DataItem"
DataItem:
type: object
properties:
cid:
$ref: "#/components/schemas/Cid"
manifest:
$ref: "#/components/schemas/ManifestItem"
ManifestItem:
type: object
properties:
rootHash:
$ref: "#/components/schemas/Cid"
description: "Root hash of the content"
originalBytes:
type: integer
format: int64
description: "Length of original content in bytes"
blockSize:
type: integer
description: "Size of blocks"
protected:
type: boolean
description: "Indicates if content is protected by erasure-coding"
Space:
type: object
properties:
totalBlocks:
description: "Number of blocks stored by the node"
type: integer
format: int64
quotaMaxBytes:
type: integer
format: int64
description: "Maximum storage space used by the node"
quotaUsedBytes:
type: integer
format: int64
description: "Amount of storage space currently in use"
quotaReservedBytes:
type: integer
format: int64
description: "Amount of storage space reserved"
servers:
- url: "http://localhost:8080/api/codex/v1"
tags:
- name: Marketplace
description: Marketplace information and operations
- name: Data
description: Data operations
- name: Node
description: Node management
- name: Debug
description: Debugging configuration
paths:
"/connect/{peerId}":
get:
summary: "Connect to a peer"
description: |
If `addrs` param is supplied, it will be used to dial the peer, otherwise the `peerId` is used
to invoke peer discovery, if it succeeds the returned addresses will be used to dial.
tags: [ Node ]
operationId: connectPeer
parameters:
- in: path
name: peerId
required: true
schema:
$ref: "#/components/schemas/PeerId"
description: Peer that should be dialed.
- in: query
name: addrs
schema:
type: array
nullable: true
items:
$ref: "#/components/schemas/MultiAddress"
description: |
If supplied, it will be used to dial the peer.
The address has to target the listening address of the peer,
which is specified with the `--listen-addrs` CLI flag.
responses:
"200":
description: Successfully connected to peer
"400":
description: Peer either not found or was not possible to dial
"/data":
get:
summary: "Lists manifest CIDs stored locally in node."
tags: [ Data ]
operationId: listData
responses:
"200":
description: Retrieved list of content CIDs
content:
application/json:
schema:
$ref: "#/components/schemas/DataList"
"400":
description: Invalid CID is specified
"404":
description: Content specified by the CID is not found
"500":
description: Well it was bad-bad
post:
summary: "Upload a file in a streaming manner. Once finished, the file is stored in the node and can be retrieved by any node in the network using the returned CID."
tags: [ Data ]
operationId: upload
requestBody:
content:
application/octet-stream:
schema:
type: string
format: binary
responses:
"200":
description: CID of uploaded file
content:
text/plain:
schema:
type: string
"500":
description: Well it was bad-bad and the upload did not work out
"/data/{cid}":
get:
summary: "Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned."
tags: [ Data ]
operationId: downloadLocal
parameters:
- in: path
name: cid
required: true
schema:
$ref: "#/components/schemas/Cid"
description: File to be downloaded.
responses:
"200":
description: Retrieved content specified by CID
content:
application/octet-stream:
schema:
type: string
format: binary
"400":
description: Invalid CID is specified
"404":
description: Content specified by the CID is unavailable locally
"500":
description: Well it was bad-bad
"/data/{cid}/network":
get:
summary: "Download a file from the network in a streaming manner. If the file is not available locally, it will be retrieved from other nodes in the network if able."
tags: [ Data ]
operationId: downloadNetwork
parameters:
- in: path
name: cid
required: true
schema:
$ref: "#/components/schemas/Cid"
description: "File to be downloaded."
responses:
"200":
description: Retrieved content specified by CID
content:
application/octet-stream:
schema:
type: string
format: binary
"400":
description: Invalid CID is specified
"404":
description: Content specified by the CID is not found
"500":
description: Well it was bad-bad
"/space":
get:
summary: "Gets a summary of the storage space allocation of the node."
tags: [ Data ]
operationId: space
responses:
"200":
description: "Summary of storage allocation"
content:
application/json:
schema:
$ref: "#/components/schemas/Space"
"500":
description: "It's not working as planned"
"/sales/slots":
get:
summary: "Returns active slots"
tags: [ Marketplace ]
operationId: getActiveSlots
responses:
"200":
description: Retrieved active slots
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Slot"
"503":
description: Sales are unavailable
"/sales/slots/{slotId}":
get:
summary: "Returns active slot with id {slotId} for the host"
tags: [ Marketplace ]
operationId: getActiveSlotById
parameters:
- in: path
name: slotId
required: true
schema:
$ref: "#/components/schemas/Cid"
description: File to be downloaded.
responses:
"200":
description: Retrieved active slot
content:
application/json:
schema:
$ref: "#/components/schemas/Slot"
"400":
description: Invalid or missing SlotId
"404":
description: Host is not in an active sale for the slot
"503":
description: Sales are unavailable
"/sales/availability":
get:
summary: "Returns storage that is for sale"
tags: [ Marketplace ]
operationId: getOfferedStorage
responses:
"200":
description: Retrieved storage availabilities of the node
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/SalesAvailability"
"500":
description: Error getting unused availabilities
"503":
description: Sales are unavailable
post:
summary: "Offers storage for sale"
operationId: offerStorage
tags: [ Marketplace ]
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/SalesAvailabilityCREATE"
responses:
"201":
description: Created storage availability
content:
application/json:
schema:
$ref: "#/components/schemas/SalesAvailabilityREAD"
"400":
description: Invalid data input
"422":
description: Not enough node's storage quota available
"500":
description: Error reserving availability
"503":
description: Sales are unavailable
"/sales/availability/{id}":
patch:
summary: "Updates availability"
description: |
The new parameters will be only considered for new requests.
Existing Requests linked to this Availability will continue as is.
operationId: updateOfferedStorage
tags: [ Marketplace ]
parameters:
- in: path
name: id
required: true
schema:
type: string
description: ID of Availability
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/SalesAvailability"
responses:
"204":
description: Availability successfully updated
"400":
description: Invalid data input
"404":
description: Availability not found
"422":
description: Not enough node's storage quota available
"500":
description: Error reserving availability
"503":
description: Sales are unavailable
"/sales/availability/{id}/reservations":
patch:
summary: "Get availability's reservations"
description: Return's list of Reservations for ongoing Storage Requests that the node hosts.
operationId: getReservations
tags: [ Marketplace ]
parameters:
- in: path
name: id
required: true
schema:
type: string
description: ID of Availability
responses:
"200":
description: Retrieved storage availabilities of the node
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Reservation"
"400":
description: Invalid Availability ID
"404":
description: Availability not found
"500":
description: Error getting reservations
"503":
description: Sales are unavailable
"/storage/request/{cid}":
post:
summary: "Creates a new Request for storage"
tags: [ Marketplace ]
operationId: createStorageRequest
parameters:
- in: path
name: cid
required: true
schema:
$ref: "#/components/schemas/Cid"
description: CID of the uploaded data that should be stored
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/StorageRequestCreation"
responses:
"200":
description: Returns the Request ID as decimal string
content:
text/plain:
schema:
type: string
"400":
description: Invalid or missing Request ID
"404":
description: Request ID not found
"503":
description: Purchasing is unavailable
"/storage/purchases":
get:
summary: "Returns list of purchase IDs"
tags: [ Marketplace ]
operationId: getPurchases
responses:
"200":
description: Gets all purchase IDs stored in node
content:
application/json:
schema:
type: array
items:
type: string
"503":
description: Purchasing is unavailable
"/storage/purchases/{id}":
get:
summary: "Returns purchase details"
tags: [ Marketplace ]
operationId: getPurchase
parameters:
- in: path
name: id
required: true
schema:
type: string
description: Hexadecimal ID of a Purchase
responses:
"200":
description: Purchase details
content:
application/json:
schema:
$ref: "#/components/schemas/Purchase"
"400":
description: Invalid or missing Purchase ID
"404":
description: Purchase not found
"503":
description: Purchasing is unavailable
"/node/spr":
get:
summary: "Get Node's SPR"
operationId: getSPR
tags: [ Node ]
responses:
"200":
description: Node's SPR
content:
plain/text:
schema:
$ref: "#/components/schemas/SPR"
application/json:
schema:
$ref: "#/components/schemas/SPRRead"
"503":
description: Node SPR not ready, try again later
"/node/peerid":
get:
summary: "Get Node's PeerID"
operationId: getPeerId
tags: [ Node ]
responses:
"200":
description: Node's Peer ID
content:
plain/text:
schema:
$ref: "#/components/schemas/PeerId"
application/json:
schema:
$ref: "#/components/schemas/PeerIdRead"
"/debug/chronicles/loglevel":
post:
summary: "Set log level at run time"
tags: [ Debug ]
operationId: setDebugLogLevel
parameters:
- in: query
name: level
required: true
schema:
$ref: "#/components/schemas/LogLevel"
responses:
"200":
description: Successfully log level set
"400":
description: Invalid or missing log level
"500":
description: Well it was bad-bad
"/debug/info":
get:
summary: "Gets node information"
operationId: getDebugInfo
tags: [ Debug ]
responses:
"200":
description: Node's information
content:
application/json:
schema:
$ref: "#/components/schemas/DebugInfo"

55
codex_client/__init__.py Normal file
View File

@ -0,0 +1,55 @@
# coding: utf-8
# flake8: noqa
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
__version__ = "1.0.0"
# import apis into sdk package
from codex_client.api.data_api import DataApi
from codex_client.api.debug_api import DebugApi
from codex_client.api.marketplace_api import MarketplaceApi
from codex_client.api.node_api import NodeApi
# import ApiClient
from codex_client.api_response import ApiResponse
from codex_client.api_client import ApiClient
from codex_client.configuration import Configuration
from codex_client.exceptions import OpenApiException
from codex_client.exceptions import ApiTypeError
from codex_client.exceptions import ApiValueError
from codex_client.exceptions import ApiKeyError
from codex_client.exceptions import ApiAttributeError
from codex_client.exceptions import ApiException
# import models into sdk package
from codex_client.models.content import Content
from codex_client.models.data_item import DataItem
from codex_client.models.data_list import DataList
from codex_client.models.debug_info import DebugInfo
from codex_client.models.erasure_parameters import ErasureParameters
from codex_client.models.manifest_item import ManifestItem
from codex_client.models.peer_id_read import PeerIdRead
from codex_client.models.po_r_parameters import PoRParameters
from codex_client.models.purchase import Purchase
from codex_client.models.reservation import Reservation
from codex_client.models.spr_read import SPRRead
from codex_client.models.sales_availability import SalesAvailability
from codex_client.models.sales_availability_create import SalesAvailabilityCREATE
from codex_client.models.sales_availability_read import SalesAvailabilityREAD
from codex_client.models.slot import Slot
from codex_client.models.space import Space
from codex_client.models.storage_ask import StorageAsk
from codex_client.models.storage_request import StorageRequest
from codex_client.models.storage_request_creation import StorageRequestCreation

View File

@ -0,0 +1,8 @@
# flake8: noqa
# import apis into api package
from codex_client.api.data_api import DataApi
from codex_client.api.debug_api import DebugApi
from codex_client.api.marketplace_api import MarketplaceApi
from codex_client.api.node_api import NodeApi

1336
codex_client/api/data_api.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,533 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import warnings
from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Annotated
from pydantic import StrictStr
from codex_client.models.debug_info import DebugInfo
from codex_client.api_client import ApiClient, RequestSerialized
from codex_client.api_response import ApiResponse
from codex_client.rest import RESTResponseType
class DebugApi:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
@validate_call
def get_debug_info(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> DebugInfo:
"""Gets node information
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_debug_info_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "DebugInfo",
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
def get_debug_info_with_http_info(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[DebugInfo]:
"""Gets node information
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_debug_info_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "DebugInfo",
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
def get_debug_info_without_preload_content(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Gets node information
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_debug_info_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "DebugInfo",
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _get_debug_info_serialize(
self,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[str, Union[str, bytes]] = {}
_body_params: Optional[bytes] = None
# process the path parameters
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/debug/info',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)
@validate_call
def set_debug_log_level(
self,
level: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> None:
"""Set log level at run time
:param level: (required)
:type level: str
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._set_debug_log_level_serialize(
level=level,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'400': None,
'500': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
def set_debug_log_level_with_http_info(
self,
level: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[None]:
"""Set log level at run time
:param level: (required)
:type level: str
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._set_debug_log_level_serialize(
level=level,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'400': None,
'500': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
def set_debug_log_level_without_preload_content(
self,
level: StrictStr,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Set log level at run time
:param level: (required)
:type level: str
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._set_debug_log_level_serialize(
level=level,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'400': None,
'500': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _set_debug_log_level_serialize(
self,
level,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[str, Union[str, bytes]] = {}
_body_params: Optional[bytes] = None
# process the path parameters
# process the query parameters
if level is not None:
_query_params.append(('level', level))
# process the header parameters
# process the form parameters
# process the body parameter
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='POST',
resource_path='/debug/chronicles/loglevel',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,795 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import warnings
from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Annotated
from pydantic import Field, StrictStr
from typing import List, Optional
from typing_extensions import Annotated
from codex_client.api_client import ApiClient, RequestSerialized
from codex_client.api_response import ApiResponse
from codex_client.rest import RESTResponseType
class NodeApi:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
@validate_call
def connect_peer(
self,
peer_id: Annotated[StrictStr, Field(description="Peer that should be dialed.")],
addrs: Annotated[Optional[List[StrictStr]], Field(description="If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag. ")] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> None:
"""Connect to a peer
If `addrs` param is supplied, it will be used to dial the peer, otherwise the `peerId` is used to invoke peer discovery, if it succeeds the returned addresses will be used to dial.
:param peer_id: Peer that should be dialed. (required)
:type peer_id: str
:param addrs: If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag.
:type addrs: List[str]
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._connect_peer_serialize(
peer_id=peer_id,
addrs=addrs,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'400': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
def connect_peer_with_http_info(
self,
peer_id: Annotated[StrictStr, Field(description="Peer that should be dialed.")],
addrs: Annotated[Optional[List[StrictStr]], Field(description="If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag. ")] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[None]:
"""Connect to a peer
If `addrs` param is supplied, it will be used to dial the peer, otherwise the `peerId` is used to invoke peer discovery, if it succeeds the returned addresses will be used to dial.
:param peer_id: Peer that should be dialed. (required)
:type peer_id: str
:param addrs: If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag.
:type addrs: List[str]
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._connect_peer_serialize(
peer_id=peer_id,
addrs=addrs,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'400': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
def connect_peer_without_preload_content(
self,
peer_id: Annotated[StrictStr, Field(description="Peer that should be dialed.")],
addrs: Annotated[Optional[List[StrictStr]], Field(description="If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag. ")] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Connect to a peer
If `addrs` param is supplied, it will be used to dial the peer, otherwise the `peerId` is used to invoke peer discovery, if it succeeds the returned addresses will be used to dial.
:param peer_id: Peer that should be dialed. (required)
:type peer_id: str
:param addrs: If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag.
:type addrs: List[str]
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._connect_peer_serialize(
peer_id=peer_id,
addrs=addrs,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'400': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _connect_peer_serialize(
self,
peer_id,
addrs,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
'addrs': 'multi',
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[str, Union[str, bytes]] = {}
_body_params: Optional[bytes] = None
# process the path parameters
if peer_id is not None:
_path_params['peerId'] = peer_id
# process the query parameters
if addrs is not None:
_query_params.append(('addrs', addrs))
# process the header parameters
# process the form parameters
# process the body parameter
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/connect/{peerId}',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)
@validate_call
def get_peer_id(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> str:
"""Get Node's PeerID
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_peer_id_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
def get_peer_id_with_http_info(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[str]:
"""Get Node's PeerID
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_peer_id_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
def get_peer_id_without_preload_content(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Get Node's PeerID
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_peer_id_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _get_peer_id_serialize(
self,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[str, Union[str, bytes]] = {}
_body_params: Optional[bytes] = None
# process the path parameters
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'plain/text',
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/node/peerid',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)
@validate_call
def get_spr(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> str:
"""Get Node's SPR
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_spr_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
'503': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
def get_spr_with_http_info(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[str]:
"""Get Node's SPR
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_spr_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
'503': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
def get_spr_without_preload_content(
self,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""Get Node's SPR
: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.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._get_spr_serialize(
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': "str",
'503': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _get_spr_serialize(
self,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[str, Union[str, bytes]] = {}
_body_params: Optional[bytes] = None
# process the path parameters
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
# set the HTTP header `Accept`
if 'Accept' not in _header_params:
_header_params['Accept'] = self.api_client.select_header_accept(
[
'plain/text',
'application/json'
]
)
# authentication setting
_auth_settings: List[str] = [
]
return self.api_client.param_serialize(
method='GET',
resource_path='/node/spr',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)

788
codex_client/api_client.py Normal file
View File

@ -0,0 +1,788 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import datetime
from dateutil.parser import parse
from enum import Enum
import decimal
import json
import mimetypes
import os
import re
import tempfile
from urllib.parse import quote
from typing import Tuple, Optional, List, Dict, Union
from pydantic import SecretStr
from codex_client.configuration import Configuration
from codex_client.api_response import ApiResponse, T as ApiResponseT
import codex_client.models
from codex_client import rest
from codex_client.exceptions import (
ApiValueError,
ApiException,
BadRequestException,
UnauthorizedException,
ForbiddenException,
NotFoundException,
ServiceException
)
RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
class ApiClient:
"""Generic API client for OpenAPI client library builds.
OpenAPI 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 OpenAPI
templates.
: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, str, int)
NATIVE_TYPES_MAPPING = {
'int': int,
'long': int, # TODO remove as only py3 is supported?
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'decimal': decimal.Decimal,
'object': object,
}
_pool = None
def __init__(
self,
configuration=None,
header_name=None,
header_value=None,
cookie=None
) -> None:
# use default configuration if none is provided
if configuration is None:
configuration = Configuration.get_default()
self.configuration = configuration
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 = 'py_codex_client'
self.client_side_validation = configuration.client_side_validation
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
@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
_default = None
@classmethod
def get_default(cls):
"""Return new instance of ApiClient.
This method returns newly created, based on default constructor,
object of ApiClient class or returns a copy of default
ApiClient.
:return: The ApiClient object.
"""
if cls._default is None:
cls._default = ApiClient()
return cls._default
@classmethod
def set_default(cls, default):
"""Set default instance of ApiClient.
It stores default ApiClient.
:param default: object of ApiClient.
"""
cls._default = default
def param_serialize(
self,
method,
resource_path,
path_params=None,
query_params=None,
header_params=None,
body=None,
post_params=None,
files=None, auth_settings=None,
collection_formats=None,
_host=None,
_request_auth=None
) -> RequestSerialized:
"""Builds the HTTP request params needed by the request.
:param method: Method to call.
:param resource_path: Path to method endpoint.
: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 files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:return: tuple of form (path, http_method, query_params, header_params,
body, post_params, files)
"""
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)
)
# post parameters
if post_params or files:
post_params = post_params if post_params else []
post_params = self.sanitize_for_serialization(post_params)
post_params = self.parameters_to_tuples(
post_params,
collection_formats
)
if files:
post_params.extend(self.files_parameters(files))
# auth setting
self.update_params_for_auth(
header_params,
query_params,
auth_settings,
resource_path,
method,
body,
request_auth=_request_auth
)
# body
if body:
body = self.sanitize_for_serialization(body)
# request url
if _host is None or self.configuration.ignore_operation_servers:
url = self.configuration.host + resource_path
else:
# use server/host defined in path or operation instead
url = _host + resource_path
# query parameters
if query_params:
query_params = self.sanitize_for_serialization(query_params)
url_query = self.parameters_to_url_query(
query_params,
collection_formats
)
url += "?" + url_query
return method, url, header_params, body, post_params
def call_api(
self,
method,
url,
header_params=None,
body=None,
post_params=None,
_request_timeout=None
) -> rest.RESTResponse:
"""Makes the HTTP request (synchronous)
:param method: Method to call.
:param url: Path to method endpoint.
: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 _request_timeout: timeout setting for this request.
:return: RESTResponse
"""
try:
# perform request and return response
response_data = self.rest_client.request(
method, url,
headers=header_params,
body=body, post_params=post_params,
_request_timeout=_request_timeout
)
except ApiException as e:
raise e
return response_data
def response_deserialize(
self,
response_data: rest.RESTResponse,
response_types_map: Optional[Dict[str, ApiResponseT]]=None
) -> ApiResponse[ApiResponseT]:
"""Deserializes response into an object.
:param response_data: RESTResponse object to be deserialized.
:param response_types_map: dict of response types.
:return: ApiResponse
"""
msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
assert response_data.data is not None, msg
response_type = response_types_map.get(str(response_data.status), None)
if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
# if not found, look for '1XX', '2XX', etc.
response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
# deserialize response data
response_text = None
return_data = None
try:
if response_type == "bytearray":
return_data = response_data.data
elif response_type == "file":
return_data = self.__deserialize_file(response_data)
elif response_type is not None:
match = None
content_type = response_data.getheader('content-type')
if content_type is not None:
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
encoding = match.group(1) if match else "utf-8"
response_text = response_data.data.decode(encoding)
return_data = self.deserialize(response_text, response_type, content_type)
finally:
if not 200 <= response_data.status <= 299:
raise ApiException.from_response(
http_resp=response_data,
body=response_text,
data=return_data,
)
return ApiResponse(
status_code = response_data.status,
data = return_data,
headers = response_data.getheaders(),
raw_data = response_data.data
)
def sanitize_for_serialization(self, obj):
"""Builds a JSON POST object.
If obj is None, return None.
If obj is SecretStr, return obj.get_secret_value()
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 decimal.Decimal return string representation.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is OpenAPI 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, Enum):
return obj.value
elif isinstance(obj, SecretStr):
return obj.get_secret_value()
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()
elif isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, dict):
obj_dict = obj
else:
# Convert model obj to dict except
# attributes `openapi_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
obj_dict = obj.to_dict()
else:
obj_dict = obj.__dict__
return {
key: self.sanitize_for_serialization(val)
for key, val in obj_dict.items()
}
def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
"""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.
:param content_type: content type of response.
:return: deserialized object.
"""
# fetch data from response object
if content_type is None:
try:
data = json.loads(response_text)
except ValueError:
data = response_text
elif content_type.startswith("application/json"):
if response_text == "":
data = ""
else:
data = json.loads(response_text)
elif content_type.startswith("text/plain"):
data = response_text
else:
raise ApiException(
status=0,
reason="Unsupported content type: {0}".format(content_type)
)
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 isinstance(klass, str):
if klass.startswith('List['):
m = re.match(r'List\[(.*)]', klass)
assert m is not None, "Malformed List type definition"
sub_kls = m.group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('Dict['):
m = re.match(r'Dict\[([^,]*), (.*)]', klass)
assert m is not None, "Malformed Dict type definition"
sub_kls = m.group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in data.items()}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(codex_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_datetime(data)
elif klass == decimal.Decimal:
return decimal.Decimal(data)
elif issubclass(klass, Enum):
return self.__deserialize_enum(data, klass)
else:
return self.__deserialize_model(data, klass)
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: List[Tuple[str, str]] = []
if collection_formats is None:
collection_formats = {}
for k, v in params.items() if isinstance(params, dict) else params:
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 parameters_to_url_query(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: URL query string (e.g. a=Hello%20World&b=123)
"""
new_params: List[Tuple[str, str]] = []
if collection_formats is None:
collection_formats = {}
for k, v in params.items() if isinstance(params, dict) else params:
if isinstance(v, bool):
v = str(v).lower()
if isinstance(v, (int, float)):
v = str(v)
if isinstance(v, dict):
v = json.dumps(v)
if k in collection_formats:
collection_format = collection_formats[k]
if collection_format == 'multi':
new_params.extend((k, str(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(quote(str(value)) for value in v))
)
else:
new_params.append((k, quote(str(v))))
return "&".join(["=".join(map(str, item)) for item in new_params])
def files_parameters(self, files: Dict[str, Union[str, bytes]]):
"""Builds form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = []
for k, v in files.items():
if isinstance(v, str):
with open(v, 'rb') as f:
filename = os.path.basename(f.name)
filedata = f.read()
elif isinstance(v, bytes):
filename = k
filedata = v
else:
raise ValueError("Unsupported file value")
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: List[str]) -> Optional[str]:
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
:return: Accept (e.g. application/json).
"""
if not accepts:
return None
for accept in accepts:
if re.search('json', accept, re.IGNORECASE):
return accept
return accepts[0]
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 None
for content_type in content_types:
if re.search('json', content_type, re.IGNORECASE):
return content_type
return content_types[0]
def update_params_for_auth(
self,
headers,
queries,
auth_settings,
resource_path,
method,
body,
request_auth=None
) -> None:
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param queries: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
:resource_path: A string representation of the HTTP request resource path.
:method: A string representation of the HTTP request method.
:body: A object representing the body of the HTTP request.
The object type is the return value of sanitize_for_serialization().
:param request_auth: if set, the provided settings will
override the token in the configuration.
"""
if not auth_settings:
return
if request_auth:
self._apply_auth_params(
headers,
queries,
resource_path,
method,
body,
request_auth
)
else:
for auth in auth_settings:
auth_setting = self.configuration.auth_settings().get(auth)
if auth_setting:
self._apply_auth_params(
headers,
queries,
resource_path,
method,
body,
auth_setting
)
def _apply_auth_params(
self,
headers,
queries,
resource_path,
method,
body,
auth_setting
) -> None:
"""Updates the request parameters based on a single auth_setting
:param headers: Header parameters dict to be updated.
:param queries: Query parameters tuple list to be updated.
:resource_path: A string representation of the HTTP request resource path.
:method: A string representation of the HTTP request method.
:body: A object representing the body of the HTTP request.
The object type is the return value of sanitize_for_serialization().
:param auth_setting: auth settings for the endpoint
"""
if auth_setting['in'] == 'cookie':
headers['Cookie'] = auth_setting['value']
elif auth_setting['in'] == 'header':
if auth_setting['type'] != 'http-signature':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
queries.append((auth_setting['key'], auth_setting['value']))
else:
raise ApiValueError(
'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.
handle file downloading
save response body into a tmp file and return the instance
: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:
m = re.search(
r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition
)
assert m is not None, "Unexpected 'content-disposition' header value"
filename = m.group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") 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 str(data)
except TypeError:
return data
def __deserialize_object(self, value):
"""Return an original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
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_datetime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
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 __deserialize_enum(self, data, klass):
"""Deserializes primitive type to enum.
:param data: primitive type.
:param klass: class literal.
:return: enum value.
"""
try:
return klass(data)
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as `{1}`"
.format(data, klass)
)
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal.
:return: model object.
"""
return klass.from_dict(data)

View File

@ -0,0 +1,21 @@
"""API response object."""
from __future__ import annotations
from typing import Optional, Generic, Mapping, TypeVar
from pydantic import Field, StrictInt, StrictBytes, BaseModel
T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]):
"""
API response object
"""
status_code: StrictInt = Field(description="HTTP status code")
headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
data: T = Field(description="Deserialized data given the data type")
raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
model_config = {
"arbitrary_types_allowed": True
}

View File

@ -0,0 +1,450 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import copy
import logging
from logging import FileHandler
import multiprocessing
import sys
from typing import Optional
import urllib3
import http.client as httplib
JSON_SCHEMA_VALIDATION_KEYWORDS = {
'multipleOf', 'maximum', 'exclusiveMaximum',
'minimum', 'exclusiveMinimum', 'maxLength',
'minLength', 'pattern', 'maxItems', 'minItems'
}
class Configuration:
"""This class contains various settings of the API client.
:param host: Base url.
:param ignore_operation_servers
Boolean to ignore operation servers for the API client.
Config will use `host` as the base url regardless of the operation servers.
:param api_key: Dict to store API key(s).
Each entry in the dict specifies an API key.
The dict key is the name of the security scheme in the OAS specification.
The dict value is the API key secret.
:param api_key_prefix: Dict to store API prefix (e.g. Bearer).
The dict key is the name of the security scheme in the OAS specification.
The dict value is an API key prefix when generating the auth data.
:param username: Username for HTTP basic authentication.
:param password: Password for HTTP basic authentication.
:param access_token: Access token.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum
values before.
:param ssl_ca_cert: str - the path to a file of concatenated CA certificates
in PEM format.
:param retries: Number of retries for API requests.
"""
_default = None
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
access_token=None,
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
ignore_operation_servers=False,
ssl_ca_cert=None,
retries=None,
*,
debug: Optional[bool] = None
) -> None:
"""Constructor
"""
self._base_path = "http://localhost:8080/api/codex/v1" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.ignore_operation_servers = ignore_operation_servers
"""Ignore operation servers
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
# Authentication Settings
self.api_key = {}
if api_key:
self.api_key = api_key
"""dict to store API key(s)
"""
self.api_key_prefix = {}
if api_key_prefix:
self.api_key_prefix = api_key_prefix
"""dict to store API prefix (e.g. Bearer)
"""
self.refresh_api_key_hook = None
"""function hook to refresh API key if expired
"""
self.username = username
"""Username for HTTP basic authentication
"""
self.password = password
"""Password for HTTP basic authentication
"""
self.access_token = access_token
"""Access token
"""
self.logger = {}
"""Logging Settings
"""
self.logger["package_logger"] = logging.getLogger("codex_client")
self.logger["urllib3_logger"] = logging.getLogger("urllib3")
self.logger_format = '%(asctime)s %(levelname)s %(message)s'
"""Log format
"""
self.logger_stream_handler = None
"""Log stream handler
"""
self.logger_file_handler: Optional[FileHandler] = None
"""Log file handler
"""
self.logger_file = None
"""Debug file location
"""
if debug is not None:
self.debug = debug
else:
self.__debug = False
"""Debug switch
"""
self.verify_ssl = True
"""SSL/TLS verification
Set this to false to skip verifying SSL certificate when calling API
from https server.
"""
self.ssl_ca_cert = ssl_ca_cert
"""Set this to customize the certificate file to verify the peer.
"""
self.cert_file = None
"""client certificate file
"""
self.key_file = None
"""client key file
"""
self.assert_hostname = None
"""Set this to True/False to enable/disable SSL hostname verification.
"""
self.tls_server_name = None
"""SSL/TLS Server Name Indication (SNI)
Set this to the SNI value expected by the server.
"""
self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
"""urllib3 connection pool's maximum number of connections saved
per pool. urllib3 uses 1 connection as default value, but this is
not the best value when you are making a lot of possibly parallel
requests to the same host, which is often the case here.
cpu_count * 5 is used as default value to increase performance.
"""
self.proxy: Optional[str] = None
"""Proxy URL
"""
self.proxy_headers = None
"""Proxy headers
"""
self.safe_chars_for_path_param = ''
"""Safe chars for path_param
"""
self.retries = retries
"""Adding retries to override urllib3 default value 3
"""
# Enable client side validation
self.client_side_validation = True
self.socket_options = None
"""Options to pass down to the underlying urllib3 socket
"""
self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
"""datetime format
"""
self.date_format = "%Y-%m-%d"
"""date format
"""
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k not in ('logger', 'logger_file_handler'):
setattr(result, k, copy.deepcopy(v, memo))
# shallow copy of loggers
result.logger = copy.copy(self.logger)
# use setters to configure loggers
result.logger_file = self.logger_file
result.debug = self.debug
return result
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
@classmethod
def set_default(cls, default):
"""Set default instance of configuration.
It stores default configuration, which can be
returned by get_default_copy method.
:param default: object of Configuration
"""
cls._default = default
@classmethod
def get_default_copy(cls):
"""Deprecated. Please use `get_default` instead.
Deprecated. Please use `get_default` instead.
:return: The configuration object.
"""
return cls.get_default()
@classmethod
def get_default(cls):
"""Return the default configuration.
This method returns newly created, based on default constructor,
object of Configuration class or returns a copy of default
configuration.
:return: The configuration object.
"""
if cls._default is None:
cls._default = Configuration()
return cls._default
@property
def logger_file(self):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
return self.__logger_file
@logger_file.setter
def logger_file(self, value):
"""The logger file.
If the logger_file is None, then add stream handler and remove file
handler. Otherwise, add file handler and remove stream handler.
:param value: The logger_file path.
:type: str
"""
self.__logger_file = value
if self.__logger_file:
# If set logging file,
# then add file handler and remove stream handler.
self.logger_file_handler = logging.FileHandler(self.__logger_file)
self.logger_file_handler.setFormatter(self.logger_formatter)
for _, logger in self.logger.items():
logger.addHandler(self.logger_file_handler)
@property
def debug(self):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
return self.__debug
@debug.setter
def debug(self, value):
"""Debug status
:param value: The debug status, True or False.
:type: bool
"""
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
for _, logger in self.logger.items():
logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
for _, logger in self.logger.items():
logger.setLevel(logging.WARNING)
# turn off httplib debug
httplib.HTTPConnection.debuglevel = 0
@property
def logger_format(self):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
return self.__logger_format
@logger_format.setter
def logger_format(self, value):
"""The logger format.
The logger_formatter will be updated when sets logger_format.
:param value: The format string.
:type: str
"""
self.__logger_format = value
self.logger_formatter = logging.Formatter(self.__logger_format)
def get_api_key_with_prefix(self, identifier, alias=None):
"""Gets API key (with prefix if set).
:param identifier: The identifier of apiKey.
:param alias: The alternative identifier of apiKey.
:return: The token for api key authentication.
"""
if self.refresh_api_key_hook is not None:
self.refresh_api_key_hook(self)
key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
if key:
prefix = self.api_key_prefix.get(identifier)
if prefix:
return "%s %s" % (prefix, key)
else:
return key
def get_basic_auth_token(self):
"""Gets HTTP basic authentication header (string).
:return: The token for basic HTTP authentication.
"""
username = ""
if self.username is not None:
username = self.username
password = ""
if self.password is not None:
password = self.password
return urllib3.util.make_headers(
basic_auth=username + ':' + password
).get('authorization')
def auth_settings(self):
"""Gets Auth Settings dict for api client.
:return: The Auth Settings information dict.
"""
auth = {}
return auth
def to_debug_report(self):
"""Gets the essential information for debugging.
:return: The report for debugging.
"""
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 0.0.1\n"\
"SDK Package Version: 1.0.0".\
format(env=sys.platform, pyversion=sys.version)
def get_host_settings(self):
"""Gets an array of host settings
:return: An array of host settings
"""
return [
{
'url': "http://localhost:8080/api/codex/v1",
'description': "No description provided",
}
]
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path
variables = {} if variables is None else variables
servers = self.get_host_settings() if servers is None else servers
try:
server = servers[index]
except IndexError:
raise ValueError(
"Invalid index {0} when selecting the host settings. "
"Must be less than {1}".format(index, len(servers)))
url = server['url']
# go through variables and replace placeholders
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])
if 'enum_values' in variable \
and used_value not in variable['enum_values']:
raise ValueError(
"The variable `{0}` in the host URL has invalid value "
"{1}. Must be {2}.".format(
variable_name, variables[variable_name],
variable['enum_values']))
url = url.replace("{" + variable_name + "}", used_value)
return url
@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)
@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None

199
codex_client/exceptions.py Normal file
View File

@ -0,0 +1,199 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from typing import Any, Optional
from typing_extensions import Self
class OpenApiException(Exception):
"""The base exception class for all OpenAPIExceptions"""
class ApiTypeError(OpenApiException, TypeError):
def __init__(self, msg, path_to_item=None, valid_classes=None,
key_type=None) -> None:
""" Raises an exception for TypeErrors
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list): a list of keys an indices to get to the
current_item
None if unset
valid_classes (tuple): the primitive classes that current item
should be an instance of
None if unset
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
None if unset
"""
self.path_to_item = path_to_item
self.valid_classes = valid_classes
self.key_type = key_type
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiTypeError, self).__init__(full_msg)
class ApiValueError(OpenApiException, ValueError):
def __init__(self, msg, path_to_item=None) -> None:
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (list) the path to the exception in the
received_data dict. None if unset
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiValueError, self).__init__(full_msg)
class ApiAttributeError(OpenApiException, AttributeError):
def __init__(self, msg, path_to_item=None) -> None:
"""
Raised when an attribute reference or assignment fails.
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiAttributeError, self).__init__(full_msg)
class ApiKeyError(OpenApiException, KeyError):
def __init__(self, msg, path_to_item=None) -> None:
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_item = path_to_item
full_msg = msg
if path_to_item:
full_msg = "{0} at {1}".format(msg, render_path(path_to_item))
super(ApiKeyError, self).__init__(full_msg)
class ApiException(OpenApiException):
def __init__(
self,
status=None,
reason=None,
http_resp=None,
*,
body: Optional[str] = None,
data: Optional[Any] = None,
) -> None:
self.status = status
self.reason = reason
self.body = body
self.data = data
self.headers = None
if http_resp:
if self.status is None:
self.status = http_resp.status
if self.reason is None:
self.reason = http_resp.reason
if self.body is None:
try:
self.body = http_resp.data.decode('utf-8')
except Exception:
pass
self.headers = http_resp.getheaders()
@classmethod
def from_response(
cls,
*,
http_resp,
body: Optional[str],
data: Optional[Any],
) -> Self:
if http_resp.status == 400:
raise BadRequestException(http_resp=http_resp, body=body, data=data)
if http_resp.status == 401:
raise UnauthorizedException(http_resp=http_resp, body=body, data=data)
if http_resp.status == 403:
raise ForbiddenException(http_resp=http_resp, body=body, data=data)
if http_resp.status == 404:
raise NotFoundException(http_resp=http_resp, body=body, data=data)
if 500 <= http_resp.status <= 599:
raise ServiceException(http_resp=http_resp, body=body, data=data)
raise ApiException(http_resp=http_resp, body=body, data=data)
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.data or self.body:
error_message += "HTTP response body: {0}\n".format(self.data or self.body)
return error_message
class BadRequestException(ApiException):
pass
class NotFoundException(ApiException):
pass
class UnauthorizedException(ApiException):
pass
class ForbiddenException(ApiException):
pass
class ServiceException(ApiException):
pass
def render_path(path_to_item):
"""Returns a string representation of a path"""
result = ""
for pth in path_to_item:
if isinstance(pth, int):
result += "[{0}]".format(pth)
else:
result += "['{0}']".format(pth)
return result

View File

@ -0,0 +1,35 @@
# coding: utf-8
# flake8: noqa
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
# import models into model package
from codex_client.models.content import Content
from codex_client.models.data_item import DataItem
from codex_client.models.data_list import DataList
from codex_client.models.debug_info import DebugInfo
from codex_client.models.erasure_parameters import ErasureParameters
from codex_client.models.manifest_item import ManifestItem
from codex_client.models.peer_id_read import PeerIdRead
from codex_client.models.po_r_parameters import PoRParameters
from codex_client.models.purchase import Purchase
from codex_client.models.reservation import Reservation
from codex_client.models.spr_read import SPRRead
from codex_client.models.sales_availability import SalesAvailability
from codex_client.models.sales_availability_create import SalesAvailabilityCREATE
from codex_client.models.sales_availability_read import SalesAvailabilityREAD
from codex_client.models.slot import Slot
from codex_client.models.space import Space
from codex_client.models.storage_ask import StorageAsk
from codex_client.models.storage_request import StorageRequest
from codex_client.models.storage_request_creation import StorageRequestCreation

View File

@ -0,0 +1,99 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from codex_client.models.erasure_parameters import ErasureParameters
from codex_client.models.po_r_parameters import PoRParameters
from typing import Optional, Set
from typing_extensions import Self
class Content(BaseModel):
"""
Parameters specifying the content
""" # noqa: E501
cid: Optional[StrictStr] = Field(default=None, description="Content Identifier as specified at https://github.com/multiformats/cid")
erasure: Optional[ErasureParameters] = None
por: Optional[PoRParameters] = None
__properties: ClassVar[List[str]] = ["cid", "erasure", "por"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Content from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of erasure
if self.erasure:
_dict['erasure'] = self.erasure.to_dict()
# override the default output from pydantic by calling `to_dict()` of por
if self.por:
_dict['por'] = self.por.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Content from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"cid": obj.get("cid"),
"erasure": ErasureParameters.from_dict(obj["erasure"]) if obj.get("erasure") is not None else None,
"por": PoRParameters.from_dict(obj["por"]) if obj.get("por") is not None else None
})
return _obj

View File

@ -0,0 +1,93 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from codex_client.models.manifest_item import ManifestItem
from typing import Optional, Set
from typing_extensions import Self
class DataItem(BaseModel):
"""
DataItem
""" # noqa: E501
cid: Optional[StrictStr] = Field(default=None, description="Content Identifier as specified at https://github.com/multiformats/cid")
manifest: Optional[ManifestItem] = None
__properties: ClassVar[List[str]] = ["cid", "manifest"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DataItem from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of manifest
if self.manifest:
_dict['manifest'] = self.manifest.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DataItem from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"cid": obj.get("cid"),
"manifest": ManifestItem.from_dict(obj["manifest"]) if obj.get("manifest") is not None else None
})
return _obj

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from codex_client.models.data_item import DataItem
from typing import Optional, Set
from typing_extensions import Self
class DataList(BaseModel):
"""
DataList
""" # noqa: E501
content: Optional[List[DataItem]] = None
__properties: ClassVar[List[str]] = ["content"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DataList from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in content (list)
_items = []
if self.content:
for _item_content in self.content:
if _item_content:
_items.append(_item_content.to_dict())
_dict['content'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DataList from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"content": [DataItem.from_dict(_item) for _item in obj["content"]] if obj.get("content") is not None else None
})
return _obj

View File

@ -0,0 +1,93 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class DebugInfo(BaseModel):
"""
DebugInfo
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="Peer Identity reference as specified at https://docs.libp2p.io/concepts/fundamentals/peers/")
addrs: Optional[List[StrictStr]] = None
repo: Optional[StrictStr] = Field(default=None, description="Path of the data repository where all nodes data are stored")
spr: Optional[StrictStr] = Field(default=None, description="Signed Peer Record (libp2p)")
__properties: ClassVar[List[str]] = ["id", "addrs", "repo", "spr"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of DebugInfo from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of DebugInfo from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"addrs": obj.get("addrs"),
"repo": obj.get("repo"),
"spr": obj.get("spr")
})
return _obj

View File

@ -0,0 +1,87 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class ErasureParameters(BaseModel):
"""
ErasureParameters
""" # noqa: E501
total_chunks: Optional[StrictInt] = Field(default=None, alias="totalChunks")
__properties: ClassVar[List[str]] = ["totalChunks"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ErasureParameters from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ErasureParameters from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"totalChunks": obj.get("totalChunks")
})
return _obj

View File

@ -0,0 +1,93 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class ManifestItem(BaseModel):
"""
ManifestItem
""" # noqa: E501
root_hash: Optional[StrictStr] = Field(default=None, description="Content Identifier as specified at https://github.com/multiformats/cid", alias="rootHash")
original_bytes: Optional[StrictInt] = Field(default=None, description="Length of original content in bytes", alias="originalBytes")
block_size: Optional[StrictInt] = Field(default=None, description="Size of blocks", alias="blockSize")
protected: Optional[StrictBool] = Field(default=None, description="Indicates if content is protected by erasure-coding")
__properties: ClassVar[List[str]] = ["rootHash", "originalBytes", "blockSize", "protected"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ManifestItem from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ManifestItem from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"rootHash": obj.get("rootHash"),
"originalBytes": obj.get("originalBytes"),
"blockSize": obj.get("blockSize"),
"protected": obj.get("protected")
})
return _obj

View File

@ -0,0 +1,87 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class PeerIdRead(BaseModel):
"""
PeerIdRead
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="Peer Identity reference as specified at https://docs.libp2p.io/concepts/fundamentals/peers/")
__properties: ClassVar[List[str]] = ["id"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of PeerIdRead from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of PeerIdRead from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id")
})
return _obj

View File

@ -0,0 +1,91 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class PoRParameters(BaseModel):
"""
Parameters for Proof of Retrievability
""" # noqa: E501
u: Optional[StrictStr] = None
public_key: Optional[StrictStr] = Field(default=None, alias="publicKey")
name: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["u", "publicKey", "name"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of PoRParameters from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of PoRParameters from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"u": obj.get("u"),
"publicKey": obj.get("publicKey"),
"name": obj.get("name")
})
return _obj

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from codex_client.models.storage_request import StorageRequest
from typing import Optional, Set
from typing_extensions import Self
class Purchase(BaseModel):
"""
Purchase
""" # noqa: E501
state: Optional[StrictStr] = Field(default=None, description="Description of the Request's state")
error: Optional[StrictStr] = Field(default=None, description="If Request failed, then here is presented the error message")
request: Optional[StorageRequest] = None
__properties: ClassVar[List[str]] = ["state", "error", "request"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Purchase from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of request
if self.request:
_dict['request'] = self.request.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Purchase from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"state": obj.get("state"),
"error": obj.get("error"),
"request": StorageRequest.from_dict(obj["request"]) if obj.get("request") is not None else None
})
return _obj

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class Reservation(BaseModel):
"""
Reservation
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="32bits identifier encoded in hex-decimal string.")
availability_id: Optional[StrictStr] = Field(default=None, description="32bits identifier encoded in hex-decimal string.", alias="availabilityId")
size: Optional[StrictStr] = Field(default=None, description="Integer represented as decimal string")
request_id: Optional[StrictStr] = Field(default=None, description="32bits identifier encoded in hex-decimal string.", alias="requestId")
slot_index: Optional[StrictStr] = Field(default=None, description="Slot Index as hexadecimal string", alias="slotIndex")
__properties: ClassVar[List[str]] = ["id", "availabilityId", "size", "requestId", "slotIndex"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Reservation from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Reservation from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"availabilityId": obj.get("availabilityId"),
"size": obj.get("size"),
"requestId": obj.get("requestId"),
"slotIndex": obj.get("slotIndex")
})
return _obj

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class SalesAvailability(BaseModel):
"""
SalesAvailability
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="32bits identifier encoded in hex-decimal string.")
total_size: Optional[StrictStr] = Field(default=None, description="Total size of availability's storage in bytes as decimal string", alias="totalSize")
duration: Optional[StrictStr] = Field(default=None, description="The duration of the request in seconds as decimal string")
min_price: Optional[StrictStr] = Field(default=None, description="Minimum price to be paid (in amount of tokens) as decimal string", alias="minPrice")
max_collateral: Optional[StrictStr] = Field(default=None, description="Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string", alias="maxCollateral")
__properties: ClassVar[List[str]] = ["id", "totalSize", "duration", "minPrice", "maxCollateral"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of SalesAvailability from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of SalesAvailability from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"totalSize": obj.get("totalSize"),
"duration": obj.get("duration"),
"minPrice": obj.get("minPrice"),
"maxCollateral": obj.get("maxCollateral")
})
return _obj

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class SalesAvailabilityCREATE(BaseModel):
"""
SalesAvailabilityCREATE
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="32bits identifier encoded in hex-decimal string.")
total_size: StrictStr = Field(description="Total size of availability's storage in bytes as decimal string", alias="totalSize")
duration: StrictStr = Field(description="The duration of the request in seconds as decimal string")
min_price: StrictStr = Field(description="Minimum price to be paid (in amount of tokens) as decimal string", alias="minPrice")
max_collateral: StrictStr = Field(description="Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string", alias="maxCollateral")
__properties: ClassVar[List[str]] = ["id", "totalSize", "duration", "minPrice", "maxCollateral"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of SalesAvailabilityCREATE from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of SalesAvailabilityCREATE from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"totalSize": obj.get("totalSize"),
"duration": obj.get("duration"),
"minPrice": obj.get("minPrice"),
"maxCollateral": obj.get("maxCollateral")
})
return _obj

View File

@ -0,0 +1,97 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class SalesAvailabilityREAD(BaseModel):
"""
SalesAvailabilityREAD
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="32bits identifier encoded in hex-decimal string.")
total_size: Optional[StrictStr] = Field(default=None, description="Total size of availability's storage in bytes as decimal string", alias="totalSize")
duration: Optional[StrictStr] = Field(default=None, description="The duration of the request in seconds as decimal string")
min_price: Optional[StrictStr] = Field(default=None, description="Minimum price to be paid (in amount of tokens) as decimal string", alias="minPrice")
max_collateral: Optional[StrictStr] = Field(default=None, description="Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string", alias="maxCollateral")
free_size: Optional[StrictStr] = Field(default=None, description="Unused size of availability's storage in bytes as decimal string", alias="freeSize")
__properties: ClassVar[List[str]] = ["id", "totalSize", "duration", "minPrice", "maxCollateral", "freeSize"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of SalesAvailabilityREAD from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of SalesAvailabilityREAD from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"totalSize": obj.get("totalSize"),
"duration": obj.get("duration"),
"minPrice": obj.get("minPrice"),
"maxCollateral": obj.get("maxCollateral"),
"freeSize": obj.get("freeSize")
})
return _obj

View File

@ -0,0 +1,95 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from codex_client.models.storage_request import StorageRequest
from typing import Optional, Set
from typing_extensions import Self
class Slot(BaseModel):
"""
Slot
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="Keccak hash of the abi encoded tuple (RequestId, slot index)")
request: Optional[StorageRequest] = None
slot_index: Optional[StrictStr] = Field(default=None, description="Slot Index as hexadecimal string", alias="slotIndex")
__properties: ClassVar[List[str]] = ["id", "request", "slotIndex"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Slot from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of request
if self.request:
_dict['request'] = self.request.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Slot from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"request": StorageRequest.from_dict(obj["request"]) if obj.get("request") is not None else None,
"slotIndex": obj.get("slotIndex")
})
return _obj

View File

@ -0,0 +1,93 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class Space(BaseModel):
"""
Space
""" # noqa: E501
total_blocks: Optional[StrictInt] = Field(default=None, description="Number of blocks stored by the node", alias="totalBlocks")
quota_max_bytes: Optional[StrictInt] = Field(default=None, description="Maximum storage space used by the node", alias="quotaMaxBytes")
quota_used_bytes: Optional[StrictInt] = Field(default=None, description="Amount of storage space currently in use", alias="quotaUsedBytes")
quota_reserved_bytes: Optional[StrictInt] = Field(default=None, description="Amount of storage space reserved", alias="quotaReservedBytes")
__properties: ClassVar[List[str]] = ["totalBlocks", "quotaMaxBytes", "quotaUsedBytes", "quotaReservedBytes"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Space from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Space from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"totalBlocks": obj.get("totalBlocks"),
"quotaMaxBytes": obj.get("quotaMaxBytes"),
"quotaUsedBytes": obj.get("quotaUsedBytes"),
"quotaReservedBytes": obj.get("quotaReservedBytes")
})
return _obj

View File

@ -0,0 +1,87 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class SPRRead(BaseModel):
"""
SPRRead
""" # noqa: E501
spr: Optional[StrictStr] = Field(default=None, description="Signed Peer Record (libp2p)")
__properties: ClassVar[List[str]] = ["spr"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of SPRRead from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of SPRRead from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"spr": obj.get("spr")
})
return _obj

View File

@ -0,0 +1,97 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class StorageAsk(BaseModel):
"""
StorageAsk
""" # noqa: E501
slots: Optional[StrictInt] = Field(default=None, description="Number of slots (eq. hosts) that the Request want to have the content spread over")
slot_size: Optional[StrictStr] = Field(default=None, description="Amount of storage per slot (in bytes) as decimal string", alias="slotSize")
duration: Optional[StrictStr] = Field(default=None, description="The duration of the request in seconds as decimal string")
proof_probability: Optional[StrictStr] = Field(default=None, description="How often storage proofs are required as decimal string", alias="proofProbability")
reward: StrictStr = Field(description="The maximum amount of tokens paid per second per slot to hosts the client is willing to pay")
max_slot_loss: Optional[StrictInt] = Field(default=None, description="Max slots that can be lost without data considered to be lost", alias="maxSlotLoss")
__properties: ClassVar[List[str]] = ["slots", "slotSize", "duration", "proofProbability", "reward", "maxSlotLoss"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of StorageAsk from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of StorageAsk from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"slots": obj.get("slots"),
"slotSize": obj.get("slotSize"),
"duration": obj.get("duration"),
"proofProbability": obj.get("proofProbability"),
"reward": obj.get("reward"),
"maxSlotLoss": obj.get("maxSlotLoss")
})
return _obj

View File

@ -0,0 +1,105 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from codex_client.models.content import Content
from codex_client.models.storage_ask import StorageAsk
from typing import Optional, Set
from typing_extensions import Self
class StorageRequest(BaseModel):
"""
StorageRequest
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="Request ID")
client: Optional[StrictStr] = Field(default=None, description="Address of Ethereum address")
ask: Optional[StorageAsk] = None
content: Optional[Content] = None
expiry: Optional[StrictStr] = Field(default='10 minutes', description="A timestamp as seconds since unix epoch at which this request expires if the Request does not find requested amount of nodes to host the data.")
nonce: Optional[StrictStr] = Field(default=None, description="Random data")
__properties: ClassVar[List[str]] = ["id", "client", "ask", "content", "expiry", "nonce"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of StorageRequest from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of ask
if self.ask:
_dict['ask'] = self.ask.to_dict()
# override the default output from pydantic by calling `to_dict()` of content
if self.content:
_dict['content'] = self.content.to_dict()
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of StorageRequest from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"client": obj.get("client"),
"ask": StorageAsk.from_dict(obj["ask"]) if obj.get("ask") is not None else None,
"content": Content.from_dict(obj["content"]) if obj.get("content") is not None else None,
"expiry": obj.get("expiry") if obj.get("expiry") is not None else '10 minutes',
"nonce": obj.get("nonce")
})
return _obj

View File

@ -0,0 +1,99 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class StorageRequestCreation(BaseModel):
"""
StorageRequestCreation
""" # noqa: E501
duration: StrictStr = Field(description="The duration of the request in seconds as decimal string")
reward: StrictStr = Field(description="The maximum amount of tokens paid per second per slot to hosts the client is willing to pay")
proof_probability: StrictStr = Field(description="How often storage proofs are required as decimal string", alias="proofProbability")
nodes: Optional[StrictInt] = Field(default=1, description="Minimal number of nodes the content should be stored on")
tolerance: Optional[StrictInt] = Field(default=0, description="Additional number of nodes on top of the `nodes` property that can be lost before pronouncing the content lost")
collateral: StrictStr = Field(description="Number as decimal string that represents how much collateral is asked from hosts that wants to fill a slots")
expiry: StrictStr = Field(description="Number as decimal string that represents expiry threshold in seconds from when the Request is submitted. When the threshold is reached and the Request does not find requested amount of nodes to host the data, the Request is voided. The number of seconds can not be higher then the Request's duration itself.")
__properties: ClassVar[List[str]] = ["duration", "reward", "proofProbability", "nodes", "tolerance", "collateral", "expiry"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of StorageRequestCreation from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of StorageRequestCreation from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"duration": obj.get("duration"),
"reward": obj.get("reward"),
"proofProbability": obj.get("proofProbability"),
"nodes": obj.get("nodes") if obj.get("nodes") is not None else 1,
"tolerance": obj.get("tolerance") if obj.get("tolerance") is not None else 0,
"collateral": obj.get("collateral"),
"expiry": obj.get("expiry")
})
return _obj

0
codex_client/py.typed Normal file
View File

257
codex_client/rest.py Normal file
View File

@ -0,0 +1,257 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import io
import json
import re
import ssl
import urllib3
from codex_client.exceptions import ApiException, ApiValueError
SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"}
RESTResponseType = urllib3.HTTPResponse
def is_socks_proxy_url(url):
if url is None:
return False
split_section = url.split("://")
if len(split_section) < 2:
return False
else:
return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES
class RESTResponse(io.IOBase):
def __init__(self, resp) -> None:
self.response = resp
self.status = resp.status
self.reason = resp.reason
self.data = None
def read(self):
if self.data is None:
self.data = self.response.data
return self.data
def getheaders(self):
"""Returns a dictionary of the response headers."""
return self.response.headers
def getheader(self, name, default=None):
"""Returns a given response header."""
return self.response.headers.get(name, default)
class RESTClientObject:
def __init__(self, configuration) -> 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
# 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
pool_args = {
"cert_reqs": cert_reqs,
"ca_certs": configuration.ssl_ca_cert,
"cert_file": configuration.cert_file,
"key_file": configuration.key_file,
}
if configuration.assert_hostname is not None:
pool_args['assert_hostname'] = (
configuration.assert_hostname
)
if configuration.retries is not None:
pool_args['retries'] = configuration.retries
if configuration.tls_server_name:
pool_args['server_hostname'] = configuration.tls_server_name
if configuration.socket_options is not None:
pool_args['socket_options'] = configuration.socket_options
if configuration.connection_pool_maxsize is not None:
pool_args['maxsize'] = configuration.connection_pool_maxsize
# https pool manager
self.pool_manager: urllib3.PoolManager
if configuration.proxy:
if is_socks_proxy_url(configuration.proxy):
from urllib3.contrib.socks import SOCKSProxyManager
pool_args["proxy_url"] = configuration.proxy
pool_args["headers"] = configuration.proxy_headers
self.pool_manager = SOCKSProxyManager(**pool_args)
else:
pool_args["proxy_url"] = configuration.proxy
pool_args["proxy_headers"] = configuration.proxy_headers
self.pool_manager = urllib3.ProxyManager(**pool_args)
else:
self.pool_manager = urllib3.PoolManager(**pool_args)
def request(
self,
method,
url,
headers=None,
body=None,
post_params=None,
_request_timeout=None
):
"""Perform requests.
:param method: http request method
:param url: http request 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 _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 ApiValueError(
"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, float)):
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]
)
try:
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
# no content type provided or payload is json
content_type = headers.get('Content-Type')
if (
not content_type
or re.search('json', content_type, re.IGNORECASE)
):
request_body = None
if body is not None:
request_body = json.dumps(body)
r = self.pool_manager.request(
method,
url,
body=request_body,
timeout=timeout,
headers=headers,
preload_content=False
)
elif content_type == 'application/x-www-form-urlencoded':
r = self.pool_manager.request(
method,
url,
fields=post_params,
encode_multipart=False,
timeout=timeout,
headers=headers,
preload_content=False
)
elif 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']
# Ensures that dict objects are serialized
post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params]
r = self.pool_manager.request(
method,
url,
fields=post_params,
encode_multipart=True,
timeout=timeout,
headers=headers,
preload_content=False
)
# 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) or isinstance(body, bytes):
r = self.pool_manager.request(
method,
url,
body=body,
timeout=timeout,
headers=headers,
preload_content=False
)
elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool):
request_body = "true" if body else "false"
r = self.pool_manager.request(
method,
url,
body=request_body,
preload_content=False,
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={},
timeout=timeout,
headers=headers,
preload_content=False
)
except urllib3.exceptions.SSLError as e:
msg = "\n".join([type(e).__name__, str(e)])
raise ApiException(status=0, reason=msg)
return RESTResponse(r)

32
docs/Content.md Normal file
View File

@ -0,0 +1,32 @@
# Content
Parameters specifying the content
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cid** | **str** | Content Identifier as specified at https://github.com/multiformats/cid | [optional]
**erasure** | [**ErasureParameters**](ErasureParameters.md) | | [optional]
**por** | [**PoRParameters**](PoRParameters.md) | | [optional]
## Example
```python
from codex_client.models.content import Content
# TODO update the JSON string below
json = "{}"
# create an instance of Content from a JSON string
content_instance = Content.from_json(json)
# print the JSON string representation of the object
print(Content.to_json())
# convert the object into a dict
content_dict = content_instance.to_dict()
# create an instance of Content from a dict
content_from_dict = Content.from_dict(content_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

343
docs/DataApi.md Normal file
View File

@ -0,0 +1,343 @@
# codex_client.DataApi
All URIs are relative to *http://localhost:8080/api/codex/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**download_local**](DataApi.md#download_local) | **GET** /data/{cid} | Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned.
[**download_network**](DataApi.md#download_network) | **GET** /data/{cid}/network | Download a file from the network in a streaming manner. If the file is not available locally, it will be retrieved from other nodes in the network if able.
[**list_data**](DataApi.md#list_data) | **GET** /data | Lists manifest CIDs stored locally in node.
[**space**](DataApi.md#space) | **GET** /space | Gets a summary of the storage space allocation of the node.
[**upload**](DataApi.md#upload) | **POST** /data | Upload a file in a streaming manner. Once finished, the file is stored in the node and can be retrieved by any node in the network using the returned CID.
# **download_local**
> bytearray download_local(cid)
Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned.
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DataApi(api_client)
cid = 'cid_example' # str | File to be downloaded.
try:
# Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned.
api_response = api_instance.download_local(cid)
print("The response of DataApi->download_local:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DataApi->download_local: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cid** | **str**| File to be downloaded. |
### Return type
**bytearray**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/octet-stream
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved content specified by CID | - |
**400** | Invalid CID is specified | - |
**404** | Content specified by the CID is unavailable locally | - |
**500** | Well it was bad-bad | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **download_network**
> bytearray download_network(cid)
Download a file from the network in a streaming manner. If the file is not available locally, it will be retrieved from other nodes in the network if able.
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DataApi(api_client)
cid = 'cid_example' # str | File to be downloaded.
try:
# Download a file from the network in a streaming manner. If the file is not available locally, it will be retrieved from other nodes in the network if able.
api_response = api_instance.download_network(cid)
print("The response of DataApi->download_network:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DataApi->download_network: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cid** | **str**| File to be downloaded. |
### Return type
**bytearray**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/octet-stream
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved content specified by CID | - |
**400** | Invalid CID is specified | - |
**404** | Content specified by the CID is not found | - |
**500** | Well it was bad-bad | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **list_data**
> DataList list_data()
Lists manifest CIDs stored locally in node.
### Example
```python
import codex_client
from codex_client.models.data_list import DataList
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DataApi(api_client)
try:
# Lists manifest CIDs stored locally in node.
api_response = api_instance.list_data()
print("The response of DataApi->list_data:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DataApi->list_data: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**DataList**](DataList.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved list of content CIDs | - |
**400** | Invalid CID is specified | - |
**404** | Content specified by the CID is not found | - |
**500** | Well it was bad-bad | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **space**
> Space space()
Gets a summary of the storage space allocation of the node.
### Example
```python
import codex_client
from codex_client.models.space import Space
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DataApi(api_client)
try:
# Gets a summary of the storage space allocation of the node.
api_response = api_instance.space()
print("The response of DataApi->space:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DataApi->space: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**Space**](Space.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Summary of storage allocation | - |
**500** | It&#39;s not working as planned | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **upload**
> str upload(body=body)
Upload a file in a streaming manner. Once finished, the file is stored in the node and can be retrieved by any node in the network using the returned CID.
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DataApi(api_client)
body = None # bytearray | (optional)
try:
# Upload a file in a streaming manner. Once finished, the file is stored in the node and can be retrieved by any node in the network using the returned CID.
api_response = api_instance.upload(body=body)
print("The response of DataApi->upload:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DataApi->upload: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | **bytearray**| | [optional]
### Return type
**str**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/octet-stream
- **Accept**: text/plain
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | CID of uploaded file | - |
**500** | Well it was bad-bad and the upload did not work out | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

30
docs/DataItem.md Normal file
View File

@ -0,0 +1,30 @@
# DataItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**cid** | **str** | Content Identifier as specified at https://github.com/multiformats/cid | [optional]
**manifest** | [**ManifestItem**](ManifestItem.md) | | [optional]
## Example
```python
from codex_client.models.data_item import DataItem
# TODO update the JSON string below
json = "{}"
# create an instance of DataItem from a JSON string
data_item_instance = DataItem.from_json(json)
# print the JSON string representation of the object
print(DataItem.to_json())
# convert the object into a dict
data_item_dict = data_item_instance.to_dict()
# create an instance of DataItem from a dict
data_item_from_dict = DataItem.from_dict(data_item_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

29
docs/DataList.md Normal file
View File

@ -0,0 +1,29 @@
# DataList
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**content** | [**List[DataItem]**](DataItem.md) | | [optional]
## Example
```python
from codex_client.models.data_list import DataList
# TODO update the JSON string below
json = "{}"
# create an instance of DataList from a JSON string
data_list_instance = DataList.from_json(json)
# print the JSON string representation of the object
print(DataList.to_json())
# convert the object into a dict
data_list_dict = data_list_instance.to_dict()
# create an instance of DataList from a dict
data_list_from_dict = DataList.from_dict(data_list_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

137
docs/DebugApi.md Normal file
View File

@ -0,0 +1,137 @@
# codex_client.DebugApi
All URIs are relative to *http://localhost:8080/api/codex/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**get_debug_info**](DebugApi.md#get_debug_info) | **GET** /debug/info | Gets node information
[**set_debug_log_level**](DebugApi.md#set_debug_log_level) | **POST** /debug/chronicles/loglevel | Set log level at run time
# **get_debug_info**
> DebugInfo get_debug_info()
Gets node information
### Example
```python
import codex_client
from codex_client.models.debug_info import DebugInfo
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DebugApi(api_client)
try:
# Gets node information
api_response = api_instance.get_debug_info()
print("The response of DebugApi->get_debug_info:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling DebugApi->get_debug_info: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**DebugInfo**](DebugInfo.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Node&#39;s information | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **set_debug_log_level**
> set_debug_log_level(level)
Set log level at run time
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.DebugApi(api_client)
level = 'level_example' # str |
try:
# Set log level at run time
api_instance.set_debug_log_level(level)
except Exception as e:
print("Exception when calling DebugApi->set_debug_log_level: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**level** | **str**| |
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successfully log level set | - |
**400** | Invalid or missing log level | - |
**500** | Well it was bad-bad | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

32
docs/DebugInfo.md Normal file
View File

@ -0,0 +1,32 @@
# DebugInfo
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | Peer Identity reference as specified at https://docs.libp2p.io/concepts/fundamentals/peers/ | [optional]
**addrs** | **List[str]** | | [optional]
**repo** | **str** | Path of the data repository where all nodes data are stored | [optional]
**spr** | **str** | Signed Peer Record (libp2p) | [optional]
## Example
```python
from codex_client.models.debug_info import DebugInfo
# TODO update the JSON string below
json = "{}"
# create an instance of DebugInfo from a JSON string
debug_info_instance = DebugInfo.from_json(json)
# print the JSON string representation of the object
print(DebugInfo.to_json())
# convert the object into a dict
debug_info_dict = debug_info_instance.to_dict()
# create an instance of DebugInfo from a dict
debug_info_from_dict = DebugInfo.from_dict(debug_info_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

29
docs/ErasureParameters.md Normal file
View File

@ -0,0 +1,29 @@
# ErasureParameters
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**total_chunks** | **int** | | [optional]
## Example
```python
from codex_client.models.erasure_parameters import ErasureParameters
# TODO update the JSON string below
json = "{}"
# create an instance of ErasureParameters from a JSON string
erasure_parameters_instance = ErasureParameters.from_json(json)
# print the JSON string representation of the object
print(ErasureParameters.to_json())
# convert the object into a dict
erasure_parameters_dict = erasure_parameters_instance.to_dict()
# create an instance of ErasureParameters from a dict
erasure_parameters_from_dict = ErasureParameters.from_dict(erasure_parameters_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

32
docs/ManifestItem.md Normal file
View File

@ -0,0 +1,32 @@
# ManifestItem
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**root_hash** | **str** | Content Identifier as specified at https://github.com/multiformats/cid | [optional]
**original_bytes** | **int** | Length of original content in bytes | [optional]
**block_size** | **int** | Size of blocks | [optional]
**protected** | **bool** | Indicates if content is protected by erasure-coding | [optional]
## Example
```python
from codex_client.models.manifest_item import ManifestItem
# TODO update the JSON string below
json = "{}"
# create an instance of ManifestItem from a JSON string
manifest_item_instance = ManifestItem.from_json(json)
# print the JSON string representation of the object
print(ManifestItem.to_json())
# convert the object into a dict
manifest_item_dict = manifest_item_instance.to_dict()
# create an instance of ManifestItem from a dict
manifest_item_from_dict = ManifestItem.from_dict(manifest_item_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

631
docs/MarketplaceApi.md Normal file
View File

@ -0,0 +1,631 @@
# codex_client.MarketplaceApi
All URIs are relative to *http://localhost:8080/api/codex/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**create_storage_request**](MarketplaceApi.md#create_storage_request) | **POST** /storage/request/{cid} | Creates a new Request for storage
[**get_active_slot_by_id**](MarketplaceApi.md#get_active_slot_by_id) | **GET** /sales/slots/{slotId} | Returns active slot with id {slotId} for the host
[**get_active_slots**](MarketplaceApi.md#get_active_slots) | **GET** /sales/slots | Returns active slots
[**get_offered_storage**](MarketplaceApi.md#get_offered_storage) | **GET** /sales/availability | Returns storage that is for sale
[**get_purchase**](MarketplaceApi.md#get_purchase) | **GET** /storage/purchases/{id} | Returns purchase details
[**get_purchases**](MarketplaceApi.md#get_purchases) | **GET** /storage/purchases | Returns list of purchase IDs
[**get_reservations**](MarketplaceApi.md#get_reservations) | **PATCH** /sales/availability/{id}/reservations | Get availability&#39;s reservations
[**offer_storage**](MarketplaceApi.md#offer_storage) | **POST** /sales/availability | Offers storage for sale
[**update_offered_storage**](MarketplaceApi.md#update_offered_storage) | **PATCH** /sales/availability/{id} | Updates availability
# **create_storage_request**
> str create_storage_request(cid, storage_request_creation=storage_request_creation)
Creates a new Request for storage
### Example
```python
import codex_client
from codex_client.models.storage_request_creation import StorageRequestCreation
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
cid = 'cid_example' # str | CID of the uploaded data that should be stored
storage_request_creation = codex_client.StorageRequestCreation() # StorageRequestCreation | (optional)
try:
# Creates a new Request for storage
api_response = api_instance.create_storage_request(cid, storage_request_creation=storage_request_creation)
print("The response of MarketplaceApi->create_storage_request:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->create_storage_request: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**cid** | **str**| CID of the uploaded data that should be stored |
**storage_request_creation** | [**StorageRequestCreation**](StorageRequestCreation.md)| | [optional]
### Return type
**str**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: text/plain
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Returns the Request ID as decimal string | - |
**400** | Invalid or missing Request ID | - |
**404** | Request ID not found | - |
**503** | Purchasing is unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_active_slot_by_id**
> Slot get_active_slot_by_id(slot_id)
Returns active slot with id {slotId} for the host
### Example
```python
import codex_client
from codex_client.models.slot import Slot
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
slot_id = 'slot_id_example' # str | File to be downloaded.
try:
# Returns active slot with id {slotId} for the host
api_response = api_instance.get_active_slot_by_id(slot_id)
print("The response of MarketplaceApi->get_active_slot_by_id:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->get_active_slot_by_id: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**slot_id** | **str**| File to be downloaded. |
### Return type
[**Slot**](Slot.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved active slot | - |
**400** | Invalid or missing SlotId | - |
**404** | Host is not in an active sale for the slot | - |
**503** | Sales are unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_active_slots**
> List[Slot] get_active_slots()
Returns active slots
### Example
```python
import codex_client
from codex_client.models.slot import Slot
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
try:
# Returns active slots
api_response = api_instance.get_active_slots()
print("The response of MarketplaceApi->get_active_slots:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->get_active_slots: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**List[Slot]**](Slot.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved active slots | - |
**503** | Sales are unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_offered_storage**
> List[SalesAvailability] get_offered_storage()
Returns storage that is for sale
### Example
```python
import codex_client
from codex_client.models.sales_availability import SalesAvailability
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
try:
# Returns storage that is for sale
api_response = api_instance.get_offered_storage()
print("The response of MarketplaceApi->get_offered_storage:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->get_offered_storage: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**List[SalesAvailability]**](SalesAvailability.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved storage availabilities of the node | - |
**500** | Error getting unused availabilities | - |
**503** | Sales are unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_purchase**
> Purchase get_purchase(id)
Returns purchase details
### Example
```python
import codex_client
from codex_client.models.purchase import Purchase
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
id = 'id_example' # str | Hexadecimal ID of a Purchase
try:
# Returns purchase details
api_response = api_instance.get_purchase(id)
print("The response of MarketplaceApi->get_purchase:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->get_purchase: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **str**| Hexadecimal ID of a Purchase |
### Return type
[**Purchase**](Purchase.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Purchase details | - |
**400** | Invalid or missing Purchase ID | - |
**404** | Purchase not found | - |
**503** | Purchasing is unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_purchases**
> List[str] get_purchases()
Returns list of purchase IDs
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
try:
# Returns list of purchase IDs
api_response = api_instance.get_purchases()
print("The response of MarketplaceApi->get_purchases:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->get_purchases: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
**List[str]**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Gets all purchase IDs stored in node | - |
**503** | Purchasing is unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_reservations**
> List[Reservation] get_reservations(id)
Get availability's reservations
Return's list of Reservations for ongoing Storage Requests that the node hosts.
### Example
```python
import codex_client
from codex_client.models.reservation import Reservation
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
id = 'id_example' # str | ID of Availability
try:
# Get availability's reservations
api_response = api_instance.get_reservations(id)
print("The response of MarketplaceApi->get_reservations:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->get_reservations: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **str**| ID of Availability |
### Return type
[**List[Reservation]**](Reservation.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Retrieved storage availabilities of the node | - |
**400** | Invalid Availability ID | - |
**404** | Availability not found | - |
**500** | Error getting reservations | - |
**503** | Sales are unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **offer_storage**
> SalesAvailabilityREAD offer_storage(sales_availability_create=sales_availability_create)
Offers storage for sale
### Example
```python
import codex_client
from codex_client.models.sales_availability_create import SalesAvailabilityCREATE
from codex_client.models.sales_availability_read import SalesAvailabilityREAD
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
sales_availability_create = codex_client.SalesAvailabilityCREATE() # SalesAvailabilityCREATE | (optional)
try:
# Offers storage for sale
api_response = api_instance.offer_storage(sales_availability_create=sales_availability_create)
print("The response of MarketplaceApi->offer_storage:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling MarketplaceApi->offer_storage: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**sales_availability_create** | [**SalesAvailabilityCREATE**](SalesAvailabilityCREATE.md)| | [optional]
### Return type
[**SalesAvailabilityREAD**](SalesAvailabilityREAD.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**201** | Created storage availability | - |
**400** | Invalid data input | - |
**422** | Not enough node&#39;s storage quota available | - |
**500** | Error reserving availability | - |
**503** | Sales are unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **update_offered_storage**
> update_offered_storage(id, sales_availability=sales_availability)
Updates availability
The new parameters will be only considered for new requests. Existing Requests linked to this Availability will continue as is.
### Example
```python
import codex_client
from codex_client.models.sales_availability import SalesAvailability
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.MarketplaceApi(api_client)
id = 'id_example' # str | ID of Availability
sales_availability = codex_client.SalesAvailability() # SalesAvailability | (optional)
try:
# Updates availability
api_instance.update_offered_storage(id, sales_availability=sales_availability)
except Exception as e:
print("Exception when calling MarketplaceApi->update_offered_storage: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **str**| ID of Availability |
**sales_availability** | [**SalesAvailability**](SalesAvailability.md)| | [optional]
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**204** | Availability successfully updated | - |
**400** | Invalid data input | - |
**404** | Availability not found | - |
**422** | Not enough node&#39;s storage quota available | - |
**500** | Error reserving availability | - |
**503** | Sales are unavailable | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

202
docs/NodeApi.md Normal file
View File

@ -0,0 +1,202 @@
# codex_client.NodeApi
All URIs are relative to *http://localhost:8080/api/codex/v1*
Method | HTTP request | Description
------------- | ------------- | -------------
[**connect_peer**](NodeApi.md#connect_peer) | **GET** /connect/{peerId} | Connect to a peer
[**get_peer_id**](NodeApi.md#get_peer_id) | **GET** /node/peerid | Get Node&#39;s PeerID
[**get_spr**](NodeApi.md#get_spr) | **GET** /node/spr | Get Node&#39;s SPR
# **connect_peer**
> connect_peer(peer_id, addrs=addrs)
Connect to a peer
If `addrs` param is supplied, it will be used to dial the peer, otherwise the `peerId` is used to invoke peer discovery, if it succeeds the returned addresses will be used to dial.
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.NodeApi(api_client)
peer_id = 'peer_id_example' # str | Peer that should be dialed.
addrs = ['addrs_example'] # List[str] | If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the `--listen-addrs` CLI flag. (optional)
try:
# Connect to a peer
api_instance.connect_peer(peer_id, addrs=addrs)
except Exception as e:
print("Exception when calling NodeApi->connect_peer: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**peer_id** | **str**| Peer that should be dialed. |
**addrs** | [**List[str]**](str.md)| If supplied, it will be used to dial the peer. The address has to target the listening address of the peer, which is specified with the &#x60;--listen-addrs&#x60; CLI flag. | [optional]
### Return type
void (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Successfully connected to peer | - |
**400** | Peer either not found or was not possible to dial | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_peer_id**
> str get_peer_id()
Get Node's PeerID
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.NodeApi(api_client)
try:
# Get Node's PeerID
api_response = api_instance.get_peer_id()
print("The response of NodeApi->get_peer_id:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling NodeApi->get_peer_id: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
**str**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: plain/text, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Node&#39;s Peer ID | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_spr**
> str get_spr()
Get Node's SPR
### Example
```python
import codex_client
from codex_client.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to http://localhost:8080/api/codex/v1
# See configuration.py for a list of all supported configuration parameters.
configuration = codex_client.Configuration(
host = "http://localhost:8080/api/codex/v1"
)
# Enter a context with an instance of the API client
with codex_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = codex_client.NodeApi(api_client)
try:
# Get Node's SPR
api_response = api_instance.get_spr()
print("The response of NodeApi->get_spr:\n")
pprint(api_response)
except Exception as e:
print("Exception when calling NodeApi->get_spr: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
**str**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: plain/text, application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Node&#39;s SPR | - |
**503** | Node SPR not ready, try again later | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

29
docs/PeerIdRead.md Normal file
View File

@ -0,0 +1,29 @@
# PeerIdRead
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | Peer Identity reference as specified at https://docs.libp2p.io/concepts/fundamentals/peers/ | [optional]
## Example
```python
from codex_client.models.peer_id_read import PeerIdRead
# TODO update the JSON string below
json = "{}"
# create an instance of PeerIdRead from a JSON string
peer_id_read_instance = PeerIdRead.from_json(json)
# print the JSON string representation of the object
print(PeerIdRead.to_json())
# convert the object into a dict
peer_id_read_dict = peer_id_read_instance.to_dict()
# create an instance of PeerIdRead from a dict
peer_id_read_from_dict = PeerIdRead.from_dict(peer_id_read_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

32
docs/PoRParameters.md Normal file
View File

@ -0,0 +1,32 @@
# PoRParameters
Parameters for Proof of Retrievability
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**u** | **str** | | [optional]
**public_key** | **str** | | [optional]
**name** | **str** | | [optional]
## Example
```python
from codex_client.models.po_r_parameters import PoRParameters
# TODO update the JSON string below
json = "{}"
# create an instance of PoRParameters from a JSON string
po_r_parameters_instance = PoRParameters.from_json(json)
# print the JSON string representation of the object
print(PoRParameters.to_json())
# convert the object into a dict
po_r_parameters_dict = po_r_parameters_instance.to_dict()
# create an instance of PoRParameters from a dict
po_r_parameters_from_dict = PoRParameters.from_dict(po_r_parameters_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

31
docs/Purchase.md Normal file
View File

@ -0,0 +1,31 @@
# Purchase
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**state** | **str** | Description of the Request&#39;s state | [optional]
**error** | **str** | If Request failed, then here is presented the error message | [optional]
**request** | [**StorageRequest**](StorageRequest.md) | | [optional]
## Example
```python
from codex_client.models.purchase import Purchase
# TODO update the JSON string below
json = "{}"
# create an instance of Purchase from a JSON string
purchase_instance = Purchase.from_json(json)
# print the JSON string representation of the object
print(Purchase.to_json())
# convert the object into a dict
purchase_dict = purchase_instance.to_dict()
# create an instance of Purchase from a dict
purchase_from_dict = Purchase.from_dict(purchase_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

33
docs/Reservation.md Normal file
View File

@ -0,0 +1,33 @@
# Reservation
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | 32bits identifier encoded in hex-decimal string. | [optional]
**availability_id** | **str** | 32bits identifier encoded in hex-decimal string. | [optional]
**size** | **str** | Integer represented as decimal string | [optional]
**request_id** | **str** | 32bits identifier encoded in hex-decimal string. | [optional]
**slot_index** | **str** | Slot Index as hexadecimal string | [optional]
## Example
```python
from codex_client.models.reservation import Reservation
# TODO update the JSON string below
json = "{}"
# create an instance of Reservation from a JSON string
reservation_instance = Reservation.from_json(json)
# print the JSON string representation of the object
print(Reservation.to_json())
# convert the object into a dict
reservation_dict = reservation_instance.to_dict()
# create an instance of Reservation from a dict
reservation_from_dict = Reservation.from_dict(reservation_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

29
docs/SPRRead.md Normal file
View File

@ -0,0 +1,29 @@
# SPRRead
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**spr** | **str** | Signed Peer Record (libp2p) | [optional]
## Example
```python
from codex_client.models.spr_read import SPRRead
# TODO update the JSON string below
json = "{}"
# create an instance of SPRRead from a JSON string
spr_read_instance = SPRRead.from_json(json)
# print the JSON string representation of the object
print(SPRRead.to_json())
# convert the object into a dict
spr_read_dict = spr_read_instance.to_dict()
# create an instance of SPRRead from a dict
spr_read_from_dict = SPRRead.from_dict(spr_read_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

33
docs/SalesAvailability.md Normal file
View File

@ -0,0 +1,33 @@
# SalesAvailability
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | 32bits identifier encoded in hex-decimal string. | [optional]
**total_size** | **str** | Total size of availability&#39;s storage in bytes as decimal string | [optional]
**duration** | **str** | The duration of the request in seconds as decimal string | [optional]
**min_price** | **str** | Minimum price to be paid (in amount of tokens) as decimal string | [optional]
**max_collateral** | **str** | Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string | [optional]
## Example
```python
from codex_client.models.sales_availability import SalesAvailability
# TODO update the JSON string below
json = "{}"
# create an instance of SalesAvailability from a JSON string
sales_availability_instance = SalesAvailability.from_json(json)
# print the JSON string representation of the object
print(SalesAvailability.to_json())
# convert the object into a dict
sales_availability_dict = sales_availability_instance.to_dict()
# create an instance of SalesAvailability from a dict
sales_availability_from_dict = SalesAvailability.from_dict(sales_availability_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,33 @@
# SalesAvailabilityCREATE
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | 32bits identifier encoded in hex-decimal string. | [optional]
**total_size** | **str** | Total size of availability&#39;s storage in bytes as decimal string |
**duration** | **str** | The duration of the request in seconds as decimal string |
**min_price** | **str** | Minimum price to be paid (in amount of tokens) as decimal string |
**max_collateral** | **str** | Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string |
## Example
```python
from codex_client.models.sales_availability_create import SalesAvailabilityCREATE
# TODO update the JSON string below
json = "{}"
# create an instance of SalesAvailabilityCREATE from a JSON string
sales_availability_create_instance = SalesAvailabilityCREATE.from_json(json)
# print the JSON string representation of the object
print(SalesAvailabilityCREATE.to_json())
# convert the object into a dict
sales_availability_create_dict = sales_availability_create_instance.to_dict()
# create an instance of SalesAvailabilityCREATE from a dict
sales_availability_create_from_dict = SalesAvailabilityCREATE.from_dict(sales_availability_create_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,34 @@
# SalesAvailabilityREAD
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | 32bits identifier encoded in hex-decimal string. | [optional]
**total_size** | **str** | Total size of availability&#39;s storage in bytes as decimal string | [optional]
**duration** | **str** | The duration of the request in seconds as decimal string | [optional]
**min_price** | **str** | Minimum price to be paid (in amount of tokens) as decimal string | [optional]
**max_collateral** | **str** | Maximum collateral user is willing to pay per filled Slot (in amount of tokens) as decimal string | [optional]
**free_size** | **str** | Unused size of availability&#39;s storage in bytes as decimal string | [optional]
## Example
```python
from codex_client.models.sales_availability_read import SalesAvailabilityREAD
# TODO update the JSON string below
json = "{}"
# create an instance of SalesAvailabilityREAD from a JSON string
sales_availability_read_instance = SalesAvailabilityREAD.from_json(json)
# print the JSON string representation of the object
print(SalesAvailabilityREAD.to_json())
# convert the object into a dict
sales_availability_read_dict = sales_availability_read_instance.to_dict()
# create an instance of SalesAvailabilityREAD from a dict
sales_availability_read_from_dict = SalesAvailabilityREAD.from_dict(sales_availability_read_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

31
docs/Slot.md Normal file
View File

@ -0,0 +1,31 @@
# Slot
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | Keccak hash of the abi encoded tuple (RequestId, slot index) | [optional]
**request** | [**StorageRequest**](StorageRequest.md) | | [optional]
**slot_index** | **str** | Slot Index as hexadecimal string | [optional]
## Example
```python
from codex_client.models.slot import Slot
# TODO update the JSON string below
json = "{}"
# create an instance of Slot from a JSON string
slot_instance = Slot.from_json(json)
# print the JSON string representation of the object
print(Slot.to_json())
# convert the object into a dict
slot_dict = slot_instance.to_dict()
# create an instance of Slot from a dict
slot_from_dict = Slot.from_dict(slot_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

32
docs/Space.md Normal file
View File

@ -0,0 +1,32 @@
# Space
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**total_blocks** | **int** | Number of blocks stored by the node | [optional]
**quota_max_bytes** | **int** | Maximum storage space used by the node | [optional]
**quota_used_bytes** | **int** | Amount of storage space currently in use | [optional]
**quota_reserved_bytes** | **int** | Amount of storage space reserved | [optional]
## Example
```python
from codex_client.models.space import Space
# TODO update the JSON string below
json = "{}"
# create an instance of Space from a JSON string
space_instance = Space.from_json(json)
# print the JSON string representation of the object
print(Space.to_json())
# convert the object into a dict
space_dict = space_instance.to_dict()
# create an instance of Space from a dict
space_from_dict = Space.from_dict(space_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

34
docs/StorageAsk.md Normal file
View File

@ -0,0 +1,34 @@
# StorageAsk
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**slots** | **int** | Number of slots (eq. hosts) that the Request want to have the content spread over | [optional]
**slot_size** | **str** | Amount of storage per slot (in bytes) as decimal string | [optional]
**duration** | **str** | The duration of the request in seconds as decimal string | [optional]
**proof_probability** | **str** | How often storage proofs are required as decimal string | [optional]
**reward** | **str** | The maximum amount of tokens paid per second per slot to hosts the client is willing to pay |
**max_slot_loss** | **int** | Max slots that can be lost without data considered to be lost | [optional]
## Example
```python
from codex_client.models.storage_ask import StorageAsk
# TODO update the JSON string below
json = "{}"
# create an instance of StorageAsk from a JSON string
storage_ask_instance = StorageAsk.from_json(json)
# print the JSON string representation of the object
print(StorageAsk.to_json())
# convert the object into a dict
storage_ask_dict = storage_ask_instance.to_dict()
# create an instance of StorageAsk from a dict
storage_ask_from_dict = StorageAsk.from_dict(storage_ask_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

34
docs/StorageRequest.md Normal file
View File

@ -0,0 +1,34 @@
# StorageRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **str** | Request ID | [optional]
**client** | **str** | Address of Ethereum address | [optional]
**ask** | [**StorageAsk**](StorageAsk.md) | | [optional]
**content** | [**Content**](Content.md) | | [optional]
**expiry** | **str** | A timestamp as seconds since unix epoch at which this request expires if the Request does not find requested amount of nodes to host the data. | [optional] [default to '10 minutes']
**nonce** | **str** | Random data | [optional]
## Example
```python
from codex_client.models.storage_request import StorageRequest
# TODO update the JSON string below
json = "{}"
# create an instance of StorageRequest from a JSON string
storage_request_instance = StorageRequest.from_json(json)
# print the JSON string representation of the object
print(StorageRequest.to_json())
# convert the object into a dict
storage_request_dict = storage_request_instance.to_dict()
# create an instance of StorageRequest from a dict
storage_request_from_dict = StorageRequest.from_dict(storage_request_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,35 @@
# StorageRequestCreation
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**duration** | **str** | The duration of the request in seconds as decimal string |
**reward** | **str** | The maximum amount of tokens paid per second per slot to hosts the client is willing to pay |
**proof_probability** | **str** | How often storage proofs are required as decimal string |
**nodes** | **int** | Minimal number of nodes the content should be stored on | [optional] [default to 1]
**tolerance** | **int** | Additional number of nodes on top of the &#x60;nodes&#x60; property that can be lost before pronouncing the content lost | [optional] [default to 0]
**collateral** | **str** | Number as decimal string that represents how much collateral is asked from hosts that wants to fill a slots |
**expiry** | **str** | Number as decimal string that represents expiry threshold in seconds from when the Request is submitted. When the threshold is reached and the Request does not find requested amount of nodes to host the data, the Request is voided. The number of seconds can not be higher then the Request&#39;s duration itself. |
## Example
```python
from codex_client.models.storage_request_creation import StorageRequestCreation
# TODO update the JSON string below
json = "{}"
# create an instance of StorageRequestCreation from a JSON string
storage_request_creation_instance = StorageRequestCreation.from_json(json)
# print the JSON string representation of the object
print(StorageRequestCreation.to_json())
# convert the object into a dict
storage_request_creation_dict = storage_request_creation_instance.to_dict()
# create an instance of StorageRequestCreation from a dict
storage_request_creation_from_dict = StorageRequestCreation.from_dict(storage_request_creation_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

8
generate.sh Executable file
View File

@ -0,0 +1,8 @@
#!/bin/sh
openapi-generator-cli generate \
-g python \
-i codex.yaml \
--additional-properties="packageName=codex_client,projectName=Codex\ API\ Client,packageUrl=https://github.com/AuHau/py-codex-api" \
--git-repo-id py-codex-api --git-user-id auhau \
--http-user-agent py_codex_client

57
git_push.sh Normal file
View File

@ -0,0 +1,57 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="auhau"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="py-codex-api"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

7
openapitools.json Normal file
View File

@ -0,0 +1,7 @@
{
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "7.8.0"
}
}

71
pyproject.toml Normal file
View File

@ -0,0 +1,71 @@
[tool.poetry]
name = "codex_client"
version = "1.0.0"
description = "Codex API"
authors = ["OpenAPI Generator Community <team@openapitools.org>"]
license = "NoLicense"
readme = "README.md"
repository = "https://github.com/auhau/py-codex-api"
keywords = ["OpenAPI", "OpenAPI-Generator", "Codex API"]
include = ["codex_client/py.typed"]
[tool.poetry.dependencies]
python = "^3.7"
urllib3 = ">= 1.25.3"
python-dateutil = ">=2.8.2"
pydantic = ">=2"
typing-extensions = ">=4.7.1"
[tool.poetry.dev-dependencies]
pytest = ">=7.2.1"
tox = ">=3.9.0"
flake8 = ">=4.0.0"
types-python-dateutil = ">=2.8.19.14"
mypy = "1.4.1"
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[tool.pylint.'MESSAGES CONTROL']
extension-pkg-whitelist = "pydantic"
[tool.mypy]
files = [
"codex_client",
#"test", # auto-generated tests
"tests", # hand-written tests
]
# TODO: enable "strict" once all these individual checks are passing
# strict = true
# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
## Getting these passing should be easy
strict_equality = true
strict_concatenate = true
## Strongly recommend enabling this one as soon as you can
check_untyped_defs = true
## These shouldn't be too much additional work, but may be tricky to
## get passing if you use a lot of untyped libraries
disallow_subclassing_any = true
disallow_untyped_decorators = true
disallow_any_generics = true
### These next few are various gradations of forcing use of type annotations
#disallow_untyped_calls = true
#disallow_incomplete_defs = true
#disallow_untyped_defs = true
#
### This one isn't too hard to get passing, but return on investment is lower
#no_implicit_reexport = true
#
### This one can be tricky to get passing if you use a lot of untyped libraries
#warn_return_any = true

5
requirements.txt Normal file
View File

@ -0,0 +1,5 @@
python_dateutil >= 2.5.3
setuptools >= 21.0.0
urllib3 >= 1.25.3, < 2.1.0
pydantic >= 2
typing-extensions >= 4.7.1

2
setup.cfg Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length=99

49
setup.py Normal file
View File

@ -0,0 +1,49 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from setuptools import setup, find_packages # noqa: H301
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
NAME = "Codex API Client"
VERSION = "1.0.0"
PYTHON_REQUIRES = ">=3.7"
REQUIRES = [
"urllib3 >= 1.25.3, < 2.1.0",
"python-dateutil",
"pydantic >= 2",
"typing-extensions >= 4.7.1",
]
setup(
name=NAME,
version=VERSION,
description="Codex API",
author="OpenAPI Generator community",
author_email="team@openapitools.org",
url="https://github.com/AuHau/py-codex-api",
keywords=["OpenAPI", "OpenAPI-Generator", "Codex API"],
install_requires=REQUIRES,
packages=find_packages(exclude=["test", "tests"]),
include_package_data=True,
long_description_content_type='text/markdown',
long_description="""\
List of endpoints and interfaces available to Codex API users
""", # noqa: E501
package_data={"codex_client": ["py.typed"]},
)

5
test-requirements.txt Normal file
View File

@ -0,0 +1,5 @@
pytest~=7.1.3
pytest-cov>=2.8.1
pytest-randomly>=3.12.0
mypy>=1.4.1
types-python-dateutil>=2.8.19

0
test/__init__.py Normal file
View File

57
test/test_content.py Normal file
View File

@ -0,0 +1,57 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.content import Content
class TestContent(unittest.TestCase):
"""Content unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> Content:
"""Test Content
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Content`
"""
model = Content()
if include_optional:
return Content(
cid = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
erasure = codex_client.models.erasure_parameters.ErasureParameters(
total_chunks = 56, ),
por = codex_client.models.po_r_parameters.PoRParameters(
u = '',
public_key = '',
name = '', )
)
else:
return Content(
)
"""
def testContent(self):
"""Test Content"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

66
test/test_data_api.py Normal file
View File

@ -0,0 +1,66 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.api.data_api import DataApi
class TestDataApi(unittest.TestCase):
"""DataApi unit test stubs"""
def setUp(self) -> None:
self.api = DataApi()
def tearDown(self) -> None:
pass
def test_download_local(self) -> None:
"""Test case for download_local
Download a file from the local node in a streaming manner. If the file is not available locally, a 404 is returned.
"""
pass
def test_download_network(self) -> None:
"""Test case for download_network
Download a file from the network in a streaming manner. If the file is not available locally, it will be retrieved from other nodes in the network if able.
"""
pass
def test_list_data(self) -> None:
"""Test case for list_data
Lists manifest CIDs stored locally in node.
"""
pass
def test_space(self) -> None:
"""Test case for space
Gets a summary of the storage space allocation of the node.
"""
pass
def test_upload(self) -> None:
"""Test case for upload
Upload a file in a streaming manner. Once finished, the file is stored in the node and can be retrieved by any node in the network using the returned CID.
"""
pass
if __name__ == '__main__':
unittest.main()

56
test/test_data_item.py Normal file
View File

@ -0,0 +1,56 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.data_item import DataItem
class TestDataItem(unittest.TestCase):
"""DataItem unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> DataItem:
"""Test DataItem
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `DataItem`
"""
model = DataItem()
if include_optional:
return DataItem(
cid = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
manifest = codex_client.models.manifest_item.ManifestItem(
root_hash = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
original_bytes = 56,
block_size = 56,
protected = True, )
)
else:
return DataItem(
)
"""
def testDataItem(self):
"""Test DataItem"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

59
test/test_data_list.py Normal file
View File

@ -0,0 +1,59 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.data_list import DataList
class TestDataList(unittest.TestCase):
"""DataList unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> DataList:
"""Test DataList
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `DataList`
"""
model = DataList()
if include_optional:
return DataList(
content = [
codex_client.models.data_item.DataItem(
cid = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
manifest = codex_client.models.manifest_item.ManifestItem(
root_hash = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
original_bytes = 56,
block_size = 56,
protected = True, ), )
]
)
else:
return DataList(
)
"""
def testDataList(self):
"""Test DataList"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

45
test/test_debug_api.py Normal file
View File

@ -0,0 +1,45 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.api.debug_api import DebugApi
class TestDebugApi(unittest.TestCase):
"""DebugApi unit test stubs"""
def setUp(self) -> None:
self.api = DebugApi()
def tearDown(self) -> None:
pass
def test_get_debug_info(self) -> None:
"""Test case for get_debug_info
Gets node information
"""
pass
def test_set_debug_log_level(self) -> None:
"""Test case for set_debug_log_level
Set log level at run time
"""
pass
if __name__ == '__main__':
unittest.main()

56
test/test_debug_info.py Normal file
View File

@ -0,0 +1,56 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.debug_info import DebugInfo
class TestDebugInfo(unittest.TestCase):
"""DebugInfo unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> DebugInfo:
"""Test DebugInfo
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `DebugInfo`
"""
model = DebugInfo()
if include_optional:
return DebugInfo(
id = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
addrs = [
'/ip4/127.0.0.1/tcp/8080'
],
repo = '',
spr = ''
)
else:
return DebugInfo(
)
"""
def testDebugInfo(self):
"""Test DebugInfo"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,51 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.erasure_parameters import ErasureParameters
class TestErasureParameters(unittest.TestCase):
"""ErasureParameters unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> ErasureParameters:
"""Test ErasureParameters
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `ErasureParameters`
"""
model = ErasureParameters()
if include_optional:
return ErasureParameters(
total_chunks = 56
)
else:
return ErasureParameters(
)
"""
def testErasureParameters(self):
"""Test ErasureParameters"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,54 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.manifest_item import ManifestItem
class TestManifestItem(unittest.TestCase):
"""ManifestItem unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> ManifestItem:
"""Test ManifestItem
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `ManifestItem`
"""
model = ManifestItem()
if include_optional:
return ManifestItem(
root_hash = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
original_bytes = 56,
block_size = 56,
protected = True
)
else:
return ManifestItem(
)
"""
def testManifestItem(self):
"""Test ManifestItem"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,94 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.api.marketplace_api import MarketplaceApi
class TestMarketplaceApi(unittest.TestCase):
"""MarketplaceApi unit test stubs"""
def setUp(self) -> None:
self.api = MarketplaceApi()
def tearDown(self) -> None:
pass
def test_create_storage_request(self) -> None:
"""Test case for create_storage_request
Creates a new Request for storage
"""
pass
def test_get_active_slot_by_id(self) -> None:
"""Test case for get_active_slot_by_id
Returns active slot with id {slotId} for the host
"""
pass
def test_get_active_slots(self) -> None:
"""Test case for get_active_slots
Returns active slots
"""
pass
def test_get_offered_storage(self) -> None:
"""Test case for get_offered_storage
Returns storage that is for sale
"""
pass
def test_get_purchase(self) -> None:
"""Test case for get_purchase
Returns purchase details
"""
pass
def test_get_purchases(self) -> None:
"""Test case for get_purchases
Returns list of purchase IDs
"""
pass
def test_get_reservations(self) -> None:
"""Test case for get_reservations
Get availability's reservations
"""
pass
def test_offer_storage(self) -> None:
"""Test case for offer_storage
Offers storage for sale
"""
pass
def test_update_offered_storage(self) -> None:
"""Test case for update_offered_storage
Updates availability
"""
pass
if __name__ == '__main__':
unittest.main()

52
test/test_node_api.py Normal file
View File

@ -0,0 +1,52 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.api.node_api import NodeApi
class TestNodeApi(unittest.TestCase):
"""NodeApi unit test stubs"""
def setUp(self) -> None:
self.api = NodeApi()
def tearDown(self) -> None:
pass
def test_connect_peer(self) -> None:
"""Test case for connect_peer
Connect to a peer
"""
pass
def test_get_peer_id(self) -> None:
"""Test case for get_peer_id
Get Node's PeerID
"""
pass
def test_get_spr(self) -> None:
"""Test case for get_spr
Get Node's SPR
"""
pass
if __name__ == '__main__':
unittest.main()

51
test/test_peer_id_read.py Normal file
View File

@ -0,0 +1,51 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.peer_id_read import PeerIdRead
class TestPeerIdRead(unittest.TestCase):
"""PeerIdRead unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> PeerIdRead:
"""Test PeerIdRead
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `PeerIdRead`
"""
model = PeerIdRead()
if include_optional:
return PeerIdRead(
id = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N'
)
else:
return PeerIdRead(
)
"""
def testPeerIdRead(self):
"""Test PeerIdRead"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,53 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.po_r_parameters import PoRParameters
class TestPoRParameters(unittest.TestCase):
"""PoRParameters unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> PoRParameters:
"""Test PoRParameters
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `PoRParameters`
"""
model = PoRParameters()
if include_optional:
return PoRParameters(
u = '',
public_key = '',
name = ''
)
else:
return PoRParameters(
)
"""
def testPoRParameters(self):
"""Test PoRParameters"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

72
test/test_purchase.py Normal file
View File

@ -0,0 +1,72 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.purchase import Purchase
class TestPurchase(unittest.TestCase):
"""Purchase unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> Purchase:
"""Test Purchase
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Purchase`
"""
model = Purchase()
if include_optional:
return Purchase(
state = '',
error = '',
request = codex_client.models.storage_request.StorageRequest(
id = '',
client = '',
ask = codex_client.models.storage_ask.StorageAsk(
slots = 56,
slot_size = '',
duration = '',
proof_probability = '',
reward = '',
max_slot_loss = 56, ),
content = codex_client.models.content.Content(
cid = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
erasure = codex_client.models.erasure_parameters.ErasureParameters(
total_chunks = 56, ),
por = codex_client.models.po_r_parameters.PoRParameters(
u = '',
public_key = '',
name = '', ), ),
expiry = '10 minutes',
nonce = '', )
)
else:
return Purchase(
)
"""
def testPurchase(self):
"""Test Purchase"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

55
test/test_reservation.py Normal file
View File

@ -0,0 +1,55 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.reservation import Reservation
class TestReservation(unittest.TestCase):
"""Reservation unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> Reservation:
"""Test Reservation
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Reservation`
"""
model = Reservation()
if include_optional:
return Reservation(
id = '0x...',
availability_id = '0x...',
size = '',
request_id = '0x...',
slot_index = ''
)
else:
return Reservation(
)
"""
def testReservation(self):
"""Test Reservation"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,55 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.sales_availability import SalesAvailability
class TestSalesAvailability(unittest.TestCase):
"""SalesAvailability unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> SalesAvailability:
"""Test SalesAvailability
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `SalesAvailability`
"""
model = SalesAvailability()
if include_optional:
return SalesAvailability(
id = '0x...',
total_size = '',
duration = '',
min_price = '',
max_collateral = ''
)
else:
return SalesAvailability(
)
"""
def testSalesAvailability(self):
"""Test SalesAvailability"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,59 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.sales_availability_create import SalesAvailabilityCREATE
class TestSalesAvailabilityCREATE(unittest.TestCase):
"""SalesAvailabilityCREATE unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> SalesAvailabilityCREATE:
"""Test SalesAvailabilityCREATE
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `SalesAvailabilityCREATE`
"""
model = SalesAvailabilityCREATE()
if include_optional:
return SalesAvailabilityCREATE(
id = '0x...',
total_size = '',
duration = '',
min_price = '',
max_collateral = ''
)
else:
return SalesAvailabilityCREATE(
total_size = '',
duration = '',
min_price = '',
max_collateral = '',
)
"""
def testSalesAvailabilityCREATE(self):
"""Test SalesAvailabilityCREATE"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,56 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.sales_availability_read import SalesAvailabilityREAD
class TestSalesAvailabilityREAD(unittest.TestCase):
"""SalesAvailabilityREAD unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> SalesAvailabilityREAD:
"""Test SalesAvailabilityREAD
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `SalesAvailabilityREAD`
"""
model = SalesAvailabilityREAD()
if include_optional:
return SalesAvailabilityREAD(
id = '0x...',
total_size = '',
duration = '',
min_price = '',
max_collateral = '',
free_size = ''
)
else:
return SalesAvailabilityREAD(
)
"""
def testSalesAvailabilityREAD(self):
"""Test SalesAvailabilityREAD"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

72
test/test_slot.py Normal file
View File

@ -0,0 +1,72 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.slot import Slot
class TestSlot(unittest.TestCase):
"""Slot unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> Slot:
"""Test Slot
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Slot`
"""
model = Slot()
if include_optional:
return Slot(
id = '268a781e0db3f7cf36b18e5f4fdb7f586ec9edd08e5500b17c0e518a769f114a',
request = codex_client.models.storage_request.StorageRequest(
id = '',
client = '',
ask = codex_client.models.storage_ask.StorageAsk(
slots = 56,
slot_size = '',
duration = '',
proof_probability = '',
reward = '',
max_slot_loss = 56, ),
content = codex_client.models.content.Content(
cid = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
erasure = codex_client.models.erasure_parameters.ErasureParameters(
total_chunks = 56, ),
por = codex_client.models.po_r_parameters.PoRParameters(
u = '',
public_key = '',
name = '', ), ),
expiry = '10 minutes',
nonce = '', ),
slot_index = ''
)
else:
return Slot(
)
"""
def testSlot(self):
"""Test Slot"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

54
test/test_space.py Normal file
View File

@ -0,0 +1,54 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.space import Space
class TestSpace(unittest.TestCase):
"""Space unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> Space:
"""Test Space
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `Space`
"""
model = Space()
if include_optional:
return Space(
total_blocks = 56,
quota_max_bytes = 56,
quota_used_bytes = 56,
quota_reserved_bytes = 56
)
else:
return Space(
)
"""
def testSpace(self):
"""Test Space"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

51
test/test_spr_read.py Normal file
View File

@ -0,0 +1,51 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.spr_read import SPRRead
class TestSPRRead(unittest.TestCase):
"""SPRRead unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> SPRRead:
"""Test SPRRead
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `SPRRead`
"""
model = SPRRead()
if include_optional:
return SPRRead(
spr = ''
)
else:
return SPRRead(
)
"""
def testSPRRead(self):
"""Test SPRRead"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

57
test/test_storage_ask.py Normal file
View File

@ -0,0 +1,57 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.storage_ask import StorageAsk
class TestStorageAsk(unittest.TestCase):
"""StorageAsk unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> StorageAsk:
"""Test StorageAsk
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `StorageAsk`
"""
model = StorageAsk()
if include_optional:
return StorageAsk(
slots = 56,
slot_size = '',
duration = '',
proof_probability = '',
reward = '',
max_slot_loss = 56
)
else:
return StorageAsk(
reward = '',
)
"""
def testStorageAsk(self):
"""Test StorageAsk"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,69 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.storage_request import StorageRequest
class TestStorageRequest(unittest.TestCase):
"""StorageRequest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> StorageRequest:
"""Test StorageRequest
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `StorageRequest`
"""
model = StorageRequest()
if include_optional:
return StorageRequest(
id = '',
client = '',
ask = codex_client.models.storage_ask.StorageAsk(
slots = 56,
slot_size = '',
duration = '',
proof_probability = '',
reward = '',
max_slot_loss = 56, ),
content = codex_client.models.content.Content(
cid = 'QmYyQSo1c1Ym7orWxLYvCrM2EmxFTANf8wXmmE7DWjhx5N',
erasure = codex_client.models.erasure_parameters.ErasureParameters(
total_chunks = 56, ),
por = codex_client.models.po_r_parameters.PoRParameters(
u = '',
public_key = '',
name = '', ), ),
expiry = '10 minutes',
nonce = ''
)
else:
return StorageRequest(
)
"""
def testStorageRequest(self):
"""Test StorageRequest"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,62 @@
# coding: utf-8
"""
Codex API
List of endpoints and interfaces available to Codex API users
The version of the OpenAPI document: 0.0.1
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from codex_client.models.storage_request_creation import StorageRequestCreation
class TestStorageRequestCreation(unittest.TestCase):
"""StorageRequestCreation unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> StorageRequestCreation:
"""Test StorageRequestCreation
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `StorageRequestCreation`
"""
model = StorageRequestCreation()
if include_optional:
return StorageRequestCreation(
duration = '',
reward = '',
proof_probability = '',
nodes = 56,
tolerance = 56,
collateral = '',
expiry = ''
)
else:
return StorageRequestCreation(
duration = '',
reward = '',
proof_probability = '',
collateral = '',
expiry = '',
)
"""
def testStorageRequestCreation(self):
"""Test StorageRequestCreation"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()

9
tox.ini Normal file
View File

@ -0,0 +1,9 @@
[tox]
envlist = py3
[testenv]
deps=-r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements.txt
commands=
pytest --cov=codex_client