Created
November 29, 2011 04:26
-
-
Save evanlong/1403409 to your computer and use it in GitHub Desktop.
twitter image fetcher
This file contains hidden or 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
#!/usr/bin/env python | |
""" Sample calls: | |
http://twimgproxy.appspot.com/image?screen_name=evanlong | |
http://twimgproxy.appspot.com/image?user_id=20 | |
""" | |
from google.appengine.ext import webapp | |
from google.appengine.ext.webapp import util | |
from google.appengine.api.urlfetch import fetch | |
import simplejson as json | |
import logging | |
import urllib | |
class ImageHandler(webapp.RequestHandler): | |
def get(self): | |
BASE_URL = "https://api.twitter.com/1/users/show.json?" | |
screen_name = self.request.get("screen_name") | |
user_id = self.request.get("user_id") | |
fetch_response = None | |
if screen_name: | |
params = urllib.urlencode({"screen_name": screen_name}) | |
fetch_response = fetch(BASE_URL + params) | |
elif user_id: | |
params = urllib.urlencode({"user_id": user_id}) | |
fetch_response = fetch(BASE_URL + params) | |
else: | |
self.error(404) | |
return | |
limit = fetch_response.headers.get("X-RateLimit-Remaining") | |
if limit: | |
self.response.headers["X-Twitter-RateLimit-Remaining"] = limit | |
if fetch_response.status_code != 200: | |
self.error(404) | |
return | |
content = fetch_response.content | |
parsed = {} | |
try: | |
parsed = json.loads(content) | |
except ValueError: | |
logging.error("Invalid json for request %s" % self.request) | |
image_url = parsed.get("profile_image_url_https") | |
if image_url: | |
self.redirect(image_url) | |
else: | |
self.error(404) | |
def main(): | |
application = webapp.WSGIApplication([('/image', ImageHandler)], | |
debug=True) | |
util.run_wsgi_app(application) | |
if __name__ == '__main__': | |
main() |
I don't really get its "screen_name" it works but if the user name is an integer then it lookups up by user_id.
http://api.twitter.com/1/users/profile_image/14967425.json -> @evanlong image instead of @14967425 image. Not that big a deal but @Divi said he would pay for a service that worked with user_id and screen_name so I did my best effort to think about the quirks. Gotta work hard for my €€€ although it's mostly a troll script.
Although it is slow and still rate limited. And only sort of works around rate limiting because google's url fetchers have many IPs they work from (looking at the rate limit headers coming back I am obviously not the only person using app engine for this)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not use Twitter? users/profile_image/:screen_name