why is Exact Target FUEL SDK not validating my API keys? - python-2.7

I am working with the FUEL SDK for Exact Target API. I have setup my enviorment variables but the app keeps denying me data, and throws the following error message
raise Exception('Unable to validate App Keys(ClientID/ClientSecret) provided: ' + repr(r.json()))
Exception: Unable to validate App Keys(ClientID/ClientSecret) provided: {u'errorcode': 1, u'message': u'Unauthorized', u'documentation': u''}
I am looking in the client, but do not see why the authentication would be stopping. here is my code:
import os
os.environ["FUELSDK_CLIENT_ID"] = ""
os.environ["FUELSDK_CLIENT_SECRET"] = ""
os.environ["FUELSDK_DEFAULT_WSDL"] = "https://webservice.exacttarget.com/etframework.wsdl"
os.environ
["FUELSDK_AUTH_URL"] = "https://auth.exacttargetapis.com/v1/requestToken?legacy=1"
#os.environ["FUELSDK_WSDL_FILE_LOCAL_LOC"] = "C:\Users\Aditya.Sharma\AppData\Local\Temp\ExactTargetWSDL.s6.xml"
# Add a require statement to reference the Fuel SDK's functionality:
import FuelSDK
# Next, create an instance of the ET_Client class:
myClient = FuelSDK.ET_Client()
# Create an instance of the object type we want to work with:
list = FuelSDK.ET_List()
# Associate the ET_Client to the object using the auth_stub property:
list.auth_stub = myClient
# Utilize one of the ET_List methods:
response = list.get()
# Print out the results for viewing
print 'Post Status: ' + str(response.status)
print 'Code: ' + str(response.code)
print 'Message: ' + str(response.message)
print 'Result Count: ' + str(len(response.results))
print 'Results: ' + str(response.results)
Could someone please tell me why I am being shut out?
here is git repository I am using: https://github.com/salesforce-marketingcloud/FuelSDK-Python
Thank you in advance.

Update Client KEY/PWD in client.py

Related

Tensorboard Error - NameError: name 'tensorboard' is not defined

I am now learning tensorflow but am unable to get tensorboard to work. I tried the simple program below with no luck. The program works before I use the tensorboard code but when I use the tensorboard code I get the following error:
NameError: name 'tensorboard' is not defined
Please any assistance is apppreciated.
import tensorflow as tf
a = tf.constant(5, name="input_a")
b = tf.constant(3, name="input_a")
c = tf.multiply(a,b, name="mul_c")
d = tf.add(a,b, name="add_d")
e = tf.add(c,d, name="add_e")
sess = tf.Session()
sess.run(e)
output = sess.run(e)
writer = tf.summary.FileWriter('/tmp/newtest', graph=sess.graph)
print(sess.run(e))
tensorboard --logdir /tmp/newtest
I believe this is already 'answered', but, to give a sample of what I did, regarding this, and I hope it helps you or others.
This is just covering ending overhead of triggering & showing tensorboard.
import subprocess
import webbrowser
import time
logLocation = 'tflearn_logs'
print("\r\nWould you like to see the visual results (y/N)? ", end='', flush=True)
answer = input()
if answer.strip().lower() == "y":
port = str(8018)
print("Starting Tensorboard to visualize... ")
process = subprocess.Popen(['tensorboard', "--logdir='" + logLocation + "'", '--port=' + port])
# Wait for a few seconds, give the tensorboard a headstart
time.sleep(5)
print("Opening Tensorboard webpage... ")
url = 'http://127.0.0.1:' + port + '/'
# Path differs per OS (Windows, Linux, iOS)
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
print("Press enter to quit... ", end='', flush=True)
answer = input()
if process is not None:
process.kill()

Paramiko SSH - Multiple Authentication Credentials with Python

I have the following code:
import paramiko
import time
import re
import sys
import random
import fileinput
ip_address = raw_input("Enter a valid WAP IP: ")
#Open SSHv2 connection to devices
def open_ssh_conn(ip):
try:
#Logging into device
session = paramiko.SSHClient()
#AutoAddPolicy
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#Passing the necessary
session.connect(ip, username = 'myUsername', password = 'myPassword')
#Start an interactive shell session on the switch
connection = session.invoke_shell()
#Commands
connection.send("enable\n")
time.sleep(1)
connection.send("show version\n")
time.sleep(1)
#Checking command output for IOS syntax errors
output = connection.recv(65535)
#Checking command output for IOS Syntax errors
if re.search(r"% Invalid input detected at", output):
print "* There was at least one IOS syntax error on device %s" % ip
else:
print "\nDONE for device %s" % ip
#Test for reading command output
print output + "\n"
#Closing the connection
session.close()
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check
the username/password file or the device configuration!"
print "* Closing program...\n"
#Calling the SSH function
open_ssh_conn(ip_address)
How can I test multiple credential without getting kick out of the program when an exception is caught?
for example, try this new credentials:
session.connect(ip, username = 'myNewUsername', password = 'myNewPassword')
I figured it out! I created a nested list with the credentials:
list = [['username1', 'password1'], ['username2', 'password2'], \
['username3', 'password3']]
Then, created a for loop and put my code inside:
for elem in list:
my code...
# this is the connect line:
session.connect(ip, username = elem[0], password = elem[1])
That did it!!!!

Indent or sequencing problems with python

I am new to python and have probably started with something a little complicated. Nevertheless I am nearly there.
My problem is I am having a bit of difficulty understanding how to group, or sequence a group of statements in my code (my syntax is probably wrong as well) using try and except or if, elsif and else. I really just need someone to say I should be using this instead of that and I can figure it out from there.
Here is a diagram of what I am trying to accomplish:
https://drive.google.com/file/d/0BxtxgkV8mylgSFRuMnZtaEpXLVE/view?usp=sharing
And here is my code so far (please note this is my FIRST python program - actually first program of any sort - so I would appreciate it if you would not tear me apart too badly for any formatting or syntax errors - updated to include Johns fix)
import ldap
import os
import subprocess
import uuid
from pwd import getpwnam
# Lookup all the users in the cloud group
path='dc=saao'
l=ldap.open('ldap1.cape')
l.protocol_version = ldap.VERSION3
l.simple_bind('dc=cape')
a=l.search_s(path,ldap.SCOPE_SUBTREE,'cn=cloudcape')
# Add members to uids
uids=a[0][1]['memberUid']
# Check if a bindmount already exists or it not, that each cloud group user has the required directory i.e. /home/USER/cloud and /var/www/owncloud/data/USER/files
for uid in uids:
cloudfiledir="/var/www/owncloud/data/"+uid+"/files"
clouddir="/home/"+uid+"/cloud"
try:
subprocess.check_output(["mountpoint", cloudfiledir])
# If the output is all good, their bind mount is setup and mounted
break
except:
print uid+" has not logged into ownCloud yet - please ask them to do so and then try again"
break
# Now check if they have the required directories
try:
if os.path.isdir(cloudfiledir):
print "user "+ uid +" has a data directory in the owncloud data directory- this is good."
if os.path.isdir("/home/"+uid+"/cloud"):
print "user "+ uid +" has a cloud dir in their home directory - this is good."
else:
# They don't have a cloud directory, creating one
print uid+" does not have a cloud folder in their home directory, creating it"
if not os.path.exists("/home/"+uid+"/cloud"):
os.makedirs("/home/"+uid+"/cloud")
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown("/home/"+uid+"/cloud", "+uid+", "Domain Users")
else:
break
# Now make sure the cloufilesdir is empty
if not os.listdir(cloudfiledir):
print "Empty"
break
except:
print "rename and recreate the folder"
os.rename(clouddir, clouddir + str(uuid.uuid4()))
os.makedirs(clouddir)
os.chown(clouddir, 33, 33)
print "Now let's bind mount the directories"
# Bind each users home dir to their cloud dir
# Eg: bindfs -M www-data --create-for-user=1168 --create-for-group=513 /home/simon/cloud /var/www/owncloud/data/simon/files
# Still figuring this bit out
for user in a[0][1]['memberUid']:
filt = "(uid=" + user + ")"
u=l.search_s(path, ldap.SCOPE_SUBTREE, filt, ['uidNumber'])
print "\t", user, "filter: ", filt, u, "or"
uid = u[0][1]['uidNumber'][0]
print "\t\t", user, filt, uid
command = 'bindfs -M www-data --create-for-user=' + uid + ' --create-for-group=513 ' + '/home/' + user + '/cloud' + ' /var/www/owncloud/data/' + user + '/files'
print "BINGO: ", command, "\n"
John's advice fixed my except syntax, not I need to try and understand why the program only runs for the first UID and not the rest of them (there are 5 in the ldap group at the moment, 2 of which I have manually mounted so I would expect 3 bind mounts to happen).
I would appreciate any guidance as I continue to try and figure this out by trial and error.
Thanks in advance.
Simon
So, much reading and asking some wise colleagues later, I much a much better understanding of how for loops work, what break does and how useful continue can be.
Here is my final piece of code:
#!/usr/bin/python
import ldap
import os
import subprocess
import uuid
from pwd import getpwnam
# Lookup all the users in the cloudcape group
path='dc=cape'
l=ldap.open('ldap1.cape')
l.protocol_version = ldap.VERSION3
l.simple_bind('dc=cape')
a=l.search_s(path,ldap.SCOPE_SUBTREE,'cn=cloudcape')
# Add members to uids
uids=a[0][1]['memberUid']
# Check if a bindmount already exists or it not, that each cloud group user has the required directory i.e.home/USER/cloud and /var/www/owncloud/data/USER/files
for uid in uids:
# Define the directory paths
cloudfiledir="/var/www/owncloud/data/"+uid+"/files"
clouddir="/home/"+uid+"/cloud"
try:
subprocess.check_output(["mountpoint", cloudfiledir])
# If the output is all good, their bind mount is setup and mounted, if not carry on
except subprocess.CalledProcessError:
print uid+" does not have a mountpoint"
else:
continue
# Check if they have /var/www/owncloud/data/UID
if not os.path.isdir(cloudfiledir):
print uid+" does not have a owncloud directory structure in /var/www/owncloud, creating it"
os.makedirs("/var/www/owncloud/data/"+uid+"")
os.makedirs("/var/www/owncloud/data/"+uid+"/files")
os.makedirs("/var/www/owncloud/data/"+uid+"/cache")
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown("/var/www/owncloud/data/"+uid+"", 33, 33)
os.chown("/var/www/owncloud/data/"+uid+"/files", 33, 33)
os.chown("/var/www/owncloud/data/"+uid+"/cache/", 33, 33)
# Now check if the have /home/UID/cloud
if not os.path.isdir(clouddir):
# They don't have a cloud directory, creating one
print uid+" does not have a cloud folder in their home directory, creating it"
os.makedirs(clouddir)
# Now set permissions ("+uid+":Domain Users) - os.chown(path, uid, gid)
os.chown(clouddir, "+uid+", "Domain Users")
# Now make sure the cloudfilesdir is empty
try:
if not os.listdir(cloudfiledir) == []:
print "The mount point is not empty"
os.rename(cloudfiledir, cloudfiledir + str(uuid.uuid4()))
os.makedirs(cloudfiledir)
os.chown(cloudfiledir, 33, 33)
except:
print "The mount point is empty, moving on"
print "Now let's bind mount the directories"
# Bind each users home dir to their cloud dir
filt = "(uid=" + uid + ")"
userid=l.search_s(path, ldap.SCOPE_SUBTREE, filt, ['uidNumber'])
print "\t", uid, "filter: ", filt, userid, "or"
numuid = userid[0][1]['uidNumber'][0]
print "\t\t", uid, filt, uid
os.system('bindfs -M www-data --create-for-user=' + numuid + ' --create-for-group=513 ' + '/home/' + uid + '/cloud' + ' /var/www/owncloud/data/' + uid + '/files')
I have no doubt there are simpler and more efficient ways to do this but for now, the code does what I want it to do. I still need to build some fault tolerance into it, I already spotted one area where it might fail if a certain directory exists but that is next weeks problem.

Uploading video to YouTube and adding it to playlist using YouTube Data API v3 in Python

I wrote a script to upload a video to YouTube using YouTube Data API v3 in the python with help of example given in Example code.
And I wrote another script to add uploaded video to playlist using same YouTube Data API v3 you can be seen here
After that I wrote a single script to upload video and add that video to playlist. In that I took care of authentication and scops still I am getting permission error. here is my new script
#!/usr/bin/python
import httplib
import httplib2
import os
import random
import sys
import time
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1
# Maximum number of times to retry before giving up.
MAX_RETRIES = 10
# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
httplib.IncompleteRead, httplib.ImproperConnectionState,
httplib.CannotSendRequest, httplib.CannotSendHeader,
httplib.ResponseNotReady, httplib.BadStatusLine)
# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
CLIENT_SECRETS_FILE = "client_secrets.json"
# A limited OAuth 2 access scope that allows for uploading files, but not other
# types of account access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# Helpful message to display if the CLIENT_SECRETS_FILE is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the APIs Console
https://code.google.com/apis/console#access
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))
def get_authenticated_service():
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(flow, storage)
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
def initialize_upload(title,description,keywords,privacyStatus,file):
youtube = get_authenticated_service()
tags = None
if keywords:
tags = keywords.split(",")
insert_request = youtube.videos().insert(
part="snippet,status",
body=dict(
snippet=dict(
title=title,
description=description,
tags=tags,
categoryId='26'
),
status=dict(
privacyStatus=privacyStatus
)
),
# chunksize=-1 means that the entire file will be uploaded in a single
# HTTP request. (If the upload fails, it will still be retried where it
# left off.) This is usually a best practice, but if you're using Python
# older than 2.6 or if you're running on App Engine, you should set the
# chunksize to something like 1024 * 1024 (1 megabyte).
media_body=MediaFileUpload(file, chunksize=-1, resumable=True)
)
vid=resumable_upload(insert_request)
#Here I added lines to add video to playlist
#add_video_to_playlist(youtube,vid,"PL2JW1S4IMwYubm06iDKfDsmWVB-J8funQ")
#youtube = get_authenticated_service()
add_video_request=youtube.playlistItems().insert(
part="snippet",
body={
'snippet': {
'playlistId': "PL2JW1S4IMwYubm06iDKfDsmWVB-J8funQ",
'resourceId': {
'kind': 'youtube#video',
'videoId': vid
}
#'position': 0
}
}
).execute()
def resumable_upload(insert_request):
response = None
error = None
retry = 0
vid=None
while response is None:
try:
print "Uploading file..."
status, response = insert_request.next_chunk()
if 'id' in response:
print "'%s' (video id: %s) was successfully uploaded." % (
title, response['id'])
vid=response['id']
else:
exit("The upload failed with an unexpected response: %s" % response)
except HttpError, e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
e.content)
else:
raise
except RETRIABLE_EXCEPTIONS, e:
error = "A retriable error occurred: %s" % e
if error is not None:
print error
retry += 1
if retry > MAX_RETRIES:
exit("No longer attempting to retry.")
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print "Sleeping %f seconds and then retrying..." % sleep_seconds
time.sleep(sleep_seconds)
return vid
if __name__ == '__main__':
title="sample title"
description="sample description"
keywords="keyword1,keyword2,keyword3"
privacyStatus="public"
file="myfile.mp4"
vid=initialize_upload(title,description,keywords,privacyStatus,file)
print 'video ID is :',vid
I am not able to figure out what is wrong. I am getting permission error. both script works fine independently.
could anyone help me figure out where I am wrong or how to achieve uploading video and adding that too playlist.
I got the answer actually in both the independent script scope is different.
scope for uploading is "https://www.googleapis.com/auth/youtube.upload"
scope for adding to playlist is "https://www.googleapis.com/auth/youtube"
as scope is different so I had to handle authentication separately.

How do I access the URL's Query String in a Python CGI script?

I'm trying to access the query string in a python script: in bash I'd access it using the ${QUERY_STRING} environment variable.
I've come across things like this:https://stackoverflow.com/a/2764822/32836, but this script, as run by Apache2:
#!/usr/bin/python
print self.request.query_string
prints nothing, and at the command line, the same produces this error:
$ ./testing.py
Traceback (most recent call last):
File "./testing.py", line 3, in <module>
print self.request.query_string
NameError: name 'self' is not defined
How do I read the query_string?
First of all, the 'self' keyword is only available once defined in a function, typically an object's. It is normally used the same way 'this' is used in other OOP languages.
Now, the snippet of code you were trying to use was intended for the Google App Engine, which you have not imported (nor installed, I presume). Since you are accustomed to using environment variables, here's what you can do:
#!/usr/bin/python
import os
print os.environ.get("QUERY_STRING", "No Query String in url")
However, I would advise you to use the cgi module instead. Read more about it here: http://docs.python.org/2/library/cgi.html
Just like to add an alternate method to accessing the QUERY_STRING value if you're running a cgi script, you could just do the following:
import os
print "content-type: text/html\n" # so we can print to the webpage
print os.environ['QUERY_STRING']
My testing and understanding is that this also works when there aren't any query strings in the URL, you'd just get an empty string.
This is confirmed to be working on 2.7.6, view all environment variables like so:
#!/usr/bin/python
import os
print "Content-type: text/html\r\n\r\n";
print "<font size=+1>Environment</font><\br>";
for param in os.environ.keys():
print "<b>%20s</b>: %s<\br>" % (param, os.environ[param])
This snippet of code was obtained from a TutorialsPoint tutorial on CGI Programming with Python.
Although, as zombie_raptor_jesus mentioned, it's probably better to use Python's CGI module, with FieldStorage to make things easier.
Again from the above tutorial:
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
Will save values from the Query String first_name=Bobby&last_name=Ray
This is how I capture in Python 3 from CGI (A) URL, (B) GET parameters and (C) POST data:
I am using these methods on Windows Server running Python 3 using CGI via MIIS.
import sys, os, io
# CAPTURE URL
myDomainSelf = os.environ.get('SERVER_NAME')
myPathSelf = os.environ.get('PATH_INFO')
myURLSelf = myDomainSelf + myPathSelf
# CAPTURE GET DATA
myQuerySelf = os.environ.get('QUERY_STRING')
# CAPTURE POST DATA
myTotalBytesStr=(os.environ.get('HTTP_CONTENT_LENGTH'))
if (myTotalBytesStr == None):
myJSONStr = '{"error": {"value": true, "message": "No (post) data received"}}'
else:
myTotalBytes=int(os.environ.get('HTTP_CONTENT_LENGTH'))
myPostDataRaw = io.open(sys.stdin.fileno(),"rb").read(myTotalBytes)
myPostData = myPostDataRaw.decode("utf-8")
# Write RAW to FILE
mySpy = "myURLSelf: [" + str(myURLSelf) + "]\n"
mySpy = mySpy + "myQuerySelf: [" + str(myQuerySelf) + "]\n"
mySpy = mySpy + "myPostData: [" + str(myPostData) + "]\n"
# You need to define your own myPath here
myFilename = "spy.txt"
myFilePath = myPath + "\\" + myFilename
myFile = open(myFilePath, "w")
myFile.write(mySpy)
myFile.close()
=======================================================
Here are some other useful CGI environment vars:
AUTH_TYPE
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
============================================
Hope this can help you.
import os
print('Content-Type: text/html\n\n<h1>Search query/h1>')
query_string = os.environ['QUERY_STRING']
SearchParams = [i.split('=') for i in query_string.split('&')] #parse query string
# SearchParams is an array of type [['key','value'],['key','value']]
# for example 'k1=val1&data=test' will transform to
#[['k1','val1'],['data','test']]
for key, value in SearchParams:
print('<b>' + key + '</b>: ' + value + '<br>\n')
with query_string = 'k1=val1&data=test'
it will echo:
<h1>Search query</h1>
<b>k1</b>: val1<br>
<b>data</b>: test<br>
image output