How to use a variable in API payload in Jupyter Notebook - python

I'm using Jupyter Notebook to gather up a bunch of API calls then use various plotting tools to generate pretty graphs.
I have the notebook working great when using constants in the API payload. Now I'm trying to replace the constants with user entered variables and having some challenges.
The following method for variable use works when the variable isn't part of a filter or function:
key = input('Enter your subscription API Key then press Enter: ')
When prompted, the user enters the key and that value is used perfectly fine in the following:
headers = {
'X-Co-Integration-Key': key,
'Content-Type': "application/json",
'Cache-Control': "no-cache",
}
Next, enter another variable for a guide called guideId:
guideId = input('Enter the Guide ID of the guide for which you want statistics then press Enter: ')
When prompted, the user enters the guideId and that value is stored, but I can't seem to get it to be used properly in the API payload.
I've tried several different methods of inserting the variable and the following gets me the closest to something that works:
{\n \"filter\": \"id== \"" + guideId + "\n }
The API call runs, but I get the following error:
{"overall": {"DeserializationError": "invalid character 'q' after object key:value pair"}, "fields": {"pipeline": "Required"}}
It looks like it is reading the variable and stopping after it hits the first character in the variable, which, in this case is a q.
I tried changing the variable to start with a number. No change in behavior.
I tried using str(guideId) - no change in behavior.
I'm stumped. Any ideas?

Related

Refer to variables dynamically

Context: I am creating a Django management command which will accept a positional argument. This argument is a location. My goal is to use the location value to refer to a corresponding variable.
I have a global variable named Boston_webhook. This is a simple string which contains a long URL which is just a MSteams webhook...
I have an additional global variable named Budapest_webhook which contains the same data type, but instead refers to a webhook related to the Budapest location.
In my script, a connector variable has to be defined in order to send the message to the correct place.
myTeamsMessage = pymsteams.connectorcard()
If someone entered python manage.py report Boston I want to insert this into the connector params, but I am unsure how to refer to variables dynamically.
Is it possible to refer to Boston_webhook when the location == 'Boston' using some sort of concatenation...?
something like myTeamsMessage = pymsteams.connectorcard(location + _webhook) would be ideal
I would like to avoid using conditionals as it is not scalable. I need to be able to add locations to the database without having to change code...
Use dictionary to map names of webhooks to webhooks itself - like this
webhooks = {
"Boston": "boston url",
"Budapest": "budapest url"
}
Now you can refer to your webhooks like this
# this will give you Boston webhook
myTeamsMessage = pymsteams.connectorcard(location + webhooks["Boston"])
This is simpliest way to do it. I think it would be better to create new class only for this and convert that class to string using a method , but this would be enough if you don't need anything more complex
I was able to determine a suitable solution;
myTeamsMessage = pymsteams.connectorcard(webhooks["{}".format(location)])
where the webhooks are stored in a dictionary keyed by location name.
i.e:
webhooks = {'Boston':'www.url.com',
'Budapest':'www.url1.com',
}
Thanks for the recommendations everyone!

How I can make my db add codes for users to register with one of the codes ? (Python-Django)

I want to put a number of codes in my database so that when a user wants to register my application need to enter a code of those who are in the database, so that the system registry access.
All this in django, but honestly I have no idea how to do it, if you can help me, I would appreciate it very much.
Thanks for your time.
There are a couple of steps that you will need to do, but essentially you are just seeding the DB with valid registration codes. To generate a number of registration codes you can use the following, I limit the number to 1000 but this can be changed
import uuid
codes = set()
num_codes = 1000
while (num_codes > 0):
code = str(uuid.uuid4())
# make sure the randomly gen code isn't a duplicated
while code in codes:
code = str(uuid.uuid4())
# add the newly generated code to the set and dec the counter
codes.add(code)
num_codes -= 1
Next what you will want to do is add the codes to a new table. It would probably make sense to have a table structure like:
{
table_name: registration code,
columns: {
id: int,
code: string,
valid: bool,
}
}
where valid limits the code to a one time registration.
Then when a user tries to register select where the key used = code column and valid = true, if it returns something it is valid otherwise the key is invalid or already used.

Checking if A follows B on twitter using Tweepy/Python

I have a list of a few thousand twitter ids and I would like to check who follows who in this network.
I used Tweepy to get the accounts using something like:
ids = {}
for i in list_of_accounts:
for page in tweepy.Cursor(api.followers_ids, screen_name=i).pages():
ids[i]=page
time.sleep(60)
The values in the dictionary ids form the network I would like to analyze. If I try to get the complete list of followers for each id (to compare to the list of users in the network) I run into two problems.
The first is that I may not have permission to see the user's followers - that's okay and I can skip those - but they stop my program. This is the case with the following code:
connections = {}
for x in user_ids:
l=[]
for page in tweepy.Cursor(api.followers_ids, user_id=x).pages():
l.append(page)
connections[x]=l
The second is that I have no way of telling when my program will need to sleep to avoid the rate-limit. If I put a 60 second wait after every page in this query - my program would take too long to run.
I tried to find a simple 'exists_friendship' command that might get around these issues in a simpler way - but I only find things that became obsolete with the change to API 1.1. I am open to using other packages for Python. Thanks.
if api.exists_friendship(userid_a, userid_b):
print "a follows b"
else:
print "a doesn't follow b, check separately if b follows a"

Use Powershell to retrieve number from a sequence using web request

I have a very specific problem I have been trying to work out. I'm using a PowerShell script to name newly imaged computers during the imaging proceess, and I need to grab a newly generated number from a sequence. I use SCCM 2012 R2 for this, btw
For example, I have the script naming our computers by our convention using wmi query:
if ($ComputerVersion -eq "ThinkPad T400")
{
$OSDComputerName = "T400xxxx-11"
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$TSEnv.Value("OSDComputerName") = "$OSDComputerName"
}
I set the $ComputerVersion variable, using WMI query, like so:
$ComputerVersion = (Get-WmiObject -Class Win32_ComputerSystemProduct | Select-Object Version).Version
So, the crux of my question is I want to set another variable, probably something simple
like $num, for the next number available to label our computers. This number will be replacing the "xxxx". I'll be doing that by:
if ($ComputerVersion -eq "ThinkPad T400")
{
$OSDComputerName = "T400" + $num + "-11"
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$TSEnv.Value("OSDComputerName") = "$OSDComputerName"
}
This number is being generated by a linux server we have, and its already running some python script to dish out the next available number in the sequence. I can post that python script if needed, but it's 133 lines.
What I need to know is how to call for that web request via PowerShell, and set that returned number (the next available) as a new variable.
I've never used web-services or web-requests before and any help would be greatly appreciated. Thanks in advance!
Depends what the web request returns and whether or not you need to process any return data, but if it simply returns the number you could do this:
$webClient = New-Object System.Net.WebClient
$num = $webClient.downloadstring("http://yourwebservice.com/buildnumber")

How to read facebook graph json data using python?

When I print "user_stream" in the development environment, the full string gets printed. However when I view what gets printed in the console in the production environment, the full contents of "user_stream" is not printed, which I believe is leading to an error later on in additional code I have.
My question is: why aren't all the contents of "user_stream" being printed in the console in the production environment and how do I fix this?
instance = UserSocialAuth.objects.get(user=request.user, provider='facebook')
token = instance.tokens
user_url = "https://graph.facebook.com/me/friends?access_token=" + token['access_token']
u = urllib.urlopen(user_url);
user_stream = json.loads(u.read())
print user_stream
There is an error in your user_stream somehow. The best way to figure out what it is is to either print the string, or print the error message directly. These commands should help you figure out what is going on.
print u.read()
print user_stream['error']
I strongly suspect that your access token isn't valid somehow. Look into that as well. An example of what you might see from the Graph API Explorer is this:
{
"error": {
"message": "Malformed access token AAACEdEose0cBAM0CipLFjIDZCysqmGyZCRJ6x4JsdSVkb177lM0UNMWqSYZA9BmBY0h3PbUiIJppQCbDZD",
"type": "OAuthException",
"code": 190
}
Read the message there carefully, and see if you can figure out how to correct it. Also, try printing our your full URL and running it in the Graph API Explorer.

Categories

Resources