Created
June 16, 2017 01:58
-
-
Save cjoshmartin/2913e4bf12b1f3a8e3cdd60fe1f56bec to your computer and use it in GitHub Desktop.
Example of using firebase's RESTful API in python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests ## you need to do a pip install requests | |
class database(object): | |
def __init__(self): | |
object.__init__(self) | |
self.baseUrl= "https://{YourDatabaseHere}.firebaseio.com/cars/" | |
# utilities | |
def urlBuilder(self,name="",color="",make="",year=0,parm=""): | |
car= self.makeTitle(name.lower(),color.lower(),make.lower(),year).replace(" ","%20") | |
if(parm != ""): | |
print("{}{}/{}.json".format(self.baseUrl,car.lower(),parm.lower()) ) | |
return "{}{}/{}.json".format(self.baseUrl,car.lower(),parm.lower()) | |
return "{}{}.json".format(self.baseUrl, car) | |
def makeTitle(self,name="",color="",make="",year=0): | |
return "{} {} {} {}".format(year,color.lower(),make.lower(),name.lower()) | |
# database commands | |
def get(self,name="",color="",make="",year=0,parm=""): | |
r=requests.get(self.urlBuilder(name,color,make,year,parm)) | |
return r.json() | |
def insert(self,name="",color="",make="",year=0,price=0): | |
url =self.urlBuilder(name,color,make,year) | |
req= self.get(name,color,make,year) | |
if req is None: | |
dataStruture ={ | |
"name": name.lower(), | |
"color": color.lower(), | |
"make": make.lower(), | |
"year": year, | |
"price": price, | |
"quantity":1 | |
} | |
r=requests.put(url, json=dataStruture) | |
print (r.json()) | |
else: | |
quantity =self.get(name, color, make, year,"quantity") | |
quantity= quantity +1 | |
r= requests.put(self.urlBuilder(name, color, make, year,"quantity"),data=str(quantity)) | |
print (r.json()) | |
def main(): | |
a =database() | |
a.insert("Civic","orange","Honda",2017,23000) | |
#print(a.get("Civic","red","Honda","2017","quantity")) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment