Getting Fault 1: "SQLSTATE[21000]: Cardinality violation: 1241 - python

While creating a customer with Magento API using Python, i am getting this error:
Fault 1: "SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s), query was: SELECT `customer_entity`.* FROM `customer_entity` WHERE (entity_id ='firstname', '3876')"
But if i specify only the customer id, it will ask for all the other fields, and when i extend the dict with these values, the same error comes again.
Here is the dict i use to create the customer:
address = {}
address['customer_id'] = '3876'
address['addressdata']={}
address['addressdata']['firstname'] = 'firstname'
address['addressdata']['lastname'] = 'lastname'
address['addressdata']['city'] = 'city'
address['addressdata']['region'] = 'Texas'
address['addressdata']['region_id'] = 1
address['addressdata']['postcode'] = '23423' #ZIP
address['addressdata']['telephone'] = '3245235235' #phone
address['addressdata']['is_default_billing'] = False
address['addressdata']['is_default_shipping'] = False
address = proxy.call(session, 'customer_address.create', [address])
What do you think can be wrong here? Thanks

On the server side, enable sql logging (ideally only your API call should run against that server, in order to debug):
In Varien_Db_Adapter_Pdo_Mysql
lib/varien/Db/Adapter/Pdo/Mysql.php
set
protected $_debug = true;
protected $_logAllQueries = true;
and (if nor already there) create the folder defined in
protected $_debugFile = 'var/debug/sql.txt';
Run the API call then have a look at the log file and see what queries ran and why it gives an error.
You can also try these following links for same issue, might be helpfull for you.
https://stackoverflow.com/a/14864123
https://stackoverflow.com/a/34997348
https://stackoverflow.com/a/38326377

Related

Unable to set ms-TS-Max-Idle-Time LDAP attribute from Python Script

I need help with an LDAP attribute that I’m trying to assign for adding a new AD user.
I’m using the following Python script for adding a new user and everything works as expected:
# attributes
ldap_attr = {}
ldap_attr['objectClass'] = ['top', 'person' , 'organizationalPerson' , 'user' ]
ldap_attr['cn'] = user_username
ldap_attr['givenName'] = user_firstname
ldap_attr['sn'] = user_lastname
ldap_attr['uid'] = user_username
ldap_attr['sAMAccountName'] = user_username
ldap_attr['mail'] = user_email
ldap_attr['telephoneNumber'] = user_phonenumber
ldap_attr['userPrincipalName'] = f"{user_username}#{ad_domain}"
ldap_attr['displayName'] = f"{user_firstname} {user_lastname}"
### SCRIPT PATH
ldap_attr['scriptPath'] = 'setup.bat'
### SESSION TIMEOUTS
ldap_attr['msTSMaxDisconnectionTime'] = 1
ldap_attr['msTSMaxIdleTime'] = 120
ldap_attr['msTSReconnectionAction'] = True
ldap_conn = connect_ldap_server()
response = ldap_conn.add(f'CN={user_username},{users},{base}', attributes=ldap_attr)
However, the following attributes listed in that script aren’t being added to that user related to Terminal Service.
msTSMaxDisconnectionTime
msTSMaxIdleTime
msTSReconnectionAction
I’m using the correct LDAP name and value type based on the supported Microsoft documentation found here: https://learn.microsoft.com/en-us/windows/win32/adschema/a-mstsmaxidletime
I’m not sure if there is anything that needs to be set on the AD domain controller itself or anything I need to define differently within my script. But any help is much appreciated because I’m unable to find any results related to my issue.
Thanks!

How do I use a loop until a key is added in a dictionary?

I am using Django as the framework. I am using boto3 to create an AWS account in my views function. Every created aws account will have an AccountId. Before going into further details, here is my snippet :
org = boto3.client('organizations')
acc = org.create_account(
Email=email,
AccountName=lab_name,
IamUserAccessToBilling='ALLOW'
)
cid = acc['CreateAccountStatus']['Id']
time.sleep(70)
#GET ACCOUNT DETAILS
status = org.describe_create_account_status(
CreateAccountRequestId=cid
)
accid = status['CreateAccountStatus']['AccountId']
Initially I am creating the account. Like I mentioned before it takes some time (around 1 to 1.5 mins) to create the account. Then I need to GET the account details, one of the details being the AccountId. I tried increasing the sleep time to resolve this issue but that didn't help. I am getting an error when I try to GET the AccountId value in 'accid' declaration line. The error I am getting is:
KeyError: AccountId doesn't exist
This is probably happening because the account is not getting created yet and before that event my code is trying to fetch the AccountId value. How can I get the AccountId value then ? Should I try putting it in a loop or using try and except block to avoid the error message ? Please help. Thanks in advance.
status = org.describe_create_account_status(CreateAccountRequestId=cid)
while status.get('CreateAccountStatus',{}).get('AccountId',None) is None:
# sleep here
status = org.describe_create_account_status(CreateAccountRequestId=cid)
accid = status['CreateAccountStatus']['AccountId']
This will use the .get(key, default) of dict to supply it (or an empty dict) for 'CreateAccountStatus' and a None for 'AccountId' and loop while it is None.
About dict.get() and the dict.get-API
As pointed out by JonClements it might be more pythonic to use a while True: ... break ... construct for this:
while True:
status = org.describe_create_account_status(CreateAccountRequestId=cid)
try:
accid = status['CreateAccountStatus']['AccountId']
break
except KeyError:
time.sleep(30)
This avoids duplication of the status = ... line and makes for a more clearer flow.
Using try: ... except: fits better with the pythonic ask-forgiveness-not-permission approach.
In your acc['CreateAccountStatus'] variable, you should have a key State that will tell you when the creation is completed.
Here is the documentation, see in the Response Syntax

Recurly API returning 500 error

I am following the example code snippets the one in the right panel here. So I have a Recurly token and am trying to start a subscription using it.
subscription = Subscription()
subscription.plan_code = 'monthly'
subscription.currency = 'USD'
account = Account(account_code='1a')
account.email = 'mark#example.com'
account.first_name = 'mark'
account.last_name = 'lname'
billing_info = BillingInfo()
billing_info.number = '4111-1111-1111-1111'
billing_info.month = 1
billing_info.year = 2019
account.billing_info = billing_info
subscription.account = account
subscription.save()
I get error 500 when the code above runs. If I comment out subscription.save() the logs show ParseError: mismatched tag: line 6, col 2 which seems like xml parsing error. I get no error(but of course I presume the subscription is not being saved). Could this error be as a result of testing many times? or what could be the issue? am using sandbox.
My bad. I was missing recurly.SUBDOMAIN together with recurly.RECURLY_API_KEY settings. All save() methods for recurly.Subscription(), recurly.BillingInfo(), recurly.Account() were throwing the error when called.

Getting issue comments JIRA python

I am trying to get all comments of issues created in JIRA of a certain search query. My query is fairly simple:
import jira
from jira.client import JIRA
def fetch_tickets_open_yesterday(jira_object):
# JIRA query to fetch the issues
open_issues = jira_object.search_issues('project = Support AND issuetype = Incident AND \
(status = "Open" OR status = "Resolved" OR status = "Waiting For Customer")', maxResults = 100,expand='changelog')
# returns all open issues
return open_issues
However, if I try to access the comments of tickets created using the following notation, I get a key error.
for issue in issues:
print issue.raw['fields']['comment']
If I try to get comments of a single issue like below, I can access the comments:
single_issue = jira_object.issue('SUP-136834')
single_issue.raw['fields']['comment']
How do I access these comments through search_issues() function?
The comment field is not returned by the search_issues method you have to manually state the fields that must be included by setting the corresponding parameter.
just include the 'fields' and 'json_result' parameter in the search_issue method and set it like this
open_issues = jira_object.search_issues('project = Support AND issuetype = Incident AND \
(status = "Open" OR status = "Resolved" OR status = "Waiting For Customer")', maxResults = 100,expand='changelog',fields = 'comment',json_result ='True')
Now you can access the comments without getting keytype error
comm=([issue.raw['fields']['comment']['comments'] for issue in open_issues])
I struggled with the same issue. Assuming "issue" is an object of type Issue, and "jira" is an object of type JIRA, according to http://jira.readthedocs.org/en/latest/#issues
issue.fields.comment.comments
should work, but the fields object does not have any key "comment".
The other option mentioned there works for me:
jira.comments(issue)
So, for it to work you use the issues from your search result and call jira.comments. E.g.
issues = jira.search_issues(query)
comments = jira.comments(issues[index])
(My version of the library is 1.0.3, python 2.7.10)
from jira import JIRA
Jira = JIRA('https://jira.atlassian.com')
issue_num = "ISSUE-123"
issue = Jira.issue(issue_num)
comments = issue.fields.comment.comments
for comment in comments:
print("Comment text : ",comment.body)
print("Comment author : ",comment.author.displayName)
print("Comment time : ",comment.created)

couchdb-python change notifications

I'm trying to use couchdb.py to create and update databases. I'd like to implement notification changes, preferably in continuous mode. Running the test code posted below, I don't see how the changes scheme works within python.
class SomeDocument(Document):
#############################################################################
# def __init__ (self):
intField = IntegerField()#for now - this should to be an integer
textField = TextField()
couch = couchdb.Server('http://127.0.0.1:5984')
databasename = 'testnotifications'
if databasename in couch:
print 'Deleting then creating database ' + databasename + ' from server'
del couch[databasename]
db = couch.create(databasename)
else:
print 'Creating database ' + databasename + ' on server'
db = couch.create(databasename)
for iii in range(5):
doc = SomeDocument(intField=iii,textField='somestring'+str(iii))
doc.store(db)
print doc.id + '\t' + doc.rev
something = db.changes(feed='continuous',since=4,heartbeat=1000)
for iii in range(5,10):
doc = SomeDocument(intField=iii,textField='somestring'+str(iii))
doc.store(db)
time.sleep(1)
print something
print db.changes(since=iii-1)
The value
db.changes(since=iii-1)
returns information that is of interest, but in a format from which I haven't worked out how to extract the sequence or revision numbers, or the document information:
{u'last_seq': 6, u'results': [{u'changes': [{u'rev': u'1-9c1e4df5ceacada059512a8180ead70e'}], u'id': u'7d0cb1ccbfd9675b4b6c1076f40049a8', u'seq': 5}, {u'changes': [{u'rev': u'1-bbe2953a5ef9835a0f8d548fa4c33b42'}], u'id': u'7d0cb1ccbfd9675b4b6c1076f400560d', u'seq': 6}]}
Meanwhile, the code I'm really interested in using:
db.changes(feed='continuous',since=4,heartbeat=1000)
Returns a generator object and doesn't appear to provide notifications as they come in, as the CouchDB guide suggests ....
Has anyone used changes in couchdb-python successfully?
I use long polling rather than continous, and that works ok for me. In long polling mode db.changes blocks until at least one change has happened, and then returns all the changes in a generator object.
Here is the code I use to handle changes. settings.db is my CouchDB Database object.
since = 1
while True:
changes = settings.db.changes(since=since)
since = changes["last_seq"]
for changeset in changes["results"]:
try:
doc = settings.db[changeset["id"]]
except couchdb.http.ResourceNotFound:
continue
else:
// process doc
As you can see it's an infinite loop where we call changes on each iteration. The call to changes returns a dictionary with two elements, the sequence number of the most recent update and the objects that were modified. I then loop through each result loading the appropriate object and processing it.
For a continuous feed, instead of the while True: line use for changes in settings.db.changes(feed="continuous", since=since).
I setup a mailspooler using something similar to this. You'll need to also load couchdb.Session() I also use a filter for only receiving unsent emails to the spooler changes feed.
from couchdb import Server
s = Server('http://localhost:5984/')
db = s['testnotifications']
# the since parameter defaults to 'last_seq' when using continuous feed
ch = db.changes(feed='continuous',heartbeat='1000',include_docs=True)
for line in ch:
doc = line['doc']
// process doc here
doc['priority'] = 'high'
doc['recipient'] = 'Joe User'
# doc['state'] + 'sent'
db.save(doc)
This will allow you access your doc directly from the changes feed, manipulate your data as you see fit, and finally update you document. I use a try/except block on the actual 'db.save(doc)' so I can catch when a document has been updated while I was editing and reload the doc before saving.

Categories