def create_app(config=config, app_name=None): """Create a Flask app.""" if app_name is None: app_name = APP_NAME app = Flask(app_name) app.root_path=app.root_path+"/adsgut" _configure_app(app, config) _configure_logging(app) if not config.TESTING: _configure_wsgi_middleware(app) # configure_hook(app) _configure_blueprints(app) _configure_extensions(app) #_configure_template_filters(app) #_configure_error_handlers(app) _configure_misc_handlers(app) _configure_global_variables(app) if config.DEBUG: from flask_debugtoolbar import DebugToolbarExtension toolbar = DebugToolbarExtension(app) @app.route('/foobar') def foobar(): return render_template('index/main_page.html') return app
def make_app(projectPath): app = Flask(__name__) app.root_path = str(projectPath) app.config.update( DEBUG=True, FLATPAGES_AUTO_RELOAD=True, FLATPAGES_EXTENSION='.md', FREEZER_RELATIVE_URLS=True) app.add_url_rule('/', 'index', route_index) app.add_url_rule('/<path:path>/', 'page', route_page) app.add_url_rule('/tag/<string:tag>/', 'tag', route_tag) return app
def app(tmpdir): from flask import Flask root_path = tmpdir.ensure("test-proj", dir=True) tmpdir.ensure("test-proj/static/coffee", dir=True) p = tmpdir.join("test-proj/static/coffee", "Cakefile") p.write("") app = Flask(__name__) app.root_path = root_path.strpath return app
def test_init_without_cache_folder(self): app = Flask(__name__) app.root_path = os.path.abspath(os.path.normpath(os.path.dirname(__file__) + '/../')) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGINE_ADAPTER'] = { 'name': 'fs', 'source_folder': 'images' } imagine = Imagine(app) self.assertTrue(isinstance(imagine, Imagine))
def create_app(app_state): app = Flask(__name__) app.debug = True if getattr(sys, 'frozen', None): # set root_path to data dir from PyInstaller basedir = sys._MEIPASS app.root_path = os.path.join(basedir, os.path.join(*__name__.split('.'))) app.config.geobox_state = app_state app.config['SECRET_KEY'] = app_state.config.get('web', 'secret_key') from . import views app.register_blueprint(views.main) app.register_blueprint(views.map) app.register_blueprint(views.tasks) app.register_blueprint(views.project) app.register_blueprint(views.user) app.register_blueprint(views.admin) app.register_blueprint(views.vector) app.register_blueprint(views.downloads) @app.before_request def before_request(): from helper import request_for_static g.db = app_state.user_db_session() if request_for_static(): return username = session.get('username', False) if not username and request.endpoint != 'user_view.login': abort(403) @app.teardown_request def teardown_request(exception): """Closes the database again at the end of the request.""" if hasattr(g, 'db'): g.db.close() from .helper import css_alert_category, add_auth_to_url app.jinja_env.globals.update(css_alert_category=css_alert_category, add_auth_to_url=add_auth_to_url) configure_i18n(app, app_state.locale()) configure_errorhandlers(app) return app
def __init__( self, environment: "Environment", host: str, port: int, auth_credentials: Optional[str] = None, tls_cert: Optional[str] = None, tls_key: Optional[str] = None, stats_csv_writer: Optional[StatsCSV] = None, delayed_start=False, ): """ Create WebUI instance and start running the web server in a separate greenlet (self.greenlet) Arguments: environment: Reference to the current Locust Environment host: Host/interface that the web server should accept connections to port: Port that the web server should listen to auth_credentials: If provided, it will enable basic auth with all the routes protected by default. Should be supplied in the format: "user:pass". tls_cert: A path to a TLS certificate tls_key: A path to a TLS private key delayed_start: Whether or not to delay starting web UI until `start()` is called. Delaying web UI start allows for adding Flask routes or Blueprints before accepting requests, avoiding errors. """ environment.web_ui = self self.stats_csv_writer = stats_csv_writer or StatsCSV( environment, stats_module.PERCENTILES_TO_REPORT) self.environment = environment self.host = host self.port = port self.tls_cert = tls_cert self.tls_key = tls_key app = Flask(__name__) CORS(app) self.app = app app.jinja_env.add_extension("jinja2.ext.do") app.debug = True app.root_path = os.path.dirname(os.path.abspath(__file__)) self.app.config["BASIC_AUTH_ENABLED"] = False self.auth: Optional[BasicAuth] = None self.greenlet: Optional[gevent.Greenlet] = None self._swarm_greenlet: Optional[gevent.Greenlet] = None self.template_args = {} if auth_credentials is not None: credentials = auth_credentials.split(":") if len(credentials) == 2: self.app.config["BASIC_AUTH_USERNAME"] = credentials[0] self.app.config["BASIC_AUTH_PASSWORD"] = credentials[1] self.app.config["BASIC_AUTH_ENABLED"] = True self.auth = BasicAuth() self.auth.init_app(self.app) else: raise AuthCredentialsError( "Invalid auth_credentials. It should be a string in the following format: 'user:pass'" ) if environment.runner: self.update_template_args() if not delayed_start: self.start() @app.route("/") @self.auth_required_if_enabled def index() -> Union[str, Response]: if not environment.runner: return make_response( "Error: Locust Environment does not have any runner", 500) self.update_template_args() return render_template("index.html", **self.template_args) @app.route("/swarm", methods=["POST"]) @self.auth_required_if_enabled def swarm() -> Response: assert request.method == "POST" parsed_options_dict = vars(environment.parsed_options ) if environment.parsed_options else {} for key, value in request.form.items(): if key == "user_count": # if we just renamed this field to "users" we wouldn't need this user_count = int(value) elif key == "spawn_rate": spawn_rate = float(value) elif key == "host": # Replace < > to guard against XSS environment.host = str(request.form["host"]).replace( "<", "").replace(">", "") elif key in parsed_options_dict: # update the value in environment.parsed_options, but dont change the type. # This won't work for parameters that are None parsed_options_dict[key] = type( parsed_options_dict[key])(value) if environment.shape_class and environment.runner is not None: environment.runner.start_shape() return jsonify({ "success": True, "message": "Swarming started using shape class", "host": environment.host }) if self._swarm_greenlet is not None: self._swarm_greenlet.kill(block=True) self._swarm_greenlet = None if environment.runner is not None: self._swarm_greenlet = gevent.spawn(environment.runner.start, user_count, spawn_rate) self._swarm_greenlet.link_exception(greenlet_exception_handler) return jsonify({ "success": True, "message": "Swarming started", "host": environment.host }) else: return jsonify({ "success": False, "message": "No runner", "host": environment.host }) @app.route("/stop") @self.auth_required_if_enabled def stop() -> Response: if self._swarm_greenlet is not None: self._swarm_greenlet.kill(block=True) self._swarm_greenlet = None if environment.runner is not None: environment.runner.stop() return jsonify({"success": True, "message": "Test stopped"}) @app.route("/stats/reset") @self.auth_required_if_enabled def reset_stats() -> str: environment.events.reset_stats.fire() if environment.runner is not None: environment.runner.stats.reset_all() environment.runner.exceptions = {} return "ok" @app.route("/stats/report") @self.auth_required_if_enabled def stats_report() -> Response: res = get_html_report( self.environment, show_download_link=not request.args.get("download")) if request.args.get("download"): res = app.make_response(res) res.headers[ "Content-Disposition"] = f"attachment;filename=report_{time()}.html" return res def _download_csv_suggest_file_name( suggest_filename_prefix: str) -> str: """Generate csv file download attachment filename suggestion. Arguments: suggest_filename_prefix: Prefix of the filename to suggest for saving the download. Will be appended with timestamp. """ return f"{suggest_filename_prefix}_{time()}.csv" def _download_csv_response(csv_data: str, filename_prefix: str) -> Response: """Generate csv file download response with 'csv_data'. Arguments: csv_data: CSV header and data rows. filename_prefix: Prefix of the filename to suggest for saving the download. Will be appended with timestamp. """ response = make_response(csv_data) response.headers["Content-type"] = "text/csv" response.headers[ "Content-disposition"] = f"attachment;filename={_download_csv_suggest_file_name(filename_prefix)}" return response @app.route("/stats/requests/csv") @self.auth_required_if_enabled def request_stats_csv() -> Response: data = StringIO() writer = csv.writer(data) self.stats_csv_writer.requests_csv(writer) return _download_csv_response(data.getvalue(), "requests") @app.route("/stats/requests_full_history/csv") @self.auth_required_if_enabled def request_stats_full_history_csv() -> Response: options = self.environment.parsed_options if options and options.stats_history_enabled and isinstance( self.stats_csv_writer, StatsCSVFileWriter): return send_file( os.path.abspath( self.stats_csv_writer.stats_history_file_name()), mimetype="text/csv", as_attachment=True, download_name=_download_csv_suggest_file_name( "requests_full_history"), etag=True, max_age=0, conditional=True, last_modified=None, ) return make_response( "Error: Server was not started with option to generate full history.", 404) @app.route("/stats/failures/csv") @self.auth_required_if_enabled def failures_stats_csv() -> Response: data = StringIO() writer = csv.writer(data) self.stats_csv_writer.failures_csv(writer) return _download_csv_response(data.getvalue(), "failures") @app.route("/stats/requests") @self.auth_required_if_enabled @memoize(timeout=DEFAULT_CACHE_TIME, dynamic_timeout=True) def request_stats() -> Response: stats: List[Dict[str, Any]] = [] errors: List[StatsErrorDict] = [] if environment.runner is None: report = { "stats": stats, "errors": errors, "total_rps": 0.0, "fail_ratio": 0.0, "current_response_time_percentile_95": None, "current_response_time_percentile_50": None, "state": STATE_MISSING, "user_count": 0, } if isinstance(environment.runner, MasterRunner): report.update({"workers": []}) return jsonify(report) for s in chain(sort_stats(environment.runner.stats.entries), [environment.runner.stats.total]): stats.append({ "method": s.method, "name": s.name, "safe_name": escape(s.name, quote=False), "num_requests": s.num_requests, "num_failures": s.num_failures, "avg_response_time": s.avg_response_time, "min_response_time": 0 if s.min_response_time is None else proper_round( s.min_response_time), "max_response_time": proper_round(s.max_response_time), "current_rps": s.current_rps, "current_fail_per_sec": s.current_fail_per_sec, "median_response_time": s.median_response_time, "ninetieth_response_time": s.get_response_time_percentile(0.9), "ninety_ninth_response_time": s.get_response_time_percentile(0.99), "avg_content_length": s.avg_content_length, }) for e in environment.runner.errors.values(): err_dict = e.serialize() err_dict["name"] = escape(err_dict["name"]) err_dict["error"] = escape(err_dict["error"]) errors.append(err_dict) # Truncate the total number of stats and errors displayed since a large number of rows will cause the app # to render extremely slowly. Aggregate stats should be preserved. truncated_stats = stats[:500] if len(stats) > 500: truncated_stats += [stats[-1]] report = {"stats": truncated_stats, "errors": errors[:500]} if stats: report["total_rps"] = stats[len(stats) - 1]["current_rps"] report[ "fail_ratio"] = environment.runner.stats.total.fail_ratio report[ "current_response_time_percentile_95"] = environment.runner.stats.total.get_current_response_time_percentile( 0.95) report[ "current_response_time_percentile_50"] = environment.runner.stats.total.get_current_response_time_percentile( 0.5) if isinstance(environment.runner, MasterRunner): workers = [] for worker in environment.runner.clients.values(): workers.append({ "id": worker.id, "state": worker.state, "user_count": worker.user_count, "cpu_usage": worker.cpu_usage, "memory_usage": worker.memory_usage, }) report["workers"] = workers report["state"] = environment.runner.state report["user_count"] = environment.runner.user_count return jsonify(report) @app.route("/exceptions") @self.auth_required_if_enabled def exceptions() -> Response: return jsonify({ "exceptions": [{ "count": row["count"], "msg": escape(row["msg"]), "traceback": escape(row["traceback"]), "nodes": ", ".join(row["nodes"]), } for row in (environment.runner.exceptions.values( ) if environment.runner is not None else [])] }) @app.route("/exceptions/csv") @self.auth_required_if_enabled def exceptions_csv() -> Response: data = StringIO() writer = csv.writer(data) self.stats_csv_writer.exceptions_csv(writer) return _download_csv_response(data.getvalue(), "exceptions") @app.route("/tasks") @self.auth_required_if_enabled def tasks() -> Dict[str, Dict[str, Dict[str, float]]]: runner = self.environment.runner user_spawned: Dict[str, int] if runner is None: user_spawned = {} else: user_spawned = (runner.reported_user_classes_count if isinstance(runner, MasterRunner) else runner.user_classes_count) task_data = { "per_class": get_ratio(self.environment.user_classes, user_spawned, False), "total": get_ratio(self.environment.user_classes, user_spawned, True), } return task_data
def get(): global _app if not _app: _app = Flask(__name__) _app.root_path = get_parent_dir(_app.root_path) return _app
def __init__(self, environment, runner): self.environment = environment self.runner = runner app = Flask(__name__) self.app = app app.debug = True app.root_path = os.path.dirname(os.path.abspath(__file__)) @app.route('/') def index(): is_distributed = isinstance(runner, MasterLocustRunner) if is_distributed: slave_count = runner.slave_count else: slave_count = 0 override_host_warning = False if environment.host: host = environment.host elif runner.locust_classes: all_hosts = set([l.host for l in runner.locust_classes]) if len(all_hosts) == 1: host = list(all_hosts)[0] else: # since we have mulitple Locust classes with different host attributes, we'll # inform that specifying host will override the host for all Locust classes override_host_warning = True host = None else: host = None return render_template("index.html", state=runner.state, is_distributed=is_distributed, user_count=runner.user_count, version=version, host=host, override_host_warning=override_host_warning, slave_count=slave_count, is_step_load=environment.step_load, ) @app.route('/swarm', methods=["POST"]) def swarm(): assert request.method == "POST" locust_count = int(request.form["locust_count"]) hatch_rate = float(request.form["hatch_rate"]) if (request.form.get("host")): environment.host = str(request.form["host"]) if environment.step_load: step_locust_count = int(request.form["step_locust_count"]) step_duration = parse_timespan(str(request.form["step_duration"])) runner.start_stepload(locust_count, hatch_rate, step_locust_count, step_duration) return jsonify({'success': True, 'message': 'Swarming started in Step Load Mode', 'host': environment.host}) runner.start(locust_count, hatch_rate) return jsonify({'success': True, 'message': 'Swarming started', 'host': environment.host}) @app.route('/stop') def stop(): runner.stop() return jsonify({'success':True, 'message': 'Test stopped'}) @app.route("/stats/reset") def reset_stats(): runner.stats.reset_all() runner.exceptions = {} return "ok" @app.route("/stats/requests/csv") def request_stats_csv(): response = make_response(requests_csv(self.runner.stats)) file_name = "requests_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response @app.route("/stats/stats_history/csv") def stats_history_stats_csv(): response = make_response(stats_history_csv(self.runner.stats, False, True)) file_name = "stats_history_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response @app.route("/stats/failures/csv") def failures_stats_csv(): response = make_response(failures_csv(self.runner.stats)) file_name = "failures_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response @app.route('/stats/requests') @memoize(timeout=DEFAULT_CACHE_TIME, dynamic_timeout=True) def request_stats(): stats = [] for s in chain(sort_stats(self.runner.stats.entries), [runner.stats.total]): stats.append({ "method": s.method, "name": s.name, "safe_name": escape(s.name, quote=False), "num_requests": s.num_requests, "num_failures": s.num_failures, "avg_response_time": s.avg_response_time, "min_response_time": 0 if s.min_response_time is None else proper_round(s.min_response_time), "max_response_time": proper_round(s.max_response_time), "current_rps": s.current_rps, "current_fail_per_sec": s.current_fail_per_sec, "median_response_time": s.median_response_time, "ninetieth_response_time": s.get_response_time_percentile(0.9), "avg_content_length": s.avg_content_length, }) errors = [] for e in runner.errors.values(): err_dict = e.to_dict() err_dict["name"] = escape(err_dict["name"]) err_dict["error"] = escape(err_dict["error"]) errors.append(err_dict) # Truncate the total number of stats and errors displayed since a large number of rows will cause the app # to render extremely slowly. Aggregate stats should be preserved. report = {"stats": stats[:500], "errors": errors[:500]} if len(stats) > 500: report["stats"] += [stats[-1]] if stats: report["total_rps"] = stats[len(stats)-1]["current_rps"] report["fail_ratio"] = runner.stats.total.fail_ratio report["current_response_time_percentile_95"] = runner.stats.total.get_current_response_time_percentile(0.95) report["current_response_time_percentile_50"] = runner.stats.total.get_current_response_time_percentile(0.5) is_distributed = isinstance(runner, MasterLocustRunner) if is_distributed: slaves = [] for slave in runner.clients.values(): slaves.append({"id":slave.id, "state":slave.state, "user_count": slave.user_count, "cpu_usage":slave.cpu_usage}) report["slaves"] = slaves report["state"] = runner.state report["user_count"] = runner.user_count return jsonify(report) @app.route("/exceptions") def exceptions(): return jsonify({ 'exceptions': [ { "count": row["count"], "msg": row["msg"], "traceback": row["traceback"], "nodes" : ", ".join(row["nodes"]) } for row in runner.exceptions.values() ] }) @app.route("/exceptions/csv") def exceptions_csv(): data = StringIO() writer = csv.writer(data) writer.writerow(["Count", "Message", "Traceback", "Nodes"]) for exc in runner.exceptions.values(): nodes = ", ".join(exc["nodes"]) writer.writerow([exc["count"], exc["msg"], exc["traceback"], nodes]) data.seek(0) response = make_response(data.read()) file_name = "exceptions_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response
import itertools import copy import logging from flask import Flask, request, render_template, redirect, url_for, abort, session from sgsession import Session import shotgun_api3_registry log = logging.getLogger(__name__) app = Flask( __name__, static_url_path='', ) app.root_path = os.path.dirname(os.path.dirname(__file__)) app.config.from_object('sgviewer.config') def Shotgun(): return Session(shotgun_api3_registry.connect('sgviewer')) def static(path): path = path.strip('/') real_path = os.path.join(app.root_path, 'static', path) if os.path.exists(real_path): return '/%s?mt=%d' % (path, os.path.getmtime(real_path)) else: return '/%s' % path
def run(config, run=True): appli = Flask('tracsearch', instance_relative_config=True) appli.root_path = '.' if config.has_section('sentry'): from raven.contrib.flask import Sentry sentry = Sentry(appli, dsn=config.get('sentry', 'dsn')) if config.has_section('statsd'): from statsd import StatsClient stats = StatsClient(config.get('statsd', 'host'), 8125, prefix='tracsearch') else: stats = None es = Elasticsearch(hosts=config.get('elasticsearch', 'url', '127.0.0.1:9200')) @appli.template_filter('nicedate') def nicedate(value): value = escape(value) year = value[0:4] month = value[4:6] day = value[6:8] time = value[9:17] return "%s-%s-%s %s" % (year, month, day, time) @appli.route("/components/<path:filename>") def components(filename): return send_from_directory("components", filename) @appli.route("/", methods=['GET']) def index(): q = request.args.get('q', '') size = 20 from_ = int(request.args.get('from', 0)) facets = ['status', 'user', 'priority', 'keywords', 'component', '_type', 'path', 'domain'] selected = {} for facet in facets: a = request.args.get('facet_%s' % facet, '') if a != '': selected[facet] = a if q == '': context = {'results': None} else: # http://www.elasticsearch.org/guide/reference/query-dsl/query-string-query.html query = { 'query': { 'query_string': { 'query': q, 'default_operator': 'AND' } }, 'facets': { 'changetime': { 'date_histogram': { 'field': 'changetime', 'interval': 'week' } } }, 'highlight': { "pre_tags": ["<b>"], "post_tags": ["</b>"], 'fields': { '_all': {}, 'comment.comment': {}, 'description': {}, 'summary': {}, 'body': {}, 'name': {} } }, 'filter': {}, } for facet in facets: query['facets'][facet] = { 'terms': {'field': facet} } if selected != {}: query['facets'][facet]['facet_filter'] = {'term': selected} if selected != {}: query['filter'] = {'term': selected} query['facets']['changetime']['facet_filter'] = {'term': selected} context = dict(q=q, facets=selected) start = request.args.get('start', '') end = request.args.get('end', '') if end != '': filter_ = {'changetime': { 'from': int(start), 'to': int(end) } } query['filter']['range'] = filter_ query['facets']['changetime']['facet_filter'] = {'range': filter_} context['start'] = start context['end'] = end tmp = request.args.copy() tmp['from'] = int(request.args.get('from', 0)) + 1 context['next'] = urllib.urlencode(encode_dict(tmp)) tmp['from'] = tmp['from'] - 2 context['previous'] = urllib.urlencode(encode_dict(tmp)) tmp['from'] = 0 context['first'] = urllib.urlencode(encode_dict(tmp)) print query context['from'] = from_ context['size'] = size results = es.search( index='trac', size=size, body=query ) if stats: stats.incr('query') stats.timing('query', results['took']) print results.keys() print results['hits'] context['results'] = results return render_template('index.html', **context) appli.debug = config.get('web', 'debug', False) if run: appli.run(config.get('web', 'host', '127.0.0.1')) else: return appli
Application bootstrapping, config and routes. """ from flask import Flask, render_template, request from jinja2 import FileSystemLoader from .utils import curry from .services import Service from exceptions import ImportError import os, sys # Setup the app and load the settings app = Flask(__name__) app.config.from_envvar('NARCISSIST_SETTINGS') app.root_path = app.config["ROOT_PATH"] main_template_path = os.path.join(app.root_path, "themes") app.jinja_loader = FileSystemLoader(main_template_path) # We will hold the mapped URLS in config so we can access them in the templates app.config["URLS"] = [] def _endpoint(service): """ Helper for XHR requests. If the request is XHR, omit the layout. """ if request.is_xhr: return self.service.render() else: return render_template(app.config["THEME"] + "/main.html",
from gevent import wsgi from flask import Flask, make_response, request, render_template from locust import runners from locust.cache import memoize from locust.runners import MasterLocustRunner from locust.stats import median_from_dict from locust import __version__ as version logger = logging.getLogger(__name__) DEFAULT_CACHE_TIME = 2.0 app = Flask(__name__, static_url_path='/meruem/static') app.debug = True app.root_path = os.path.dirname(os.path.abspath(__file__)) @app.route('/meruem') def index(): is_distributed = isinstance(runners.locust_runner, MasterLocustRunner) if is_distributed: slave_count = runners.locust_runner.slave_count else: slave_count = 0 return render_template( "index.html", state=runners.locust_runner.state, is_distributed=is_distributed, slave_count=slave_count,
def serve(options): try: import flask from flask import Flask, send_file, safe_join from flask.json import jsonify except ImportError: abort("Cannot find flask module which is required for webserver mode.") logger = standard_logger(__name__, options.debug) webserver = Flask('git-deps') here = os.path.dirname(os.path.realpath(__file__)) root = os.path.join(here, 'html') webserver.root_path = root logger.debug("Webserver root is %s" % root) ########################################################## # Static content @webserver.route('/') def main_page(): return send_file('git-deps.html') @webserver.route('/tip-template.html') def tip_template(): return send_file('tip-template.html') @webserver.route('/test.json') def data(): return send_file('test.json') def make_subdir_handler(subdir): def subdir_handler(filename): path = safe_join(root, subdir) path = safe_join(path, filename) if os.path.exists(path): return send_file(path) else: flask.abort(404) return subdir_handler for subdir in ('node_modules', 'css', 'js'): fn = make_subdir_handler(subdir) route = '/%s/<path:filename>' % subdir webserver.add_url_rule(route, subdir + '_handler', fn) ########################################################## # Dynamic content def json_error(status_code, error_class, message, **extra): json = { 'status': status_code, 'error_class': error_class, 'message': message, } json.update(extra) response = jsonify(json) response.status_code = status_code return response @webserver.route('/options') def send_options(): client_options = options.__dict__ client_options['repo_path'] = os.getcwd() return jsonify(client_options) @webserver.route('/deps.json/<revspec>') def deps(revspec): detector = DependencyDetector(options) listener = JSONDependencyListener(options) detector.add_listener(listener) if '..' in revspec: try: revisions = GitUtils.rev_list(revspec) except subprocess.CalledProcessError: return json_error(422, 'Invalid revision range', "Could not resolve revision range '%s'" % revspec, revspec=revspec) else: revisions = [revspec] for rev in revisions: try: detector.get_commit(rev) except InvalidCommitish: return json_error(422, 'Invalid revision', "Could not resolve revision '%s'" % rev, rev=rev) detector.find_dependencies(rev) tip_commit = detector.get_commit(revisions[0]) tip_sha1 = tip_commit.hex json = listener.json() json['query'] = { 'revspec': revspec, 'revisions': revisions, 'tip_sha1': tip_sha1, 'tip_abbrev': GitUtils.abbreviate_sha1(tip_sha1), } return jsonify(json) # We don't want to see double-decker warnings, so check # WERKZEUG_RUN_MAIN which is only set for the first startup, not # on app reloads. if options.debug and not os.getenv('WERKZEUG_RUN_MAIN'): print("!! WARNING! Debug mode enabled, so webserver is completely " "insecure!") print("!! Arbitrary code can be executed from browser!") print() try: webserver.run(port=options.port, debug=options.debug, host=options.bindaddr) except OSError as e: print("\n!!! ERROR: Could not start server:") print("!!!") print("!!! " + str(e)) print("!!!") if e.strerror == "Address already in use": print("!!! Do you already have a git deps server running?") print("!!! If so, stop it first and try again.") print("!!!") print("!!! Aborting.") sys.exit(1)
APP_NAME = 'trin_report_rddp' app.config.update( APP_SESSION_NAME='trin_report_rddp', SENTRY_DSN= 'https://*****:*****@sentry.io/110628' ) SentryClient.init_flask(app) if app.config.get('ENV') == 'development': cacheStatic = False else: cacheStatic = True app.root_path = _root app.wsgi_app = SharedDataMiddleware( app.wsgi_app, { '/static': os.path.join(os.path.dirname(__file__), 'static'), }, cache=cacheStatic) # blueprints and views from blueprints.main import main app.register_blueprint(main) from blueprints.accounts import accounts app.register_blueprint(accounts) from blueprints.emergency import emergency app.register_blueprint(emergency) from blueprints.report import report
import constants import db import dictionary import model import segment import utils DEBUG = True SECRET_KEY = 'development key' app = Flask(__name__) app.config.from_object(__name__) ## this file is in serverside, but we need one directory up. myfn = os.path.abspath(__file__) app.root_path = os.path.dirname(os.path.dirname(myfn)) + os.path.sep app.debug = DEBUG app.config.update( PERSONA_JS='https://login.persona.org/include.js', PERSONA_VERIFIER='https://verifier.login.persona.org/verify', ) @utils.nocache @app.route('/') def index(): return send_from_directory(app.root_path + 'app', 'index.html') @app.route('/upload', methods=['GET']) def upload(): return send_from_directory(app.root_path + 'app', 'upload.html')
try: cache[f] = DomainLoader(filename=fname, cachefile=fname + "_cache.pkl").domain except: try: cache[f] = AIMind(filename=fname, cachefile=fname + "_cache.pkl").domain except Exception as e: print(e) print("cannot load file %s, ignoring" % fname) return cache[f] app = Flask(__name__) app.root_path = os.path.dirname(sys.executable) if getattr( sys, 'frozen', False) else os.path.dirname(__file__) def clean(x, form): if x is None: return "No analogy could be made." if form.get('sanitize') == "true": x = x.replace("<", "<") x = x.replace(">", ">") if form.get('clear') == "true": x = x.replace("<", "") x = x.replace(">", "") return x @app.route('/')
from flask import Flask from os.path import join, split from flask.ext.script import Manager from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.root_path = '/'.join(app.root_path.split('/')[:-1]) app.config.from_object('deanthe.config.DevelopmentConfig') url = app.add_url_rule manager = Manager(app) db = SQLAlchemy(app)
import logging import traceback #====================================================== # APP CONFIGURATION #====================================================== app = Flask(__name__) #create flask object app.secret_key = 'secret' #secret cookie key for flash! MAX_FILE_SIZE = 16 #size in MB #debug #app.root_path = os.getcwd() #production app.root_path = '/var/www/Fix/Fix' app.config['UPLOAD_FOLDER'] = str( app.root_path) + "/static/uploaded_files" #save path file_input_location_relative = "/static/uploaded_files/" # passed to the script that manipulates the pdf file_input_location_absolute = "var/www/Fix/Fix/static/uploaded_files/" # passed to the script that manipulates the pdf file_output_location_relative = "/static/served_files" file_output_location_absolute = "/var/www/Fix/Fix/static/served_files/" app.config['MAX_CONTENT_LENGTH'] = MAX_FILE_SIZE * 1024 * 1024 ALLOWED_EXTENSIONS = set(['pdf']) # allowed file extensions #logger obj logger = logging.getLogger(__name__)
import os from app.views import website_bp from config import Configs from flask import Flask app = Flask(__name__) app.root_path = os.getenv('ROOT_PATH') app.template_folder = "app/templates" app.static_folder = "app/static" app.config.from_object(Configs) app.register_blueprint(website_bp)
from flask import Flask from flask import render_template, url_for import os import os.path app = Flask(__name__) app.root_path = os.path.abspath(os.path.dirname(app.root_path)) progs = ["approximate", "precipitation", "feature_view", "clusters", "voronoi"] cache = {} @app.route("/viz/<prog>") def viz(prog): if prog not in progs: raise Exception("Bad program") return render_template(prog + ".html") @app.route("/precipitation") def precipitation(): import scipy.io import json cache_name = "precipitation" if cache_name in cache: return cache[cache_name] matrices = scipy.io.loadmat("gen/precip/201505.mat") matrix = matrices["precip"]
# coding:utf-8 try: from config.db import db except ModuleNotFoundError as err: print("Module not found,manual load module") from flask import Flask import os # import sys app = Flask(__name__) app.root_path = os.path.join(os.path.dirname(__file__), '../') app.config['SECRET_KEY'] = '12345678' app.config[ 'SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:[email protected]:3306/article_web" app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['UP'] = os.path.join(app.root_path, 'static/uploads') from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) # pass class Template(db.Model): __tablename__ = 'template' id = db.Column(db.Integer, primary_key=True) # 编号 title = db.Column(db.String(40), nullable=False) # content = db.Column(db.Text, nullable=False) # 内容 saveName = db.Column(db.String(100), nullable=False) # toPath = db.Column(db.String(100), nullable=False) # addtime = db.Column(db.DateTime, nullable=False) # 注册时间
import json import os.path from gevent import wsgi from flask import Flask, make_response app = Flask("Locust Monitor") app.debug = True app.root_path = os.path.dirname(__file__) _locust = None _num_clients = None _num_requests = None _hatch_rate = None @app.route('/') def index(): response = make_response(open(os.path.join(app.root_path, "static", "index.html")).read()) response.headers["Content-type"] = "text/html" return response @app.route('/swarm') def swarm(): from core import locust_runner locust_runner.start_hatching() return json.dumps({'message': 'Swarming started'}) @app.route('/stats/requests') def request_stats(): from core import locust_runner stats = []
def create_app(request): app = Flask(__name__) app.root_path = request.fspath.dirname logging_init_app(app) app.config['SECRET_KEY'] = 'secret_key' return app
def __call__(self, environ, start_response): # only set PATH_INFO for older versions of Lighty or if no # server software is provided. That's because the test was # added in newer Werkzeug versions and we don't want to break # people's code if they are using this fixer in a test that # does not set the SERVER_SOFTWARE key. if 'SERVER_SOFTWARE' not in environ or \ environ['SERVER_SOFTWARE'] < 'lighttpd/1.4.28': environ['PATH_INFO'] = environ.get('SCRIPT_NAME', '') + \ environ.get('PATH_INFO', '') environ['SCRIPT_NAME'] = self.app_root.rstrip('/') return self.app(environ, start_response) app = Flask(__name__) app.root_path = abspath(dirname(__file__)) opt = {} parser = OptionParser() parser.add_option('-d', '--debug', dest='DEBUG', action='store_true', help='Provides debug output when unhandled exceptions occur.') parser.add_option('-v', '--verbose', dest='VERBOSE', action='store_true', help='Provides verbose output for what is being done.') parser.add_option('-s', '--student', dest='STUDENT', action='store_true', help='Connects to the student LDAP instead of the staff.') cmd_opt, junk = parser.parse_args() c = ConfigFile(app.root_path + '/config.ini') keys = c.getsection('Refdesk') for key in keys: opt[key] = keys[key]
def run(config, run=True): appli = Flask('tracsearch', instance_relative_config=True) appli.root_path = '.' if config.has_section('sentry'): from raven.contrib.flask import Sentry sentry = Sentry(appli, dsn=config.get('sentry', 'dsn')) if config.has_section('statsd'): from statsd import StatsClient stats = StatsClient(config.get('statsd', 'host'), 8125, prefix='tracsearch') else: stats = None es = Elasticsearch( hosts=config.get('elasticsearch', 'url', '127.0.0.1:9200')) @appli.template_filter('nicedate') def nicedate(value): value = escape(value) year = value[0:4] month = value[4:6] day = value[6:8] time = value[9:17] return "%s-%s-%s %s" % (year, month, day, time) @appli.route("/components/<path:filename>") def components(filename): return send_from_directory("components", filename) @appli.route("/", methods=['GET']) def index(): q = request.args.get('q', '') size = 20 from_ = int(request.args.get('from', 0)) facets = [ 'status', 'user', 'priority', 'keywords', 'component', '_type', 'path', 'domain' ] selected = {} for facet in facets: a = request.args.get('facet_%s' % facet, '') if a != '': selected[facet] = a if q == '': context = {'results': None} else: # http://www.elasticsearch.org/guide/reference/query-dsl/query-string-query.html query = { 'query': { 'query_string': { 'query': q, 'default_operator': 'AND' } }, 'facets': { 'changetime': { 'date_histogram': { 'field': 'changetime', 'interval': 'week' } } }, 'highlight': { "pre_tags": ["<b>"], "post_tags": ["</b>"], 'fields': { '_all': {}, 'comment.comment': {}, 'description': {}, 'summary': {}, 'body': {}, 'name': {} } }, 'filter': {}, } for facet in facets: query['facets'][facet] = {'terms': {'field': facet}} if selected != {}: query['facets'][facet]['facet_filter'] = {'term': selected} if selected != {}: query['filter'] = {'term': selected} query['facets']['changetime']['facet_filter'] = { 'term': selected } context = dict(q=q, facets=selected) start = request.args.get('start', '') end = request.args.get('end', '') if end != '': filter_ = {'changetime': {'from': int(start), 'to': int(end)}} query['filter']['range'] = filter_ query['facets']['changetime']['facet_filter'] = { 'range': filter_ } context['start'] = start context['end'] = end tmp = request.args.copy() tmp['from'] = int(request.args.get('from', 0)) + 1 context['next'] = urllib.urlencode(encode_dict(tmp)) tmp['from'] = tmp['from'] - 2 context['previous'] = urllib.urlencode(encode_dict(tmp)) tmp['from'] = 0 context['first'] = urllib.urlencode(encode_dict(tmp)) print query context['from'] = from_ context['size'] = size results = es.search(index='trac', size=size, body=query) if stats: stats.incr('query') stats.timing('query', results['took']) print results.keys() print results['hits'] context['results'] = results return render_template('index.html', **context) appli.debug = config.get('web', 'debug', False) if run: appli.run(config.get('web', 'host', '127.0.0.1')) else: return appli
#!/bin/python3 # author: Jan Hybs import sys sys.path.append('/home/jan-hybs/projects/cc/codecritic/src') from flask import Flask, render_template from flask_sse import sse from env import Env app = Flask(__name__) app.config["REDIS_URL"] = "redis://localhost" app.register_blueprint(sse, url_prefix='/stream') app.root_path = Env.www @app.route('/') def index(): return render_template("index.html") @app.route('/hello') def publish_hello(): sse.publish({"message": "Hello!"}, type='greeting') return "Message sent!" # app.run(debug=True) # #!/usr/bin/env python # import datetime # import flask
import os from flask import Flask from monitoring.views.base import IndexView app = Flask(__name__, static_folder='static') app.config.from_pyfile('flask.conf.py') app.root_path = os.path.join(app.root_path, 'monitoring') app.add_url_rule('/', view_func=IndexView.as_view('index')) app.debug = True
from plume.user import UserBackend from plume.utils import get_path, split_path from pytz import common_timezones def filter_render(data, toc=False): return Markup(render_document(data, toc)) def filter_strong(data): return Markup("<strong>%s</strong>" % data) # Create application app = Flask("__main__", static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR) app.root_path = ROOT_PATH app.jinja_options["extensions"].append("jinja2.ext.do") app.jinja_env.filters.update({"render": filter_render, "strong": filter_strong}) # Load secret key file_path = os.path.join(CONF_DIR, "plume.secret") if not os.path.exists(file_path): raise Exception("secret file %s is missing\n" % file_path) mode = os.stat(file_path).st_mode if mode & stat.S_IRWXU != 384 or mode & stat.S_IRWXG != 0 or mode & stat.S_IRWXO != 0:
# Set the rundir rundir = get_rundir() # Include paths sys.path.insert(0, rundir) sys.path.insert(0, os.path.join(rundir, 'lib')) # Create Flask instance from flask import Flask app = Flask(__name__) # If frozen, we need define static and template paths if check_frozen(): app.root_path = rundir app.static_path = '/static' app.add_url_rule(app.static_path + '/<path:filename>', endpoint='static', view_func=app.send_static_file) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader(os.path.join(rundir, 'templates')) def import_modules(): """All modules that are available in Maraschino are at this point imported.""" import modules.applications import modules.controls import modules.couchpotato import modules.currently_playing
try: return cache[f] except KeyError: try: cache[f] = DomainLoader(filename=fname, cachefile=fname+"_cache.pkl").domain except: try: cache[f] = AIMind(filename=fname, cachefile=fname+"_cache.pkl").domain except Exception as e: print(e) print("cannot load file %s, ignoring"%fname) return cache[f] app = Flask(__name__) app.root_path = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(__file__) def clean(x, form): if x is None: return "No analogy could be made." if form.get('sanitize') == "true": x = x.replace("<","<") x = x.replace(">",">") if form.get('clear') == "true": x = x.replace("<","") x = x.replace(">","") return x @app.route('/') def index():
def serve(options): try: import flask from flask import Flask, send_file, safe_join from flask.json import jsonify except ImportError: abort("Cannot find flask module which is required for webserver mode.") webserver = Flask('git-deps') here = os.path.dirname(os.path.realpath(__file__)) root = os.path.join(here, 'html') webserver.root_path = root ########################################################## # Static content @webserver.route('/') def main_page(): return send_file('git-deps.html') @webserver.route('/tip-template.html') def tip_template(): return send_file('tip-template.html') @webserver.route('/test.json') def data(): return send_file('test.json') def make_subdir_handler(subdir): def subdir_handler(filename): path = safe_join(root, subdir) path = safe_join(path, filename) if os.path.exists(path): return send_file(path) else: flask.abort(404) return subdir_handler for subdir in ('node_modules', 'css', 'js'): fn = make_subdir_handler(subdir) route = '/%s/<path:filename>' % subdir webserver.add_url_rule(route, subdir + '_handler', fn) ########################################################## # Dynamic content def json_error(status_code, error_class, message, **extra): json = { 'status': status_code, 'error_class': error_class, 'message': message, } json.update(extra) response = jsonify(json) response.status_code = status_code return response @webserver.route('/options') def send_options(): client_options = options.__dict__ client_options['repo_path'] = os.getcwd() return jsonify(client_options) @webserver.route('/deps.json/<commitish>') def deps(commitish): detector = DependencyDetector(options) listener = JSONDependencyListener(options) detector.add_listener(listener) try: root_commit = detector.get_commit(commitish) except InvalidCommitish as e: return json_error( 422, 'Invalid commitish', "Could not resolve commitish '%s'" % commitish, commitish=commitish) detector.find_dependencies(commitish) json = listener.json() json['root'] = { 'commitish': commitish, 'sha1': root_commit.hex, 'abbrev': GitUtils.abbreviate_sha1(root_commit.hex), } return jsonify(json) # We don't want to see double-decker warnings, so check # WERKZEUG_RUN_MAIN which is only set for the first startup, not # on app reloads. if options.debug and not os.getenv('WERKZEUG_RUN_MAIN'): print("!! WARNING! Debug mode enabled, so webserver is completely " "insecure!") print("!! Arbitrary code can be executed from browser!") print() webserver.run(port=options.port, debug=options.debug, host=options.bindaddr)
import inspect import os import sys from flask import Flask, Blueprint from flask_sqlalchemy import SQLAlchemy from comsvc.lib import models from comsvc.lib import queue from comsvc.lib import tasks project_name = 'comsvc' path = os.path.dirname(__file__) app = Flask(__name__) app.template_folder = path + '/templates' app.static_folder = path + '/static' app.root_path = path config = __import__('config') app.config.from_object('config') app.db = SQLAlchemy(app) models.declare_models(app.db) celery = app.celery = queue.init_app(app) tasks.define_tasks(app.celery) for blueprint_file in app.config['ENABLED_BLUEPRINTS']: module_name = project_name + '.blueprints.' + blueprint_file __import__(module_name) module = sys.modules[module_name] for name, obj in inspect.getmembers(module): if isinstance(obj, Blueprint): app.register_blueprint(obj)
import json import os import shelve import requests from flask import Flask, session from flask.ext.mako import MakoTemplates from flask.ext.githubhook import GitHubHook from memoize import Memoizer app = Flask(__name__, static_url_path='') app.root_path = os.path.abspath(os.path.join(__file__, '..')) app.instance_path = os.path.abspath(os.path.join(__file__, '..', '..', 'var')) config_path = os.path.join(app.instance_path, 'config.py') if os.path.exists(config_path): locals_ = {} execfile(config_path, locals_, app.config) app.config.update(locals_) else: print 'Could not find var/config.py' app.config['SECRET_KEY'] = app.config.get('SECRET_KEY') or 'monkey' app.config['GITHUB_ALLOWED_OWNERS'] = set(['mikeboers', 'FluentImage']) app.debug = app.debug or bool(os.environ.get('DEBUG')) githubhook = GitHubHook(app=app, url_prefix='/hook') mako = MakoTemplates(app)
print(e) continue def predict_img(img): model_dir = '../models/models_resnext101_32x8d_acc_ 0.951807 loss_ 0.18151' data_transform = get_transform() predictor, opt, epoch = setup(model_dir, createModel) pred, conf, preds = predict(predictor, img, data_transform, epoch) # return "Prediction: {} at {:g} confidence \nConf list: {}".format(pred, conf, preds) return pred, conf app = Flask(__name__) app.root_path = os.path.join(os.getcwd()) UPLOAD_FOLDER = os.path.join(os.getcwd(), 'static', 'uploads') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/') def home(): return render_template('trash.html', filename='#') @app.route('/upload', methods= ['POST']) def upload_file(): if request.method == 'POST': file = request.files['image'] filename = file.filename
from flask import Flask, render_template, abort, send_file import os.path as path import os import re import vlc from subprocess import call, Popen app = Flask(__name__) app.root_path = path.abspath(path.dirname(__file__)).replace("\\","/") app.media_path = app.root_path+"/content/local-media"#path.join(app.root_path, "content", "local-media") #create custom 404 page for friendly faults and then have an ajax for internet connection check (succeed reload old url, failure report) streams = [ ('localMedia', 'images/local-media-icon.png'), ('youtube', 'images/youtube-icon.png') ] i = vlc.Instance("--video-on-top") mediaPlayer = i.media_player_new() app.download = None @app.route("/") #return the app itself def index(): return render_template("2col_base.html") @app.route("/mediaPlayerAction/<string:action>") def mediaPlayerAction(action): if action == "play": if mediaPlayer.get_state() == vlc.State.Ended: mediaPlayer.stop() if mediaPlayer.get_state() == vlc.State.Stopped: mediaPlayer.play() else:
import os from celery import Celery from flask import Flask from flask import send_from_directory from flask.ext.cache import Cache from flask.ext.pymongo import PyMongo from app.celery import make_celery from app.config import Config from app.ext.session.redis import RedisSessionInterface app = Flask(__name__) app.session_interface = RedisSessionInterface() app.config.from_object(config.Development) app._static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../static') app.root_path = os.path.dirname(os.path.abspath(__file__ + '/../')) print(app.root_path) app.cache = Cache(app) app.mongo = PyMongo(app) celery = make_celery(app) from teddy.views import teddy as teddy_blueprint app.register_blueprint(teddy_blueprint, url_prefix='/teddy')
import ssl, os, hashlib, datetime from flask import Flask, request, render_template, send_from_directory sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) sslcontext.options |= ssl.OP_NO_TLSv1 sslcontext.options |= ssl.OP_NO_TLSv1_1 sslcontext.protocol = ssl.PROTOCOL_TLSv1_2 sslcontext.set_ciphers( "ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305") sslcontext.set_ecdh_curve("secp384r1") sslcontext.load_cert_chain("/home/pi/keys/fullchain.pem", "/home/pi/keys/privkey.pem") WORK_DIR = '/media/kingdian/' app = Flask(__name__) app.root_path = os.path.dirname(WORK_DIR) @app.route('/thumbnails/<filename>') def send_image(filename): return send_from_directory("thumbnails", filename) @app.route('/videos/<filename>') def send_video(filename): return send_from_directory("videos", filename) @app.route('/gallery', methods=['GET', 'POST']) def get_gallery(): if request.method == 'POST':
import serveconf import logging import os,sys support = WebSupport(serveconf.SRCDIR, serveconf.BUILDDIR) #### flask part from flask import Flask, render_template, abort, g, request, jsonify, redirect, url_for from jinja2 import Environment, FileSystemLoader app = Flask(__name__) app.debug = True # デバッグ用フラグ app.jinja_env = Environment(loader = FileSystemLoader(os.path.abspath(serveconf.TEMPLATE_DIR)+'/'), extensions=['jinja2.ext.i18n']) app.root_path = serveconf.BUILDDIR # Via bzrlib.tests class StringIOWrapper(object): """A wrapper around cStringIO which just adds an encoding attribute. Internally we can check sys.stdout to see what the output encoding should be. However, cStringIO has no encoding attribute that we can set. So we wrap it instead. """ encoding='ascii' _cstring = None def __init__(self, s=None): from cStringIO import StringIO if s is not None:
def create_app(): app = Flask(__name__) app.root_path = app.root_path app.secret_key = os.urandom(12) return app
from flask import Flask from flask import render_template from flask import Markup from werkzeug.contrib.cache import MemcachedCache import os import markdown app = Flask(__name__) app.root_path = os.path.dirname(os.path.realpath(__file__)) import logging from logging import FileHandler file_handler = FileHandler(app.root_path+'/error.log') file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler) try: cache = MemcachedCache(['127.0.0.1:11211']) except RuntimeError: class FakeCache: def get(self, k): return None def set(self, k, v, **kwargs): return None cache = FakeCache() @app.route('/') @app.route('/<page>') @app.route('/<page>/<section>')
import os from flask import Flask from tcidatabase import db PROJECT_PATH = os.path.abspath(os.path.dirname(__file__) + '/..') os.environ.setdefault('SETTINGS', PROJECT_PATH + '/settings.py') app = Flask('tci-online') app.config.from_envvar('SETTINGS') app.root_path = PROJECT_PATH app.secret_key = app.config['SECRET_KEY'] db.connect(**app.config['DATABASE'])
import os import json from flask import Flask, render_template, jsonify, send_from_directory, request from flask_swagger import swagger from localstack.constants import VERSION from localstack.utils.aws.aws_stack import Environment from localstack.utils import common from localstack.dashboard import infra root_path = os.path.dirname(os.path.realpath(__file__)) web_dir = root_path + '/web/' app = Flask('app', template_folder=web_dir) app.root_path = root_path @app.route('/swagger.json') def spec(): swag = swagger(app) swag['info']['version'] = VERSION swag['info']['title'] = 'AWS Resources Dashboard' return jsonify(swag) @app.route('/graph', methods=['POST']) def get_graph(): """ Get deployment graph --- operationId: 'getGraph' parameters:
def __init__( self, environment, host, port, auth_credentials=None, tls_cert=None, tls_key=None, stats_csv_writer=None, delayed_start=False, ): """ Create WebUI instance and start running the web server in a separate greenlet (self.greenlet) Arguments: environment: Reference to the current Locust Environment host: Host/interface that the web server should accept connections to port: Port that the web server should listen to auth_credentials: If provided, it will enable basic auth with all the routes protected by default. Should be supplied in the format: "user:pass". tls_cert: A path to a TLS certificate tls_key: A path to a TLS private key delayed_start: Whether or not to delay starting web UI until `start()` is called. Delaying web UI start allows for adding Flask routes or Blueprints before accepting requests, avoiding errors. """ environment.web_ui = self self.stats_csv_writer = stats_csv_writer or StatsCSV(environment, stats_module.PERCENTILES_TO_REPORT) self.environment = environment self.host = host self.port = port self.tls_cert = tls_cert self.tls_key = tls_key app = Flask(__name__) self.app = app app.debug = True app.root_path = os.path.dirname(os.path.abspath(__file__)) self.app.config["BASIC_AUTH_ENABLED"] = False self.auth = None self.greenlet = None if auth_credentials is not None: credentials = auth_credentials.split(":") if len(credentials) == 2: self.app.config["BASIC_AUTH_USERNAME"] = credentials[0] self.app.config["BASIC_AUTH_PASSWORD"] = credentials[1] self.app.config["BASIC_AUTH_ENABLED"] = True self.auth = BasicAuth() self.auth.init_app(self.app) else: raise AuthCredentialsError( "Invalid auth_credentials. It should be a string in the following format: 'user.pass'" ) if environment.runner: self.update_template_args() if not delayed_start: self.start() @app.route("/") @self.auth_required_if_enabled def index(): if not environment.runner: return make_response("Error: Locust Environment does not have any runner", 500) self.update_template_args() return render_template("index.html", **self.template_args) @app.route("/swarm", methods=["POST"]) @self.auth_required_if_enabled def swarm(): assert request.method == "POST" user_count = int(request.form["user_count"]) spawn_rate = float(request.form["spawn_rate"]) if request.form.get("host"): # Replace < > to guard against XSS environment.host = str(request.form["host"]).replace("<", "").replace(">", "") if environment.shape_class: environment.runner.start_shape() return jsonify( {"success": True, "message": "Swarming started using shape class", "host": environment.host} ) environment.runner.start(user_count, spawn_rate) return jsonify({"success": True, "message": "Swarming started", "host": environment.host}) @app.route("/stop") @self.auth_required_if_enabled def stop(): environment.runner.stop() return jsonify({"success": True, "message": "Test stopped"}) @app.route("/stats/reset") @self.auth_required_if_enabled def reset_stats(): environment.events.reset_stats.fire() environment.runner.stats.reset_all() environment.runner.exceptions = {} return "ok" @app.route("/stats/report") @self.auth_required_if_enabled def stats_report(): stats = self.environment.runner.stats start_ts = stats.start_time start_time = datetime.datetime.fromtimestamp(start_ts) start_time = start_time.strftime("%Y-%m-%d %H:%M:%S") end_ts = stats.last_request_timestamp end_time = datetime.datetime.fromtimestamp(end_ts) end_time = end_time.strftime("%Y-%m-%d %H:%M:%S") host = None if environment.host: host = environment.host elif environment.runner.user_classes: all_hosts = set([l.host for l in environment.runner.user_classes]) if len(all_hosts) == 1: host = list(all_hosts)[0] requests_statistics = list(chain(sort_stats(stats.entries), [stats.total])) failures_statistics = sort_stats(stats.errors) exceptions_statistics = [] for exc in environment.runner.exceptions.values(): exc["nodes"] = ", ".join(exc["nodes"]) exceptions_statistics.append(exc) history = stats.history static_js = "" js_files = ["jquery-1.11.3.min.js", "echarts.common.min.js", "vintage.js", "chart.js"] for js_file in js_files: path = os.path.join(os.path.dirname(__file__), "static", js_file) with open(path, encoding="utf8") as f: content = f.read() static_js += "// " + js_file + "\n" static_js += content static_js += "\n\n\n" res = render_template( "report.html", int=int, round=round, requests_statistics=requests_statistics, failures_statistics=failures_statistics, exceptions_statistics=exceptions_statistics, start_time=start_time, end_time=end_time, host=host, history=history, static_js=static_js, ) if request.args.get("download"): res = app.make_response(res) res.headers["Content-Disposition"] = "attachment;filename=report_%s.html" % time() return res def _download_csv_suggest_file_name(suggest_filename_prefix): """Generate csv file download attachment filename suggestion. Arguments: suggest_filename_prefix: Prefix of the filename to suggest for saving the download. Will be appended with timestamp. """ return f"{suggest_filename_prefix}_{time()}.csv" def _download_csv_response(csv_data, filename_prefix): """Generate csv file download response with 'csv_data'. Arguments: csv_data: CSV header and data rows. filename_prefix: Prefix of the filename to suggest for saving the download. Will be appended with timestamp. """ response = make_response(csv_data) response.headers["Content-type"] = "text/csv" response.headers[ "Content-disposition" ] = f"attachment;filename={_download_csv_suggest_file_name(filename_prefix)}" return response @app.route("/stats/requests/csv") @self.auth_required_if_enabled def request_stats_csv(): data = StringIO() writer = csv.writer(data) self.stats_csv_writer.requests_csv(writer) return _download_csv_response(data.getvalue(), "requests") @app.route("/stats/requests_full_history/csv") @self.auth_required_if_enabled def request_stats_full_history_csv(): options = self.environment.parsed_options if options and options.stats_history_enabled: return send_file( os.path.abspath(self.stats_csv_writer.stats_history_file_name()), mimetype="text/csv", as_attachment=True, attachment_filename=_download_csv_suggest_file_name("requests_full_history"), add_etags=True, cache_timeout=None, conditional=True, last_modified=None, ) return make_response("Error: Server was not started with option to generate full history.", 404) @app.route("/stats/failures/csv") @self.auth_required_if_enabled def failures_stats_csv(): data = StringIO() writer = csv.writer(data) self.stats_csv_writer.failures_csv(writer) return _download_csv_response(data.getvalue(), "failures") @app.route("/stats/requests") @self.auth_required_if_enabled @memoize(timeout=DEFAULT_CACHE_TIME, dynamic_timeout=True) def request_stats(): stats = [] for s in chain(sort_stats(self.environment.runner.stats.entries), [environment.runner.stats.total]): stats.append( { "method": s.method, "name": s.name, "safe_name": escape(s.name, quote=False), "num_requests": s.num_requests, "num_failures": s.num_failures, "avg_response_time": s.avg_response_time, "min_response_time": 0 if s.min_response_time is None else proper_round(s.min_response_time), "max_response_time": proper_round(s.max_response_time), "current_rps": s.current_rps, "current_fail_per_sec": s.current_fail_per_sec, "median_response_time": s.median_response_time, "ninetieth_response_time": s.get_response_time_percentile(0.9), "avg_content_length": s.avg_content_length, } ) errors = [] for e in environment.runner.errors.values(): err_dict = e.to_dict() err_dict["name"] = escape(err_dict["name"]) err_dict["error"] = escape(err_dict["error"]) errors.append(err_dict) # Truncate the total number of stats and errors displayed since a large number of rows will cause the app # to render extremely slowly. Aggregate stats should be preserved. report = {"stats": stats[:500], "errors": errors[:500]} if len(stats) > 500: report["stats"] += [stats[-1]] if stats: report["total_rps"] = stats[len(stats) - 1]["current_rps"] report["fail_ratio"] = environment.runner.stats.total.fail_ratio report[ "current_response_time_percentile_95" ] = environment.runner.stats.total.get_current_response_time_percentile(0.95) report[ "current_response_time_percentile_50" ] = environment.runner.stats.total.get_current_response_time_percentile(0.5) is_distributed = isinstance(environment.runner, MasterRunner) if is_distributed: workers = [] for worker in environment.runner.clients.values(): workers.append( { "id": worker.id, "state": worker.state, "user_count": worker.user_count, "cpu_usage": worker.cpu_usage, } ) report["workers"] = workers report["state"] = environment.runner.state report["user_count"] = environment.runner.user_count return jsonify(report) @app.route("/exceptions") @self.auth_required_if_enabled def exceptions(): return jsonify( { "exceptions": [ { "count": row["count"], "msg": row["msg"], "traceback": row["traceback"], "nodes": ", ".join(row["nodes"]), } for row in environment.runner.exceptions.values() ] } ) @app.route("/exceptions/csv") @self.auth_required_if_enabled def exceptions_csv(): data = StringIO() writer = csv.writer(data) writer.writerow(["Count", "Message", "Traceback", "Nodes"]) for exc in environment.runner.exceptions.values(): nodes = ", ".join(exc["nodes"]) writer.writerow([exc["count"], exc["msg"], exc["traceback"], nodes]) return _download_csv_response(data.getvalue(), "exceptions")
pyximport.install() import os, sys from orbit.framing import TEXT from flask import Flask, render_template from orbit.server import WebSocketResource, WSGISiteResource from orbit.transaction import Transaction, State, TransactionManager from twisted.web.static import File from twisted.internet import reactor from twisted.web.server import Site from twisted.web.wsgi import WSGIResource from twisted.python import log from twisted.web.resource import Resource import cgi app = Flask(__name__) app.root_path = os.path.join(os.path.dirname(__file__), '..') app.static_folder = os.path.join(app.root_path, 'static') app.template_folder = os.path.join(app.root_path, 'templates') class EchoState(State): def onNewConnection(self, ws): ws.opcode = TEXT def onUpdate(self, ws, opcode, data, fin): print 'Opcode: %s' % opcode print 'Data: %s' % data ws.write(cgi.escape(data).encode('utf8')) def onEndConnection(self, ws): self.transaction.finish()
def __init__(self, environment, auth_credentials=None): """ If auth_credentials is provided, it will enable basic auth with all the routes protected by default. Should be supplied in the format: "user:pass". """ environment.web_ui = self self.environment = environment app = Flask(__name__) self.app = app app.debug = True app.root_path = os.path.dirname(os.path.abspath(__file__)) self.app.config["BASIC_AUTH_ENABLED"] = False self.auth = None if auth_credentials is not None: credentials = auth_credentials.split(':') if len(credentials) == 2: self.app.config["BASIC_AUTH_USERNAME"] = credentials[0] self.app.config["BASIC_AUTH_PASSWORD"] = credentials[1] self.app.config["BASIC_AUTH_ENABLED"] = True self.auth = BasicAuth() self.auth.init_app(self.app) else: raise AuthCredentialsError( "Invalid auth_credentials. It should be a string in the following format: 'user.pass'" ) @app.route('/') @self.auth_required_if_enabled def index(): if not environment.runner: return make_response( "Error: Locust Environment does not have any runner", 500) is_distributed = isinstance(environment.runner, MasterLocustRunner) if is_distributed: worker_count = environment.runner.worker_count else: worker_count = 0 override_host_warning = False if environment.host: host = environment.host elif environment.runner.locust_classes: all_hosts = set( [l.host for l in environment.runner.locust_classes]) if len(all_hosts) == 1: host = list(all_hosts)[0] else: # since we have mulitple Locust classes with different host attributes, we'll # inform that specifying host will override the host for all Locust classes override_host_warning = True host = None else: host = None return render_template( "index.html", state=environment.runner.state, is_distributed=is_distributed, user_count=environment.runner.user_count, version=version, host=host, override_host_warning=override_host_warning, worker_count=worker_count, is_step_load=environment.step_load, ) @app.route('/swarm', methods=["POST"]) @self.auth_required_if_enabled def swarm(): assert request.method == "POST" locust_count = int(request.form["locust_count"]) hatch_rate = float(request.form["hatch_rate"]) if (request.form.get("host")): environment.host = str(request.form["host"]) if environment.step_load: step_locust_count = int(request.form["step_locust_count"]) step_duration = parse_timespan( str(request.form["step_duration"])) environment.runner.start_stepload(locust_count, hatch_rate, step_locust_count, step_duration) return jsonify({ 'success': True, 'message': 'Swarming started in Step Load Mode', 'host': environment.host }) environment.runner.start(locust_count, hatch_rate) return jsonify({ 'success': True, 'message': 'Swarming started', 'host': environment.host }) @app.route('/stop') @self.auth_required_if_enabled def stop(): environment.runner.stop() return jsonify({'success': True, 'message': 'Test stopped'}) @app.route("/stats/reset") @self.auth_required_if_enabled def reset_stats(): environment.runner.stats.reset_all() environment.runner.exceptions = {} return "ok" @app.route("/stats/requests/csv") @self.auth_required_if_enabled def request_stats_csv(): response = make_response( requests_csv(self.environment.runner.stats)) file_name = "requests_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response @app.route("/stats/failures/csv") @self.auth_required_if_enabled def failures_stats_csv(): response = make_response( failures_csv(self.environment.runner.stats)) file_name = "failures_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response @app.route('/stats/requests') @self.auth_required_if_enabled @memoize(timeout=DEFAULT_CACHE_TIME, dynamic_timeout=True) def request_stats(): stats = [] for s in chain(sort_stats(self.environment.runner.stats.entries), [environment.runner.stats.total]): stats.append({ "method": s.method, "name": s.name, "safe_name": escape(s.name, quote=False), "num_requests": s.num_requests, "num_failures": s.num_failures, "avg_response_time": s.avg_response_time, "min_response_time": 0 if s.min_response_time is None else proper_round( s.min_response_time), "max_response_time": proper_round(s.max_response_time), "current_rps": s.current_rps, "current_fail_per_sec": s.current_fail_per_sec, "median_response_time": s.median_response_time, "ninetieth_response_time": s.get_response_time_percentile(0.9), "avg_content_length": s.avg_content_length, }) errors = [] for e in environment.runner.errors.values(): err_dict = e.to_dict() err_dict["name"] = escape(err_dict["name"]) err_dict["error"] = escape(err_dict["error"]) errors.append(err_dict) # Truncate the total number of stats and errors displayed since a large number of rows will cause the app # to render extremely slowly. Aggregate stats should be preserved. report = {"stats": stats[:500], "errors": errors[:500]} if len(stats) > 500: report["stats"] += [stats[-1]] if stats: report["total_rps"] = stats[len(stats) - 1]["current_rps"] report[ "fail_ratio"] = environment.runner.stats.total.fail_ratio report[ "current_response_time_percentile_95"] = environment.runner.stats.total.get_current_response_time_percentile( 0.95) report[ "current_response_time_percentile_50"] = environment.runner.stats.total.get_current_response_time_percentile( 0.5) is_distributed = isinstance(environment.runner, MasterLocustRunner) if is_distributed: workers = [] for worker in environment.runner.clients.values(): workers.append({ "id": worker.id, "state": worker.state, "user_count": worker.user_count, "cpu_usage": worker.cpu_usage }) report["workers"] = workers report["state"] = environment.runner.state report["user_count"] = environment.runner.user_count return jsonify(report) @app.route("/exceptions") @self.auth_required_if_enabled def exceptions(): return jsonify({ 'exceptions': [{ "count": row["count"], "msg": row["msg"], "traceback": row["traceback"], "nodes": ", ".join(row["nodes"]) } for row in environment.runner.exceptions.values()] }) @app.route("/exceptions/csv") @self.auth_required_if_enabled def exceptions_csv(): data = StringIO() writer = csv.writer(data) writer.writerow(["Count", "Message", "Traceback", "Nodes"]) for exc in environment.runner.exceptions.values(): nodes = ", ".join(exc["nodes"]) writer.writerow( [exc["count"], exc["msg"], exc["traceback"], nodes]) data.seek(0) response = make_response(data.read()) file_name = "exceptions_{0}.csv".format(time()) disposition = "attachment;filename={0}".format(file_name) response.headers["Content-type"] = "text/csv" response.headers["Content-disposition"] = disposition return response
import os import xbmcaddon from flask import Flask __addonpath__ = xbmcaddon.Addon(id="script.webui").getAddonInfo("path") app = Flask(__name__) app.root_path = __addonpath__ app.static_path = "/static" app.static_folder = os.path.join(__addonpath__, "resources", "static") app.template_folder = os.path.join(__addonpath__, "resources", "templates") app.add_url_rule(app.static_path + "/<path:filename>", endpoint="static", view_func=app.send_static_file) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader(os.path.join(__addonpath__, "resources", "templates"))
def create_app(): app = Flask('Adyen') # Update root_path to specific module. If using multiple modules, can define relative to instance path app.root_path = app.root_path + '/app' # Register 404 handler app.register_error_handler(404, page_not_found) # read in values from config.ini file and load them into project read_config() # Routes: @app.route('/') def home(): return render_template('home.html') @app.route('/cart/<integration>') def cart(integration): return render_template('cart.html', method=integration) @app.route('/checkout/<integration>') def checkout(integration): payment_methods_response = adyen_payment_methods() origin_key = config.origin_key if integration in config.supported_integrations: return render_template('component.html', method=integration, payment_methods=payment_methods_response, origin_key=origin_key) else: abort(404) @app.route('/api/getPaymentMethods', methods=['GET']) def get_payment_methods(): payment_methods_response = adyen_payment_methods() return payment_methods_response @app.route('/api/initiatePayment', methods=['POST']) def initiate_payment(): payment_response = adyen_payments(request) return payment_response @app.route('/api/submitAdditionalDetails', methods=['POST']) def payment_details(): details_response = get_payment_details(request) return details_response @app.route('/api/handleShopperRedirect', methods=['POST', 'GET']) def handle_redirect(): values = request.json if request.is_json else request.values.to_dict( ) # Get values from request object # Fetch paymentData from the frontend if we have not already if 'paymentData' in values: redirect_response = handle_shopper_redirect(values) if redirect_response["resultCode"] == 'Authorised': return redirect(url_for('checkout_success')) elif redirect_response[ "resultCode"] == 'Received' or redirect_response[ "resultCode"] == 'Pending': return redirect(url_for('checkout_pending')) else: return redirect(url_for('checkout_failure')) else: return render_template('fetch-payment-data.html', values=values) @app.route('/success', methods=['GET']) def checkout_success(): return render_template('checkout-success.html') @app.route('/failed', methods=['GET']) def checkout_failure(): return render_template('checkout-failed.html') @app.route('/pending', methods=['GET']) def checkout_pending(): return render_template('checkout-success.html') @app.route('/error', methods=['GET']) def checkout_error(): return render_template('checkout-failed.html') @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'img/favicon.ico') return app
import os import jinja2 from flask import Flask from flask_sockets import Sockets CURRENT_DIRECTORY = os.path.dirname(__file__) STATIC_FOLDER = os.path.join("twidder", "static") MEDIA_FOLDER = os.path.join("twidder", "media") ALLOWED_MEDIA = {"jpg", "png", "mp4", "mp3", "wav"} app = Flask(__name__, static_url_path='', static_folder=STATIC_FOLDER) app.config["SECRET_KEY"] = os.urandom(24) app.config['UPLOAD_FOLDER'] = MEDIA_FOLDER app.root_path = os.getcwd() app.jinja_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(os.path.join(CURRENT_DIRECTORY, "static")) ]) sockets = Sockets(app) from . import twidder
import json import logging import click from flask import Flask, render_template, jsonify, send_from_directory, request from flask_swagger import swagger from localstack.constants import VERSION from localstack.utils.aws.aws_stack import Environment from localstack.utils import common from localstack.dashboard import infra root_path = os.path.dirname(os.path.realpath(__file__)) web_dir = root_path + '/web/' app = Flask('app', template_folder=web_dir) app.root_path = root_path @app.route('/swagger.json') def spec(): swag = swagger(app) swag['info']['version'] = VERSION swag['info']['title'] = 'AWS Resources Dashboard' return jsonify(swag) @app.route('/graph', methods=['POST']) def get_graph(): """ Get deployment graph --- operationId: 'getGraph'
return os.path.abspath(__file__)[:-13] # Set the rundir rundir = get_rundir() # Include paths sys.path.insert(0, rundir) sys.path.insert(0, os.path.join(rundir, 'lib')) # Create Flask instance from flask import Flask app = Flask(__name__) # If frozen, we need define static and template paths if check_frozen(): app.root_path = rundir app.static_path = '/static' app.add_url_rule( app.static_path + '/<path:filename>', endpoint='static', view_func=app.send_static_file ) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader(os.path.join(rundir, 'templates')) def import_modules(): """All modules that are available in Maraschino are at this point imported.""" import modules.applications import modules.controls
import os import xbmcaddon from flask import Flask __addonpath__ = xbmcaddon.Addon(id='script.webui').getAddonInfo('path') app = Flask(__name__) app.root_path = __addonpath__ app.static_path = '/static' app.static_folder = os.path.join(__addonpath__, 'resources', 'static') app.template_folder = os.path.join(__addonpath__, 'resources', 'templates') app.add_url_rule(app.static_path + '/<path:filename>', endpoint='static', view_func=app.send_static_file) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader( os.path.join(__addonpath__, 'resources', 'templates'))
def initWebServer(myport): app = Flask(__name__,static_folder='html',template_folder='html/templates') app.root_path = os.getcwd() logging.config.fileConfig(app.root_path+'/python/'+'logging.conf') logger = logging.getLogger('simple') @app.route('/') def send_1(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return redirect("login.html") return redirect("dashboard.html") @app.route('/login.html') def send_2(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return send_from_directory(app.static_folder, 'login.html') if (priv == 'JWSError'): response = make_response('login.html') response.set_cookie('jwt', '') return response return redirect("dashboard.html") @app.route('/login_action.cgi',methods=['POST', 'GET']) def send_3(): error = None if request.method == 'POST': user = request.form['inputUsername'] if (m_valid_login(user,request.form['inputPassword']) == True): privilage = dbman.get_privilage(user).decode('utf-8'); client_jwt = myjwt.generate_JWT(user,privilage) response = make_response('dashboard.html') response.set_cookie('jwt', client_jwt) return response return "Wrong username or wrong password." return 'Bad Request', 400, {'Content-Type': 'text/html'}#Generate http 400 @app.route('/templates/dashboard.html') def send_4(first='无',second='0',third='0',fourth='0'): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} chk_internet = internet_on() if chk_internet == True: first='良好' second = str(callcpp.get_online_client()) fourth = str(dbman.get_user_count()) return render_template('dashboard.html', first=first,second=second,third=third,fourth=fourth) @app.route('/templates/IRControl.html') def send_5(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} return render_template('IRControl.html') @app.route('/templates/Usermanager.html') def send_6(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} return render_template('Usermanager.html') @app.route('/<path:filename>') def send_7(filename): return send_from_directory(app.static_folder, filename) @app.route('/js/<path:filename>') def send_8(filename): return send_from_directory(app.static_folder+'/js', filename) @app.route('/css/<path:filename>') def send_9(filename): return send_from_directory(app.static_folder+'/css', filename) @app.route('/fonts/<path:filename>') def send_10(filename): return send_from_directory(app.static_folder+'/fonts', filename) @app.route('/get_user_info.cgi',methods=['GET']) def send_11(): user,priv = proc_jwt(request.cookies.get('jwt')) res='{"User": "******","Priv": "'+priv+'"}' return res,200,{'Content-Type': 'application/json'} @app.route('/logout.cgi',methods=['GET']) def send_12(): response = make_response(redirect('login.html')) response.set_cookie('jwt', '') return response @app.route('/renew_jwt.cgi',methods=['GET']) def send_13(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} response = make_response() renew = myjwt.renew_JWT(request.cookies.get('jwt')) if (renew == 'Error'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} if (renew == 'NotNess'): return '' else: response.set_cookie('jwt', renew) return response @app.route('/study_IR.cgi',methods=['POST', 'GET']) def send_14(): if request.method == 'POST': user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} IRID = request.form['IRID'] m_dict={} m_dict["b"]="b" m_dict["c"]=int(IRID) callcpp.m_write_dict(m_dict) return 'Bad Request', 400, {'Content-Type': 'text/html'} @app.route('/get_IR_recode.cgi') def send_15(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} st = request.args['rangeL'] num = request.args['num'] res = dbman.get_IR_dict(st,num) response = make_response(JSONEncoder().encode(res)) return respond @app.route('/go_IR_action.cgi',methods=['POST', 'GET']) def send_16(): if request.method == 'POST': user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} action = request.form['action'] operator = {'send':IR_action_Send,'modify':IR_action_Modify,'remove':IR_action_Remove} res = operator.get(action)(request.form['m_data']) respond = make_response(res) return respond return 'Bad Request', 400, {'Content-Type': 'text/html'} @app.route('/get_user_list.cgi') def send_17(): #{ID:username} user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} num = request.args['num'] st = request.args['start'] res = dbman.get_user_list(st,num) return JSONEncoder().encode(res),200,{'Content-Type': 'application/json'} @app.route('/get_IR_learn_proc.cgi') def send_18(): res = callcpp.m_read() return '' @app.route('/get_priv_list.cgi') def send_19(): #{username:privilage} user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} num = request.args['num'] st = request.args['start'] res = dbman.get_priv_list(st,num) return JSONEncoder().encode(res),200,{'Content-Type': 'application/json'} @app.route('/modify_password.cgi',methods=['POST', 'GET']) def send_20(): if request.method == 'POST': user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} u_name = request.form['username'] oripass = request.form['oripass'] newpass = request.form['newpass'] if ((user != u_name) and (priv != "admin")): return 'Privilage Error', 400, {'Content-Type': 'text/html'} if (dbman.verify_user(u_name,oripass) != "Success."): return 'Original password wrong', 400, {'Content-Type': 'text/html'} if (dbman.change_user_pass(u_name,newpass) == "Success."): respond = make_response("Success.") if (u_name == user): #revoke jwt respond = make_response('Relogin.') respond.set_cookie('jwt', '') return respond return 'Bad Request', 400, {'Content-Type': 'text/html'} @app.route('/get_operation_log.cgi') def send_21(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} respond = make_response("Success.") return respond @app.route('/get_ready_info.cgi') def send_22(): user,priv = proc_jwt(request.cookies.get('jwt')) if (priv == 'JWTError'): return 'Unauthorized', 401, {'Content-Type': 'text/html'} respond = make_response("Success.") return respond app.run(host="0.0.0.0",port=int(myport),threaded=True)
pass # and now redirect all default streams to this dummyStream: sys.stdout = dummyStream() sys.stderr = dummyStream() sys.stdin = dummyStream() sys.__stdout__ = dummyStream() sys.__stderr__ = dummyStream() sys.__stdin__ = dummyStream() app = Flask(__name__) app.secret_key = '8af32bf6ff121fecbce4cbb67f5cb43b' if getattr(sys, "frozen", False): # The application is frozen app.root_path = os.path.dirname(sys.executable) # datadir = os.path.dirname(sys.executable) else: # The application is not frozen # Change this bit to match where you store your data files: app.root_path = os.path.dirname(__file__) ui = FlaskUI(app=app) try: conn = rpyc.connect('localhost', 12345, config={ "allow_all_attrs": True, "allow_pickle": True })