Posts

How to Integrate Firebase Into Your App

William HillWilliam is a Software Engineer at Lawrence Livermore Lab by day and a Senior Instructor for Hackbright’s Intro to Programming course by night. He developed a passion for teaching while earning his Bachelor’s and Master’s degrees in Computer Science from Mississippi State University.  He has a drive for increasing diversity in tech and has volunteered with Black Girls Code, the Hidden Genius Project and is a member of /dev/color. When he isn’t churning out code, he enjoys playing basketball, strength training, and playing video games. Follow him on twitter at @emjay_hill.



Looking for an easy way to add a database to your Python app? We’ll show you how to get started with Firebase. Creating an app isn’t easy, but learning how to store your app’s vital data is! Here is a step-by-step tutorial to help you figure out how to connect to a database with Firebase and take the headache out of data storage and retrieval. A Python app without Firebase is like a chicken without a hen-house; if you don’t have a place to store your eggs, it’s time to re-think the farm.computer on fire

You have created this awesome new app that you want to share with the world.  Your code has elegantly structured Classes, efficient Loops, and well commented Functions. You fire up your app and start creating Objects.  Life is good.

woohoo

But then you shut down your interpreter and all of your newly created data is gone.  

crying

Surely there has to be some simple way to save data associated with you app.  Someone must have thought of a better way than just throwing data in text files, right?  Right?!?  Well you’re in luck, because that’s exactly what databases are for.

A database is a collection of data that can be structured to describe attributes and relationships between data entities of a program.  The ability to save data associated with your app makes your app…useful.

This tutorial will show you how to connect to a database hosted by Firebase to store and retrieve data.

Creating a Firebase Account

Creating a Firebase account is simple.  You can register using an existing Google account at https://firebase.google.com/

Installing pip

Before we can connect to our Firebase database with Python, we need to download a couple of helper modules.  We are going to use pip to install them.

Pip is a package manager (i.e. a software application that helps you download and update software packages) that can install and manage Python packages obtained from third party repositories (i.e. sites where anyone can write and share code for other people to use). Many python distributions have pip pre-installed.

You can check to see if you currently have pip install by running the command in the terminal:

pip --version

If it is not currently installed, you can install pip by running following command:

curl https://bootstrap.pypa.io/get-pip.py | python

Installing Pyrebase

Pyrebase is a Python interface to Firebase’s REST API. In layman’s terms, it allows you to use Python to manipulate your Firebase database. The documentation for Pyrebase can be found at https://github.com/thisbejim/Pyrebase

We will install the Pyrebase and its dependencies using pip

sudo pip install Pyrebase

Aside: sudo is a terminal command that temporarily grants the current user (aka you) root access to the file system.  It will typically ask you to enter a password, which will normally be the same password to use to login to your computer. Don’t freak out if start entering the password and don’t see any characters showing up in the terminal.  Your password is still being entered (though its not the best UX design by any stretch).

Connecting to your database

Now we can import the Pyrebase module into a file and make a connection to our Firebase database

import pyrebase
config = {
  "apiKey": "apiKey",
  "authDomain": "projectId.firebaseapp.com",
  "databaseURL": "https://databaseName.firebaseio.com",
  "storageBucket": "projectId.appspot.com",
  "serviceAccount": "path/to/serviceAccountCredentials.json"
}

firebase = pyrebase.initialize_app(config)

We define a dictionary named config with several key-value pairs that configure the connection to the database.  The apiKey, authDomain, databaseUrl, and storageBucket values needed to connect to your database can be found at by clicking the Web Setup link in the Auth tab of the Firebase console.  The value for the serviceAccount is actually a JSON file that can be generated by Firebase.

You’ll need to create a service account by going to https://console.firebase.google.com/iam-admin/serviceaccounts and clicking the Create Service Account button in the Service Account tab.  Be sure to check the Furnish a new private key option.  The JSON file will then be downloaded and you can reference its file path in the config dictionary.

Authentication

The default permissions of a Firebase database requires authentication to perform read or write actions.  The simplest way to authenticate is by signing in with an email and password.  A new user can be created in the Auth tab of the Firebase console.  Once a user is created, the following Pyrebase code can be used to created an authentication connection:

auth = firebase.auth()
#authenticate a user
user = auth.sign_in_with_email_and_password("william@hackbrightacademy.com", "mySuperStrongPassword")

The user variable now holds a reference to an authenticated user.  The user’s token that is needed to perform certain actions can be referenced like so:

user['idToken'] 

The user token will need to be passed as a parameter to the get(), push(), set(), update() and remove() functions described below in order to authorize the actions.

Now that we are connected to the database and properly authenticated, let’s perform some actions.

CRUD-dy Behavior

The main functionalities of a database interface are the abilities to create, read, update, and delete data.  The aforementioned abilities are commonly referred to as the CRUD functions. The Pyrebase module provides a simple interface for performing each of the CRUD functions.

Create

There are two methods available for creating a new data entity in your database, push() and set().  These methods can be used in conjunction with the child() method, which builds paths to objects in the database.

The push() method creates a unique, time-stamped based alphanumeric key for the data that’s being added to your database.  That’s good in some cases, but not great when you want to refer to that key.

archer = {"name": "Sterling Archer", "agency": "Figgis Agency"}
db.child("agents").push(archer, user['idToken'])

The set method on the other hand provides a much nicer way to create keys that can be retrieved.

lana = {"name": "Lana Kane", "agency": "Figgis Agency"}
db.child("agents").child("Lana").set(lana, user['idToken'])

Read

Data can be read from your database using the get() method.  The get() method returns a PyreResponse object from the database.  Using the val() method on the PyreResponse object will return the actual data.

You can get all of the values of an object

all_agents = db.child("agents").get(user['idToken']).val()

Or you can get a specific value of an object

lana_data = db.child("agents").child("Lana").get(user['idToken']).val()

Update

Updates can be made with the update() method.

db.child("agents").child("Lana").update({"name": "Lana Anthony Kane"}, user['idToken'])
  

Delete

Lastly, we can delete an object from our database.  The remove() method removes objects from the database.

db.child("agents").remove(user['idToken'])

Or a specific value from an object

db.child("agents").child("Lana").remove(user['idToken'])

You should now be able to set up a basic database for your Python apps. The example code can be found here: https://github.com/hackbrightacademy/Pyrebase_Example

 

Until next time, Happy Hacking!  

louiseonfire


 



Hackbright Goes to PyBay!

Screen Shot 2016-03-23 at 12.32.07 PMFormerly an internal tools software engineer, Meggie Mahnken is now happy to be an instructor for Hackbright Academy’s 12-week software engineering fellowship for women.  After much soul-searching years ago, she parted with studies in social cognition and feminist theory to become a software engineer. When she’s not computering, she enjoys modern dance, delis, and public speaking. Follow her on twitter @megthedeveloper.


The Hackbright Fellowship Education Team had the pleasure of attending PyBay,  the inaugural SF Bay Area Regional Python Conference. In planning this conference, the organizers (Simeon Franklin and Grace Law) hoped that it would be akin to the largest Python conference, PyCon, but specific to the Bay Area. 

PyBayWalking into the conference on the first full day, I recognized some familiar faces: Hackbright alumna, fellow engineers I’ve seen/talked to at various Python meetups, and even some people I’d consider to be Python celebrities, such as Raymond Hettinger (core Python language contributor, but more importantly to me, answerer of many amazing Stack Overflow questions about the innards of Python).

Breaking it Down

There were roughly 38 talks, in addition to 20 five-minute lightning talks (one of which I gave!). In the closing statements, the organizers boasted that attendance was 25% women; this announcement was met with applause. The speakers at PyBay were 21% women, including the first keynote speaker. Comparatively, at PyCon 2016, 40% of talks were given by women. Talks were helpfully labelled in the program as either Data, Web, or Fundamentals and Performance.

For readers who haven’t attended a conference, I think it might be helpful to describe what a programmer– myself, in particular– hopes to get out of a tech conference. The promise of inspiration is what initially excites me about a whole weekend devoted to the primary language in which I code. When I attend a conference, I like to learn about a new library, code pattern, or an idea for a new side project. Other reasons I attend (in no particular order): to meet other Python programmers, to push myself to explore unfamiliar/advanced modules in the Python Standard Library, to get updates about how Python is currently growing and changing, and to critique other people’s explanations of things that I already understand. The last point is not meant to be arrogant or judgmental. When teaching Python to new engineers at Hackbright, it’s helpful to be thoughtful about which metaphors and examples work, and which don’t.

Flask and Familiarity

Armin Ronacher’s talk on flask.

This was the first time the education staff was able to attend a Python conference together. We found that the types of things we teach at Hackbright are exactly the kinds of things Python programmers like to talk about at conferences– Python memory subtleties, HTTP protocol and cryptography, runtime and performance. Many of the talks reminded us of lectures we give at Hackbright while others helped us deepen our knowledge of the technologies we teach. For example, we attended a talk about Flask, the Python web framework we teach at Hackbright, given by one of the original authors of Flask, Armin Ronacher. It was delightful to see so many familiar code snippets up on the screen in a different context than our cozy lecture hall.

Wesley Chun

Wesley Chun’s talk on Python memory.

Personally, I wasn’t prepared for the extent to which educators are celebrated and even admired in the Python community. Some of the most popular and well-attended talks were not given by people who write mountains and mountains of code for big tech companies every day, but by people who teach Python for a living. Wesley Chun’s well-attended, lively, and informative talk on Python memory was reinforcing to me both in the sense that we are teaching relevant Python concepts at Hackbright, but also that teaching Python well is just as impressive and important to the community as writing code.

One of the talks that delivered particularly well (in the area of learning new libraries and new concepts) was Python Profiling & Performance: Elementary to Enterprise, given by Mahmoud Hashemi. Mahmoud took a Pythonic approach to understanding performance. Pythonistas (people who write Python) believe in practicality over purity. So, Mahmoud emphasized the importance of optimizations that actually matter, discouraging his audience from micro-optimizing their code. Improvements that you make to your code only matter in relation to the greater context. Can you make a small improvement to code that factors hugely in performance, versus a huge improvement to something that doesn’t play a huge part in determining the performance? It’s easy to waste time making meaningless improvements.

 

Meggie_PyBay

Speaking about a memory optimization technique for object-oriented Python programming.

The Lightning Round

On the first day, I was pleased to hear that lightning talks slots were open to anyone wishing to give a 5-minute talk of their choosing. I seized the chance to present on a technical topic at a Python Conference, choosing to speak about a memory optimization technique for object-oriented Python programming. I signed up on the morning of the last day of the conference for a slot later that day. Throughout the day, something funny happened: though I lecture for 90 minutes at a time at Hackbright as many as 4 or 5 times a week, I immediately started feeling incredibly nervous about a minuscule five minute tech talk. I tried to distract myself throughout the day by trying to deploy my slide deck to my slightly ancient personal website, which helped a bit. Debugging old, crappy code that I wrote always calms me down. With the support and a couple of heroic code reviews from my coworkers, the talk went well. I was even able to show off one of the performance profiling tools I had learned about that morning, bringing the conference full circle for me.

Thanks to all the PyBay organizers and volunteers, and thanks to Hackbright for sending the Education Team to learn “all the things”! I can’t wait until next year.

Screen Shot 2016-08-26 at 6.56.39 PM

Hackbright’s Education Team and alumnae!


Hackbright Academy is the leading engineering school for women in San Francisco dedicated to closing the gender gap in the tech industry. Learn more about our full-time software engineering fellowshipIntro to Programming night courses, volunteer mentor opportunities, and how to partner with us to hire female software engineers and #changetheratio of women in tech!