Skip to content

Instantly share code, notes, and snippets.

@CavemanIV
Created August 23, 2015 15:03
Show Gist options
  • Save CavemanIV/ef8c6729b04609d205b0 to your computer and use it in GitHub Desktop.
Save CavemanIV/ef8c6729b04609d205b0 to your computer and use it in GitHub Desktop.
Proxy server for fetching daily bing wallpaper, can work with SpeedDial2 theme
from datetime import datetime
import BaseHTTPServer
import time
import random
import requests
HOST_NAME = '0.0.0.0'
PORT_NUMBER = 23796
REQUEST_IMAGE_NUM = 15
BING_PIC_URL = 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n={0}'.format(REQUEST_IMAGE_NUM)
# TODO: find a nicer image...
LAST_RESORT = 'http://www.planwallpaper.com/static/images/wallpapers-hd-8000-8331-hd-wallpapers.jpg'
class RedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
# cache image for daily purpose
_last_update_day = None
_image_urls = []
@classmethod
def should_fetch(cls):
if cls._last_update_day is None:
return True
if cls._last_update_day < datetime.today().day:
return True
return False
@classmethod
def fetch_bing_pic(cls):
try:
r = requests.get(BING_PIC_URL)
bing_json = r.json()
images = bing_json['images']
cls._image_urls = [image['url'] for image in images]
cls._last_update_day = datetime.today().day
print '[{0}] - refresh bing url {1}'.format(time.asctime(), cls._image_urls)
except Exception, e:
daily_image = LAST_RESORT
def do_HEAD(s):
print '[{0}] - request from {1}'.format(time.asctime(), s.client_address)
if s.should_fetch():
s.fetch_bing_pic()
which_image = random.randint(0, len(s._image_urls) - 1)
redirect_to = s._image_urls[which_image]
s.send_response(302)
s.send_header("Location", redirect_to)
s.end_headers()
def do_GET(s):
s.do_HEAD()
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), RedirectHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment