Reputation: 1264
I am trying to update Firebase entity using PATCH. Here is what I have:
Data:
'foo': {
'bar': 'baz'
}
Rules:
"foo": {
".write": true,
".read": true,
"bar": {
".write": true,
".read": true,
}
},
Code:
import urllib
import urllib2
AUTH_SECRET = 'redacted'
BASE_URL = 'redacted'
URL = BASE_URL + '/foo/.json'
values = {'bar' : 'baz3'}
data = urllib.urlencode(values)
request = urllib2.Request(URL + '?auth=' + AUTH_SECRET, data)
request.get_method = lambda: 'PATCH'
resp = urllib2.urlopen(request)
print resp.read()
I am getting "HTTP Error 400: Bad Request".
Upvotes: 1
Views: 3094
Reputation: 14997
Why use urllib to build the URL with the params? You can just give them as dict to requests.
Upvotes: 1
Reputation: 541
You can wrap the code for sending requests in try/except
and then read what is sent back as a content in case of an error, like this:
from urllib2 import HTTPError
try:
resp = urllib2.urlopen(request)
except HTTPError as e:
print e.read()
I ran your code and that's what I received:
{
"error" : "Invalid data; couldn't parse JSON object. Are you sending a JSON object with valid key names?"
}
So Firebase expects you to send data in JSON while you sending it like a URL query string 'bar=baz3'
. Thus serializing the data into a JSON formated string would fix the error:
import json
values = {'bar': 'baz3'}
data = json.dumps(values)
Also I would recommend you to use Requests library, since it's much nicer to use.
First of all install Requests:
pip install requests
And then you could do it like this:
import urllib
import requests
AUTH_SECRET = 'redacted'
BASE_URL = 'redacted'
get_params = urllib.urlencode({'auth': AUTH_SECRET})
url = BASE_URL + '/foo/.json' + '?' + get_params
data = {'bar': 'baz3'}
resp = requests.patch(url, json=data)
print resp.json()
Upvotes: 2