Redbeard / redbeard.py

  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
"""
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'))

    return render_template('index.html')

@app.route('/keys')
@app.route('/keys/<int:amount>')
def keys(amount=500):
    """ 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'))

    total_keys = len(r.keys())
    initial_keys = r.keys()[:amount]
    return jsonify(total_keys=total_keys, initial_keys=initial_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)

# 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=r.keys(pattern=search_string))

if __name__ == '__main__':
    app.run()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.