Skip to content

Commit

Permalink
Move the request wrappers to a separate class
Browse files Browse the repository at this point in the history
  • Loading branch information
SergeoLacruz committed Jun 6, 2024
1 parent 24ca865 commit 443a019
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 73 deletions.
62 changes: 62 additions & 0 deletions inventree_supplier_panel/request_wrappers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import requests
import os


# ----------------------------------------------------------------------------
# Wrappers around the requests for better error handling
class Wrappers():

def post_request(self, post_data, path, headers):
proxy_con = os.getenv('PROXY_CON')
proxy_url = os.getenv('PROXY_URL')
if proxy_con and proxy_url:
proxies = {proxy_con: proxy_url}
elif self.get_setting('PROXY_CON') != '' and self.get_setting('PROXY_URL') != '':
proxies = {self.get_setting('PROXY_CON'): self.get_setting('PROXY_URL')}
else:
proxies = {}
try:
response = requests.post(path,
verify=False,
proxies=proxies,
data=post_data,
timeout=5,
headers=headers
)
except Exception as e:
self.status_code = e.args
raise ConnectionError
if response.status_code != 200:
self.status_code = response.status_code
self.message = response.content
return (response)
self.status_code = 200
self.message = 'OK'
return (response)

def get_request(self, path, headers):
proxy_con = os.getenv('PROXY_CON')
proxy_url = os.getenv('PROXY_URL')
if proxy_con and proxy_url:
proxies = {proxy_con: proxy_url}
elif self.get_setting('PROXY_CON') != '' and self.get_setting('PROXY_URL') != '':
proxies = {self.get_setting('PROXY_CON'): self.get_setting('PROXY_URL')}
else:
proxies = {}
try:
response = requests.get(path,
verify=False,
proxies=proxies,
timeout=5,
headers=headers
)
except Exception as e:
self.status_code = e.args
raise ConnectionError
if response.status_code != 200:
self.status_code = response.status_code
self.message = response.content
return (response)
self.status_code = 200
self.message = 'OK'
return (response)
84 changes: 11 additions & 73 deletions inventree_supplier_panel/supplier_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@
from company.models import SupplierPriceBreak
from inventree_supplier_panel.version import PLUGIN_VERSION
from inventree_supplier_panel.meta_access import MetaAccess
from inventree_supplier_panel.request_wrappers import Wrappers
from users.models import check_user_role
from common.models import InvenTreeSetting

from requests.exceptions import ConnectionError
from urllib.parse import quote
import requests
import json
import os
import re


Expand Down Expand Up @@ -177,7 +175,7 @@ def get_custom_panels(self, view, request):
'content_template': self.registered_suppliers[s]['po_template'],
})

# For parts: Suppliet part creation
# For parts: Supplier part creation
if isinstance(view, PartDetail):
has_permission = (check_user_role(view.request.user, 'part', 'change')
or check_user_role(view.request.user, 'part', 'delete')
Expand All @@ -204,66 +202,6 @@ def setup_urls(self):
re_path(r'addsupplierpart(?:\.(?P<format>json))?$', self.add_supplierpart, name='add-supplierpart'),
]

# ----------------------------------------------------------------------------
# Wrappers around the requests for better error handling

def post_request(self, post_data, path, headers):
proxy_con = os.getenv('PROXY_CON')
proxy_url = os.getenv('PROXY_URL')
if proxy_con and proxy_url:
proxies = {proxy_con: proxy_url}
elif self.get_setting('PROXY_CON') != '' and self.get_setting('PROXY_URL') != '':
proxies = {self.get_setting('PROXY_CON'): self.get_setting('PROXY_URL')}
else:
proxies = {}
try:
response = requests.post(path,
verify=False,
proxies=proxies,
data=post_data,
timeout=5,
headers=headers
)
except Exception as e:
self.status_code = e.args
raise ConnectionError
if self.debug:
print('SPP:', response)
print('SPP:', response.content)
if response.status_code != 200:
self.status_code = response.status_code
self.message = response.content
return (response)
return (response)

def get_request(self, path, headers):
proxy_con = os.getenv('PROXY_CON')
proxy_url = os.getenv('PROXY_URL')
if proxy_con and proxy_url:
proxies = {proxy_con: proxy_url}
elif self.get_setting('PROXY_CON') != '' and self.get_setting('PROXY_URL') != '':
proxies = {self.get_setting('PROXY_CON'): self.get_setting('PROXY_URL')}
else:
proxies = {}
try:
response = requests.get(path,
verify=False,
proxies=proxies,
timeout=5,
headers=headers
)
except Exception as e:
self.status_code = e.args
raise ConnectionError
if self.debug:
print('SPP:', response)
print('SPP:', response.content)
if response.status_code != 200:
self.status_code = response.status_code
self.message = response.content
return (response)
return (response)

# ------------------------ update_cart ----------------------------------
# The Mouser part.
# Actually we send an empty CartKey. So Mouser creates a new key each time
Expand All @@ -283,7 +221,7 @@ def update_mouser_cart(self, order, cart_key):
}
url = 'https://api.mouser.com/api/v001/cart/items/insert?apiKey=' + self.get_setting('MOUSERKEY') + '&countryCode=' + country_code
header = {'Content-type': 'application/json', 'Accept': 'application/json'}
response = self.post_request(json.dumps(cart), url, header)
response = Wrappers.post_request(self, json.dumps(cart), url, header)
response = response.json()

# Return with error if response was not OK
Expand Down Expand Up @@ -342,7 +280,7 @@ def get_mouser_partdata(self, sku):
}
url = 'https://api.mouser.com/api/v1.0/search/partnumber?apiKey=' + self.get_setting('MOUSERSEARCHKEY')
header = {'Content-type': 'application/json', 'Accept': 'application/json'}
response = self.post_request(json.dumps(part), url, header)
response = Wrappers.post_request(self, json.dumps(part), url, header)
response = response.json()
if response['Errors'] != []:
self.status_code = response['Errors']
Expand Down Expand Up @@ -410,7 +348,7 @@ def update_digikey_cart(self, order, list_id):
'CustomerReference': item.part.part.IPN
})
# The post equest just generates the list in the Digikey cloud
self.post_request(json.dumps(cart_items), url, header)
Wrappers.post_request(self, json.dumps(cart_items), url, header)

# Now we get the parts from the generated list
parts_in_list = self.get_parts_in_list(list_id)
Expand Down Expand Up @@ -473,7 +411,7 @@ def get_parts_in_list(self, list_id):
'X-DIGIKEY-Client-Id': self.get_setting('DIGIKEY_CLIENT_ID'),
'accept': 'application/json'
}
response = self.get_request(url, headers=header)
response = Wrappers.get_request(self, url, headers=header)
if not response:
return (None)
return (response.json())
Expand All @@ -497,7 +435,7 @@ def get_digikey_partdata(self, sku):
'X-DIGIKEY-Locale-Site': country_code,
'X-DIGIKEY-Locale-Language': 'EN'
}
response = self.get_request(url, headers=header)
response = Wrappers.get_request(self, url, headers=header)
if not response:
return (None)
print('Remaining requests:', response.headers['X-RateLimit-Remaining'])
Expand Down Expand Up @@ -566,7 +504,7 @@ def create_digikey_cart(self, order):
'ListName': list_name,
'accept': 'application/json'
}
response = self.post_request(json.dumps(url_data), url, headers=header)
response = Wrappers.post_request(self, json.dumps(url_data), url, headers=header)
self.status_code = response.status_code
cart_data['ID'] = response.json()
self.message = 'success'
Expand All @@ -579,7 +517,7 @@ def check_valid_listname(self, list_name):
'X-DIGIKEY-Client-Id': self.get_setting('DIGIKEY_CLIENT_ID'),
'accept': 'application/json'
}
response = self.get_request(url, headers=header)
response = Wrappers.get_request(self, url, headers=header)
return (response.content == b'true')

# -------------------- Here starts the digikey token stuff --------------------
Expand All @@ -597,7 +535,7 @@ def refresh_digikey_access_token(self):
}
header = {}
token = {}
response = self.post_request(url_data, url, headers=header)
response = Wrappers.post_request(self, url_data, url, headers=header)
if not response:
return (None)
print('\033[32mToken refresh SUCCESS\033[0m')
Expand All @@ -624,7 +562,7 @@ def receive_authcode(self, request):
'grant_type': 'authorization_code'
}
header = {}
response = self.post_request(url_data, url, headers=header)
response = Wrappers.post_request(self, url_data, url, headers=header)
if response.status_code == 200:
print('\033[32mAccess Token get SUCCESS\033[0m')
response_data = response.json()
Expand Down

0 comments on commit 443a019

Please sign in to comment.