paste2 / paste2.py

import sqlite3
import random
from flask import Flask
from flask import g
from flask import abort, request, make_response
app = Flask(__name__)

DATABASE = '/path/to/sqlite3.db'

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.after_request
def after_request(response):
    g.db.close()
    return response

def query_db(query, args=(), one=False):
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

def init_db():
    from contextlib import closing
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql') as f:
            db.cursor().executescript(f.read())
        db.commit()


def new_key():
    key = ''
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    i = 0
    r = 0
    while i < 4:
        n = random.randint(0,35)
        key += chars[n]
        i+=1
    return key

@app.route('/', methods=['GET'])
def help():
    return "nothing to see here\n"

@app.route('/favicon.ico')
def favicon():
    abort(404)

@app.route('/', methods=['POST'])
def post():
    content = request.form.get('content', '')
    if not content:
        return "i need moar\n"

    key = new_key()
    retries = 10
    while query_db('SELECT key FROM entries WHERE key = ?', [key], one=True):
        key = new_key()
        retries -= 1
        if retries == 0:
            abort(500)

    g.db.execute("""
        INSERT INTO entries (key, content, created)  
        VALUES(?, ?, datetime('now'))
        """, [key, content])
    g.db.commit()

    return "%s%s\n" % (request.url_root, key)

@app.route('/<key>')
def get(key):
    a = request.args
    content = query_db('SELECT content FROM entries WHERE key = ?', 
                       [key], 
                       one=True)
    if not content:
        abort(404) 

    content = content['content']

    if not a.keys():
        response = make_response("%s\n" % content)
        response.mimetype='text/plain'
        return response

    from pygments import highlight
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters import HtmlFormatter

    lang = a.keys()[0]
    try:
        lexer = get_lexer_by_name(lang)
    except:
        lexer = get_lexer_by_name('text')

    return highlight(content,
                     lexer,
                     HtmlFormatter(full=True,
                                   style='borland',
                                   lineanchors='l',
                                   linenos='inline',
                                   encoding='utf-8'))

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')
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.