My code is:
from ipwhois import IPWhois
import pprint
obj = IPWhois('74.125.227.206')
results = obj.lookup_rws()
pprint.pprint(results)
It returns:
{'asn': '15169',
'asn_cidr': '74.125.227.0/24',
'asn_country_code': 'US',
'asn_date': '2007-03-13',
'asn_registry': 'arin',
'nets': [{'abuse_emails': 'arin-contact#google.com',
'address': '1600 Amphitheatre Parkway',
'cidr': '74.125.0.0/16',
'city': 'Mountain View',
'country': 'US',
'created': '2007-03-13T12:09:54-04:00',
'description': 'Google Inc.',
'handle': u'NET-74-125-0-0-1',
'misc_emails': None,
'name': 'GOOGLE',
'postal_code': '94043',
'range': u'74.125.0.0 - 74.125.255.255',
'state': 'CA',
'tech_emails': 'arin-contact#google.com',
'updated': '2012-02-24T09:44:34-05:00'}],
'query': '74.125.227.206',
'raw': None}
What is the best or easiest way in python to print a single line from the output?
For example:
'name': 'GOOGLE',
or 'abuse_emails': 'arin-contact#google.com',
Any help would be appreciated!!
results is already a dictionary, so just get the keys and values that you want.
from ipwhois import IPWhois
obj = IPWhois('74.125.227.206')
results = obj.lookup_rws()
print(results['nets'][0]['name'])
lookup_rws() function is deprecated. Instead, use:
from ipwhois import IPWhois
obj = IPWhois('{}'.format('IP') # Enter IP
result = obj.lookup_rdap(depth=1)
print(result['network']['name'])
Related
I'm making a call to an api which is returning a JSON response, whcih i am then trying to retrieve certain data from within the response.
{'data': {'9674': {'category': 'token',
'contract_address': [{'contract_address': '0x2a3bff78b79a009976eea096a51a948a3dc00e34',
'platform': {'coin': {'id': '1027',
'name': 'Ethereum',
'slug': 'ethereum',
'symbol': 'ETH'},
'name': 'Ethereum'}}],
'date_added': '2021-05-10T00:00:00.000Z',
'date_launched': '2021-05-10T00:00:00.000Z',
'description': 'Wilder World (WILD) is a cryptocurrency '
'launched in 2021and operates on the '
'Ethereum platform. Wilder World has a '
'current supply of 500,000,000 with '
'83,683,300.17 in circulation. The last '
'known price of Wilder World is 2.28165159 '
'USD and is down -6.79 over the last 24 '
'hours. It is currently trading on 21 active '
'market(s) with $2,851,332.76 traded over '
'the last 24 hours. More information can be '
'found at https://www.wilderworld.com/.',
'id': 9674,
'is_hidden': 0,
'logo': 'https://s2.coinmarketcap.com/static/img/coins/64x64/9674.png',
'name': 'Wilder World',
'notice': '',
'platform': {'id': 1027,
'name': 'Ethereum',
'slug': 'ethereum',
'symbol': 'ETH',
'token_address': '0x2a3bff78b79a009976eea096a51a948a3dc00e34'},
'self_reported_circulating_supply': 19000000,
'self_reported_tags': None,
'slug': 'wilder-world',
'subreddit': '',
'symbol': 'WILD',
'tag-groups': ['INDUSTRY',
'CATEGORY',
'INDUSTRY',
'CATEGORY',
'CATEGORY',
'CATEGORY',
'CATEGORY'],
'tag-names': ['VR/AR',
'Collectibles & NFTs',
'Gaming',
'Metaverse',
'Polkastarter',
'Animoca Brands Portfolio',
'SkyVision Capital Portfolio'],
'tags': ['vr-ar',
'collectibles-nfts',
'gaming',
'metaverse',
'polkastarter',
'animoca-brands-portfolio',
'skyvision-capital-portfolio'],
'twitter_username': 'WilderWorld',
'urls': {'announcement': [],
'chat': [],
'explorer': ['https://etherscan.io/token/0x2a3bff78b79a009976eea096a51a948a3dc00e34'],
'facebook': [],
'message_board': ['https://medium.com/#WilderWorld'],
'reddit': [],
'source_code': [],
'technical_doc': [],
'twitter': ['https://twitter.com/WilderWorld'],
'website': ['https://www.wilderworld.com/']}}},
'status': {'credit_count': 1,
'elapsed': 7,
'error_code': 0,
'error_message': None,
'notice': None,
'timestamp': '2022-01-20T21:33:04.832Z'}}
The data i am trying to get is 'logo': 'https://s2.coinmarketcap.com/static/img/coins/64x64/9674.png', but this sits within [data][9674][logo]
But as this script to running in the background for other objects, i won't know what the number [9674] is for other requests.
So is there a way to get that number automatically?
[data] will always be consistent.
Im using this to get the data back
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
pprint.pprint(json.loads(response.text)['data']['9674']['logo'])
You can try this:
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
resp = json.loads(response.text)
pprint.pprint(resp['data'][next(iter(resp['data']))]['logo'])
where next(iter(resp['data'])) - returns first key in resp['data'] dict. In your example it '9674'
With .keys() you get a List of all Keys in a Dictionary.
So you can use keys = json.loads(response.text)['data'].keys() to get the keys in the data-dict.
If you know there is always only one entry in 'data' you could use json.loads(response.text)['data'][keys[0]]['logo']. Otherwise you would need to iterate over all keys in the list and check which one you need.
I'm sorry for my bad english
Hello, I am using a brokerage firm for payment instrument. The API connection is successful and I get the result. But I can't use the returned result information.
payment_card = {
'cardHolderName': kartisim,
'cardNumber': kartno,
'expireMonth': kartskt_ay,
'expireYear': '2030',
'cvc': karcvc,
'registerCard': '0'
}
buyer = {
'id': adres.id,
'name': adres.adres_uye.username,
'surname': 'Doe',
'gsmNumber': '+905350000000',
'email': adres.adres_uye.email,
'identityNumber': '74300864791',
'lastLoginDate': '2015-10-05 12:43:35',
'registrationDate': '2013-04-21 15:12:09',
'registrationAddress': adres.adres_detay,
'ip': '85.34.78.112',
'city': 'Istanbul',
'country': 'Turkey',
'zipCode': '34732'
}
address = {
'contactName': 'Jane Doe',
'city': 'Istanbul',
'country': 'Turkey',
'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
'zipCode': '34732'
}
basket_items = []
for bas in uye:
basa = {
'id': str(bas.id),
'name': str(bas.sepet_urun.urun_baslik),
'category1': str(bas.sepet_urun.urun_anakategori.anakategori_baslik),
'category2': str(bas.sepet_urun.urun_altkategori.altkategori_baslik),
'itemType': 'VIRTUAL',
'price': str(bas.sepet_fiyat)
}
basket_items.append(basa)
print(basket_items)
request_payload = {
'locale': 'tr',
'conversationId': '123456789',
'price': str(sepetf),
'paidPrice': str(sepetf),
'currency': 'TRY',
'installment': '1',
'basketId': str(sepetid),
'paymentChannel': 'WEB',
'paymentGroup': 'PRODUCT',
'paymentCard': payment_card,
'buyer': buyer,
'shippingAddress': address,
'billingAddress': address,
'basketItems': basket_items
}
payment = iyzipay.Payment().create(request_payload, options)
print(payment.read().decode('utf-8'))
return HttpResponse(payment["status"])
I cannot use the returned result information. The returned result is as follows
The error I get is as follows:
'HTTPResponse' object is not subscriptable
Looks like the issue is here.
return HttpResponse(payment["status"])
payment returns an HTTPResponse response object and you cannot directly index the status. Instead you should use .status attribute.
If your intention is to return JSON back as response you could use JsonResponse class from django.http module.
return JsonResponse(json.loads(payment.read().decode('utf-8')))
I'm looking to parse the following dictionary received json response and am running into issues. My dictionary name is results.
This is a simple json response that appears to be dict.
{'resultType': 'vector', 'result': [{'metric': {'agent_host': 'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch', 'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance': 'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack', 'site_name': 'test_site'}, 'value': [1631917506.324, '0.00009262475396549728']}]}
Type confirms that:
<class 'dict'>
Ultimately what I'd like to do is something along the lines of:
for key, value in results.items():
(rx_error, rx_error_freq) = value[16]
In order to get the value 0.00009262475396549728 from above. How would I go about doing this?
One great way to visualize nested dictionaries is to use pprint which comes built into python3
from pprint import pprint
d = {'resultType': 'vector', 'result': [{'metric': {'agent_host':
'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch',
'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance':
'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack',
'site_name': 'test_site'}, 'value': [1631917506.324,
'0.00009262475396549728']}]}
pprint(d)
>>> {'result': [{'metric': {'agent_host': 'x.x.x.x',
'cluster_name': 'test_cluser',
'device_type': 'switch',
'hostname': 'myswitch',
'ifName': 'xe-0/0/10',
'instance': 'telegraf:1111',
'job': 'telegraf',
'rack_name': 'test_rack',
'site_name': 'test_site'},
'value': [1631917506.324, '0.00009262475396549728']}],
'resultType': 'vector'}
This allows us to see the different key value pairs a lot more easily. So the data you're looking to access would is
rx_error, rx_error_freq = d["result"][0]["value"]
Loop over the result list to get the value, then print the second element
>>> data = {'resultType': 'vector', 'result': [{'metric': {'agent_host': 'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch', 'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance': 'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack', 'site_name': 'test_site'}, 'value': [1631917506.324, '0.00009262475396549728']}]}
>>> for r in data['result']:
... print(r['value'][1])
...
0.00009262475396549728
import requests
import re
import json
def parser(code):
params = {
'template': 'professional',
'level': 'search',
'search': code
}
r = requests.get("https://maps.locations.husqvarna.com/api/getAsyncLocations",
params=params).json()
goal = re.search(r'({.+})', r['maplist'], re.M | re.DOTALL).group(1)
print(goal)
parser("35801")
The code will return a string of dicts which is not wrapped. i tried to dump/loads and wrapped it within [ ] but for weired reason it's still a string
You need to convert goal into a list manually, to receive Python objects:
import requests
import re
import json
def parser(code):
params = {
'template': 'professional',
'level': 'search',
'search': code
}
r = requests.get("https://maps.locations.husqvarna.com/api/getAsyncLocations",
params=params).json()
goal = re.search(r'({.+})', r['maplist'], re.M | re.DOTALL).group(1)
jsonList = '[%s]' % goal # Make proper json list!
items = json.loads(jsonList)
for item in items:
print(item)
parser("35801")
Out:
{'fid': 'USF221344-2115METROCIRCLE', 'lid': '56063', 'lat': '34.7004049', 'lng': '-86.5924508', 'url': 'https://locations.husqvarna.com/al/huntsville/product-manufacturer-usf221344-2115metrocircle.html', 'country': 'US', 'url_slug': 'product-manufacturer-usf221344-2115metrocircle.html', 'location_name': 'HEDDEN LAWN & GARDEN', 'address_1': '2115 METRO CIRCLE', 'address_2': '', 'city': 'HUNTSVILLE', 'city_clean': 'huntsville', 'region': 'AL', 'region_lc': 'al', 'post_code': '35801', 'local_phone': '(256) 885-1750', 'local_phone_pn_dashes': '256-885-1750', 'local_fax': '', 'local_fax_pn_dashes': '', 'from_email': '', 'hours_timezone': '', 'hours_dst': '', 'distance': '2.2', 'hours_sets:primary': '{"label":"Primary Hours","name":"primary","type":"0","timezone":"-6","dst":"1"}', 'Store Type_CS': 'Buy,Service', 'Location Type_CS': 'Authorized Dealers,Servicing Locations'}
...
I am trying to pull 'created' from the Monzo data I'm pulling.
I have made a call to the Monzo api with the following code:
from monzo.monzo import Monzo
client = Monzo(INSERT API KEY)
data = client.get_transactions("INSERT ACCOUNT NUMBER")
print (data)
and I can't quite get the data I need which looks like this:
d': 'merch_000094MPASVBf7xCdrZOz3', 'created': '2016-01-20T21: 26: 33.985Z', 'name': 'DelicedeFrance', 'logo': 'https: //mondo-logo-cache.appspot.com/twitter/deliceuk/?size=large', 'emoji': '🇫🇷', 'category': 'eating_out', 'online': False, 'atm': False, 'address': {'short_formatted': 'LiverpoolStreetStation,
LondonEC2M7PY', 'formatted': 'LiverpoolStreetStation,
LondonEC2M7PY,
UnitedKingdom', 'address': 'LiverpoolStreetStation', 'city': 'London', 'region': 'GreaterLondon', 'country': 'GBR', 'postcode': 'EC2M7PY', 'latitude': 51.518159172221615, 'longitude': -0.08210659649555102, 'zoom_level': 17, 'approximate': False}, 'updated': '2016-02-02T14: 10: 48.664Z', 'metadata': {'foursquare_category': 'Restaurant', 'foursquare_category_icon': 'https: //ss3.4sqi.net/img/categories_v2/food/default_88.png','foursquare_website': '', 'google_places_icon': 'https: //maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png', 'google_places_name': 'DelicedeFrance', 'suggested_name': 'DelicedeFrance', 'suggested_tags': '#food', 'twitter_id': ''}, 'disable_feedback': False}, 'notes': '', 'metadata': {}, 'account_balance': 3112, 'attachments': [], 'category': 'eating_out', 'is_load': False, 'settled': '2017-04-28T04: 54: 18.167Z', 'local_amount': -199, 'local_currency': 'GBP', 'updated': '2017-04-28T06: 15: 06.095Z', 'counterparty': {}, 'originator': False, 'include_in_spending': True}, {'created': '2017-04-28T08: 54: 10.917Z','amount': -130, 'currency': 'GBP', 'merchant': {'created': '2016-04-21T08: 02: 13.537Z','logo': 'https: //mondo-logo-cache.appspot.com/twitter/MCSaatchiLondon/?size=large', 'emoji': '🍲', 'category': 'eating_out', 'online': False, 'atm': False...
How do I pull the 'created' date?
Try this:
#!/usr/bin/env python
import csv
from pymonzo import MonzoAPI
if __name__ == '__main__':
monzo_api = MonzoAPI()
monzo_transactions = monzo_api.transactions()
with open('monzo_transactions.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
for transaction in monzo_transactions:
writer.writerow([
transaction.amount, transaction.description,
transaction.created,
])
print('All done!')
If this is actually right json code and you just have paste errors, than you can use the python libary json:
import json
data = json.loads(datastring)
If this not json code, you probably have to write a parser on your own.