How to query a currency in binance? - json

How to query a currency in binance? In the bitfinex API I can only filter BTCUSD, but in binance the query returns all negotiated pairs.
import requests
import json
requisicao = requests.get('https://api.binance.com/api/v3/ticker/price')
cotacao = json.loads(requisicao.text)
def bitfinex_btc():
bitFinexTick1 = requests.get("https://api.bitfinex.com/v1/ticker/btcusd")
return bitFinexTick1.json()['last_price']
bitfinexlivebtc = float(bitfinex_btc())
print ('BITFINEX BTC = U$',bitfinexlivebtc)
print ('BINANCE BTC = U$',cotacao)

If I understand correctly, you want to filter on BTC->USD only when accessing Binance.
From the API documentation at:
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-price-ticker
you can add the symbol as a query parameter, so it would look like this:
https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT
The response is of the following form:
{
"price": "8196.79000000",
"symbol": "BTCUSDT"
}
so in Python the function would be something like:
def binance_btc():
binanceTick1 = requests.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT")
return binanceTick1.json()['price']

Related

how to convert group by(values) to json - django

i'm trying to convert my grouped by (values in django) data into JsonResponse but it raise this error :
AttributeError: 'dict' object has no attribute 'f_type'
this is my function of loadding json data
def load_cate(request):
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
data = []
for i in lists.values():
item = {
'wc_type':i.f_type,
'room_type':i.room_type,
'beds':i.beds,
'balcon':i.balcon,
'total':i.total
}
data.append(item)
return JsonResponse({'success':True,'data':data})
is there something i did wrong ? or its different for group by values ?!
thanks in advance ..
There is no need to loop throught objects. You just need to convert QuerySet into a list.
values() will return a QuerySet object which cant be return in a JsonResponse. So just convert into a list.
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
lists = list(lists)

Groovy - parse/ convert x-www-form-urlencoded to something like JSON

this is my second try to explain a bit more precisely what I'm looking for ;-)
I set a webhook in Mailchimp that fires every time a new subscriber of an audience appears. Mailchimp sends a HTTP POST request to a Jira Sriptrunner REST endpoint.
The content type of this request is application/x-www-form-urlencoded.
Within the Jira endpoint I would like to read the request data. How can I do that?
The payload (raw body) I receive looks like this:
type=unsubscribe&fired_at=2020-05-26+07%3A04%3A42&data%5Baction%5D=unsub&data%5Breason%5D=manual&data%5Bid%5D=34f28a4516&data%5Bemail%5D=examlple%40bla.com&data%5Bemail_type%5D=html&data%5Bip_opt%5D=xx.xxx.xxx.198&data%5Bweb_id%5D=118321378&data%5Bmerges%5D%5BEMAIL%5D=example%40bla.com&data%5Bmerges%5D%5BFNAME%5D=Horst&data%5Bmerges%5D%5BLNAME%5D=Schlemmer&data%5Bmerges%5D%5BCOMPANY%5D=First&data%5Bmerges%5D%5BADDRESS%5D%5Baddr1%5D=XXX
Now I would like to parse the data of the raw body into a JSON or something similiar.
The result might look like this:
{
"web_id": 123,
"email": "example#bla.com",
"company": "First",
...
}
Meanwhile I searched around a little and found something like the node.js "querystring" module. It would be great if there is something similiar within Groovy or any other way to parse the data of application/x-www-form-urlencoded to json format.
Best regards and thanks in advance
Bernhard
def body = "type=unsubscribe&fired_at=2020-05-26+07%3A04%3A42&data%5Baction%5D=unsub&data%5Breason%5D=manual&data%5Bid%5D=34f28a4516&data%5Bemail%5D=examlple%40bla.com&data%5Bemail_type%5D=html&data%5Bip_opt%5D=xx.xxx.xxx.198&data%5Bweb_id%5D=118321378&data%5Bmerges%5D%5BEMAIL%5D=example%40bla.com&data%5Bmerges%5D%5BFNAME%5D=Horst&data%5Bmerges%5D%5BLNAME%5D=Schlemmer&data%5Bmerges%5D%5BCOMPANY%5D=First&data%5Bmerges%5D%5BADDRESS%5D%5Baddr1%5D=XXX"
def map = body.split('&').collectEntries{e->
e.split('=').collect{ URLDecoder.decode(it, "UTF-8") }
}
assert map.'data[merges][EMAIL]'=='example#bla.com'
map.each{println it}
prints:
type=unsubscribe
fired_at=2020-05-26 07:04:42
data[action]=unsub
data[reason]=manual
data[id]=34f28a4516
data[email]=examlple#bla.com
data[email_type]=html
data[ip_opt]=xx.xxx.xxx.198
data[web_id]=118321378
data[merges][EMAIL]=example#bla.com
data[merges][FNAME]=Horst
data[merges][LNAME]=Schlemmer
data[merges][COMPANY]=First
data[merges][ADDRESS][addr1]=XXX
A imple no-brainer groovy:
def a = '''
data[email_type]: html
data[web_id]: 123
fired_at: 2020-05-26 07:28:25
data[email]: example#bla.com
data[merges][COMPANY]: First
data[merges][FNAME]: Horst
data[ip_opt]: xx.xxx.xxx.xxx
data[merges][PHONE]: xxxxx
data[merges][ADDRESS][zip]: 33615
type: subscribe
data[list_id]: xxXXyyXX
data[merges][ADDRESS][addr1]: xxx.xxx'''
def res = [:]
a.eachLine{
def parts = it.split( /\s*:\s*/, 2 )
if( 2 != parts.size() ) return
def ( k, v ) = parts
def complexKey = ( k =~ /\[(\w+)\]/ ).findAll()
if( complexKey ) complexKey = complexKey.last().last()
res[ ( complexKey ?: k ).toLowerCase() ] = v
}
res
gives:
[email_type:html, web_id:123, fired_at:2020-05-26 07:28:25,
email:example#bla.com, company:First, fname:Horst, ip_opt:xx.xxx.xxx.xxx,
phone:xxxxx, zip:33615, type:subscribe, list_id:xxXXyyXX, addr1:xxx.xxx]
I found a solution finally. I hope you understand and maybe it helps others too ;-)
Starting from daggett's answer I did the following:
// Split body and remove unnecessary characters
def map = body.split('&').collectEntries{e->
e.split('=').collect{ URLDecoder.decode(it, "UTF-8") }
}
// Processing the map to readable stuff
def prettyMap = new JsonBuilder(map).toPrettyString()
// Convert the pretty map into a json object
def slurper = new JsonSlurper()
def jsonObject = slurper.parseText(prettyMap)
(The map looks pretty much like in daggett's answer.
prettyMap)
Then I extract the keys:
// Finally extracting customer data
def type = jsonObject['type']
And I get the data I need. For example
Type : subscribe
...
First Name : Heinz
...
Thanks to daggett!

Try and except to check and count returned JSON from API

I am learning how to get JSON data from a particular API using Python 3. I am using input() to select a word for inclusion in the url search string. I generally get the JSON results I expect which includes a count of records returned. However for some search words, the JSON is returned as expected but the except is invoked and the records are not counted. I think the problem is to do with the try and except. In my code the input words that work as expected include "pool" and "Pool" and the results include both "pool" and "Pool" but "captain" or "Captain" does not give a final count even though there are records with "Captain", and the JSON is returned.
My code is below and a sample of the json also. I'd be grateful for any assistance with this:
import urllib.request, urllib.parse
import json
what = input('What?: ')
what = what.strip()
url = 'http://collections.anmm.gov.au/advancedsearch/objects/'+'title:'+ what +'/'+'json'
#print ('Retrieving: ', url)
connection = urllib.request.urlopen(url)
data = connection.read().decode()
try:
results = json.loads(data)
#print (results)
print ('Retrieving: ', url)
count = 0
if results['objects']:
for item in results['objects']:
objectNumber = item['invno']['value'];
title = item['title']['value'];
date = item['displayDate']['value'];
count = count +1
print(objectNumber,'',title,'',date)
print(count, 'records with ',what,' returned')
except:
print('No search results returned')
And my json sample:
{
"objects":[
{
"displayDate":{
"label":"Date",
"value":1930,
"order":3
},
"invno":{
"label":"Object No",
"value":"ANMS0427[063]",
"order":9
},
"id":{
"label":"Id",
"value":88089,
"order":0
},
"title":{
"label":"Title",
"value":"Article by Donald McLean titled 'Lure of buried treasure; from Carolina to Cocos' about pirates: Captain blackbeard, Captain Kidd and Captain Edward Davis",
"order":2
}
}
]
}
If you debug your code, you'll see that there is a problem with this instruction's output :
date = item['displayDate']['value'];

How to properly parse JSON in Groovy

I am not sure how to properly parse through nested JSON using Groovy. I have included a working Python script so you can see exactly what I'm trying to do in Groovy.
JSON I need to parse:
json_payload = {"number": 3585, "url": "https://jenkins.test.com/job/test/3585/",
"displayName": "test_3585", "timestamp": 1516992464686,
"actions": [{"causes": [{"userId": "test"}]}]}
What I want to do (Python):
class JenkinsParser:
def __init__(self, json_data):
self.display_name = json_data['displayName']
self.url = json_data['url']
self.start_time = json_data['timestamp']
self.exec_url = json_data['url']
self.exec_number = json_data['number']
self.user = None
actions = json_data['actions']
for a in actions:
if 'causes' in a:
for cause in a['causes']:
if 'userId' in cause:
self.user = cause['userId']
url_split = self.execution_url.split("/job/")
self.jenkins_url = url_split[0]
self.job_name = url_split[-1].split("/")[0]
Note: The Groovy does not necessarily need to be a class, and doesn't need to use JSonSlurper
If I use JsonSlurper
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json_payload)
Can I access all the values I need like so?
result.displayName
result.url
result.timestamp
result.url
result.number
result.actions.causes.userId
I'm not sure how to grab userId..
Yes, you can access the values like you described.
You could access userId like result​.actions.first().causes.first().userId​ if you're sure your data is structured exactly like that. If you may or may not have actions, or may or may not have causes, you could do something like result​.actions?.first()?.causes?.first()?.userId​ to make your access null-safe, or you could use the spread (*.) operator to access userId if there may be multiple actions or causes.
Per your comment about something returning null, this works as expected:
def json_payload = """{"number": 3585, "url": "https://jenkins.test.com/job/test/3585/", "displayName": "test_3585", "timestamp": 1516992464686, "actions": [{"causes": [{"userId": "test"}]}]}"""
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json_payload)
return result​.actions?.first()?.causes?.first()?.userId​
and returns "test". If you are not seeing similar results you may have a syntax error or different key in your actual data.

Converting mongoengine objects to JSON

i tried to fetch data from mongodb using mongoengine with flask. query is work perfect the problem is when i convert query result into json its show only fields name.
here is my code
view.py
from model import Users
result = Users.objects()
print(dumps(result))
model.py
class Users(DynamicDocument):
meta = {'collection' : 'users'}
user_name = StringField()
phone = StringField()
output
[["id", "user_name", "phone"], ["id", "user_name", "phone"]]
why its show only fields name ?
Your query returns a queryset. Use the .to_json() method to convert it.
Depending on what you need from there, you may want to use something like json.loads() to get a python dictionary.
For example:
from model import Users
# This returns <class 'mongoengine.queryset.queryset.QuerySet'>
q_set = Users.objects()
json_data = q_set.to_json()
# You might also find it useful to create python dictionaries
import json
dicts = json.loads(json_data)