'module' object has no attribute 'HTTPSConncetion' - python

Hi I have the following code but am getting an error that the module object has no attribute HTTPSConnection:
from ecomstore import settings
import httplib
import urllib
def do_auth_capture(amount='0.00', card_num=None, exp_date=None, card_cvv=None):
delimiter = '|'
raw_params = {
'x_login':settings.AUTHNET_LOGIN,
'x_tran_key':settings.AUTHNET_KEY,
'x_type':'AUTH_CAPTURE',
'x_amount':amount,
'x_version':'3.1',
'x_card_num':card_num,
'x_exp_date':exp_date,
'x_delim_char':delimiter,
'x_relay_response':'FALSE',
'x_delim_data':'TRUE',
'x_card_code':card_cvv
}
params = urllib.urlencode(raw_params)
headers = {'content-type':'application/x-www-form-urlencoded',
'content-length':len(params)}
post_url = settings.AUTHNET_POST_URL
post_path = settings.AUTHNET_POST_PATH
cn = httplib.HTTPSConncetion(post_url,httplib.HTTPS_PORT)
cn.request('POST',post_path, params, headers)
return cn.getresponse().read().split(delimiter)
Is there a reason this is happening?

cn = httplib.HTTPSConncetion(post_url,httplib.HTTPS_PORT)
You've misspelled "Connection".

Related

im grtting an error called (send_login_otp failure - module 'requests' has no attribute 'post4')

first i taut i have multiple file usig same name but i anable to find the file so, i tried using create new virtual env but i got same error .even i tried to upgrade the package but noting works .
here is my code
import requests
def verify_totp(request_key, totp):
try:
payload = {
"request_key": request_key,
"otp": totp
}
result_string = requests.post4(url=URL_VERIFY_TOTP, json=payload)
if result_string.status_code != 200:
return [ERROR, result_string.text]
result = json.loads(result_string.text)
request_key = result["request_key"]
return [SUCCESS, request_key]
It should be requests.post not requests.post4
Also check your try block and indentation.
def verify_totp(request_key, totp):
# you can avoid the use of a `try except`block if you don't use it
payload = {
"request_key": request_key,
"otp": totp
}
result_string = requests.post(url=URL_VERIFY_TOTP, json=payload)
if result_string.status_code != 200:
return ["ERROR", result_string.text]
result = json.loads(result_string.text)
request_key = result["request_key"]
return ["SUCCESS", request_key]
request_key = "<INSERT YOUR REQUEST KEY HERE>"
totp = "<INSERT YOUR TOTP HERE>"
request_status, request_key = verify_totp(request_key, totp)
print(request_status, request_key)

AWS Lambda Boto3 python - filter expression on dynamodb table throw error "errorMessage": "name 'Attr' is not defined",

I am using a filter on dynamodb table. it throws error the following error.
Boto3 documentation shows response = table.scan(FilterExpression=Attr('myattribute').eq('myvalue')
I did same thing. I want items in this table where the agentRole = Receiver
Response
{
"errorMessage": "name 'Attr' is not defined",
"errorType": "NameError",
"requestId": "1b2fbee6-5fa2-4951-8689-3d1bfec76e5c",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 21, in lambda_handler\n
response = tableresource.scan(FilterExpression=Attr('agentRole').eq('Receiver'))\n"
]
}
This is the code:
import json
import os
import boto3
from pprint import pprint
#Find records that has agentRole as 'Receiver'
tableName = os.environ.get('TABLE')
fieldName = os.environ.get('FIELD')
keytofind = os.environ.get('FILTER')
fieldname = "agentRole"
dbclient = boto3.resource('dynamodb')
def lambda_handler(event, context):
tableresource = dbclient.Table(tableName)
count = tableresource.item_count
response = tableresource.scan(FilterExpression=Attr('agentRole').eq('Receiver'))
from boto3.dynamodb.conditions import Attr

python function says " no attribute in function"

I am running below proecedure to get some values so that i use those values later in main program globally
import requests
import json
import sys
client= 'test'
def get_path(client):
headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()}
URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+client
response=requests.get(URL,headers=headers)
jout = json.loads(response.text)
azure_path=jout['data']['account_id']
get_path.tenant_id=jout['data']['tenant_id']
return azure_path
tenant = ('tenant is :' + get_path(client).tenant_id)
print(tenant)
but its erroring saying there is no attribute
tenant = ('tanant is :' + get_path.tenant_id(client))
AttributeError: 'function' object has no attribute 'tenant_id'
I am sure it has value when i print variable called jout it does have tenant id
EDIT 1: Solved it by below
import requests
import json
import sys
client= 'test'
tenant_var = None
def get_path(client):
global tenant_var
headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()}
URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+client
response=requests.get(URL,headers=headers)
jout = json.loads(response.text)
azure_path=jout['data']['account_id']
tenant_var=jout['data']['tenant_id']
return azure_path
tenant = ('tenant is :' + tenant_var)
print(tenant)
In your function, you are setting tenant_id as attribute of your function object get_path... it's a rather strange way of coding.
To make this work, you can adapt the following snippet:
def get_path(arg):
get_path.tenant_id = '123' + arg
return 'something else'
# get the function object
myfunction = get_path
# call the function
myfunction('myargument')
# consume the function object attribute
tenant = ('tenant is :' + myfunction.tenant_id)
Or the better way: as suggested in the comments, return the tenant_id as part of a tuple in the return value of your function.
Solved it by using global variable deceleration
import requests
import json
import sys
client= 'test'
tenant_var = None
def get_path(client):
global tenant_var
headers = {'Content-Type': 'application/json', 'X-Vault-Token': get_token()}
URL='https://xxxxxxxx.xxx/v1/'+'ab/li/'+client
response=requests.get(URL,headers=headers)
jout = json.loads(response.text)
azure_path=jout['data']['account_id']
tenant_var=jout['data']['tenant_id']
return azure_path
tenant = ('tenant is :' + tenant_var)
print(tenant)

Parsing json GitHub api with Python

Having difficulty parsing json from GitHub api. I'm trying to populate a team with all the repos from an organisation. I'm using myteamname to obtain the teamid required for the loop which populates the team with the repo names.
import json
import requests
mytokenid = "xxx"
myorg = "xxx"
myteamname = "xxx"
headers = {
'Authorization': 'token %s' % mytokenid,
}
response = requests.get('https://api.github.com/orgs/{0}/teams/{1}'.format(myorg, myteamname), headers=headers)
teamidjson = json.loads(response.text)
myteamid = teamidjson(['id'])
g = Github(tokenid)
for repo in g.get_organization(myorg).get_repos():
myreponame = repo.name
response = requests.put('https://api.github.com/teams/{0}/repos/{1}/{2}'.format(myteamid, myorg, myreponame), headers=headers)
I get this error message
File "githubteam.py", line 74, in <module>
myteamid = teamidjson(['id'])
TypeError: 'dict' object is not callable
myteamid = teamidjson(['id'])
That seems to be causing the error. The correct way to access the id key is:
myteamid = teamidjson['id']
I think you meant
myteamid = teamidjson['id']
# you can also use this
myteamid = teamidjson.get('id', None) # it will default to None if id doesn't exist...

How to Add XML Element Types using Python Suds Client

I have been having trouble figuring out how to add element types using a Suds factory. My code is below:
from xml.etree import cElementTree as ElementTree
from suds.client import Client
from suds.wsse import *
from suds.sax.text import Raw
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
username = 'username#tenant'
password = 'password'
url = 'https://wd2-impl-
services1.workday.com/ccx/service/[tenant]/Revenue_Management/v31.1?wsdl'
client = Client(url, username = username, password = password, faults = False)
CustomerObjectType = client.factory.create('ns0:CustomerObjectType')
CustomerObjectType.ID = 'CUS3466'
FinancialsBusinessProcess = client.factory.create('ns0:Financials_Business_Process_ParametersType')
FinancialsBusinessProcess.Auto_Complete = 'true'
CustomerData = client.factory.create('ns0:Customer_WWS_DataType')
CustomerData.Customer_Name = 'Test'
CustomerData.Worktag_Only = 'false'
CustomerData.Submit = 'true'
CustomerData.Payment_Terms_Reference.ID = ['NET30', 'Customer_ID']
CustomerData.Default_Payment_Type_Reference.ID = ['PTY_CHECK', 'Payment_Terms_ID']
CustomerData.Included_Children_Reference = ['CUS3029', 'Customer_ID']
CustomerData.Business_Entity_Data.Business_Entity_Name = 'Test'
security = Security()
token = UsernameToken(username, password)
security.tokens.append(token)
client.set_options(wsse=security)
client.service.Submit_Customer('true', CustomerObjectType, FinancialsBusinessProcess, CustomerData)
The error I am receiving is:
ERROR:suds.client:<suds.sax.document.Document instance at 0x10eb0e488>
With the output:
DEBUG:suds.client:headers = {'SOAPAction': '""', 'Content-Type': 'text/xml; charset=utf-8'}
DEBUG:suds.client:HTTP failed - 500 - Internal Server Error:
<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope xmlns:SOAP ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wd="urn:com.workday/bsvc">
<faultcode>SOAP-ENV:Client.validationError</faultcode>
<faultstring>Validation error occurred. Element 'ID' is missing attribute 'type'</faultstring>
<detail>
<wd:Validation_Fault>
<wd:Validation_Error>
<wd:Message>Element 'ID' is missing attribute 'type'</wd:Message>
<wd:Detail_Message>Element 'ID' is missing attribute 'type'</wd:Detail_Message>
<wd:Xpath>/ns0:Submit_Customer_Request[1]/ns0:Customer_Data[1]/ns0:Payment_Terms_Reference[1]/ns0:ID[2]</wd:Xpath>
</wd:Validation_Error>
</wd:Validation_Fault>
</detail>
</SOAP-ENV:Fault>
The formatting given back by the suds factory for the "Payment_Terms_Reference" element is as follows:
Payment_Terms_Reference =
(Payment_TermsObjectType){
ID[] =
"NET30",
"Customer_ID",
_Descriptor = ""
}
Where I am confused is that it looks like it is using the index
Payment_Terms_Reference[1]/ns0:ID[2]
to find the element type, but when I add more data to the list in the complex object type it doesn't solve the problem.
The current XML code that spits out for Payment_Terms_Reference when I run this code comes out as:
<ns0:Payment_Terms_Reference>
<ns0:ID>PTY_CHECK</ns0:ID>
<ns0:ID>Payment_Terms_ID</ns0:ID>
</ns0:Payment_Terms_Reference>
But I think I need it to format like:
<ns0:Payment_Terms_Reference>
<ns0:ID ns0:type="Payment_Terms_ID">ID</ns0:ID>
</ns0:Payment_Terms_Reference>
If anyone knows what might help me solve this problem, that would be much appreciated.
Thanks!
You need to create a factory for the Payment_TermsObjectType
paymenttype = client.factory.create('ns0:Payment_TermsObjectIDType')
paymenttype._type = "PTY_CHECK"
paymenttype.value = "Payment_Type_ID"
CustomerData.Payment_Terms_Reference.ID = paymenttype

Categories