Python Unexpected keyword argument' in constructor call - python

Hi and thanks in advance for your help. I am not a Python expert but an accomplished programmer in other languages.
I'm getting the error on "is_server_running"
Client
from ibw.client import IBClient
REGULAR_USERNAME = 'MY_ACCOUNT_USERNAME'
REGULAR_ACCOUNT = 'MY_ACCOUNT_NUMBER'
# Create a new session of the IB Web API.
ib_client = IBClient(username=REGULAR_USERNAME,
account=REGULAR_ACCOUNT,
client_gateway_path=None,
is_server_running=True)
class IBClient():
def __init__(self, username: str, account: str, client_gateway_path: str = None, is_server_running:
bool = True) -> None
self.account = account
self.username = username
self.client_gateway_path = client_gateway_path
self.client_portal_client = ClientPortal()
self.api_version = 'v1/'
self._operating_system = sys.platform
self.session_state_path: pathlib.Path =
pathlib.Path(__file__).parent.joinpath('server_session.json').resolve()
self.authenticated = False
self._is_server_running = is_server_running
# Define URL Components
ib_gateway_host = r"https://localhost"
ib_gateway_port = r"5000"
self.ib_gateway_path = ib_gateway_host + ":" + ib_gateway_port
self.backup_gateway_path = r"https://cdcdyn.interactivebrokers.com/portal.proxy"
self.login_gateway_path = self.ib_gateway_path + "/sso/Login?forwardTo=22&RL=1&ip2loc=on"
[more code]
Again thanks in advance for your help
Bob

Related

Mock the object call on function

I'm trying to mock the object, But it's not happening can anyone help me
payment_gateway
----payment.py
class Razz:
def __init__(self) -> None:
self.base_url = "https://api.example.com/v1"
self.api_key = os.environ["API_KEY"]
self.api_secret = os.environ["SECRET"]
self.kh_account_number = os.environ["ACCOUNT_NUMBER"]
def create_contact(self):
res = request.post(usrl=f"{base_url}/contact", data=payload, auth(self.api_key,self.api_secret)
return "id"
And am importing this class on another fille i.e event_bank_deails.py
from payment_gateway.payment import Razz, PaymentGatewayErrors
PAYMENT_GATEWAY= Razz()
def update_bank_detials(request: Request) -> Response:
contact_id = PAYMENT_GATEWAY.create_contact(body, event_id) # Creating contact
fund_id = PAYMENT_GATEWAY.create_account(contact_id, body) # Creating fund account on razorpayX
return resposes
TestCases file
#patch("event_bank_details.event_bank_details.Razz")
#pytest.mark.parametrize("input, expected_op", UPDATE_EVENT_BANK_DETAILS_INPUT)
def test_update_event_bank_details(mock_email, mock_object, input, expected_op):
from event_bank_details.event_bank_details import update_bank_detials
# mock_object.return_value.create_contact.return_value = None
# mock_object.return_value.create_account.create_account = None
response = update_bank_detials(input)
response.prepare()
response_dict = response.get()
assert response_dict["statusCode"] == expected_op
And then am writing test cases for the update_bank_details function It's throwing an error invalid API_KEYandAPI_SECREATEHow can I mock theRazzclassinit()` call on update_bank_details function???

How to log into SAP silently using win32com methods?

I have a question about SAP silent logon which I implemented using win32com this way
from win32com.client import Dispatch
R3 = Dispatch("SAP.Functions")
R3.Conn.System = 'xxx'
R3.Conn.Client = '100'
# other values needed to pass to R3.Conn
R3.Conn.logon #here is the problem
In VB i can use R3.Conn.Logon(1, True) to make logon siliencely. But in Python Logon seems not to be a method and do not allow me to pass parameters to it.
I tried using R3.Conn.Logon(1, True) in Python, but it returned an error
Logon was not callable.
How should I call silent logon in Python?
Thanks
This works for me.
Still experimenting, I want to add field selection and of course a filter to the RFC_READ_TABLE. But the connection works.
from win32com.client import Dispatch
Functions = Dispatch("SAP.Functions")
Functions.Connection.Client = "000"
Functions.Connection.ApplicationServer = "your server"
Functions.Connection.Language = "EN"
Functions.Connection.User = "you"
Functions.Connection.Password = "your pass"
Functions.Connection.SystemNumber = "00"
Functions.Connection.UseSAPLogonIni = False
if (Functions.Connection.Logon (0,True) == True):
print("Logon OK")
RfcCallTransaction = Functions.Add("RFC_READ_TABLE")
strExport1 = RfcCallTransaction.exports("QUERY_TABLE")
strExport2 = RfcCallTransaction.exports("DELIMITER")
strExport3 = RfcCallTransaction.exports("ROWSKIPS")
strExport4 = RfcCallTransaction.exports("ROWCOUNT")
tblOptions = RfcCallTransaction.Tables("OPTIONS")
#RETURNED DATA
tblData = RfcCallTransaction.Tables("DATA")
tblFields = RfcCallTransaction.Tables("FIELDS")
strExport1.Value = 'AGR_DEFINE'
strExport2.Value = ";"
strExport3.Value = 0
strExport4.Value = 10
if RfcCallTransaction.Call == True:
print ("Function call successful")
#print (tblData.RowCount)
j = 1
while j < tblData.RowCount:
print (tblData(j,"WA"))
j = j + 1

TypeError: insert_or_replace_entity() takes at most 4 arguments (5 given)

I'm trying to store entity into azure storage table using python. But I got following error.
self.table_service.insert_or_replace_entity('myDataTable', 'A100', keyVal, self.task)
TypeError: insert_or_replace_entity() takes at most 4 arguments (5 given)
I have provide 4 arguments only into insert_or_replace_entity() function, but compiler consider five, Why? I don't understand, please someone help me.
My code is here:
#!/usr/bin/env python
import time
import csv
import sys
from azure.storage.table import TableService, Entity
class Azure:
table_service = ''
task = {}
PartitionKey = ''
RowKey = ''
RPI_ID = ''
PIC_ID = ''
Date = ''
Time = ''
Temp = ''
def openAccount(self):
self.table_service = TableService(account_name='<My account name>', account_key='<My key>')
def createTable(self):
self.table_service.create_table('myDataTable')
def setEntity(self, i):
task_i = Entity()
task_i.PartitionKey = 'A100'
task_i.RowKey = str(i)
print task_i
task_i.RPI_ID = 'A100'
task_i.PIC_ID = 'P100'
task_i.Date = time.strftime("%d-%m-%Y")
task_i.Time = time.strftime("%I:%M")
task_i.Temp = '22.05'
self.task = task_i;
def insertOrReplaceEntity(self, keyVal):
self.table_service.insert_or_replace_entity('myDataTable', 'A100', keyVal, self.task)
data = Azure()
data.openAccount()
data.createTable()
cnt = 0
while (cnt < 10):
data.setEntity(cnt)
data.insertOrReplaceEntity(cnt)
cnt = cnt + 1
time.sleep(1)
Thanks in advance.
insert_or_replace_entity(table_name, entity, timeout=None) (https://azure.github.io/azure-storage-python/ref/azure.storage.table.tableservice.html#azure.storage.table.tableservice.TableService.insert_or_replace_entity) actually has signature:
def insert_or_replace_entity(self, table_name, entity, timeout=None):
So with self.table_service.insert_or_replace_entity('myDataTable', 'A100', keyVal, self.task) you are actually doing something like insert_or_replace_entity(self, 'myDataTable', 'A100', keyVal, self.task), hence the five arguments.

Invalid JSON object when posting to an API - Python

I am using Blockchain.info's API to send multiple payments. I believe I have everything how it should be however when I run the code I get the following Error: RuntimeError: ERROR: Invalid Recipients JSON. Please make sure it is url encoded and consult the docs. The docs can be found here: https://blockchain.info/api/blockchain_wallet_api
The Python library I am using can be found here: https://github.com/p4u/blockchain.py/blob/master/blockchain.py
The only other post on this issue is posted by the original creator of the library, he said the problem was that the amounts cannot be a decimal, mine are not however.Post can be found here: https://bitcointalk.org/index.php?topic=600870.0
Here is my code:
from __future__ import print_function
from itertools import islice, imap
import csv, requests, json, math
from collections import defaultdict
import requests
import urllib
import json
from os.path import expanduser
import configparser
class Wallet:
guid = 'g'
isAccount = 0
isKey = 0
password1 = 'x'
password2 = 'y'
url = ''
def __init__(self, guid = 'g', password1 = 'x', password2 = 'y'):
if guid.count('-') > 0:
self.isAccount = 1
if password1 == '': # wallet guid's contain -
raise ValueError('No password with guid.')
else:
self.isKey = 1
self.guid = guid
self.url = 'https://blockchain.info/merchant/' + guid + '/'
self.password1 = password1
self.password2 = password2
r = requests.get('http://api.blockcypher.com/v1/btc/main/addrs/A/balance')
balance = r.json()['balance']
with open("Entries#x1.csv") as f,open("winningnumbers.csv") as nums:
nums = set(imap(str.rstrip, nums))
r = csv.reader(f)
results = defaultdict(list)
for row in r:
results[sum(n in nums for n in islice(row, 1, None))].append(row[0])
self.number_matched_0 = results[0]
self.number_matched_1 = results[1]
self.number_matched_2 = results[2]
self.number_matched_3 = results[3]
self.number_matched_4 = results[4]
self.number_matched_5 = results[5]
self.number_matched_5_json = json.dumps(self.number_matched_5, sort_keys = True, indent = 4)
print(self.number_matched_5_json)
if len(self.number_matched_3) == 0:
print('Nobody matched 3 numbers')
else:
self.tx_amount_3 = int((balance*0.001)/ len(self.number_matched_3))
if len(self.number_matched_4) == 0:
print('Nobody matched 4 numbers')
else:
self.tx_amount_4 = int((balance*0.1)/ len(self.number_matched_4))
if len(self.number_matched_5) == 0:
print('Nobody matched 3 numbers')
else:
self.tx_amount_5 = int((balance*0.4)/ len(self.number_matched_5))
self.d = {el: self.tx_amount_5 for el in json.loads(self.number_matched_5_json)}
print(self.d)
self.d_url_enc = urllib.urlencode(self.d)
def Call(self, method, data = {}):
if self.password1 != '':
data['password'] = self.password1
if self.password2 != '':
data['second_password'] = self.password2
response = requests.post(self.url + method,params=data)
json = response.json()
if 'error' in json:
raise RuntimeError('ERROR: ' + json['error'])
return json
def SendPayment(self, toaddr, amount, fromaddr = 'A', shared = 0, fee = 0.0001, note = True):
data = {}
data['to'] = toaddr
data['amount'] = self.tx_amount_5
data['fee'] = fee
data['recipients'] = self.d_url_enc
if fromaddr:
data['from'] = fromaddr
if shared:
data['shared'] = 'true'
if note:
data['note'] = 'n'
response = self.Call('payment',data)
def SendManyPayment(self, fromaddr = True, shared = False, fee = 0.0001, note = True):
data = {}
recipients = self.d_url_enc
data['recipients'] = recipients.__str__().replace("'",'"')
data['fee'] = str(fee)
if fromaddr:
data['from'] = 'A'
if shared:
data['shared'] = 'true'
else:
data['shared'] = 'false'
if note:
data['note'] = 'n'
response = self.Call('sendmany',data)
return response
print(Wallet().SendManyPayment())
Complete runtime error: Traceback (most recent call last):
File "D:\Documents\B\Code\A\jsontest.py", line 125, in <module>
print(Wallet().SendManyPayment())
File "D:\Documents\B\Code\A\jsontest.py", line 121, in SendManyPayment
response = self.Call('sendmany',data)
File "D:\Documents\B\Code\A\jsontest.py", line 86, in Call
raise RuntimeError('ERROR: ' + json['error'])
RuntimeError: ERROR: Invalid Recipients JSON. Please make sure it is url encoded and consult the docs.
What does data['recipients'] contain inside of your SendManyPayment() function? It looks like you are trying to do some manual encoding instead of using json.dumps(recipients)
The docs say it should look like this:
{
"1JzSZFs2DQke2B3S4pBxaNaMzzVZaG4Cqh": 100000000,
"12Cf6nCcRtKERh9cQm3Z29c9MWvQuFSxvT": 1500000000,
"1dice6YgEVBf88erBFra9BHf6ZMoyvG88": 200000000
}
Try this out for send many:
def SendManyPayment(self, fromaddr = True, shared = False, fee = 0.0001, note = True):
data = {}
recipients = self.d_url_enc
# recipients should be a json string FIRST!
data['recipients'] = json.dumps(recipients)
data['fee'] = str(fee)
if fromaddr:
data['from'] = 'A'
if shared:
data['shared'] = 'true'
else:
data['shared'] = 'false'
if note:
data['note'] = 'n'
response = self.Call('sendmany',data)
return response

GAE Datastore Put()

def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
Should this will update the existing record if the 'update' is querystring containing key datastore key. I try this but keep adding new record/entity. Please give me some sugesstion to correctly updating the record/entity.
Correction? :
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update:
personal = Personal.get(db.Key(update))
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
personal= Personal()
personal.name = self.request.get('name')
personal.gender = self.request.get('gender')
personal.mobile_num = self.request.get('mobile_num')
personal.birthdate = int(self.request.get('birthdate'))
personal.birthplace = self.request.get('birthplace')
personal.address = self.request.get('address')
personal.geo_pos = self.request.get('geo_pos')
personal.info = self.request.get('info')
photo = images.resize(self.request.get('img'), 0, 80)
personal.photo = db.Blob(photo)
personal.put()
self.redirect('/admin/personal')
else:
self.response.out.write('I\'m sorry, you don\'t have permission to add this LP Personal Data.')
There's no need to do a query when you know the key: Simply call db.get() on the key to retrieve it directly, which is much faster than doing a query.
As to why you're creating a new record each time, it looks like you're not passing in 'update' to your page correctly. Try logging the query string parameters to see what's going wrong.
I finally answer this myself, Thanks for Nick Johnson guide on this.
I cannot get the query string url as 'string key' that always raise BadKeyError: Invalid string key exception.
I try to put this 'update' string as hidden field on html edit form and this works since 'update' is a valid 'string key' now.
def post(self):
update = self.request.get('update')
if users.get_current_user():
if update != '':
personal = Personal.get(db.Key(update))

Categories

Resources