Python output to valid JSON from a FOR loop - python

OK Guys, i'm brand new to Python.
I have started using it at work to query AWS with Boto3
My first task is to build a script to query users in AWS with MFA, the initial script works and returns all users which don't have a MFA Device, pretty simple really.
What i'm wanting to do is export the list to a JSON file so I can then consume the data within an Angular application to display the report.
When I run the code I get a JSON output but it's incorrect, its missing the comma and closing the JSON after each object instead of creating a complete singular JSON output.
My code is as follows:
import json
# boto code here
for user in iam.list_users()['Users']:
mfa = iam.list_mfa_devices(UserName=user['UserName'])
if len(mfa['MFADevices']) == 0:
q = []
q.append({"account": item['alias'], "Username":
user['UserName'], "MFA": "No MFA Enabled"})
print json.dumps(q, indent=4)
Result format is:
[
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "account"
}
]
[
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "account"
}
]

There are many valid JSON-formats. One of them is a list with dictionaries:
[ {}, {} ]
I suggest you try this:
import json
# boto code here
q = []
for user in iam.list_users()['Users']:
mfa = iam.list_mfa_devices(UserName=user['UserName'])
if len(mfa['MFADevices']) == 0:
q.append({"account": item['alias'], "Username":
user['UserName'], "MFA": "No MFA Enabled"})
print json.dumps(q, indent=4)

Nearly worked, but seems to be duplicating and multiplying the results creating a huge list
[
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
}
]
[
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
},
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
}
]
[
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
},
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
},
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
}
]
[
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
},
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
},
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
},
{
"Username": "Username",
"MFA": "No MFA Enabled",
"account": "Account"
}
]

Related

Add severity in JIRA json dump api

I'm creating a JIRA ticket from the python api, i'm able to create the ticket with the same detials i'm providing on the dump except the severity.
payload = json.dumps(
{
"fields": {
"project":
{
"key": "xyz"
},
"summary": summary",
"assignee": {
"id": account_id
},
"description": "description",
"issuetype": {
"name": "Bug",
"severity": 'S2'
}
}
}
)
This is the data payload i've written. Here even after providing severity as S2 or even S1, I'm still having my JIRA ticket generated as S3. please help me out on this
pushed severity inside the issue type as S2/S1

How to get new access_token from refresh_token using django_oauth_toolkit?

I am using django-oauth-toolkit version 1.1.2 to get access_token as seen below:-
Reauest:-
POST http://localhost:8597/login
{
"application_id": "cuOt3raxH9ClbCrbbgP68iU6ssfO2N78TplxwlMq",
"username": "test#gmail.com",
"password": "test",
"grant_type": "password"
}
Response:-
{
"type": "success",
"shortDescription": "User Logged in",
"longDescription": "User logged in successfully",
"success": "User Logged in",
"success_message": "User logged in successfully",
"data": {
"access_token": "RXMXGNl2HqYJMVkCBkrrMU5aYFS8uU",
"expires_in": 31536000,
"token_type": "Bearer",
"scope": "read write",
"refresh_token": "wsLetw7c2Q56k07XoisWkEa7SYxORb",
"user": {
"id": "c7d9f8ee-5e87-4a70-9c07-6a2e8c13a50a",
"created_at": "2019-11-21T16:55:45.817324+05:30",
"email": "test#gmail.com",
"first_name": "Test",
"last_name": "User",
"is_deleted": false,
"is_email_verified": true,
"last_login": "2020-02-19T11:17:24.656615+05:30",
"landline_country_code": "us",
"landline_number": "3242343434",
"mobile_country_code": "us",
"mobile_number": "34234234324",
"role": "USER",
"designation": "software engineer",
"is_active": true,
},
}
Now I want to use this 'refresh_token' to get new access_token, I am making the following request:-
Request:-
POST http://localhost:8597/o/token/
{
"grant_type": "refresh_token",
"client_id": "sHPPirW86SuOwDOfhxmag1fZ9oRCpHFS24wrZj00",
"refresh_token":"wsLetw7c2Q56k07XoisWkEa7SYxORb"
}
Response:-
{
"error": "invalid_grant"
}
There is something wrong with this request, can you please guide me how to fix it? Thanks.
The request looks alright. But do note that we'll also get the same invalid_grant error when the token is invalid. Since the toolkit uses refresh token rotation by default, this also includes the case when the refresh token has already been used, resulting in the same request working the first time, and then failing with invalid_grant error in all the subsequent tries, which I suspect might be the case with your request.
In addition, you may also want to check the refresh token object for that particular token used in your request and see if it has already been revoked or not.

Problems creating new query DoubleClick Bid Manager - Python

dict = {
"kind": "doubleclickbidmanager#query",
"metadata": {
"dataRange": "LAST_30_DAYS",
"format": "CSV",
"title": "test API"
},
"params": {
"filters": [
{
"type": "FILTER_PARTNER",
"value": "Nestle (GCC&Levant)_PM MENA (2410734)"
}
],
"metrics": [
"METRIC_CLICKS",
"METRIC_UNIQUE_REACH_CLICK_REACH",
"METRIC_UNIQUE_REACH_IMPRESSION_REACH"
]
}
}
r = requests.post('https://www.googleapis.com/doubleclickbidmanager/v1.1/query',data = dict)
This is the code i am trying to use for creating Query for offline report on google bid manager.
It give me following error
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
I have tried different ways even tried using the request type call and put the authorization keys in the API call but it didn't work. Surely something is missing can anyone confirm?
You can follow these python exemples for login :https://github.com/googleads/googleads-bidmanager-examples/tree/master/python
But anyway, there is always something wrong after the login, i post another question below : HttpEroor 500 Backend Error and HttpError 403 using DoubleClick Bid Manager API in python

How to read list in json file from python script

ISSUE:1
Appreciate someone could advise me further. I want to ssh to my equipment using python script and using netmiko module. I get the ssh details (json file) via api request and used the data to run the script. However I'm getting error below. I hope someone could advise and show me the way.
I miss something here, but I don't know how to resolve it.Please correct and lead me. Thanks.
The json file is create as snippet below;
response = requests.post(url,data=data,headers=headers,verify=False)
dictionary_info = response.json()
with open('devices.json', 'w') as fp:
json.dump(dictionary_info, fp, indent=4, sort_keys=True)
devices.json file as follows;
{
"device": [
{
"login": "test1",
"ip": "10.10.10.1",
"password": "test1",
"device_type": "cisco_ios"
},
{
"login": "test1",
"ip": "10.10.10.2",
"password": "test1",
"device_type": "cisco_ios"
},
{
"login": "test1",
"ip": "10.10.10.3",
"password": "test1",
"device_type": "cisco_ios"
},
{
"login": "test1",
"ip": "10.10.10.4",
"password": "test1",
"device_type": "cisco_ios"
}
],
"status": "SUCCESS"
}
when i run the script below (snippet) , it will return an error below
File "devices.py", line 18, in <module>
print('Connecting to device:',device['ip'])
TypeError: string indices must be integers
for device in devices:
try:
print('~' * 79)
print('Connecting to device:',device['ip'])
connection = netmiko.ConnectHandler(**device)
print(connection.send_command('show interface'))
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)
I should be able to run the script and ssh to each devices based on the ssh details provided by the json file. Somehow the code need to be modified further just I don't know how. Please assist me. Thanks
I edit the content of devices.json..I remove the curly bracket {}, the object name 'device' and 'status' and just remain the list[] as follows;
[
{
"username": "scnpa",
"ip": "10.10.10.1",
"password": "123",
"device_type": "cisco_ios"
},
{
"username": "scnpa",
"ip": "10.10.10.2",
"password": "123",
"device_type": "cisco_ios"
},
{
"username": "scnpa",
"ip": "10.10.10.3",
"password": "123",
"device_type": "cisco_ios"
},
{
"username": "scnpa",
"ip": "10.10.10.4",
"password": "123",
"device_type": "cisco_ios"
}
]
Today, I just try n error...and run back the script and it works..using editable json file above... I know this is not the solution as final I will get the json file that i shared earlier (with curly bracket {} and etc) or is there a way, I can get like the format above [{},{},{},{}]? Create file from json api response and only get the {{},{}.{},{}] content...?
or remain the format as it is...
Maybe need to modified the python script at the for loop part. I try remove the device and I'm getting different error.. change the 'device' to other name and still give me error 'TypeError: string indices must be integers'.
No idea...
for device in devices:
try:
print('~' * 79)
print('Connecting to device:',device['ip'])
connection = netmiko.ConnectHandler(**device)
print(connection.send_command('show interface'))
connection.disconnect()
ISSUE:2 I CREATE SEPARATE POST
I have another questions regarding reading the response json file (string) query from the API. For example json response as follow
{
"status": "SUCCESS",
"device": [
{
"model":"XXXX-A",
"username": "scnpa1",
"ip": "10.10.10.1",
"password": "123",
"device_type": "cisco_ios"
},
{
"model":"XXXX-A",
"username": "scnpa2",
"ip": "10.10.10.2",
"password": "456",
"device_type": "cisco_ios"
}
]
}
How to ensure only specific keys/values such as name and password and able to print and create the file as a json file (list) that can be read as an input by python script. Expect it will be like this below
{
"status": "SUCCESS",
"device": [
{
"username": "scnpa1",
"ip": "10.10.10.1",
"password": "123"
},
{
"username": "scnpa2",
"ip": "10.10.10.2",
"password": "456"
}
]
}
I use the code below but it will create json file with all the parameters
response = requests.post(url,data=data,headers=headers,verify=False)
dictionary_info = response.json()
with open('devices.json', 'w') as fp:
json.dump(dictionary_info, fp, indent=4, sort_keys=True)
Please advise me. Thanks
You should change the loop to
for device in devices['mydevice']:

Location widget in messenger platform displays a search bar in mobile version but not in Desktop Version

By using bot functionality provided by facebook messenger platform,
I want users to be able to provide location by using search.
It's working as expected in mobile app of the messenger as it's showing search option. But in the desktop version of the messenger, search option is not showing in location widget.
I wanted to ask that is it expected behavior or I'm missing out something.
Also in browser console, it's showing some error:
ErrorUtils caught an error:
"navigator.permissions.query(...).then(...).done is not a function".
Subsequent errors won't be logged;
see https://fburl.com/debugjs.ja # qtaMy7UNoCv.js:47.
Here's what I've tried so far:
def send_location_with_quick_reply(self, recipient_id, message, quick_replies):
url = self.get_message_url()
payload = {
"recipient":{
"id":recipient_id
},
"message":{
"text": message,
"quick_replies":[{
"content_type": "location"
}]
}
}
# _do_post will hit the send_message API of `Messenger`.
return self._do_post(url, payload)
And here's the response I'm getting after the user chooses the location:
{
"object": "page",
"entry": [{
"id": "128922990987384",
"time": 1505890084176,
"messaging": [{
"sender": {
"id": "1456347437763847"
},
"recipient": {
"id": "128922990987384"
},
"timestamp": 1505890084065,
"message": {
"mid": "mid.$cAAAvskrTvY9kz1Bs4Vengsjpb9L_",
"seq": 2366,
"attachments": [{
"title": "User's Location",
"url": "https:\\/\\/l.facebook.com\\/l.php?u=https\\u00253A\\u00252F\\u00252Fwww.bing.com\\u00252Fmaps\\u00252Fdefault.aspx\\u00253Fv\\u00253D2\\u002526pc\\u00253DFACEBK\\u002526mid\\u00253D8100\\u002526where1\\u00253D12.9703749\\u0025252C\\u00252B77.6361206\\u002526FORM\\u00253DFBKPL1\\u002526mkt\\u00253Den-US&h=ATNsjbke0tPFGIFpCq4MA5l1W6wmiwp0cTfUZNXSSbMDHxygEM4GrVlZmtaebsN4elliFhMSJNmIFwQgn-p_fxnF2hW0VdKTj2z_0hsWnH4dlLZGdQ&s=1&enc=AZN9DwrutbtXSfRAdxQf4bzFSMSO3zujAb0LBOgUt9mz16ZnDn7CSZDBLmnISjfAMbLG6b6H6hn9a3KCb6wOo7dn",
"type": "location",
"payload": {
"coordinates": {
"lat": 12.9703749,
"long": 77.6361206
}
}
}]
}
}]
}]
}
I am using python and drf to integrate with messenger platform.
Yes, this is expected behavior currently.

Categories

Resources