I'm trying to create a Recurly account using their python API, and keep hitting the same error:
def upsert_recurly_account(office):
try:
account = recurly.Account.get(office.pk)
except recurly.errors.NotFoundError:
logger.warning("Creating new recurly account for pk %s" % office.pk)
account = recurly.Account(account_code=office.pk)
else:
logger.info("Recurly account %s already exists, we will update it")
account.email = office.manager.email
account.first_name = office.manager.first_name
account.last_name = office.manager.last_name
account.company_name = '%s - %s' % (office.legal_name, office.name)
account.vat_number = office.tax_id
account.tax_exempt = office.tax_exempt
billing_info = recurly.BillingInfo()
billing_info.first_name = office.manager.first_name
billing_info.last_name = office.manager.last_name
billing_info.address1 = office.address1
billing_info.address2 = office.address2
billing_info.city = office.city
billing_info.country = office.country
billing_info.zip = office.postal_code
billing_info.phone = office.phone
billing_info.vat_number = office.tax_id
account.billing_info = billing_info
account.save()
The error I'm getting is:
ValidationError:required: account.number is required
Manually adding
account.number = 1234
Doesn't solve the problem.
Any ideas?
Since you're creating a new Account with nested billing info you need to provide a valid credit card number in the billing_info hash like so:
billing_info.number = 123
There are other mandatory fields (like month and year) when creating a new account with nested billing info. Please read the docs
Account.number isn't a valid Recurly field - it looks like you need to be passing through account_code - see the sample at https://docs.recurly.com/api/accounts#create-account
Related
TLDR; I am running an Algorand PrivateNet in a sandbox. I would like to know how I can use the Python SDK for Algorand to return the address and balance of the accounts on this network.
Longer version;
Until now I have been using "./sandbox goal account list" to find the account addresses and account balances in Bash, this returns:
[offline]
I3CMDHG236HVBDMCKEM22DLY5L2OJ3CBRUDHG4PVVFGEZ4QQR3X3KNHRMU
I3CMDHG236HVBDMCKEM22DLY5L2OJ3CBRUDHG4PVVFGEZ4QQR3X3KNHRMU
8012889074131520 microAlgos
[offline]
3NSWKJTYMW3PSZZDIE6NCHMRTOZ24VY5G3OJNDSTYRVRXMZBZVPCGQHJJI
3NSWKJTYMW3PSZZDIE6NCHMRTOZ24VY5G3OJNDSTYRVRXMZBZVPCGQHJJI
1001611000000000 microAlgos
[online]
5KLSI3AHMBBDALXBEO2HEA3PBBCBAYT4PIHCD3B25557WGWUZGRTQETPHQ
5KLSI3AHMBBDALXBEO2HEA3PBBCBAYT4PIHCD3B25557WGWUZGRTQETPHQ
100000 microAlgos
I have tried to utilise the algod and v2client.indexer modules as outlined below but instead of the 3 accounts listed above 4 are being listed by my code (the original 3 +1). The code:
#imports
from algosdk import algod, v2client
# instatiate AlgodClient
def connect_to_network():
algod_address = "http://localhost:4001"
algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
algod_client = algod.AlgodClient(algod_token, algod_address)
return algod_client
# instantiate IndexClient
def indexer():
indexer_token = ""
indexer_address = "http://localhost:8980"
indexer_client = v2client.indexer.IndexerClient(indexer_token, indexer_address)
return indexer_client
# returns all account details from indexer
def account_details():
raw_details = indexer().accounts() # <-- I think the error is here because this returns 4 addresses.
account_details = []
for details in raw_details["accounts"]:
account_details.append({"address":details["address"], "amount": details["amount"]})
return account_details
# returns the amount in each account
def account_amounts(account_address):
return connect_to_network().account_info(account_address)
# returns account address and amount for each account
for detail in account_details():
print(account_amounts(detail["address"])["address"])
print(account_amounts(detail["address"])["amount"])
This returns:
I3CMDHG236HVBDMCKEM22DLY5L2OJ3CBRUDHG4PVVFGEZ4QQR3X3KNHRMU
8013089091731545
NTMTJYBQHWUXEGVG3XRRX5CH6FCYJ3HKCSIOYW4DLAOF6V2WHSIIFMWMPY
1001636000000000
3NSWKJTYMW3PSZZDIE6NCHMRTOZ24VY5G3OJNDSTYRVRXMZBZVPCGQHJJI
1001636000000000
5KLSI3AHMBBDALXBEO2HEA3PBBCBAYT4PIHCD3B25557WGWUZGRTQETPHQ
100000
How can I replicate "./sandbox goal account list" with py-algorand-sdk?
(Bonus question) what is this extra mystery "account" that appears when I use the SDK compared to Bash?
The issue above arose because like with ./sandbox goal accounts listI was trying to return the accounts I had keys for locally in the KMD but my call to the indexer raw_details = indexer().accounts() was returning all accounts on the network.
To remedy this, instead of importing and using the v2client.indexer module import the wallet module from the algosdk library. These are the necessary imports:
from algosdk import algod, kmd, wallet
Then set up the connections to algod, kmd, and your wallet:
# instatiate AlgodClient
def connect_to_network():
algod_address = "http://localhost:4001"
algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
algod_client = algod.AlgodClient(algod_token, algod_address)
return algod_client
# instantiate KMDClient <--- this is used as a parameter when instantiating the Wallet Class.
def key_management():
kmd_address = "http://localhost:4002"
kmd_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
kmd_client = kmd.KMDClient(kmd_token, kmd_address)
return kmd_client
#get wallet details
def wallet_details():
wallet_name = 'unencrypted-default-wallet'
password = ""
kmd_client = key_management()
return wallet.Wallet(wallet_name, password, kmd_client)
You can now return the account addresses held locally in the KMD:
keys = wallet_details().list_keys()
Now that you have the addresses you can query use the algod client to return the amount of (Micro) Algo held at each of these addresses.
Summary of the requirement :
To access emails from a specific folder in Outlook within a user given date range,
ex: all mails from June or all mails from 23-June-2020 to 15-July-2020
So far we have tried the following but the issues are :
Date range is not giving correct output
It is taking too long to give output, also sometimes returning with a timeout error.
The Code:
from exchangelib import Credentials, Account, DELEGATE, Configuration, IMPERSONATION, FaultTolerance,EWSDateTime,EWSTimeZone,Message
import datetime
import pandas as pd
new_password = "your password"
credentials = Credentials(username = 'username', password = new_password)
config = Configuration(server ='outlook.office365.com', credentials = credentials)
account = Account(primary_smtp_address ='username', credentials = credentials, autodiscover = False, config = config, access_type = DELEGATE)
#first approach.....................................
conversation_id = []
datetime_received = []
has_attachment = []
Senders = []
for i in account.inbox.all().order_by('-datetime_received')[:40]:
if isinstance(i, Message):
if i.datetime_received:
if ((i.datetime_received).year == 2020):
if ((i.datetime_received).month == 7):
if i.conversation_id:
print("conversation id: ", i.conversation_id.id)
conversation_id.append(i.conversation_id.id)
if not i.conversation_id:
conversation_id.append("Not available")
if i.sender:
print("Sender name : ", i.sender.name)
Senders.append(i.sender.name)
if not i.sender:
Senders.append("not available")
if i.datetime_received:
print("Time : ", i.datetime_received.date)
datetime_received.append(i.datetime_received.date)
if not i.datetime_received:
datetime_received.append("not available")
if i.has_attachments:
print("Has attachment: ", i.has_attachments)
has_attachment.append(i.has_attachments)
if not i.has_attachments:
has_attachment.append("not available")
# second approach.....................................................................
items_for_2019 = account.inbox.filter(start__range=(
tz.localize(EWSDateTime(2019, 8, 1)),
tz.localize(EWSDateTime(2020, 1, 1))
))
for i in items_for_2019:
print("")
#third approach.........................................................................
for item in account.inbox.filter(datetime_received__range=(tz.localize(EWSDateTime(2019, 8, 1)),tz.localize(EWSDateTime(2020, 1, 1)))):
print(item.sender.name)
first approach is working for specific month but extremely slow
second and third approach giving wrong output
A little guidance would be highly appreciated.
The start field belongs to CalendarItem. It is not a valid field for Message objects. That's why your 2nd approach does not work.
Your 3rd approach should work. Which output do you see, and what did you expect?
If your queries are taking a long time, try to limit the fields you are fetching for each item, by using the .only() QuerySet method.
As I'm not able to understand via documentation, please help in where do I enter the email id and password if I want to use test.py as an example.
from gpapi.googleplay import GooglePlayAPI, RequestError
import sys
import argparse
ap = argparse.ArgumentParser(description='Test download of expansion files')
ap.add_argument('-e', '--email', dest='email', help='google username')
ap.add_argument('-p', '--password', dest='password', help='google password')
args = ap.parse_args()
server = GooglePlayAPI('it_IT', 'Europe/Rome')
# LOGIN
print('\nLogging in with email and password\n')
server.login(args.email, args.password, None, None)
gsfId = server.gsfId
authSubToken = server.authSubToken
print('\nNow trying secondary login with ac2dm token and gsfId saved\n')
server = GooglePlayAPI('it_IT', 'Europe/Rome')
server.login(None, None, gsfId, authSubToken)
# SEARCH
apps = server.search('telegram', 34, None)
print('\nSearch suggestion for "fir"\n')
print(server.searchSuggest('fir'))
print('nb_result: 34')
print('number of results: %d' % len(apps))
print('\nFound those apps:\n')
for a in apps:
print(a['docId'])
I re-wrote some of it, modernized it (Python 3.7), and used global variables instead of system args (command line). I commented it best I could using the GitHub page given and the source code.
from gpapi.googleplay import GooglePlayAPI
# Create global variables for easy settings change and use.
LOCALE = "us_US"
TIMEZONE = "America/Chicago"
MAX_RESPONSE = 34
APP_NAME = "Super Fun Game"
EMAIL = "test#gmail.com"
PASSWORD = "stackoverflow5"
# Create instance of API with ( locale, time zone )
server = GooglePlayAPI(locale = LOCALE, timezone = TIMEZONE)
# Login using just username and password.
print("\nTrying log in with just email and password\n")
server.login(email = "abc123babyYouandMe#gmail.com", password = "jaksun5")
gsfId = server.gsfId
authSubToken = server.authSubToken
# Now that we've been authorized once, we can use the gsfID and token previously
# generated to create a new instance w/o email or password.
print("\nTrying secondary login with ac2dm token and gsfId saved...\n")
server = GooglePlayAPI(locale = LOCALE, timezone = TIMEZONE)
server.login(gsfId = gsfId, authSubToken = authSubToken)
# Search the Play Store using `search` function
# First: Search query for the Play Store.
# Specify the maximum amount of apps that meet criteria that can be returned.
# Third param is `offset`. Determines if you want to start at a certain
# index in the returned list. Default is `None`.
apps = server.search(query = APP_NAME, nb_result = MAX_RESPONSE)
# Get the suggested search options from our desired app name
print("Search Suggestions for `%s`:" % APP_NAME)
print(server.searchSuggest(APP_NAME))
# Print our max limit and then the actual amount returned
print("Max #of Results: %i" % MAX_RESPONSE)
print("Actual #of Results: %d" % len(apps))
# if at least 1 app found, then print out its ID.
if len(apps) > 0:
print("Found apps: ")
# each app acts as a Dictionary
for _app in apps:
print("App[docID]: %s" % app["docId"])
PS: Stick to PEP 8 for coding styles, conventions, naming, etc. Since you're just starting off, it will come in handy for coding your own programs and understanding others.
Resources
List of Locales
List of Time Zones
I'm trying to be able to set a custom fields in NetSuite using webservices.
The WSDL I'm using is: https://webservices.netsuite.com/wsdl/v2017_2_0/netsuite.wsdl
Currently I'm testing it on creating a customer. Here's what I have so far:
def add_customer():
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
Customer = client.get_type('ns13:Customer')
customer = Customer(
companyName='TEST',
subsidiary = RecordRef(internalId='5', type='subsidiary')
)
response = client.service.add(customer)
print(response)
add_customer()
This Works perfectly, but now I'm trying to set a custom field with id custfield1
After doing some searching, I found:
http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_2/schema/other/customfieldlist.html?mode=package
From this link I know that I'll be needing to use CustomFieldRef, I'm just not sure how it would be implemented.
I found a way to do this:
def add_customer():
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
StringCustomFieldRef = client.get_type('ns0:StringCustomFieldRef') #StringCustomFieldRef
CustomFieldList = client.get_type('ns0:CustomFieldList') #To go from object to list
#Cust field 1
acctName = StringCustomFieldRef()
acctName.internalID = '1569'
acctName.scriptId = 'custentity_account_name'
acctName.value = 'testData'
#custField2
acctID= StringCustomFieldRef()
acctID.internalId= '1596'
acctID.scriptId= 'custentity_sf_account_id'
acctID.value = 'FIELD DATA'
Customer = client.get_type('ns13:Customer')
customer = Customer(
companyName='TEST',
entityId='TEST ID',
subsidiary = RecordRef(internalId='5', type='subsidiary'),
customFieldList = CustomFieldList([acctID,acctName]) #List of cust objects
)
response = client.service.add(customer)
print(response)
add_customer()
You have to use the Ref type for the field you are working with: https://system.na1.netsuite.com/app/help/helpcenter.nl?fid=section_n3458179.html
Hi I have below setup.
Django 1.9,
mongoDB,
pymongo 2.7,
mongoengine 0.9
I have written an API to store logs at backend server userwise. Below is sample of table
user subject registered changed_on
abc eng Y "2018-04-18T00:00:00Z"
abc maths N "2018-04-18T00:10:00Z"
xyz eng Y "2018-04-18T00:10:00Z"
I also have read API for this in which we give user name and timestamp for filter like below:
{
"user" : "abc",
"from_date" : "2018-04-18T00:00:00Z"
}
The line in serializers.py which is applying filter is
Logs.objects.filter(user__iexact='abc',changed_on__gte=from_date)
Now Sometimes when I add new log and retrieve it from postman, it is not working. I have to restart django server and then it gives me newly added row.
I dont understand why this is happening.
EDIT1 : Full Serializer.py
from rest_framework import serializers
class GetUserLogs(serializers.Serializer):
user = serializers.CharField(label=_("USER"))
token = serializers.CharField(label=_("Token"))
from_date = serializers.CharField(label=_('From date'), default="")
till_date = serializers.CharField(label=_('Till date'), default=datetime.datetime.now().isoformat().split(".")[0]+'Z')
def validate(self, attrs):
user = attrs.get('user')
token = attrs.get('token')
from_date = attrs.get('from_date')
if user:
tokendetails = validate_token(token)
if not tokendetails:
msg = _('Invalid token.')
raise serializers.ValidationError(msg)
else:
userdetails = tokendetails.user
if userdetails.check_user(user):
rows = Logs.objects.all().filter(user__iexact=user,changed_on__gte=from_date, changed_on__lte = till_date)
print(len(rows))
else:
msg = _('Invalid USER)
raise serializers.ValidationError(msg)
else:
msg = _('Must include "USER".')
raise serializers.ValidationError(msg)
attrs['rows'] = rows
return attrs
So After a lot of debugging for almost a day, I found that the default value of till_date that we are setting to current timestamp of system is not increasing as time increase. So I changed default value to empty string and added below code after reading value of till_date.
if till_date == "":
till_date = datetime.datetime.now().isoformat().split(".")[0]+'Z'
It will reset the till_date value to current timestamp every time its value is missing.
Hope it will help someone someday.