Source

Redbeard / redbeard.py

Chris Jones 96c19cd 



Kenneth Love 1c87dfd 
Chris Jones 96c19cd 

Kenneth Love 7000f29 
Chris Jones 28553a7 
Kenneth Love c283702 
Kenneth Love 753d30f 
Chris Jones 28553a7 
Chris Jones 2dfbed1 
Chris Jones 28553a7 
Kenneth Love 66f021d 
Chris Jones 761e3e3 
Chris Jones 28553a7 
Chris Jones 0071a25 

Kenneth Love c283702 

Kenneth Love 66f021d 
Kenneth Love c283702 
Kenneth Love 66f021d 

Chris Jones 28553a7 
Kenneth Love cb3afa9 
Chris Jones 28553a7 
Kenneth Love f34f74c 
Chris Jones 28553a7 
Kenneth Love cb3afa9 



Chris Jones 37e2001 
Kenneth Love 9342c89 
Kenneth Love 594cd12 

Chris Jones 37e2001 
Kenneth Love cb3afa9 
Kenneth Love 83edc94 





Kenneth Love cb3afa9 
Chris Jones 2dfbed1 


Kenneth Love cb3afa9 

Chris Jones 2dfbed1 
Kenneth Love f34f74c 
Kenneth Love 03860b4 


Chris Jones 761e3e3 


Kenneth Love 03860b4 

Kenneth Love f34f74c 
Chris Jones 4eed33b 
Chris Jones 7ab31f7 




Chris Jones c1b25ba 

Chris Jones 761e3e3 

Chris Jones 4eed33b 
Chris Jones 7ab31f7 

Chris Jones 761e3e3 
Chris Jones 7ab31f7 



Chris Jones 4eed33b 







Chris Jones c1b25ba 



Chris Jones 4eed33b 





Chris Jones c65196e 
Chris Jones 4eed33b 






Chris Jones c65196e 
Chris Jones 4eed33b 

Kenneth Love 7cf7b5a 
Chris Jones 4eed33b 
Chris Jones 7ab31f7 







Chris Jones 761e3e3 
Chris Jones 7ab31f7 







Chris Jones 761e3e3 
Chris Jones 7ab31f7 





Kenneth Love f34f74c 











Kenneth Love 66f021d 

Kenneth Love fe5e113 
Chris Jones 4eed33b 



Chris Jones 7ab31f7 


Kenneth Love 32bf44a 


Kenneth Love 66f021d 
Kenneth Love 620dc14 






Chris Jones 7ab31f7 


Kenneth Love 620dc14 


Kenneth Love 66f021d 

Kenneth Love fe5e113 
Chris Jones 4eed33b 

Chris Jones 7ab31f7 


Kenneth Love 15fd894 











Chris Jones a7f7f9f 

Kenneth Love 66f021d 
Kenneth Love 15fd894 
Kenneth Love 66f021d 
Kenneth Love 32bf44a 






























Kenneth Love f34f74c 























Kenneth Love f8fa6bf 

Kenneth Love fe5e113 
Chris Jones 4eed33b 

Chris Jones 7ab31f7 


Kenneth Love f8fa6bf 
Kenneth Love c283702 
Kenneth Love f8fa6bf 

Kenneth Love fe5e113 

Kenneth Love 4d6165e 

Kenneth Love fe5e113 


Kenneth Love ef976ea 
Kenneth Love 4d6165e 

Kenneth Love ed7ebe0 
Kenneth Love 7000f29 

Kenneth Love ed7ebe0 
Kenneth Love ef976ea 


Kenneth Love 4d6165e 
Kenneth Love ef976ea 
Kenneth Love 7000f29 









Kenneth Love 4d6165e 
Kenneth Love 7000f29 


Kenneth Love ef976ea 
Kenneth Love c283702 

Kenneth Love fe5e113 
Kenneth Love 2829ea4 





Kenneth Love 753d30f 

Kenneth Love 2829ea4 


Kenneth Love 753d30f 
Chris Jones 2e9c693 
Kenneth Love 5fa8d4c 
Kenneth Love a20631f 
Kenneth Love 5fa8d4c 
Kenneth Love a20631f 
Kenneth Love 5fa8d4c 


Kenneth Love 594cd12 
Kenneth Love 5fa8d4c 










Kenneth Love 0622e13 


Kenneth Love 5fa8d4c 





Chris Jones 37e2001 





Kenneth Love 9342c89 
Chris Jones 37e2001 

Kenneth Love 594cd12 
Chris Jones 37e2001 




Kenneth Love 594cd12 

Chris Jones 37e2001 
Kenneth Love 0622e13 


Kenneth Love 594cd12 
Chris Jones 37e2001 



Kenneth Love 594cd12 




Kenneth Love 9342c89 
Kenneth Love 594cd12 


















Kenneth Love 83edc94 

























Chris Jones 2dfbed1 







Kenneth Love cb3afa9 
Chris Jones 2dfbed1 




Kenneth Love cb3afa9 


Chris Jones 2dfbed1 
Kenneth Love cb3afa9 

Chris Jones 2dfbed1 





Chris Jones 82ac34c 




Chris Jones 7ab31f7 


Chris Jones 82ac34c 





Kenneth Love 500a1eb 








Kenneth Love f2556b6 
Kenneth Love 500a1eb 


Kenneth Love 32bf44a 

Kenneth Love 500a1eb 
Kenneth Love 66f021d 
  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
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
"""
TODO
"""
__author__ = 'Chris Jones, Kenneth Love'
__version__ = '0.8.5'
__license__ = 'MIT'

import re

from flask import Flask, render_template, redirect, url_for, request, flash
from flask import session, jsonify

from flaskext.wtf import Form, TextField, Required, IntegerField, FloatField

import redis
from redis.exceptions import ConnectionError, ResponseError

import settings

SECRET_KEY = '781b0650af13493089a6ffafac755a61'

app = Flask(__name__)
app.config.from_object(__name__)
app.debug = True

# Forms
class KeyForm(Form):
    key_name = TextField('Key', validators=[Required()])
    key_ttl = IntegerField('TTL')

class StringForm(KeyForm):
    key_value = TextField('Value', validators=[Required()])

class ListSetForm(KeyForm):
    """
    Form for creating a new set or list
    """
    member = TextField('Member', validators=[Required()])

class HashForm(KeyForm):
    """
    Form for creating a hash.
    """
    member_name = TextField('Member', validators=[Required()])
    member_value = TextField('Value', validators=[Required()])

class ZSetForm(KeyForm):
    """
    Form for creating a ZSet
    """
    member_name = TextField('Member', validators=[Required()])
    member_score = FloatField('Score', validators=[Required()])

# Context processors
@app.context_processor
def get_db_size():
    r = get_redis_connection(session)
    if not r:
        return {'db_size':0}

    return dict(db_size=r.dbsize())

# Control app flow
def get_redis_connection(session):
    """
    Get Redis connection with session values. Ping Redis
    to make sure connection is working.
    """
    r = redis.Redis(
        host=session.get('redis_host', settings.REDIS_HOST),
        port=session.get('redis_port', settings.REDIS_PORT),
        db=session.get('redis_db', settings.REDIS_DB),
        password=session.get('redis_password', ''))

    try:
        r.ping()
    except (ConnectionError, ResponseError):
        return None

    return r

def set_session_defaults(session):
    """ Setup default session """
    session['redis_db'] = settings.REDIS_DB
    session['redis_host'] = settings.REDIS_HOST
    session['redis_port'] = settings.REDIS_PORT

@app.route('/logout/')
def logout():
    if session:
        for key in session.keys():
            session.pop(key)

    return redirect(url_for('index'))

@app.route('/change_db', methods=['GET', 'POST'])
def change_db():
    """
    View to handle changing the redis db. Make sure val is an int
    and within the redis db range.
    """
    if request.method == 'POST':
        try:
            db = int(request.form['redis_db'])
        except ValueError:
            return redirect(url_for('index'))

        if db in xrange(0,10):
            session['redis_db'] = db
            flash('Redis DB changed to ' + str(db))
    return redirect(request.referrer)

@app.route('/setup/', methods=['GET', 'POST'])
def setup():
    """
    If a connection error with Redis occurs, users will be redirected
    here to setup the connection information.
    """
    if request.method == 'POST':
        host = request.form['host'] or settings.REDIS_HOST
        password = request.form['password']
        try:
            port = int(request.form['port'])
        except ValueError:
            port = settings.REDIS_PORT
            flash('Port number must be an integer. Default used.')

        session['redis_host'] = host
        session['redis_port'] = port
        session['redis_password'] = password

        return redirect(url_for('index'))


    return render_template('setup.html')

# Static views
@app.route('/info/')
def info():
    """ View for info about your redis set up. """
    r = get_redis_connection(session)
    if not r:
        return redirect(url_for('setup'))

    info = r.info().items()

    return render_template('info.html', info=info)

@app.route('/')
def index():
    """ All available keys. """
    if not session.has_key('redis_db'):
        set_session_defaults(session)
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))

    #keys = r.keys()
    #return render_template('index.html', keys=keys)
    return render_template('layout.html')

@app.route('/keys')
def keys():
    """ Get available keys. """
    if not session.has_key('redis_db'):
        set_session_defaults(session)
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))

    keys = r.keys()
    return jsonify(keys=keys)

@app.route('/key/<key>')
def key(key):
    """ Info for the key. """
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))

    if r.exists(key):
        rtype = r.type(key)
        if rtype == 'hash':
            output = r.hgetall(key)
        elif rtype == 'set':
            output = r.smembers(key)
        elif rtype == 'zset':
            output = r.zrange(key, 0, -1, withscores=True)
        elif rtype == 'list':
            output = [r.lindex(key, n) for n in xrange(r.llen(key))]
        else:
            output = r.get(key)
        return render_template('key.html', rtype=rtype, key=key, output=output,
            ttl=r.ttl(key))
    else:
        return render_template('no_key.html', key=key)

@app.route('/key/<key>/json')
def key_json(key):
    """ JSON info for the key """
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))

    if r.exists(key):
        rtype = r.type(key)
        if rtype == 'hash':
            output = r.hgetall(key)
        elif rtype == 'set':
            output = r.smembers(key)
        elif rtype == 'zset':
            output = r.zrange(key, 0, -1, withscores=True)
        elif rtype == 'list':
            output = [r.lindex(key, n) for n in xrange(r.llen(key))]
        else:
            output = r.get(key)
        return jsonify(
            rtype=rtype,
            key=key,
            output=output,
            ttl=r.ttl(key)
        )
    else:
        return jsonify({})



# Read/write views
@app.route('/new', methods=['GET', 'POST'])
def new_key():
    form = StringForm(request.form or None)
    if form.validate_on_submit():
        key = request.form['key_name']
        value = request.form['key_value']

        r = get_redis_connection(session)
        if not r:
            return redirect(url_for('setup'))

        if r.exists(key):
            return jsonify(flash=key + ' already exists.')

        try:
            r.set(key, value)
            flash('%s was saved successfully.' % key)
            return redirect('#%s' % key)
        except:
            return jsonify(flash=key + ' was not saved successfully.')

    return render_template('new_key.html', form=form)

@app.route('/key/save/<key>', methods=['POST'])
def save(key):
    """ Update the value of a key. """
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))

    rtype = r.type(key)
    value = request.form['value']

    if rtype == 'hash':
        value = request.form['value'].strip("{}")
        values = [k.split(':', 1) for k in value.split(',')]

        r.delete(key)
        for k, v in values:
            r.hset(key, k.strip("' "), v.strip("' "))

    elif rtype == 'set':
        value = request.form['value'].strip("set([])")

        r.delete(key)
        for k in value.split(','):
            r.sadd(key, k.strip(" '\""))

    elif rtype == 'list':
        value = request.form['value'].strip("[]")

        r.delete(key)
        for k in value.split(','):
            r.rpush(key, k.strip().strip("'"))

    elif rtype == 'zset':
        value = request.form['value'].strip('[]')
        regex = re.compile('(?P<key>\(.*\))(?P<comma>,\s)(?P<value>\(.*\))')
        matches = re.search(regex, value)
        values = [match for match in matches.groups() if match != ', ']

        values_list = [k.split() for k in values]

        r.delete(key)
        for k, v in values_list:
            k, v = k.strip("(' ,)"), v.strip("(' ,)")
            r.zadd(key, k, v)

    elif rtype == 'string':
        r.set(key, value)

    key_changed = 'false'
    if request.form['key_name'] != request.form['saved_key_name']:
        r.rename(key, request.form['key_name'])
        key = request.form['key_name']
        key_changed = 'true'

    return jsonify(
        flash=key + ' was saved successfully',
        value=value,
        key=key,
        key_changed=key_changed
    )

@app.route('/key/new/string', methods=['GET', 'POST'])
def new_string():
    form = StringForm(request.form or None)

    if form.validate_on_submit():
        key = request.form['key_name']
        value = request.form['key_value']
        ttl = int(request.form['key_ttl'])

        r = get_redis_connection(session)
        if not r:
            return redirect(url_for('setup'))

        if r.exists(key):
            flash('%s already exists, edit it below' % key)
            return redirect('#%s' % key)

        try:
            r.set(key, value)
            if ttl and ttl != 0:
                r.expire(key, ttl)

            flash('%s was saved successfully.' % key)
            return redirect('#%s' % key)
        except:
            return jsonify(flash=key + ' failed to save.')
    else:
        return render_template('new_string.html', form=form)

@app.route('/key/new/set', methods=['GET', 'POST'])
def new_set():
    """
    View for creating a new set/member
    """
    form = ListSetForm(request.form or None)
    if form.validate_on_submit():
        key = request.form['key_name']
        ttl = int(request.form['key_ttl'])

        r = get_redis_connection(session)
        if not r:
            return redirect(url_for('setup'))

        for m in [k for k in request.form.keys() if k.startswith('member')]:
           r.sadd(key, request.form[m])

        if ttl and ttl != 0:
            r.expire(key, ttl)

        flash('%s was created.' % key)
        return redirect('#%s' % key)

    return render_template('new_set.html', form=form)

@app.route('/key/new/list', methods=['GET', 'POST'])
def new_list():
    """
    View for creating a new list with members.
    """
    form = ListSetForm(request.form or None)
    if form.validate_on_submit():
        key = request.form['key_name']
        ttl = int(request.form['key_ttl'])

        r = get_redis_connection(session)
        if not r:
            return redirect(url_for('setup'))

        for m in [k for k in request.form.keys() if k.startswith('member')]:
           r.rpush(key, request.form[m])

        if ttl and ttl != 0:
            r.expire(key, ttl)

        flash('%s was created.' % key)
        return redirect('#%s' % key)

    return render_template('new_list.html', form=form)

@app.route('/key/new/hash', methods=['GET', 'POST'])
def new_hash():
    """
    View for creating a new list with members.
    """
    form = HashForm(request.form or None)
    if form.validate_on_submit():
        key = request.form['key_name']
        ttl = int(request.form['key_ttl'])

        r = get_redis_connection(session)
        if not r:
            return redirect(url_for('setup'))

        for m in [k for k in request.form.keys() if k.startswith('member_name')]:
            v = re.sub('name', 'value', m)
            r.hset(key, request.form[m], request.form[v])

        if ttl and ttl != 0:
            r.expire(key, ttl)

        flash('%s was created.' % key)
        return redirect('#%s' % key)

    return render_template('new_hash.html', form=form)

@app.route('/key/new/zset', methods=['GET', 'POST'])
def new_zset():
    """
    View for creating a new zset
    """
    form = ZSetForm(request.form or None)
    if form.validate_on_submit():
        key = request.form['key_name']
        ttl = int(request.form['key_ttl'])

        r = get_redis_connection(session)
        if not r:
            return redirect(url_for('setup'))

        for m in [k for k in request.form.keys() if k.startswith('member_name')]:
            v = re.sub('name', 'score', m)
            r.zadd(key, request.form[m], float(request.form[v]))

        if ttl and ttl != 0:
            r.expire(key, ttl)

        flash('%s was created.' % key)
        return redirect('#%s' % key)

    return render_template('new_zset.html', form=form)

@app.route('/key/delete/<key>', methods=['GET'])
def delete(key):
    """ Delete key """
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))

    if r.exists(key):
        r.delete(key)
        return jsonify(flash="Key '" + key + "' was deleted successfully")
    else:
        return jsonify(flash="Key '" + key + "' was not found in Redis")

@app.route('/search/<string>', methods=['GET'])
@app.route('/search/', methods=['GET'])
def search(string=None):
    """ Find keys matching a string. """
    r = get_redis_connection(session)

    if not r:
        return redirect(url_for('setup'))
    if string:
        search_string = '*' + string + '*'
    else:
        search_string = '*'

    return jsonify(
        keys=[{'key': v} for k,v in enumerate(r.keys(pattern=search_string))])

if __name__ == '__main__':
    app.run()