I try to add header when sending SOAP request in Python.
The header in SOAP is:
> <SOAP-ENV:Header>
> <ns3:userCredentials
> xsi:type="https://4psa.com/HeaderData.xsd/2.0.0">
> <username>admin</username>
> <password>welcome</password>
> </ns3:userCredentials>
> </SOAP-ENV:Header>
I have used:
from suds.client import Client
from suds.xsd.doctor import ImportDoctor, Import
wsdl = 'https://192.168.1.15//soap2/schema/2.5.0/Report/Report.wsdl'
client = Client(wsdl)
and I don`t know how to add header to this code.
Please suggest how to add it.
And I tried:
> >>> from suds.client import Client
> >>> from suds.xsd.doctor import ImportDoctor, Import
> >>> imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
> >>> url = 'https://192.168.1.15//soap2/schema/2.5.0/Report/Report.wsdl'
> >>> client = Client(url)
> >>> userid = 'admin'
> >>> passwd = '12345678#X'
> >>> client.set_options(soapheaders=(userid,passwd))
> >>> print client a get error when run:
>
> >>> client.service.CallCosts(1) Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/client.py",
> line 542, in __call__
> return client.invoke(args, kwargs) File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/client.py",
> line 602, in invoke
> result = self.send(soapenv) File "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/client.py",
> line 637, in send
> reply = transport.send(request) File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/transport/https.py",
> line 64, in send
> return HttpTransport.send(self, request) File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/transport/http.py", line 77, in send
> fp = self.u2open(u2request) File "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/transport/http.py", line 118, in u2open
> return url.open(u2request, timeout=tm) File
> "/usr/lib/python2.6/urllib2.py", line
> 391, in open
> response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py",
> line 409, in _open
> '_open', req) File "/usr/lib/python2.6/urllib2.py", line
> 369, in _call_chain
> result = func(*args) File "/usr/lib/python2.6/urllib2.py", line
> 1169, in https_open
> return self.do_open(httplib.HTTPSConnection,
> req) File
> "/usr/lib/python2.6/urllib2.py", line
> 1136, in do_open
> raise URLError(err) urllib2.URLError: <urlopen error
> [Errno 111] Connection refused>
Please suggest if you know what is the problem here.
I did something like this
def client_with_token(token):
header_ns = ('ns1', "http://4psa.com/HeaderData.xsd/3.5.0")
access_token = Element('accessToken', ns=header_ns).setText(token)
auth_header = Element('userCredentials', ns=header_ns)
auth_header.append(access_token)
client = Client(url)
auth_header = get_auth_header()
client.set_options(soapheaders=auth_header, *args, **kwargs)
return client
The suds client has many that may be used to control the behavior of the library. Some are general options and others are transport options. Although, the options objects are exposed, the preferred and supported way to set/unset options is through:
The Client constructor
The Client.set_options()
The Transport constructor(s).
soapheaders – Provides for soap headers.
https://fedorahosted.org/suds/wiki/Documentation#OPTIONS
http://jortel.fedorapeople.org/suds/doc/suds.options.Options-class.html
http://jortel.fedorapeople.org/suds/doc/suds.client.Client-class.html#set_options
Related
I'm using urllib.request.
I'm trying to use the BingX Swap Api with Python and I'm getting this error:
I'm trying to use the BingX Swap Api with Python and I'm getting this error:
I'm trying to use the BingX Swap Api with Python and I'm getting this error:
I'm trying to use the BingX Swap Api with Python and I'm getting this error:
Traceback (most recent call last):
File "Desktop\MyBot\MyApi.py", line 118, in <module>
main()
File "Desktop\MyBot\MyApi.py", line 103, in main
print("getLatestPrice:", getLatestPrice())
^^^^^^^^^^^^^^^^
File "Desktop\MyBot\MyApi.py", line 70, in getLatestPrice
return post(url, paramsStr)
^^^^^^^^^^^^^^^^^^^^
File "Desktop\MyBot\MyApi.py", line 19, in post
return urllib.request.urlopen(req).read()
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\urllib\request.py", line 216, in urlopen
return opener.open(url, data, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\urllib\request.py", line 525, in open
response = meth(req, response)
^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\urllib\request.py", line 634, in http_response
response = self.parent.error(
^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\urllib\request.py", line 563, in error
return self._call_chain(*args)
^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\urllib\request.py", line 496, in _call_chain
result = func(*args)
^^^^^^^^^^^
File "Python\Python311\Lib\urllib\request.py", line 643, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 405: Method Not Allowed
I don't know what I'm doing wrong, I think that my code is ok.
This is My Code:
import urllib.request
import json
import base64
import hmac
import time
APIURL = "https://api-swap-rest.bingbon.pro"
APIKEY = "xxxxxxxxxxxxx"
SECRETKEY = "xxxxxxxxxxxxx"
def genSignature(path, method, paramsMap):
sortedKeys = sorted(paramsMap)
paramsStr = "&".join(["%s=%s" % (x, paramsMap[x]) for x in sortedKeys])
paramsStr = method + path + paramsStr
return hmac.new(SECRETKEY.encode("utf-8"), paramsStr.encode("utf-8"), digestmod="sha256").digest()
def post(url, body):
req = urllib.request.Request(url, data=body.encode("utf-8"), headers={'User-Agent': 'Mozilla/5.0'})
return urllib.request.urlopen(req).read()
def getLatestPrice():
paramsMap = {
"symbol": "BTC-USDT",
}
sortedKeys = sorted(paramsMap)
paramsStr = "&".join(["%s=%s" % (x, paramsMap[x]) for x in sortedKeys])
paramsStr += "&sign=" + urllib.parse.quote(base64.b64encode(genSignature("/api/v1/market/getLatestPrice", "GET", paramsMap)))
url = "%s/api/v1/market/getLatestPrice" % APIURL
return post(url, paramsStr)
def main():
print("getLatestPrice:", getLatestPrice())
if __name__ == "__main__":
main()
This is a small API request that is throwing me a requests.exceptions.ChunkedEncodingError
import requests
def categories_list():
categories = []
response = requests.get("https://fr.openfoodfacts.org/categories&json=1")
data = response.json()
i = 0
for category in data["tags"]:
if category["products"] >= 1200:
name = category["name"]
categories.append(name)
i += 1
print("It's ok, imported %s" % i)
categories_list()
Error code:
File "exception.py", line 18, in <module>
categories_list()
File "exception.py", line 6, in categories_list
response = requests.get("https://fr.openfoodfacts.org/categories&json=1")
File "/home/pi/Documents/venv/lib/python3.7/site-packages/requests/api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "/home/pi/Documents/venv/lib/python3.7/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/home/pi/Documents/venv/lib/python3.7/site-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/home/pi/Documents/venv/lib/python3.7/site-packages/requests/sessions.py", line 683, in send
r.content
File "/home/pi/Documents/venv/lib/python3.7/site-packages/requests/models.py", line 829, in content
self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
File "/home/pi/Documents/venv/lib/python3.7/site-packages/requests/models.py", line 754, in generate
raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(3573 bytes read, 6667 more expected)', IncompleteRead(3573 bytes read, 6667 more expected))
Could it be possibly my internet connection? Similar queries worked for me yesterday...
I am trying to make the below short code to work. My focus is in fetch_historical_yahoo which seems not to be working. I am trying to use it in a larger code.
import datetime
import matplotlib.finance as finance
import matplotlib.mlab as mlab
startdate = datetime.date(2005,1,1)
today = enddate = datetime.date.today()
ticker = 'nvda'
fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
r = mlab.csv2rec(fh); fh.close()
r.sort()
When I run the code, I get the below error. When I go and open finance.py I can't seem to be able to place my finger on the url issue.
Any ideas?
I tried mlp_finance but I was nopt able to install it.
fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
Traceback (most recent call last):
File "<ipython-input-61-e83eb3d28a19>", line 1, in <module>
fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
File "C:\Users\dvargas\Anaconda3\lib\site-packages\matplotlib\finance.py", line 362, in fetch_historical_yahoo
with contextlib.closing(urlopen(url)) as urlfh:
File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 466, in open
response = self._open(req, data)
File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 484, in _open
'_open', req)
File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 444, in _call_chain
result = func(*args)
File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 1282, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Users\dvargas\Anaconda3\lib\urllib\request.py", line 1256, in do_open
raise URLError(err)
URLError: <urlopen error [Errno 11004] getaddrinfo failed>
I had to use a workaround.
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
def get_historical_data(name, number_of_days):
data = []
url = "https://finance.yahoo.com/quote/" + name + "/history/"
rows = bs(urlopen(url).read()).findAll('table')[0].tbody.findAll('tr')
for each_row in rows:
divs = each_row.findAll('td')
if divs[1].span.text != 'Dividend': #Ignore this row in the table
#I'm only interested in 'Open' price; For other values, play with divs[1 - 5]
data.append({'Date': divs[0].span.text, 'Open': float(divs[1].span.text.replace(',',''))})
return data[:number_of_days]
#Test
for i in get_historical_data('googl', 5):
print(i)
I am running a python script with Phontomjs and Selenium. I am facing timeout issue. It is stopping after 20-50min. I need a solution so that I can run my script without this timeout issue. where is the problem please and how can I solve it?
The input file cannot be read or no in proper format.
Traceback (most recent call last):
File "links_crawler.py", line 147, in <module>
crawler.Run()
File "links_crawler.py", line 71, in Run
self.checkForNextPages()
File "links_crawler.py", line 104, in checkForNextPages
self.next.click()
File "/home/dev/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 75, in click
self._execute(Command.CLICK_ELEMENT)
File "/home/dev/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 454, in _execute
return self._parent.execute(command, params)
File "/home/dev/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 199, in execute
response = self.command_executor.execute(driver_command, params)
File "/home/dev/.local/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 395, in execute
return self._request(command_info[0], url, body=data)
File "/home/dev/.local/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 463, in _request
resp = opener.open(request, timeout=self._timeout)
File "/usr/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1227, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1200, in do_open
r = h.getresponse(buffering=True)
File "/usr/lib/python2.7/httplib.py", line 1127, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 453, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 417, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine: ''
Code:
class Crawler():
def __init__(self,where_to_save, verbose = 0):
self.link_to_explore = ''
self.TAG_RE = re.compile(r'<[^>]+>')
self.TAG_SCRIPT = re.compile(r'<(script).*?</\1>(?s)')
if verbose == 1:
self.driver = webdriver.Firefox()
else:
self.driver = webdriver.PhantomJS()
self.links = []
self.next = True
self.where_to_save = where_to_save
self.logs = self.where_to_save + "/logs"
self.outputs = self.where_to_save + "/outputs"
self.logfile = ''
self.rnd = 0
try:
os.stat(self.logs)
except:
os.makedirs(self.logs)
try:
os.stat(self.outputs)
except:
os.makedirs(self.outputs)
try:
fin = open(file_to_read,"r")
FileContent = fin.read()
fin.close()
crawler =Crawler(where_to_save)
data = FileContent.split("\n")
for info in data:
if info!="":
to_process = info.split("|")
link = to_process[0].strip()
category = to_process[1].strip().replace(' ','_')
print "Processing the link: " + link : " + info
crawler.Init(link,category)
crawler.Run()
crawler.End()
crawler.closeSpider()
except:
print "The input file cannot be read or no in proper format."
raise
If you don't want Timeout to stop your script you can catch the exception
selenium.common.exceptions.TimeoutException and pass it.
You can set the default page load timeout using the set_page_load_timeout() method of webdriver.
Like this
driver.set_page_load_timeout(10)
This will throw a TimeoutException if your page didn't load in 10 seconds.
EDIT:
Forgot to mention that you will have to put your code in a loop.
Add import
from selenium.common.exceptions import TimeoutException
while True:
try:
# Your code here
break # Loop will exit
except TimeoutException:
pass
At work I have to access/work with the Channel Advisor API
Source:
I'm attempting to perform a simple OrderService
from suds.client import Client
wsdl_url = 'https://api.channeladvisor.com/ChannelAdvisorAPI/v6/OrderService.asmx?WSDL'
service_url = 'https://api.channeladvisor.com/ChannelAdvisorAPI/v6/OrderService.asmx'
headers = {'Content-Type': 'text/xml; charset=utf-8'}
client = Client(wsdl_url, location = service_url, headers=headers)
Here is error:
Traceback (most recent call last):
File "test_suds.py", line 9, in <module>
client = Client(wsdl_url, location = service_url, headers=headers)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/client.py", line 112, in __init__
self.wsdl = reader.open(url)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/reader.py", line 152, in open
d = self.fn(url, self.options)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/wsdl.py", line 136, in __init__
d = reader.open(url)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/reader.py", line 79, in open
d = self.download(url)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/reader.py", line 95, in download
fp = self.options.transport.open(Request(url))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/transport/https.py", line 60, in open
return HttpTransport.open(self, request)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/transport/http.py", line 62, in open
return self.u2open(u2request)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/suds-0.4.1-py2.7.egg/suds/transport/http.py", line 118, in u2open
return url.open(u2request, timeout=tm)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1222, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 54] Connection reset by peer>