Skip to content

Instantly share code, notes, and snippets.

@wadey
Created March 7, 2013 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wadey/5111695 to your computer and use it in GitHub Desktop.
Save wadey/5111695 to your computer and use it in GitHub Desktop.
findi -> postgres
from record_location import Base, engine
msg = 'Warning! This will drop your database. Please confirm:'
shall = True if raw_input("%s (y/N) " % msg).lower() == 'y' else False
if not shall:
print "Cancelled database drop and creation..."
else:
print "Dropping and creating the database..."
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
"""
Running this file will dispatch a request to the Find My iPhone API
and write the resulting location into a database.
The credentials to connect to Apple, and the database url should
be present in the environment as environment variables.
"""
import os
import json
from datetime import datetime
from findi import FindMyIPhone
from sqlalchemy import Column, String, DateTime, Integer, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# This will raise an exception of they are not in the environment.
APPLE_EMAIL = os.environ["APPLE_EMAIL"]
APPLE_PASSWORD = os.environ["APPLE_PASSWORD"]
DATABASE_URL = os.environ["DATABASE_URL"]
# Sqlachemy Engine
engine = create_engine(DATABASE_URL)
# Sqlalchemy Base Class
Base = declarative_base()
# Sqlalchemy Session
Session = sessionmaker(bind=engine)
# We'll use db later for database operations.
db = Session()
class Location(Base):
__tablename__ = 'locations'
id = Column(Integer, primary_key=True)
name = Column(String)
latitude = Column(String)
longitude = Column(String)
timestamp = Column(DateTime)
raw = Column(String)
date = Column(DateTime, default=datetime.utcnow,
onupdate=datetime.utcnow)
def __repr__(self):
return "<Location('%s','%s', '%s')>" % (self.latitude, self.longitude, self.date)
def store_location(findi, i):
"Fetches an iPhone location from the Apple API and creates a Location Object"
iphone_location = findi.locate(i)
location = Location()
location.latitude = iphone_location.get('latitude')
location.longitude = iphone_location.get('longitude')
location.name = iphone_location.get('name')
location.timestamp = iphone_location.get('timestamp')
location.raw = json.dumps(iphone_location.get('raw'))
db.add(location)
# Persist to the database
db.commit()
return location
if __name__ == "__main__":
findi = FindMyIPhone(APPLE_EMAIL, APPLE_PASSWORD)
for i, device in enumerate(findi.devices):
try:
location = store_location(findi, i)
print "Succesfully stored: %s" % location
except Exception as e:
print "Unexpected error:", e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment