Example #1
0
class TestAnnotations(unittest.TestCase):
    def setUp(self):
        self.client = Client(MY_OAUTH_KEY,
                             MY_OAUTH_SECRET,
                             host=API_HOST,
                             port=API_PORT)
        self.handle = 'SG_4H2GqJDZrc0ZAjKGR8qM4D'

    def test_get_annotations(self):
        mockhttp = mock.Mock()
        headers = {'status': '200', 'content-type': 'application/json'}
        mockhttp.request.return_value = (
            headers, json.dumps(EXAMPLE_ANNOTATIONS_RESPONSE))
        self.client.http = mockhttp

        res = self.client.get_annotations(self.handle)

        self.assertEqual(mockhttp.method_calls[0][0], 'request')
        self.assertEqual(
            mockhttp.method_calls[0][1][0],
            'http://api.simplegeo.com:80/%s/features/%s/annotations.json' %
            (API_VERSION, self.handle))
        self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')

        # Make sure client returns a dict.
        self.failUnless(isinstance(res, dict))

    def test_get_annotations_bad_handle(self):
        try:
            self.client.get_annotations('bad_handle')
        except TypeError, e:
            self.failUnless(
                str(e).startswith(
                    'simplegeohandle is required to match the regex'))
        else:
class TestAnnotations(unittest.TestCase):

    def setUp(self):
        self.client = Client(MY_OAUTH_KEY, MY_OAUTH_SECRET, host=API_HOST, port=API_PORT)
        self.handle = 'SG_4H2GqJDZrc0ZAjKGR8qM4D'

    def test_get_annotations(self):
        mockhttp = mock.Mock()
        headers = {'status': '200', 'content-type': 'application/json'}
        mockhttp.request.return_value = (headers, json.dumps(EXAMPLE_ANNOTATIONS_RESPONSE))
        self.client.http = mockhttp

        res = self.client.get_annotations(self.handle)

        self.assertEqual(mockhttp.method_calls[0][0], 'request')
        self.assertEqual(mockhttp.method_calls[0][1][0], 'http://api.simplegeo.com:80/%s/features/%s/annotations.json' % (API_VERSION, self.handle))
        self.assertEqual(mockhttp.method_calls[0][1][1], 'GET')

        # Make sure client returns a dict.
        self.failUnless(isinstance(res, dict))

    def test_get_annotations_bad_handle(self):
        try:
            self.client.get_annotations('bad_handle')
        except TypeError, e:
            self.failUnless(str(e).startswith('simplegeohandle is required to match the regex'))
        else:
Example #3
0
 def test_get_feature_useful_validation_error_message(self):
     c = Client('whatever', 'whatever')
     try:
         c.get_feature('wrong thing')
     except TypeError, e:
         self.failUnless(
             str(e).startswith('simplegeohandle is required to match '),
             str(e))
Example #4
0
def im_moody(mood_words):
    """
        Main mood searching def. This will ping the twitter search api
        every [SLEEP_TIME] seconds and find tweets that display a mood, and
        have a location
    """

    # Found it easier to store the parameters as a list
    # so I can update the since_id
    params_list = [
        "q=query",
        "rpp=100",
        "since_id=1"
    ]

    # Get the SimpleGeo Client
    client = Client(SIMPLE_GEO_TOKEN, SIMPLE_GEO_SECRET)

    # update the query to the mood words
    params_list[0] = "q=%s" % '+OR+'.join(mood_words)

    while True:

        # Init an empty list of records
        records = []

        # Search twitter
        json = get_twitter_search_json('&'.join(params_list))

        # if we got something back
        if json:

            # store the results
            results = json["results"]

            # set the since_id so we don't search more than we need
            params_list[2] = "since_id=%s" % json['max_id']

            # if we got at least 1 result
            if len(results) > 0:

                # get the SimpleGeo records from the api
                records = get_records(results)
        else:

            print "API Error: No data returned"

        # Save 90 records at a time
        for chunk in chunker(records, 90):

            # add records to the SimpleGeo Layer
            client.add_records(SIMPLE_GEO_LAYER, chunk)

            # how many records added
            print "%s %s records added" % (len(chunk), mood_words[0])

        # Wait x seconds before continuing
        time.sleep(SLEEP_TIME)
Example #5
0
    def __init__(self, key, secret, api_version='1.0', host='api.simplegeo.com', port=80):
        self.subclient = True
        ParentClient.__init__(self, key, secret, host=host, port=port)

        self.endpoints.update([
            # Context
            ('context', '1.0/context/%(lat)s,%(lon)s.json'),
            ('context_by_ip', '1.0/context/%(ip)s.json'),
            ('context_by_my_ip', '1.0/context/ip.json'),
            ('context_by_address', '1.0/context/address.json')])
Example #6
0
    def __init__(self, key, secret, api_version='1.0', host='api.simplegeo.com', port=80):
        self.subclient = True
        ParentClient.__init__(self, key, secret, host=host, port=port)

        self.endpoints.update([
            # Places
            ('create', '1.0/places'),
            ('search', '1.0/places/%(lat)s,%(lon)s.json'),
            ('search_by_ip', '1.0/places/%(ipaddr)s.json'),
            ('search_by_my_ip', '1.0/places/ip.json'),
            ('search_by_address', '1.0/places/address.json')])
Example #7
0
def im_moody(mood_words):
    """
        Main mood searching def. This will ping the twitter search api
        every [SLEEP_TIME] seconds and find tweets that display a mood, and
        have a location
    """

    # Found it easier to store the parameters as a list
    # so I can update the since_id
    params_list = ["q=query", "rpp=100", "since_id=1"]

    # Get the SimpleGeo Client
    client = Client(SIMPLE_GEO_TOKEN, SIMPLE_GEO_SECRET)

    # update the query to the mood words
    params_list[0] = "q=%s" % '+OR+'.join(mood_words)

    while True:

        # Init an empty list of records
        records = []

        # Search twitter
        json = get_twitter_search_json('&'.join(params_list))

        # if we got something back
        if json:

            # store the results
            results = json["results"]

            # set the since_id so we don't search more than we need
            params_list[2] = "since_id=%s" % json['max_id']

            # if we got at least 1 result
            if len(results) > 0:

                # get the SimpleGeo records from the api
                records = get_records(results)
        else:

            print "API Error: No data returned"

        # Save 90 records at a time
        for chunk in chunker(records, 90):

            # add records to the SimpleGeo Layer
            client.add_records(SIMPLE_GEO_LAYER, chunk)

            # how many records added
            print "%s %s records added" % (len(chunk), mood_words[0])

        # Wait x seconds before continuing
        time.sleep(SLEEP_TIME)
Example #8
0
    def __init__(self, key, secret, **kwargs):
        ParentClient.__init__(self, key, secret, **kwargs)

        self.endpoints.update(
            feature='1.2/places/%(place_id)s.json',
            search='1.2/places/%(lat)s,%(lon)s.json',
            search_text='1.2/places/search.json',
            search_bbox='1.2/places/%(lat_sw)s,%(lon_sw)s,%(lat_ne)s,%(lon_ne)s.json',
            search_by_ip='1.2/places/%(ipaddr)s.json',
            search_by_my_ip='1.2/places/ip.json',
            search_by_address='1.2/places/address.json')
Example #9
0
    def __init__(self, key, secret, api_version="1.0", **kwargs):
        ParentClient.__init__(self, key, secret, **kwargs)

        context_endpoints = [
            ["context", "/context/%(lat)s,%(lon)s.json"],
            ["context_by_ip", "/context/%(ip)s.json"],
            ["context_by_my_ip", "/context/ip.json"],
            ["context_by_address", "/context/address.json"],
            ["context_from_bbox", "/context/%(sw_lat)s,%(sw_lon)s,%(ne_lat)s,%(ne_lon)s.json"],
        ]

        self.endpoints.update(map(lambda x: (x[0], api_version + x[1]), context_endpoints))
Example #10
0
    def __init__(self, key, secret, api_version='1.0', **kwargs):
        ParentClient.__init__(self, key, secret, **kwargs)

        places_endpoints = [
            ['create', '/places'],
            ['search', '/places/%(lat)s,%(lon)s.json'],
            ['search_by_ip', '/places/%(ipaddr)s.json'],
            ['search_by_my_ip', '/places/ip.json'],
            ['search_by_address', '/places/address.json']
        ]

        self.endpoints.update(map(lambda x: (x[0], api_version+x[1]), places_endpoints))
Example #11
0
    def __init__(self, key, secret, api_version='1.0', **kwargs):
        self.subclient = True
        ParentClient.__init__(self, key, secret, **kwargs)

        context_endpoints = [
            ['context', '/context/%(lat)s,%(lon)s.json'],
            ['context_by_ip', '/context/%(ip)s.json'],
            ['context_by_my_ip', '/context/ip.json'],
            ['context_by_address', '/context/address.json'],
            ['context_from_bbox', '/context/%(sw_lat)s,%(sw_lon)s,%(ne_lat)s,%(ne_lon)s.json']
        ]

        self.endpoints.update(map(lambda x: (x[0], api_version+x[1]), context_endpoints))
Example #12
0
    def __init__(self, key, secret, api_version='0.1', **kwargs):
        ParentClient.__init__(self, key, secret, **kwargs)

        storage_endpoints = [
            ['record', '/records/%(layer)s/%(id)s.json'],
            ['records', '/records/%(layer)s/%(ids)s.json'],
            ['add_records', '/records/%(layer)s.json'],
            ['history', '/records/%(layer)s/%(id)s/history.json'],
            ['nearby', '/records/%(layer)s/nearby/%(arg)s.json'],
            ['layer', '/layers/%(layer)s.json'],
            ['layers', '/layers.json']
        ]

        self.endpoints.update(map(lambda x: (x[0], api_version+x[1]), storage_endpoints))
Example #13
0
 def setUp(self):
     self.client = Client(MY_OAUTH_KEY,
                          MY_OAUTH_SECRET,
                          host=API_HOST,
                          port=API_PORT)
     self.query_lat = D('37.8016')
     self.query_lon = D('-122.4783')
Example #14
0
    def __init__(self,
                 key,
                 secret,
                 api_version='1.0',
                 host='api.simplegeo.com',
                 port=80):
        self.subclient = True
        ParentClient.__init__(self, key, secret, host=host, port=port)

        self.endpoints.update([
            # Context
            ('context', '1.0/context/%(lat)s,%(lon)s.json'),
            ('context_by_ip', '1.0/context/%(ip)s.json'),
            ('context_by_my_ip', '1.0/context/ip.json'),
            ('context_by_address', '1.0/context/address.json')
        ])
Example #15
0
    def setUp(self):
        self.client = Client(config.MY_OAUTH_KEY, config.MY_OAUTH_SECRET, host=config.API_HOST, port=config.API_PORT)
        self.known_points = {
            'darrell_k_royal_stadium': {
                'lat': 30.283863,
                'lon': -97.732519,
                'expected_response': EXPECTED_RESPONSES['darrell_k_royal_stadium']
            },
            'att_park': {
                'lat': 37.778434,
                'lon': -122.389146,
                'expected_response': EXPECTED_RESPONSES['att_park']
            },
            'invesco_field': {
                'lat': 39.744026,
                'lon': -105.019893,
                'expected_response': EXPECTED_RESPONSES['invesco_field']
            }
        }

        # Request known points.
        self.known_requests = []
        for (point_name, point) in self.known_points.iteritems():
            point['name'] = point_name
            response = self.client.context.get_context(point['lat'], point['lon'])
            self.known_points[point_name]['response'] = response
            self.known_requests.append((point, response))

        # Request random points.
        self.random_requests = []
        for i in range(10):
            (lat, lon) = random_lat_lon()
            point = {'lat': lat, 'lon': lon}
            response = self.client.context.get_context(lat, lon)
            self.random_requests.append((point, response))
Example #16
0
    def __init__(self,
                 key,
                 secret,
                 api_version='1.0',
                 host='api.simplegeo.com',
                 port=80):
        self.subclient = True
        ParentClient.__init__(self, key, secret, host=host, port=port)

        self.endpoints.update([
            # Places
            ('create', '1.0/places'),
            ('search', '1.0/places/%(lat)s,%(lon)s.json'),
            ('search_by_ip', '1.0/places/%(ipaddr)s.json'),
            ('search_by_my_ip', '1.0/places/ip.json'),
            ('search_by_address', '1.0/places/address.json')
        ])
Example #17
0
    def __init__(self,
                 key,
                 secret,
                 api_version='0.1',
                 host='api.simplegeo.com',
                 port=80):
        self.subclient = True
        ParentClient.__init__(self, key, secret, host=host, port=port)

        self.endpoints.update([
            ('record', '0.1/records/%(layer)s/%(id)s.json'),
            ('records', '0.1/records/%(layer)s/%(ids)s.json'),
            ('add_records', '0.1/records/%(layer)s.json'),
            ('history', '0.1/records/%(layer)s/%(id)s/history.json'),
            ('nearby', '0.1/records/%(layer)s/nearby/%(arg)s.json'),
            ('layer', '0.1/layers/%(layer)s.json'),
            ('layers', '0.1/layers.json')
        ])
Example #18
0
 def calculate_timezone(self):
     from simplegeo import Client
     client = Client('oauth key', 'oauth secret SHH')
     response = client.context.get_context_by_address(self.location)
     for feature in response['features']:
         if feature['classifiers'][0]['category'] == 'Time Zone':
             timezone = feature['name']
     self.timezone = timezone
     self.put()
Example #19
0
def main():
    tweet_ids = []
    client = Client(MY_OAUTH_KEY, MY_OAUTH_SECRET)
    my_tweets = tweepy.api.user_timeline(MY_TWITTER_USERNAME)
    print "\n\n" 
        
    for tweet in my_tweets:
        if (tweet.geo):
            lat = tweet.geo['coordinates'][0]
            lng = tweet.geo['coordinates'][1]
        else:
            lat = 0
            lng = 0
        
        if (tweet.place):
            place_name = tweet.place['full_name']
            place_URL = tweet.place['url']
        else: 
            place_name = "None"
            place_URL = "None"
                             
        tweet_URL = "http://twitter.com/" + tweet.user.screen_name + "/" + str(tweet.id)
        created_t = tweet.created_at - datetime.timedelta(seconds=7*60*60)
        created_t = int(time.mktime(created_t.timetuple()))
        if (tweet.geo):
            record = Record(
		        layer=MY_LAYER,
		        id=str(tweet.id),
		        lat=lat,
		        lon=lng,
		        created=created_t,
		        text=tweet.text,
		        URL=tweet_URL,
		        type="object"
	        )
            print "\nCreated record with ID: %s" % record.id
            records.append(record)
  
    for chunk in chunker(records, 90):
        client.add_records(MY_LAYER, chunk)
        print "\n%s records added" % len(chunk)
Example #20
0
 def setUp(self):
     self.client = Client(MY_OAUTH_KEY,
                          MY_OAUTH_SECRET,
                          host=API_HOST,
                          port=API_PORT)
     self.handle = 'SG_4H2GqJDZrc0ZAjKGR8qM4D'
Example #21
0
 def setUp(self):
     self.client = Client(MY_OAUTH_KEY, MY_OAUTH_SECRET, host=API_HOST, port=API_PORT)
     self.handle = 'SG_4H2GqJDZrc0ZAjKGR8qM4D'
Example #22
0
 def test_get_feature_useful_validation_error_message(self):
     c = Client('whatever', 'whatever')
     try:
         c.get_feature('wrong thing')
     except TypeError, e:
         self.failUnless(str(e).startswith('simplegeohandle is required to match '), str(e))
Example #23
0
import cherrypy
import pymongo
import urllib2
from simplegeo import Client
from pymongo import Connection
from Cheetah.Template import Template


connection = Connection()
db = connection['meetme']
client = Client('p2R3QHMxH3xZV6SAgeTdb6sqrxG6Qk8f','XbF4sZxLyhNDMzjykHmVysbzYtnbEtCn')


class Index(object):
    def group(self,name="",error=""):

        group_collection = db.Groups
        group = group_collection.find_one({"name":name})

        grouppage_t = open('grouppage.tmpl', 'r')
        self.grouppage_template = grouppage_t.read()

        g_exist = self.group_exist(name)
        if g_exist > 0:
            max_num = group["max"]
            cur_num = group["joined"]
            namespace = {"cur_num":cur_num,"max_num":max_num}
            namespace["error"] = error
            namespace["name"] = name

            if g_exist == 1:
Example #24
0
 def setUp(self):
     self.client = Client(MY_OAUTH_KEY,
                          MY_OAUTH_SECRET,
                          host=API_HOST,
                          port=API_PORT)