Firebase delete method - python

i have a json in Realtime firebase that look something like that :
{
"-NMtZNTISnGhT-rdibeb": {
"motorista": "Jose",
"plate": "IZC2F45",
"produto": "caroco",
"transp": "VIDAL"
},
"-NN1zI2MHFtbi6G5qUvR": {
"motorista": "ANTONIO",
"plate": "AWJ-9353",
"produto": "CAROCO",
"transp": "GRANLIDER"
}
}
I'm working with a python code that sould delete a select line from a Treeview(Tkinter) and also delete from this database. The method Delete is called from a Button(tkinter). Actually he delete only the select line from Treeview, but don't delete from database.
def delete(self):
selected_item = self.tree.selection()
if selected_item:
id = self.tree.item(selected_item, "text")
url = self.base_url + id + '.json'
response = requests.delete(url)
print(url)
print(response)
if response.status_code == 200:
self.tree.delete(selected_item)
messagebox.showinfo("Info", "Linha deletada com sucesso!")
else:
messagebox.showerror("Erro", "Não foi possível deletar a linha!")
else:
messagebox.showerror("Erro", "Nenhum item selecionado para deletar!")
also, i made 2 prints to check what he gave me. and this is what i got from prints:
ttps://fila2-6bd6b-default-rtdb.firebaseio.com/-NNh38XBrRen17bGWHga.json
<Response [200]>
already tried chatgpt, reddit. Already check the Rules from laboratory in firebase and he allowed to use Delete, get, update.
https://github.com/ChristopherMachad/truckQueueOnline/blob/main/Main.py

Related

Get data for JSON Python second List

Hoping you are good
I am trying to get data from zendisk by API and Python Json
i can get any data Value under Audits LikeTicket_id and auther_id but when tried get data under Events such as Body
keep get this error
print(audit['body'])
KeyError: 'body'
JSON Output
{
"audits":[
{
"id":1727876301271,
"ticket_id":54010951,
"created_at":"2021-10-21T10:58:06Z",
"author_id":12306596687,
"metadata":{
"system":{
"client":"GuzzleHttp/6.2.1 curl/7.29.0 PHP/7.1.2",
"ip_address":"x.x.x.x",
"location":"Boardman, OR, United States",
"latitude":45.8491,
"longitude":-119.7143
},
"custom":{
}
},
"events":[
{
"id":1727876301291,
"type":"Comment",
"author_id":366289833251,
"body":"Sehr geehrte Damen und Herren,\n\nIn unserer Bestellung fehlt das Kleid, es war nicht mit dabei, obwohl es hätte drin sein müssen.\nFreundliche Grüße",
"attachments":[
],
"audit_id":1727876301271
},
{
"id":1727876301311,
"type":"Create",
"value":"366289833251",
"field_name":"requester_id"
},
Python Code
import requests
import csv
# Settings
auth = 'xxxxxxx', 'xxxxxx'
view_tickets = []
view_id = 214459268
view_audits = []
ticket_id = 54010951
view_events =[]
print(f'Getting tickets from ticket_id ID {ticket_id}')
url = f'https://xxxx.zendesk.com/api/v2/tickets/54010951/audits.json'
while url:
response = requests.get(url, auth=auth)
page_data = response.json()
audits = page_data['audits'] # extract the "tickets" list from the page
view_audits.extend(audits)
url = page_data['next_page']
for audit in audits:
print(audit['body'])
You know you're overwriting, not adding, to audits right? (in this line: audits = page_data['audits']). I don't think that makes sense, but it's hard to know your intent.
To fix the error itself, your json structure has the body key inside the events key. So you can access it with:
print(audit['events'][0]['body'])
or, using another loop:
for audit in audits:
for event in audit['events']
print(event['body'])
You might get an error for the 2nd one because it doesn't appear to have the body key. You can add an if statement to handle that if you want.

Facebook Graph API | Request [400] Errorr

I create a bot to monitor the comment if there is any new comment and if so it will automatically private_replies them But instead i got a Request [400] Error instead.
def monitor_comment():
print("Bot is monitoring comments")
time.sleep(5)
comment_data = graph.get_connections(COMBINED_POST_ID_TO_MONITOR,"comments",order='reverse_chronological')
commends = []
for comment in comment_data['data'][:10]:
commends.append (comment)
data = commends[0]['id']
data_converted = str(data)
#time.sleep(5)
print(data)
return data_converted
def private_reply(comment_ids):
url = "https://graph.facebook.com/v12.0/me/messages?"
access = {"access_token":Page_Token}
params = {
"recipient": {
"comment_id": comment_ids
},
"message": {
"text":"Testing Private_Replies"
}
request = requests.post(url=url, files=access, json=params)
print(request)
This is the logs
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500,"fbtrace_id":"AMCiqy1Aw8CyODPlUBE1b98"}}

List object has no attribute 'detectedLanguage'

I'm using microsoft azure translator api to detect and translate the language the user is inputting and translating it back to english. After translating it, I'm printing the results in json format, which can be seen here: https://i.stack.imgur.com/Zcq9l.png
Afterwards, I'm trying to print whatever is translated after the 'text:' bit, however, I keep getting an error each time I try to do so. I tried using a for loop and referencing them, but it doesn't work.
Here is the code bit:
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': ['en']
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
user_input = input("You: ")
body = [{
"text": user_input
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
json_data = json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(",", ": "))
print(json_data)
print("Translated Text: " + response.detectedLanguage.translations.text)
The final line is what's causing the error, but I'm not sure how to resolve it. I would appreciate if someone can guide me accordingly.
[1]: https://i.stack.imgur.com/Zcq9l.png
The object is a List of Dictionaries (just one in this case). As seen in the linked image.
In this particular case, to reach the translation text, you need to do:
response[0]["translations"]["text"]

New Twitch API getting json data Python 3

I am trying to get a python script to say whether a twitch channel is live but haven't been able to do it, any and all help would be appreciated.
here are the docs I've been able to find
https://dev.twitch.tv/docs/api/guide
This is what I have atm but I keep on getting "'set' object has no attribute 'items'". This is modified code from "Is There Any Way To Check if a Twitch Stream Is Live Using Python?" however it is now outdated because of the new API.
import requests
def checkUser():
API_HEADERS = {
'Client-ID : [client id here from dev portal]',
'Accept : application/vnd.twitchtv.v5+json',
}
url = "https://api.twitch.tv/helix/streams/[streamer here]"
req = requests.Session().get(url, headers=API_HEADERS)
jsondata = req.json()
print(jsondata)
checkUser()
The answer to your problem of "'set' object has no attribute 'items'" is just a simple typo. It should be
API_HEADERS = {
'Client-ID' : '[client id here from dev portal]',
'Accept' : 'application/vnd.twitchtv.v5+json'
}
Notice how the Colon's aren't part of the text now
And to answer your overarching question of how to tell if a channel is online you can look at this sample code I made.
import requests
URL = 'https://api.twitch.tv/helix/streams?user_login=[Channel_Name_Here]'
authURL = 'https://id.twitch.tv/oauth2/token'
Client_ID = [Your_client_ID]
Secret = [Your Client_Secret]
AutParams = {'client_id': Client_ID,
'client_secret': Secret,
'grant_type': 'client_credentials'
}
def Check():
AutCall = requests.post(url=authURL, params=AutParams)
access_token = AutCall.json()['access_token']
head = {
'Client-ID' : Client_ID,
'Authorization' : "Bearer " + access_token
}
r = requests.get(URL, headers = head).json()['data']
if r:
r = r[0]
if r['type'] == 'live':
return True
else:
return False
else:
return False
print(Check())

Database fields not updating through REST API after migrating to ParseServer from parse.com

I migrated from parse.com to an hosted ParseSever. Most of the things are working, however I found that for one class, the fields are not updated. The HTTP request returns 200 in logs and in Python, updatedAt field shows the recent timestamp, but the fields are not changed. In the python code and its printout below, fields field1 and field2 continue to show old values even when updatedAt and HTTP response check out. Updates to other classes from REST API are generally working (have not checked exhaustively). Updates from SDK are working. Was working flawlessly on parse.com. ACL of class and entries are public.
def updateObjectWithId(self,objectId, objectJson):
self.connection.connect()
if(objectId == ""):
self.connection.request('POST','/parse/classes/'+self._className,objectJson,
{
"X-Parse-Application-Id": self.appId,
"X-Parse-Master-Key": self.masterApiKey
})
else:
print "ParseArchiver.updateObjectWithId: id: ", objectId, " of Class: ", self._className, " with json: ", objectJson
self.connection.request('PUT','/parse/classes/'+self._className+'/'+objectId,objectJson,
{
"X-Parse-Application-Id": self.appId,
"X-Parse-Master-Key": self.masterApiKey
})
result = json.loads(self.connection.getresponse().read())
time.sleep(ParseArchiver.ParseSleepTime)
print "*** ParseArchiver.updateObjectWithId: Result object is:",result
return
The output:
PredictionObject.write(): updating existing object with ID: On6AdEnPVb
ParseArchiver.updateObjectWithId: id: correct_id of Class: correct_class with json: {"field1": ["2016-06-07T22:00:00.000Z|0.267835319042|-0700", "2016-06-08T10:00:00.000Z|0.446276366711|-0700", "2016-06-08T22:00:00.000Z|0.778348565102|-0700", "2016-06-09T10:00:00.000Z|0.00348118506372|-0700", "2016-06-09T22:00:00.000Z|0.0183897037059|-0700", "2016-06-10T10:00:00.000Z|0.562650620937|-0700", "2016-06-10T22:00:00.000Z|0.079613097012|-0700", "2016-06-11T10:00:00.000Z|0.562650620937|-0700", "2016-06-11T22:00:00.000Z|0.0199579093605|-0700", "2016-06-12T10:00:00.000Z|0.629606068134|-0700", "2016-06-12T22:00:00.000Z|0.292343884706|-0700", "2016-06-13T10:00:00.000Z|0.0342484489083|-0700", "2016-06-13T22:00:00.000Z|0.0746899694204|-0700", "2016-06-14T10:00:00.000Z|0.0594595149159|-0700", "2016-06-14T22:00:00.000Z|0.424203515053|-0700", "2016-06-15T10:00:00.000Z|0.0349752865732|-0700", "2016-06-15T22:00:00.000Z|0.00455725379288|-0700", "2016-06-16T10:00:00.000Z|0.0987700968981|-0700", "2016-06-16T22:00:00.000Z|0.30742970109|-0700", "2016-06-17T10:00:00.000Z|0.0781866833568|-0700", "2016-06-17T22:00:00.000Z|0.367497861385|-0700", "2016-06-18T10:00:00.000Z|0.225806906819|-0700", "2016-06-18T22:00:00.000Z|0.0179004631937|-0700", "2016-06-19T10:00:00.000Z|0.11387591809|-0700", "2016-06-19T22:00:00.000Z|0.103792026639|-0700", "2016-06-20T10:00:00.000Z|0.710064172745|-0700", "2016-06-20T22:00:00.000Z|0.728509664536|-0700", "2016-06-22T10:00:00.000Z|0.140641510487|-0700"], "uid": "correct_uid", "field2": ["2016-06-20T22:00:00.000Z|0.728509664536|-0700", "2016-06-22T10:00:00.000Z|0.140641510487|-0700"]}
*** ParseArchiver.updateObjectWithId: Result object is: {u'updatedAt': u'2016-06-22T16:38:55.690Z'}
I found that every non-GET request must have a "Content-Type" field now. This was not required on parse.com. I am thinking may be ParseServer can be set-up with a default content type that would allow one to omit this parameter and then old code will work w/o modifications. The modified working code snippet is below:
def updateObjectWithId(self,objectId, objectJson):
self.connection.connect()
if(objectId == ""):
self.connection.request('POST','/parse/classes/'+self._className,objectJson,
{
"X-Parse-Application-Id": self.appId,
"X-Parse-Master-Key": self.masterApiKey,
"Content-Type": "application/json" #This made it work
})
else:
print "ParseArchiver.updateObjectWithId: id: ", objectId, " of Class: ", self._className, " with json: ", objectJson
self.connection.request('PUT','/parse/classes/'+self._className+'/'+objectId,objectJson,
{
"X-Parse-Application-Id": self.appId,
"X-Parse-Master-Key": self.masterApiKey,
"Content-Type": "application/json" #This made it work.
})
result = json.loads(self.connection.getresponse().read())
time.sleep(ParseArchiver.ParseSleepTime)
print "*** ParseArchiver.updateObjectWithId: Result object is:",result
return

Categories

Resources