#! /usr/bin/env python # -*- coding: utf-8 - import binascii import sys import string from threading import Lock import simplejson as json from couchdb import Server, ResourceNotFound server = Server() lock = Lock() BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" BASE62_VALUES = ''.join([chr(i) for i in range(62)]) D_BASE62_PRIMITIVES = string.maketrans(BASE62_VALUES, BASE62_CHARS) def b62encode(value): """ encode int/long to base62 stsring. >>> b62encode(1123458) '4iGI' """ number = value result = '' while number != 0: result = D_BASE62_PRIMITIVES[number % 62] + result number /= 62 return result def requests(): line = sys.stdin.readline() while line: yield json.loads(line) line = sys.stdin.readline() def respond(code=200, data={}, headers={}): sys.stdout.write("%s\n" % json.dumps({"code": code, "json": data, "headers": headers})) sys.stdout.flush() def get_id(req): global lock, server dbname = req['info']['db_name'] db = server[dbname] stem = 0 with lock: try: doc = db['shortcode'] except ResourceNotFound: doc = {} db['shortcode'] = doc stem, revid = doc['_rev'].split('-') stem = int(stem) + 10000 return { "code": b62encode(stem), "code_num": stem} def main(): for req in requests(): respond(data=get_id(req)) if __name__ == "__main__": #print get_id({ "info": { "db_name": "testing" }}) main()