Created
July 5, 2011 21:04
-
-
Save kenegozi/1065936 to your computer and use it in GitHub Desktop.
Super dumbed-down ad server - serving a random image every-time.
This file contains 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
using Manos; | |
using System; | |
using System.IO; | |
public class RandomAd : ManosApp { | |
public RandomAd () { | |
var ads = Directory.GetFiles(".", "*.gif"); | |
var random = new Random(); | |
Route ("/", ctx=> { | |
var idx = random.Next(ads.Length); | |
ctx.Response.Headers.SetNormalizedHeader ("Content-Type", "image/gif"); | |
ctx.Response.SendFile(ads[idx]); | |
ctx.Response.End(); | |
}); | |
} | |
} |
This file contains 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
import tornado.ioloop | |
import tornado.web | |
import glob | |
import random | |
class AdsHandler(tornado.web.RequestHandler): | |
# future: a proper storage instead of local folder | |
# future: set cache policy | |
# we actually do not want to cache that as we want to keep it random | |
# but the images themselves should be cached. | |
# perhaps replace it with a redirect (with no-cache) to a url of the image (on CDN with far-away cache) | |
ads = glob.glob("./*.gif") | |
def get(self): | |
self.set_header("Content-Type", "image/gif") | |
ad = random.choice(self.ads) | |
# future: add location aware/user aware logic | |
self.write_binary(ad) | |
def write_binary(self, filename): | |
# there probably is a better way of doing that with async io | |
with open(filename, "rb") as f: | |
while True: | |
# and there probably is a better way to chunk the reads. | |
# half a kb feels right, however for real-scenario I'd be | |
# reasearching + trial/err to optimise *if needed* | |
bytes = f.read(500) | |
print len(bytes) | |
if not bytes: break | |
self.write(bytes) | |
application = tornado.web.Application([ | |
(r"/", AdsHandler), | |
]) | |
if __name__ == "__main__": | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment