Skip to content

Instantly share code, notes, and snippets.

@yahelc
Created July 4, 2011 00:52
Show Gist options
  • Save yahelc/1062772 to your computer and use it in GitHub Desktop.
Save yahelc/1062772 to your computer and use it in GitHub Desktop.
FollowTheRedirect.AppSpot.com source
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
import urlparse
import urllib
from google.appengine.api.urlfetch import DownloadError
class MainHandler(webapp.RequestHandler):
def get(self):
url = urllib.unquote_plus(self.request.get("url"))
callback = self.request.get("callback")
content_type = "application/javascript"
parsed = urlparse.urlparse(url)
if callback=="" and url!="":
self.response.headers["Content-Type"] = content_type
self.response.out.write("Error. Callback parameter required")
elif not hasattr(parsed,"scheme") or not hasattr(parsed,"netloc") or parsed.scheme not in ("http, https") or parsed.netloc=='':
self.response.headers["Content-Type"] = content_type
self.response.out.write(callback+'({error:"The url parameter you provided is invalid."});')
else:
if url=="" and callback!="":
self.response.headers["Content-Type"] = content_type
self.response.out.write(callback+'({error:"must include a url parameter"});')
elif callback=="" and url=="":
self.response.headers["Content-Type"] = content_type
self.response.out.write("Error. Both url and callback parameters required")
else:
try:
result = urlfetch.fetch(url=url,method="HEAD",follow_redirects=False)
self.response.headers["Content-Type"] = content_type
try:
self.response.out.write(callback+'({location:"'+result.headers[u'location']+'"});')
except KeyError:
self.response.out.write(callback+'({result:"No redirect header set for this url."});')
except urlfetch.Error:
self.response.headers["Content-Type"] = content_type
self.response.out.write(callback+'({error:"The URL request was not successful."});')
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=False)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment