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)
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)
''', (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()
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()
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)
conn = dbh() with conn.cursor(dictionary=True) as c: c.execute("TRUNCATE seat_reservations") c.execute("TRUNCATE reservations") c.execute("TRUNCATE users") load_station() return flask.jsonify({ "language": "python", # 実装言語を返す "available_days": AvailableDays, }) # Load first if __name__ == "__main__": import pathlib from wsgi_lineprof.filters import FilenameFilter app.logger.setLevel(logging.DEBUG) log_path = pathlib.Path('/tmp/profile.log') log_path.parent.mkdir(parents=True, exist_ok=True) with open(log_path, "w") as f: filters = [ FilenameFilter("app.py"), lambda stats: filter(lambda stat: stat.total_time > 0.001, stats), ] app.wsgi_app = LineProfilerMiddleware(app.wsgi_app, stream=f, filters=filters) app.run(port=8001, debug=True, threaded=True)
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()
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()
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()
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()
def setup(self, profiler): filters = [ FilenameFilter("apps.py"), ] self.app = prepare_app(jinja_app, profiler, filters=filters)
for i in range(n): time.sleep(0.1) result.append(f"Item: {i}") return result @app.route("/") def index(): size = int(request.query.get("size", "10")) items = mock_db_access(size) items_str = "\n".join(items) time.sleep(0.3) return "Hello, world!\n" + items_str # Profile w/o filtering # from wsgi_lineprof.middleware import LineProfilerMiddleware # app = LineProfilerMiddleware(app) # Profile w/ filtering from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter from wsgi_lineprof.middleware import LineProfilerMiddleware filters = [ FilenameFilter("main.py"), TotalTimeSorter(), ] app = LineProfilerMiddleware(app, filters=filters) bottle.run(app=app, reloader=True)
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)