Esempio n. 1
0
def prepare_app(app, profiler, filters=None):
    if filters is None:
        filters = []

    if profiler == "sync":
        app = LineProfilerMiddleware(app,
                                     filters=filters,
                                     stream=StringNoopIO())
    elif profiler == "async":
        app = LineProfilerMiddleware(app,
                                     filters=filters,
                                     stream=StringNoopIO(),
                                     async_stream=True)
    return TestApp(app)
Esempio n. 2
0
def lineprof(app):
    from wsgi_lineprof.middleware import LineProfilerMiddleware
    from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter, TopItemsFilter

    filters = [
        # Results which filename contains "mikeswebdav"
        FilenameFilter("mikeswebdav"),
        # Sort by total time of results
        TotalTimeSorter(),
        # Get first n stats
        TopItemsFilter(),
    ]
    app.wsgi_app = LineProfilerMiddleware(app.wsgi_app, filters=filters)
Esempio n. 3
0
def run(filepath, wsgiapp, host, port, reload, interval, static, static_root,
        static_dirs, lineprof, lineprof_file, validate):
    """
    Runs a development server for WSGI Application.

    Usage:

        $ wsgicli run hello.py app -h 0.0.0.0 -p 5000

        $ wsgicli run hello.py app --reload

        $ wsgicli run hello.py app --static --static-root /static/ --static-dirs ./static/

        $ wsgicli run hello.py app --lineprof
    """
    module = SourceFileLoader('module', filepath).load_module()
    app = getattr(module, wsgiapp)

    if static:
        from wsgi_static_middleware import StaticMiddleware
        app = StaticMiddleware(app,
                               static_root=static_root,
                               static_dirs=static_dirs)

    if validate:
        from wsgiref.validate import validator
        app = validator(app)

    if lineprof:
        # Caution: wsgi-lineprof is still pre-alpha. Except breaking API Changes.
        from wsgi_lineprof.middleware import LineProfilerMiddleware
        from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter

        if lineprof_file:
            # Now wsgi-lineprof is now supported only 1 file checking.
            lineprof_file = lineprof_file[0]
        else:
            lineprof_file = filepath.split(
                '/')[-1] if '/' in filepath else filepath
        filters = [FilenameFilter(lineprof_file), TotalTimeSorter()]
        app = LineProfilerMiddleware(app, filters=filters)

    if reload:
        run_live_reloading_server(interval, app=app, host=host, port=port)
    else:
        run_server(app=app, host=host, port=port)
Esempio n. 4
0
        ''', (session['user_id'],))
        events = cursor.fetchall()
        if events and bool(events[0]['unread']):
            cursor.execute('''
            UPDATE event_haveread
            SET since = NOW() WHERE user_id = %s
            ''', (session['user_id'],))
    return render_template('events.html', events=events)


def initialize():
    with connect_db() as conn:
        cursor = conn.cursor()
        cursor.execute('''
        TRUNCATE
        relations, comments, favorites, posts, users, events, event_haveread
        RESTART IDENTITY CASCADE
        ''')

    for path in glob.glob(os.path.join(app.config['UPLOAD_FOLDER'], '*')):
        os.remove(path)


if __name__ == '__main__':
    from wsgi_lineprof.middleware import LineProfilerMiddleware
    from wsgi_lineprof.filters import FilenameFilter
    from wsgiref.simple_server import make_server
    profile_app = LineProfilerMiddleware(app, filters=[FilenameFilter("main.py")])
    with make_server('0.0.0.0', 5000, profile_app) as server:
        server.serve_forever()
Esempio n. 5
0
            header_list = read_header_list_from_db()
            BLOCKCHAIN.build_from_header_list(header_list)

        # Sync with all my peers
        sync_with_peers()

        # Start mining Thread
        Thread(target=start_mining_thread, daemon=True).start()
        if consts.NO_MINING:
            logger.info("FullNode: Not Mining")

        # Start server
        if LINE_PROFILING:
            from wsgi_lineprof.middleware import LineProfilerMiddleware

            with open("lineprof" + str(consts.MINER_SERVER_PORT) + ".log",
                      "w") as f:
                app = LineProfilerMiddleware(app, stream=f, async_stream=True)
                waitress.serve(app,
                               host="0.0.0.0",
                               threads=16,
                               port=consts.MINER_SERVER_PORT)
        else:
            waitress.serve(app,
                           host="0.0.0.0",
                           threads=16,
                           port=consts.MINER_SERVER_PORT)

    except KeyboardInterrupt:
        miner.stop_mining()
Esempio n. 6
0
import bottle

from wsgi_lineprof.middleware import LineProfilerMiddleware

app = bottle.app()


@app.route('/hello/<name>')
def index(name):
    return bottle.template('<b>Hello {{name}}</b>!', name=name)


app = LineProfilerMiddleware(app)

if __name__ == "__main__":
    bottle.run(host='localhost', port=8080, app=app)
Esempio n. 7
0
        p.incr('keyword_modified')
        # Get star
        cur.execute("""
            SELECT keyword, user_name
            FROM star
        """)
        stars = cur.fetchall()
        for star in stars:
            p.rpush('list:stars:%s' % star['keyword'], star['user_name'])
        # Execute
        p.execute()
    return

# Initialize
with _dbh() as cur:
    r = _rh()
    if r.exists('initialized') == 0:
        initialize_redis(cur, r)
    r.close()

if __name__ == "__main__":
    from wsgi_lineprof.middleware import LineProfilerMiddleware
    from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter
    filters = [
        FilenameFilter(__file__),
        TotalTimeSorter(),
    ]
    with open('lineprof.log', 'w') as f:
        app.wsgi_app = LineProfilerMiddleware(app.wsgi_app, async_stream=True, stream=f, filters=filters)
        app.run()
Esempio n. 8
0
from wsgiref.simple_server import demo_app, make_server

from wsgi_lineprof.middleware import LineProfilerMiddleware

app = LineProfilerMiddleware(demo_app)

if __name__ == "__main__":
    httpd = make_server('', 8000, app)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()
Esempio n. 9
0
import bottle

from wsgi_lineprof.middleware import LineProfilerMiddleware


@bottle.route('/hello/<name>')
def index(name):
    return bottle.template('<b>Hello {{name}}</b>!', name=name)


app = LineProfilerMiddleware(bottle.app())

if __name__ == "__main__":
    bottle.run(host='localhost', port=8080, app=app)
Esempio n. 10
0
from app import app
from wsgi_lineprof.middleware import LineProfilerMiddleware
from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter

if __name__ == '__main__':
    #app.app.run(port=5000, debug=True, threaded=True)

    filters = [
        FilenameFilter("/home/isucon/isubata/webapp/python/app.py"),
        TotalTimeSorter(),
    ]
    with open("/home/isucon/isubata/webapp/python/lineprof.log", "w") as f:
        app.wsgi_app = LineProfilerMiddleware(app.wsgi_app,
                                              stream=f,
                                              filters=filters)
        app.run(port=5000, debug=True, threaded=True)
Esempio n. 11
0
        return n
    return fib(n - 1) + fib(n - 2)


# Simple WSGI application
def app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    n = 30
    fib_n = fib(n)
    res = "fib(%d) = %d" % (n, fib_n)
    return [res.encode("utf-8")]


if __name__ == "__main__":
    # Set up profiler
    filters = [
        FilenameFilter("fib.py"),
        TotalTimeSorter(),
    ]
    app = LineProfilerMiddleware(app, filters=filters)

    server = make_server('127.0.0.1', 8000, app)
    print("Serving on 127.0.0.1:8000...")
    server.serve_forever()
Esempio n. 12
0
        flash('You must be logged in')
        return redirect(url_for('index'))


@app.route('/report')
def report():
    response = jsonify({
        'banned_ips': banned_ips(),
        'locked_users': locked_users()
    })
    response.status_code = 200
    return response


from wsgi_lineprof.middleware import LineProfilerMiddleware
from wsgi_lineprof.filters import FilenameFilter
profile_app = LineProfilerMiddleware(
    app,
    filters=[FilenameFilter('app.py')],
    stream=open('lineprof.log', 'w'),
)

if __name__ == '__main__':
    import bjoern
    load_config()
    port = int(os.environ.get('PORT', '8080'))
    #app.run(debug=1, host='0.0.0.0', port=port)
    bjoern.run(app, '0.0.0.0', port)
else:
    load_config()
Esempio n. 13
0
def get_user_cache(mynumber, name, address):
    key_name = md5('{}{}{}'.format(mynumber, name,
                                   address).encode('utf-8')).hexdigest()
    cache = r2.get(key_name)
    if cache:
        user_id, votes = cache.decode('utf-8').split(':')
        return int(user_id), int(votes)
    return None


@lru_cache(maxsize=100)
def unquote_cached(keyword):
    return unquote_plus(keyword)


from wsgi_lineprof.filters import FilenameFilter
from wsgi_lineprof.middleware import LineProfilerMiddleware
f = open("/run/mylog/profile.log", "a")  # 複数ワーカが書き込むので多分wじゃだめな気がする。
filters = [
    FilenameFilter('myapp.py'),  # プロファイル対象のファイル名指定
]
# stremで出力ファイルを指定、filtersでフィルタを追加
app_profile = LineProfilerMiddleware(app,
                                     stream=f,
                                     filters=filters,
                                     async_stream=True)

if __name__ == "__main__":
    app.run()
Esempio n. 14
0
        return 'image/png'
    if ext == '.gif':
        return 'image/gif'
    return ''


@app.route('/icons/<file_name>')
def get_icon(file_name):
    cur = dbh().cursor()
    cur.execute("SELECT * FROM image WHERE name = %s", (file_name, ))
    row = cur.fetchone()
    ext = os.path.splitext(file_name)[1] if '.' in file_name else ''
    mime = ext2mime(ext)
    if row and mime:
        return flask.Response(row['data'], mimetype=mime)
    flask.abort(404)


from wsgi_lineprof.middleware import LineProfilerMiddleware
from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter
from wsgiref.simple_server import make_server
profile_app = LineProfilerMiddleware(
    app,
    filters=[FilenameFilter("main.py"),
             TotalTimeSorter()],
    stream=open('lineprof.log', 'w'))

if __name__ == "__main__":
    server = make_server('0.0.0.0', 5000, profile_app)
    server.serve_forever()
Esempio n. 15
0

def stats_reset():
    profiler = app.wsgi_app.profiler
    profiler.disable()
    profiler.reset()
    profiler.enable()


@app.route('/stats/reset')
def get_stats_reset():
    stats_reset()
    return 'OK'


if __name__ == "__main__":
    filters = [
        FilenameFilter("webapp/python/app.py"),
        lambda stats: filter(lambda stat: stat.total_time > 0.001, stats),
        TotalTimeSorter()
    ]

    app.config['PROFILE'] = True

    with open("lineprof.log", "w") as f:
        app.wsgi_app = LineProfilerMiddleware(app.wsgi_app,
                                              stream=f,
                                              filters=filters,
                                              accumulate=True)
        app.run(port=8080, debug=True, threaded=True)