diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..4b370c0 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,26 @@ +# This workflows will upload a Python Package using Twine when a release is created +# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries + +name: Upload Python Package + +on: + push: + tags: + - "v*" + +jobs: + deploy: + + runs-on: ubuntu-latest + container: setsoft/kicad_pybuild:latest + + steps: + - uses: actions/checkout@v2 + + - name: Build and publish + env: + TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + run: | + python3 setup.py sdist bdist_wheel + twine upload dist/* diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..216248d --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,86 @@ +name: release + +on: + push: + tags-ignore: + - "v1" + - "v1_k6" + - "v2" + - "v2_k6" + - "v3" + - "v3_k6" + - "v4" + - "v4_k6" + +jobs: + check: + runs-on: ubuntu-latest + outputs: + is_tag: ${{ steps.check.outputs.is_tag }} + + steps: + - name: Check if it's a tagged release + id: check + run: | + REF=${{ github.ref }} + URL="https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/tags/${REF##*/}" + StatusCode=$(curl -o -I -L -s -w "%{http_code}" -X GET -G $URL) + echo $StatusCode + if [[ "$StatusCode" == 200 ]]; then + echo "This is tagged release!" + echo "::set-output name=is_tag::no" + else + echo "This is a tag not release!" + echo "::set-output name=is_tag::yes" + fi + + build: + runs-on: ubuntu-latest + container: setsoft/kicad_pybuild:latest + needs: check + if: ${{ needs.check.outputs.is_tag == 'yes' }} + outputs: + deb_name: ${{ steps.mdeb.outputs.deb_name }} + + steps: + - name: Checkout + uses: actions/checkout@v1 + + - name: Build + id: mdeb + run: | + make deb + mv ../*.deb . + echo "::set-output name=deb_name::"`ls *.deb` + mkdir output + mv *.deb output + + - name: Store + uses: actions/upload-artifact@v1 + with: + name: package + path: output + + release: + needs: build + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v1 + + - name: Retrieve + uses: actions/download-artifact@v1 + with: + name: package + + - name: Release + uses: docker://antonyurchenko/git-release:latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DRAFT_RELEASE: "false" + PRE_RELEASE: "false" + CHANGELOG_FILE: "CHANGELOG.md" + with: + args: | + package/${{needs.build.outputs.deb_name}} + diff --git a/.gitignore b/.gitignore index bc64f33..e98bc00 100644 --- a/.gitignore +++ b/.gitignore @@ -73,3 +73,5 @@ generate-v3-api/ # Other repository dependent tests/local/ .env/config.ini + +*.epr diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8c6061a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,26 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.1.3] - 2023-11-08 +### Added +- Support for Python 3.12 (ssl.wrap_socket no longer available) + +## [0.1.2] - 2022-10-06 +### Added +- Option to exclude marketpace products + +### Fixed +- Problems when a Digi-Key query gives time-out + +## [0.1.1] - 2022-03-21 +### Fixed +- Requirements + +## [0.1.0] - 2022-03-21 +### Added +- First release diff --git a/MANIFEST.in b/MANIFEST.in index e69de29..f9bd145 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -0,0 +1 @@ +include requirements.txt diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..900f692 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +#!/usr/bin/make + +deb: + DEB_BUILD_OPTIONS=nocheck fakeroot dpkg-buildpackage -uc -b + +deb_sig: + DEB_BUILD_OPTIONS=nocheck fakeroot dpkg-buildpackage -b + +deb_clean: + fakeroot debian/rules clean + + +.PHONY: deb deb_clean diff --git a/README.md b/README.md index aefcff5..4630bc0 100644 --- a/README.md +++ b/README.md @@ -1,143 +1,47 @@ -Python Client for Digikey API +KiCost plug-in for Digi-Key API ================================= -Search for parts in the Digi-Key catalog by keyword using KeywordSearch. Then make a PartDetails call to retrieve all -real time information about the part including pricing. PartDetails works best with Digi-Key part numbers as some -manufacturers overlap other manufacturer part numbers. +This is an experimental plug-in to allow KiCost to do native Digi-Key API requests. -[![Pypi](https://img.shields.io/pypi/v/digikey-api.svg?color=brightgreen)](https://pypi.org/project/digikey-api/) -[![Donate](https://img.shields.io/badge/Donate-PayPal-gold.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=53HWHHVCJ3D4J¤cy_code=EUR&source=url) +The plug-in is based on the [Python Client for Digikey API](https://github.com/peeter123/digikey-api) +by [Peter Oostewechel](https://github.com/peeter123). -# What does it do -`digikey-api` is an [Digkey Part Search API](https://api-portal.digikey.com/node/8517) client for Python 3.6+. API response data is returned as Python objects that attempt to make it easy to get the data you want. Not all endpoints have been implemented. +I'm not using the original project as a module because it pulls some rare dependencies. -# Quickstart - -## Install -```sh -pip install digikey-api - -export DIGIKEY_CLIENT_ID="client_id" -export DIGIKEY_CLIENT_SECRET="client_secret" -export DIGIKEY_STORAGE_PATH="cache_dir" -``` - -# API V3 -## Register -Register an app on the Digikey API portal: [Digi-Key API V3](https://developer.digikey.com/get_started). You will need -the client ID and the client secret to use the API. You will also need a Digi-Key account to authenticate, using the -Oauth2 process. - -When registering an app the OAuth Callback needs to be set to `https://localhost:8139/digikey_callback`. - -## Use [API V3] -Python will automatically spawn a browser to allow you to authenticate using the Oauth2 process. After obtaining a token -the library will cache the access token and use the refresh token to automatically refresh your credentials. - -You can test your application using the sandbox API, the data returned from a Sandbox API may not be complete, but the -structure of the Sandbox API response will be a representation of what to expect in Production. - -For valid responses make sure you use the client ID and secret for a [Production App](https://developer.digikey.com/documentation/organization) - -```python -import os -import digikey -from digikey.v3.productinformation import KeywordSearchRequest - -os.environ['DIGIKEY_CLIENT_ID'] = 'client_id' -os.environ['DIGIKEY_CLIENT_SECRET'] = 'client_secret' -os.environ['DIGIKEY_CLIENT_SANDBOX'] = 'False' -os.environ['DIGIKEY_STORAGE_PATH'] = 'cache_dir' - -# Query product number -dkpn = '296-6501-1-ND' -part = digikey.product_details(dkpn) - -# Search for parts -search_request = KeywordSearchRequest(keywords='CRCW080510K0FKEA', record_count=10) -result = digikey.keyword_search(body=search_request) -``` - -## Top-level APIs +The license is GPL v3 as the original work. -#### Product Information -All functions from the [PartSearch](https://developer.digikey.com/products/product-information/partsearch/) API have been implemented. -* `digikey.keyword_search()` -* `digikey.product_details()` -* `digikey.digi_reel_pricing()` -* `digikey.suggested_parts()` -* `digikey.manufacturer_product_details()` - -#### Batch Product Details -The one function from the [BatchProductDetailsAPI](https://developer.digikey.com/products/batch-productdetails/batchproductdetailsapi) API has been implemented. -* `digikey.batch_product_details()` - -#### Order Support -All functions from the [OrderDetails](https://developer.digikey.com/products/order-support/orderdetails/) API have been implemented. -* `digikey.salesorder_history()` -* `digikey.status_salesorder_id()` - -#### Barcode -TODO - -## API Limits -The API has a limited amount of requests you can make per time interval [Digikey Rate Limits](https://developer.digikey.com/documentation/shared-concepts#rate-limits). - -It is possible to retrieve the number of max requests and current requests by passing an optional api_limits kwarg to an API function: -```python -api_limit = {} -search_request = KeywordSearchRequest(keywords='CRCW080510K0FKEA', record_count=10) -result = digikey.keyword_search(body=search_request, api_limits=api_limit) -``` - -The dict will be filled with the information returned from the API: -```python -{ - 'api_requests_limit': 1000, - 'api_requests_remaining': 139 -} -``` -Sometimes the API does not return any rate limit data, the values will then be set to None. - -# API V2 [Deprecated] -**NOTE: API V2 is not supported anymore by Digi-Key and you cannot register new applications** - -See API V3 above to use the new API. - -## Register -Register an app on the Digikey API portal: [Digi-Key API V2](https://api-portal.digikey.com/start). You will need the client -ID and the client secret to use the API. You will also need a Digi-Key account to authenticate, using the Oauth2 process. - -## Use -Python will automatically spawn a browser to allow you to authenticate using the Oauth2 process. After obtaining a token -the library will cache the access token and use the refresh token to automatically refresh your credentials. - -```python -import os -import digikey - -os.environ['DIGIKEY_CLIENT_ID'] = 'client_id' -os.environ['DIGIKEY_CLIENT_SECRET'] = 'client_secret' -os.environ['DIGIKEY_STORAGE_PATH'] = 'cache_dir' +# Quickstart -dkpn = '296-6501-1-ND' -part = digikey.part(dkpn) -print(part) -# +- Register at Digi-Key. You need a valid user in order to register an application and in order to authenticate. +- Go to the API portal: [Digi-Key API Solutions](https://developer.digikey.com/get_started) +- Login to Digi-Key from the API portal +- Create an [organization](https://developer.digikey.com/teams) +- Choose the `Production Apps` operation +- Create a production app + - Choose a `Production App name` + - Use `https://localhost:8139/digikey_callback` for the OAuth Callback. So you can authorize the use of the app. + - Give a description + - Enable the `Product Information` API + - Click `Add production app` +- Now select your newly created `Production App` +- In the `Credential` section enable the options to show the `Client ID` and `Client Secret` +- Copy these values to a file named `config.txt` containing: -print(part.manufacturer) -# 'Texas Instruments' ``` - -## Test -```sh -python -m pytest --cov=digikey --doctest-modules --ignore=setup.py -python -m mypy digikey --ignore-missing-imports +DIGIKEY_CLIENT_ID = Client_ID_Value_for_your_app +DIGIKEY_CLIENT_SECRET = Client_Secret_Value_for_your_app ``` -## Top-level API -* `digikey.search()` -* `digikey.part()` +- Create a folder `~/.config/kicost_digikey_api_v3` +- Store the config.txt file +- Now install the plug-in: + - Clone the git repo somewhere using `git clone https://github.com/set-soft/kicost-digikey-api-v3.git` + - Enter to `kicost-digikey-api-v3` + - Install it using `pip3 install -e .` +- Now test the plug-in: + - run `python3 test_production.py` + - A browser window will pop-up asking to login to Digi-Key. Login. + - Choose the allow option to enable the token. + - Now you'll load a local page, allow it. + - Now the token is stored on disk and you won't need to confirm it for months. + - You should get the information for Digi-Key part 296-6501-6-ND -## Data models -* `digikey.models.KeywordSearchResult` -* `digikey.models.Part` \ No newline at end of file diff --git a/debian/README.Debian b/debian/README.Debian new file mode 100644 index 0000000..8b41c4e --- /dev/null +++ b/debian/README.Debian @@ -0,0 +1,8 @@ +kicost-digikey-api-v3 for Debian + +Please edit this to provide information specific to +this kicost-digikey-api-v3 Debian package. + + (Automatically generated by debmake Version 4.3.2) + + -- Salvador E. Tropea <> Mon, 21 Mar 2022 16:06:37 -0300 diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..d0abf9f --- /dev/null +++ b/debian/changelog @@ -0,0 +1,24 @@ +kicost-digikey-api-v3 (0.1.3-1) stable; urgency=medium + + * Added support for Python 3.12 + + -- Salvador E. Tropea Wed, 08 Nov 2023 08:58:30 -0300 + +kicost-digikey-api-v3 (0.1.2-1) stable; urgency=medium + + * Added option to exclude market place results + * Fixed problems when digi-key times out + + -- Salvador E. Tropea Thu, 06 Oct 2022 09:43:00 -0300 + +kicost-digikey-api-v3 (0.1.1-1) stable; urgency=medium + + * New upstream release + + -- Salvador E. Tropea Mon, 21 Mar 2022 16:55:01 -0300 + +kicost-digikey-api-v3 (0.1.0-1) stable; urgency=low + + * Initial release. + + -- Salvador E. Tropea Mon, 21 Mar 2022 16:06:37 -0300 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..a4e3644 --- /dev/null +++ b/debian/control @@ -0,0 +1,15 @@ +Source: kicost-digikey-api-v3 +Section: electronics +Priority: optional +Maintainer: Salvador E. Tropea +Build-Depends: debhelper-compat (= 12), dh-python, python3-all +Standards-Version: 4.5.0 +Homepage: https://github.com/set-soft/kicost-digikey-api-v3/ +X-Python3-Version: >= 3.2 + +Package: kicost-digikey-api-v3 +Architecture: all +Multi-Arch: foreign +Depends: ${misc:Depends}, ${python3:Depends} +Description: Digi-Key API plug-in for KiCost + This package adds native support for Digi-Key to KiCost. diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..ef58965 --- /dev/null +++ b/debian/copyright @@ -0,0 +1,775 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: kicost-digikey-api-v3 +Upstream-Contact: +Source: +# +# Please double check copyright with the licensecheck(1) command. + +Files: README.md + generate-v3-api/generage_client_swagger.py + kicost_digikey_api_v3/__init__.py + kicost_digikey_api_v3/certauth/__init__.py + kicost_digikey_api_v3/certauth/certauth.py + kicost_digikey_api_v3/exceptions.py + kicost_digikey_api_v3/oauth/__init__.py + kicost_digikey_api_v3/oauth/oauth2.py + kicost_digikey_api_v3/v3/__init__.py + kicost_digikey_api_v3/v3/api.py + kicost_digikey_api_v3/v3/productinformation/__init__.py + kicost_digikey_api_v3/v3/productinformation/api/__init__.py + kicost_digikey_api_v3/v3/productinformation/api/part_search_api.py + kicost_digikey_api_v3/v3/productinformation/api_client.py + kicost_digikey_api_v3/v3/productinformation/configuration.py + kicost_digikey_api_v3/v3/productinformation/models/__init__.py + kicost_digikey_api_v3/v3/productinformation/models/api_error_response.py + kicost_digikey_api_v3/v3/productinformation/models/api_validation_error.py + kicost_digikey_api_v3/v3/productinformation/models/associated_product.py + kicost_digikey_api_v3/v3/productinformation/models/basic_product.py + kicost_digikey_api_v3/v3/productinformation/models/digi_reel_pricing.py + kicost_digikey_api_v3/v3/productinformation/models/filters.py + kicost_digikey_api_v3/v3/productinformation/models/iso_search_locale.py + kicost_digikey_api_v3/v3/productinformation/models/keyword_search_request.py + kicost_digikey_api_v3/v3/productinformation/models/keyword_search_response.py + kicost_digikey_api_v3/v3/productinformation/models/kit_part.py + kicost_digikey_api_v3/v3/productinformation/models/limited_parameter.py + kicost_digikey_api_v3/v3/productinformation/models/limited_taxonomy.py + kicost_digikey_api_v3/v3/productinformation/models/manufacturer_product_details_request.py + kicost_digikey_api_v3/v3/productinformation/models/media_links.py + kicost_digikey_api_v3/v3/productinformation/models/parametric_filter.py + kicost_digikey_api_v3/v3/productinformation/models/pid_vid.py + kicost_digikey_api_v3/v3/productinformation/models/price_break.py + kicost_digikey_api_v3/v3/productinformation/models/product.py + kicost_digikey_api_v3/v3/productinformation/models/product_details.py + kicost_digikey_api_v3/v3/productinformation/models/product_details_response.py + kicost_digikey_api_v3/v3/productinformation/models/result_code.py + kicost_digikey_api_v3/v3/productinformation/models/search_option.py + kicost_digikey_api_v3/v3/productinformation/models/sort_direction.py + kicost_digikey_api_v3/v3/productinformation/models/sort_option.py + kicost_digikey_api_v3/v3/productinformation/models/sort_parameters.py + kicost_digikey_api_v3/v3/productinformation/models/value_pair.py + kicost_digikey_api_v3/v3/productinformation/rest.py + setup.py + test_production.py + tests/__init__.py + tests/fixtures.py + tests/responses/keywordsearch_response.json + tests/responses/oauth2_response.json + tests/test_oauth2.py + tests/utils.py + tests/v3/ordersupport/__init__.py + tests/v3/ordersupport/test_address.py + tests/v3/ordersupport/test_api_error_response.py + tests/v3/ordersupport/test_api_validation_error.py + tests/v3/ordersupport/test_line_item.py + tests/v3/ordersupport/test_order_details_api.py + tests/v3/ordersupport/test_order_status_response.py + tests/v3/ordersupport/test_salesorder_history_item.py + tests/v3/ordersupport/test_schedule.py + tests/v3/ordersupport/test_shipping_detail.py + tests/v3/productinformation/__init__.py + tests/v3/productinformation/test_api_error_response.py + tests/v3/productinformation/test_api_validation_error.py + tests/v3/productinformation/test_basic_product.py + tests/v3/productinformation/test_digi_reel_pricing.py + tests/v3/productinformation/test_filters.py + tests/v3/productinformation/test_iso_search_locale.py + tests/v3/productinformation/test_keyword_search_request.py + tests/v3/productinformation/test_keyword_search_response.py + tests/v3/productinformation/test_limited_parameter.py + tests/v3/productinformation/test_limited_taxonomy.py + tests/v3/productinformation/test_manufacturer_product_details_request.py + tests/v3/productinformation/test_parametric_filter.py + tests/v3/productinformation/test_part_search_api.py + tests/v3/productinformation/test_pid_vid.py + tests/v3/productinformation/test_price_break.py + tests/v3/productinformation/test_product.py + tests/v3/productinformation/test_product_details.py + tests/v3/productinformation/test_search_option.py + tests/v3/productinformation/test_sort_direction.py + tests/v3/productinformation/test_sort_option.py + tests/v3/productinformation/test_sort_parameters.py + tests/v3/productinformation/test_value_pair.py + tools/user_agent.py +Copyright: __NO_COPYRIGHT_NOR_LICENSE__ +License: GPL-3.0 + +Files: kicost_digikey_api_v3/utils.py +Copyright: 2021 Salvador E. Tropea / Instituto Nacional de Tecnologia Industrial +License: GPL-3.0 + +#---------------------------------------------------------------------------- +# License file: LICENSE + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + . + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + . + Preamble + . + The GNU General Public License is a free, copyleft license for + software and other kinds of works. + . + The licenses for most software and other practical works are designed + to take away your freedom to share and change the works. By contrast, + the GNU General Public License is intended to guarantee your freedom to + share and change all versions of a program--to make sure it remains free + software for all its users. We, the Free Software Foundation, use the + GNU General Public License for most of our software; it applies also to + any other work released this way by its authors. You can apply it to + your programs, too. + . + When we speak of free software, we are referring to freedom, not + price. Our General Public Licenses are designed to make sure that you + have the freedom to distribute copies of free software (and charge for + them if you wish), that you receive source code or can get it if you + want it, that you can change the software or use pieces of it in new + free programs, and that you know you can do these things. + . + To protect your rights, we need to prevent others from denying you + these rights or asking you to surrender the rights. Therefore, you have + certain responsibilities if you distribute copies of the software, or if + you modify it: responsibilities to respect the freedom of others. + . + For example, if you distribute copies of such a program, whether + gratis or for a fee, you must pass on to the recipients the same + freedoms that you received. You must make sure that they, too, receive + or can get the source code. And you must show them these terms so they + know their rights. + . + Developers that use the GNU GPL protect your rights with two steps: + (1) assert copyright on the software, and (2) offer you this License + giving you legal permission to copy, distribute and/or modify it. + . + For the developers' and authors' protection, the GPL clearly explains + that there is no warranty for this free software. For both users' and + authors' sake, the GPL requires that modified versions be marked as + changed, so that their problems will not be attributed erroneously to + authors of previous versions. + . + Some devices are designed to deny users access to install or run + modified versions of the software inside them, although the manufacturer + can do so. This is fundamentally incompatible with the aim of + protecting users' freedom to change the software. The systematic + pattern of such abuse occurs in the area of products for individuals to + use, which is precisely where it is most unacceptable. Therefore, we + have designed this version of the GPL to prohibit the practice for those + products. If such problems arise substantially in other domains, we + stand ready to extend this provision to those domains in future versions + of the GPL, as needed to protect the freedom of users. + . + Finally, every program is threatened constantly by software patents. + States should not allow patents to restrict development and use of + software on general-purpose computers, but in those that do, we wish to + avoid the special danger that patents applied to a free program could + make it effectively proprietary. To prevent this, the GPL assures that + patents cannot be used to render the program non-free. + . + The precise terms and conditions for copying, distribution and + modification follow. + . + TERMS AND CONDITIONS + . + 0. Definitions. + . + "This License" refers to version 3 of the GNU General Public License. + . + "Copyright" also means copyright-like laws that apply to other kinds of + works, such as semiconductor masks. + . + "The Program" refers to any copyrightable work licensed under this + License. Each licensee is addressed as "you". "Licensees" and + "recipients" may be individuals or organizations. + . + To "modify" a work means to copy from or adapt all or part of the work + in a fashion requiring copyright permission, other than the making of an + exact copy. The resulting work is called a "modified version" of the + earlier work or a work "based on" the earlier work. + . + A "covered work" means either the unmodified Program or a work based + on the Program. + . + To "propagate" a work means to do anything with it that, without + permission, would make you directly or secondarily liable for + infringement under applicable copyright law, except executing it on a + computer or modifying a private copy. Propagation includes copying, + distribution (with or without modification), making available to the + public, and in some countries other activities as well. + . + To "convey" a work means any kind of propagation that enables other + parties to make or receive copies. Mere interaction with a user through + a computer network, with no transfer of a copy, is not conveying. + . + An interactive user interface displays "Appropriate Legal Notices" + to the extent that it includes a convenient and prominently visible + feature that (1) displays an appropriate copyright notice, and (2) + tells the user that there is no warranty for the work (except to the + extent that warranties are provided), that licensees may convey the + work under this License, and how to view a copy of this License. If + the interface presents a list of user commands or options, such as a + menu, a prominent item in the list meets this criterion. + . + 1. Source Code. + . + The "source code" for a work means the preferred form of the work + for making modifications to it. "Object code" means any non-source + form of a work. + . + A "Standard Interface" means an interface that either is an official + standard defined by a recognized standards body, or, in the case of + interfaces specified for a particular programming language, one that + is widely used among developers working in that language. + . + The "System Libraries" of an executable work include anything, other + than the work as a whole, that (a) is included in the normal form of + packaging a Major Component, but which is not part of that Major + Component, and (b) serves only to enable use of the work with that + Major Component, or to implement a Standard Interface for which an + implementation is available to the public in source code form. A + "Major Component", in this context, means a major essential component + (kernel, window system, and so on) of the specific operating system + (if any) on which the executable work runs, or a compiler used to + produce the work, or an object code interpreter used to run it. + . + The "Corresponding Source" for a work in object code form means all + the source code needed to generate, install, and (for an executable + work) run the object code and to modify the work, including scripts to + control those activities. However, it does not include the work's + System Libraries, or general-purpose tools or generally available free + programs which are used unmodified in performing those activities but + which are not part of the work. For example, Corresponding Source + includes interface definition files associated with source files for + the work, and the source code for shared libraries and dynamically + linked subprograms that the work is specifically designed to require, + such as by intimate data communication or control flow between those + subprograms and other parts of the work. + . + The Corresponding Source need not include anything that users + can regenerate automatically from other parts of the Corresponding + Source. + . + The Corresponding Source for a work in source code form is that + same work. + . + 2. Basic Permissions. + . + All rights granted under this License are granted for the term of + copyright on the Program, and are irrevocable provided the stated + conditions are met. This License explicitly affirms your unlimited + permission to run the unmodified Program. The output from running a + covered work is covered by this License only if the output, given its + content, constitutes a covered work. This License acknowledges your + rights of fair use or other equivalent, as provided by copyright law. + . + You may make, run and propagate covered works that you do not + convey, without conditions so long as your license otherwise remains + in force. You may convey covered works to others for the sole purpose + of having them make modifications exclusively for you, or provide you + with facilities for running those works, provided that you comply with + the terms of this License in conveying all material for which you do + not control copyright. Those thus making or running the covered works + for you must do so exclusively on your behalf, under your direction + and control, on terms that prohibit them from making any copies of + your copyrighted material outside their relationship with you. + . + Conveying under any other circumstances is permitted solely under + the conditions stated below. Sublicensing is not allowed; section 10 + makes it unnecessary. + . + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + . + No covered work shall be deemed part of an effective technological + measure under any applicable law fulfilling obligations under article + 11 of the WIPO copyright treaty adopted on 20 December 1996, or + similar laws prohibiting or restricting circumvention of such + measures. + . + When you convey a covered work, you waive any legal power to forbid + circumvention of technological measures to the extent such circumvention + is effected by exercising rights under this License with respect to + the covered work, and you disclaim any intention to limit operation or + modification of the work as a means of enforcing, against the work's + users, your or third parties' legal rights to forbid circumvention of + technological measures. + . + 4. Conveying Verbatim Copies. + . + You may convey verbatim copies of the Program's source code as you + receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy an appropriate copyright notice; + keep intact all notices stating that this License and any + non-permissive terms added in accord with section 7 apply to the code; + keep intact all notices of the absence of any warranty; and give all + recipients a copy of this License along with the Program. + . + You may charge any price or no price for each copy that you convey, + and you may offer support or warranty protection for a fee. + . + 5. Conveying Modified Source Versions. + . + You may convey a work based on the Program, or the modifications to + produce it from the Program, in the form of source code under the + terms of section 4, provided that you also meet all of these conditions: + . + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + . + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + . + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + . + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + . + A compilation of a covered work with other separate and independent + works, which are not by their nature extensions of the covered work, + and which are not combined with it such as to form a larger program, + in or on a volume of a storage or distribution medium, is called an + "aggregate" if the compilation and its resulting copyright are not + used to limit the access or legal rights of the compilation's users + beyond what the individual works permit. Inclusion of a covered work + in an aggregate does not cause this License to apply to the other + parts of the aggregate. + . + 6. Conveying Non-Source Forms. + . + You may convey a covered work in object code form under the terms + of sections 4 and 5, provided that you also convey the + machine-readable Corresponding Source under the terms of this License, + in one of these ways: + . + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + . + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + . + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + . + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + . + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + . + A separable portion of the object code, whose source code is excluded + from the Corresponding Source as a System Library, need not be + included in conveying the object code work. + . + A "User Product" is either (1) a "consumer product", which means any + tangible personal property which is normally used for personal, family, + or household purposes, or (2) anything designed or sold for incorporation + into a dwelling. In determining whether a product is a consumer product, + doubtful cases shall be resolved in favor of coverage. For a particular + product received by a particular user, "normally used" refers to a + typical or common use of that class of product, regardless of the status + of the particular user or of the way in which the particular user + actually uses, or expects or is expected to use, the product. A product + is a consumer product regardless of whether the product has substantial + commercial, industrial or non-consumer uses, unless such uses represent + the only significant mode of use of the product. + . + "Installation Information" for a User Product means any methods, + procedures, authorization keys, or other information required to install + and execute modified versions of a covered work in that User Product from + a modified version of its Corresponding Source. The information must + suffice to ensure that the continued functioning of the modified object + code is in no case prevented or interfered with solely because + modification has been made. + . + If you convey an object code work under this section in, or with, or + specifically for use in, a User Product, and the conveying occurs as + part of a transaction in which the right of possession and use of the + User Product is transferred to the recipient in perpetuity or for a + fixed term (regardless of how the transaction is characterized), the + Corresponding Source conveyed under this section must be accompanied + by the Installation Information. But this requirement does not apply + if neither you nor any third party retains the ability to install + modified object code on the User Product (for example, the work has + been installed in ROM). + . + The requirement to provide Installation Information does not include a + requirement to continue to provide support service, warranty, or updates + for a work that has been modified or installed by the recipient, or for + the User Product in which it has been modified or installed. Access to a + network may be denied when the modification itself materially and + adversely affects the operation of the network or violates the rules and + protocols for communication across the network. + . + Corresponding Source conveyed, and Installation Information provided, + in accord with this section must be in a format that is publicly + documented (and with an implementation available to the public in + source code form), and must require no special password or key for + unpacking, reading or copying. + . + 7. Additional Terms. + . + "Additional permissions" are terms that supplement the terms of this + License by making exceptions from one or more of its conditions. + Additional permissions that are applicable to the entire Program shall + be treated as though they were included in this License, to the extent + that they are valid under applicable law. If additional permissions + apply only to part of the Program, that part may be used separately + under those permissions, but the entire Program remains governed by + this License without regard to the additional permissions. + . + When you convey a copy of a covered work, you may at your option + remove any additional permissions from that copy, or from any part of + it. (Additional permissions may be written to require their own + removal in certain cases when you modify the work.) You may place + additional permissions on material, added by you to a covered work, + for which you have or can give appropriate copyright permission. + . + Notwithstanding any other provision of this License, for material you + add to a covered work, you may (if authorized by the copyright holders of + that material) supplement the terms of this License with terms: + . + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + . + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + . + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + . + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + . + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + . + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + . + All other non-permissive additional terms are considered "further + restrictions" within the meaning of section 10. If the Program as you + received it, or any part of it, contains a notice stating that it is + governed by this License along with a term that is a further + restriction, you may remove that term. If a license document contains + a further restriction but permits relicensing or conveying under this + License, you may add to a covered work material governed by the terms + of that license document, provided that the further restriction does + not survive such relicensing or conveying. + . + If you add terms to a covered work in accord with this section, you + must place, in the relevant source files, a statement of the + additional terms that apply to those files, or a notice indicating + where to find the applicable terms. + . + Additional terms, permissive or non-permissive, may be stated in the + form of a separately written license, or stated as exceptions; + the above requirements apply either way. + . + 8. Termination. + . + You may not propagate or modify a covered work except as expressly + provided under this License. Any attempt otherwise to propagate or + modify it is void, and will automatically terminate your rights under + this License (including any patent licenses granted under the third + paragraph of section 11). + . + However, if you cease all violation of this License, then your + license from a particular copyright holder is reinstated (a) + provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and (b) permanently, if the copyright + holder fails to notify you of the violation by some reasonable means + prior to 60 days after the cessation. + . + Moreover, your license from a particular copyright holder is + reinstated permanently if the copyright holder notifies you of the + violation by some reasonable means, this is the first time you have + received notice of violation of this License (for any work) from that + copyright holder, and you cure the violation prior to 30 days after + your receipt of the notice. + . + Termination of your rights under this section does not terminate the + licenses of parties who have received copies or rights from you under + this License. If your rights have been terminated and not permanently + reinstated, you do not qualify to receive new licenses for the same + material under section 10. + . + 9. Acceptance Not Required for Having Copies. + . + You are not required to accept this License in order to receive or + run a copy of the Program. Ancillary propagation of a covered work + occurring solely as a consequence of using peer-to-peer transmission + to receive a copy likewise does not require acceptance. However, + nothing other than this License grants you permission to propagate or + modify any covered work. These actions infringe copyright if you do + not accept this License. Therefore, by modifying or propagating a + covered work, you indicate your acceptance of this License to do so. + . + 10. Automatic Licensing of Downstream Recipients. + . + Each time you convey a covered work, the recipient automatically + receives a license from the original licensors, to run, modify and + propagate that work, subject to this License. You are not responsible + for enforcing compliance by third parties with this License. + . + An "entity transaction" is a transaction transferring control of an + organization, or substantially all assets of one, or subdividing an + organization, or merging organizations. If propagation of a covered + work results from an entity transaction, each party to that + transaction who receives a copy of the work also receives whatever + licenses to the work the party's predecessor in interest had or could + give under the previous paragraph, plus a right to possession of the + Corresponding Source of the work from the predecessor in interest, if + the predecessor has it or can get it with reasonable efforts. + . + You may not impose any further restrictions on the exercise of the + rights granted or affirmed under this License. For example, you may + not impose a license fee, royalty, or other charge for exercise of + rights granted under this License, and you may not initiate litigation + (including a cross-claim or counterclaim in a lawsuit) alleging that + any patent claim is infringed by making, using, selling, offering for + sale, or importing the Program or any portion of it. + . + 11. Patents. + . + A "contributor" is a copyright holder who authorizes use under this + License of the Program or a work on which the Program is based. The + work thus licensed is called the contributor's "contributor version". + . + A contributor's "essential patent claims" are all patent claims + owned or controlled by the contributor, whether already acquired or + hereafter acquired, that would be infringed by some manner, permitted + by this License, of making, using, or selling its contributor version, + but do not include claims that would be infringed only as a + consequence of further modification of the contributor version. For + purposes of this definition, "control" includes the right to grant + patent sublicenses in a manner consistent with the requirements of + this License. + . + Each contributor grants you a non-exclusive, worldwide, royalty-free + patent license under the contributor's essential patent claims, to + make, use, sell, offer for sale, import and otherwise run, modify and + propagate the contents of its contributor version. + . + In the following three paragraphs, a "patent license" is any express + agreement or commitment, however denominated, not to enforce a patent + (such as an express permission to practice a patent or covenant not to + sue for patent infringement). To "grant" such a patent license to a + party means to make such an agreement or commitment not to enforce a + patent against the party. + . + If you convey a covered work, knowingly relying on a patent license, + and the Corresponding Source of the work is not available for anyone + to copy, free of charge and under the terms of this License, through a + publicly available network server or other readily accessible means, + then you must either (1) cause the Corresponding Source to be so + available, or (2) arrange to deprive yourself of the benefit of the + patent license for this particular work, or (3) arrange, in a manner + consistent with the requirements of this License, to extend the patent + license to downstream recipients. "Knowingly relying" means you have + actual knowledge that, but for the patent license, your conveying the + covered work in a country, or your recipient's use of the covered work + in a country, would infringe one or more identifiable patents in that + country that you have reason to believe are valid. + . + If, pursuant to or in connection with a single transaction or + arrangement, you convey, or propagate by procuring conveyance of, a + covered work, and grant a patent license to some of the parties + receiving the covered work authorizing them to use, propagate, modify + or convey a specific copy of the covered work, then the patent license + you grant is automatically extended to all recipients of the covered + work and works based on it. + . + A patent license is "discriminatory" if it does not include within + the scope of its coverage, prohibits the exercise of, or is + conditioned on the non-exercise of one or more of the rights that are + specifically granted under this License. You may not convey a covered + work if you are a party to an arrangement with a third party that is + in the business of distributing software, under which you make payment + to the third party based on the extent of your activity of conveying + the work, and under which the third party grants, to any of the + parties who would receive the covered work from you, a discriminatory + patent license (a) in connection with copies of the covered work + conveyed by you (or copies made from those copies), or (b) primarily + for and in connection with specific products or compilations that + contain the covered work, unless you entered into that arrangement, + or that patent license was granted, prior to 28 March 2007. + . + Nothing in this License shall be construed as excluding or limiting + any implied license or other defenses to infringement that may + otherwise be available to you under applicable patent law. + . + 12. No Surrender of Others' Freedom. + . + If conditions are imposed on you (whether by court order, agreement or + otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot convey a + covered work so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you may + not convey it at all. For example, if you agree to terms that obligate you + to collect a royalty for further conveying from those to whom you convey + the Program, the only way you could satisfy both those terms and this + License would be to refrain entirely from conveying the Program. + . + 13. Use with the GNU Affero General Public License. + . + Notwithstanding any other provision of this License, you have + permission to link or combine any covered work with a work licensed + under version 3 of the GNU Affero General Public License into a single + combined work, and to convey the resulting work. The terms of this + License will continue to apply to the part which is the covered work, + but the special requirements of the GNU Affero General Public License, + section 13, concerning interaction through a network will apply to the + combination as such. + . + 14. Revised Versions of this License. + . + The Free Software Foundation may publish revised and/or new versions of + the GNU General Public License from time to time. Such new versions will + be similar in spirit to the present version, but may differ in detail to + address new problems or concerns. + . + Each version is given a distinguishing version number. If the + Program specifies that a certain numbered version of the GNU General + Public License "or any later version" applies to it, you have the + option of following the terms and conditions either of that numbered + version or of any later version published by the Free Software + Foundation. If the Program does not specify a version number of the + GNU General Public License, you may choose any version ever published + by the Free Software Foundation. + . + If the Program specifies that a proxy can decide which future + versions of the GNU General Public License can be used, that proxy's + public statement of acceptance of a version permanently authorizes you + to choose that version for the Program. + . + Later license versions may give you additional or different + permissions. However, no additional obligations are imposed on any + author or copyright holder as a result of your choosing to follow a + later version. + . + 15. Disclaimer of Warranty. + . + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY + APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT + HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY + OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM + IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF + ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + . + 16. Limitation of Liability. + . + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS + THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY + GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE + USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF + DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD + PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), + EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF + SUCH DAMAGES. + . + 17. Interpretation of Sections 15 and 16. + . + If the disclaimer of warranty and limitation of liability provided + above cannot be given local legal effect according to their terms, + reviewing courts shall apply local law that most closely approximates + an absolute waiver of all civil liability in connection with the + Program, unless a warranty or assumption of liability accompanies a + copy of the Program in return for a fee. + . + END OF TERMS AND CONDITIONS + . + How to Apply These Terms to Your New Programs + . + If you develop a new program, and you want it to be of the greatest + possible use to the public, the best way to achieve this is to make it + free software which everyone can redistribute and change under these terms. + . + To do so, attach the following notices to the program. It is safest + to attach them to the start of each source file to most effectively + state the exclusion of warranty; and each file should have at least + the "copyright" line and a pointer to where the full notice is found. + . + + Copyright (C) + . + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + . + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + . + You should have received a copy of the GNU General Public License + along with this program. If not, see . + . + Also add information on how to contact you by electronic and paper mail. + . + If the program does terminal interaction, make it output a short + notice like this when it starts in an interactive mode: + . + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + . + The hypothetical commands `show w' and `show c' should show the appropriate + parts of the General Public License. Of course, your program's commands + might be different; for a GUI interface, you would use an "about box". + . + You should also get your employer (if you work as a programmer) or school, + if any, to sign a "copyright disclaimer" for the program, if necessary. + For more information on this, and how to apply and follow the GNU GPL, see + . + . + The GNU General Public License does not permit incorporating your program + into proprietary programs. If your program is a subroutine library, you + may consider it more useful to permit linking proprietary applications with + the library. If this is what you want to do, use the GNU Lesser General + Public License instead of this License. But first, please read + . diff --git a/debian/patches/series b/debian/patches/series new file mode 100644 index 0000000..4a97dfa --- /dev/null +++ b/debian/patches/series @@ -0,0 +1 @@ +# You must remove unused comment lines for the released package. diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..158e311 --- /dev/null +++ b/debian/rules @@ -0,0 +1,6 @@ +#!/usr/bin/make -f +# You must remove unused comment lines for the released package. +#export DH_VERBOSE = 1 + +%: + dh $@ --with python3 --buildsystem=pybuild diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 0000000..163aaf8 --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/debian/source/local-options b/debian/source/local-options new file mode 100644 index 0000000..00131ee --- /dev/null +++ b/debian/source/local-options @@ -0,0 +1,2 @@ +#abort-on-upstream-changes +#unapply-patches diff --git a/debian/watch b/debian/watch new file mode 100644 index 0000000..568760a --- /dev/null +++ b/debian/watch @@ -0,0 +1,3 @@ +# You must remove unused comment lines for the released package. +version=3 +https://github.com/set-soft/kicost-digikey-api-v3/tags .*/(\d[\d\.]*)\.(?:tar.gz|tar.bz2|tar.xz) diff --git a/digikey/decorators.py b/digikey/decorators.py deleted file mode 100644 index 454f773..0000000 --- a/digikey/decorators.py +++ /dev/null @@ -1,64 +0,0 @@ -import functools -import logging - -import retrying -from requests.exceptions import RequestException - -from digikey.exceptions import DigikeyError - -logger = logging.getLogger(__name__) - - -def wrap_exception_in(exc_type, catch=Exception): - """ - Wraps raised exception in another exception type, and only includes - the original exception type name in the new exception message. - Args: - exc_type: Exception type - catch: optional, Exception type to catch - """ - - def wrapper(func): - @functools.wraps(func) - def inner(*args, **kwargs): - try: - return func(*args, **kwargs) - except catch as exc: - logger.error('Wrapped error: %s', str(exc)) - message = type(exc).__name__ - # Add HTTP status code, if one is attached to 'exc'. - try: - message += f' {exc.response.status_code}' - except AttributeError: - pass - raise exc_type(message) from exc - - return inner - - return wrapper - - -# Retry when RequestException is raised. -# wait 2^x * 100 milliseconds between each retry, -# wait up to 10 seconds between each retry, -# and stop retrying after 20 total seconds. -exponential_backoff = retrying.retry( - retry_on_exception=lambda exc: isinstance(exc, RequestException), - wait_exponential_multiplier=100, - wait_exponential_max=10000, - stop_max_delay=20000) - - -def retry(func): - """ - Applies exponential backoff and exception wrapper decorators to expose - a single decorator, to wrap functions that make HTTP requests. - """ - - @functools.wraps(func) - @wrap_exception_in(DigikeyError) - @exponential_backoff - def inner(*args, **kwargs): - return func(*args, **kwargs) - - return inner \ No newline at end of file diff --git a/digikey/utils.py b/digikey/utils.py deleted file mode 100644 index 96ed715..0000000 --- a/digikey/utils.py +++ /dev/null @@ -1,115 +0,0 @@ -import collections -import itertools -import json -import logging -from typing import List, Tuple -from urllib.parse import urlencode - -from .exceptions import DigikeyTypeError - -logger = logging.getLogger(__name__) - - -URL_MAX_LENGTH = 8000 - - -def chunked(list_: List, chunksize: int=20) -> List[List]: - """ - Partitions list into chunks of a given size. - NOTE: Octopart enforces that its 'parts/match' endpoint take no more - than 20 queries in a single request. - Args: - list_: list to be partitioned - chunksize: size of resulting chunks - Returns: - list of lists. - """ - chunks: List[List] = [] - for i in range(0, len(list_), chunksize): - chunks.append(list_[i:i + chunksize]) - return chunks - - -def chunk_queries(queries: List) -> List[List]: - """ - Partitions list into chunks, and ensures that each chunk is small enough - to not trigger an HTTP 414 error (Request URI Too Large). - Args: - queries (list) - Returns: - list - """ - chunks: List[List] = [] - # Octopart can only handle 20 queries per request, so split into chunks. - for chunk in chunked(queries): - chunks.extend(split_chunk(chunk)) - return chunks - - -def split_chunk(chunk: List) -> List[List]: - """ - Split chunk into smaller pieces if encoding the chunk into a URL would - result in an HTTP 414 error. - Args: - chunk (list) - Returns: - list of chunks - """ - encoded = urlencode({'queries': json.dumps(chunk)}) - if len(encoded) > URL_MAX_LENGTH: - # Split chunk in half to avoid HTTP 414 error. - mid = len(chunk) // 2 - left, right = chunk[:mid], chunk[mid:] - # Recurse in case either half is still too long. - return flatten([split_chunk(left), split_chunk(right)]) - else: - return [chunk] - - -def flatten(list_of_lists: List[List]) -> List: - """Chain together a list of lists - >>> flatten([[1, 2], [3, 4, 5], ['a']]) - [1, 2, 3, 4, 5, 'a'] - """ - return list(itertools.chain(*list_of_lists)) - - -def unique(list_: List) -> List: - """Remove duplicate entries from list, keeping it in its original order - >>> unique([1, 2, 2, 3, 4, 6, 2, 5]) - [1, 2, 3, 4, 6, 5] - >>> unique(['bb', 'aa', 'aa', 'aa', 'aa', 'aa', 'bb']) - ['bb', 'aa'] - """ - return list(collections.OrderedDict.fromkeys(list_)) - - -def sortby_param_str_from_list(sortby: List[Tuple[str, str]]=None) -> str: - """Turns a list of tuples into a string for sending as GET parameter - >>> sortby_param_str_from_list([('avg_price', 'asc'), ('score', 'desc')]) - 'avg_price asc,score desc' - """ - if sortby and not isinstance(sortby, list): - raise DigikeyTypeError( - '"sortyby" must be a list of tuples of fieldname and one of "asc" ' - 'or "desc"') - - def exc_from_entry(entry): - return DigikeyTypeError( - 'All "sortby" entries must be a tuple of a fieldname and one of ' - '"asc" or "desc", not %s' % entry) - - out = [] - - for entry in sortby or []: - try: - sort_value, sort_order = entry - except ValueError: - raise exc_from_entry(entry) from ValueError - - if sort_order not in ('asc', 'desc'): - raise exc_from_entry(entry) - - out.append(f"{sort_value} {sort_order}") - - return ','.join(out) \ No newline at end of file diff --git a/digikey/v2/api.py b/digikey/v2/api.py deleted file mode 100644 index d383625..0000000 --- a/digikey/v2/api.py +++ /dev/null @@ -1,54 +0,0 @@ -""" -Top-level API, provides access to the Digikey API -without directly instantiating a client object. -Also wraps the response JSON in types that provide easier access -to various fields. -""" -from digikey.v2 import models -from digikey.v2.client import DigikeyClient - - -def search(query: str, - start: int = 0, - limit: int = 10, - ) -> models.KeywordSearchResult: - """ - Search Digikey for a general keyword (and optional filters). - Args: - query (str): Free-form keyword query - start: Ordinal position of first result - limit: Maximum number of results to return - Returns: - list of `models.KeywordSearchResult` objects. - """ - - client = DigikeyClient() - response = client.search( - query, - start=start, - limit=limit, - ) - return models.KeywordSearchResult(response) - - -def part(partnr: str, - include_associated: bool = False, - include_for_use_with: bool = False, - ) -> models.Part: - """ - Query part by unique ID - Args: - partnr (str): Part number. Works best with Digi-Key part numbers. - include_associated (bool): The option to include all Associated products - include_for_use_with (bool): The option to include all For Use With product - Kwargs: - Returns: - dict. See `models.Part` for exact fields. - """ - client = DigikeyClient() - response = client.part( - partnr, - include_associated=include_associated, - include_for_use_with=include_for_use_with, - ) - return models.Part(response['PartDetails']) diff --git a/digikey/v2/client.py b/digikey/v2/client.py deleted file mode 100644 index 1a86737..0000000 --- a/digikey/v2/client.py +++ /dev/null @@ -1,145 +0,0 @@ -import logging -import os -import re -import typing as t -from pathlib import Path - -import requests -from fake_useragent import UserAgent - -from digikey.v2 import models -from digikey.decorators import retry -from digikey.exceptions import DigikeyError -from digikey.oauth.oauth2 import TokenHandler - -logger = logging.getLogger(__name__) - -DEFAULT_BASE_URL = 'https://api.digikey.com/services/partsearch/v2' - - -class DigikeyClient(object): - """Client object for Digikey API - Visit https://api-portal.digikey.com/ to get an app key and secret, then set it as - an environment variable or pass the key directly to this constructor. - """ - - def __init__(self, - a_id: t.Optional[str] = None, - a_secret: t.Optional[str] = None, - a_token_storage_path: t.Optional[str] = None, - base_url: t.Optional[str] = DEFAULT_BASE_URL - ) -> None: - - a_id = a_id or os.getenv('DIGIKEY_CLIENT_ID') - a_secret = a_secret or os.getenv('DIGIKEY_CLIENT_SECRET') - if not a_id or not a_secret: - raise ValueError( - "CLIENT ID and SECRET must be set. " - "Set 'DIGIKEY_CLIENT_ID' and 'DIGIKEY_CLIENT_SECRET' " - "as an environment variable, or pass your keys directly to the client." - ) - - a_token_storage_path = a_token_storage_path or os.getenv('DIGIKEY_STORAGE_PATH') - if not a_token_storage_path or not Path(a_token_storage_path).exists(): - raise ValueError( - "STORAGE PATH must be set and must exist." - "Set 'DIGIKEY_STORAGE_PATH' as an environment variable, " - "or pass your keys directly to the client." - ) - - self._id = a_id - self._secret = a_secret - self._token_storage_path = Path(a_token_storage_path).joinpath('token_storage.json') - self.base_url = base_url - self.oauth2 = TokenHandler().get_access_token() - - @property - def client_key_param(self) -> t.Dict[str, str]: - return {'clientid': self._id, - 'clientsecret': self._secret} - - @retry - def _request(self, - path: str, - data: t.Dict[str, t.Any]=None - ) -> t.Any: - headers = {'user-agent': f'{UserAgent().firefox}', - 'x-ibm-client-id': self._id, - 'authorization': self.oauth2.get_authorization()} - - response = requests.post('%s%s' % (self.base_url, path), json=data, headers=headers) - try: - rate_limit = re.split('[,;]+', response.headers['x-ratelimit-limit'])[1] - rate_limit_rem = re.split('[,;]+', response.headers['x-ratelimit-remaining'])[1] - logger.debug('Requested Digikey URI: {} [{}/{}]'.format(response.url, rate_limit_rem, rate_limit)) - except KeyError as e: - logger.debug('Requested Digikey URI: {}'.format(response.url)) - - response.raise_for_status() - return response.json() - - def search(self, - query: str, # maps to "keyword" parameter in Digikey API - start: int = 0, - limit: int = 10, - ) -> dict: - """ - Search for parts, using more fields and filter options than 'match'. - This calls the /parts/search endpoint of the Octopart API: - https://octopart.com/api/docs/v3/rest-api#endpoints-parts-search - Args: - query (str): free-form keyword query - start (int): ordinal position of first result - limit (int): maximum number of results to return - Kwargs: - Returns: - dict. See `models.PartsSearchResponse` for exact fields. - """ - data = { - 'keywords': query, - 'search_options': None, - 'record_count': limit, - 'record_start_pos': start, - 'filters': None, - 'sort': None, - 'requested_quantity': 1 - } - - if not models.KeywordSearchRequest.is_valid(data): - errors = models.KeywordSearchRequest.errors(data) - raise DigikeyError('Query is malformed: %s' % errors) - - # Convert `query` to format that Octopart accepts. - params = models.KeywordSearchRequest.camelize(models.KeywordSearchRequest(data).to_primitive()) - - return self._request('/keywordsearch', data=params) - - def part(self, - partnr: str, - include_associated: bool = False, - include_for_use_with: bool = False, - ) -> dict: - """ - Query part by unique ID - Args: - partnr (str): Part number. Works best with Digi-Key part numbers. - include_associated (bool): The option to include all Associated products - include_for_use_with (bool): The option to include all For Use With product - Kwargs: - Returns: - dict. See `models.Part` for exact fields. - """ - data = { - 'part': partnr, - 'include_all_associated_products': include_associated, - 'include_all_for_use_with_products': include_for_use_with - } - - if not models.PartDetailPostRequest.is_valid(data): - errors = models.PartDetailPostRequest.errors(data) - raise DigikeyError('Query is malformed: %s' % errors) - - # Convert `query` to format that Octopart accepts. - params = models.PartDetailPostRequest.camelize(models.PartDetailPostRequest(data).to_primitive()) - - return self._request('/partdetails', data=params) diff --git a/digikey/v2/directives.py b/digikey/v2/directives.py deleted file mode 100644 index 9104e7c..0000000 --- a/digikey/v2/directives.py +++ /dev/null @@ -1,58 +0,0 @@ -import enum -from typing import List - - -class IncludeDirectives(str, enum.Enum): - """Categories of information that can optionally be requested - These categories may be included in the include[] request parameter to - request additional information in the response content. - API docs: https://octopart.com/api/docs/v3/rest-api#include-directives - """ - short_description = 'short_description' - datasheets = 'datasheets' - compliance_documents = 'compliance_documents' - descriptions = 'descriptions' - imagesets = 'imagesets' - specs = 'specs' - category_uids = 'category_uids' - external_links = 'external_links' - reference_designs = 'reference_designs' - cad_models = 'cad_models' - - -def include_directives_from_kwargs(**kwargs) -> List[str]: - """Turn "include_"-prefixed kwargs into list of strings for the request - Arguments: - All keyword arguments whose name consists of "include_*" and an - entry of the INCLUDE enum are used to construct the output. All - others are ignored. - Known directives are included in the output if their value is truthy: - >>> include_directives_from_kwargs( - ... include_datasheets=True, include_specs=True, - ... include_imagesets=False) - ['datasheets', 'specs'] - Keyword args whose name starts with "include_" but don't match known - directives trigger an exception: - >>> include_directives_from_kwargs(include_abcdefg=True) - Traceback (most recent call last): - ... - ValueError: abcdefg is not a known include directive - However, keyword arguments not starting with "include_" are ignored - silently: - >>> include_directives_from_kwargs(abcdefg=True, include_specs=True) - ['specs'] - """ - includes = [] - - for kw_key, kw_val in kwargs.items(): - # filter for kwargs named include_* and value True - if kw_key.startswith('include_') and kw_val: - _, incl_key = kw_key.split('include_') - # only accept documented values for the include directive - if hasattr(IncludeDirectives, incl_key): - includes.append(incl_key) - else: - raise ValueError( - f"{incl_key} is not a known include directive") - - return includes \ No newline at end of file diff --git a/digikey/v2/models.py b/digikey/v2/models.py deleted file mode 100644 index 6759296..0000000 --- a/digikey/v2/models.py +++ /dev/null @@ -1,267 +0,0 @@ -""" -Types that wrap responses from the Octopart API -and make various attributes easier to access. -""" - -import inflection - -from schematics.exceptions import ConversionError, DataError, ValidationError -from schematics.models import Model -from schematics.types import BooleanType, IntType, StringType -from schematics.types.compound import ListType, ModelType - - -class BaseModel(Model): - @classmethod - def errors(cls, dict_): - """ - Wraps `schematics` validate method to return an error list instead of - having to catch an exception in the caller. - Returns: - list of validation errors, or None. - """ - try: - cls(dict_).validate() - return None - except (DataError, ValidationError) as err: - return err.messages - - @classmethod - def errors_list(cls, list_): - """ - Return any validation errors in list of dicts. - Args: - list_ (list): dicts to be validated. - Returns: - list of errors, if any, otherwise None. - """ - try: - errors = [cls(dict_).errors for dict_ in list_] - if any(errors): - return [_f for _f in errors if _f] - return None - except (ConversionError, DataError) as err: - return err.messages - - @classmethod - def is_valid(cls, dict_): - return not cls.errors(dict_) - - @classmethod - def is_valid_list(cls, list_): - try: - return all([cls(dict_).is_valid for dict_ in list_]) - except (ConversionError, DataError): - return False - - @classmethod - def camelize(cls, dict_): - return {inflection.camelize(k): v for k, v in dict_.items()} - - -class Filters(BaseModel): - """Query format sent to the search endpoint - https://api-portal.digikey.com/node/8517 - """ - - -class Sort(BaseModel): - """Query format sent to the search endpoint - https://api-portal.digikey.com/node/8517 - """ - - -class KeywordSearchRequest(BaseModel): - """Query format sent to the search endpoint - https://api-portal.digikey.com/node/8517 - """ - # Keywords to search on - keywords = StringType(required=True) - # Filters the search results by the included SearchOptions - search_options = ListType(StringType) - # Maximum number of items to return - record_count = IntType(default=10, min_value=1, max_value=50, required=True) - # Ordinal position of first returned item - record_start_pos = IntType(default=0) - # Set Filters to narrow down search response - filters = ModelType(Filters) - # Sort Parameters - sort = ModelType(Sort) - # The RequestedQuantity is used with the SortByUnitPrice Sort Option to sort by unit price at the RequestedQuantity - requested_quantity = IntType(default=1) - - -class PartDetailPostRequest(BaseModel): - """Query format sent to the partdetails endpoint - https://api-portal.digikey.com/node/8517 - """ - # Part number. Works best with Digi-Key part numbers. - part = StringType(required=True) - # The option to include all Associated products - include_all_associated_products = BooleanType() - # The option to include all For Use With products - include_all_for_use_with_products = BooleanType() - - -class KeywordSearchResult: - def __init__(self, result): - self._result = result - - @property - def parts(self): - return [ - Part(result) - for result in self._result.get('Parts', []) - ] - - def __repr__(self): - return '' % self._result['Results'] - - def pretty_print(self): - print(self) - for part in self.parts: - print('\t%s' % part) - - -''' -Helper classes for responses -''' - - -class PriceBreak: - def __init__(self, pricebreak: dict): - self._pricebreak = pricebreak - - @property - def breakquantity(self) -> int: - return self._pricebreak.get('BreakQuantity', 0) - - @property - def unitprice(self) -> float: - return self._pricebreak.get('UnitPrice', 0.0) - - @property - def totalprice(self) -> float: - return self._pricebreak.get('TotalPrice', 0.0) - - -class IdTextPair: - def __init__(self, idtextpair: dict): - self._idtextpair = idtextpair - - @property - def id(self) -> str: - return self._idtextpair.get('Id', '') - - @property - def text(self) -> str: - return self._idtextpair.get('Text', '') - - -class PidVid: - def __init__(self, pidvid: dict): - self._pidvid = pidvid - - @property - def parameter_id(self) -> int: - return self._pidvid.get('ParameterId', 0) - - @property - def value_id(self) -> int: - return self._pidvid.get('ValueId', 0) - - @property - def parameter(self) -> str: - return self._pidvid.get('Parameter', '') - - @property - def value(self) -> str: - return self._pidvid.get('Value', '') - - def __repr__(self): - return ''.format(self.parameter, self.value) - - -class Family: - def __init__(self, family: dict): - self._family = family - - @property - def id(self) -> str: - return self._family.get('Id', '') - - @property - def name(self) -> str: - return self._family.get('Name', '') - - @property - def part_count(self) -> int: - return self._family.get('PartCount', 0) - - -class Part: - def __init__(self, part: dict): - self._part = part - - @property - def standard_pricing(self) -> list: - return [ - PriceBreak(part) - for part in self._part.get('StandardPricing', []) - ] - - @property - def category(self) -> IdTextPair: - return IdTextPair(self._part.get('Category', {})) - - @property - def family(self) -> IdTextPair: - return IdTextPair(self._part.get('Family', {})) - - @property - def manufacturer(self) -> str: - return IdTextPair(self._part.get('ManufacturerName', {})).text - - @property - def mpn(self) -> str: - return self._part.get('ManufacturerPartNumber', None) - - @property - def part_status(self) -> str: - return self._part.get('PartStatus', None) - - @property - def digikey_pn(self) -> str: - return self._part.get('DigiKeyPartNumber', None) - - @property - def digikey_url(self) -> str: - return 'https://www.digikey.com' + self._part.get('PartUrl', '') - - @property - def in_stock(self) -> int: - return self._part.get('QuantityOnHand', None) - - @property - def moq(self) -> int: - return self._part.get('MinimumOrderQuantity', None) - - @property - def parameters(self) -> dict: - _params = [PidVid(param) for param in self._part.get('Parameters', [])] - return {p.parameter: p.value for p in _params} - - @property - def description_product(self) -> str: - return self._part.get('ProductDescription', None) - - @property - def description_detailed(self) -> str: - return self._part.get('DetailedDescription', None) - - @property - def datasheet(self) -> str: - return self._part.get('PrimaryDatasheet', None) - - def __repr__(self): - return '' % self.mpn diff --git a/digikey/v3/batchproductdetails/__init__.py b/digikey/v3/batchproductdetails/__init__.py deleted file mode 100644 index b9a07f0..0000000 --- a/digikey/v3/batchproductdetails/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import apis into sdk package -from digikey.v3.batchproductdetails.api.batch_search_api import BatchSearchApi - -# import ApiClient -from digikey.v3.batchproductdetails.api_client import ApiClient -from digikey.v3.batchproductdetails.configuration import Configuration -# import models into sdk package -from digikey.v3.batchproductdetails.models.api_error_response import ApiErrorResponse -from digikey.v3.batchproductdetails.models.api_validation_error import ApiValidationError -from digikey.v3.batchproductdetails.models.associated_product import AssociatedProduct -from digikey.v3.batchproductdetails.models.basic_product import BasicProduct -from digikey.v3.batchproductdetails.models.batch_product_details_request import BatchProductDetailsRequest -from digikey.v3.batchproductdetails.models.batch_product_details_response import BatchProductDetailsResponse -from digikey.v3.batchproductdetails.models.iso_search_locale import IsoSearchLocale -from digikey.v3.batchproductdetails.models.kit_part import KitPart -from digikey.v3.batchproductdetails.models.limited_taxonomy import LimitedTaxonomy -from digikey.v3.batchproductdetails.models.media_links import MediaLinks -from digikey.v3.batchproductdetails.models.pid_vid import PidVid -from digikey.v3.batchproductdetails.models.price_break import PriceBreak -from digikey.v3.batchproductdetails.models.product_details import ProductDetails diff --git a/digikey/v3/batchproductdetails/api/__init__.py b/digikey/v3/batchproductdetails/api/__init__.py deleted file mode 100644 index e67de79..0000000 --- a/digikey/v3/batchproductdetails/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from __future__ import absolute_import - -# flake8: noqa - -# import apis into api package -from digikey.v3.batchproductdetails.api.batch_search_api import BatchSearchApi diff --git a/digikey/v3/batchproductdetails/api/batch_search_api.py b/digikey/v3/batchproductdetails/api/batch_search_api.py deleted file mode 100644 index f3bc32a..0000000 --- a/digikey/v3/batchproductdetails/api/batch_search_api.py +++ /dev/null @@ -1,169 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import re # noqa: F401 - -# python 2 and python 3 compatibility library -import six - -from digikey.v3.batchproductdetails.api_client import ApiClient - - -class BatchSearchApi(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def batch_product_details(self, authorization, x_digikey_client_id, **kwargs): # noqa: E501 - """Retrieve detailed product information including real time pricing and availability. # noqa: E501 - - Locale information is required in the headers for accurate pricing and currencies. Locale defaults to United States. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.batch_product_details(authorization, x_digikey_client_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str authorization: OAuth Bearer Token. Please see OAuth 2.0 Documentation page for more info. (required) - :param str x_digikey_client_id: The Client Id for your App. (required) - :param bool exclude_market_place_products: Used to exclude MarkPlace products from search results. Default is false - :param str x_digikey_locale_site: Two letter code for Digi-Key product website to search on. Different countries sites have different part restrictions, supported languages, and currencies. Acceptable values include: US, CA, JP, UK, DE, AT, BE, DK, FI, GR, IE, IT, LU, NL, NO, PT, ES, KR, HK, SG, CN, TW, AU, FR, IN, NZ, SE, MX, CH, IL, PL, SK, SI, LV, LT, EE, CZ, HU, BG, MY, ZA, RO, TH, PH. - :param str x_digikey_locale_language: Two letter code for language to search on. Langauge must be supported by the selected site. If searching on keyword, this language is used to find matches. Acceptable values include: en, ja, de, fr, ko, zhs, zht, it, es, he, nl, sv, pl, fi, da, no. - :param str x_digikey_locale_currency: Three letter code for Currency to return part pricing for. Currency must be supported by the selected site. Acceptable values include: USD, CAD, JPY, GBP, EUR, HKD, SGD, TWD, KRW, AUD, NZD, INR, DKK, NOK, SEK, ILS, CNY, PLN, CHF, CZK, HUF, RON, ZAR, MYR, THB, PHP. - :param str x_digikey_locale_ship_to_country: ISO code for country to ship to. - :param str x_digikey_customer_id: Your Digi-Key Customer id. If your account has multiple Customer Ids for different regions, this allows you to select one of them. - :param BatchProductDetailsRequest body: List of Digi-Key products - :return: BatchProductDetailsResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.batch_product_details_with_http_info(authorization, x_digikey_client_id, **kwargs) # noqa: E501 - else: - (data) = self.batch_product_details_with_http_info(authorization, x_digikey_client_id, **kwargs) # noqa: E501 - return data - - def batch_product_details_with_http_info(self, authorization, x_digikey_client_id, **kwargs): # noqa: E501 - """Retrieve detailed product information including real time pricing and availability. # noqa: E501 - - Locale information is required in the headers for accurate pricing and currencies. Locale defaults to United States. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.batch_product_details_with_http_info(authorization, x_digikey_client_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str authorization: OAuth Bearer Token. Please see OAuth 2.0 Documentation page for more info. (required) - :param str x_digikey_client_id: The Client Id for your App. (required) - :param bool exclude_market_place_products: Used to exclude MarkPlace products from search results. Default is false - :param str x_digikey_locale_site: Two letter code for Digi-Key product website to search on. Different countries sites have different part restrictions, supported languages, and currencies. Acceptable values include: US, CA, JP, UK, DE, AT, BE, DK, FI, GR, IE, IT, LU, NL, NO, PT, ES, KR, HK, SG, CN, TW, AU, FR, IN, NZ, SE, MX, CH, IL, PL, SK, SI, LV, LT, EE, CZ, HU, BG, MY, ZA, RO, TH, PH. - :param str x_digikey_locale_language: Two letter code for language to search on. Langauge must be supported by the selected site. If searching on keyword, this language is used to find matches. Acceptable values include: en, ja, de, fr, ko, zhs, zht, it, es, he, nl, sv, pl, fi, da, no. - :param str x_digikey_locale_currency: Three letter code for Currency to return part pricing for. Currency must be supported by the selected site. Acceptable values include: USD, CAD, JPY, GBP, EUR, HKD, SGD, TWD, KRW, AUD, NZD, INR, DKK, NOK, SEK, ILS, CNY, PLN, CHF, CZK, HUF, RON, ZAR, MYR, THB, PHP. - :param str x_digikey_locale_ship_to_country: ISO code for country to ship to. - :param str x_digikey_customer_id: Your Digi-Key Customer id. If your account has multiple Customer Ids for different regions, this allows you to select one of them. - :param BatchProductDetailsRequest body: List of Digi-Key products - :return: BatchProductDetailsResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['authorization', 'x_digikey_client_id', 'exclude_market_place_products', 'x_digikey_locale_site', 'x_digikey_locale_language', 'x_digikey_locale_currency', 'x_digikey_locale_ship_to_country', 'x_digikey_customer_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method batch_product_details" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'authorization' is set - if ('authorization' not in params or - params['authorization'] is None): - raise ValueError("Missing the required parameter `authorization` when calling `batch_product_details`") # noqa: E501 - # verify the required parameter 'x_digikey_client_id' is set - if ('x_digikey_client_id' not in params or - params['x_digikey_client_id'] is None): - raise ValueError("Missing the required parameter `x_digikey_client_id` when calling `batch_product_details`") # noqa: E501 - - collection_formats = {} - - path_params = {} - - query_params = [] - if 'exclude_market_place_products' in params: - query_params.append(('excludeMarketPlaceProducts', params['exclude_market_place_products'])) # noqa: E501 - - header_params = {} - if 'authorization' in params: - header_params['Authorization'] = params['authorization'] # noqa: E501 - if 'x_digikey_client_id' in params: - header_params['X-DIGIKEY-Client-Id'] = params['x_digikey_client_id'] # noqa: E501 - if 'x_digikey_locale_site' in params: - header_params['X-DIGIKEY-Locale-Site'] = params['x_digikey_locale_site'] # noqa: E501 - if 'x_digikey_locale_language' in params: - header_params['X-DIGIKEY-Locale-Language'] = params['x_digikey_locale_language'] # noqa: E501 - if 'x_digikey_locale_currency' in params: - header_params['X-DIGIKEY-Locale-Currency'] = params['x_digikey_locale_currency'] # noqa: E501 - if 'x_digikey_locale_ship_to_country' in params: - header_params['X-DIGIKEY-Locale-ShipToCountry'] = params['x_digikey_locale_ship_to_country'] # noqa: E501 - if 'x_digikey_customer_id' in params: - header_params['X-DIGIKEY-Customer-Id'] = params['x_digikey_customer_id'] # noqa: E501 - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json-patch+json', 'application/json', 'text/json', 'application/*+json']) # noqa: E501 - - # Authentication setting - auth_settings = ['apiKeySecurity', 'oauth2AccessCodeSecurity'] # noqa: E501 - - return self.api_client.call_api( - '/ProductDetails', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='BatchProductDetailsResponse', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/digikey/v3/batchproductdetails/api_client.py b/digikey/v3/batchproductdetails/api_client.py deleted file mode 100644 index 4075732..0000000 --- a/digikey/v3/batchproductdetails/api_client.py +++ /dev/null @@ -1,638 +0,0 @@ -# coding: utf-8 -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import datetime -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote - -from digikey.v3.batchproductdetails.configuration import Configuration -import digikey.v3.batchproductdetails.models -from digikey.v3.batchproductdetails import rest - - -class ApiClient(object): - """Generic API client for Swagger client library builds. - - Swagger generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the Swagger - templates. - - NOTE: This class is auto generated by the swagger code generator program. - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - """ - - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int if six.PY3 else long, # noqa: F821 - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - - # Use the pool property to lazily initialize the ThreadPool. - self._pool = None - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'Swagger-Codegen/0.1.0/python' - - def __del__(self): - if self._pool is not None: - self._pool.close() - self._pool.join() - - @property - def pool(self): - if self._pool is None: - self._pool = ThreadPool() - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - - # post parameters - if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.configuration.host + resource_path - - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return (return_data) - else: - return (return_data, response_data.status, - response_data.getheaders()) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - - return {key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict)} - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith('list['): - sub_kls = re.match(r'list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('dict('): - sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in six.iteritems(data)} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(digikey.v3.batchproductdetails.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, async_req=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout) - else: - thread = self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, query_params, - header_params, body, - post_params, files, - response_type, auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, _request_timeout)) - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "POST": - return self.rest_client.POST(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def prepare_post_parameters(self, post_params=None, files=None): - """Builds form parameters. - - :param post_params: Normal form parameters. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if post_params: - params = post_params - - if files: - for k, v in six.iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return 'application/json' - - content_types = [x.lower() for x in content_types] - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if not auth_setting['value']: - continue - elif auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys.append((auth_setting['key'], auth_setting['value'])) - else: - raise ValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "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 six.text_type(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return a original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datatime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse `{0}` as datetime object" - .format(string) - ) - ) - - def __hasattr(self, object, name): - return name in object.__class__.__dict__ - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - if (not klass.swagger_types and - not self.__hasattr(klass, 'get_real_child_model')): - return data - - kwargs = {} - if klass.swagger_types is not None: - for attr, attr_type in six.iteritems(klass.swagger_types): - if (data is not None and - klass.attribute_map[attr] in data and - isinstance(data, (list, dict))): - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if (isinstance(instance, dict) and - klass.swagger_types is not None and - isinstance(data, dict)): - for key, value in data.items(): - if key not in klass.swagger_types: - instance[key] = value - if self.__hasattr(instance, 'get_real_child_model'): - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance diff --git a/digikey/v3/batchproductdetails/configuration.py b/digikey/v3/batchproductdetails/configuration.py deleted file mode 100644 index faf88e5..0000000 --- a/digikey/v3/batchproductdetails/configuration.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import six -from six.moves import http_client as httplib - - -class Configuration(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - """ - - _default = None - - def __init__(self): - """Constructor""" - if self._default: - for key in self._default.__dict__.keys(): - self.__dict__[key] = copy.copy(self._default.__dict__[key]) - return - - # Default Base url - self.host = "https://api.digikey.com/BatchSearch/v3" - # Temp file folder for downloading files - self.temp_folder_path = None - - # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - - # access token for OAuth - self.access_token = "" - - # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("digikey.v3.batchproductdetails") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - # Log stream handler - self.logger_stream_handler = None - # Log file handler - self.logger_file_handler = None - # Debug file location - self.logger_file = None - # Debug switch - self.debug = False - - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. - self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file - self.cert_file = None - # client key file - self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. - self.assert_hostname = None - - # 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.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - - # Proxy URL - self.proxy = None - # Safe chars for path_param - self.safe_chars_for_path_param = '' - - @classmethod - def set_default(cls, default): - cls._default = 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 six.iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(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 six.iteritems(self.logger): - 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 six.iteritems(self.logger): - 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): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if (self.api_key.get(identifier) and - self.api_key_prefix.get(identifier)): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 - elif self.api_key.get(identifier): - return self.api_key[identifier] - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - return urllib3.util.make_headers( - basic_auth=self.username + ':' + self.password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - return { - 'apiKeySecurity': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'X-DIGIKEY-Client-Id', - 'value': self.get_api_key_with_prefix('X-DIGIKEY-Client-Id') - }, - - 'oauth2AccessCodeSecurity': - { - 'type': 'oauth2', - 'in': 'header', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - }, - - } - - 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: v3\n"\ - "SDK Package Version: 0.1.0".\ - format(env=sys.platform, pyversion=sys.version) diff --git a/digikey/v3/batchproductdetails/models/__init__.py b/digikey/v3/batchproductdetails/models/__init__.py deleted file mode 100644 index 6583bd0..0000000 --- a/digikey/v3/batchproductdetails/models/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import models into model package -from digikey.v3.batchproductdetails.models.api_error_response import ApiErrorResponse -from digikey.v3.batchproductdetails.models.api_validation_error import ApiValidationError -from digikey.v3.batchproductdetails.models.associated_product import AssociatedProduct -from digikey.v3.batchproductdetails.models.basic_product import BasicProduct -from digikey.v3.batchproductdetails.models.batch_product_details_request import BatchProductDetailsRequest -from digikey.v3.batchproductdetails.models.batch_product_details_response import BatchProductDetailsResponse -from digikey.v3.batchproductdetails.models.iso_search_locale import IsoSearchLocale -from digikey.v3.batchproductdetails.models.kit_part import KitPart -from digikey.v3.batchproductdetails.models.limited_taxonomy import LimitedTaxonomy -from digikey.v3.batchproductdetails.models.media_links import MediaLinks -from digikey.v3.batchproductdetails.models.pid_vid import PidVid -from digikey.v3.batchproductdetails.models.price_break import PriceBreak -from digikey.v3.batchproductdetails.models.product_details import ProductDetails diff --git a/digikey/v3/batchproductdetails/models/api_error_response.py b/digikey/v3/batchproductdetails/models/api_error_response.py deleted file mode 100644 index bf72a9c..0000000 --- a/digikey/v3/batchproductdetails/models/api_error_response.py +++ /dev/null @@ -1,245 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class ApiErrorResponse(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'error_response_version': 'str', - 'status_code': 'int', - 'error_message': 'str', - 'error_details': 'str', - 'request_id': 'str', - 'validation_errors': 'list[ApiValidationError]' - } - - attribute_map = { - 'error_response_version': 'ErrorResponseVersion', - 'status_code': 'StatusCode', - 'error_message': 'ErrorMessage', - 'error_details': 'ErrorDetails', - 'request_id': 'RequestId', - 'validation_errors': 'ValidationErrors' - } - - def __init__(self, error_response_version=None, status_code=None, error_message=None, error_details=None, request_id=None, validation_errors=None): # noqa: E501 - """ApiErrorResponse - a model defined in Swagger""" # noqa: E501 - - self._error_response_version = None - self._status_code = None - self._error_message = None - self._error_details = None - self._request_id = None - self._validation_errors = None - self.discriminator = None - - if error_response_version is not None: - self.error_response_version = error_response_version - if status_code is not None: - self.status_code = status_code - if error_message is not None: - self.error_message = error_message - if error_details is not None: - self.error_details = error_details - if request_id is not None: - self.request_id = request_id - if validation_errors is not None: - self.validation_errors = validation_errors - - @property - def error_response_version(self): - """Gets the error_response_version of this ApiErrorResponse. # noqa: E501 - - - :return: The error_response_version of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._error_response_version - - @error_response_version.setter - def error_response_version(self, error_response_version): - """Sets the error_response_version of this ApiErrorResponse. - - - :param error_response_version: The error_response_version of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._error_response_version = error_response_version - - @property - def status_code(self): - """Gets the status_code of this ApiErrorResponse. # noqa: E501 - - - :return: The status_code of this ApiErrorResponse. # noqa: E501 - :rtype: int - """ - return self._status_code - - @status_code.setter - def status_code(self, status_code): - """Sets the status_code of this ApiErrorResponse. - - - :param status_code: The status_code of this ApiErrorResponse. # noqa: E501 - :type: int - """ - - self._status_code = status_code - - @property - def error_message(self): - """Gets the error_message of this ApiErrorResponse. # noqa: E501 - - - :return: The error_message of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._error_message - - @error_message.setter - def error_message(self, error_message): - """Sets the error_message of this ApiErrorResponse. - - - :param error_message: The error_message of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._error_message = error_message - - @property - def error_details(self): - """Gets the error_details of this ApiErrorResponse. # noqa: E501 - - - :return: The error_details of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._error_details - - @error_details.setter - def error_details(self, error_details): - """Sets the error_details of this ApiErrorResponse. - - - :param error_details: The error_details of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._error_details = error_details - - @property - def request_id(self): - """Gets the request_id of this ApiErrorResponse. # noqa: E501 - - - :return: The request_id of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._request_id - - @request_id.setter - def request_id(self, request_id): - """Sets the request_id of this ApiErrorResponse. - - - :param request_id: The request_id of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._request_id = request_id - - @property - def validation_errors(self): - """Gets the validation_errors of this ApiErrorResponse. # noqa: E501 - - - :return: The validation_errors of this ApiErrorResponse. # noqa: E501 - :rtype: list[ApiValidationError] - """ - return self._validation_errors - - @validation_errors.setter - def validation_errors(self, validation_errors): - """Sets the validation_errors of this ApiErrorResponse. - - - :param validation_errors: The validation_errors of this ApiErrorResponse. # noqa: E501 - :type: list[ApiValidationError] - """ - - self._validation_errors = validation_errors - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ApiErrorResponse, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ApiErrorResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/api_validation_error.py b/digikey/v3/batchproductdetails/models/api_validation_error.py deleted file mode 100644 index 73902de..0000000 --- a/digikey/v3/batchproductdetails/models/api_validation_error.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class ApiValidationError(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'field': 'str', - 'message': 'str' - } - - attribute_map = { - 'field': 'Field', - 'message': 'Message' - } - - def __init__(self, field=None, message=None): # noqa: E501 - """ApiValidationError - a model defined in Swagger""" # noqa: E501 - - self._field = None - self._message = None - self.discriminator = None - - if field is not None: - self.field = field - if message is not None: - self.message = message - - @property - def field(self): - """Gets the field of this ApiValidationError. # noqa: E501 - - - :return: The field of this ApiValidationError. # noqa: E501 - :rtype: str - """ - return self._field - - @field.setter - def field(self, field): - """Sets the field of this ApiValidationError. - - - :param field: The field of this ApiValidationError. # noqa: E501 - :type: str - """ - - self._field = field - - @property - def message(self): - """Gets the message of this ApiValidationError. # noqa: E501 - - - :return: The message of this ApiValidationError. # noqa: E501 - :rtype: str - """ - return self._message - - @message.setter - def message(self, message): - """Sets the message of this ApiValidationError. - - - :param message: The message of this ApiValidationError. # noqa: E501 - :type: str - """ - - self._message = message - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ApiValidationError, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ApiValidationError): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/associated_product.py b/digikey/v3/batchproductdetails/models/associated_product.py deleted file mode 100644 index 23f5ff8..0000000 --- a/digikey/v3/batchproductdetails/models/associated_product.py +++ /dev/null @@ -1,477 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class AssociatedProduct(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'product_url': 'str', - 'manufacturer_part_number': 'str', - 'minimum_order_quantity': 'int', - 'non_stock': 'bool', - 'packaging': 'PidVid', - 'quantity_available': 'int', - 'digi_key_part_number': 'str', - 'product_description': 'str', - 'unit_price': 'float', - 'manufacturer': 'PidVid', - 'manufacturer_public_quantity': 'int', - 'quantity_on_order': 'int', - 'dk_plus_restriction': 'bool', - 'supplier_direct_ship': 'bool' - } - - attribute_map = { - 'product_url': 'ProductUrl', - 'manufacturer_part_number': 'ManufacturerPartNumber', - 'minimum_order_quantity': 'MinimumOrderQuantity', - 'non_stock': 'NonStock', - 'packaging': 'Packaging', - 'quantity_available': 'QuantityAvailable', - 'digi_key_part_number': 'DigiKeyPartNumber', - 'product_description': 'ProductDescription', - 'unit_price': 'UnitPrice', - 'manufacturer': 'Manufacturer', - 'manufacturer_public_quantity': 'ManufacturerPublicQuantity', - 'quantity_on_order': 'QuantityOnOrder', - 'dk_plus_restriction': 'DKPlusRestriction', - 'supplier_direct_ship': 'SupplierDirectShip' - } - - def __init__(self, product_url=None, manufacturer_part_number=None, minimum_order_quantity=None, non_stock=None, packaging=None, quantity_available=None, digi_key_part_number=None, product_description=None, unit_price=None, manufacturer=None, manufacturer_public_quantity=None, quantity_on_order=None, dk_plus_restriction=None, supplier_direct_ship=None): # noqa: E501 - """AssociatedProduct - a model defined in Swagger""" # noqa: E501 - - self._product_url = None - self._manufacturer_part_number = None - self._minimum_order_quantity = None - self._non_stock = None - self._packaging = None - self._quantity_available = None - self._digi_key_part_number = None - self._product_description = None - self._unit_price = None - self._manufacturer = None - self._manufacturer_public_quantity = None - self._quantity_on_order = None - self._dk_plus_restriction = None - self._supplier_direct_ship = None - self.discriminator = None - - if product_url is not None: - self.product_url = product_url - if manufacturer_part_number is not None: - self.manufacturer_part_number = manufacturer_part_number - if minimum_order_quantity is not None: - self.minimum_order_quantity = minimum_order_quantity - if non_stock is not None: - self.non_stock = non_stock - if packaging is not None: - self.packaging = packaging - if quantity_available is not None: - self.quantity_available = quantity_available - if digi_key_part_number is not None: - self.digi_key_part_number = digi_key_part_number - if product_description is not None: - self.product_description = product_description - if unit_price is not None: - self.unit_price = unit_price - if manufacturer is not None: - self.manufacturer = manufacturer - if manufacturer_public_quantity is not None: - self.manufacturer_public_quantity = manufacturer_public_quantity - if quantity_on_order is not None: - self.quantity_on_order = quantity_on_order - if dk_plus_restriction is not None: - self.dk_plus_restriction = dk_plus_restriction - if supplier_direct_ship is not None: - self.supplier_direct_ship = supplier_direct_ship - - @property - def product_url(self): - """Gets the product_url of this AssociatedProduct. # noqa: E501 - - Full URL of the Digi-Key catalog page to purchase the product. This is based on your provided Locale values. # noqa: E501 - - :return: The product_url of this AssociatedProduct. # noqa: E501 - :rtype: str - """ - return self._product_url - - @product_url.setter - def product_url(self, product_url): - """Sets the product_url of this AssociatedProduct. - - Full URL of the Digi-Key catalog page to purchase the product. This is based on your provided Locale values. # noqa: E501 - - :param product_url: The product_url of this AssociatedProduct. # noqa: E501 - :type: str - """ - - self._product_url = product_url - - @property - def manufacturer_part_number(self): - """Gets the manufacturer_part_number of this AssociatedProduct. # noqa: E501 - - The manufacturer part number. Note that some manufacturer part numbers may be used by multiple manufacturers for different parts. # noqa: E501 - - :return: The manufacturer_part_number of this AssociatedProduct. # noqa: E501 - :rtype: str - """ - return self._manufacturer_part_number - - @manufacturer_part_number.setter - def manufacturer_part_number(self, manufacturer_part_number): - """Sets the manufacturer_part_number of this AssociatedProduct. - - The manufacturer part number. Note that some manufacturer part numbers may be used by multiple manufacturers for different parts. # noqa: E501 - - :param manufacturer_part_number: The manufacturer_part_number of this AssociatedProduct. # noqa: E501 - :type: str - """ - - self._manufacturer_part_number = manufacturer_part_number - - @property - def minimum_order_quantity(self): - """Gets the minimum_order_quantity of this AssociatedProduct. # noqa: E501 - - The minimum quantity to order from Digi-Key. # noqa: E501 - - :return: The minimum_order_quantity of this AssociatedProduct. # noqa: E501 - :rtype: int - """ - return self._minimum_order_quantity - - @minimum_order_quantity.setter - def minimum_order_quantity(self, minimum_order_quantity): - """Sets the minimum_order_quantity of this AssociatedProduct. - - The minimum quantity to order from Digi-Key. # noqa: E501 - - :param minimum_order_quantity: The minimum_order_quantity of this AssociatedProduct. # noqa: E501 - :type: int - """ - - self._minimum_order_quantity = minimum_order_quantity - - @property - def non_stock(self): - """Gets the non_stock of this AssociatedProduct. # noqa: E501 - - Indicates this product is a non stock product. # noqa: E501 - - :return: The non_stock of this AssociatedProduct. # noqa: E501 - :rtype: bool - """ - return self._non_stock - - @non_stock.setter - def non_stock(self, non_stock): - """Sets the non_stock of this AssociatedProduct. - - Indicates this product is a non stock product. # noqa: E501 - - :param non_stock: The non_stock of this AssociatedProduct. # noqa: E501 - :type: bool - """ - - self._non_stock = non_stock - - @property - def packaging(self): - """Gets the packaging of this AssociatedProduct. # noqa: E501 - - - :return: The packaging of this AssociatedProduct. # noqa: E501 - :rtype: PidVid - """ - return self._packaging - - @packaging.setter - def packaging(self, packaging): - """Sets the packaging of this AssociatedProduct. - - - :param packaging: The packaging of this AssociatedProduct. # noqa: E501 - :type: PidVid - """ - - self._packaging = packaging - - @property - def quantity_available(self): - """Gets the quantity_available of this AssociatedProduct. # noqa: E501 - - Quantity of the product available for immediate sale. # noqa: E501 - - :return: The quantity_available of this AssociatedProduct. # noqa: E501 - :rtype: int - """ - return self._quantity_available - - @quantity_available.setter - def quantity_available(self, quantity_available): - """Sets the quantity_available of this AssociatedProduct. - - Quantity of the product available for immediate sale. # noqa: E501 - - :param quantity_available: The quantity_available of this AssociatedProduct. # noqa: E501 - :type: int - """ - - self._quantity_available = quantity_available - - @property - def digi_key_part_number(self): - """Gets the digi_key_part_number of this AssociatedProduct. # noqa: E501 - - The Digi-Key part number. # noqa: E501 - - :return: The digi_key_part_number of this AssociatedProduct. # noqa: E501 - :rtype: str - """ - return self._digi_key_part_number - - @digi_key_part_number.setter - def digi_key_part_number(self, digi_key_part_number): - """Sets the digi_key_part_number of this AssociatedProduct. - - The Digi-Key part number. # noqa: E501 - - :param digi_key_part_number: The digi_key_part_number of this AssociatedProduct. # noqa: E501 - :type: str - """ - - self._digi_key_part_number = digi_key_part_number - - @property - def product_description(self): - """Gets the product_description of this AssociatedProduct. # noqa: E501 - - Catalog description of the product. # noqa: E501 - - :return: The product_description of this AssociatedProduct. # noqa: E501 - :rtype: str - """ - return self._product_description - - @product_description.setter - def product_description(self, product_description): - """Sets the product_description of this AssociatedProduct. - - Catalog description of the product. # noqa: E501 - - :param product_description: The product_description of this AssociatedProduct. # noqa: E501 - :type: str - """ - - self._product_description = product_description - - @property - def unit_price(self): - """Gets the unit_price of this AssociatedProduct. # noqa: E501 - - The price for a single unit of this product. # noqa: E501 - - :return: The unit_price of this AssociatedProduct. # noqa: E501 - :rtype: float - """ - return self._unit_price - - @unit_price.setter - def unit_price(self, unit_price): - """Sets the unit_price of this AssociatedProduct. - - The price for a single unit of this product. # noqa: E501 - - :param unit_price: The unit_price of this AssociatedProduct. # noqa: E501 - :type: float - """ - - self._unit_price = unit_price - - @property - def manufacturer(self): - """Gets the manufacturer of this AssociatedProduct. # noqa: E501 - - - :return: The manufacturer of this AssociatedProduct. # noqa: E501 - :rtype: PidVid - """ - return self._manufacturer - - @manufacturer.setter - def manufacturer(self, manufacturer): - """Sets the manufacturer of this AssociatedProduct. - - - :param manufacturer: The manufacturer of this AssociatedProduct. # noqa: E501 - :type: PidVid - """ - - self._manufacturer = manufacturer - - @property - def manufacturer_public_quantity(self): - """Gets the manufacturer_public_quantity of this AssociatedProduct. # noqa: E501 - - Quantity of this product available to order from manufacturer. # noqa: E501 - - :return: The manufacturer_public_quantity of this AssociatedProduct. # noqa: E501 - :rtype: int - """ - return self._manufacturer_public_quantity - - @manufacturer_public_quantity.setter - def manufacturer_public_quantity(self, manufacturer_public_quantity): - """Sets the manufacturer_public_quantity of this AssociatedProduct. - - Quantity of this product available to order from manufacturer. # noqa: E501 - - :param manufacturer_public_quantity: The manufacturer_public_quantity of this AssociatedProduct. # noqa: E501 - :type: int - """ - - self._manufacturer_public_quantity = manufacturer_public_quantity - - @property - def quantity_on_order(self): - """Gets the quantity_on_order of this AssociatedProduct. # noqa: E501 - - Quantity of this product ordered but not immediately available. # noqa: E501 - - :return: The quantity_on_order of this AssociatedProduct. # noqa: E501 - :rtype: int - """ - return self._quantity_on_order - - @quantity_on_order.setter - def quantity_on_order(self, quantity_on_order): - """Sets the quantity_on_order of this AssociatedProduct. - - Quantity of this product ordered but not immediately available. # noqa: E501 - - :param quantity_on_order: The quantity_on_order of this AssociatedProduct. # noqa: E501 - :type: int - """ - - self._quantity_on_order = quantity_on_order - - @property - def dk_plus_restriction(self): - """Gets the dk_plus_restriction of this AssociatedProduct. # noqa: E501 - - If true- this product is not available for purchase through the Ordering API - it must be purchased through the Digi-Key web site # noqa: E501 - - :return: The dk_plus_restriction of this AssociatedProduct. # noqa: E501 - :rtype: bool - """ - return self._dk_plus_restriction - - @dk_plus_restriction.setter - def dk_plus_restriction(self, dk_plus_restriction): - """Sets the dk_plus_restriction of this AssociatedProduct. - - If true- this product is not available for purchase through the Ordering API - it must be purchased through the Digi-Key web site # noqa: E501 - - :param dk_plus_restriction: The dk_plus_restriction of this AssociatedProduct. # noqa: E501 - :type: bool - """ - - self._dk_plus_restriction = dk_plus_restriction - - @property - def supplier_direct_ship(self): - """Gets the supplier_direct_ship of this AssociatedProduct. # noqa: E501 - - If true- this product is shipped directly from the Supplier # noqa: E501 - - :return: The supplier_direct_ship of this AssociatedProduct. # noqa: E501 - :rtype: bool - """ - return self._supplier_direct_ship - - @supplier_direct_ship.setter - def supplier_direct_ship(self, supplier_direct_ship): - """Sets the supplier_direct_ship of this AssociatedProduct. - - If true- this product is shipped directly from the Supplier # noqa: E501 - - :param supplier_direct_ship: The supplier_direct_ship of this AssociatedProduct. # noqa: E501 - :type: bool - """ - - self._supplier_direct_ship = supplier_direct_ship - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(AssociatedProduct, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AssociatedProduct): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/basic_product.py b/digikey/v3/batchproductdetails/models/basic_product.py deleted file mode 100644 index 08004d2..0000000 --- a/digikey/v3/batchproductdetails/models/basic_product.py +++ /dev/null @@ -1,449 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class BasicProduct(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'manufacturer_part_number': 'str', - 'minimum_order_quantity': 'int', - 'non_stock': 'bool', - 'packaging': 'PidVid', - 'quantity_available': 'int', - 'digi_key_part_number': 'str', - 'product_description': 'str', - 'unit_price': 'float', - 'manufacturer': 'PidVid', - 'manufacturer_public_quantity': 'int', - 'quantity_on_order': 'int', - 'dk_plus_restriction': 'bool', - 'supplier_direct_ship': 'bool' - } - - attribute_map = { - 'manufacturer_part_number': 'ManufacturerPartNumber', - 'minimum_order_quantity': 'MinimumOrderQuantity', - 'non_stock': 'NonStock', - 'packaging': 'Packaging', - 'quantity_available': 'QuantityAvailable', - 'digi_key_part_number': 'DigiKeyPartNumber', - 'product_description': 'ProductDescription', - 'unit_price': 'UnitPrice', - 'manufacturer': 'Manufacturer', - 'manufacturer_public_quantity': 'ManufacturerPublicQuantity', - 'quantity_on_order': 'QuantityOnOrder', - 'dk_plus_restriction': 'DKPlusRestriction', - 'supplier_direct_ship': 'SupplierDirectShip' - } - - def __init__(self, manufacturer_part_number=None, minimum_order_quantity=None, non_stock=None, packaging=None, quantity_available=None, digi_key_part_number=None, product_description=None, unit_price=None, manufacturer=None, manufacturer_public_quantity=None, quantity_on_order=None, dk_plus_restriction=None, supplier_direct_ship=None): # noqa: E501 - """BasicProduct - a model defined in Swagger""" # noqa: E501 - - self._manufacturer_part_number = None - self._minimum_order_quantity = None - self._non_stock = None - self._packaging = None - self._quantity_available = None - self._digi_key_part_number = None - self._product_description = None - self._unit_price = None - self._manufacturer = None - self._manufacturer_public_quantity = None - self._quantity_on_order = None - self._dk_plus_restriction = None - self._supplier_direct_ship = None - self.discriminator = None - - if manufacturer_part_number is not None: - self.manufacturer_part_number = manufacturer_part_number - if minimum_order_quantity is not None: - self.minimum_order_quantity = minimum_order_quantity - if non_stock is not None: - self.non_stock = non_stock - if packaging is not None: - self.packaging = packaging - if quantity_available is not None: - self.quantity_available = quantity_available - if digi_key_part_number is not None: - self.digi_key_part_number = digi_key_part_number - if product_description is not None: - self.product_description = product_description - if unit_price is not None: - self.unit_price = unit_price - if manufacturer is not None: - self.manufacturer = manufacturer - if manufacturer_public_quantity is not None: - self.manufacturer_public_quantity = manufacturer_public_quantity - if quantity_on_order is not None: - self.quantity_on_order = quantity_on_order - if dk_plus_restriction is not None: - self.dk_plus_restriction = dk_plus_restriction - if supplier_direct_ship is not None: - self.supplier_direct_ship = supplier_direct_ship - - @property - def manufacturer_part_number(self): - """Gets the manufacturer_part_number of this BasicProduct. # noqa: E501 - - The manufacturer part number. Note that some manufacturer part numbers may be used by multiple manufacturers for different parts. # noqa: E501 - - :return: The manufacturer_part_number of this BasicProduct. # noqa: E501 - :rtype: str - """ - return self._manufacturer_part_number - - @manufacturer_part_number.setter - def manufacturer_part_number(self, manufacturer_part_number): - """Sets the manufacturer_part_number of this BasicProduct. - - The manufacturer part number. Note that some manufacturer part numbers may be used by multiple manufacturers for different parts. # noqa: E501 - - :param manufacturer_part_number: The manufacturer_part_number of this BasicProduct. # noqa: E501 - :type: str - """ - - self._manufacturer_part_number = manufacturer_part_number - - @property - def minimum_order_quantity(self): - """Gets the minimum_order_quantity of this BasicProduct. # noqa: E501 - - The minimum quantity to order from Digi-Key. # noqa: E501 - - :return: The minimum_order_quantity of this BasicProduct. # noqa: E501 - :rtype: int - """ - return self._minimum_order_quantity - - @minimum_order_quantity.setter - def minimum_order_quantity(self, minimum_order_quantity): - """Sets the minimum_order_quantity of this BasicProduct. - - The minimum quantity to order from Digi-Key. # noqa: E501 - - :param minimum_order_quantity: The minimum_order_quantity of this BasicProduct. # noqa: E501 - :type: int - """ - - self._minimum_order_quantity = minimum_order_quantity - - @property - def non_stock(self): - """Gets the non_stock of this BasicProduct. # noqa: E501 - - Indicates this product is a non stock product. # noqa: E501 - - :return: The non_stock of this BasicProduct. # noqa: E501 - :rtype: bool - """ - return self._non_stock - - @non_stock.setter - def non_stock(self, non_stock): - """Sets the non_stock of this BasicProduct. - - Indicates this product is a non stock product. # noqa: E501 - - :param non_stock: The non_stock of this BasicProduct. # noqa: E501 - :type: bool - """ - - self._non_stock = non_stock - - @property - def packaging(self): - """Gets the packaging of this BasicProduct. # noqa: E501 - - - :return: The packaging of this BasicProduct. # noqa: E501 - :rtype: PidVid - """ - return self._packaging - - @packaging.setter - def packaging(self, packaging): - """Sets the packaging of this BasicProduct. - - - :param packaging: The packaging of this BasicProduct. # noqa: E501 - :type: PidVid - """ - - self._packaging = packaging - - @property - def quantity_available(self): - """Gets the quantity_available of this BasicProduct. # noqa: E501 - - Quantity of the product available for immediate sale. # noqa: E501 - - :return: The quantity_available of this BasicProduct. # noqa: E501 - :rtype: int - """ - return self._quantity_available - - @quantity_available.setter - def quantity_available(self, quantity_available): - """Sets the quantity_available of this BasicProduct. - - Quantity of the product available for immediate sale. # noqa: E501 - - :param quantity_available: The quantity_available of this BasicProduct. # noqa: E501 - :type: int - """ - - self._quantity_available = quantity_available - - @property - def digi_key_part_number(self): - """Gets the digi_key_part_number of this BasicProduct. # noqa: E501 - - The Digi-Key part number. # noqa: E501 - - :return: The digi_key_part_number of this BasicProduct. # noqa: E501 - :rtype: str - """ - return self._digi_key_part_number - - @digi_key_part_number.setter - def digi_key_part_number(self, digi_key_part_number): - """Sets the digi_key_part_number of this BasicProduct. - - The Digi-Key part number. # noqa: E501 - - :param digi_key_part_number: The digi_key_part_number of this BasicProduct. # noqa: E501 - :type: str - """ - - self._digi_key_part_number = digi_key_part_number - - @property - def product_description(self): - """Gets the product_description of this BasicProduct. # noqa: E501 - - Catalog description of the product. # noqa: E501 - - :return: The product_description of this BasicProduct. # noqa: E501 - :rtype: str - """ - return self._product_description - - @product_description.setter - def product_description(self, product_description): - """Sets the product_description of this BasicProduct. - - Catalog description of the product. # noqa: E501 - - :param product_description: The product_description of this BasicProduct. # noqa: E501 - :type: str - """ - - self._product_description = product_description - - @property - def unit_price(self): - """Gets the unit_price of this BasicProduct. # noqa: E501 - - The price for a single unit of this product. # noqa: E501 - - :return: The unit_price of this BasicProduct. # noqa: E501 - :rtype: float - """ - return self._unit_price - - @unit_price.setter - def unit_price(self, unit_price): - """Sets the unit_price of this BasicProduct. - - The price for a single unit of this product. # noqa: E501 - - :param unit_price: The unit_price of this BasicProduct. # noqa: E501 - :type: float - """ - - self._unit_price = unit_price - - @property - def manufacturer(self): - """Gets the manufacturer of this BasicProduct. # noqa: E501 - - - :return: The manufacturer of this BasicProduct. # noqa: E501 - :rtype: PidVid - """ - return self._manufacturer - - @manufacturer.setter - def manufacturer(self, manufacturer): - """Sets the manufacturer of this BasicProduct. - - - :param manufacturer: The manufacturer of this BasicProduct. # noqa: E501 - :type: PidVid - """ - - self._manufacturer = manufacturer - - @property - def manufacturer_public_quantity(self): - """Gets the manufacturer_public_quantity of this BasicProduct. # noqa: E501 - - Quantity of this product available to order from manufacturer. # noqa: E501 - - :return: The manufacturer_public_quantity of this BasicProduct. # noqa: E501 - :rtype: int - """ - return self._manufacturer_public_quantity - - @manufacturer_public_quantity.setter - def manufacturer_public_quantity(self, manufacturer_public_quantity): - """Sets the manufacturer_public_quantity of this BasicProduct. - - Quantity of this product available to order from manufacturer. # noqa: E501 - - :param manufacturer_public_quantity: The manufacturer_public_quantity of this BasicProduct. # noqa: E501 - :type: int - """ - - self._manufacturer_public_quantity = manufacturer_public_quantity - - @property - def quantity_on_order(self): - """Gets the quantity_on_order of this BasicProduct. # noqa: E501 - - Quantity of this product ordered but not immediately available. # noqa: E501 - - :return: The quantity_on_order of this BasicProduct. # noqa: E501 - :rtype: int - """ - return self._quantity_on_order - - @quantity_on_order.setter - def quantity_on_order(self, quantity_on_order): - """Sets the quantity_on_order of this BasicProduct. - - Quantity of this product ordered but not immediately available. # noqa: E501 - - :param quantity_on_order: The quantity_on_order of this BasicProduct. # noqa: E501 - :type: int - """ - - self._quantity_on_order = quantity_on_order - - @property - def dk_plus_restriction(self): - """Gets the dk_plus_restriction of this BasicProduct. # noqa: E501 - - If true- this product is not available for purchase through the Ordering API - it must be purchased through the Digi-Key web site # noqa: E501 - - :return: The dk_plus_restriction of this BasicProduct. # noqa: E501 - :rtype: bool - """ - return self._dk_plus_restriction - - @dk_plus_restriction.setter - def dk_plus_restriction(self, dk_plus_restriction): - """Sets the dk_plus_restriction of this BasicProduct. - - If true- this product is not available for purchase through the Ordering API - it must be purchased through the Digi-Key web site # noqa: E501 - - :param dk_plus_restriction: The dk_plus_restriction of this BasicProduct. # noqa: E501 - :type: bool - """ - - self._dk_plus_restriction = dk_plus_restriction - - @property - def supplier_direct_ship(self): - """Gets the supplier_direct_ship of this BasicProduct. # noqa: E501 - - If true- this product is shipped directly from the Supplier # noqa: E501 - - :return: The supplier_direct_ship of this BasicProduct. # noqa: E501 - :rtype: bool - """ - return self._supplier_direct_ship - - @supplier_direct_ship.setter - def supplier_direct_ship(self, supplier_direct_ship): - """Sets the supplier_direct_ship of this BasicProduct. - - If true- this product is shipped directly from the Supplier # noqa: E501 - - :param supplier_direct_ship: The supplier_direct_ship of this BasicProduct. # noqa: E501 - :type: bool - """ - - self._supplier_direct_ship = supplier_direct_ship - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(BasicProduct, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, BasicProduct): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/batch_product_details_request.py b/digikey/v3/batchproductdetails/models/batch_product_details_request.py deleted file mode 100644 index 9a92953..0000000 --- a/digikey/v3/batchproductdetails/models/batch_product_details_request.py +++ /dev/null @@ -1,118 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class BatchProductDetailsRequest(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'products': 'list[str]' - } - - attribute_map = { - 'products': 'Products' - } - - def __init__(self, products=None): # noqa: E501 - """BatchProductDetailsRequest - a model defined in Swagger""" # noqa: E501 - - self._products = None - self.discriminator = None - - self.products = products - - @property - def products(self): - """Gets the products of this BatchProductDetailsRequest. # noqa: E501 - - # noqa: E501 - - :return: The products of this BatchProductDetailsRequest. # noqa: E501 - :rtype: list[str] - """ - return self._products - - @products.setter - def products(self, products): - """Sets the products of this BatchProductDetailsRequest. - - # noqa: E501 - - :param products: The products of this BatchProductDetailsRequest. # noqa: E501 - :type: list[str] - """ - if products is None: - raise ValueError("Invalid value for `products`, must not be `None`") # noqa: E501 - - self._products = products - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(BatchProductDetailsRequest, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, BatchProductDetailsRequest): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/batch_product_details_response.py b/digikey/v3/batchproductdetails/models/batch_product_details_response.py deleted file mode 100644 index 2291e42..0000000 --- a/digikey/v3/batchproductdetails/models/batch_product_details_response.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class BatchProductDetailsResponse(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'product_details': 'list[ProductDetails]', - 'errors': 'list[str]' - } - - attribute_map = { - 'product_details': 'ProductDetails', - 'errors': 'Errors' - } - - def __init__(self, product_details=None, errors=None): # noqa: E501 - """BatchProductDetailsResponse - a model defined in Swagger""" # noqa: E501 - - self._product_details = None - self._errors = None - self.discriminator = None - - if product_details is not None: - self.product_details = product_details - if errors is not None: - self.errors = errors - - @property - def product_details(self): - """Gets the product_details of this BatchProductDetailsResponse. # noqa: E501 - - List of ProductDetails # noqa: E501 - - :return: The product_details of this BatchProductDetailsResponse. # noqa: E501 - :rtype: list[ProductDetails] - """ - return self._product_details - - @product_details.setter - def product_details(self, product_details): - """Sets the product_details of this BatchProductDetailsResponse. - - List of ProductDetails # noqa: E501 - - :param product_details: The product_details of this BatchProductDetailsResponse. # noqa: E501 - :type: list[ProductDetails] - """ - - self._product_details = product_details - - @property - def errors(self): - """Gets the errors of this BatchProductDetailsResponse. # noqa: E501 - - List of Errors # noqa: E501 - - :return: The errors of this BatchProductDetailsResponse. # noqa: E501 - :rtype: list[str] - """ - return self._errors - - @errors.setter - def errors(self, errors): - """Sets the errors of this BatchProductDetailsResponse. - - List of Errors # noqa: E501 - - :param errors: The errors of this BatchProductDetailsResponse. # noqa: E501 - :type: list[str] - """ - - self._errors = errors - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(BatchProductDetailsResponse, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, BatchProductDetailsResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/iso_search_locale.py b/digikey/v3/batchproductdetails/models/iso_search_locale.py deleted file mode 100644 index 69b9f62..0000000 --- a/digikey/v3/batchproductdetails/models/iso_search_locale.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class IsoSearchLocale(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'site': 'str', - 'language': 'str', - 'currency': 'str', - 'ship_to_country': 'str' - } - - attribute_map = { - 'site': 'Site', - 'language': 'Language', - 'currency': 'Currency', - 'ship_to_country': 'ShipToCountry' - } - - def __init__(self, site=None, language=None, currency=None, ship_to_country=None): # noqa: E501 - """IsoSearchLocale - a model defined in Swagger""" # noqa: E501 - - self._site = None - self._language = None - self._currency = None - self._ship_to_country = None - self.discriminator = None - - if site is not None: - self.site = site - if language is not None: - self.language = language - if currency is not None: - self.currency = currency - if ship_to_country is not None: - self.ship_to_country = ship_to_country - - @property - def site(self): - """Gets the site of this IsoSearchLocale. # noqa: E501 - - The site used for the API call. # noqa: E501 - - :return: The site of this IsoSearchLocale. # noqa: E501 - :rtype: str - """ - return self._site - - @site.setter - def site(self, site): - """Sets the site of this IsoSearchLocale. - - The site used for the API call. # noqa: E501 - - :param site: The site of this IsoSearchLocale. # noqa: E501 - :type: str - """ - - self._site = site - - @property - def language(self): - """Gets the language of this IsoSearchLocale. # noqa: E501 - - The language used for the API call. If the provided language is not valid for the site, it will be set to the site default. # noqa: E501 - - :return: The language of this IsoSearchLocale. # noqa: E501 - :rtype: str - """ - return self._language - - @language.setter - def language(self, language): - """Sets the language of this IsoSearchLocale. - - The language used for the API call. If the provided language is not valid for the site, it will be set to the site default. # noqa: E501 - - :param language: The language of this IsoSearchLocale. # noqa: E501 - :type: str - """ - - self._language = language - - @property - def currency(self): - """Gets the currency of this IsoSearchLocale. # noqa: E501 - - The currency used for the API call. If the provided currency is not valid for the site, it will be set to the site default. # noqa: E501 - - :return: The currency of this IsoSearchLocale. # noqa: E501 - :rtype: str - """ - return self._currency - - @currency.setter - def currency(self, currency): - """Sets the currency of this IsoSearchLocale. - - The currency used for the API call. If the provided currency is not valid for the site, it will be set to the site default. # noqa: E501 - - :param currency: The currency of this IsoSearchLocale. # noqa: E501 - :type: str - """ - - self._currency = currency - - @property - def ship_to_country(self): - """Gets the ship_to_country of this IsoSearchLocale. # noqa: E501 - - The destination for shipping the product. This is used for tariffs and regional pricing. # noqa: E501 - - :return: The ship_to_country of this IsoSearchLocale. # noqa: E501 - :rtype: str - """ - return self._ship_to_country - - @ship_to_country.setter - def ship_to_country(self, ship_to_country): - """Sets the ship_to_country of this IsoSearchLocale. - - The destination for shipping the product. This is used for tariffs and regional pricing. # noqa: E501 - - :param ship_to_country: The ship_to_country of this IsoSearchLocale. # noqa: E501 - :type: str - """ - - self._ship_to_country = ship_to_country - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(IsoSearchLocale, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, IsoSearchLocale): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/kit_part.py b/digikey/v3/batchproductdetails/models/kit_part.py deleted file mode 100644 index f891562..0000000 --- a/digikey/v3/batchproductdetails/models/kit_part.py +++ /dev/null @@ -1,143 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class KitPart(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'associated_product': 'AssociatedProduct', - 'kit_part_quantity': 'int' - } - - attribute_map = { - 'associated_product': 'AssociatedProduct', - 'kit_part_quantity': 'KitPartQuantity' - } - - def __init__(self, associated_product=None, kit_part_quantity=None): # noqa: E501 - """KitPart - a model defined in Swagger""" # noqa: E501 - - self._associated_product = None - self._kit_part_quantity = None - self.discriminator = None - - if associated_product is not None: - self.associated_product = associated_product - if kit_part_quantity is not None: - self.kit_part_quantity = kit_part_quantity - - @property - def associated_product(self): - """Gets the associated_product of this KitPart. # noqa: E501 - - - :return: The associated_product of this KitPart. # noqa: E501 - :rtype: AssociatedProduct - """ - return self._associated_product - - @associated_product.setter - def associated_product(self, associated_product): - """Sets the associated_product of this KitPart. - - - :param associated_product: The associated_product of this KitPart. # noqa: E501 - :type: AssociatedProduct - """ - - self._associated_product = associated_product - - @property - def kit_part_quantity(self): - """Gets the kit_part_quantity of this KitPart. # noqa: E501 - - Number of the product in the Kit. # noqa: E501 - - :return: The kit_part_quantity of this KitPart. # noqa: E501 - :rtype: int - """ - return self._kit_part_quantity - - @kit_part_quantity.setter - def kit_part_quantity(self, kit_part_quantity): - """Sets the kit_part_quantity of this KitPart. - - Number of the product in the Kit. # noqa: E501 - - :param kit_part_quantity: The kit_part_quantity of this KitPart. # noqa: E501 - :type: int - """ - - self._kit_part_quantity = kit_part_quantity - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(KitPart, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, KitPart): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/limited_taxonomy.py b/digikey/v3/batchproductdetails/models/limited_taxonomy.py deleted file mode 100644 index ae5ccbc..0000000 --- a/digikey/v3/batchproductdetails/models/limited_taxonomy.py +++ /dev/null @@ -1,285 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class LimitedTaxonomy(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'children': 'list[LimitedTaxonomy]', - 'product_count': 'int', - 'new_product_count': 'int', - 'parameter_id': 'int', - 'value_id': 'str', - 'parameter': 'str', - 'value': 'str' - } - - attribute_map = { - 'children': 'Children', - 'product_count': 'ProductCount', - 'new_product_count': 'NewProductCount', - 'parameter_id': 'ParameterId', - 'value_id': 'ValueId', - 'parameter': 'Parameter', - 'value': 'Value' - } - - def __init__(self, children=None, product_count=None, new_product_count=None, parameter_id=None, value_id=None, parameter=None, value=None): # noqa: E501 - """LimitedTaxonomy - a model defined in Swagger""" # noqa: E501 - - self._children = None - self._product_count = None - self._new_product_count = None - self._parameter_id = None - self._value_id = None - self._parameter = None - self._value = None - self.discriminator = None - - if children is not None: - self.children = children - if product_count is not None: - self.product_count = product_count - if new_product_count is not None: - self.new_product_count = new_product_count - if parameter_id is not None: - self.parameter_id = parameter_id - if value_id is not None: - self.value_id = value_id - if parameter is not None: - self.parameter = parameter - if value is not None: - self.value = value - - @property - def children(self): - """Gets the children of this LimitedTaxonomy. # noqa: E501 - - List of taxonomies contained within this taxonomy. # noqa: E501 - - :return: The children of this LimitedTaxonomy. # noqa: E501 - :rtype: list[LimitedTaxonomy] - """ - return self._children - - @children.setter - def children(self, children): - """Sets the children of this LimitedTaxonomy. - - List of taxonomies contained within this taxonomy. # noqa: E501 - - :param children: The children of this LimitedTaxonomy. # noqa: E501 - :type: list[LimitedTaxonomy] - """ - - self._children = children - - @property - def product_count(self): - """Gets the product_count of this LimitedTaxonomy. # noqa: E501 - - The number of products contained within this taxonomy. # noqa: E501 - - :return: The product_count of this LimitedTaxonomy. # noqa: E501 - :rtype: int - """ - return self._product_count - - @product_count.setter - def product_count(self, product_count): - """Sets the product_count of this LimitedTaxonomy. - - The number of products contained within this taxonomy. # noqa: E501 - - :param product_count: The product_count of this LimitedTaxonomy. # noqa: E501 - :type: int - """ - - self._product_count = product_count - - @property - def new_product_count(self): - """Gets the new_product_count of this LimitedTaxonomy. # noqa: E501 - - The number of new products contained within this taxonomy. # noqa: E501 - - :return: The new_product_count of this LimitedTaxonomy. # noqa: E501 - :rtype: int - """ - return self._new_product_count - - @new_product_count.setter - def new_product_count(self, new_product_count): - """Sets the new_product_count of this LimitedTaxonomy. - - The number of new products contained within this taxonomy. # noqa: E501 - - :param new_product_count: The new_product_count of this LimitedTaxonomy. # noqa: E501 - :type: int - """ - - self._new_product_count = new_product_count - - @property - def parameter_id(self): - """Gets the parameter_id of this LimitedTaxonomy. # noqa: E501 - - The Id of the parameter. # noqa: E501 - - :return: The parameter_id of this LimitedTaxonomy. # noqa: E501 - :rtype: int - """ - return self._parameter_id - - @parameter_id.setter - def parameter_id(self, parameter_id): - """Sets the parameter_id of this LimitedTaxonomy. - - The Id of the parameter. # noqa: E501 - - :param parameter_id: The parameter_id of this LimitedTaxonomy. # noqa: E501 - :type: int - """ - - self._parameter_id = parameter_id - - @property - def value_id(self): - """Gets the value_id of this LimitedTaxonomy. # noqa: E501 - - The Id of the value. # noqa: E501 - - :return: The value_id of this LimitedTaxonomy. # noqa: E501 - :rtype: str - """ - return self._value_id - - @value_id.setter - def value_id(self, value_id): - """Sets the value_id of this LimitedTaxonomy. - - The Id of the value. # noqa: E501 - - :param value_id: The value_id of this LimitedTaxonomy. # noqa: E501 - :type: str - """ - - self._value_id = value_id - - @property - def parameter(self): - """Gets the parameter of this LimitedTaxonomy. # noqa: E501 - - The name of the parameter. # noqa: E501 - - :return: The parameter of this LimitedTaxonomy. # noqa: E501 - :rtype: str - """ - return self._parameter - - @parameter.setter - def parameter(self, parameter): - """Sets the parameter of this LimitedTaxonomy. - - The name of the parameter. # noqa: E501 - - :param parameter: The parameter of this LimitedTaxonomy. # noqa: E501 - :type: str - """ - - self._parameter = parameter - - @property - def value(self): - """Gets the value of this LimitedTaxonomy. # noqa: E501 - - The name of the value. # noqa: E501 - - :return: The value of this LimitedTaxonomy. # noqa: E501 - :rtype: str - """ - return self._value - - @value.setter - def value(self, value): - """Sets the value of this LimitedTaxonomy. - - The name of the value. # noqa: E501 - - :param value: The value of this LimitedTaxonomy. # noqa: E501 - :type: str - """ - - self._value = value - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(LimitedTaxonomy, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, LimitedTaxonomy): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/media_links.py b/digikey/v3/batchproductdetails/models/media_links.py deleted file mode 100644 index 67bf45f..0000000 --- a/digikey/v3/batchproductdetails/models/media_links.py +++ /dev/null @@ -1,229 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class MediaLinks(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'media_type': 'str', - 'title': 'str', - 'small_photo': 'str', - 'thumbnail': 'str', - 'url': 'str' - } - - attribute_map = { - 'media_type': 'MediaType', - 'title': 'Title', - 'small_photo': 'SmallPhoto', - 'thumbnail': 'Thumbnail', - 'url': 'Url' - } - - def __init__(self, media_type=None, title=None, small_photo=None, thumbnail=None, url=None): # noqa: E501 - """MediaLinks - a model defined in Swagger""" # noqa: E501 - - self._media_type = None - self._title = None - self._small_photo = None - self._thumbnail = None - self._url = None - self.discriminator = None - - if media_type is not None: - self.media_type = media_type - if title is not None: - self.title = title - if small_photo is not None: - self.small_photo = small_photo - if thumbnail is not None: - self.thumbnail = thumbnail - if url is not None: - self.url = url - - @property - def media_type(self): - """Gets the media_type of this MediaLinks. # noqa: E501 - - The type of media. # noqa: E501 - - :return: The media_type of this MediaLinks. # noqa: E501 - :rtype: str - """ - return self._media_type - - @media_type.setter - def media_type(self, media_type): - """Sets the media_type of this MediaLinks. - - The type of media. # noqa: E501 - - :param media_type: The media_type of this MediaLinks. # noqa: E501 - :type: str - """ - - self._media_type = media_type - - @property - def title(self): - """Gets the title of this MediaLinks. # noqa: E501 - - The title of the media. # noqa: E501 - - :return: The title of this MediaLinks. # noqa: E501 - :rtype: str - """ - return self._title - - @title.setter - def title(self, title): - """Sets the title of this MediaLinks. - - The title of the media. # noqa: E501 - - :param title: The title of this MediaLinks. # noqa: E501 - :type: str - """ - - self._title = title - - @property - def small_photo(self): - """Gets the small_photo of this MediaLinks. # noqa: E501 - - URL to a small photo. # noqa: E501 - - :return: The small_photo of this MediaLinks. # noqa: E501 - :rtype: str - """ - return self._small_photo - - @small_photo.setter - def small_photo(self, small_photo): - """Sets the small_photo of this MediaLinks. - - URL to a small photo. # noqa: E501 - - :param small_photo: The small_photo of this MediaLinks. # noqa: E501 - :type: str - """ - - self._small_photo = small_photo - - @property - def thumbnail(self): - """Gets the thumbnail of this MediaLinks. # noqa: E501 - - URL to the thumbnail image of the media. # noqa: E501 - - :return: The thumbnail of this MediaLinks. # noqa: E501 - :rtype: str - """ - return self._thumbnail - - @thumbnail.setter - def thumbnail(self, thumbnail): - """Sets the thumbnail of this MediaLinks. - - URL to the thumbnail image of the media. # noqa: E501 - - :param thumbnail: The thumbnail of this MediaLinks. # noqa: E501 - :type: str - """ - - self._thumbnail = thumbnail - - @property - def url(self): - """Gets the url of this MediaLinks. # noqa: E501 - - URL of the media. # noqa: E501 - - :return: The url of this MediaLinks. # noqa: E501 - :rtype: str - """ - return self._url - - @url.setter - def url(self, url): - """Sets the url of this MediaLinks. - - URL of the media. # noqa: E501 - - :param url: The url of this MediaLinks. # noqa: E501 - :type: str - """ - - self._url = url - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(MediaLinks, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, MediaLinks): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/pid_vid.py b/digikey/v3/batchproductdetails/models/pid_vid.py deleted file mode 100644 index 5561213..0000000 --- a/digikey/v3/batchproductdetails/models/pid_vid.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class PidVid(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'parameter_id': 'int', - 'value_id': 'str', - 'parameter': 'str', - 'value': 'str' - } - - attribute_map = { - 'parameter_id': 'ParameterId', - 'value_id': 'ValueId', - 'parameter': 'Parameter', - 'value': 'Value' - } - - def __init__(self, parameter_id=None, value_id=None, parameter=None, value=None): # noqa: E501 - """PidVid - a model defined in Swagger""" # noqa: E501 - - self._parameter_id = None - self._value_id = None - self._parameter = None - self._value = None - self.discriminator = None - - if parameter_id is not None: - self.parameter_id = parameter_id - if value_id is not None: - self.value_id = value_id - if parameter is not None: - self.parameter = parameter - if value is not None: - self.value = value - - @property - def parameter_id(self): - """Gets the parameter_id of this PidVid. # noqa: E501 - - The Id of the parameter. # noqa: E501 - - :return: The parameter_id of this PidVid. # noqa: E501 - :rtype: int - """ - return self._parameter_id - - @parameter_id.setter - def parameter_id(self, parameter_id): - """Sets the parameter_id of this PidVid. - - The Id of the parameter. # noqa: E501 - - :param parameter_id: The parameter_id of this PidVid. # noqa: E501 - :type: int - """ - - self._parameter_id = parameter_id - - @property - def value_id(self): - """Gets the value_id of this PidVid. # noqa: E501 - - The Id of the value. # noqa: E501 - - :return: The value_id of this PidVid. # noqa: E501 - :rtype: str - """ - return self._value_id - - @value_id.setter - def value_id(self, value_id): - """Sets the value_id of this PidVid. - - The Id of the value. # noqa: E501 - - :param value_id: The value_id of this PidVid. # noqa: E501 - :type: str - """ - - self._value_id = value_id - - @property - def parameter(self): - """Gets the parameter of this PidVid. # noqa: E501 - - The name of the parameter. # noqa: E501 - - :return: The parameter of this PidVid. # noqa: E501 - :rtype: str - """ - return self._parameter - - @parameter.setter - def parameter(self, parameter): - """Sets the parameter of this PidVid. - - The name of the parameter. # noqa: E501 - - :param parameter: The parameter of this PidVid. # noqa: E501 - :type: str - """ - - self._parameter = parameter - - @property - def value(self): - """Gets the value of this PidVid. # noqa: E501 - - The name of the value. # noqa: E501 - - :return: The value of this PidVid. # noqa: E501 - :rtype: str - """ - return self._value - - @value.setter - def value(self, value): - """Sets the value of this PidVid. - - The name of the value. # noqa: E501 - - :param value: The value of this PidVid. # noqa: E501 - :type: str - """ - - self._value = value - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PidVid, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PidVid): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/price_break.py b/digikey/v3/batchproductdetails/models/price_break.py deleted file mode 100644 index 2e24cda..0000000 --- a/digikey/v3/batchproductdetails/models/price_break.py +++ /dev/null @@ -1,173 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class PriceBreak(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'break_quantity': 'int', - 'unit_price': 'float', - 'total_price': 'float' - } - - attribute_map = { - 'break_quantity': 'BreakQuantity', - 'unit_price': 'UnitPrice', - 'total_price': 'TotalPrice' - } - - def __init__(self, break_quantity=None, unit_price=None, total_price=None): # noqa: E501 - """PriceBreak - a model defined in Swagger""" # noqa: E501 - - self._break_quantity = None - self._unit_price = None - self._total_price = None - self.discriminator = None - - if break_quantity is not None: - self.break_quantity = break_quantity - if unit_price is not None: - self.unit_price = unit_price - if total_price is not None: - self.total_price = total_price - - @property - def break_quantity(self): - """Gets the break_quantity of this PriceBreak. # noqa: E501 - - Price tiers based on the available quantities of the product. # noqa: E501 - - :return: The break_quantity of this PriceBreak. # noqa: E501 - :rtype: int - """ - return self._break_quantity - - @break_quantity.setter - def break_quantity(self, break_quantity): - """Sets the break_quantity of this PriceBreak. - - Price tiers based on the available quantities of the product. # noqa: E501 - - :param break_quantity: The break_quantity of this PriceBreak. # noqa: E501 - :type: int - """ - - self._break_quantity = break_quantity - - @property - def unit_price(self): - """Gets the unit_price of this PriceBreak. # noqa: E501 - - Price of a single unit of the product at this break. # noqa: E501 - - :return: The unit_price of this PriceBreak. # noqa: E501 - :rtype: float - """ - return self._unit_price - - @unit_price.setter - def unit_price(self, unit_price): - """Sets the unit_price of this PriceBreak. - - Price of a single unit of the product at this break. # noqa: E501 - - :param unit_price: The unit_price of this PriceBreak. # noqa: E501 - :type: float - """ - - self._unit_price = unit_price - - @property - def total_price(self): - """Gets the total_price of this PriceBreak. # noqa: E501 - - Price of BreakQuantity units of the product. # noqa: E501 - - :return: The total_price of this PriceBreak. # noqa: E501 - :rtype: float - """ - return self._total_price - - @total_price.setter - def total_price(self, total_price): - """Sets the total_price of this PriceBreak. - - Price of BreakQuantity units of the product. # noqa: E501 - - :param total_price: The total_price of this PriceBreak. # noqa: E501 - :type: float - """ - - self._total_price = total_price - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PriceBreak, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PriceBreak): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/models/product_details.py b/digikey/v3/batchproductdetails/models/product_details.py deleted file mode 100644 index a0d0473..0000000 --- a/digikey/v3/batchproductdetails/models/product_details.py +++ /dev/null @@ -1,1423 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class ProductDetails(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'my_pricing': 'list[PriceBreak]', - 'obsolete': 'bool', - 'media_links': 'list[MediaLinks]', - 'standard_package': 'int', - 'limited_taxonomy': 'LimitedTaxonomy', - 'kits': 'list[AssociatedProduct]', - 'kit_contents': 'list[KitPart]', - 'mating_products': 'list[AssociatedProduct]', - 'search_locale_used': 'IsoSearchLocale', - 'associated_products': 'list[AssociatedProduct]', - 'for_use_with_products': 'list[AssociatedProduct]', - 'rohs_subs': 'list[AssociatedProduct]', - 'suggested_subs': 'list[AssociatedProduct]', - 'additional_value_fee': 'float', - 'reach_effective_date': 'str', - 'standard_pricing': 'list[PriceBreak]', - 'ro_hs_status': 'str', - 'lead_status': 'str', - 'parameters': 'list[PidVid]', - 'product_url': 'str', - 'primary_datasheet': 'str', - 'primary_photo': 'str', - 'primary_video': 'str', - 'series': 'PidVid', - 'manufacturer_lead_weeks': 'str', - 'manufacturer_page_url': 'str', - 'product_status': 'str', - 'date_last_buy_chance': 'datetime', - 'alternate_packaging': 'list[BasicProduct]', - 'detailed_description': 'str', - 'reach_status': 'str', - 'export_control_class_number': 'str', - 'htsus_code': 'str', - 'tariff_description': 'str', - 'moisture_sensitivity_level': 'str', - 'manufacturer_part_number': 'str', - 'minimum_order_quantity': 'int', - 'non_stock': 'bool', - 'packaging': 'PidVid', - 'quantity_available': 'int', - 'digi_key_part_number': 'str', - 'product_description': 'str', - 'unit_price': 'float', - 'manufacturer': 'PidVid', - 'manufacturer_public_quantity': 'int', - 'quantity_on_order': 'int', - 'dk_plus_restriction': 'bool', - 'supplier_direct_ship': 'bool' - } - - attribute_map = { - 'my_pricing': 'MyPricing', - 'obsolete': 'Obsolete', - 'media_links': 'MediaLinks', - 'standard_package': 'StandardPackage', - 'limited_taxonomy': 'LimitedTaxonomy', - 'kits': 'Kits', - 'kit_contents': 'KitContents', - 'mating_products': 'MatingProducts', - 'search_locale_used': 'SearchLocaleUsed', - 'associated_products': 'AssociatedProducts', - 'for_use_with_products': 'ForUseWithProducts', - 'rohs_subs': 'RohsSubs', - 'suggested_subs': 'SuggestedSubs', - 'additional_value_fee': 'AdditionalValueFee', - 'reach_effective_date': 'ReachEffectiveDate', - 'standard_pricing': 'StandardPricing', - 'ro_hs_status': 'RoHSStatus', - 'lead_status': 'LeadStatus', - 'parameters': 'Parameters', - 'product_url': 'ProductUrl', - 'primary_datasheet': 'PrimaryDatasheet', - 'primary_photo': 'PrimaryPhoto', - 'primary_video': 'PrimaryVideo', - 'series': 'Series', - 'manufacturer_lead_weeks': 'ManufacturerLeadWeeks', - 'manufacturer_page_url': 'ManufacturerPageUrl', - 'product_status': 'ProductStatus', - 'date_last_buy_chance': 'DateLastBuyChance', - 'alternate_packaging': 'AlternatePackaging', - 'detailed_description': 'DetailedDescription', - 'reach_status': 'ReachStatus', - 'export_control_class_number': 'ExportControlClassNumber', - 'htsus_code': 'HTSUSCode', - 'tariff_description': 'TariffDescription', - 'moisture_sensitivity_level': 'MoistureSensitivityLevel', - 'manufacturer_part_number': 'ManufacturerPartNumber', - 'minimum_order_quantity': 'MinimumOrderQuantity', - 'non_stock': 'NonStock', - 'packaging': 'Packaging', - 'quantity_available': 'QuantityAvailable', - 'digi_key_part_number': 'DigiKeyPartNumber', - 'product_description': 'ProductDescription', - 'unit_price': 'UnitPrice', - 'manufacturer': 'Manufacturer', - 'manufacturer_public_quantity': 'ManufacturerPublicQuantity', - 'quantity_on_order': 'QuantityOnOrder', - 'dk_plus_restriction': 'DKPlusRestriction', - 'supplier_direct_ship': 'SupplierDirectShip' - } - - def __init__(self, my_pricing=None, obsolete=None, media_links=None, standard_package=None, limited_taxonomy=None, kits=None, kit_contents=None, mating_products=None, search_locale_used=None, associated_products=None, for_use_with_products=None, rohs_subs=None, suggested_subs=None, additional_value_fee=None, reach_effective_date=None, standard_pricing=None, ro_hs_status=None, lead_status=None, parameters=None, product_url=None, primary_datasheet=None, primary_photo=None, primary_video=None, series=None, manufacturer_lead_weeks=None, manufacturer_page_url=None, product_status=None, date_last_buy_chance=None, alternate_packaging=None, detailed_description=None, reach_status=None, export_control_class_number=None, htsus_code=None, tariff_description=None, moisture_sensitivity_level=None, manufacturer_part_number=None, minimum_order_quantity=None, non_stock=None, packaging=None, quantity_available=None, digi_key_part_number=None, product_description=None, unit_price=None, manufacturer=None, manufacturer_public_quantity=None, quantity_on_order=None, dk_plus_restriction=None, supplier_direct_ship=None): # noqa: E501 - """ProductDetails - a model defined in Swagger""" # noqa: E501 - - self._my_pricing = None - self._obsolete = None - self._media_links = None - self._standard_package = None - self._limited_taxonomy = None - self._kits = None - self._kit_contents = None - self._mating_products = None - self._search_locale_used = None - self._associated_products = None - self._for_use_with_products = None - self._rohs_subs = None - self._suggested_subs = None - self._additional_value_fee = None - self._reach_effective_date = None - self._standard_pricing = None - self._ro_hs_status = None - self._lead_status = None - self._parameters = None - self._product_url = None - self._primary_datasheet = None - self._primary_photo = None - self._primary_video = None - self._series = None - self._manufacturer_lead_weeks = None - self._manufacturer_page_url = None - self._product_status = None - self._date_last_buy_chance = None - self._alternate_packaging = None - self._detailed_description = None - self._reach_status = None - self._export_control_class_number = None - self._htsus_code = None - self._tariff_description = None - self._moisture_sensitivity_level = None - self._manufacturer_part_number = None - self._minimum_order_quantity = None - self._non_stock = None - self._packaging = None - self._quantity_available = None - self._digi_key_part_number = None - self._product_description = None - self._unit_price = None - self._manufacturer = None - self._manufacturer_public_quantity = None - self._quantity_on_order = None - self._dk_plus_restriction = None - self._supplier_direct_ship = None - self.discriminator = None - - if my_pricing is not None: - self.my_pricing = my_pricing - if obsolete is not None: - self.obsolete = obsolete - if media_links is not None: - self.media_links = media_links - if standard_package is not None: - self.standard_package = standard_package - if limited_taxonomy is not None: - self.limited_taxonomy = limited_taxonomy - if kits is not None: - self.kits = kits - if kit_contents is not None: - self.kit_contents = kit_contents - if mating_products is not None: - self.mating_products = mating_products - if search_locale_used is not None: - self.search_locale_used = search_locale_used - if associated_products is not None: - self.associated_products = associated_products - if for_use_with_products is not None: - self.for_use_with_products = for_use_with_products - if rohs_subs is not None: - self.rohs_subs = rohs_subs - if suggested_subs is not None: - self.suggested_subs = suggested_subs - if additional_value_fee is not None: - self.additional_value_fee = additional_value_fee - if reach_effective_date is not None: - self.reach_effective_date = reach_effective_date - if standard_pricing is not None: - self.standard_pricing = standard_pricing - if ro_hs_status is not None: - self.ro_hs_status = ro_hs_status - if lead_status is not None: - self.lead_status = lead_status - if parameters is not None: - self.parameters = parameters - if product_url is not None: - self.product_url = product_url - if primary_datasheet is not None: - self.primary_datasheet = primary_datasheet - if primary_photo is not None: - self.primary_photo = primary_photo - if primary_video is not None: - self.primary_video = primary_video - if series is not None: - self.series = series - if manufacturer_lead_weeks is not None: - self.manufacturer_lead_weeks = manufacturer_lead_weeks - if manufacturer_page_url is not None: - self.manufacturer_page_url = manufacturer_page_url - if product_status is not None: - self.product_status = product_status - if date_last_buy_chance is not None: - self.date_last_buy_chance = date_last_buy_chance - if alternate_packaging is not None: - self.alternate_packaging = alternate_packaging - if detailed_description is not None: - self.detailed_description = detailed_description - if reach_status is not None: - self.reach_status = reach_status - if export_control_class_number is not None: - self.export_control_class_number = export_control_class_number - if htsus_code is not None: - self.htsus_code = htsus_code - if tariff_description is not None: - self.tariff_description = tariff_description - if moisture_sensitivity_level is not None: - self.moisture_sensitivity_level = moisture_sensitivity_level - if manufacturer_part_number is not None: - self.manufacturer_part_number = manufacturer_part_number - if minimum_order_quantity is not None: - self.minimum_order_quantity = minimum_order_quantity - if non_stock is not None: - self.non_stock = non_stock - if packaging is not None: - self.packaging = packaging - if quantity_available is not None: - self.quantity_available = quantity_available - if digi_key_part_number is not None: - self.digi_key_part_number = digi_key_part_number - if product_description is not None: - self.product_description = product_description - if unit_price is not None: - self.unit_price = unit_price - if manufacturer is not None: - self.manufacturer = manufacturer - if manufacturer_public_quantity is not None: - self.manufacturer_public_quantity = manufacturer_public_quantity - if quantity_on_order is not None: - self.quantity_on_order = quantity_on_order - if dk_plus_restriction is not None: - self.dk_plus_restriction = dk_plus_restriction - if supplier_direct_ship is not None: - self.supplier_direct_ship = supplier_direct_ship - - @property - def my_pricing(self): - """Gets the my_pricing of this ProductDetails. # noqa: E501 - - Your pricing for the account with which you authenticated. Also dependent on locale information. # noqa: E501 - - :return: The my_pricing of this ProductDetails. # noqa: E501 - :rtype: list[PriceBreak] - """ - return self._my_pricing - - @my_pricing.setter - def my_pricing(self, my_pricing): - """Sets the my_pricing of this ProductDetails. - - Your pricing for the account with which you authenticated. Also dependent on locale information. # noqa: E501 - - :param my_pricing: The my_pricing of this ProductDetails. # noqa: E501 - :type: list[PriceBreak] - """ - - self._my_pricing = my_pricing - - @property - def obsolete(self): - """Gets the obsolete of this ProductDetails. # noqa: E501 - - Indicates whether this Part is obsolete. # noqa: E501 - - :return: The obsolete of this ProductDetails. # noqa: E501 - :rtype: bool - """ - return self._obsolete - - @obsolete.setter - def obsolete(self, obsolete): - """Sets the obsolete of this ProductDetails. - - Indicates whether this Part is obsolete. # noqa: E501 - - :param obsolete: The obsolete of this ProductDetails. # noqa: E501 - :type: bool - """ - - self._obsolete = obsolete - - @property - def media_links(self): - """Gets the media_links of this ProductDetails. # noqa: E501 - - Collection of MediaLinks objects. These can contain links to datasheets, photos or manuals. # noqa: E501 - - :return: The media_links of this ProductDetails. # noqa: E501 - :rtype: list[MediaLinks] - """ - return self._media_links - - @media_links.setter - def media_links(self, media_links): - """Sets the media_links of this ProductDetails. - - Collection of MediaLinks objects. These can contain links to datasheets, photos or manuals. # noqa: E501 - - :param media_links: The media_links of this ProductDetails. # noqa: E501 - :type: list[MediaLinks] - """ - - self._media_links = media_links - - @property - def standard_package(self): - """Gets the standard_package of this ProductDetails. # noqa: E501 - - The number of products in the manufacturer's standard package. # noqa: E501 - - :return: The standard_package of this ProductDetails. # noqa: E501 - :rtype: int - """ - return self._standard_package - - @standard_package.setter - def standard_package(self, standard_package): - """Sets the standard_package of this ProductDetails. - - The number of products in the manufacturer's standard package. # noqa: E501 - - :param standard_package: The standard_package of this ProductDetails. # noqa: E501 - :type: int - """ - - self._standard_package = standard_package - - @property - def limited_taxonomy(self): - """Gets the limited_taxonomy of this ProductDetails. # noqa: E501 - - - :return: The limited_taxonomy of this ProductDetails. # noqa: E501 - :rtype: LimitedTaxonomy - """ - return self._limited_taxonomy - - @limited_taxonomy.setter - def limited_taxonomy(self, limited_taxonomy): - """Sets the limited_taxonomy of this ProductDetails. - - - :param limited_taxonomy: The limited_taxonomy of this ProductDetails. # noqa: E501 - :type: LimitedTaxonomy - """ - - self._limited_taxonomy = limited_taxonomy - - @property - def kits(self): - """Gets the kits of this ProductDetails. # noqa: E501 - - Kits that this product is contained in. # noqa: E501 - - :return: The kits of this ProductDetails. # noqa: E501 - :rtype: list[AssociatedProduct] - """ - return self._kits - - @kits.setter - def kits(self, kits): - """Sets the kits of this ProductDetails. - - Kits that this product is contained in. # noqa: E501 - - :param kits: The kits of this ProductDetails. # noqa: E501 - :type: list[AssociatedProduct] - """ - - self._kits = kits - - @property - def kit_contents(self): - """Gets the kit_contents of this ProductDetails. # noqa: E501 - - Products contained within this product. Only applicable if this product is a kit. # noqa: E501 - - :return: The kit_contents of this ProductDetails. # noqa: E501 - :rtype: list[KitPart] - """ - return self._kit_contents - - @kit_contents.setter - def kit_contents(self, kit_contents): - """Sets the kit_contents of this ProductDetails. - - Products contained within this product. Only applicable if this product is a kit. # noqa: E501 - - :param kit_contents: The kit_contents of this ProductDetails. # noqa: E501 - :type: list[KitPart] - """ - - self._kit_contents = kit_contents - - @property - def mating_products(self): - """Gets the mating_products of this ProductDetails. # noqa: E501 - - An association of same manufacturer products that mate with each other. # noqa: E501 - - :return: The mating_products of this ProductDetails. # noqa: E501 - :rtype: list[AssociatedProduct] - """ - return self._mating_products - - @mating_products.setter - def mating_products(self, mating_products): - """Sets the mating_products of this ProductDetails. - - An association of same manufacturer products that mate with each other. # noqa: E501 - - :param mating_products: The mating_products of this ProductDetails. # noqa: E501 - :type: list[AssociatedProduct] - """ - - self._mating_products = mating_products - - @property - def search_locale_used(self): - """Gets the search_locale_used of this ProductDetails. # noqa: E501 - - - :return: The search_locale_used of this ProductDetails. # noqa: E501 - :rtype: IsoSearchLocale - """ - return self._search_locale_used - - @search_locale_used.setter - def search_locale_used(self, search_locale_used): - """Sets the search_locale_used of this ProductDetails. - - - :param search_locale_used: The search_locale_used of this ProductDetails. # noqa: E501 - :type: IsoSearchLocale - """ - - self._search_locale_used = search_locale_used - - @property - def associated_products(self): - """Gets the associated_products of this ProductDetails. # noqa: E501 - - Products that are directly correlated to complete the intended function of the product. These products may be either same manufacturer or differ. # noqa: E501 - - :return: The associated_products of this ProductDetails. # noqa: E501 - :rtype: list[AssociatedProduct] - """ - return self._associated_products - - @associated_products.setter - def associated_products(self, associated_products): - """Sets the associated_products of this ProductDetails. - - Products that are directly correlated to complete the intended function of the product. These products may be either same manufacturer or differ. # noqa: E501 - - :param associated_products: The associated_products of this ProductDetails. # noqa: E501 - :type: list[AssociatedProduct] - """ - - self._associated_products = associated_products - - @property - def for_use_with_products(self): - """Gets the for_use_with_products of this ProductDetails. # noqa: E501 - - Products that are directly correlated to complete the intended function of the product. These products may be either same manufacturer or differ. # noqa: E501 - - :return: The for_use_with_products of this ProductDetails. # noqa: E501 - :rtype: list[AssociatedProduct] - """ - return self._for_use_with_products - - @for_use_with_products.setter - def for_use_with_products(self, for_use_with_products): - """Sets the for_use_with_products of this ProductDetails. - - Products that are directly correlated to complete the intended function of the product. These products may be either same manufacturer or differ. # noqa: E501 - - :param for_use_with_products: The for_use_with_products of this ProductDetails. # noqa: E501 - :type: list[AssociatedProduct] - """ - - self._for_use_with_products = for_use_with_products - - @property - def rohs_subs(self): - """Gets the rohs_subs of this ProductDetails. # noqa: E501 - - Rohs substitutions # noqa: E501 - - :return: The rohs_subs of this ProductDetails. # noqa: E501 - :rtype: list[AssociatedProduct] - """ - return self._rohs_subs - - @rohs_subs.setter - def rohs_subs(self, rohs_subs): - """Sets the rohs_subs of this ProductDetails. - - Rohs substitutions # noqa: E501 - - :param rohs_subs: The rohs_subs of this ProductDetails. # noqa: E501 - :type: list[AssociatedProduct] - """ - - self._rohs_subs = rohs_subs - - @property - def suggested_subs(self): - """Gets the suggested_subs of this ProductDetails. # noqa: E501 - - Suggested substitutions for when the product is obsolete. # noqa: E501 - - :return: The suggested_subs of this ProductDetails. # noqa: E501 - :rtype: list[AssociatedProduct] - """ - return self._suggested_subs - - @suggested_subs.setter - def suggested_subs(self, suggested_subs): - """Sets the suggested_subs of this ProductDetails. - - Suggested substitutions for when the product is obsolete. # noqa: E501 - - :param suggested_subs: The suggested_subs of this ProductDetails. # noqa: E501 - :type: list[AssociatedProduct] - """ - - self._suggested_subs = suggested_subs - - @property - def additional_value_fee(self): - """Gets the additional_value_fee of this ProductDetails. # noqa: E501 - - Any additional value fee. Most commonly the Digi-Reel fee. May be used for programmable parts as well. # noqa: E501 - - :return: The additional_value_fee of this ProductDetails. # noqa: E501 - :rtype: float - """ - return self._additional_value_fee - - @additional_value_fee.setter - def additional_value_fee(self, additional_value_fee): - """Sets the additional_value_fee of this ProductDetails. - - Any additional value fee. Most commonly the Digi-Reel fee. May be used for programmable parts as well. # noqa: E501 - - :param additional_value_fee: The additional_value_fee of this ProductDetails. # noqa: E501 - :type: float - """ - - self._additional_value_fee = additional_value_fee - - @property - def reach_effective_date(self): - """Gets the reach_effective_date of this ProductDetails. # noqa: E501 - - REACH effective date is string in format \"MMM-yyyy\" or blank \"\". REACH is a regulation of the European Union. See documentation from the European Chemicals Agency. # noqa: E501 - - :return: The reach_effective_date of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._reach_effective_date - - @reach_effective_date.setter - def reach_effective_date(self, reach_effective_date): - """Sets the reach_effective_date of this ProductDetails. - - REACH effective date is string in format \"MMM-yyyy\" or blank \"\". REACH is a regulation of the European Union. See documentation from the European Chemicals Agency. # noqa: E501 - - :param reach_effective_date: The reach_effective_date of this ProductDetails. # noqa: E501 - :type: str - """ - - self._reach_effective_date = reach_effective_date - - @property - def standard_pricing(self): - """Gets the standard_pricing of this ProductDetails. # noqa: E501 - - Standard pricing for the validated locale. # noqa: E501 - - :return: The standard_pricing of this ProductDetails. # noqa: E501 - :rtype: list[PriceBreak] - """ - return self._standard_pricing - - @standard_pricing.setter - def standard_pricing(self, standard_pricing): - """Sets the standard_pricing of this ProductDetails. - - Standard pricing for the validated locale. # noqa: E501 - - :param standard_pricing: The standard_pricing of this ProductDetails. # noqa: E501 - :type: list[PriceBreak] - """ - - self._standard_pricing = standard_pricing - - @property - def ro_hs_status(self): - """Gets the ro_hs_status of this ProductDetails. # noqa: E501 - - RoHS status. Can be: RoHS Compliant, RoHS non-compliant, RoHS Compliant By Exemption, Not Applicable, Vendor undefined, Request Inventory Verification, ROHS3 Compliant. # noqa: E501 - - :return: The ro_hs_status of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._ro_hs_status - - @ro_hs_status.setter - def ro_hs_status(self, ro_hs_status): - """Sets the ro_hs_status of this ProductDetails. - - RoHS status. Can be: RoHS Compliant, RoHS non-compliant, RoHS Compliant By Exemption, Not Applicable, Vendor undefined, Request Inventory Verification, ROHS3 Compliant. # noqa: E501 - - :param ro_hs_status: The ro_hs_status of this ProductDetails. # noqa: E501 - :type: str - """ - - self._ro_hs_status = ro_hs_status - - @property - def lead_status(self): - """Gets the lead_status of this ProductDetails. # noqa: E501 - - Lead status. Can be: Lead Free, Contains lead, Lead Free By Exemption, Not Applicable, Vendor undefined, unknown, or Request Inventory Verification. # noqa: E501 - - :return: The lead_status of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._lead_status - - @lead_status.setter - def lead_status(self, lead_status): - """Sets the lead_status of this ProductDetails. - - Lead status. Can be: Lead Free, Contains lead, Lead Free By Exemption, Not Applicable, Vendor undefined, unknown, or Request Inventory Verification. # noqa: E501 - - :param lead_status: The lead_status of this ProductDetails. # noqa: E501 - :type: str - """ - - self._lead_status = lead_status - - @property - def parameters(self): - """Gets the parameters of this ProductDetails. # noqa: E501 - - Parameters for the part. Can be used for filtering keyword searches. # noqa: E501 - - :return: The parameters of this ProductDetails. # noqa: E501 - :rtype: list[PidVid] - """ - return self._parameters - - @parameters.setter - def parameters(self, parameters): - """Sets the parameters of this ProductDetails. - - Parameters for the part. Can be used for filtering keyword searches. # noqa: E501 - - :param parameters: The parameters of this ProductDetails. # noqa: E501 - :type: list[PidVid] - """ - - self._parameters = parameters - - @property - def product_url(self): - """Gets the product_url of this ProductDetails. # noqa: E501 - - Full URL of the Digi-Key catalog page to purchase the product. This is based on your provided Locale values. # noqa: E501 - - :return: The product_url of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._product_url - - @product_url.setter - def product_url(self, product_url): - """Sets the product_url of this ProductDetails. - - Full URL of the Digi-Key catalog page to purchase the product. This is based on your provided Locale values. # noqa: E501 - - :param product_url: The product_url of this ProductDetails. # noqa: E501 - :type: str - """ - - self._product_url = product_url - - @property - def primary_datasheet(self): - """Gets the primary_datasheet of this ProductDetails. # noqa: E501 - - The URL to the product's datasheet. # noqa: E501 - - :return: The primary_datasheet of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._primary_datasheet - - @primary_datasheet.setter - def primary_datasheet(self, primary_datasheet): - """Sets the primary_datasheet of this ProductDetails. - - The URL to the product's datasheet. # noqa: E501 - - :param primary_datasheet: The primary_datasheet of this ProductDetails. # noqa: E501 - :type: str - """ - - self._primary_datasheet = primary_datasheet - - @property - def primary_photo(self): - """Gets the primary_photo of this ProductDetails. # noqa: E501 - - The URL to the product's image. # noqa: E501 - - :return: The primary_photo of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._primary_photo - - @primary_photo.setter - def primary_photo(self, primary_photo): - """Sets the primary_photo of this ProductDetails. - - The URL to the product's image. # noqa: E501 - - :param primary_photo: The primary_photo of this ProductDetails. # noqa: E501 - :type: str - """ - - self._primary_photo = primary_photo - - @property - def primary_video(self): - """Gets the primary_video of this ProductDetails. # noqa: E501 - - The URL to the product's video. # noqa: E501 - - :return: The primary_video of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._primary_video - - @primary_video.setter - def primary_video(self, primary_video): - """Sets the primary_video of this ProductDetails. - - The URL to the product's video. # noqa: E501 - - :param primary_video: The primary_video of this ProductDetails. # noqa: E501 - :type: str - """ - - self._primary_video = primary_video - - @property - def series(self): - """Gets the series of this ProductDetails. # noqa: E501 - - - :return: The series of this ProductDetails. # noqa: E501 - :rtype: PidVid - """ - return self._series - - @series.setter - def series(self, series): - """Sets the series of this ProductDetails. - - - :param series: The series of this ProductDetails. # noqa: E501 - :type: PidVid - """ - - self._series = series - - @property - def manufacturer_lead_weeks(self): - """Gets the manufacturer_lead_weeks of this ProductDetails. # noqa: E501 - - The number of weeks expected to receive stock from manufacturer. # noqa: E501 - - :return: The manufacturer_lead_weeks of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._manufacturer_lead_weeks - - @manufacturer_lead_weeks.setter - def manufacturer_lead_weeks(self, manufacturer_lead_weeks): - """Sets the manufacturer_lead_weeks of this ProductDetails. - - The number of weeks expected to receive stock from manufacturer. # noqa: E501 - - :param manufacturer_lead_weeks: The manufacturer_lead_weeks of this ProductDetails. # noqa: E501 - :type: str - """ - - self._manufacturer_lead_weeks = manufacturer_lead_weeks - - @property - def manufacturer_page_url(self): - """Gets the manufacturer_page_url of this ProductDetails. # noqa: E501 - - The URL to Digi-Key's page on the manufacturer. # noqa: E501 - - :return: The manufacturer_page_url of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._manufacturer_page_url - - @manufacturer_page_url.setter - def manufacturer_page_url(self, manufacturer_page_url): - """Sets the manufacturer_page_url of this ProductDetails. - - The URL to Digi-Key's page on the manufacturer. # noqa: E501 - - :param manufacturer_page_url: The manufacturer_page_url of this ProductDetails. # noqa: E501 - :type: str - """ - - self._manufacturer_page_url = manufacturer_page_url - - @property - def product_status(self): - """Gets the product_status of this ProductDetails. # noqa: E501 - - Status of the product. Options include: Active, Obsolete, Discontinued at Digi-Key, Last Time Buy, Not For New Designs, Preliminary. For obsolete parts the part will become a non-stocking item when stock is depleted; minimums will apply. Order the quantity available or the quantity available plus a multiple of the minimum order quantity. # noqa: E501 - - :return: The product_status of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._product_status - - @product_status.setter - def product_status(self, product_status): - """Sets the product_status of this ProductDetails. - - Status of the product. Options include: Active, Obsolete, Discontinued at Digi-Key, Last Time Buy, Not For New Designs, Preliminary. For obsolete parts the part will become a non-stocking item when stock is depleted; minimums will apply. Order the quantity available or the quantity available plus a multiple of the minimum order quantity. # noqa: E501 - - :param product_status: The product_status of this ProductDetails. # noqa: E501 - :type: str - """ - - self._product_status = product_status - - @property - def date_last_buy_chance(self): - """Gets the date_last_buy_chance of this ProductDetails. # noqa: E501 - - Last date that the product will be available for purchase. Date is in ISO 8601. # noqa: E501 - - :return: The date_last_buy_chance of this ProductDetails. # noqa: E501 - :rtype: datetime - """ - return self._date_last_buy_chance - - @date_last_buy_chance.setter - def date_last_buy_chance(self, date_last_buy_chance): - """Sets the date_last_buy_chance of this ProductDetails. - - Last date that the product will be available for purchase. Date is in ISO 8601. # noqa: E501 - - :param date_last_buy_chance: The date_last_buy_chance of this ProductDetails. # noqa: E501 - :type: datetime - """ - - self._date_last_buy_chance = date_last_buy_chance - - @property - def alternate_packaging(self): - """Gets the alternate_packaging of this ProductDetails. # noqa: E501 - - Other packaging types available for this product. # noqa: E501 - - :return: The alternate_packaging of this ProductDetails. # noqa: E501 - :rtype: list[BasicProduct] - """ - return self._alternate_packaging - - @alternate_packaging.setter - def alternate_packaging(self, alternate_packaging): - """Sets the alternate_packaging of this ProductDetails. - - Other packaging types available for this product. # noqa: E501 - - :param alternate_packaging: The alternate_packaging of this ProductDetails. # noqa: E501 - :type: list[BasicProduct] - """ - - self._alternate_packaging = alternate_packaging - - @property - def detailed_description(self): - """Gets the detailed_description of this ProductDetails. # noqa: E501 - - Extended catalog description of the product. # noqa: E501 - - :return: The detailed_description of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._detailed_description - - @detailed_description.setter - def detailed_description(self, detailed_description): - """Sets the detailed_description of this ProductDetails. - - Extended catalog description of the product. # noqa: E501 - - :param detailed_description: The detailed_description of this ProductDetails. # noqa: E501 - :type: str - """ - - self._detailed_description = detailed_description - - @property - def reach_status(self): - """Gets the reach_status of this ProductDetails. # noqa: E501 - - REACH is a regulation of the European Union. See documentation from the European Chemicals Agency. # noqa: E501 - - :return: The reach_status of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._reach_status - - @reach_status.setter - def reach_status(self, reach_status): - """Sets the reach_status of this ProductDetails. - - REACH is a regulation of the European Union. See documentation from the European Chemicals Agency. # noqa: E501 - - :param reach_status: The reach_status of this ProductDetails. # noqa: E501 - :type: str - """ - - self._reach_status = reach_status - - @property - def export_control_class_number(self): - """Gets the export_control_class_number of this ProductDetails. # noqa: E501 - - Export control class number. See documentation from the U.S. Department of Commerce. # noqa: E501 - - :return: The export_control_class_number of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._export_control_class_number - - @export_control_class_number.setter - def export_control_class_number(self, export_control_class_number): - """Sets the export_control_class_number of this ProductDetails. - - Export control class number. See documentation from the U.S. Department of Commerce. # noqa: E501 - - :param export_control_class_number: The export_control_class_number of this ProductDetails. # noqa: E501 - :type: str - """ - - self._export_control_class_number = export_control_class_number - - @property - def htsus_code(self): - """Gets the htsus_code of this ProductDetails. # noqa: E501 - - Harmonized Tariff Schedule of the United States. See documentation from the U.S. International Trade Commission. # noqa: E501 - - :return: The htsus_code of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._htsus_code - - @htsus_code.setter - def htsus_code(self, htsus_code): - """Sets the htsus_code of this ProductDetails. - - Harmonized Tariff Schedule of the United States. See documentation from the U.S. International Trade Commission. # noqa: E501 - - :param htsus_code: The htsus_code of this ProductDetails. # noqa: E501 - :type: str - """ - - self._htsus_code = htsus_code - - @property - def tariff_description(self): - """Gets the tariff_description of this ProductDetails. # noqa: E501 - - Description of the tariff status. Only applies if purchasing in USD and shipping to the US. Valid options are No Tariff and Tariff Applied. # noqa: E501 - - :return: The tariff_description of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._tariff_description - - @tariff_description.setter - def tariff_description(self, tariff_description): - """Sets the tariff_description of this ProductDetails. - - Description of the tariff status. Only applies if purchasing in USD and shipping to the US. Valid options are No Tariff and Tariff Applied. # noqa: E501 - - :param tariff_description: The tariff_description of this ProductDetails. # noqa: E501 - :type: str - """ - - self._tariff_description = tariff_description - - @property - def moisture_sensitivity_level(self): - """Gets the moisture_sensitivity_level of this ProductDetails. # noqa: E501 - - Code for Moisture Sensitivity Level of the product # noqa: E501 - - :return: The moisture_sensitivity_level of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._moisture_sensitivity_level - - @moisture_sensitivity_level.setter - def moisture_sensitivity_level(self, moisture_sensitivity_level): - """Sets the moisture_sensitivity_level of this ProductDetails. - - Code for Moisture Sensitivity Level of the product # noqa: E501 - - :param moisture_sensitivity_level: The moisture_sensitivity_level of this ProductDetails. # noqa: E501 - :type: str - """ - - self._moisture_sensitivity_level = moisture_sensitivity_level - - @property - def manufacturer_part_number(self): - """Gets the manufacturer_part_number of this ProductDetails. # noqa: E501 - - The manufacturer part number. Note that some manufacturer part numbers may be used by multiple manufacturers for different parts. # noqa: E501 - - :return: The manufacturer_part_number of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._manufacturer_part_number - - @manufacturer_part_number.setter - def manufacturer_part_number(self, manufacturer_part_number): - """Sets the manufacturer_part_number of this ProductDetails. - - The manufacturer part number. Note that some manufacturer part numbers may be used by multiple manufacturers for different parts. # noqa: E501 - - :param manufacturer_part_number: The manufacturer_part_number of this ProductDetails. # noqa: E501 - :type: str - """ - - self._manufacturer_part_number = manufacturer_part_number - - @property - def minimum_order_quantity(self): - """Gets the minimum_order_quantity of this ProductDetails. # noqa: E501 - - The minimum quantity to order from Digi-Key. # noqa: E501 - - :return: The minimum_order_quantity of this ProductDetails. # noqa: E501 - :rtype: int - """ - return self._minimum_order_quantity - - @minimum_order_quantity.setter - def minimum_order_quantity(self, minimum_order_quantity): - """Sets the minimum_order_quantity of this ProductDetails. - - The minimum quantity to order from Digi-Key. # noqa: E501 - - :param minimum_order_quantity: The minimum_order_quantity of this ProductDetails. # noqa: E501 - :type: int - """ - - self._minimum_order_quantity = minimum_order_quantity - - @property - def non_stock(self): - """Gets the non_stock of this ProductDetails. # noqa: E501 - - Indicates this product is a non stock product. # noqa: E501 - - :return: The non_stock of this ProductDetails. # noqa: E501 - :rtype: bool - """ - return self._non_stock - - @non_stock.setter - def non_stock(self, non_stock): - """Sets the non_stock of this ProductDetails. - - Indicates this product is a non stock product. # noqa: E501 - - :param non_stock: The non_stock of this ProductDetails. # noqa: E501 - :type: bool - """ - - self._non_stock = non_stock - - @property - def packaging(self): - """Gets the packaging of this ProductDetails. # noqa: E501 - - - :return: The packaging of this ProductDetails. # noqa: E501 - :rtype: PidVid - """ - return self._packaging - - @packaging.setter - def packaging(self, packaging): - """Sets the packaging of this ProductDetails. - - - :param packaging: The packaging of this ProductDetails. # noqa: E501 - :type: PidVid - """ - - self._packaging = packaging - - @property - def quantity_available(self): - """Gets the quantity_available of this ProductDetails. # noqa: E501 - - Quantity of the product available for immediate sale. # noqa: E501 - - :return: The quantity_available of this ProductDetails. # noqa: E501 - :rtype: int - """ - return self._quantity_available - - @quantity_available.setter - def quantity_available(self, quantity_available): - """Sets the quantity_available of this ProductDetails. - - Quantity of the product available for immediate sale. # noqa: E501 - - :param quantity_available: The quantity_available of this ProductDetails. # noqa: E501 - :type: int - """ - - self._quantity_available = quantity_available - - @property - def digi_key_part_number(self): - """Gets the digi_key_part_number of this ProductDetails. # noqa: E501 - - The Digi-Key part number. # noqa: E501 - - :return: The digi_key_part_number of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._digi_key_part_number - - @digi_key_part_number.setter - def digi_key_part_number(self, digi_key_part_number): - """Sets the digi_key_part_number of this ProductDetails. - - The Digi-Key part number. # noqa: E501 - - :param digi_key_part_number: The digi_key_part_number of this ProductDetails. # noqa: E501 - :type: str - """ - - self._digi_key_part_number = digi_key_part_number - - @property - def product_description(self): - """Gets the product_description of this ProductDetails. # noqa: E501 - - Catalog description of the product. # noqa: E501 - - :return: The product_description of this ProductDetails. # noqa: E501 - :rtype: str - """ - return self._product_description - - @product_description.setter - def product_description(self, product_description): - """Sets the product_description of this ProductDetails. - - Catalog description of the product. # noqa: E501 - - :param product_description: The product_description of this ProductDetails. # noqa: E501 - :type: str - """ - - self._product_description = product_description - - @property - def unit_price(self): - """Gets the unit_price of this ProductDetails. # noqa: E501 - - The price for a single unit of this product. # noqa: E501 - - :return: The unit_price of this ProductDetails. # noqa: E501 - :rtype: float - """ - return self._unit_price - - @unit_price.setter - def unit_price(self, unit_price): - """Sets the unit_price of this ProductDetails. - - The price for a single unit of this product. # noqa: E501 - - :param unit_price: The unit_price of this ProductDetails. # noqa: E501 - :type: float - """ - - self._unit_price = unit_price - - @property - def manufacturer(self): - """Gets the manufacturer of this ProductDetails. # noqa: E501 - - - :return: The manufacturer of this ProductDetails. # noqa: E501 - :rtype: PidVid - """ - return self._manufacturer - - @manufacturer.setter - def manufacturer(self, manufacturer): - """Sets the manufacturer of this ProductDetails. - - - :param manufacturer: The manufacturer of this ProductDetails. # noqa: E501 - :type: PidVid - """ - - self._manufacturer = manufacturer - - @property - def manufacturer_public_quantity(self): - """Gets the manufacturer_public_quantity of this ProductDetails. # noqa: E501 - - Quantity of this product available to order from manufacturer. # noqa: E501 - - :return: The manufacturer_public_quantity of this ProductDetails. # noqa: E501 - :rtype: int - """ - return self._manufacturer_public_quantity - - @manufacturer_public_quantity.setter - def manufacturer_public_quantity(self, manufacturer_public_quantity): - """Sets the manufacturer_public_quantity of this ProductDetails. - - Quantity of this product available to order from manufacturer. # noqa: E501 - - :param manufacturer_public_quantity: The manufacturer_public_quantity of this ProductDetails. # noqa: E501 - :type: int - """ - - self._manufacturer_public_quantity = manufacturer_public_quantity - - @property - def quantity_on_order(self): - """Gets the quantity_on_order of this ProductDetails. # noqa: E501 - - Quantity of this product ordered but not immediately available. # noqa: E501 - - :return: The quantity_on_order of this ProductDetails. # noqa: E501 - :rtype: int - """ - return self._quantity_on_order - - @quantity_on_order.setter - def quantity_on_order(self, quantity_on_order): - """Sets the quantity_on_order of this ProductDetails. - - Quantity of this product ordered but not immediately available. # noqa: E501 - - :param quantity_on_order: The quantity_on_order of this ProductDetails. # noqa: E501 - :type: int - """ - - self._quantity_on_order = quantity_on_order - - @property - def dk_plus_restriction(self): - """Gets the dk_plus_restriction of this ProductDetails. # noqa: E501 - - If true- this product is not available for purchase through the Ordering API - it must be purchased through the Digi-Key web site # noqa: E501 - - :return: The dk_plus_restriction of this ProductDetails. # noqa: E501 - :rtype: bool - """ - return self._dk_plus_restriction - - @dk_plus_restriction.setter - def dk_plus_restriction(self, dk_plus_restriction): - """Sets the dk_plus_restriction of this ProductDetails. - - If true- this product is not available for purchase through the Ordering API - it must be purchased through the Digi-Key web site # noqa: E501 - - :param dk_plus_restriction: The dk_plus_restriction of this ProductDetails. # noqa: E501 - :type: bool - """ - - self._dk_plus_restriction = dk_plus_restriction - - @property - def supplier_direct_ship(self): - """Gets the supplier_direct_ship of this ProductDetails. # noqa: E501 - - If true- this product is shipped directly from the Supplier # noqa: E501 - - :return: The supplier_direct_ship of this ProductDetails. # noqa: E501 - :rtype: bool - """ - return self._supplier_direct_ship - - @supplier_direct_ship.setter - def supplier_direct_ship(self, supplier_direct_ship): - """Sets the supplier_direct_ship of this ProductDetails. - - If true- this product is shipped directly from the Supplier # noqa: E501 - - :param supplier_direct_ship: The supplier_direct_ship of this ProductDetails. # noqa: E501 - :type: bool - """ - - self._supplier_direct_ship = supplier_direct_ship - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ProductDetails, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ProductDetails): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/batchproductdetails/rest.py b/digikey/v3/batchproductdetails/rest.py deleted file mode 100644 index 9476756..0000000 --- a/digikey/v3/batchproductdetails/rest.py +++ /dev/null @@ -1,323 +0,0 @@ -# coding: utf-8 - -""" - Batch Product Details Api - - Retrieve list of product details from list of part numbers # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import io -import json -import logging -import re -import ssl - -import certifi -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode - -try: - import urllib3 -except ImportError: - raise ImportError('Swagger python client requires urllib3.') - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) - - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if query_params: - url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str): - request_body = body - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if six.PY3: - r.data = r.data.decode('utf8') - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - -class ApiException(Exception): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message diff --git a/digikey/v3/ordersupport/__init__.py b/digikey/v3/ordersupport/__init__.py deleted file mode 100644 index bc0c661..0000000 --- a/digikey/v3/ordersupport/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import apis into sdk package -from digikey.v3.ordersupport.api.order_details_api import OrderDetailsApi - -# import ApiClient -from digikey.v3.ordersupport.api_client import ApiClient -from digikey.v3.ordersupport.configuration import Configuration -# import models into sdk package -from digikey.v3.ordersupport.models.address import Address -from digikey.v3.ordersupport.models.api_error_response import ApiErrorResponse -from digikey.v3.ordersupport.models.api_validation_error import ApiValidationError -from digikey.v3.ordersupport.models.line_item import LineItem -from digikey.v3.ordersupport.models.order_status_response import OrderStatusResponse -from digikey.v3.ordersupport.models.sales_order_history_item import SalesOrderHistoryItem -from digikey.v3.ordersupport.models.schedule import Schedule -from digikey.v3.ordersupport.models.shipping_detail import ShippingDetail diff --git a/digikey/v3/ordersupport/api/__init__.py b/digikey/v3/ordersupport/api/__init__.py deleted file mode 100644 index 639dfb2..0000000 --- a/digikey/v3/ordersupport/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from __future__ import absolute_import - -# flake8: noqa - -# import apis into api package -from digikey.v3.ordersupport.api.order_details_api import OrderDetailsApi diff --git a/digikey/v3/ordersupport/api/order_details_api.py b/digikey/v3/ordersupport/api/order_details_api.py deleted file mode 100644 index ed40082..0000000 --- a/digikey/v3/ordersupport/api/order_details_api.py +++ /dev/null @@ -1,272 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import re # noqa: F401 - -# python 2 and python 3 compatibility library -import six - -from digikey.v3.ordersupport.api_client import ApiClient - - -class OrderDetailsApi(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def order_history(self, authorization, x_digikey_client_id, **kwargs): # noqa: E501 - """Retrieves a list of SalesOrderIds and dates for all SalesOrders within a date range belonging to a CustomerId. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.order_history(authorization, x_digikey_client_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str authorization: OAuth Bearer Token. Please see OAuth 2.0 Documentation page for more info. (required) - :param str x_digikey_client_id: The Client Id for your App. (required) - :param int customer_id: CustomerId that is on the Digi-Key account with which you authenticated. If not provided, will default to the first CustomerId on the Digi-Key account. - :param bool open_only: If true will only return open orders. If false, will return open and closed orders. - :param bool include_company_orders: Include all company orders for the location associated with the given CustomerId. - :param str start_date: Begining of date range in ISO 8601 format. For example: 2018-10-31 - :param str end_date: End of date range in ISO 8601 format. For example: 2018-10-31 - :param str includes: Comma separated list of fields to return. Used to customize response to reduce bandwidth with fields that you do not wish to receive. For example: \"SalesOrderId,PurchaseOrder\" - :return: list[SalesOrderHistoryItem] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.order_history_with_http_info(authorization, x_digikey_client_id, **kwargs) # noqa: E501 - else: - (data) = self.order_history_with_http_info(authorization, x_digikey_client_id, **kwargs) # noqa: E501 - return data - - def order_history_with_http_info(self, authorization, x_digikey_client_id, **kwargs): # noqa: E501 - """Retrieves a list of SalesOrderIds and dates for all SalesOrders within a date range belonging to a CustomerId. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.order_history_with_http_info(authorization, x_digikey_client_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str authorization: OAuth Bearer Token. Please see OAuth 2.0 Documentation page for more info. (required) - :param str x_digikey_client_id: The Client Id for your App. (required) - :param int customer_id: CustomerId that is on the Digi-Key account with which you authenticated. If not provided, will default to the first CustomerId on the Digi-Key account. - :param bool open_only: If true will only return open orders. If false, will return open and closed orders. - :param bool include_company_orders: Include all company orders for the location associated with the given CustomerId. - :param str start_date: Begining of date range in ISO 8601 format. For example: 2018-10-31 - :param str end_date: End of date range in ISO 8601 format. For example: 2018-10-31 - :param str includes: Comma separated list of fields to return. Used to customize response to reduce bandwidth with fields that you do not wish to receive. For example: \"SalesOrderId,PurchaseOrder\" - :return: list[SalesOrderHistoryItem] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['authorization', 'x_digikey_client_id', 'customer_id', 'open_only', 'include_company_orders', 'start_date', 'end_date', 'includes'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method order_history" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'authorization' is set - if ('authorization' not in params or - params['authorization'] is None): - raise ValueError("Missing the required parameter `authorization` when calling `order_history`") # noqa: E501 - # verify the required parameter 'x_digikey_client_id' is set - if ('x_digikey_client_id' not in params or - params['x_digikey_client_id'] is None): - raise ValueError("Missing the required parameter `x_digikey_client_id` when calling `order_history`") # noqa: E501 - - collection_formats = {} - - path_params = {} - - query_params = [] - if 'customer_id' in params: - query_params.append(('CustomerId', params['customer_id'])) # noqa: E501 - if 'open_only' in params: - query_params.append(('OpenOnly', params['open_only'])) # noqa: E501 - if 'include_company_orders' in params: - query_params.append(('IncludeCompanyOrders', params['include_company_orders'])) # noqa: E501 - if 'start_date' in params: - query_params.append(('StartDate', params['start_date'])) # noqa: E501 - if 'end_date' in params: - query_params.append(('EndDate', params['end_date'])) # noqa: E501 - if 'includes' in params: - query_params.append(('Includes', params['includes'])) # noqa: E501 - - header_params = {} - if 'authorization' in params: - header_params['Authorization'] = params['authorization'] # noqa: E501 - if 'x_digikey_client_id' in params: - header_params['X-DIGIKEY-Client-Id'] = params['x_digikey_client_id'] # noqa: E501 - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # Authentication setting - auth_settings = [] # noqa: E501 - - return self.api_client.call_api( - '/History', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[SalesOrderHistoryItem]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def order_status(self, sales_order_id, authorization, x_digikey_client_id, **kwargs): # noqa: E501 - """Retrieve order status for given SalesOrderId # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.order_status(sales_order_id, authorization, x_digikey_client_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int sales_order_id: SalesOrderId belonging to you or your company that you wish to lookup (required) - :param str authorization: OAuth Bearer Token. Please see OAuth 2.0 Documentation page for more info. (required) - :param str x_digikey_client_id: The Client Id for your App. (required) - :param str includes: Comma separated list of fields to return. Used to customize response to reduce bandwidth with fields that you do not wish to receive. For example: \"SalesOrderId,ShippingDetails\" - :return: OrderStatusResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.order_status_with_http_info(sales_order_id, authorization, x_digikey_client_id, **kwargs) # noqa: E501 - else: - (data) = self.order_status_with_http_info(sales_order_id, authorization, x_digikey_client_id, **kwargs) # noqa: E501 - return data - - def order_status_with_http_info(self, sales_order_id, authorization, x_digikey_client_id, **kwargs): # noqa: E501 - """Retrieve order status for given SalesOrderId # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.order_status_with_http_info(sales_order_id, authorization, x_digikey_client_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int sales_order_id: SalesOrderId belonging to you or your company that you wish to lookup (required) - :param str authorization: OAuth Bearer Token. Please see OAuth 2.0 Documentation page for more info. (required) - :param str x_digikey_client_id: The Client Id for your App. (required) - :param str includes: Comma separated list of fields to return. Used to customize response to reduce bandwidth with fields that you do not wish to receive. For example: \"SalesOrderId,ShippingDetails\" - :return: OrderStatusResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['sales_order_id', 'authorization', 'x_digikey_client_id', 'includes'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method order_status" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'sales_order_id' is set - if ('sales_order_id' not in params or - params['sales_order_id'] is None): - raise ValueError("Missing the required parameter `sales_order_id` when calling `order_status`") # noqa: E501 - # verify the required parameter 'authorization' is set - if ('authorization' not in params or - params['authorization'] is None): - raise ValueError("Missing the required parameter `authorization` when calling `order_status`") # noqa: E501 - # verify the required parameter 'x_digikey_client_id' is set - if ('x_digikey_client_id' not in params or - params['x_digikey_client_id'] is None): - raise ValueError("Missing the required parameter `x_digikey_client_id` when calling `order_status`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'sales_order_id' in params: - path_params['salesOrderId'] = params['sales_order_id'] # noqa: E501 - - query_params = [] - if 'includes' in params: - query_params.append(('Includes', params['includes'])) # noqa: E501 - - header_params = {} - if 'authorization' in params: - header_params['Authorization'] = params['authorization'] # noqa: E501 - if 'x_digikey_client_id' in params: - header_params['X-DIGIKEY-Client-Id'] = params['x_digikey_client_id'] # noqa: E501 - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # Authentication setting - auth_settings = [] # noqa: E501 - - return self.api_client.call_api( - '/Status/{salesOrderId}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='OrderStatusResponse', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) diff --git a/digikey/v3/ordersupport/api_client.py b/digikey/v3/ordersupport/api_client.py deleted file mode 100644 index 851fb97..0000000 --- a/digikey/v3/ordersupport/api_client.py +++ /dev/null @@ -1,638 +0,0 @@ -# coding: utf-8 -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import datetime -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote - -from digikey.v3.ordersupport.configuration import Configuration -import digikey.v3.ordersupport.models -from digikey.v3.ordersupport import rest - - -class ApiClient(object): - """Generic API client for Swagger client library builds. - - Swagger generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the Swagger - templates. - - NOTE: This class is auto generated by the swagger code generator program. - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - """ - - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int if six.PY3 else long, # noqa: F821 - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - - # Use the pool property to lazily initialize the ThreadPool. - self._pool = None - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'Swagger-Codegen/0.1.0/python' - - def __del__(self): - if self._pool is not None: - self._pool.close() - self._pool.join() - - @property - def pool(self): - if self._pool is None: - self._pool = ThreadPool() - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - - # post parameters - if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.configuration.host + resource_path - - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return (return_data) - else: - return (return_data, response_data.status, - response_data.getheaders()) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - - return {key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict)} - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith('list['): - sub_kls = re.match(r'list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('dict('): - sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in six.iteritems(data)} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(digikey.v3.ordersupport.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, async_req=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout) - else: - thread = self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, query_params, - header_params, body, - post_params, files, - response_type, auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, _request_timeout)) - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "POST": - return self.rest_client.POST(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def prepare_post_parameters(self, post_params=None, files=None): - """Builds form parameters. - - :param post_params: Normal form parameters. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if post_params: - params = post_params - - if files: - for k, v in six.iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return 'application/json' - - content_types = [x.lower() for x in content_types] - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if not auth_setting['value']: - continue - elif auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys.append((auth_setting['key'], auth_setting['value'])) - else: - raise ValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "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 six.text_type(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return a original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datatime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse `{0}` as datetime object" - .format(string) - ) - ) - - def __hasattr(self, object, name): - return name in object.__class__.__dict__ - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - if (not klass.swagger_types and - not self.__hasattr(klass, 'get_real_child_model')): - return data - - kwargs = {} - if klass.swagger_types is not None: - for attr, attr_type in six.iteritems(klass.swagger_types): - if (data is not None and - klass.attribute_map[attr] in data and - isinstance(data, (list, dict))): - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if (isinstance(instance, dict) and - klass.swagger_types is not None and - isinstance(data, dict)): - for key, value in data.items(): - if key not in klass.swagger_types: - instance[key] = value - if self.__hasattr(instance, 'get_real_child_model'): - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance diff --git a/digikey/v3/ordersupport/configuration.py b/digikey/v3/ordersupport/configuration.py deleted file mode 100644 index 1b4b454..0000000 --- a/digikey/v3/ordersupport/configuration.py +++ /dev/null @@ -1,255 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import six -from six.moves import http_client as httplib - - -class Configuration(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - """ - - _default = None - - def __init__(self): - """Constructor""" - if self._default: - for key in self._default.__dict__.keys(): - self.__dict__[key] = copy.copy(self._default.__dict__[key]) - return - - # Default Base url - self.host = "https://api.digikey.com/OrderDetails/v3" - # Temp file folder for downloading files - self.temp_folder_path = None - - # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - - # access token for OAuth - self.access_token = "" - - # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("digikey.v3.ordersupport") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - # Log stream handler - self.logger_stream_handler = None - # Log file handler - self.logger_file_handler = None - # Debug file location - self.logger_file = None - # Debug switch - self.debug = False - - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. - self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file - self.cert_file = None - # client key file - self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. - self.assert_hostname = None - - # 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.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - - # Proxy URL - self.proxy = None - # Safe chars for path_param - self.safe_chars_for_path_param = '' - - @classmethod - def set_default(cls, default): - cls._default = 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 six.iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(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 six.iteritems(self.logger): - 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 six.iteritems(self.logger): - 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): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if (self.api_key.get(identifier) and - self.api_key_prefix.get(identifier)): - return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] # noqa: E501 - elif self.api_key.get(identifier): - return self.api_key[identifier] - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - return urllib3.util.make_headers( - basic_auth=self.username + ':' + self.password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - return { - 'apiKeySecurity': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'X-DIGIKEY-Client-Id', - 'value': self.get_api_key_with_prefix('X-DIGIKEY-Client-Id') - }, - - 'oauth2AccessCodeSecurity': - { - 'type': 'oauth2', - 'in': 'header', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - }, - - } - - 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: v3\n"\ - "SDK Package Version: 0.1.0".\ - format(env=sys.platform, pyversion=sys.version) diff --git a/digikey/v3/ordersupport/models/__init__.py b/digikey/v3/ordersupport/models/__init__.py deleted file mode 100644 index 6679280..0000000 --- a/digikey/v3/ordersupport/models/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import models into model package -from digikey.v3.ordersupport.models.address import Address -from digikey.v3.ordersupport.models.api_error_response import ApiErrorResponse -from digikey.v3.ordersupport.models.api_validation_error import ApiValidationError -from digikey.v3.ordersupport.models.line_item import LineItem -from digikey.v3.ordersupport.models.order_status_response import OrderStatusResponse -from digikey.v3.ordersupport.models.sales_order_history_item import SalesOrderHistoryItem -from digikey.v3.ordersupport.models.schedule import Schedule -from digikey.v3.ordersupport.models.shipping_detail import ShippingDetail diff --git a/digikey/v3/ordersupport/models/address.py b/digikey/v3/ordersupport/models/address.py deleted file mode 100644 index 319694e..0000000 --- a/digikey/v3/ordersupport/models/address.py +++ /dev/null @@ -1,369 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class Address(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'company': 'str', - 'first_name': 'str', - 'last_name': 'str', - 'address_line_one': 'str', - 'address_line_two': 'str', - 'address_line_three': 'str', - 'city': 'str', - 'province': 'str', - 'postal_code': 'str', - 'country': 'str' - } - - attribute_map = { - 'company': 'Company', - 'first_name': 'FirstName', - 'last_name': 'LastName', - 'address_line_one': 'AddressLineOne', - 'address_line_two': 'AddressLineTwo', - 'address_line_three': 'AddressLineThree', - 'city': 'City', - 'province': 'Province', - 'postal_code': 'PostalCode', - 'country': 'Country' - } - - def __init__(self, company=None, first_name=None, last_name=None, address_line_one=None, address_line_two=None, address_line_three=None, city=None, province=None, postal_code=None, country=None): # noqa: E501 - """Address - a model defined in Swagger""" # noqa: E501 - - self._company = None - self._first_name = None - self._last_name = None - self._address_line_one = None - self._address_line_two = None - self._address_line_three = None - self._city = None - self._province = None - self._postal_code = None - self._country = None - self.discriminator = None - - if company is not None: - self.company = company - if first_name is not None: - self.first_name = first_name - if last_name is not None: - self.last_name = last_name - if address_line_one is not None: - self.address_line_one = address_line_one - if address_line_two is not None: - self.address_line_two = address_line_two - if address_line_three is not None: - self.address_line_three = address_line_three - if city is not None: - self.city = city - if province is not None: - self.province = province - if postal_code is not None: - self.postal_code = postal_code - if country is not None: - self.country = country - - @property - def company(self): - """Gets the company of this Address. # noqa: E501 - - Company or Organization name # noqa: E501 - - :return: The company of this Address. # noqa: E501 - :rtype: str - """ - return self._company - - @company.setter - def company(self, company): - """Sets the company of this Address. - - Company or Organization name # noqa: E501 - - :param company: The company of this Address. # noqa: E501 - :type: str - """ - - self._company = company - - @property - def first_name(self): - """Gets the first_name of this Address. # noqa: E501 - - First Name # noqa: E501 - - :return: The first_name of this Address. # noqa: E501 - :rtype: str - """ - return self._first_name - - @first_name.setter - def first_name(self, first_name): - """Sets the first_name of this Address. - - First Name # noqa: E501 - - :param first_name: The first_name of this Address. # noqa: E501 - :type: str - """ - - self._first_name = first_name - - @property - def last_name(self): - """Gets the last_name of this Address. # noqa: E501 - - Last Name # noqa: E501 - - :return: The last_name of this Address. # noqa: E501 - :rtype: str - """ - return self._last_name - - @last_name.setter - def last_name(self, last_name): - """Sets the last_name of this Address. - - Last Name # noqa: E501 - - :param last_name: The last_name of this Address. # noqa: E501 - :type: str - """ - - self._last_name = last_name - - @property - def address_line_one(self): - """Gets the address_line_one of this Address. # noqa: E501 - - First line of address # noqa: E501 - - :return: The address_line_one of this Address. # noqa: E501 - :rtype: str - """ - return self._address_line_one - - @address_line_one.setter - def address_line_one(self, address_line_one): - """Sets the address_line_one of this Address. - - First line of address # noqa: E501 - - :param address_line_one: The address_line_one of this Address. # noqa: E501 - :type: str - """ - - self._address_line_one = address_line_one - - @property - def address_line_two(self): - """Gets the address_line_two of this Address. # noqa: E501 - - Second line of address # noqa: E501 - - :return: The address_line_two of this Address. # noqa: E501 - :rtype: str - """ - return self._address_line_two - - @address_line_two.setter - def address_line_two(self, address_line_two): - """Sets the address_line_two of this Address. - - Second line of address # noqa: E501 - - :param address_line_two: The address_line_two of this Address. # noqa: E501 - :type: str - """ - - self._address_line_two = address_line_two - - @property - def address_line_three(self): - """Gets the address_line_three of this Address. # noqa: E501 - - Third line of address # noqa: E501 - - :return: The address_line_three of this Address. # noqa: E501 - :rtype: str - """ - return self._address_line_three - - @address_line_three.setter - def address_line_three(self, address_line_three): - """Sets the address_line_three of this Address. - - Third line of address # noqa: E501 - - :param address_line_three: The address_line_three of this Address. # noqa: E501 - :type: str - """ - - self._address_line_three = address_line_three - - @property - def city(self): - """Gets the city of this Address. # noqa: E501 - - City # noqa: E501 - - :return: The city of this Address. # noqa: E501 - :rtype: str - """ - return self._city - - @city.setter - def city(self, city): - """Sets the city of this Address. - - City # noqa: E501 - - :param city: The city of this Address. # noqa: E501 - :type: str - """ - - self._city = city - - @property - def province(self): - """Gets the province of this Address. # noqa: E501 - - Province or State # noqa: E501 - - :return: The province of this Address. # noqa: E501 - :rtype: str - """ - return self._province - - @province.setter - def province(self, province): - """Sets the province of this Address. - - Province or State # noqa: E501 - - :param province: The province of this Address. # noqa: E501 - :type: str - """ - - self._province = province - - @property - def postal_code(self): - """Gets the postal_code of this Address. # noqa: E501 - - Postal Code or Zip Code # noqa: E501 - - :return: The postal_code of this Address. # noqa: E501 - :rtype: str - """ - return self._postal_code - - @postal_code.setter - def postal_code(self, postal_code): - """Sets the postal_code of this Address. - - Postal Code or Zip Code # noqa: E501 - - :param postal_code: The postal_code of this Address. # noqa: E501 - :type: str - """ - - self._postal_code = postal_code - - @property - def country(self): - """Gets the country of this Address. # noqa: E501 - - Country 2 digit ISO code # noqa: E501 - - :return: The country of this Address. # noqa: E501 - :rtype: str - """ - return self._country - - @country.setter - def country(self, country): - """Sets the country of this Address. - - Country 2 digit ISO code # noqa: E501 - - :param country: The country of this Address. # noqa: E501 - :type: str - """ - - self._country = country - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Address, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Address): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/api_error_response.py b/digikey/v3/ordersupport/models/api_error_response.py deleted file mode 100644 index effe2b1..0000000 --- a/digikey/v3/ordersupport/models/api_error_response.py +++ /dev/null @@ -1,257 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class ApiErrorResponse(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'error_response_version': 'str', - 'status_code': 'int', - 'error_message': 'str', - 'error_details': 'str', - 'request_id': 'str', - 'validation_errors': 'list[ApiValidationError]' - } - - attribute_map = { - 'error_response_version': 'ErrorResponseVersion', - 'status_code': 'StatusCode', - 'error_message': 'ErrorMessage', - 'error_details': 'ErrorDetails', - 'request_id': 'RequestId', - 'validation_errors': 'ValidationErrors' - } - - def __init__(self, error_response_version=None, status_code=None, error_message=None, error_details=None, request_id=None, validation_errors=None): # noqa: E501 - """ApiErrorResponse - a model defined in Swagger""" # noqa: E501 - - self._error_response_version = None - self._status_code = None - self._error_message = None - self._error_details = None - self._request_id = None - self._validation_errors = None - self.discriminator = None - - if error_response_version is not None: - self.error_response_version = error_response_version - if status_code is not None: - self.status_code = status_code - if error_message is not None: - self.error_message = error_message - if error_details is not None: - self.error_details = error_details - if request_id is not None: - self.request_id = request_id - if validation_errors is not None: - self.validation_errors = validation_errors - - @property - def error_response_version(self): - """Gets the error_response_version of this ApiErrorResponse. # noqa: E501 - - The version of the error handler. # noqa: E501 - - :return: The error_response_version of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._error_response_version - - @error_response_version.setter - def error_response_version(self, error_response_version): - """Sets the error_response_version of this ApiErrorResponse. - - The version of the error handler. # noqa: E501 - - :param error_response_version: The error_response_version of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._error_response_version = error_response_version - - @property - def status_code(self): - """Gets the status_code of this ApiErrorResponse. # noqa: E501 - - The HttpStatusCode of the error. # noqa: E501 - - :return: The status_code of this ApiErrorResponse. # noqa: E501 - :rtype: int - """ - return self._status_code - - @status_code.setter - def status_code(self, status_code): - """Sets the status_code of this ApiErrorResponse. - - The HttpStatusCode of the error. # noqa: E501 - - :param status_code: The status_code of this ApiErrorResponse. # noqa: E501 - :type: int - """ - - self._status_code = status_code - - @property - def error_message(self): - """Gets the error_message of this ApiErrorResponse. # noqa: E501 - - The message provided by the error handler. # noqa: E501 - - :return: The error_message of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._error_message - - @error_message.setter - def error_message(self, error_message): - """Sets the error_message of this ApiErrorResponse. - - The message provided by the error handler. # noqa: E501 - - :param error_message: The error_message of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._error_message = error_message - - @property - def error_details(self): - """Gets the error_details of this ApiErrorResponse. # noqa: E501 - - The details of the error. # noqa: E501 - - :return: The error_details of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._error_details - - @error_details.setter - def error_details(self, error_details): - """Sets the error_details of this ApiErrorResponse. - - The details of the error. # noqa: E501 - - :param error_details: The error_details of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._error_details = error_details - - @property - def request_id(self): - """Gets the request_id of this ApiErrorResponse. # noqa: E501 - - The Id of the request that triggered the error. If contacting API Support, please include the RequestId. # noqa: E501 - - :return: The request_id of this ApiErrorResponse. # noqa: E501 - :rtype: str - """ - return self._request_id - - @request_id.setter - def request_id(self, request_id): - """Sets the request_id of this ApiErrorResponse. - - The Id of the request that triggered the error. If contacting API Support, please include the RequestId. # noqa: E501 - - :param request_id: The request_id of this ApiErrorResponse. # noqa: E501 - :type: str - """ - - self._request_id = request_id - - @property - def validation_errors(self): - """Gets the validation_errors of this ApiErrorResponse. # noqa: E501 - - The list of validation errors (if applicable). # noqa: E501 - - :return: The validation_errors of this ApiErrorResponse. # noqa: E501 - :rtype: list[ApiValidationError] - """ - return self._validation_errors - - @validation_errors.setter - def validation_errors(self, validation_errors): - """Sets the validation_errors of this ApiErrorResponse. - - The list of validation errors (if applicable). # noqa: E501 - - :param validation_errors: The validation_errors of this ApiErrorResponse. # noqa: E501 - :type: list[ApiValidationError] - """ - - self._validation_errors = validation_errors - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ApiErrorResponse, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ApiErrorResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/api_validation_error.py b/digikey/v3/ordersupport/models/api_validation_error.py deleted file mode 100644 index 7ab9a9b..0000000 --- a/digikey/v3/ordersupport/models/api_validation_error.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class ApiValidationError(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'field': 'str', - 'message': 'str' - } - - attribute_map = { - 'field': 'Field', - 'message': 'Message' - } - - def __init__(self, field=None, message=None): # noqa: E501 - """ApiValidationError - a model defined in Swagger""" # noqa: E501 - - self._field = None - self._message = None - self.discriminator = None - - if field is not None: - self.field = field - if message is not None: - self.message = message - - @property - def field(self): - """Gets the field of this ApiValidationError. # noqa: E501 - - The field that generated the error. # noqa: E501 - - :return: The field of this ApiValidationError. # noqa: E501 - :rtype: str - """ - return self._field - - @field.setter - def field(self, field): - """Sets the field of this ApiValidationError. - - The field that generated the error. # noqa: E501 - - :param field: The field of this ApiValidationError. # noqa: E501 - :type: str - """ - - self._field = field - - @property - def message(self): - """Gets the message of this ApiValidationError. # noqa: E501 - - The error message that was generated. This often explains how to fix your API input to be valid. # noqa: E501 - - :return: The message of this ApiValidationError. # noqa: E501 - :rtype: str - """ - return self._message - - @message.setter - def message(self, message): - """Sets the message of this ApiValidationError. - - The error message that was generated. This often explains how to fix your API input to be valid. # noqa: E501 - - :param message: The message of this ApiValidationError. # noqa: E501 - :type: str - """ - - self._message = message - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ApiValidationError, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ApiValidationError): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/line_item.py b/digikey/v3/ordersupport/models/line_item.py deleted file mode 100644 index acae410..0000000 --- a/digikey/v3/ordersupport/models/line_item.py +++ /dev/null @@ -1,453 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class LineItem(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'digi_key_part_number': 'str', - 'manufacturer_part_number': 'str', - 'product_description': 'str', - 'manufacturer': 'str', - 'country_of_origin': 'str', - 'quantity': 'int', - 'customer_reference': 'str', - 'unit_price': 'float', - 'total_price': 'float', - 'quantity_backorder': 'int', - 'quantity_shipped': 'int', - 'invoice_id': 'int', - 'schedule': 'list[Schedule]' - } - - attribute_map = { - 'digi_key_part_number': 'DigiKeyPartNumber', - 'manufacturer_part_number': 'ManufacturerPartNumber', - 'product_description': 'ProductDescription', - 'manufacturer': 'Manufacturer', - 'country_of_origin': 'CountryOfOrigin', - 'quantity': 'Quantity', - 'customer_reference': 'CustomerReference', - 'unit_price': 'UnitPrice', - 'total_price': 'TotalPrice', - 'quantity_backorder': 'QuantityBackorder', - 'quantity_shipped': 'QuantityShipped', - 'invoice_id': 'InvoiceId', - 'schedule': 'Schedule' - } - - def __init__(self, digi_key_part_number=None, manufacturer_part_number=None, product_description=None, manufacturer=None, country_of_origin=None, quantity=None, customer_reference=None, unit_price=None, total_price=None, quantity_backorder=None, quantity_shipped=None, invoice_id=None, schedule=None): # noqa: E501 - """LineItem - a model defined in Swagger""" # noqa: E501 - - self._digi_key_part_number = None - self._manufacturer_part_number = None - self._product_description = None - self._manufacturer = None - self._country_of_origin = None - self._quantity = None - self._customer_reference = None - self._unit_price = None - self._total_price = None - self._quantity_backorder = None - self._quantity_shipped = None - self._invoice_id = None - self._schedule = None - self.discriminator = None - - if digi_key_part_number is not None: - self.digi_key_part_number = digi_key_part_number - if manufacturer_part_number is not None: - self.manufacturer_part_number = manufacturer_part_number - if product_description is not None: - self.product_description = product_description - if manufacturer is not None: - self.manufacturer = manufacturer - if country_of_origin is not None: - self.country_of_origin = country_of_origin - if quantity is not None: - self.quantity = quantity - if customer_reference is not None: - self.customer_reference = customer_reference - if unit_price is not None: - self.unit_price = unit_price - if total_price is not None: - self.total_price = total_price - if quantity_backorder is not None: - self.quantity_backorder = quantity_backorder - if quantity_shipped is not None: - self.quantity_shipped = quantity_shipped - if invoice_id is not None: - self.invoice_id = invoice_id - if schedule is not None: - self.schedule = schedule - - @property - def digi_key_part_number(self): - """Gets the digi_key_part_number of this LineItem. # noqa: E501 - - The Digi-Key part number. # noqa: E501 - - :return: The digi_key_part_number of this LineItem. # noqa: E501 - :rtype: str - """ - return self._digi_key_part_number - - @digi_key_part_number.setter - def digi_key_part_number(self, digi_key_part_number): - """Sets the digi_key_part_number of this LineItem. - - The Digi-Key part number. # noqa: E501 - - :param digi_key_part_number: The digi_key_part_number of this LineItem. # noqa: E501 - :type: str - """ - - self._digi_key_part_number = digi_key_part_number - - @property - def manufacturer_part_number(self): - """Gets the manufacturer_part_number of this LineItem. # noqa: E501 - - The Manufacturer Part Number. # noqa: E501 - - :return: The manufacturer_part_number of this LineItem. # noqa: E501 - :rtype: str - """ - return self._manufacturer_part_number - - @manufacturer_part_number.setter - def manufacturer_part_number(self, manufacturer_part_number): - """Sets the manufacturer_part_number of this LineItem. - - The Manufacturer Part Number. # noqa: E501 - - :param manufacturer_part_number: The manufacturer_part_number of this LineItem. # noqa: E501 - :type: str - """ - - self._manufacturer_part_number = manufacturer_part_number - - @property - def product_description(self): - """Gets the product_description of this LineItem. # noqa: E501 - - Catalog description of the product. # noqa: E501 - - :return: The product_description of this LineItem. # noqa: E501 - :rtype: str - """ - return self._product_description - - @product_description.setter - def product_description(self, product_description): - """Sets the product_description of this LineItem. - - Catalog description of the product. # noqa: E501 - - :param product_description: The product_description of this LineItem. # noqa: E501 - :type: str - """ - - self._product_description = product_description - - @property - def manufacturer(self): - """Gets the manufacturer of this LineItem. # noqa: E501 - - The Manufacturer of the product. # noqa: E501 - - :return: The manufacturer of this LineItem. # noqa: E501 - :rtype: str - """ - return self._manufacturer - - @manufacturer.setter - def manufacturer(self, manufacturer): - """Sets the manufacturer of this LineItem. - - The Manufacturer of the product. # noqa: E501 - - :param manufacturer: The manufacturer of this LineItem. # noqa: E501 - :type: str - """ - - self._manufacturer = manufacturer - - @property - def country_of_origin(self): - """Gets the country_of_origin of this LineItem. # noqa: E501 - - The Country Of Origin of the product # noqa: E501 - - :return: The country_of_origin of this LineItem. # noqa: E501 - :rtype: str - """ - return self._country_of_origin - - @country_of_origin.setter - def country_of_origin(self, country_of_origin): - """Sets the country_of_origin of this LineItem. - - The Country Of Origin of the product # noqa: E501 - - :param country_of_origin: The country_of_origin of this LineItem. # noqa: E501 - :type: str - """ - - self._country_of_origin = country_of_origin - - @property - def quantity(self): - """Gets the quantity of this LineItem. # noqa: E501 - - The total quantity for the order. # noqa: E501 - - :return: The quantity of this LineItem. # noqa: E501 - :rtype: int - """ - return self._quantity - - @quantity.setter - def quantity(self, quantity): - """Sets the quantity of this LineItem. - - The total quantity for the order. # noqa: E501 - - :param quantity: The quantity of this LineItem. # noqa: E501 - :type: int - """ - - self._quantity = quantity - - @property - def customer_reference(self): - """Gets the customer_reference of this LineItem. # noqa: E501 - - Freeform customer reference # noqa: E501 - - :return: The customer_reference of this LineItem. # noqa: E501 - :rtype: str - """ - return self._customer_reference - - @customer_reference.setter - def customer_reference(self, customer_reference): - """Sets the customer_reference of this LineItem. - - Freeform customer reference # noqa: E501 - - :param customer_reference: The customer_reference of this LineItem. # noqa: E501 - :type: str - """ - - self._customer_reference = customer_reference - - @property - def unit_price(self): - """Gets the unit_price of this LineItem. # noqa: E501 - - The price for a single unit of this product. # noqa: E501 - - :return: The unit_price of this LineItem. # noqa: E501 - :rtype: float - """ - return self._unit_price - - @unit_price.setter - def unit_price(self, unit_price): - """Sets the unit_price of this LineItem. - - The price for a single unit of this product. # noqa: E501 - - :param unit_price: The unit_price of this LineItem. # noqa: E501 - :type: float - """ - - self._unit_price = unit_price - - @property - def total_price(self): - """Gets the total_price of this LineItem. # noqa: E501 - - Price of ordered quantity of the product. # noqa: E501 - - :return: The total_price of this LineItem. # noqa: E501 - :rtype: float - """ - return self._total_price - - @total_price.setter - def total_price(self, total_price): - """Sets the total_price of this LineItem. - - Price of ordered quantity of the product. # noqa: E501 - - :param total_price: The total_price of this LineItem. # noqa: E501 - :type: float - """ - - self._total_price = total_price - - @property - def quantity_backorder(self): - """Gets the quantity_backorder of this LineItem. # noqa: E501 - - The quantity on backorder # noqa: E501 - - :return: The quantity_backorder of this LineItem. # noqa: E501 - :rtype: int - """ - return self._quantity_backorder - - @quantity_backorder.setter - def quantity_backorder(self, quantity_backorder): - """Sets the quantity_backorder of this LineItem. - - The quantity on backorder # noqa: E501 - - :param quantity_backorder: The quantity_backorder of this LineItem. # noqa: E501 - :type: int - """ - - self._quantity_backorder = quantity_backorder - - @property - def quantity_shipped(self): - """Gets the quantity_shipped of this LineItem. # noqa: E501 - - The quantity shipped # noqa: E501 - - :return: The quantity_shipped of this LineItem. # noqa: E501 - :rtype: int - """ - return self._quantity_shipped - - @quantity_shipped.setter - def quantity_shipped(self, quantity_shipped): - """Sets the quantity_shipped of this LineItem. - - The quantity shipped # noqa: E501 - - :param quantity_shipped: The quantity_shipped of this LineItem. # noqa: E501 - :type: int - """ - - self._quantity_shipped = quantity_shipped - - @property - def invoice_id(self): - """Gets the invoice_id of this LineItem. # noqa: E501 - - The Invoice Id for this shipment # noqa: E501 - - :return: The invoice_id of this LineItem. # noqa: E501 - :rtype: int - """ - return self._invoice_id - - @invoice_id.setter - def invoice_id(self, invoice_id): - """Sets the invoice_id of this LineItem. - - The Invoice Id for this shipment # noqa: E501 - - :param invoice_id: The invoice_id of this LineItem. # noqa: E501 - :type: int - """ - - self._invoice_id = invoice_id - - @property - def schedule(self): - """Gets the schedule of this LineItem. # noqa: E501 - - The Scheduled shipment # noqa: E501 - - :return: The schedule of this LineItem. # noqa: E501 - :rtype: list[Schedule] - """ - return self._schedule - - @schedule.setter - def schedule(self, schedule): - """Sets the schedule of this LineItem. - - The Scheduled shipment # noqa: E501 - - :param schedule: The schedule of this LineItem. # noqa: E501 - :type: list[Schedule] - """ - - self._schedule = schedule - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(LineItem, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, LineItem): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/order_status_response.py b/digikey/v3/ordersupport/models/order_status_response.py deleted file mode 100644 index 2b825af..0000000 --- a/digikey/v3/ordersupport/models/order_status_response.py +++ /dev/null @@ -1,561 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class OrderStatusResponse(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'salesorder_id': 'int', - 'customer_id': 'int', - 'billing_account': 'int', - 'email': 'str', - 'purchase_order': 'str', - 'payment_method': 'str', - 'supplier': 'str', - 'shipping_method': 'str', - 'backorder_shipping_method': 'str', - 'shipper_account_number': 'str', - 'backorder_shipper_account_number': 'str', - 'shipment_type': 'str', - 'currency': 'str', - 'shipping_address': 'Address', - 'billing_address': 'Address', - 'shipping_details': 'list[ShippingDetail]', - 'line_items': 'list[LineItem]' - } - - attribute_map = { - 'salesorder_id': 'SalesorderId', - 'customer_id': 'CustomerId', - 'billing_account': 'BillingAccount', - 'email': 'Email', - 'purchase_order': 'PurchaseOrder', - 'payment_method': 'PaymentMethod', - 'supplier': 'Supplier', - 'shipping_method': 'ShippingMethod', - 'backorder_shipping_method': 'BackorderShippingMethod', - 'shipper_account_number': 'ShipperAccountNumber', - 'backorder_shipper_account_number': 'BackorderShipperAccountNumber', - 'shipment_type': 'ShipmentType', - 'currency': 'Currency', - 'shipping_address': 'ShippingAddress', - 'billing_address': 'BillingAddress', - 'shipping_details': 'ShippingDetails', - 'line_items': 'LineItems' - } - - def __init__(self, salesorder_id=None, customer_id=None, billing_account=None, email=None, purchase_order=None, payment_method=None, supplier=None, shipping_method=None, backorder_shipping_method=None, shipper_account_number=None, backorder_shipper_account_number=None, shipment_type=None, currency=None, shipping_address=None, billing_address=None, shipping_details=None, line_items=None): # noqa: E501 - """OrderStatusResponse - a model defined in Swagger""" # noqa: E501 - - self._salesorder_id = None - self._customer_id = None - self._billing_account = None - self._email = None - self._purchase_order = None - self._payment_method = None - self._supplier = None - self._shipping_method = None - self._backorder_shipping_method = None - self._shipper_account_number = None - self._backorder_shipper_account_number = None - self._shipment_type = None - self._currency = None - self._shipping_address = None - self._billing_address = None - self._shipping_details = None - self._line_items = None - self.discriminator = None - - if salesorder_id is not None: - self.salesorder_id = salesorder_id - if customer_id is not None: - self.customer_id = customer_id - if billing_account is not None: - self.billing_account = billing_account - if email is not None: - self.email = email - if purchase_order is not None: - self.purchase_order = purchase_order - if payment_method is not None: - self.payment_method = payment_method - if supplier is not None: - self.supplier = supplier - if shipping_method is not None: - self.shipping_method = shipping_method - if backorder_shipping_method is not None: - self.backorder_shipping_method = backorder_shipping_method - if shipper_account_number is not None: - self.shipper_account_number = shipper_account_number - if backorder_shipper_account_number is not None: - self.backorder_shipper_account_number = backorder_shipper_account_number - if shipment_type is not None: - self.shipment_type = shipment_type - if currency is not None: - self.currency = currency - if shipping_address is not None: - self.shipping_address = shipping_address - if billing_address is not None: - self.billing_address = billing_address - if shipping_details is not None: - self.shipping_details = shipping_details - if line_items is not None: - self.line_items = line_items - - @property - def salesorder_id(self): - """Gets the salesorder_id of this OrderStatusResponse. # noqa: E501 - - Id for this order # noqa: E501 - - :return: The salesorder_id of this OrderStatusResponse. # noqa: E501 - :rtype: int - """ - return self._salesorder_id - - @salesorder_id.setter - def salesorder_id(self, salesorder_id): - """Sets the salesorder_id of this OrderStatusResponse. - - Id for this order # noqa: E501 - - :param salesorder_id: The salesorder_id of this OrderStatusResponse. # noqa: E501 - :type: int - """ - - self._salesorder_id = salesorder_id - - @property - def customer_id(self): - """Gets the customer_id of this OrderStatusResponse. # noqa: E501 - - Your Digi-Key customer Id # noqa: E501 - - :return: The customer_id of this OrderStatusResponse. # noqa: E501 - :rtype: int - """ - return self._customer_id - - @customer_id.setter - def customer_id(self, customer_id): - """Sets the customer_id of this OrderStatusResponse. - - Your Digi-Key customer Id # noqa: E501 - - :param customer_id: The customer_id of this OrderStatusResponse. # noqa: E501 - :type: int - """ - - self._customer_id = customer_id - - @property - def billing_account(self): - """Gets the billing_account of this OrderStatusResponse. # noqa: E501 - - Net Terms billing account number used for the order. # noqa: E501 - - :return: The billing_account of this OrderStatusResponse. # noqa: E501 - :rtype: int - """ - return self._billing_account - - @billing_account.setter - def billing_account(self, billing_account): - """Sets the billing_account of this OrderStatusResponse. - - Net Terms billing account number used for the order. # noqa: E501 - - :param billing_account: The billing_account of this OrderStatusResponse. # noqa: E501 - :type: int - """ - - self._billing_account = billing_account - - @property - def email(self): - """Gets the email of this OrderStatusResponse. # noqa: E501 - - Email Address # noqa: E501 - - :return: The email of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._email - - @email.setter - def email(self, email): - """Sets the email of this OrderStatusResponse. - - Email Address # noqa: E501 - - :param email: The email of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._email = email - - @property - def purchase_order(self): - """Gets the purchase_order of this OrderStatusResponse. # noqa: E501 - - Freeform purchase order # noqa: E501 - - :return: The purchase_order of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._purchase_order - - @purchase_order.setter - def purchase_order(self, purchase_order): - """Sets the purchase_order of this OrderStatusResponse. - - Freeform purchase order # noqa: E501 - - :param purchase_order: The purchase_order of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._purchase_order = purchase_order - - @property - def payment_method(self): - """Gets the payment_method of this OrderStatusResponse. # noqa: E501 - - Payment method for the order # noqa: E501 - - :return: The payment_method of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._payment_method - - @payment_method.setter - def payment_method(self, payment_method): - """Sets the payment_method of this OrderStatusResponse. - - Payment method for the order # noqa: E501 - - :param payment_method: The payment_method of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._payment_method = payment_method - - @property - def supplier(self): - """Gets the supplier of this OrderStatusResponse. # noqa: E501 - - Shipped by # noqa: E501 - - :return: The supplier of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._supplier - - @supplier.setter - def supplier(self, supplier): - """Sets the supplier of this OrderStatusResponse. - - Shipped by # noqa: E501 - - :param supplier: The supplier of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._supplier = supplier - - @property - def shipping_method(self): - """Gets the shipping_method of this OrderStatusResponse. # noqa: E501 - - Shipping method requested # noqa: E501 - - :return: The shipping_method of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._shipping_method - - @shipping_method.setter - def shipping_method(self, shipping_method): - """Sets the shipping_method of this OrderStatusResponse. - - Shipping method requested # noqa: E501 - - :param shipping_method: The shipping_method of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._shipping_method = shipping_method - - @property - def backorder_shipping_method(self): - """Gets the backorder_shipping_method of this OrderStatusResponse. # noqa: E501 - - Backorder shipping method requested # noqa: E501 - - :return: The backorder_shipping_method of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._backorder_shipping_method - - @backorder_shipping_method.setter - def backorder_shipping_method(self, backorder_shipping_method): - """Sets the backorder_shipping_method of this OrderStatusResponse. - - Backorder shipping method requested # noqa: E501 - - :param backorder_shipping_method: The backorder_shipping_method of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._backorder_shipping_method = backorder_shipping_method - - @property - def shipper_account_number(self): - """Gets the shipper_account_number of this OrderStatusResponse. # noqa: E501 - - Account number with the shipper # noqa: E501 - - :return: The shipper_account_number of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._shipper_account_number - - @shipper_account_number.setter - def shipper_account_number(self, shipper_account_number): - """Sets the shipper_account_number of this OrderStatusResponse. - - Account number with the shipper # noqa: E501 - - :param shipper_account_number: The shipper_account_number of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._shipper_account_number = shipper_account_number - - @property - def backorder_shipper_account_number(self): - """Gets the backorder_shipper_account_number of this OrderStatusResponse. # noqa: E501 - - Account number with the backorder shipper # noqa: E501 - - :return: The backorder_shipper_account_number of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._backorder_shipper_account_number - - @backorder_shipper_account_number.setter - def backorder_shipper_account_number(self, backorder_shipper_account_number): - """Sets the backorder_shipper_account_number of this OrderStatusResponse. - - Account number with the backorder shipper # noqa: E501 - - :param backorder_shipper_account_number: The backorder_shipper_account_number of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._backorder_shipper_account_number = backorder_shipper_account_number - - @property - def shipment_type(self): - """Gets the shipment_type of this OrderStatusResponse. # noqa: E501 - - Can be Immediate, Double or Single. If Immediate, all items will ship as available. If Double, all items immediately available will ship, and other items will be held untill all are available. If Single, entire order is held untill all items are available. # noqa: E501 - - :return: The shipment_type of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._shipment_type - - @shipment_type.setter - def shipment_type(self, shipment_type): - """Sets the shipment_type of this OrderStatusResponse. - - Can be Immediate, Double or Single. If Immediate, all items will ship as available. If Double, all items immediately available will ship, and other items will be held untill all are available. If Single, entire order is held untill all items are available. # noqa: E501 - - :param shipment_type: The shipment_type of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._shipment_type = shipment_type - - @property - def currency(self): - """Gets the currency of this OrderStatusResponse. # noqa: E501 - - ISO code for currency used in the order. # noqa: E501 - - :return: The currency of this OrderStatusResponse. # noqa: E501 - :rtype: str - """ - return self._currency - - @currency.setter - def currency(self, currency): - """Sets the currency of this OrderStatusResponse. - - ISO code for currency used in the order. # noqa: E501 - - :param currency: The currency of this OrderStatusResponse. # noqa: E501 - :type: str - """ - - self._currency = currency - - @property - def shipping_address(self): - """Gets the shipping_address of this OrderStatusResponse. # noqa: E501 - - - :return: The shipping_address of this OrderStatusResponse. # noqa: E501 - :rtype: Address - """ - return self._shipping_address - - @shipping_address.setter - def shipping_address(self, shipping_address): - """Sets the shipping_address of this OrderStatusResponse. - - - :param shipping_address: The shipping_address of this OrderStatusResponse. # noqa: E501 - :type: Address - """ - - self._shipping_address = shipping_address - - @property - def billing_address(self): - """Gets the billing_address of this OrderStatusResponse. # noqa: E501 - - - :return: The billing_address of this OrderStatusResponse. # noqa: E501 - :rtype: Address - """ - return self._billing_address - - @billing_address.setter - def billing_address(self, billing_address): - """Sets the billing_address of this OrderStatusResponse. - - - :param billing_address: The billing_address of this OrderStatusResponse. # noqa: E501 - :type: Address - """ - - self._billing_address = billing_address - - @property - def shipping_details(self): - """Gets the shipping_details of this OrderStatusResponse. # noqa: E501 - - List of shipping details # noqa: E501 - - :return: The shipping_details of this OrderStatusResponse. # noqa: E501 - :rtype: list[ShippingDetail] - """ - return self._shipping_details - - @shipping_details.setter - def shipping_details(self, shipping_details): - """Sets the shipping_details of this OrderStatusResponse. - - List of shipping details # noqa: E501 - - :param shipping_details: The shipping_details of this OrderStatusResponse. # noqa: E501 - :type: list[ShippingDetail] - """ - - self._shipping_details = shipping_details - - @property - def line_items(self): - """Gets the line_items of this OrderStatusResponse. # noqa: E501 - - List of line items # noqa: E501 - - :return: The line_items of this OrderStatusResponse. # noqa: E501 - :rtype: list[LineItem] - """ - return self._line_items - - @line_items.setter - def line_items(self, line_items): - """Sets the line_items of this OrderStatusResponse. - - List of line items # noqa: E501 - - :param line_items: The line_items of this OrderStatusResponse. # noqa: E501 - :type: list[LineItem] - """ - - self._line_items = line_items - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(OrderStatusResponse, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, OrderStatusResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/sales_order_history_item.py b/digikey/v3/ordersupport/models/sales_order_history_item.py deleted file mode 100644 index 2eee431..0000000 --- a/digikey/v3/ordersupport/models/sales_order_history_item.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class SalesOrderHistoryItem(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'salesorder_id': 'int', - 'customer_id': 'int', - 'date_entered': 'str', - 'purchase_order': 'str' - } - - attribute_map = { - 'salesorder_id': 'SalesorderId', - 'customer_id': 'CustomerId', - 'date_entered': 'DateEntered', - 'purchase_order': 'PurchaseOrder' - } - - def __init__(self, salesorder_id=None, customer_id=None, date_entered=None, purchase_order=None): # noqa: E501 - """SalesOrderHistoryItem - a model defined in Swagger""" # noqa: E501 - - self._salesorder_id = None - self._customer_id = None - self._date_entered = None - self._purchase_order = None - self.discriminator = None - - if salesorder_id is not None: - self.salesorder_id = salesorder_id - if customer_id is not None: - self.customer_id = customer_id - if date_entered is not None: - self.date_entered = date_entered - if purchase_order is not None: - self.purchase_order = purchase_order - - @property - def salesorder_id(self): - """Gets the salesorder_id of this SalesOrderHistoryItem. # noqa: E501 - - The SalesOrder Id. You can use this Id to look up details on the order. # noqa: E501 - - :return: The salesorder_id of this SalesOrderHistoryItem. # noqa: E501 - :rtype: int - """ - return self._salesorder_id - - @salesorder_id.setter - def salesorder_id(self, salesorder_id): - """Sets the salesorder_id of this SalesOrderHistoryItem. - - The SalesOrder Id. You can use this Id to look up details on the order. # noqa: E501 - - :param salesorder_id: The salesorder_id of this SalesOrderHistoryItem. # noqa: E501 - :type: int - """ - - self._salesorder_id = salesorder_id - - @property - def customer_id(self): - """Gets the customer_id of this SalesOrderHistoryItem. # noqa: E501 - - The CustomerId associated with the SalesOrder # noqa: E501 - - :return: The customer_id of this SalesOrderHistoryItem. # noqa: E501 - :rtype: int - """ - return self._customer_id - - @customer_id.setter - def customer_id(self, customer_id): - """Sets the customer_id of this SalesOrderHistoryItem. - - The CustomerId associated with the SalesOrder # noqa: E501 - - :param customer_id: The customer_id of this SalesOrderHistoryItem. # noqa: E501 - :type: int - """ - - self._customer_id = customer_id - - @property - def date_entered(self): - """Gets the date_entered of this SalesOrderHistoryItem. # noqa: E501 - - Date in which the order was entered in ISO 8601 format. # noqa: E501 - - :return: The date_entered of this SalesOrderHistoryItem. # noqa: E501 - :rtype: str - """ - return self._date_entered - - @date_entered.setter - def date_entered(self, date_entered): - """Sets the date_entered of this SalesOrderHistoryItem. - - Date in which the order was entered in ISO 8601 format. # noqa: E501 - - :param date_entered: The date_entered of this SalesOrderHistoryItem. # noqa: E501 - :type: str - """ - - self._date_entered = date_entered - - @property - def purchase_order(self): - """Gets the purchase_order of this SalesOrderHistoryItem. # noqa: E501 - - Purchase order if available # noqa: E501 - - :return: The purchase_order of this SalesOrderHistoryItem. # noqa: E501 - :rtype: str - """ - return self._purchase_order - - @purchase_order.setter - def purchase_order(self, purchase_order): - """Sets the purchase_order of this SalesOrderHistoryItem. - - Purchase order if available # noqa: E501 - - :param purchase_order: The purchase_order of this SalesOrderHistoryItem. # noqa: E501 - :type: str - """ - - self._purchase_order = purchase_order - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(SalesOrderHistoryItem, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, SalesOrderHistoryItem): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/salesorder_history_item.py b/digikey/v3/ordersupport/models/salesorder_history_item.py deleted file mode 100644 index 16825ed..0000000 --- a/digikey/v3/ordersupport/models/salesorder_history_item.py +++ /dev/null @@ -1,201 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - Contact: api.contact@digikey.com - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class SalesorderHistoryItem(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'salesorder_id': 'int', - 'customer_id': 'int', - 'date_entered': 'str', - 'purchase_order': 'str' - } - - attribute_map = { - 'salesorder_id': 'SalesorderId', - 'customer_id': 'CustomerId', - 'date_entered': 'DateEntered', - 'purchase_order': 'PurchaseOrder' - } - - def __init__(self, salesorder_id=None, customer_id=None, date_entered=None, purchase_order=None): # noqa: E501 - """SalesorderHistoryItem - a model defined in Swagger""" # noqa: E501 - - self._salesorder_id = None - self._customer_id = None - self._date_entered = None - self._purchase_order = None - self.discriminator = None - - if salesorder_id is not None: - self.salesorder_id = salesorder_id - if customer_id is not None: - self.customer_id = customer_id - if date_entered is not None: - self.date_entered = date_entered - if purchase_order is not None: - self.purchase_order = purchase_order - - @property - def salesorder_id(self): - """Gets the salesorder_id of this SalesorderHistoryItem. # noqa: E501 - - The Salesorder Id. You can use this Id to look up details on the order. # noqa: E501 - - :return: The salesorder_id of this SalesorderHistoryItem. # noqa: E501 - :rtype: int - """ - return self._salesorder_id - - @salesorder_id.setter - def salesorder_id(self, salesorder_id): - """Sets the salesorder_id of this SalesorderHistoryItem. - - The Salesorder Id. You can use this Id to look up details on the order. # noqa: E501 - - :param salesorder_id: The salesorder_id of this SalesorderHistoryItem. # noqa: E501 - :type: int - """ - - self._salesorder_id = salesorder_id - - @property - def customer_id(self): - """Gets the customer_id of this SalesorderHistoryItem. # noqa: E501 - - The CustomerId associated with the Salesorder # noqa: E501 - - :return: The customer_id of this SalesorderHistoryItem. # noqa: E501 - :rtype: int - """ - return self._customer_id - - @customer_id.setter - def customer_id(self, customer_id): - """Sets the customer_id of this SalesorderHistoryItem. - - The CustomerId associated with the Salesorder # noqa: E501 - - :param customer_id: The customer_id of this SalesorderHistoryItem. # noqa: E501 - :type: int - """ - - self._customer_id = customer_id - - @property - def date_entered(self): - """Gets the date_entered of this SalesorderHistoryItem. # noqa: E501 - - Date in which the order was entered in ISO 8601 format. # noqa: E501 - - :return: The date_entered of this SalesorderHistoryItem. # noqa: E501 - :rtype: str - """ - return self._date_entered - - @date_entered.setter - def date_entered(self, date_entered): - """Sets the date_entered of this SalesorderHistoryItem. - - Date in which the order was entered in ISO 8601 format. # noqa: E501 - - :param date_entered: The date_entered of this SalesorderHistoryItem. # noqa: E501 - :type: str - """ - - self._date_entered = date_entered - - @property - def purchase_order(self): - """Gets the purchase_order of this SalesorderHistoryItem. # noqa: E501 - - Purchase order if available # noqa: E501 - - :return: The purchase_order of this SalesorderHistoryItem. # noqa: E501 - :rtype: str - """ - return self._purchase_order - - @purchase_order.setter - def purchase_order(self, purchase_order): - """Sets the purchase_order of this SalesorderHistoryItem. - - Purchase order if available # noqa: E501 - - :param purchase_order: The purchase_order of this SalesorderHistoryItem. # noqa: E501 - :type: str - """ - - self._purchase_order = purchase_order - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(SalesorderHistoryItem, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, SalesorderHistoryItem): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/schedule.py b/digikey/v3/ordersupport/models/schedule.py deleted file mode 100644 index e5cb8df..0000000 --- a/digikey/v3/ordersupport/models/schedule.py +++ /dev/null @@ -1,145 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class Schedule(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'scheduled_quantity': 'int', - 'scheduled_date': 'str' - } - - attribute_map = { - 'scheduled_quantity': 'ScheduledQuantity', - 'scheduled_date': 'ScheduledDate' - } - - def __init__(self, scheduled_quantity=None, scheduled_date=None): # noqa: E501 - """Schedule - a model defined in Swagger""" # noqa: E501 - - self._scheduled_quantity = None - self._scheduled_date = None - self.discriminator = None - - if scheduled_quantity is not None: - self.scheduled_quantity = scheduled_quantity - if scheduled_date is not None: - self.scheduled_date = scheduled_date - - @property - def scheduled_quantity(self): - """Gets the scheduled_quantity of this Schedule. # noqa: E501 - - The total quantity for the schedule. # noqa: E501 - - :return: The scheduled_quantity of this Schedule. # noqa: E501 - :rtype: int - """ - return self._scheduled_quantity - - @scheduled_quantity.setter - def scheduled_quantity(self, scheduled_quantity): - """Sets the scheduled_quantity of this Schedule. - - The total quantity for the schedule. # noqa: E501 - - :param scheduled_quantity: The scheduled_quantity of this Schedule. # noqa: E501 - :type: int - """ - - self._scheduled_quantity = scheduled_quantity - - @property - def scheduled_date(self): - """Gets the scheduled_date of this Schedule. # noqa: E501 - - The Date of the Schedule ISO 8601 format # noqa: E501 - - :return: The scheduled_date of this Schedule. # noqa: E501 - :rtype: str - """ - return self._scheduled_date - - @scheduled_date.setter - def scheduled_date(self, scheduled_date): - """Sets the scheduled_date of this Schedule. - - The Date of the Schedule ISO 8601 format # noqa: E501 - - :param scheduled_date: The scheduled_date of this Schedule. # noqa: E501 - :type: str - """ - - self._scheduled_date = scheduled_date - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Schedule, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Schedule): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/models/shipping_detail.py b/digikey/v3/ordersupport/models/shipping_detail.py deleted file mode 100644 index ecc960c..0000000 --- a/digikey/v3/ordersupport/models/shipping_detail.py +++ /dev/null @@ -1,311 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -import pprint -import re # noqa: F401 - -import six - - -class ShippingDetail(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'carrier': 'str', - 'carrier_package_id': 'str', - 'date_transaction': 'str', - 'shipping_method': 'str', - 'tracking_url': 'str', - 'invoice_id': 'int', - 'canceled_or_voided': 'bool', - 'delivery_date': 'str' - } - - attribute_map = { - 'carrier': 'Carrier', - 'carrier_package_id': 'CarrierPackageId', - 'date_transaction': 'DateTransaction', - 'shipping_method': 'ShippingMethod', - 'tracking_url': 'TrackingUrl', - 'invoice_id': 'InvoiceId', - 'canceled_or_voided': 'CanceledOrVoided', - 'delivery_date': 'DeliveryDate' - } - - def __init__(self, carrier=None, carrier_package_id=None, date_transaction=None, shipping_method=None, tracking_url=None, invoice_id=None, canceled_or_voided=None, delivery_date=None): # noqa: E501 - """ShippingDetail - a model defined in Swagger""" # noqa: E501 - - self._carrier = None - self._carrier_package_id = None - self._date_transaction = None - self._shipping_method = None - self._tracking_url = None - self._invoice_id = None - self._canceled_or_voided = None - self._delivery_date = None - self.discriminator = None - - if carrier is not None: - self.carrier = carrier - if carrier_package_id is not None: - self.carrier_package_id = carrier_package_id - if date_transaction is not None: - self.date_transaction = date_transaction - if shipping_method is not None: - self.shipping_method = shipping_method - if tracking_url is not None: - self.tracking_url = tracking_url - if invoice_id is not None: - self.invoice_id = invoice_id - if canceled_or_voided is not None: - self.canceled_or_voided = canceled_or_voided - if delivery_date is not None: - self.delivery_date = delivery_date - - @property - def carrier(self): - """Gets the carrier of this ShippingDetail. # noqa: E501 - - Name of the carrier # noqa: E501 - - :return: The carrier of this ShippingDetail. # noqa: E501 - :rtype: str - """ - return self._carrier - - @carrier.setter - def carrier(self, carrier): - """Sets the carrier of this ShippingDetail. - - Name of the carrier # noqa: E501 - - :param carrier: The carrier of this ShippingDetail. # noqa: E501 - :type: str - """ - - self._carrier = carrier - - @property - def carrier_package_id(self): - """Gets the carrier_package_id of this ShippingDetail. # noqa: E501 - - Id assigned by the carrier # noqa: E501 - - :return: The carrier_package_id of this ShippingDetail. # noqa: E501 - :rtype: str - """ - return self._carrier_package_id - - @carrier_package_id.setter - def carrier_package_id(self, carrier_package_id): - """Sets the carrier_package_id of this ShippingDetail. - - Id assigned by the carrier # noqa: E501 - - :param carrier_package_id: The carrier_package_id of this ShippingDetail. # noqa: E501 - :type: str - """ - - self._carrier_package_id = carrier_package_id - - @property - def date_transaction(self): - """Gets the date_transaction of this ShippingDetail. # noqa: E501 - - Date that tracking number was generated in ISO 8601 format # noqa: E501 - - :return: The date_transaction of this ShippingDetail. # noqa: E501 - :rtype: str - """ - return self._date_transaction - - @date_transaction.setter - def date_transaction(self, date_transaction): - """Sets the date_transaction of this ShippingDetail. - - Date that tracking number was generated in ISO 8601 format # noqa: E501 - - :param date_transaction: The date_transaction of this ShippingDetail. # noqa: E501 - :type: str - """ - - self._date_transaction = date_transaction - - @property - def shipping_method(self): - """Gets the shipping_method of this ShippingDetail. # noqa: E501 - - Shipping method used by this shipment # noqa: E501 - - :return: The shipping_method of this ShippingDetail. # noqa: E501 - :rtype: str - """ - return self._shipping_method - - @shipping_method.setter - def shipping_method(self, shipping_method): - """Sets the shipping_method of this ShippingDetail. - - Shipping method used by this shipment # noqa: E501 - - :param shipping_method: The shipping_method of this ShippingDetail. # noqa: E501 - :type: str - """ - - self._shipping_method = shipping_method - - @property - def tracking_url(self): - """Gets the tracking_url of this ShippingDetail. # noqa: E501 - - - :return: The tracking_url of this ShippingDetail. # noqa: E501 - :rtype: str - """ - return self._tracking_url - - @tracking_url.setter - def tracking_url(self, tracking_url): - """Sets the tracking_url of this ShippingDetail. - - - :param tracking_url: The tracking_url of this ShippingDetail. # noqa: E501 - :type: str - """ - - self._tracking_url = tracking_url - - @property - def invoice_id(self): - """Gets the invoice_id of this ShippingDetail. # noqa: E501 - - The Invoice Id for this shipment # noqa: E501 - - :return: The invoice_id of this ShippingDetail. # noqa: E501 - :rtype: int - """ - return self._invoice_id - - @invoice_id.setter - def invoice_id(self, invoice_id): - """Sets the invoice_id of this ShippingDetail. - - The Invoice Id for this shipment # noqa: E501 - - :param invoice_id: The invoice_id of this ShippingDetail. # noqa: E501 - :type: int - """ - - self._invoice_id = invoice_id - - @property - def canceled_or_voided(self): - """Gets the canceled_or_voided of this ShippingDetail. # noqa: E501 - - Whether this individual detail has been canceled or voided. # noqa: E501 - - :return: The canceled_or_voided of this ShippingDetail. # noqa: E501 - :rtype: bool - """ - return self._canceled_or_voided - - @canceled_or_voided.setter - def canceled_or_voided(self, canceled_or_voided): - """Sets the canceled_or_voided of this ShippingDetail. - - Whether this individual detail has been canceled or voided. # noqa: E501 - - :param canceled_or_voided: The canceled_or_voided of this ShippingDetail. # noqa: E501 - :type: bool - """ - - self._canceled_or_voided = canceled_or_voided - - @property - def delivery_date(self): - """Gets the delivery_date of this ShippingDetail. # noqa: E501 - - Date that the tracking number reports of delivery. If Tracking Number is not initiated by carrier or if tracking number is expired the value of DeliveryDate will be empty \"\" # noqa: E501 - - :return: The delivery_date of this ShippingDetail. # noqa: E501 - :rtype: str - """ - return self._delivery_date - - @delivery_date.setter - def delivery_date(self, delivery_date): - """Sets the delivery_date of this ShippingDetail. - - Date that the tracking number reports of delivery. If Tracking Number is not initiated by carrier or if tracking number is expired the value of DeliveryDate will be empty \"\" # noqa: E501 - - :param delivery_date: The delivery_date of this ShippingDetail. # noqa: E501 - :type: str - """ - - self._delivery_date = delivery_date - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ShippingDetail, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ShippingDetail): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/digikey/v3/ordersupport/rest.py b/digikey/v3/ordersupport/rest.py deleted file mode 100644 index 8cbd28f..0000000 --- a/digikey/v3/ordersupport/rest.py +++ /dev/null @@ -1,323 +0,0 @@ -# coding: utf-8 - -""" - Order Details - - Retrieve information about current and past orders. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -import io -import json -import logging -import re -import ssl - -import certifi -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode - -try: - import urllib3 -except ImportError: - raise ImportError('Swagger python client requires urllib3.') - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) - - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if query_params: - url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str): - request_body = body - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if six.PY3: - r.data = r.data.decode('utf8') - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - -class ApiException(Exception): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message diff --git a/digikey/v3/productinformation/__init__.py b/digikey/v3/productinformation/__init__.py deleted file mode 100644 index f1c8187..0000000 --- a/digikey/v3/productinformation/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - PartSearch Api - - Search for products and retrieve details and pricing. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import apis into sdk package -from digikey.v3.productinformation.api.part_search_api import PartSearchApi - -# import ApiClient -from digikey.v3.productinformation.api_client import ApiClient -from digikey.v3.productinformation.configuration import Configuration -# import models into sdk package -from digikey.v3.productinformation.models.api_error_response import ApiErrorResponse -from digikey.v3.productinformation.models.api_validation_error import ApiValidationError -from digikey.v3.productinformation.models.associated_product import AssociatedProduct -from digikey.v3.productinformation.models.basic_product import BasicProduct -from digikey.v3.productinformation.models.digi_reel_pricing import DigiReelPricing -from digikey.v3.productinformation.models.filters import Filters -from digikey.v3.productinformation.models.iso_search_locale import IsoSearchLocale -from digikey.v3.productinformation.models.keyword_search_request import KeywordSearchRequest -from digikey.v3.productinformation.models.keyword_search_response import KeywordSearchResponse -from digikey.v3.productinformation.models.kit_part import KitPart -from digikey.v3.productinformation.models.limited_parameter import LimitedParameter -from digikey.v3.productinformation.models.limited_taxonomy import LimitedTaxonomy -from digikey.v3.productinformation.models.manufacturer_product_details_request import ManufacturerProductDetailsRequest -from digikey.v3.productinformation.models.media_links import MediaLinks -from digikey.v3.productinformation.models.parametric_filter import ParametricFilter -from digikey.v3.productinformation.models.pid_vid import PidVid -from digikey.v3.productinformation.models.price_break import PriceBreak -from digikey.v3.productinformation.models.product import Product -from digikey.v3.productinformation.models.product_details import ProductDetails -from digikey.v3.productinformation.models.product_details_response import ProductDetailsResponse -from digikey.v3.productinformation.models.search_option import SearchOption -from digikey.v3.productinformation.models.sort_direction import SortDirection -from digikey.v3.productinformation.models.sort_option import SortOption -from digikey.v3.productinformation.models.sort_parameters import SortParameters -from digikey.v3.productinformation.models.value_pair import ValuePair diff --git a/digikey/v3/productinformation/api/__init__.py b/digikey/v3/productinformation/api/__init__.py deleted file mode 100644 index cfaa533..0000000 --- a/digikey/v3/productinformation/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from __future__ import absolute_import - -# flake8: noqa - -# import apis into api package -from digikey.v3.productinformation.api.part_search_api import PartSearchApi diff --git a/digikey/v3/productinformation/models/__init__.py b/digikey/v3/productinformation/models/__init__.py deleted file mode 100644 index 11a381d..0000000 --- a/digikey/v3/productinformation/models/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - PartSearch Api - - Search for products and retrieve details and pricing. # noqa: E501 - - OpenAPI spec version: v3 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - - -from __future__ import absolute_import - -# import models into model package -from digikey.v3.productinformation.models.api_error_response import ApiErrorResponse -from digikey.v3.productinformation.models.api_validation_error import ApiValidationError -from digikey.v3.productinformation.models.associated_product import AssociatedProduct -from digikey.v3.productinformation.models.basic_product import BasicProduct -from digikey.v3.productinformation.models.digi_reel_pricing import DigiReelPricing -from digikey.v3.productinformation.models.filters import Filters -from digikey.v3.productinformation.models.iso_search_locale import IsoSearchLocale -from digikey.v3.productinformation.models.keyword_search_request import KeywordSearchRequest -from digikey.v3.productinformation.models.keyword_search_response import KeywordSearchResponse -from digikey.v3.productinformation.models.kit_part import KitPart -from digikey.v3.productinformation.models.limited_parameter import LimitedParameter -from digikey.v3.productinformation.models.limited_taxonomy import LimitedTaxonomy -from digikey.v3.productinformation.models.manufacturer_product_details_request import ManufacturerProductDetailsRequest -from digikey.v3.productinformation.models.media_links import MediaLinks -from digikey.v3.productinformation.models.parametric_filter import ParametricFilter -from digikey.v3.productinformation.models.pid_vid import PidVid -from digikey.v3.productinformation.models.price_break import PriceBreak -from digikey.v3.productinformation.models.product import Product -from digikey.v3.productinformation.models.product_details import ProductDetails -from digikey.v3.productinformation.models.product_details_response import ProductDetailsResponse -from digikey.v3.productinformation.models.search_option import SearchOption -from digikey.v3.productinformation.models.sort_direction import SortDirection -from digikey.v3.productinformation.models.sort_option import SortOption -from digikey.v3.productinformation.models.sort_parameters import SortParameters -from digikey.v3.productinformation.models.value_pair import ValuePair diff --git a/digikey/__init__.py b/kicost_digikey_api_v3/__init__.py similarity index 54% rename from digikey/__init__.py rename to kicost_digikey_api_v3/__init__.py index 6c7e00a..b1973e2 100644 --- a/digikey/__init__.py +++ b/kicost_digikey_api_v3/__init__.py @@ -1,9 +1,8 @@ import logging -from digikey.v2.api import (search, part) -from digikey.v3.api import (keyword_search, product_details, digi_reel_pricing, suggested_parts, - manufacturer_product_details) -from digikey.v3.api import (status_salesorder_id, salesorder_history) -from digikey.v3.api import (batch_product_details) +from kicost_digikey_api_v3.v3.api import (keyword_search, product_details, digi_reel_pricing, suggested_parts, + manufacturer_product_details) +from .utils import by_manf_pn, by_digikey_pn, by_keyword, DK_API +from .exceptions import DigikeyError logger = logging.getLogger(__name__) diff --git a/digikey/oauth/__init__.py b/kicost_digikey_api_v3/certauth/__init__.py similarity index 100% rename from digikey/oauth/__init__.py rename to kicost_digikey_api_v3/certauth/__init__.py diff --git a/kicost_digikey_api_v3/certauth/certauth.py b/kicost_digikey_api_v3/certauth/certauth.py new file mode 100644 index 0000000..b3047aa --- /dev/null +++ b/kicost_digikey_api_v3/certauth/certauth.py @@ -0,0 +1,421 @@ +import logging +import os + +from io import BytesIO + +from OpenSSL import crypto +from OpenSSL.SSL import FILETYPE_PEM + +import random + +import ipaddress +import tldextract + +from argparse import ArgumentParser + +from collections import OrderedDict + +import threading + +# ================================================================= +# Valid for 3 years from now +# Max validity is 39 months: +# https://casecurity.org/2015/02/19/ssl-certificate-validity-periods-limited-to-39-months-starting-in-april/ +CERT_NOT_AFTER = 3 * 365 * 24 * 60 * 60 + +CERTS_DIR = './ca/certs/' + +CERT_NAME = 'certauth sample CA' + +DEF_HASH_FUNC = 'sha256' + +ROOT_CA = '!!root_ca' + + +# ================================================================= +class CertificateAuthority(object): + """ + Utility class for signing individual certificate + with a root cert. + + Static generate_ca_root() method for creating the root cert + + All certs saved on filesystem. Individual certs are stored + in specified certs_dir and reused if previously created. + """ + + def __init__(self, ca_name, + ca_file_cache, + cert_cache=None, + cert_not_before=0, + cert_not_after=CERT_NOT_AFTER, + overwrite=False): + + if isinstance(ca_file_cache, str): + self.ca_file_cache = RootCACache(ca_file_cache) + else: + self.ca_file_cache = ca_file_cache + + if isinstance(cert_cache, str): + self.cert_cache = FileCache(cert_cache) + elif isinstance(cert_cache, int): + self.cert_cache = LRUCache(max_size=cert_cache) + elif cert_cache is None: + self.cert_cache = LRUCache(max_size=100) + else: + self.cert_cache = cert_cache + + self.ca_name = ca_name + + self.cert_not_before = cert_not_before + self.cert_not_after = cert_not_after + + res = self.load_root_ca_cert(overwrite=overwrite) + self.ca_cert, self.ca_key = res + + def load_root_ca_cert(self, overwrite=False): + cert_str = None + + if not overwrite: + cert_str = self.ca_file_cache.get(ROOT_CA) + + # if cached, just read pem + if cert_str: + cert, key = self.read_pem(BytesIO(cert_str)) + + else: + cert, key = self.generate_ca_root(self.ca_name) + + # Write cert + key + buff = BytesIO() + self.write_pem(buff, cert, key) + cert_str = buff.getvalue() + + # store cert in cache + self.ca_file_cache[ROOT_CA] = cert_str + + return cert, key + + def is_host_ip(self, host): + try: + # if py2.7, need to decode to unicode str + if hasattr(host, 'decode'): #pragma: no cover + host = host.decode('ascii') + + ipaddress.ip_address(host) + return True + except (ValueError, UnicodeDecodeError) as e: + return False + + def get_wildcard_domain(self, host): + host_parts = host.split('.', 1) + if len(host_parts) < 2 or '.' not in host_parts[1]: + return host + + ext = tldextract.extract(host) + + # allow using parent domain if: + # 1) no suffix (unknown tld) + # 2) the parent domain contains 'domain.suffix', not just .suffix + if not ext.suffix or ext.domain + '.' + ext.suffix in host_parts[1]: + return host_parts[1] + + return host + + def load_cert(self, host, overwrite=False, + wildcard=False, + wildcard_use_parent=False, + include_cache_key=False): + + is_ip = self.is_host_ip(host) + + if is_ip: + wildcard = False + + if wildcard and wildcard_use_parent: + host = self.get_wildcard_domain(host) + + cert_str = None + + if not overwrite: + cert_str = self.cert_cache.get(host) + + # if cached, just read pem + if cert_str: + cert, key = self.read_pem(BytesIO(cert_str)) + + else: + # if not cached, generate new root or host cert + cert, key = self.generate_host_cert(host, + self.ca_cert, + self.ca_key, + wildcard, + is_ip=is_ip) + + # Write cert + key + buff = BytesIO() + self.write_pem(buff, cert, key) + cert_str = buff.getvalue() + + # store cert in cache + self.cert_cache[host] = cert_str + + if not include_cache_key: + return cert, key + + else: + cache_key = host + if hasattr(self.cert_cache, 'key_for_host'): + cache_key = self.cert_cache.key_for_host(host) + + return cert, key, cache_key + + def cert_for_host(self, host, overwrite=False, + wildcard=False): + + res = self.load_cert(host, overwrite=overwrite, + wildcard=wildcard, + wildcard_use_parent=False, + include_cache_key=True) + + return res[2] + + + + def get_wildcard_cert(self, cert_host, overwrite=False): + res = self.load_cert(cert_host, overwrite=overwrite, + wildcard=True, + wildcard_use_parent=True, + include_cache_key=True) + + return res[2] + + def get_root_PKCS12(self): + p12 = crypto.PKCS12() + p12.set_certificate(self.ca_cert) + p12.set_privatekey(self.ca_key) + return p12.export() + + def get_root_pem(self): + return self.ca_file_cache.get(ROOT_CA) + + def get_root_pem_filename(self): + return self.ca_file_cache.ca_file + + def _make_cert(self, certname): + cert = crypto.X509() + cert.set_serial_number(random.randint(0, 2 ** 64 - 1)) + cert.get_subject().CN = certname + + cert.set_version(2) + cert.gmtime_adj_notBefore(self.cert_not_before) + cert.gmtime_adj_notAfter(self.cert_not_after) + return cert + + def generate_ca_root(self, ca_name, hash_func=DEF_HASH_FUNC): + # Generate key + key = crypto.PKey() + key.generate_key(crypto.TYPE_RSA, 2048) + + # Generate cert + cert = self._make_cert(ca_name) + + cert.set_issuer(cert.get_subject()) + cert.set_pubkey(key) + cert.add_extensions([ + crypto.X509Extension(b"basicConstraints", + True, + b"CA:TRUE, pathlen:0"), + + crypto.X509Extension(b"keyUsage", + True, + b"keyCertSign, cRLSign"), + + crypto.X509Extension(b"subjectKeyIdentifier", + False, + b"hash", + subject=cert), + ]) + cert.sign(key, hash_func) + + return cert, key + + def generate_host_cert(self, host, root_cert, root_key, + wildcard=False, + hash_func=DEF_HASH_FUNC, + is_ip=False): + + host = host.encode('utf-8') + + # Generate key + key = crypto.PKey() + key.generate_key(crypto.TYPE_RSA, 2048) + + # Generate CSR + req = crypto.X509Req() + req.get_subject().CN = host + req.set_pubkey(key) + req.sign(key, hash_func) + + # Generate Cert + cert = self._make_cert(host) + + cert.set_issuer(root_cert.get_subject()) + cert.set_pubkey(req.get_pubkey()) + + primary = b'DNS:' + host + + if wildcard: + alt_hosts = primary + b', DNS:*.' + host + + elif is_ip: + alt_hosts = b'IP:' + host + b', ' + primary + + else: + alt_hosts = primary + + cert.add_extensions([ + crypto.X509Extension(b'subjectAltName', + False, + alt_hosts)]) + + cert.sign(root_key, hash_func) + return cert, key + + def write_pem(self, buff, cert, key): + buff.write(crypto.dump_privatekey(FILETYPE_PEM, key)) + buff.write(crypto.dump_certificate(FILETYPE_PEM, cert)) + + def read_pem(self, buff): + cert = crypto.load_certificate(FILETYPE_PEM, buff.read()) + buff.seek(0) + key = crypto.load_privatekey(FILETYPE_PEM, buff.read()) + return cert, key + + +# ================================================================= +class FileCache(object): + def __init__(self, certs_dir): + self._lock = threading.Lock() + self.certs_dir = certs_dir + self.modified = False + + if self.certs_dir and not os.path.exists(self.certs_dir): + os.makedirs(self.certs_dir) + + def key_for_host(self, host): + host = host.replace(':', '-') + return os.path.join(self.certs_dir, host) + '.pem' + + def __setitem__(self, host, cert_string): + filename = self.key_for_host(host) + with self._lock: + with open(filename, 'wb') as fh: + fh.write(cert_string) + self.modified = True + + def get(self, host): + filename = self.key_for_host(host) + try: + with open(filename, 'rb') as fh: + return fh.read() + except: + return b'' + + +# ================================================================= +class RootCACache(FileCache): + def __init__(self, ca_file): + self.ca_file = ca_file + ca_dir = os.path.dirname(ca_file) or '.' + super(RootCACache, self).__init__(ca_dir) + + def key_for_host(self, host=None): + return self.ca_file + + +# ================================================================= +class LRUCache(OrderedDict): + def __init__(self, max_size): + super(LRUCache, self).__init__() + self.max_size = max_size + + def __setitem__(self, host, cert_string): + super(LRUCache, self).__setitem__(host, cert_string) + if len(self) > self.max_size: + self.popitem(last=False) + + +# ================================================================= +def main(args=None): + parser = ArgumentParser(description='Certificate Authority Cert Maker Tools') + + parser.add_argument('root_ca_cert', + help='Path to existing or new root CA file') + + parser.add_argument('-c', '--certname', action='store', default=CERT_NAME, + help='Name for root certificate') + + parser.add_argument('-n', '--hostname', + help='Hostname certificate to create') + + parser.add_argument('-d', '--certs-dir', default=CERTS_DIR, + help='Directory for host certificates') + + parser.add_argument('-f', '--force', action='store_true', + help='Overwrite certificates if they already exist') + + parser.add_argument('-w', '--wildcard_cert', action='store_true', + help='add wildcard SAN to host: *., ') + + r = parser.parse_args(args=args) + + certs_dir = r.certs_dir + wildcard = r.wildcard_cert + + root_cert = r.root_ca_cert + hostname = r.hostname + + if not hostname: + overwrite = r.force + else: + overwrite = False + + cert_cache = FileCache(r.certs_dir) + ca_file_cache = RootCACache(root_cert) + + ca = CertificateAuthority(ca_name=r.certname, + ca_file_cache=ca_file_cache, + cert_cache=cert_cache, + overwrite=overwrite) + + # Just creating the root cert + if not hostname: + if ca_file_cache.modified: + print('Created new root cert: "' + root_cert + '"') + return 0 + else: + print('Root cert "' + root_cert + + '" already exists,' + ' use -f to overwrite') + return 1 + + # Sign a certificate for a given host + overwrite = r.force + ca.load_cert(hostname, overwrite=overwrite, + wildcard=wildcard, + wildcard_use_parent=False) + + if cert_cache.modified: + print('Created new cert "' + hostname + + '" signed by root cert ' + + root_cert) + return 0 + + else: + print('Cert for "' + hostname + '" already exists,' + + ' use -f to overwrite') + return 1 + + +if __name__ == "__main__": #pragma: no cover + main() diff --git a/digikey/exceptions.py b/kicost_digikey_api_v3/exceptions.py similarity index 100% rename from digikey/exceptions.py rename to kicost_digikey_api_v3/exceptions.py diff --git a/digikey/v2/__init__.py b/kicost_digikey_api_v3/oauth/__init__.py similarity index 100% rename from digikey/v2/__init__.py rename to kicost_digikey_api_v3/oauth/__init__.py diff --git a/digikey/oauth/oauth2.py b/kicost_digikey_api_v3/oauth/oauth2.py similarity index 70% rename from digikey/oauth/oauth2.py rename to kicost_digikey_api_v3/oauth/oauth2.py index 6adeaeb..320985a 100644 --- a/digikey/oauth/oauth2.py +++ b/kicost_digikey_api_v3/oauth/oauth2.py @@ -3,25 +3,30 @@ import os import ssl import typing as t -from datetime import datetime, timezone -from http.server import BaseHTTPRequestHandler, HTTPServer -from json.decoder import JSONDecodeError -from pathlib import Path -from urllib.parse import urlencode, urlparse, parse_qs +import sys +py_2 = sys.version_info < (3, 0) +if py_2: + from datetime import datetime + from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer + JSONDecodeError = ValueError # noqa: F821 + from urllib import urlencode + from urlparse import urlparse, parse_qs +else: + from datetime import datetime, timezone + from http.server import BaseHTTPRequestHandler, HTTPServer + from json.decoder import JSONDecodeError + from urllib.parse import urlencode, urlparse, parse_qs from webbrowser import open_new import requests -from certauth.certauth import CertificateAuthority -from fake_useragent import UserAgent -from digikey.exceptions import DigikeyOauthException +from kicost_digikey_api_v3.certauth.certauth import CertificateAuthority +from kicost_digikey_api_v3.exceptions import DigikeyOauthException +from kicost_digikey_api_v3.utils import USER_AGENT CA_CERT = 'digikey-api.pem' TOKEN_STORAGE = 'token_storage.json' -AUTH_URL_V2 = 'https://sso.digikey.com/as/authorization.oauth2' -TOKEN_URL_V2 = 'https://sso.digikey.com/as/token.oauth2' - AUTH_URL_V3_PROD = 'https://api.digikey.com/v1/oauth2/authorize' TOKEN_URL_V3_PROD = 'https://api.digikey.com/v1/oauth2/token' @@ -34,6 +39,17 @@ logger = logging.getLogger(__name__) +def set_logger(lg): + global logger + logger = lg + + +def utcnow(): + if py_2: + return datetime.utcnow() + return datetime.now(timezone.utc) + + class Oauth2Token: def __init__(self, token): self._token = token @@ -48,16 +64,18 @@ def refresh_token(self): @property def expires(self): + if py_2: + return datetime.utcfromtimestamp(self._token.get('expires')) return datetime.fromtimestamp(self._token.get('expires'), timezone.utc) @property def type(self): return self._token.get('token_type') - def expired(self) -> bool: - return datetime.now(timezone.utc) >= self.expires + def expired(self): + return utcnow() >= self.expires - def get_authorization(self) -> str: + def get_authorization(self): return self.type + ' ' + self.access_token def __repr__(self): @@ -102,16 +120,13 @@ class TokenHandler: Functions used to handle Digikey oAuth """ def __init__(self, - a_id: t.Optional[str] = None, - a_secret: t.Optional[str] = None, - a_token_storage_path: t.Optional[str] = None, - version: int = 2, - sandbox: bool = False): - - if version == 2: - self.auth_url = AUTH_URL_V2 - self.token_url = TOKEN_URL_V2 - elif version == 3: + a_id = None, + a_secret = None, + a_token_storage_path = None, + version = 3, + sandbox = False): + + if version == 3: if sandbox: self.auth_url = AUTH_URL_V3_SB self.token_url = TOKEN_URL_V3_SB @@ -121,7 +136,7 @@ def __init__(self, else: raise ValueError('Please specify the correct Digikey API version') - logger.debug(f'Using API V{version}') + logger.debug('Using API V{}'.format(version)) a_id = a_id or os.getenv('DIGIKEY_CLIENT_ID') a_secret = a_secret or os.getenv('DIGIKEY_CLIENT_SECRET') @@ -133,35 +148,35 @@ def __init__(self, ) a_token_storage_path = a_token_storage_path or os.getenv('DIGIKEY_STORAGE_PATH') - if not a_token_storage_path or not Path(a_token_storage_path).exists(): + if not a_token_storage_path or not os.path.isdir(a_token_storage_path): raise ValueError( 'STORAGE PATH must be set and must exist.' 'Set "DIGIKEY_STORAGE_PATH" as an environment variable, ' - 'or pass your keys directly to the client.' + 'or pass your keys directly to the client. ({})'.format(a_token_storage_path) ) self._id = a_id self._secret = a_secret - self._storage_path = Path(a_token_storage_path) - self._token_storage_path = self._storage_path.joinpath(TOKEN_STORAGE) - self._ca_cert = self._storage_path.joinpath(CA_CERT) + self._storage_path = a_token_storage_path + self._token_storage_path = os.path.join(self._storage_path, TOKEN_STORAGE) + self._ca_cert = os.path.join(self._storage_path, CA_CERT) def __generate_certificate(self): - ca = CertificateAuthority('Python digikey-api CA', str(self._ca_cert), cert_cache=str(self._storage_path)) + ca = CertificateAuthority('Python digikey-api CA', self._ca_cert, cert_cache=self._storage_path) return ca.cert_for_host('localhost') - def __build_authorization_url(self) -> str: + def __build_authorization_url(self): params = {'client_id': self._id, 'response_type': 'code', 'redirect_uri': REDIRECT_URI } url = self.auth_url + '?' + urlencode(params) - logger.debug(f'AUTH - Authenticating with endpoint {self.auth_url} using ID: {self._id[:-5]}...') - logger.debug(f'AUTH - Redirect URL: {REDIRECT_URI}') + logger.debug('AUTH - Authenticating with endpoint {} using ID: {}...'.format(self.auth_url, self._id[:-5])) + logger.debug('AUTH - Redirect URL: {}'.format(REDIRECT_URI)) return url def __exchange_for_token(self, code): - headers = {'user-agent': f'{UserAgent().firefox}', + headers = {'user-agent': USER_AGENT, 'Content-type': 'application/x-www-form-urlencoded' } post_data = {'grant_type': 'authorization_code', @@ -172,24 +187,24 @@ def __exchange_for_token(self, code): } try: - logger.debug(f'TOKEN - Exchanging {code} auth code for token at endpoint: {self.token_url}') - logger.debug(f'TOKEN - Using client id: {self._id[:-5]}...') - logger.debug(f'TOKEN - Using client secret: {self._secret[:-5]}...') + logger.debug('TOKEN - Exchanging {} auth code for token at endpoint: {}'.format(code, self.token_url)) + logger.debug('TOKEN - Using client id: {}...'.format(self._id[:-5])) + logger.debug('TOKEN - Using client secret: {}...'.format(self._secret[:-5])) r = requests.post(self.token_url, headers=headers, data=post_data) r.raise_for_status() except (requests.exceptions.RequestException, requests.exceptions.HTTPError) as e: raise DigikeyOauthException('TOKEN - Cannot request new token with auth code: {}'.format(e)) else: token_json = r.json() - logger.debug(f'TOKEN - Got access token with value: {token_json["access_token"][:-5]}...') - logger.info('TOKEN - Successfully retrieved access token.') + logger.debug('TOKEN - Got access token with value: {}...'.format(token_json["access_token"][:-5])) + # logger.info('TOKEN - Successfully retrieved access token.') # Create epoch timestamp from expires in, with 1 minute margin - token_json['expires'] = int(token_json['expires_in']) + datetime.now(timezone.utc).timestamp() - 60 + token_json['expires'] = int(token_json['expires_in']) + utcnow().timestamp() - 60 return token_json - def __refresh_token(self, refresh_token: str): - headers = {'user-agent': f'{UserAgent().firefox}', + def __refresh_token(self, refresh_token): + headers = {'user-agent': USER_AGENT, 'Content-type': 'application/x-www-form-urlencoded' } post_data = {'grant_type': 'refresh_token', @@ -207,11 +222,11 @@ def __refresh_token(self, refresh_token: str): raise DigikeyOauthException('REFRESH - Cannot request new token with refresh token: {}.'.format(error_message)) else: token_json = r.json() - logger.debug(f'REFRESH - Got access token with value: {token_json["access_token"]}') - logger.info('REFRESH - Successfully retrieved access token.') + logger.debug('REFRESH - Got access token with value: {}'.format(token_json["access_token"])) + # logger.info('REFRESH - Successfully retrieved access token.') # Create epoch timestamp from expires in, with 1 minute margin - token_json['expires'] = int(token_json['expires_in']) + datetime.now(timezone.utc).timestamp() - 60 + token_json['expires'] = int(token_json['expires_in']) + utcnow().timestamp() - 60 return token_json def save(self, json_data): @@ -219,7 +234,7 @@ def save(self, json_data): json.dump(json_data, f) logger.debug('Saved token to: {}'.format(self._token_storage_path)) - def get_access_token(self) -> Oauth2Token: + def get_access_token(self): """ Fetches the access key using an HTTP server to handle oAuth requests @@ -243,7 +258,7 @@ def get_access_token(self) -> Oauth2Token: # Try to refresh the credentials with the stores refresh token if token is not None and token.expired(): try: - logger.debug(f'REFRESH - Current token is stale, refresh using: {token.refresh_token}') + logger.debug('REFRESH - Current token is stale, refresh using: {}'.format(token.refresh_token)) token_json = self.__refresh_token(token.refresh_token) self.save(token_json) except DigikeyOauthException: @@ -258,7 +273,16 @@ def get_access_token(self) -> Oauth2Token: ('localhost', PORT), lambda request, address, server: HTTPServerHandler( request, address, server, self._id, self._secret)) - httpd.socket = ssl.wrap_socket(httpd.socket, certfile=str(Path(filename)), server_side=True) + + if sys.version_info < (3, 12): + # Old mechanism supported upto 3.11 + httpd.socket = ssl.wrap_socket(httpd.socket, certfile=filename, server_side=True) + else: + # New mechanism, needs more testing + context = ssl.SSLContext(ssl.PROTOCOL_TLS) + context.load_cert_chain(filename) + httpd.socket = context.wrap_socket(httpd.socket, server_side=True) + httpd.stop = 0 # This function will block until it receives a request @@ -268,7 +292,7 @@ def get_access_token(self) -> Oauth2Token: # Remove generated certificate try: - os.remove(Path(filename)) + os.remove(filename) os.remove(self._ca_cert) except OSError as e: logger.error('Cannot remove temporary certificates: {}'.format(e)) diff --git a/kicost_digikey_api_v3/utils.py b/kicost_digikey_api_v3/utils.py new file mode 100644 index 0000000..5ac09e0 --- /dev/null +++ b/kicost_digikey_api_v3/utils.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# GPL license +# +# Copyright (C) 2021 by Salvador E. Tropea / Instituto Nacional de Tecnologia Industrial +# +import os +import re +import logging + +import kicost_digikey_api_v3 +from kicost_digikey_api_v3.v3.productinformation import ManufacturerProductDetailsRequest, KeywordSearchRequest +from .exceptions import DigikeyError + +USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; rv:22.0) Gecko/20130405 Firefox/22.0" +includes = ["DigiKeyPartNumber","ProductUrl","QuantityAvailable","MinimumOrderQuantity","PrimaryDatasheet","ProductStatus", + "SearchLocaleUsed","StandardPricing","Parameters","RoHsStatus","AdditionalValueFee","ProductDescription"] +includes = ','.join(includes) + + +class PartSortWrapper(object): + """ This class is used to sort the results giving more priority to entries with less MOQ, less price, + more availability, etc. """ + def __init__(self, data): + self.data = data + self.min_price = data.standard_pricing[0].unit_price if len(data.standard_pricing) > 0 else -1 + if not hasattr(data, 'additional_value_fee'): + data.additional_value_fee = 0 + + def __eq__(self, other): + return (self.data.minimum_order_quantity == other.data.minimum_order_quantity and + self.data.quantity_available == other.data.quantity_available and + self.data.additional_value_fee == other.data.additional_value_fee and + self.min_price == other.min_price and + self.data.product_status == other.data.product_status) + + def __lt__(self, other): + if self.data.quantity_available and not other.data.quantity_available: + return True + if not self.data.minimum_order_quantity: + return False + if self.data.minimum_order_quantity < other.data.minimum_order_quantity: + return True + if self.min_price == -1: + return False + dif = self.data.additional_value_fee + self.min_price - (other.data.additional_value_fee + other.min_price) + if dif < 0: + return True + if dif == 0 and self.data.product_status == 'Active' and other.data.product_status != 'Active': + return True + return False + + +class DK_API(object): + ''' Configuration class, KiCost must extend it and provide an object with the desired options ''' + # Provided by KiCost + id = secret = None + sandbox = False + api_ops = {} + exclude_market_place_products = False + # Configured here + cache = None + logger = logging.getLogger(__name__) + extra_ops = {} # Extra options for the API + + @staticmethod + def _create_cache_name_suffix(): + suf = '_' + DK_API.extra_ops.get('x_digikey_locale_site', 'US') + suf += '_' + DK_API.extra_ops.get('x_digikey_locale_language', 'en') + suf += '_' + DK_API.extra_ops.get('x_digikey_locale_currency', 'USD') + suf += '_' + DK_API.extra_ops.get('x_digikey_locale_ship_to_country', 'US') + return suf + + @staticmethod + def configure(cache, a_logger=None): + ''' Configures the plug-in ''' + if a_logger: + DK_API.logger = a_logger + kicost_digikey_api_v3.v3.api.set_logger(a_logger) + kicost_digikey_api_v3.oauth.oauth2.set_logger(a_logger) + # Ensure we have a place to store the token + DK_API.cache = cache + cache_path = cache.path + if not os.path.isdir(cache_path): + raise DigikeyError("No directory to store tokens, please create `{}`".format(cache_path)) + os.environ['DIGIKEY_STORAGE_PATH'] = cache_path + # Ensure we have the credentials + if not DK_API.id or not DK_API.secret: + raise DigikeyError("No Digi-Key credentials defined") + os.environ['DIGIKEY_CLIENT_ID'] = DK_API.id + os.environ['DIGIKEY_CLIENT_SECRET'] = DK_API.secret + # Default to no sandbox + os.environ['DIGIKEY_CLIENT_SANDBOX'] = str(DK_API.sandbox) + # API options + DK_API.extra_ops = {'x_digikey_'+op: val for op, val in DK_API.api_ops.items()} + # Cache suffix (uses extra_ops) + cache.suffix = DK_API._create_cache_name_suffix() + # Debug information about what we got + DK_API.logger.debug('Digi-Key API plug-in options:') + DK_API.logger.debug(str([k + '=' + v for k, v in os.environ.items() if k.startswith('DIGIKEY_')])) + DK_API.logger.debug(str(DK_API.extra_ops)) + + +class by_manf_pn(object): + def __init__(self, manf_pn): + self.manf_pn = manf_pn + + def search(self): + search_request = ManufacturerProductDetailsRequest(manufacturer_product=self.manf_pn, record_count=10) + self.api_limit = {} + results, loaded = DK_API.cache.load_results('mpn', self.manf_pn) + if not loaded: + results = kicost_digikey_api_v3.manufacturer_product_details(body=search_request, api_limits=self.api_limit, **DK_API.extra_ops) + if results is not None: + DK_API.cache.save_results('mpn', self.manf_pn, results) + # print('************************') + # print(results) + # print('************************') + if results is None: + return None + if not isinstance(results, list): + results = results.product_details + if isinstance(results, list): + if len(results) == 1: + result = results[0] + elif len(results) == 0: + result = None + else: + tmp_results = [PartSortWrapper(r) for r in results] + tmp_results.sort() + result = tmp_results[0].data + # print('* ' + self.manf_pn + ':') + # for rs in tmp_results: + # r = rs.data + # print('- {} {} {} {} {}'.format(r.digi_key_part_number, r.minimum_order_quantity, r.manufacturer.value, rs.min_price, r.additional_value_fee)) + # print(result) + return result + + +class by_digikey_pn(object): + def __init__(self, dk_pn): + self.dk_pn = dk_pn + + def search(self): + self.api_limit = {} + result, loaded = DK_API.cache.load_results('dpn', self.dk_pn) + if not loaded: + result = kicost_digikey_api_v3.product_details(self.dk_pn, api_limits=self.api_limit, includes=includes, **DK_API.extra_ops) + DK_API.cache.save_results('dpn', self.dk_pn, result) + return result + + +class by_keyword(object): + def __init__(self, keyword): + self.keyword = keyword + + def search(self): + search_request = KeywordSearchRequest(keywords=self.keyword, record_count=10, + exclude_market_place_products=DK_API.exclude_market_place_products) + self.api_limit = {} + result, loaded = DK_API.cache.load_results('key', self.keyword) + if not loaded: + result = kicost_digikey_api_v3.keyword_search(body=search_request, api_limits=self.api_limit, **DK_API.extra_ops) #, includes=includes) + DK_API.cache.save_results('key', self.keyword, result) + results = result.products + # print(results) + if isinstance(results, list): + if len(results) == 1: + result = results[0] + elif len(results) == 0: + result = None + else: + tmp_results = [PartSortWrapper(r) for r in results] + tmp_results.sort() + result = tmp_results[0].data + # print('* ' + self.keyword + ':') + # for rs in tmp_results: + # r = rs.data + # print('- {} {} {} {} {}'.format(r.digi_key_part_number, r.minimum_order_quantity, r.manufacturer.value, rs.min_price, r.additional_value_fee)) + if result is not None: + # The keyword search returns incomplete data, do a query using the Digi-Key code + o = by_digikey_pn(result.digi_key_part_number) + result = o.search() + # print(result) + return result diff --git a/digikey/v3/__init__.py b/kicost_digikey_api_v3/v3/__init__.py similarity index 100% rename from digikey/v3/__init__.py rename to kicost_digikey_api_v3/v3/__init__.py diff --git a/digikey/v3/api.py b/kicost_digikey_api_v3/v3/api.py similarity index 53% rename from digikey/v3/api.py rename to kicost_digikey_api_v3/v3/api.py index 99d7de0..82b9836 100644 --- a/digikey/v3/api.py +++ b/kicost_digikey_api_v3/v3/api.py @@ -1,13 +1,11 @@ import os import logging from distutils.util import strtobool -import digikey.oauth.oauth2 -from digikey.exceptions import DigikeyError -from digikey.v3.productinformation import (KeywordSearchRequest, KeywordSearchResponse, ProductDetails, DigiReelPricing, - ManufacturerProductDetailsRequest) -from digikey.v3.productinformation.rest import ApiException -from digikey.v3.ordersupport import (OrderStatusResponse, SalesOrderHistoryItem) -from digikey.v3.batchproductdetails import (BatchProductDetailsRequest, BatchProductDetailsResponse) +import kicost_digikey_api_v3.oauth.oauth2 +from kicost_digikey_api_v3.exceptions import DigikeyError +from kicost_digikey_api_v3.v3.productinformation import (KeywordSearchRequest, KeywordSearchResponse, ProductDetails, DigiReelPricing, + ManufacturerProductDetailsRequest) +from kicost_digikey_api_v3.v3.productinformation.rest import ApiException logger = logging.getLogger(__name__) @@ -17,15 +15,11 @@ def __init__(self, wrapped_function, module): self.sandbox = False apinames = { - digikey.v3.productinformation: 'Search', - digikey.v3.ordersupport: 'OrderDetails', - digikey.v3.batchproductdetails: 'BatchSearch' + kicost_digikey_api_v3.v3.productinformation: 'Search' } apiclasses = { - digikey.v3.productinformation: digikey.v3.productinformation.PartSearchApi, - digikey.v3.ordersupport: digikey.v3.ordersupport.OrderDetailsApi, - digikey.v3.batchproductdetails: digikey.v3.batchproductdetails.BatchSearchApi + kicost_digikey_api_v3.v3.productinformation: kicost_digikey_api_v3.v3.productinformation.PartSearchApi } apiname = apinames[module] @@ -34,6 +28,7 @@ def __init__(self, wrapped_function, module): # Configure API key authorization: apiKeySecurity configuration = module.Configuration() configuration.api_key['X-DIGIKEY-Client-Id'] = os.getenv('DIGIKEY_CLIENT_ID') + configuration.logger["package_logger"] = logger # Return quietly if no clientid has been set to prevent errors when importing the module if os.getenv('DIGIKEY_CLIENT_ID') is None or os.getenv('DIGIKEY_CLIENT_SECRET') is None: @@ -52,7 +47,7 @@ def __init__(self, wrapped_function, module): # configuration.api_key_prefix['X-DIGIKEY-Client-Id'] = 'Bearer' # Configure OAuth2 access token for authorization: oauth2AccessCodeSecurity - self._digikeyApiToken = digikey.oauth.oauth2.TokenHandler(version=3, sandbox=self.sandbox).get_access_token() + self._digikeyApiToken = kicost_digikey_api_v3.oauth.oauth2.TokenHandler(version=3, sandbox=self.sandbox).get_access_token() configuration.access_token = self._digikeyApiToken.access_token # create an instance of the API class @@ -76,7 +71,7 @@ def _remaining_requests(header, api_limits): logger.debug('Requests remaining: [{}/{}]'.format(rate_limit_rem, rate_limit)) except (KeyError, ValueError) as e: - logger.debug(f'No api limits returned -> {e.__class__.__name__}: {e}') + logger.debug('No api limits returned -> {}: {}'.format(e.__class__.__name__, e)) if api_limits is not None and type(api_limits) == dict: api_limits['api_requests_limit'] = None api_limits['api_requests_remaining'] = None @@ -87,85 +82,61 @@ def call_api_function(self, *args, **kwargs): api_limits = kwargs.pop('api_limits', None) func = getattr(self._api_instance, self.wrapped_function) - logger.debug(f'CALL wrapped -> {func.__qualname__}') - api_response = func(*args, self.authorization, self.x_digikey_client_id, **kwargs) + logger.debug('CALL wrapped -> {}'.format(func.__qualname__)) + api_response = func(*(args + (self.authorization, self.x_digikey_client_id)), **kwargs) self._remaining_requests(api_response[2], api_limits) return api_response[0] except ApiException as e: - logger.error(f'Exception when calling {self.wrapped_function}: {e}') + if e.reason != 'Not Found' or logger.getEffectiveLevel() <= logging.DEBUG: + logger.error('Exception when calling {}: {}'.format(self.wrapped_function, e)) -def keyword_search(*args, **kwargs) -> KeywordSearchResponse: - client = DigikeyApiWrapper('keyword_search_with_http_info', digikey.v3.productinformation) +def keyword_search(*args, **kwargs): + client = DigikeyApiWrapper('keyword_search_with_http_info', kicost_digikey_api_v3.v3.productinformation) if 'body' in kwargs and type(kwargs['body']) == KeywordSearchRequest: - logger.info(f'Search for: {kwargs["body"].keywords}') + logger.debug('Search for: {}'.format(kwargs["body"].keywords)) logger.debug('CALL -> keyword_search') return client.call_api_function(*args, **kwargs) else: raise DigikeyError('Please provide a valid KeywordSearchRequest argument') -def product_details(*args, **kwargs) -> ProductDetails: - client = DigikeyApiWrapper('product_details_with_http_info', digikey.v3.productinformation) +def product_details(*args, **kwargs): + client = DigikeyApiWrapper('product_details_with_http_info', kicost_digikey_api_v3.v3.productinformation) if len(args): - logger.info(f'Get product details for: {args[0]}') + logger.debug('Get product details for: {}'.format(args[0])) return client.call_api_function(*args, **kwargs) -def digi_reel_pricing(*args, **kwargs) -> DigiReelPricing: - client = DigikeyApiWrapper('digi_reel_pricing_with_http_info', digikey.v3.productinformation) +def digi_reel_pricing(*args, **kwargs): + client = DigikeyApiWrapper('digi_reel_pricing_with_http_info', kicost_digikey_api_v3.v3.productinformation) if len(args): - logger.info(f'Calculate the DigiReel pricing for {args[0]} with quantity {args[1]}') + logger.debug('Calculate the DigiReel pricing for {} with quantity {}'.format(args[0], args[1])) return client.call_api_function(*args, **kwargs) -def suggested_parts(*args, **kwargs) -> ProductDetails: - client = DigikeyApiWrapper('suggested_parts_with_http_info', digikey.v3.productinformation) +def suggested_parts(*args, **kwargs): + client = DigikeyApiWrapper('suggested_parts_with_http_info', kicost_digikey_api_v3.v3.productinformation) if len(args): - logger.info(f'Retrieve detailed product information and two suggested products for: {args[0]}') + logger.debug('Retrieve detailed product information and two suggested products for: {}'.format(args[0])) return client.call_api_function(*args, **kwargs) -def manufacturer_product_details(*args, **kwargs) -> KeywordSearchResponse: - client = DigikeyApiWrapper('manufacturer_product_details_with_http_info', digikey.v3.productinformation) +def manufacturer_product_details(*args, **kwargs): + client = DigikeyApiWrapper('manufacturer_product_details_with_http_info', kicost_digikey_api_v3.v3.productinformation) if 'body' in kwargs and type(kwargs['body']) == ManufacturerProductDetailsRequest: - logger.info(f'Search for: {kwargs["body"].manufacturer_product}') + logger.debug('Search for: {}'.format(kwargs["body"].manufacturer_product)) return client.call_api_function(*args, **kwargs) else: raise DigikeyError('Please provide a valid ManufacturerProductDetailsRequest argument') -def status_salesorder_id(*args, **kwargs) -> OrderStatusResponse: - client = DigikeyApiWrapper('status_salesorder_id_get_with_http_info', digikey.v3.ordersupport) - - if len(args): - logger.info(f'Get order details for: {args[0]}') - return client.call_api_function(*args, **kwargs) - - -def salesorder_history(*args, **kwargs) -> [SalesOrderHistoryItem]: - client = DigikeyApiWrapper('history_get_with_http_info', digikey.v3.ordersupport) - - if 'start_date' in kwargs and type(kwargs['start_date']) == str \ - and 'end_date' in kwargs and type(kwargs['end_date']) == str: - logger.info(f'Searching for orders in date range ' + kwargs['start_date'] + ' to ' + kwargs['end_date']) - return client.call_api_function(*args, **kwargs) - else: - raise DigikeyError('Please provide valid start_date and end_date strings') - - -def batch_product_details(*args, **kwargs) -> BatchProductDetailsResponse: - client = DigikeyApiWrapper('batch_product_details_with_http_info', digikey.v3.batchproductdetails) - - if 'body' in kwargs and type(kwargs['body']) == BatchProductDetailsRequest: - logger.info(f'Batch product search: {kwargs["body"].products}') - logger.debug('CALL -> batch_product_details') - return client.call_api_function(*args, **kwargs) - else: - raise DigikeyError('Please provide a valid BatchProductDetailsRequest argument') +def set_logger(lg): + global logger + logger = lg diff --git a/kicost_digikey_api_v3/v3/productinformation/__init__.py b/kicost_digikey_api_v3/v3/productinformation/__init__.py new file mode 100644 index 0000000..d72dff3 --- /dev/null +++ b/kicost_digikey_api_v3/v3/productinformation/__init__.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +# flake8: noqa + +""" + PartSearch Api + + Search for products and retrieve details and pricing. # noqa: E501 + + OpenAPI spec version: v3 + + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from __future__ import absolute_import + +# import apis into sdk package +from kicost_digikey_api_v3.v3.productinformation.api.part_search_api import PartSearchApi + +# import ApiClient +from kicost_digikey_api_v3.v3.productinformation.api_client import ApiClient +from kicost_digikey_api_v3.v3.productinformation.configuration import Configuration +# import models into sdk package +from kicost_digikey_api_v3.v3.productinformation.models.api_error_response import ApiErrorResponse +from kicost_digikey_api_v3.v3.productinformation.models.api_validation_error import ApiValidationError +from kicost_digikey_api_v3.v3.productinformation.models.associated_product import AssociatedProduct +from kicost_digikey_api_v3.v3.productinformation.models.basic_product import BasicProduct +from kicost_digikey_api_v3.v3.productinformation.models.digi_reel_pricing import DigiReelPricing +from kicost_digikey_api_v3.v3.productinformation.models.filters import Filters +from kicost_digikey_api_v3.v3.productinformation.models.iso_search_locale import IsoSearchLocale +from kicost_digikey_api_v3.v3.productinformation.models.keyword_search_request import KeywordSearchRequest +from kicost_digikey_api_v3.v3.productinformation.models.keyword_search_response import KeywordSearchResponse +from kicost_digikey_api_v3.v3.productinformation.models.kit_part import KitPart +from kicost_digikey_api_v3.v3.productinformation.models.limited_parameter import LimitedParameter +from kicost_digikey_api_v3.v3.productinformation.models.limited_taxonomy import LimitedTaxonomy +from kicost_digikey_api_v3.v3.productinformation.models.manufacturer_product_details_request import ManufacturerProductDetailsRequest +from kicost_digikey_api_v3.v3.productinformation.models.media_links import MediaLinks +from kicost_digikey_api_v3.v3.productinformation.models.parametric_filter import ParametricFilter +from kicost_digikey_api_v3.v3.productinformation.models.pid_vid import PidVid +from kicost_digikey_api_v3.v3.productinformation.models.price_break import PriceBreak +from kicost_digikey_api_v3.v3.productinformation.models.product import Product +from kicost_digikey_api_v3.v3.productinformation.models.product_details import ProductDetails +from kicost_digikey_api_v3.v3.productinformation.models.product_details_response import ProductDetailsResponse +from kicost_digikey_api_v3.v3.productinformation.models.search_option import SearchOption +from kicost_digikey_api_v3.v3.productinformation.models.sort_direction import SortDirection +from kicost_digikey_api_v3.v3.productinformation.models.sort_option import SortOption +from kicost_digikey_api_v3.v3.productinformation.models.sort_parameters import SortParameters +from kicost_digikey_api_v3.v3.productinformation.models.value_pair import ValuePair diff --git a/kicost_digikey_api_v3/v3/productinformation/api/__init__.py b/kicost_digikey_api_v3/v3/productinformation/api/__init__.py new file mode 100644 index 0000000..f49b32f --- /dev/null +++ b/kicost_digikey_api_v3/v3/productinformation/api/__init__.py @@ -0,0 +1,6 @@ +from __future__ import absolute_import + +# flake8: noqa + +# import apis into api package +from kicost_digikey_api_v3.v3.productinformation.api.part_search_api import PartSearchApi diff --git a/digikey/v3/productinformation/api/part_search_api.py b/kicost_digikey_api_v3/v3/productinformation/api/part_search_api.py similarity index 99% rename from digikey/v3/productinformation/api/part_search_api.py rename to kicost_digikey_api_v3/v3/productinformation/api/part_search_api.py index b64bf6e..fcda34e 100644 --- a/digikey/v3/productinformation/api/part_search_api.py +++ b/kicost_digikey_api_v3/v3/productinformation/api/part_search_api.py @@ -18,7 +18,7 @@ # python 2 and python 3 compatibility library import six -from digikey.v3.productinformation.api_client import ApiClient +from kicost_digikey_api_v3.v3.productinformation.api_client import ApiClient class PartSearchApi(object): diff --git a/digikey/v3/productinformation/api_client.py b/kicost_digikey_api_v3/v3/productinformation/api_client.py similarity index 98% rename from digikey/v3/productinformation/api_client.py rename to kicost_digikey_api_v3/v3/productinformation/api_client.py index 80f296e..f0bbdcc 100644 --- a/digikey/v3/productinformation/api_client.py +++ b/kicost_digikey_api_v3/v3/productinformation/api_client.py @@ -23,9 +23,9 @@ import six from six.moves.urllib.parse import quote -from digikey.v3.productinformation.configuration import Configuration -import digikey.v3.productinformation.models -from digikey.v3.productinformation import rest +from kicost_digikey_api_v3.v3.productinformation.configuration import Configuration +import kicost_digikey_api_v3.v3.productinformation.models +from kicost_digikey_api_v3.v3.productinformation import rest class ApiClient(object): @@ -266,7 +266,7 @@ def __deserialize(self, data, klass): if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = getattr(digikey.v3.productinformation.models, klass) + klass = getattr(kicost_digikey_api_v3.v3.productinformation.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) diff --git a/digikey/v3/productinformation/configuration.py b/kicost_digikey_api_v3/v3/productinformation/configuration.py similarity index 98% rename from digikey/v3/productinformation/configuration.py rename to kicost_digikey_api_v3/v3/productinformation/configuration.py index 2428a87..e4fccaf 100644 --- a/digikey/v3/productinformation/configuration.py +++ b/kicost_digikey_api_v3/v3/productinformation/configuration.py @@ -59,7 +59,7 @@ def __init__(self): # Logging Settings self.logger = {} - self.logger["package_logger"] = logging.getLogger("digikey.v3.productinformation") + self.logger["package_logger"] = logging.getLogger("kicost_digikey_api_v3.v3.productinformation") self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Log format self.logger_format = '%(asctime)s %(levelname)s %(message)s' diff --git a/kicost_digikey_api_v3/v3/productinformation/models/__init__.py b/kicost_digikey_api_v3/v3/productinformation/models/__init__.py new file mode 100644 index 0000000..230887c --- /dev/null +++ b/kicost_digikey_api_v3/v3/productinformation/models/__init__.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +# flake8: noqa +""" + PartSearch Api + + Search for products and retrieve details and pricing. # noqa: E501 + + OpenAPI spec version: v3 + + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from __future__ import absolute_import + +# import models into model package +from kicost_digikey_api_v3.v3.productinformation.models.api_error_response import ApiErrorResponse +from kicost_digikey_api_v3.v3.productinformation.models.api_validation_error import ApiValidationError +from kicost_digikey_api_v3.v3.productinformation.models.associated_product import AssociatedProduct +from kicost_digikey_api_v3.v3.productinformation.models.basic_product import BasicProduct +from kicost_digikey_api_v3.v3.productinformation.models.digi_reel_pricing import DigiReelPricing +from kicost_digikey_api_v3.v3.productinformation.models.filters import Filters +from kicost_digikey_api_v3.v3.productinformation.models.iso_search_locale import IsoSearchLocale +from kicost_digikey_api_v3.v3.productinformation.models.keyword_search_request import KeywordSearchRequest +from kicost_digikey_api_v3.v3.productinformation.models.keyword_search_response import KeywordSearchResponse +from kicost_digikey_api_v3.v3.productinformation.models.kit_part import KitPart +from kicost_digikey_api_v3.v3.productinformation.models.limited_parameter import LimitedParameter +from kicost_digikey_api_v3.v3.productinformation.models.limited_taxonomy import LimitedTaxonomy +from kicost_digikey_api_v3.v3.productinformation.models.manufacturer_product_details_request import ManufacturerProductDetailsRequest +from kicost_digikey_api_v3.v3.productinformation.models.media_links import MediaLinks +from kicost_digikey_api_v3.v3.productinformation.models.parametric_filter import ParametricFilter +from kicost_digikey_api_v3.v3.productinformation.models.pid_vid import PidVid +from kicost_digikey_api_v3.v3.productinformation.models.price_break import PriceBreak +from kicost_digikey_api_v3.v3.productinformation.models.product import Product +from kicost_digikey_api_v3.v3.productinformation.models.product_details import ProductDetails +from kicost_digikey_api_v3.v3.productinformation.models.product_details_response import ProductDetailsResponse +from kicost_digikey_api_v3.v3.productinformation.models.search_option import SearchOption +from kicost_digikey_api_v3.v3.productinformation.models.sort_direction import SortDirection +from kicost_digikey_api_v3.v3.productinformation.models.sort_option import SortOption +from kicost_digikey_api_v3.v3.productinformation.models.sort_parameters import SortParameters +from kicost_digikey_api_v3.v3.productinformation.models.value_pair import ValuePair diff --git a/digikey/v3/productinformation/models/api_error_response.py b/kicost_digikey_api_v3/v3/productinformation/models/api_error_response.py similarity index 100% rename from digikey/v3/productinformation/models/api_error_response.py rename to kicost_digikey_api_v3/v3/productinformation/models/api_error_response.py diff --git a/digikey/v3/productinformation/models/api_validation_error.py b/kicost_digikey_api_v3/v3/productinformation/models/api_validation_error.py similarity index 100% rename from digikey/v3/productinformation/models/api_validation_error.py rename to kicost_digikey_api_v3/v3/productinformation/models/api_validation_error.py diff --git a/digikey/v3/productinformation/models/associated_product.py b/kicost_digikey_api_v3/v3/productinformation/models/associated_product.py similarity index 100% rename from digikey/v3/productinformation/models/associated_product.py rename to kicost_digikey_api_v3/v3/productinformation/models/associated_product.py diff --git a/digikey/v3/productinformation/models/basic_product.py b/kicost_digikey_api_v3/v3/productinformation/models/basic_product.py similarity index 100% rename from digikey/v3/productinformation/models/basic_product.py rename to kicost_digikey_api_v3/v3/productinformation/models/basic_product.py diff --git a/digikey/v3/productinformation/models/digi_reel_pricing.py b/kicost_digikey_api_v3/v3/productinformation/models/digi_reel_pricing.py similarity index 100% rename from digikey/v3/productinformation/models/digi_reel_pricing.py rename to kicost_digikey_api_v3/v3/productinformation/models/digi_reel_pricing.py diff --git a/digikey/v3/productinformation/models/filters.py b/kicost_digikey_api_v3/v3/productinformation/models/filters.py similarity index 100% rename from digikey/v3/productinformation/models/filters.py rename to kicost_digikey_api_v3/v3/productinformation/models/filters.py diff --git a/digikey/v3/productinformation/models/iso_search_locale.py b/kicost_digikey_api_v3/v3/productinformation/models/iso_search_locale.py similarity index 100% rename from digikey/v3/productinformation/models/iso_search_locale.py rename to kicost_digikey_api_v3/v3/productinformation/models/iso_search_locale.py diff --git a/digikey/v3/productinformation/models/keyword_search_request.py b/kicost_digikey_api_v3/v3/productinformation/models/keyword_search_request.py similarity index 100% rename from digikey/v3/productinformation/models/keyword_search_request.py rename to kicost_digikey_api_v3/v3/productinformation/models/keyword_search_request.py diff --git a/digikey/v3/productinformation/models/keyword_search_response.py b/kicost_digikey_api_v3/v3/productinformation/models/keyword_search_response.py similarity index 100% rename from digikey/v3/productinformation/models/keyword_search_response.py rename to kicost_digikey_api_v3/v3/productinformation/models/keyword_search_response.py diff --git a/digikey/v3/productinformation/models/kit_part.py b/kicost_digikey_api_v3/v3/productinformation/models/kit_part.py similarity index 100% rename from digikey/v3/productinformation/models/kit_part.py rename to kicost_digikey_api_v3/v3/productinformation/models/kit_part.py diff --git a/digikey/v3/productinformation/models/limited_parameter.py b/kicost_digikey_api_v3/v3/productinformation/models/limited_parameter.py similarity index 100% rename from digikey/v3/productinformation/models/limited_parameter.py rename to kicost_digikey_api_v3/v3/productinformation/models/limited_parameter.py diff --git a/digikey/v3/productinformation/models/limited_taxonomy.py b/kicost_digikey_api_v3/v3/productinformation/models/limited_taxonomy.py similarity index 100% rename from digikey/v3/productinformation/models/limited_taxonomy.py rename to kicost_digikey_api_v3/v3/productinformation/models/limited_taxonomy.py diff --git a/digikey/v3/productinformation/models/manufacturer_product_details_request.py b/kicost_digikey_api_v3/v3/productinformation/models/manufacturer_product_details_request.py similarity index 100% rename from digikey/v3/productinformation/models/manufacturer_product_details_request.py rename to kicost_digikey_api_v3/v3/productinformation/models/manufacturer_product_details_request.py diff --git a/digikey/v3/productinformation/models/media_links.py b/kicost_digikey_api_v3/v3/productinformation/models/media_links.py similarity index 100% rename from digikey/v3/productinformation/models/media_links.py rename to kicost_digikey_api_v3/v3/productinformation/models/media_links.py diff --git a/digikey/v3/productinformation/models/parametric_filter.py b/kicost_digikey_api_v3/v3/productinformation/models/parametric_filter.py similarity index 100% rename from digikey/v3/productinformation/models/parametric_filter.py rename to kicost_digikey_api_v3/v3/productinformation/models/parametric_filter.py diff --git a/digikey/v3/productinformation/models/pid_vid.py b/kicost_digikey_api_v3/v3/productinformation/models/pid_vid.py similarity index 100% rename from digikey/v3/productinformation/models/pid_vid.py rename to kicost_digikey_api_v3/v3/productinformation/models/pid_vid.py diff --git a/digikey/v3/productinformation/models/price_break.py b/kicost_digikey_api_v3/v3/productinformation/models/price_break.py similarity index 100% rename from digikey/v3/productinformation/models/price_break.py rename to kicost_digikey_api_v3/v3/productinformation/models/price_break.py diff --git a/digikey/v3/productinformation/models/product.py b/kicost_digikey_api_v3/v3/productinformation/models/product.py similarity index 100% rename from digikey/v3/productinformation/models/product.py rename to kicost_digikey_api_v3/v3/productinformation/models/product.py diff --git a/digikey/v3/productinformation/models/product_details.py b/kicost_digikey_api_v3/v3/productinformation/models/product_details.py similarity index 100% rename from digikey/v3/productinformation/models/product_details.py rename to kicost_digikey_api_v3/v3/productinformation/models/product_details.py diff --git a/digikey/v3/productinformation/models/product_details_response.py b/kicost_digikey_api_v3/v3/productinformation/models/product_details_response.py similarity index 100% rename from digikey/v3/productinformation/models/product_details_response.py rename to kicost_digikey_api_v3/v3/productinformation/models/product_details_response.py diff --git a/digikey/v3/productinformation/models/result_code.py b/kicost_digikey_api_v3/v3/productinformation/models/result_code.py similarity index 100% rename from digikey/v3/productinformation/models/result_code.py rename to kicost_digikey_api_v3/v3/productinformation/models/result_code.py diff --git a/digikey/v3/productinformation/models/search_option.py b/kicost_digikey_api_v3/v3/productinformation/models/search_option.py similarity index 100% rename from digikey/v3/productinformation/models/search_option.py rename to kicost_digikey_api_v3/v3/productinformation/models/search_option.py diff --git a/digikey/v3/productinformation/models/sort_direction.py b/kicost_digikey_api_v3/v3/productinformation/models/sort_direction.py similarity index 100% rename from digikey/v3/productinformation/models/sort_direction.py rename to kicost_digikey_api_v3/v3/productinformation/models/sort_direction.py diff --git a/digikey/v3/productinformation/models/sort_option.py b/kicost_digikey_api_v3/v3/productinformation/models/sort_option.py similarity index 100% rename from digikey/v3/productinformation/models/sort_option.py rename to kicost_digikey_api_v3/v3/productinformation/models/sort_option.py diff --git a/digikey/v3/productinformation/models/sort_parameters.py b/kicost_digikey_api_v3/v3/productinformation/models/sort_parameters.py similarity index 100% rename from digikey/v3/productinformation/models/sort_parameters.py rename to kicost_digikey_api_v3/v3/productinformation/models/sort_parameters.py diff --git a/digikey/v3/productinformation/models/value_pair.py b/kicost_digikey_api_v3/v3/productinformation/models/value_pair.py similarity index 100% rename from digikey/v3/productinformation/models/value_pair.py rename to kicost_digikey_api_v3/v3/productinformation/models/value_pair.py diff --git a/digikey/v3/productinformation/rest.py b/kicost_digikey_api_v3/v3/productinformation/rest.py similarity index 100% rename from digikey/v3/productinformation/rest.py rename to kicost_digikey_api_v3/v3/productinformation/rest.py diff --git a/requirements-dev.txt b/requirements-dev.txt deleted file mode 100644 index 26d2203..0000000 --- a/requirements-dev.txt +++ /dev/null @@ -1,4 +0,0 @@ -bump2version==1.0.0 -wheel -twine -gitpython \ No newline at end of file diff --git a/requirements-test.txt b/requirements-test.txt deleted file mode 100644 index 99b4c0d..0000000 --- a/requirements-test.txt +++ /dev/null @@ -1,7 +0,0 @@ -coverage==4.5.4 -flake8==3.7.8 -mock==3.0.5 -mypy==0.720 -pytest==5.1.2 -pytest-cov==2.7.1 -responses==0.10.6 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 9d4c208..1feb512 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,11 +1,9 @@ -inflection -certauth -fake-useragent -requests -retrying -schematics -urllib3 -responses +inflection>=0.3.1 +requests>=2.21 +urllib3>=1.24 six certifi -setuptools \ No newline at end of file +setuptools +pyopenssl +tldextract +python-dateutil diff --git a/setup.py b/setup.py index 69f41a9..10e7563 100644 --- a/setup.py +++ b/setup.py @@ -1,16 +1,18 @@ +#!/usr/bin/python3 +import re import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( - name="digikey-api", - version="0.4.0", - author="Peter Oostewechel", - author_email="peter_oostewechel@hotmail.com", + name="kicost_digikey_api_v3", + version="0.1.3", + author="Salvador E. Tropea", + author_email="stropea@inti.gob.ar", license="GPL v3", - url="https://github.com/peeter123/digikey-api", - description="Python client for Digikey API", + url="https://github.com/set-soft/kicost-digikey-api-v3", + description="KiCost plugin for the Digikey PartSearch API", long_description=long_description, long_description_content_type="text/markdown", packages=setuptools.find_packages(exclude=['contrib', 'docs', 'tests']), @@ -20,17 +22,19 @@ "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.6", "Topic :: Software Development", ], install_requires=[ - 'requests>=2.22.0', - 'retrying>=1.3.3', - 'fake-useragent>=0.1.11', - 'schematics>=2.1.0', 'inflection>=0.3.1', - 'certauth>=1.3.0', - 'urllib3>=1.25.3' - ], + 'requests>=2.21', + 'urllib3>=1.24', + 'six', + 'certifi', + 'setuptools', + 'pyopenssl', + 'tldextract', + 'python-dateutil'], tests_requires=['pytest>=5.1.2'], ) \ No newline at end of file diff --git a/test_production.py b/test_production.py new file mode 100644 index 0000000..66b04cc --- /dev/null +++ b/test_production.py @@ -0,0 +1,99 @@ +from kicost_digikey_api_v3 import by_digikey_pn, by_keyword, by_manf_pn +from tools.test_config import configure + +# Configuration file +cfg_file = None +# Default is ~/.config/kicost_digikey_api_v3/config.txt +# Must contain: +# DIGIKEY_CLIENT_ID = Digi-Key_registered_production_app_Client_ID +# DIGIKEY_CLIENT_SECRET = Digi-Key_registered_production_app_Client_Secret +# They can be defined in the OS environment. Environment vars have more priority than the config file. + +# The "DIGIKEY_CLIENT_SANDBOX = True" can bne used to avoid consuming real queries +# The DIGIKEY_STORAGE_PATH option can be used to control where the tokens are stored + +# Locale setup: +# :param str x_digikey_locale_site: Two letter code for Digi-Key product website to search on. Different countries sites have different part restrictions, supported languages, and currencies. Acceptable values include: US, CA, JP, UK, DE, AT, BE, DK, FI, GR, IE, IT, LU, NL, NO, PT, ES, KR, HK, SG, CN, TW, AU, FR, IN, NZ, SE, MX, CH, IL, PL, SK, SI, LV, LT, EE, CZ, HU, BG, MY, ZA, RO, TH, PH. +# :param str x_digikey_locale_language: Two letter code for language to search on. Langauge must be supported by the selected site. If searching on keyword, this language is used to find matches. Acceptable values include: en, ja, de, fr, ko, zhs, zht, it, es, he, nl, sv, pl, fi, da, no. +# :param str x_digikey_locale_currency: Three letter code for Currency to return part pricing for. Currency must be supported by the selected site. Acceptable values include: USD, CAD, JPY, GBP, EUR, HKD, SGD, TWD, KRW, AUD, NZD, INR, DKK, NOK, SEK, ILS, CNY, PLN, CHF, CZK, HUF, RON, ZAR, MYR, THB, PHP. +# :param str x_digikey_locale_ship_to_country: ISO code for country to ship to. +# It must be coherent, i.e. +# , x_digikey_locale_currency = 'EUR', x_digikey_locale_site = 'ES', x_digikey_locale_ship_to_country = 'ES' +# If you ask for EUR to the US site you'll get USD, they won't charge you in EUR + +configure(cfg_file) + +# Query product number +dkpn = '296-6501-6-ND' +o = by_digikey_pn(dkpn) +part = o.search() +api_limit = o.api_limit + +print(part) +print('part_num: ' + part.digi_key_part_number) +print('url: ' + part.product_url) +print('qty_avail: ' + str(part.quantity_available)) +print('moq/qty_increment: ' + str(part.minimum_order_quantity)) +print('datasheet: ' + part.primary_datasheet) +# Active, Obsolete, Discontinued at Digi-Key, Last Time Buy, Not For New Designs, Preliminary. +print('lifecycle: ' + part.product_status.lower()) +print('currency: ' + part.search_locale_used.currency) +price_tiers = {p.break_quantity: p.unit_price for p in part.standard_pricing} +print('price_tiers: ' + str(price_tiers)) +specs = {sp.parameter: (sp.parameter, sp.value) for sp in part.parameters} +specs['RoHS'] = ('RoHS', part.ro_hs_status) +print('specs: ' + str(specs)) +print('-----') +print('price_offset: ' + str(part.additional_value_fee)) +print(api_limit) +exit(0) + + +# Batch search +# This isn't a free API +# products = ['296-6501-6-ND', 'CRCW080510K0FKEA'] +# request = BatchProductDetailsRequest(products=products) +# api_limit = {} +# result = kicost_digikey_api_v3.batch_product_details(body=request, api_limits=api_limit) +# print(result) +# print(api_limit) +# exit(0) + +# Search for manufacturer parts +# Search for a manufacturer part +# Returns one record for each available match and for each digikey code (i.e. one for the reel, another for the cut tape, etc.) +# Only exact matches are returned +#manf_pn = 'CRCW080510K0FKEA' +manf_pn = 'C0805C104K5RACTU' +o = by_manf_pn(manf_pn) +result = o.search() +api_limit = o.api_limit + +print(len(result)) +for part in result: + # print(part) + print('part_num: ' + part.digi_key_part_number) + print('url: ' + part.product_url) + print('qty_avail: ' + str(part.quantity_available)) + print('moq/qty_increment: ' + str(part.minimum_order_quantity)) + print('datasheet: ' + part.primary_datasheet) + # Active, Obsolete, Discontinued at Digi-Key, Last Time Buy, Not For New Designs, Preliminary. + print('lifecycle: ' + part.product_status.lower()) + print('currency: ' + part.search_locale_used.currency) + price_tiers = {p.break_quantity: p.unit_price for p in part.standard_pricing} + print('price_tiers: ' + str(price_tiers)) + specs = {sp.parameter: (sp.parameter, sp.value) for sp in part.parameters} + specs['RoHS'] = ('RoHS', part.ro_hs_status) + print('specs: ' + str(specs)) + print('* price_offset: ' + str(part.additional_value_fee)) + print('-----') +print(api_limit) +exit(0) + +# Search for parts by keyword +o = by_keyword('CRCW080510K0FKEA') +result = o.search() +print(result) +print(o.api_limit) +exit(0) + diff --git a/tests/test_oauth2.py b/tests/test_oauth2.py index 3eae744..02b5fff 100644 --- a/tests/test_oauth2.py +++ b/tests/test_oauth2.py @@ -64,7 +64,7 @@ def test_authentication(self, mock_on): 3: oauth2.TOKEN_URL_V3_PROD + r'.*'} for version in [2, 3]: - logger.info(f'Tests that token is retrieved correctly from authorization [API V{version}]') + logger.info('Tests that token is retrieved correctly from authorization [API V{}]'.format(version)) # Mock out all calls to token endpoint. url_auth = re.compile(urls[version]) diff --git a/tools/test_config.py b/tools/test_config.py new file mode 100644 index 0000000..526d9e1 --- /dev/null +++ b/tools/test_config.py @@ -0,0 +1,77 @@ +########################## +# Configuration logic +########################## + +import os +import pickle +import time +from kicost_digikey_api_v3 import DK_API + +class QueryCache(object): + ''' Components queries cache implementation ''' + def __init__(self, path, ttl): + self.path = path + self.ttl_min = ttl*24*60 + self.suffix = '' + + def get_name(self, prefix, name): + return os.path.join(self.path, prefix + '_' + name.replace('/', '_') + self.suffix + ".dat") + + def save_results(self, prefix, name, results): + ''' Saves the results to the cache ''' + with open(self.get_name(prefix, name), "wb") as fh: + pickle.dump(results, fh, protocol=2) + + def load_results(self, prefix, name): + ''' Loads the results from the cache, must be implemented by KiCost ''' + file = self.get_name(prefix, name) + print('Looking in cache '+file) + if not os.path.isfile(file): + return None, False + mtime = os.path.getmtime(file) + ctime = time.time() + dif_minutes = int((ctime-mtime)/60) + if self.ttl_min < 0 or (self.ttl_min > 0 and dif_minutes <= self.ttl_min): + with open(file, "rb") as fh: + result = pickle.loads(fh.read()) + print('Found in cache '+str(result)) + return result, True + # Cache expired + return None, False + + +def configure(cfg_file): + if cfg_file is None: + cfg_file = '~/.config/kicost_digikey_api_v3/config.txt' + cfg_file = os.path.expanduser(cfg_file) + cache = QueryCache('/tmp', 7) + with open(cfg_file, 'rt') as f: + for ln in f: + if not ln.strip(): + continue + val = ln.split('=') + if len(val) != 2: + print(f'Malformed {ln}') + exit(1) + key = val[0].strip() + value =val[1].strip() + if key == 'DIGIKEY_CLIENT_ID': + DK_API.id = value + elif key == 'DIGIKEY_CLIENT_SECRET': + DK_API.secret = value + elif key == 'DIGIKEY_CLIENT_SANDBOX': + DK_API.sandbox = value.lower() == 'true' + elif key == 'DIGIKEY_STORAGE_PATH': + cache.path = value + else: + print(f'Unknown config option {key}') + exit(1) + if 'DIGIKEY_CLIENT_ID' in os.environ: + DK_API.id = os.environ['DIGIKEY_CLIENT_ID'] + if 'DIGIKEY_CLIENT_SECRET' in os.environ: + DK_API.secret = os.environ['DIGIKEY_CLIENT_SECRET'] + if 'DIGIKEY_CLIENT_SANDBOX' in os.environ: + DK_API.sandbox = os.environ['DIGIKEY_CLIENT_SANDBOX'].lower() == 'true' + if 'DIGIKEY_STORAGE_PATH' in os.environ: + cache.path = os.environ['DIGIKEY_STORAGE_PATH'] + DK_API.configure(cache) \ No newline at end of file diff --git a/tools/user_agent.py b/tools/user_agent.py new file mode 100755 index 0000000..16cf04c --- /dev/null +++ b/tools/user_agent.py @@ -0,0 +1,6 @@ +#!/usr/bin/python3 + +# Query a fresh user agent +from fake_useragent import UserAgent + +print('<'+UserAgent().firefox+'>')