Revision 373362386234 () - Diff

Link to this snippet: https://friendpaste.com/ww5zr0XEK5qxO3mOEeGr3
Embed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#! /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()