def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) cache.init_app(app) mail.init_app(app) celery.conf.update(app.config) # flask-login init login_manager.init_app(app) login_manager.unauthorized_handler(lambda: exception(Unauthorized())) # blueprint from app.controllers.user import users_endpoint app.register_blueprint(users_endpoint) from app.controllers.channel import channels_endpoint app.register_blueprint(channels_endpoint) from app.controllers.admin import admin_endpoint app.register_blueprint(admin_endpoint) # error handler app.register_error_handler(APIException, lambda e: exception(e)) app.register_error_handler(404, lambda e: render_template('404.html')) app.register_error_handler(500, lambda e: render_template('500.html')) return app
def create_app(): """Flask application factory :rtype: Flask """ config = os.environ.setdefault( 'NIDHOGG_SETTINGS_MODULE', 'nidhogg.settings.base' ) application = Flask(__name__) application.config.from_object(config) from nidhogg.common.database import db db.init_app(application) application.add_url_rule( '/auth/<method>', view_func=YggdrasilView.as_view('generic'), ) application.add_url_rule( '/auth/legacy/<method>', view_func=LegacyView.as_view('legacy'), ) application.add_url_rule( '/api/<method>', view_func=ApiView.as_view('api'), ) application.register_error_handler(NidhoggError, NidhoggError.handler) return application
def get_app(config): app = Flask(__name__) app.config.from_object(config) mail.init_app(app) RQ(app) csrf = CsrfProtect(app) csrf.exempt(api_1_0_blueprint) stream_handler = logging.StreamHandler() app.logger.setLevel(logging.DEBUG) app.logger.addHandler(stream_handler) db.init_app(app) Migrate(app, db) bootstrap = Bootstrap(app) security = Security(app, user_datastore) user_registered.connect(user_registered_sighandler) app.register_blueprint(ratings_blueprint) app.register_blueprint(api_1_0_blueprint, url_prefix="/api/v1") app.register_blueprint(verify_blueprint, url_prefix="/v") app.register_blueprint(tournament_blueprint, url_prefix="/tournament") app.register_error_handler(500, email_exception) return app
def create_app(): """Create Flask app using the factory.""" app = Flask(__name__) # Configuration app.config.from_object('claimstore.config') # Blueprints from claimstore.restful import blueprint as restful_bp from claimstore.views import blueprint as views_bp app.register_blueprint(restful_bp) app.register_blueprint(views_bp) # Database db.init_app(app) # Register exceptions app.register_error_handler(RestApiException, handle_restful_exceptions) @app.errorhandler(404) def not_found(error): if 'application/json' in request.headers['Content-Type']: return jsonify({ 'status': 'error', 'message': 'Resource not found.'}), 404 return render_template('404.html'), 404 return app
def create_app(): app = Flask(__name__) # config if os.getenv('DEV') == 'yes': app.config.from_object('config.DevelopmentConfig') app.logger.info("Config: Development") elif os.getenv('TEST') == 'yes': app.config.from_object('config.TestConfig') app.logger.info("Config: Test") else: app.config.from_object('config.ProductionConfig') app.logger.info("Config: Production") db.init_app(app) ## register views from views import weight_pages app.register_blueprint(weight_pages) @app.context_processor def context_processor(): """Add variables to context """ if hasattr(current_user, '_user'): curuser = current_user._user else: # if user is not logged in curuser = "" return {'today': datetime.date.today, 'user':curuser, } app.register_error_handler(401, error401) app.register_error_handler(404, error404) app.register_error_handler(500, error500) app.jinja_env.filters['year'] = format_year # flask-login login_manager = LoginManager() login_manager.setup_app(app) login_manager.login_view = ".login" @login_manager.user_loader def load_user(user): from models import User u1 = User.query.get(user) if u1: return DbUser(user) else: return None return app
class ModApi: def __init__(self): self.app = Flask(__name__) self.load_modules() for code in HTTP_STATUS_CODES: self.app.register_error_handler(code, handle_error) @self.app.route('/robots.txt') def static_from_root(): return send_from_directory(app.static_folder, request.path[1:]) @self.app.route('/favicon.ico') def favicon(): return send_from_directory(app.root_path, 'favicon.ico', mimetype='image/vnd.microsoft.icon') @self.app.route('/') @require_secret def index(): notifier = notify.boxcar.BoxcarNotifier() notifier.quick_send('Modapi running.') return jsonify({'status': 'ok'}) def shutdown_server(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() @self.app.route('/shutdown') @require_secret def shutdown(): shutdown_server() return 'Server shutting down...' def load_modules(self): for p in modularity.get_modules(config.MODULES_DIR): c = import_module(p + '.config') mc = c.config k = config.MOD_CONFIG_ROUTES_MOD_KEY rmod = mc[k] if k in mc else config.MOD_CONFIG_ROUTES_MOD_DEFAULT m = import_module(p + '.' + rmod) k = config.MOD_CONFIG_MOD_VAR_KEY mvar = mc[k] if k in mc else config.MOD_CONFIG_MOD_VAR_DEFAULT mod = getattr(m, mvar) inject(m, mc) k = config.MOD_CONFIG_URL_PREFIX_KEY pre = mc[k] if k in mc else None self.app.register_blueprint(mod, url_prefix=pre)
class Server: JSON_HEADER = {"Content-Type": "application/json"} def __init__(self, ctl_port): self.web_app = Flask(__name__) self.ctl_port = ctl_port self.web_app.add_url_rule("/", "index", self.index, methods=["GET", "POST"]) self.web_app.add_url_rule("/register", "register", self.register, methods=["POST"]) self.web_app.add_url_rule("/deregister", "deregister", self.deregister, methods=["DELETE"]) self.web_app.add_url_rule("/update", "update", self.update, methods=["POST"]) self.web_app.add_url_rule("/transfer", "transfer", self.transfer, methods=["POST"]) self.web_app.add_url_rule("/file/<sha>", "find_file", self.find_file, methods=["GET"]) self.web_app.add_url_rule("/heartbeat", "heartbeat", self.heartbeat, methods=["POST"]) self.web_app.register_error_handler(405, self.bad_method) self.db = db.Database() def run(self): self.web_app.run(host="0.0.0.0", port=self.ctl_port) def bad_method(self, error=None): return '{"status":"ERROR_METHOD_NOT_ALLOWED"}', 405, Server.JSON_HEADER def bad_request(self, error=None, msg=""): return '{"status":"ERROR_BAD_REQUEST","msg":"' + msg + '"}', 400, Server.JSON_HEADER def forbidden(self, error=None): return '{"status":"ERROR_FORBIDDEN"}', 403, Server.JSON_HEADER def success(self): return '{"status":"OK"}', 200, Server.JSON_HEADER def index(self): if request.method == "POST": return '{"json":"test_post"}', 200, Server.JSON_HEADER else: return '{"json":"test_get"}', 200, Server.JSON_HEADER def register(self): json_dict = request.get_json() try: client = Client(json_dict) if self.db.add_client(client): return self.success() else: return self.bad_request(msg="Client Exist") except Exception, e: print(traceback.print_exc()) return self.bad_request(msg="JSON Error")
def create_app(config_override: Mapping = None) -> Flask: """Create the flask app for the debug server. Parameters: config_override: Dict containing custom configuration to apply after loading the normal config. Useful for testing. """ config_override = {} if config_override is None else config_override # TODO: Rename app, no longer used only for debugging app = Flask('stuffrdebugserver', instance_relative_config=True, static_url_path='', template_folder='static') app.config.from_object('config.default') app.config.from_envvar('STUFFR_SETTINGS') app.config.from_mapping(config_override) app.json_encoder = StuffrJSONEncoder logger.set_logger(app.logger) db.init_app(app) security = Security(app, user_store, confirm_register_form=StuffrRegisterForm) security.unauthorized_handler(api_unauthenticated_handler) Mail(app) # In debug mode Swagger documentation is served at root if not app.config['DEBUG']: def api_root_view(): """Provide a link to API documentation if root accessed.""" return error_response( 'TODO: Link to documentation here', HTTPStatus.NOT_FOUND) blueprint_api.add_url_rule('/', 'apiindex', api_root_view) app.register_blueprint(blueprint_simple, url_prefix='/simple') app.register_blueprint(blueprint_api, url_prefix='/api') def default404(e): """Default handler for 404.""" # TODO: Conditional JSON/HTML response (for simple mode) return error_response(e.description, HTTPStatus.NOT_FOUND) app.register_error_handler(HTTPStatus.NOT_FOUND, default404) # TODO: Make friendlier error message (40x or 50x?) app.add_url_rule('/', 'index', lambda: "You probably shouldn't be here") return app
class RestProvider(APIProvider): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.app = Flask("iris-rest") # Make sure we have config if 'rest' not in self.daemon.config.providers: raise Exception("No config for RestProvider (need config.providers.rest)") self.config = self.daemon.config.providers['rest'] # Grab config vars self.host = self.config.get("host", "0.0.0.0") self.port = self.config.get("port", "8080") self.auth = self.config.get("auth") # Meta Registers self.app.register_error_handler(APIBase, self.handle_response) self.app.before_request(self.before_request) self.app.add_url_rule('/', 'index', self.route_index) # Controllers self.app.register_blueprint(ShardController(self).bp) self.app.register_blueprint(EntryController(self).bp) def before_request(self): if self.auth and request.headers.get("IRIS_AUTH") != self.auth: raise APIError("Invalid Credentials", 1000) def handle_response(self, obj): return jsonify(obj.data) def run(self): super().run() self.app.run(host=self.host, port=self.port) def route_index(self): raise APIResponse({ "stats": { "uptime": float("{0:.4f}".format(time.time() - self.daemon.start_time)), }, "version": __VERSION__ })
def create_app(config_object=None): app = Flask(__name__) app.config.from_object('config.default') if config_object: app.config.from_object(config_object) app.add_url_rule('/', view_func=views.get_apps, methods=['GET']) app.add_url_rule('/login', view_func=views.get_login, methods=['GET']) app.add_url_rule('/login', view_func=views.do_login, methods=['POST']) app.add_url_rule('/logout', view_func=views.do_logout, methods=['GET']) app.add_url_rule('/deploy', view_func=views.do_deploy, methods=['POST']) app.add_url_rule('/ping/ping', view_func=views.healthcheck, methods=['GET']) app.register_error_handler(WBAPIHTTPError, views.wb_error_handler) app.register_error_handler(Exception, views.generic_error_handler) app.before_request(get_api_before_request) return app
def create_app(db_create_all=False): app = Flask(__name__) # Configurations app.config.from_object('config') # Blueprints from claimstore.modules.claims.restful import claims_restful from claimstore.modules.claims.views import claims_views app.register_blueprint(claims_views) app.register_blueprint(claims_restful) # Init databse db.init_app(app) if db_create_all: # Create schema with app.app_context(): db.create_all() # Populate with predefined predicates from claimstore.modules.claims.models import Predicate predicates = [ 'is_same_as', 'is_different_than', 'is_erratum_of', 'is_superseded_by', 'is_cited_by', 'is_software_for', 'is_dataset_for' ] for pred_name in predicates: if not Predicate.query.filter_by(name=pred_name).first(): predicate = Predicate(name=pred_name) db.session.add(predicate) db.session.commit() # Register exceptions app.register_error_handler(InvalidUsage, handle_invalid_usage) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 return app
def create_app(app_name='hermes_cms', config_obj=None, blueprints=None): """ :type app_name: str :param app_name: :type config_obj: object|None :param config_obj: :type blueprints: list|None :param blueprints: :return: """ app = Flask(app_name) if config_obj: app.config.from_object(config_obj) else: # todo this needs to be in Configuration Registry app.secret_key = 'testing-key' blueprints = blueprints or Registry().get('blueprint').get('blueprint') for blueprint in blueprints: module = __import__(blueprint['name'], fromlist=blueprint['from']) route = getattr(module, blueprint['from']) if hasattr(module, 'url_rules'): module.url_rules() app.register_blueprint(route, **blueprint.get('kwargs', {})) def error_handler(error): log.exception(str(error)) return Response(response=json.dumps({ 'notify_msg': { 'title': 'Server Error', 'message': 'An internal server error occurred.', 'type': 'success' } }), content_type='application/json', status=500) app.register_error_handler(Exception, error_handler) app.before_request_funcs.setdefault(None, []).append(db_connect) app.after_request_funcs.setdefault(None, []).append(db_close) return app
def create_app(configuration=None, instance_path='/etc/ihatemoney', instance_relative_config=True): app = Flask( __name__, instance_path=instance_path, instance_relative_config=instance_relative_config) # If a configuration object is passed, use it. Otherwise try to find one. load_configuration(app, configuration) app.wsgi_app = PrefixedWSGI(app) # Get client's real IP # Note(0livd): When running in a non-proxy setup, is vulnerable to requests # with a forged X-FORWARDED-FOR header app.wsgi_app = ProxyFix(app.wsgi_app) validate_configuration(app) app.register_blueprint(web_interface) app.register_blueprint(api) app.register_error_handler(404, page_not_found) # Configure the a, root="main"pplication setup_database(app) mail = Mail() mail.init_app(app) app.mail = mail # Jinja filters app.jinja_env.filters['minimal_round'] = minimal_round # Translations babel = Babel(app) @babel.localeselector def get_locale(): # get the lang from the session if defined, fallback on the browser "accept # languages" header. lang = session.get('lang', request.accept_languages.best_match(['fr', 'en'])) setattr(g, 'lang', lang) return lang return app
def make_json_exception_app(name, **kwargs): ''' Taken from snippet http://flask.pocoo.org/snippets/83/ Method to make Flask app that returns all user unhandled exceptions as json by default ''' def make_json_error(error): response = jsonify(message=str(error)) response.status_code =\ error.code if isinstance(error, HTTPException) else 500 return response app = Flask(name, **kwargs) for code in default_exceptions.keys(): app.register_error_handler(code, make_json_error) return app
def create_app(environment='ponyexpress.config.configuration.DefaultConfig'): app = Flask(__name__) # Load configuration app.config.from_object(environment) app.config.from_pyfile('/etc/pony-express/ponyexpress.cfg', True) # Database from ponyexpress.database import db db.init_app(app) # Register blueprints from ponyexpress.api.v1.collector import collector from ponyexpress.api.v1.query import query from ponyexpress.api.v1.updater import updater app.register_blueprint(collector) app.register_blueprint(query) app.register_blueprint(updater) # Error handler app.register_error_handler(InvalidAPIUsage, handle_invalid_usage) if app.debug is not True and app.testing is not True: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler(app.config.get('REQUEST_LOG', 'ponyexpress.log'), maxBytes=1024 * 1024 * 100, backupCount=20) file_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) app.before_request(log_entry) return app
def create_app(): app = Flask(__name__) Babel(app) with app.app_context(): from . import index, youtube, vimeo, custom, autocomplete from newsic.functions import not_found app.register_blueprint(index.bp) app.register_blueprint(index.bp, url_prefix='/<lang_code>') app.register_blueprint(youtube.bp) app.register_blueprint(youtube.bp, url_prefix='/<lang_code>') app.register_blueprint(vimeo.bp) app.register_blueprint(vimeo.bp, url_prefix='/<lang_code>') app.register_blueprint(custom.bp) app.register_blueprint(custom.bp, url_prefix='/<lang_code>') app.register_blueprint(autocomplete.bp) app.register_error_handler(404, not_found) return app
def create_app(): app = Flask(__name__) import os app.config.from_object(os.environ["APP_SETTINGS"]) from .core import redis redis.init_app(app) from tasks.views import TasksView TasksView.register(app) from profiles.views import ProfilesView ProfilesView.register(app) from .handlers import not_found, bad_request, internal_error from .exceptions import DoesNotExist, ValidationError app.register_error_handler(DoesNotExist, not_found) app.register_error_handler(ValidationError, bad_request) app.register_error_handler(500, internal_error) @app.after_request def after_request(response): response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization") response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE") return response return app
def create_app(): """ Creates the flask app, loading blueprints and the configuration. :return: flask app :rtype: Flask """ init_logging() app = Flask(__name__) app.register_blueprint(v1.section) app.register_error_handler(exceptions.HTTPError, app_util.http_error_handler) config.load(app) # in case the config says that debug mode is on, we need to adjust the # log level set_log_level(app) data.start_monitoring_data_dir(app) search.load_config(app) logging.getLogger(__name__).info('application initialized') return app
def create_app(server): '''Create Flask application and attach TAXII server instance ``server`` to it. :param `opentaxii.server.TAXIIServer` server: TAXII server instance :return: Flask app ''' app = Flask(__name__) app.taxii = server app.add_url_rule("/<path:relative_path>", "opentaxii_services_view", _server_wrapper(server), methods=['POST', 'OPTIONS']) app.register_blueprint(management, url_prefix='/management') app.register_error_handler(500, handle_internal_error) app.register_error_handler(StatusMessageException, handle_status_exception) return app
def create_app(): app = Flask(__name__) app.config.from_object(settings) DB.init_app(app) redis_store.init_app(app) routes.configure_routes(app) configure_login(app) configure_logger(app) app.register_error_handler(400, error_400) app.register_error_handler(404, error_404) app.register_error_handler(405, error_405) app.register_error_handler(Exception, exception_handler) app.jinja_env.filters["json"] = json.dumps def epoch_to_date(s): import datetime return datetime.datetime.fromtimestamp(s).strftime("%B %-d, %Y") def epoch_to_ts(s): import datetime return datetime.datetime.fromtimestamp(s).strftime("%m-%-d-%Y %H:%M") app.jinja_env.filters["epoch_to_date"] = epoch_to_date app.jinja_env.filters["epoch_to_ts"] = epoch_to_ts app.config["CDN_DOMAIN"] = os.getenv( "CDN_DOMAIN", re.sub("https?://", "", settings.SERVICE_URL) ) app.config["CDN_HTTPS"] = True cdn.init_app(app) class ContextTask(celery.Task): def __call__(self, *args, **kwargs): if app.config["TESTING"]: # When testing, celery tasks are called eagerly, from the same thread # so don't push an app context, the request's app context is already there return self.run(*args, **kwargs) else: with app.app_context(): g.log = structlog.get_logger().new() return self.run(*args, **kwargs) celery.Task = ContextTask if not app.debug and not app.testing: configure_ssl_redirect(app) Limiter( app, key_func=get_ipaddr, global_limits=[settings.RATE_LIMIT], storage_uri=settings.REDIS_RATE_LIMIT, ) return app
def create_app(environment='ponyexpress.config.configuration.DevelopmentConfig'): app = Flask(__name__) # Load configuration #TODO: load configuration depending on environment app.config.from_object(environment) app.config.from_envvar('PONYEXPRES_CFG', True) # Database from ponyexpress.database import db db.init_app(app) # Register blueprints from ponyexpress.api.v1.collector import collector from ponyexpress.api.v1.query import query app.register_blueprint(collector) app.register_blueprint(query) # Error handler app.register_error_handler(InvalidAPIUsage, handle_invalid_usage) return app
def create_app(config_obj=None): """ Create a Flask application object. :return: a Flask application object :rtype: flask.Flask """ app = Flask(__name__) if config_obj: app.config.from_object(config_obj) else: load_config(app) if app.config['ENV'] != 'development': if app.config['SECRET_KEY'] == 'replace-me-with-something-random': raise RuntimeError('You need to change the SECRET_KEY configuration for production') for config in ('AD_DOMAIN', 'AD_LDAP_URI', 'AD_USERS_GROUP', 'AD_ADMINS_GROUP', 'AD_SERVICE_USERNAME', 'AD_SERVICE_PASSWORD', 'SQLALCHEMY_DATABASE_URI'): if not app.config.get(config): raise RuntimeError('You need to set the "{0}" setting'.format(config)) init_logging(app) db.init_app(app) migrations_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrations') Migrate(app, db, directory=migrations_dir) app.cli.command()(create_db) for status_code in default_exceptions.keys(): app.register_error_handler(status_code, json_error) app.register_error_handler(ValidationError, json_error) app.register_error_handler(ConfigurationError, json_error) app.register_error_handler(ADError, json_error) app.after_request(insert_headers) app.register_blueprint(api_v1, url_prefix='/api/v1') jwt = JWTManager(app) jwt.token_in_blacklist_loader(BlacklistedToken.is_token_revoked) jwt.user_claims_loader(add_jwt_claims) app.cli.command()(prune_blacklisted_tokens) return app
CHORD_SERVICES=os.environ.get( "CHORD_SERVICES", os.environ.get("BENTO_SERVICES", "chord_services.json")), CHORD_URL=os.environ.get( "CHORD_URL", os.environ.get("BENTO_URL", "http://127.0.0.1:5000/")), # Own node's URL CONTACT_TIMEOUT=int(os.environ.get("CONTACT_TIMEOUT", 1)), SERVICE_ID=os.environ.get("SERVICE_ID", SERVICE_TYPE), URL_PATH_FORMAT=os.environ.get("URL_PATH_FORMAT", "api/{artifact}"), ) # Generic catch-all application.register_error_handler( Exception, flask_error_wrap_with_traceback(flask_internal_server_error, sr_compat=True, service_name=SERVICE_NAME)) application.register_error_handler( BadRequest, flask_error_wrap(flask_bad_request_error, sr_compat=True)) application.register_error_handler( NotFound, flask_error_wrap(flask_not_found_error, sr_compat=True)) def get_service_url(artifact: str): return urljoin( current_app.config["CHORD_URL"], current_app.config["URL_PATH_FORMAT"].format(artifact=artifact)) with application.app_context():
book_view = BooksView.as_view('book_view') app.add_url_rule('/books', view_func=book_view, methods=['POST', 'GET', 'PUT', 'DELETE']) book_profile_view = BookProfileView.as_view('book_profile_view') app.add_url_rule('/books/<int:book_id>', view_func=book_profile_view, methods=['GET']) search_view = BookSearchView.as_view('search_view') app.add_url_rule('/search', view_func=search_view, methods=['POST', 'GET']) request_view = RequestView.as_view('request') app.add_url_rule(rule='/requests/<int:request_id>', view_func=request_view, methods=['PUT', 'DELETE']) app.add_url_rule(rule='/books/<int:book_id>/requests', view_func=request_view, methods=['POST']) app.add_url_rule(rule='/requests', view_func=request_view, methods=['GET']) decline_request_view = DeclineRequestView.as_view('decline_request') app.add_url_rule(rule='/requests/decline/<int:request_id>', view_func=decline_request_view, methods=['POST']) req_history_view = RequestHistoryView.as_view("req_history_view") app.add_url_rule(rule="/requests/history", view_func=req_history_view, methods=['GET']) app.register_error_handler(404, page_not_found) app.register_error_handler(403, forbidden) app.register_error_handler(410, gone) app.register_error_handler(500, internal_server_error)
class ArtBot(object): def __init__(self): try: with open('config.json', 'r') as configFile: self.config = json.load(configFile) except Exception as e: print('Unable to read config.json!') print(e) sys.exit(-1) self.app = Flask(__name__, static_folder='static') self.dbDict = None self.initDb() if self.config['USE_PIXIV']: self.pixiv = Pixiv(self.dbDict, self.config) if self.config['USE_DEVIANTART']: self.deviantart = DeviantArt(self.dbDict, 'http://localhost:{}{}'.format(self.config['PORT'], DA_AUTH_REDIRECT)) if self.config['USE_ARTSTATION']: self.artstation = ArtStation(self.dbDict, self.config['ARTSTATION_USERNAME']) self.app.add_url_rule('/', 'index', self.index) self.app.add_url_rule('/getWorks', 'getWorks', self.getWorks) self.app.add_url_rule('/authorizeDeviantart', 'authorizeDeviantart', self.authorizeDeviantart) self.app.add_url_rule(DA_AUTH_REDIRECT, 'deviantartAuthorizationRedirect', self.deviantartAuthorizationRedirect) self.app.register_error_handler(DeviantArtApiError, self.handle_invalid_usage) self.app.run(debug=True, port=self.config['PORT']) def initDb(self): if os.path.isfile(DB_FILENAME): with open(DB_FILENAME, 'rb') as dbFile: try: self.dbDict = pickle.load(dbFile) except Exception as e: print('Exception loading db file:') print(e) if not isinstance(self.dbDict, dict): print('Unable to parse db file, defaulting to empty db') self.dbDict = {} if not self.dbDict.get('works'): self.dbDict['works'] = {} def index(self): return send_file('static/index.html') def getWorks(self): if self.config['USE_DEVIANTART']: self.deviantart.loadWorks() if self.config['USE_PIXIV']: self.pixiv.loadWorks() if self.config['USE_ARTSTATION']: self.artstation.loadWorks() works = list(sorted(self.dbDict['works'].values(), key=lambda x: x['imageTimestamp'], reverse=True))[:self.config['MAX_WORKS_ON_PAGE']] self.cleanDb(works) self.loadExtraWorkInfo() self.persistDb() return json.dumps(works) def loadExtraWorkInfo(self): if self.config['USE_ARTSTATION']: self.artstation.loadExtraWorkInfo() def cleanDb(self, works): discard = list(sorted(self.dbDict['works'].items(), key=lambda x: x[1]['imageTimestamp'], reverse=True))[self.config['MAX_WORKS_ON_PAGE']:] [self.dbDict['works'].pop(key) for (key, val) in discard] # Clean images keepImages = itertools.chain(*(work['imageUrls'] for work in works)) keepImages = set(os.path.split(url)[1] for url in keepImages if not url.startswith('http')) existingImages = set(os.path.split(url)[1] for url in os.listdir(self.config['PIXIV_DOWNLOAD_DIRECTORY'])) imagesToRemove = existingImages - keepImages [os.remove(os.path.join(self.config['PIXIV_DOWNLOAD_DIRECTORY'], name)) for name in imagesToRemove] # Clean avatars keepAvatars = (work['authorAvatarUrl'] for work in works) keepAvatars = set(os.path.split(url)[1] for url in keepAvatars if not url.startswith('http')) existingAvatars = set(os.path.split(url)[1] for url in os.listdir(self.config['PIXIV_AVATAR_DIRECTORY'])) avatarsToRemove = existingAvatars - keepAvatars [os.remove(os.path.join(self.config['PIXIV_AVATAR_DIRECTORY'], name)) for name in avatarsToRemove] def persistDb(self): print('Persisting to disk') with open(DB_FILENAME, 'wb') as dbFile: pickle.dump(self.dbDict, dbFile) def authorizeDeviantart(self): return render_template('authorizeDeviantart.html', url=self.deviantart.getAuthorizationUrl()) def deviantartAuthorizationRedirect(self): self.deviantart.handleAuthorizationCallback(request) return redirect('/') def handle_invalid_usage(self, error): print('ERROR HANDLING') print(error.message) print(self.deviantart.token) response = jsonify(error.message) response.status_code = error.status_code return response
lnd_thread = BackgroundThread(update_lnd_info_thread, 60) lnd_thread.start() drive_thread = BackgroundThread(update_device_info, 60) drive_thread.start() public_ip_thread = BackgroundThread(find_public_ip, 60*60*3) # 3-hour repeat public_ip_thread.start() checkin_thread = BackgroundThread(check_in, 60*60*24) # Per-day checkin checkin_thread.start() my_logger = logging.getLogger('FlaskLogger') my_logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler(filename='/var/log/flask', maxBytes=2000000, backupCount=2) my_logger.addHandler(handler) app.logger.addHandler(my_logger) app.register_error_handler(LoginError, handle_login_exception) app.secret_key = 'NoZlPx7t15foPfKpivbVrTrTy2bTQ99chJoz3LFmf5BFsh3Nz4ud0mMpGjtB4bhP' app.permanent_session_lifetime = timedelta(days=90) try: app.run(host='0.0.0.0', port=80) except ServiceExit: # Stop background thread print("Killing {}".format(btc_thread1.pid)) os.kill(btc_thread1.pid, signal.SIGKILL) print("Killing {}".format(btc_thread2.pid)) os.kill(btc_thread2.pid, signal.SIGKILL) print("Killing {}".format(electrs_info_thread.pid)) os.kill(electrs_info_thread.pid, signal.SIGKILL) print("Killing {}".format(lnd_thread.pid))
import logging from flask import Flask from vnstatweb import settings app = Flask(__name__) app.debug = settings.debug app.logger.setLevel(logging.DEBUG) app.register_error_handler(500, lambda e: 'bad request!')
methods=("GET", )) # 10. Guides app.add_url_rule("/userguide", "guides_user_guide", guides.user_guide, methods=("GET", )) app.add_url_rule("/bbcodeguide", "guides_bbcode_guide", guides.bbcode_guide, methods=("GET", )) # 11. Error handlers app.register_error_handler(403, errors.error_403) app.register_error_handler(404, errors.error_404) app.register_error_handler(500, errors.error_500) if not app.debug and not app.testing: app.register_error_handler(Exception, errors.error_500) # 12. Log cabin app.add_url_rule("/api/users.json", "api_users", views.api_users, methods=("GET", )) # XXX dear f*****g lord we need traversal
class Server: """ REST API server """ auth = HTTPBasicAuth() def __init__(self): self.process = None self.app = Flask(__name__) self.app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 self.api = Api(self.app) # initialize SSL context self.context = ssl.SSLContext(ssl.PROTOCOL_TLS) # allow TLS 1.2 and later self.context.options |= ssl.OP_NO_SSLv2 self.context.options |= ssl.OP_NO_SSLv3 self.context.options |= ssl.OP_NO_TLSv1 self.context.options |= ssl.OP_NO_TLSv1_1 self.api.add_resource(Apps, '/apps') self.api.add_resource(App, '/apps/<app_id>') self.api.add_resource(Pools, '/pools') self.api.add_resource(Pool, '/pools/<pool_id>') self.api.add_resource(Stats, '/stats') self.api.add_resource(Caps, '/caps') if caps.sstbf_enabled(): self.api.add_resource(Sstbf, '/caps/sstbf') self.api.add_resource(Reset, '/reset') self.app.register_error_handler(RestError, Server.error_handler) def start(self, host, port, debug=False): """ Start REST server Parameters: host: address to bind to port: port to bind to debug(bool): Debug flag Returns: 0 on success """ try: # check for file existence and type with open(TLS_CERT_FILE, opener=common.check_link): pass with open(TLS_KEY_FILE, opener=common.check_link): pass self.context.load_cert_chain(TLS_CERT_FILE, TLS_KEY_FILE) except (FileNotFoundError, PermissionError) as ex: log.error("SSL cert or key file, {}".format(str(ex))) return -1 self.process = multiprocessing.Process(target=self.app.run, kwargs={'host': host, 'port': port, 'ssl_context': self.context, 'debug': debug, 'use_reloader': False, 'processes': 1}) self.process.start() return 0 def terminate(self): """ Terminates server """ os.kill(self.process.pid, signal.SIGINT) sleep(1) if self.process.is_alive(): self.process.terminate() self.process.join() @staticmethod def error_handler(error): """ Error handler Parameters: error: error """ common.STATS_STORE.general_stats_inc_num_err() response = {'message': error.message} return json.dumps(response), error.code @staticmethod @auth.verify_password def verify(username, password): """ Authenticate user, HTTP Basic Auth Parameters: username: Username password: Password Returns: Authentication result (bool) """ if not (username and password): common.STATS_STORE.general_stats_inc_num_invalid_access() return False if 'auth' in common.CONFIG_STORE.get_config(): if username == common.CONFIG_STORE.get_config()['auth']['username'] and \ password == common.CONFIG_STORE.get_config()['auth']['password']: return True common.STATS_STORE.general_stats_inc_num_invalid_access() return False
def create_app(test_config=None): # Create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( DEBUG=False, SECRET_KEY=os.environ.get("SECRET_KEY", "ppBcUQ5AL7gEmvb0blMDyEOpiBEQUupGmk_a3DMaF34"), TOPIC_STORE_USER=database_username, TOPIC_STORE_PASSWORD=database_password, TOPIC_STORE_DBNAME=database_name, TOPIC_STORE_HOST=database_host, TOPIC_STORE_PORT=database_port, SECURITY_PASSWORD_SALT=os.environ.get("SECURITY_PASSWORD_SALT", "139687009245803364536588051620840970665"), SECURITY_REGISTERABLE=True, SECURITY_RECOVERABLE=True, SECURITY_EMAIL_SENDER=email_sender, SECURITY_URL_PREFIX="/auth", SECURITY_POST_LOGIN_VIEW="/maps/", SECURITY_POST_REGISTER_VIEW="/maps/", MAIL_SERVER=email_server, MAIL_PORT=587, MAIL_USE_SSL=False, MAIL_USERNAME=email_username, MAIL_PASSWORD=email_password, MAX_CONTENT_LENGTH=4 * 1024 * 1024, # 4 megabytes (temporarily - will be 2) ) mail = Mail(app) csrf = SeaSurf(app) if test_config is None: # Load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # Load the test config if passed in app.config.from_mapping(test_config) # Ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route("/") def home(): maps = get_topic_store().get_promoted_topic_maps() # Reset breadcrumbs and (current) scope session["breadcrumbs"] = [] session["current_scope"] = UNIVERSAL_SCOPE session["scope_filter"] = 1 return render_template("index.html", maps=maps) @app.route("/health") def hello(): return "Healthy!" # HTTP error handlers def forbidden(e): return render_template("403.html"), 403 app.register_error_handler(403, forbidden) def page_not_found(e): return render_template("404.html"), 404 app.register_error_handler(404, page_not_found) def internal_server_error(e): return render_template("500.html"), 500 app.register_error_handler(500, internal_server_error) def request_entity_too_large(e): return render_template("413.html"), 413 app.register_error_handler(413, request_entity_too_large) # Setup Flask-Security user_datastore = SQLAlchemySessionUserDatastore(user_store.db_session, user_models.User, user_models.Role) security = Security(app, user_datastore) @user_registered.connect_via(app) def user_registered_handler(app, user, confirm_token, form_data, **extra_args): default_role = user_datastore.find_role("user") user_datastore.add_role_to_user(user, default_role) user_store.db_session.commit() @user_authenticated.connect_via(app) def user_authenticated_handler(app, user, authn_via, **extra_args): app.logger.info(f"User logged in successfully: [{user.email}], authentication method: [{authn_via}]") @app.before_first_request def create_user(): user_store.init_db() # Create roles user_datastore.find_or_create_role(name="admin", description="Administrator") user_datastore.find_or_create_role(name="user", description="End user") # Create users if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user(email="*****@*****.**", password=hash_password("Passw0rd1")) if not user_datastore.get_user("*****@*****.**"): user_datastore.create_user(email="*****@*****.**", password=hash_password("Passw0rd1")) user_store.db_session.commit() # Assign roles user_datastore.add_role_to_user("*****@*****.**", "user") user_datastore.add_role_to_user("*****@*****.**", "admin") user_store.db_session.commit() @app.teardown_request def checkin_db(exc): user_store.db_session.remove() # Register custom filters filters.register_filters(app) # Register Blueprints from contextualise import api app.register_blueprint(api.bp) csrf.exempt(api.create_topic) csrf.exempt(api.create_association) from contextualise import map app.register_blueprint(map.bp) from contextualise import topic app.register_blueprint(topic.bp) from contextualise import image app.register_blueprint(image.bp) from contextualise import file app.register_blueprint(file.bp) from contextualise import link app.register_blueprint(link.bp) from contextualise import video app.register_blueprint(video.bp) from contextualise import association app.register_blueprint(association.bp) from contextualise import note app.register_blueprint(note.bp) from contextualise import three_d app.register_blueprint(three_d.bp) from contextualise import attribute app.register_blueprint(attribute.bp) from contextualise import visualisation app.register_blueprint(visualisation.bp) from contextualise import tag app.register_blueprint(tag.bp) # Add topic store # from contextualise import topic_store # topic_store.init_app(app) # Set up logging if not app.debug: if not os.path.exists("logs"): os.mkdir("logs") file_handler = RotatingFileHandler("logs/contextualise.log", maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]") ) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info("Contextualise startup") return app
'db': constants.DB_NAME, 'connect': False, 'username': constants.DB_USER, 'password': constants.DB_PASSWORD, 'authentication_source': 'admin' } app.config['SWAGGER'] = { 'title': 'AHM API', 'uiversion': 3 } CORS(app, resources={r'/*': {'origins': '*'}}) api = Api(app, catch_all_404s=True) db = MongoEngine(app) swagger = Swagger(app) api.add_resource(MeasurementDetail, '/v1/measurements/<string:id>') api.add_resource(MeasurementList, '/v1/measurements') api.add_resource(ReportDetail, '/v1/report/<string:period>') app.register_error_handler(ValidationError, errors.handle_db_request_exception) app.register_error_handler(NotUniqueError, errors.handle_db_request_exception) app.register_error_handler(Exception, errors.handle_general_exception) if __name__ == '__main__': app.run(host=constants.API_HOST)
def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( # a default secret that should be overridden by instance config SECRET_KEY="dev", # store the database in the instance folder DATABASE=os.path.join(app.instance_path, "encryptor.sqlite"), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # ROUTES @app.route("/api/ceasar/encrypt/<text>") def ceasar_encrypt(text): offset = request.args.get("offset", Ceasar.DEFAULT_OFFSET) return jsonify({ "status": 200, "content": Ceasar.encrypt(text, offset) }) @app.route("/api/ceasar/decrypt/<text>") def ceasar_decrypt(text): offset = request.args.get("offset", Ceasar.DEFAULT_OFFSET) return jsonify({ "status": 200, "content": Ceasar.decrypt(text, offset) }) @app.route("/api/vigenere/encrypt/<text>") def vigenere_encrypt(text): tabula_recta = request.args.get("tabula_recta", Vigenere.ALPHABET) key = request.args.get("key", Vigenere.KEY) return jsonify({ "status": 200, "content": Vigenere.encrypt(text, key, tabula_recta) }) @app.route("/api/vigenere/decrypt/<text>") def vigenere_decrypt(text): tabula_recta = request.args.get("tabula_recta", Vigenere.ALPHABET) key = request.args.get("key", Vigenere.KEY) return jsonify({ "status": 200, "content": Vigenere.decrypt(text, key, tabula_recta) }) @app.route("/api/railfence/encrypt/<text>") def railfence_encrypt(text): rail_height = request.args.get("rail_height", RailFence.DEFAULT_RAILS) return jsonify({ "status": 200, "content": RailFence.encrypt(text, rail_height) }) @app.route("/api/railfence/decrypt/<text>") def railfence_decrypt(text): rail_height = request.args.get("rail_height", RailFence.DEFAULT_RAILS) return jsonify({ "status": 200, "content": RailFence.decrypt(text, rail_height) }) @app.route("/api/blowfish/encrypt/<text>") def blowfish_encrypt(text): mode = request.args.get("mode", Blowfish.DEFAULT_MODE) return jsonify({ "status": 200, "content": Blowfish.encrypt(text, mode) }) @app.route("/api/blowfish/decrypt/<text>") def blowfish_decrypt(text): mode = request.args.get("mode", Blowfish.DEFAULT_MODE) return jsonify({ "status": 200, "content": Blowfish.decrypt(text, mode) }) @app.route("/api/rsa/encrypt/<text>") def rsa_encrypt(text): n = request.args.get("n", Rsa.DEFAULT_N) e = request.args.get("e", Rsa.DEFAULT_E) return jsonify({"status": 200, "content": Rsa.encrypt(text, n, e)}) @app.route("/api/rsa/decrypt/<text>") def rsa_decrypt(text): p = request.args.get("p", Rsa.DEFAULT_P) q = request.args.get("q", Rsa.DEFAULT_Q) e = request.args.get("e", Rsa.DEFAULT_E) return jsonify({"status": 200, "content": Rsa.decrypt(text, p, q, e)}) @app.route("/api/error") def trigger_error(): return jsonify({"status": 200, "content": "1 / 0 = {}".format(1 / 0)}) # ERROR HANDLERS def handle_errors(e): return jsonify({ "status": e.code, "error": e.name, "content": e.description }) app.register_error_handler(400, handle_errors) app.register_error_handler(500, handle_errors) return app
def create_app(test_config=None): app = Flask(__name__) # register api blueprint and error handlers: app.register_blueprint(casting_blueprint, url_prefix='/api') app.register_error_handler(422, unprocessable) app.register_error_handler(400, bad_request) app.register_error_handler(405, method_not_allowed) app.register_error_handler(500, internal_sever_error) app.register_error_handler(404, not_found) app.register_error_handler(401, permission_error) setup_db(app) migrate = Migrate(app, db) cors = CORS(app, resources={r"/api*": {"origins": "*"}}) @app.route('/') def get_greeting(): environment = os.environ['ENV'] message = "Welcome to" seed_url = os.environ['SEED_PATH'] seed_url_html = f'<a href="{seed_url}">clicking here</a>' if environment == 'dev': message = message + "the local development environment, " + "you can seed and re-seed the database, by " + seed_url_html elif environment == 'prod': message = message + "the production app, " + "you can seed and re-seed the database, by " + seed_url_html return message return app
results = db_prueba_manuel.get_interna() return jsonify(results) @server.route("/api/movilidad", methods=['GET', 'POST']) def api_movilidad(): if request.method == 'POST': data = request.get_json() return "201 Created" if request.method == 'GET': return "204 No Content" # Cargar los dashboards desarrollados en dash calidadaire = aqi_app.aqi_dash(server, '/calidadaire/') ruido = ruido_app.ruido_dash(server, '/ruido/') thp = thp_app.thp_dash(server, '/thp/') #Manejo de paginas no encontradas @server.errorhandler(HTTPException) def page_not_found(e): return render_template("default.html") #parte principal (main) if __name__ == "__main__": server.register_error_handler(404, page_not_found) #server.secret_key = os.urandom(12) server.run()
import time_series_analysis_controller import exception_handler app = Flask(__name__) app.add_url_rule("/time-series-analysis/forecast", methods=['POST'], view_func=time_series_analysis_controller.forecast) app.add_url_rule( "/time-series-analysis/forecast-accuracy", methods=['POST'], view_func=time_series_analysis_controller.compute_accuracy_of_forecast) app.add_url_rule("/time-series-analysis/predict", methods=['POST'], view_func=time_series_analysis_controller.predict) app.register_error_handler( EngineComputationException, exception_handler.handle_engine_computation_exception) def on_shutdown(): get_logger().info("Engine will shutdown") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--port", dest="port", help="port to run python engine", required=True) parser.add_argument("--logs-path", dest="logs_path",
def show_subpath(subpath): if subpath == 'not_found': abort(404) return 'Subpath is: %s.' % subpath @app.errorhandler(NotFound) def page_not_found(error): return "<h1>页面不存在</h1>", 404 def handle_bad_request(e): return "Bad Request", 400 app.register_error_handler(400, handle_bad_request) @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['file'] f.save('./staticfile/' + secure_filename(f.filename)) return render_template('upload.html') with app.test_request_context(): print(url_for('index')) print(url_for('login', next='/')) print(url_for('show_user', name='Dawn'))
class Server: """ REST API server """ auth = HTTPBasicAuth() def __init__(self): self.process = None self.app = Flask(__name__) self.api = Api(self.app) # initialize SSL context self.context = ('appqos.crt', 'appqos.key') self.api.add_resource(Apps, '/apps') self.api.add_resource(App, '/apps/<app_id>') self.api.add_resource(Pools, '/pools') self.api.add_resource(Pool, '/pools/<pool_id>') self.api.add_resource(Stats, '/stats') self.api.add_resource(Caps, '/caps') self.api.add_resource(Reset, '/reset') self.app.register_error_handler(RestError, Server.error_handler) def start(self, host, port, debug=False): """ Start REST server Parameters: host: address to bind to port: port to bind to debug(bool): Debug flag Returns: 0 on success """ for ssl_ctx_file in self.context: if not os.path.isfile(ssl_ctx_file): log.error("SSL cert or key file missing.") return -1 self.process = multiprocessing.Process(target=self.app.run, kwargs={'host': host, 'port': port, 'ssl_context': self.context, 'debug': debug, 'use_reloader': False, 'processes': 1}) self.process.start() return 0 def terminate(self): """ Terminates server """ os.kill(self.process.pid, signal.SIGINT) sleep(1) if self.process.is_alive(): self.process.terminate() self.process.join() @staticmethod def error_handler(error): """ Error handler Parameters: error: error """ response = {"message": error.message} return json.dumps(response), error.code @staticmethod @auth.verify_password def verify(username, password): """ Authenticate user, HTTP Basic Auth Parameters: username: Username password: Password Returns: Authentication result (bool) """ if not (username and password): return False if 'auth' in common.CONFIG_STORE.get_config(): if username == common.CONFIG_STORE.get_config()['auth']['username'] and \ password == common.CONFIG_STORE.get_config()['auth']['password']: return True return False
'''Default HTTP handler''' response = err.get_response() # replace the body with JSON response.data = dumps({ "code": err.code, "name": err.name, "description": err.description, }) response.content_type = "application/json" return response @APP.before_request def extract_auth(): if request.endpoint not in ["user.create_user", "user.login", "base.base"]: g.headers = { "Authorization": request.headers.get("Authorization"), "Key": request.headers.get("Key") } APP.config['TRAP_HTTP_EXCEPTIONS'] = True APP.register_error_handler(HTTPException, default_handler) APP.register_blueprint(DOWNLOAD) APP.register_blueprint(UPLOAD) APP.register_blueprint(BASE) APP.register_blueprint(USER, url_prefix='/user') if __name__ == "__main__": APP.run(port=(int(sys.argv[1]) if len(sys.argv) == 2 else 8081), ssl_context='adhoc')
) def errorpage(e): if e.code in (404,): flash(gettext(u"Seite nicht gefunden!"), "warning") elif e.code in (401, 403): flash(gettext( u"Sie haben nicht die notwendigen Rechte um die Seite zu sehen!"), "warning") else: flash(gettext(u"Es ist ein Fehler aufgetreten!"), "error") return redirect(url_for("index")) app.register_error_handler(401, errorpage) app.register_error_handler(403, errorpage) app.register_error_handler(404, errorpage) @app.errorhandler(OperationalError) def exceptionhandler_sql(ex): """Handles global MySQL errors (server down). """ flash(u"Connection to SQL server could not be established!", "error") # todo check if infinite redirection might still occur # Proviously, requesting `/` w/o having a connection to the mysql database # would result in an infinite loop of redirects to `/` since # OperationalError is being handled globally. # In the latter case, the cause was the request of the traffic chart data. # A quick fix was catching it and returning an error status.
class LocalApigwService(BaseLocalService): _DEFAULT_PORT = 3000 _DEFAULT_HOST = '127.0.0.1' def __init__(self, routing_list, lambda_runner, static_dir=None, port=None, host=None, stderr=None): """ Creates an ApiGatewayService Parameters ---------- routing_list list(ApiGatewayCallModel) A list of the Model that represent the service paths to create. lambda_runner samcli.commands.local.lib.local_lambda.LocalLambdaRunner The Lambda runner class capable of invoking the function static_dir str Directory from which to serve static files port int Optional. port for the service to start listening on Defaults to 3000 host str Optional. host to start the service on Defaults to '127.0.0.1 stderr samcli.lib.utils.stream_writer.StreamWriter Optional stream writer where the stderr from Docker container should be written to """ super(LocalApigwService, self).__init__(lambda_runner.is_debugging(), port=port, host=host) self.routing_list = routing_list self.lambda_runner = lambda_runner self.static_dir = static_dir self._dict_of_routes = {} self.stderr = stderr def create(self): """ Creates a Flask Application that can be started. """ self._app = Flask( __name__, static_url_path="", # Mount static files at root '/' static_folder=self. static_dir # Serve static files from this directory ) for api_gateway_route in self.routing_list: path = PathConverter.convert_path_to_flask(api_gateway_route.path) for route_key in self._generate_route_keys( api_gateway_route.methods, path): self._dict_of_routes[route_key] = api_gateway_route self._app.add_url_rule(path, endpoint=path, view_func=self._request_handler, methods=api_gateway_route.methods, provide_automatic_options=False) self._construct_error_handling() def _generate_route_keys(self, methods, path): """ Generates the key to the _dict_of_routes based on the list of methods and path supplied :param list(str) methods: List of HTTP Methods :param str path: Path off the base url :return: str of Path:Method """ for method in methods: yield self._route_key(method, path) @staticmethod def _route_key(method, path): return '{}:{}'.format(path, method) def _construct_error_handling(self): """ Updates the Flask app with Error Handlers for different Error Codes """ # Both path and method not present self._app.register_error_handler(404, ServiceErrorResponses.route_not_found) # Path is present, but method not allowed self._app.register_error_handler(405, ServiceErrorResponses.route_not_found) # Something went wrong self._app.register_error_handler( 500, ServiceErrorResponses.lambda_failure_response) def _request_handler(self, **kwargs): """ We handle all requests to the host:port. The general flow of handling a request is as follows * Fetch request from the Flask Global state. This is where Flask places the request and is per thread so multiple requests are still handled correctly * Find the Lambda function to invoke by doing a look up based on the request.endpoint and method * If we don't find the function, we will throw a 502 (just like the 404 and 405 responses we get from Flask. * Since we found a Lambda function to invoke, we construct the Lambda Event from the request * Then Invoke the Lambda function (docker container) * We then transform the response or errors we get from the Invoke and return the data back to the caller Parameters ---------- kwargs dict Keyword Args that are passed to the function from Flask. This happens when we have path parameters Returns ------- Response object """ route = self._get_current_route(request) try: event = self._construct_event(request, self.port, route.binary_types) except UnicodeDecodeError: return ServiceErrorResponses.lambda_failure_response() stdout_stream = io.BytesIO() stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging) try: self.lambda_runner.invoke(route.function_name, event, stdout=stdout_stream_writer, stderr=self.stderr) except FunctionNotFound: return ServiceErrorResponses.lambda_not_found_response() lambda_response, lambda_logs, _ = LambdaOutputParser.get_lambda_output( stdout_stream) if self.stderr and lambda_logs: # Write the logs to stderr if available. self.stderr.write(lambda_logs) try: (status_code, headers, body) = self._parse_lambda_output(lambda_response, route.binary_types, request) except (KeyError, TypeError, ValueError): LOG.error( "Function returned an invalid response (must include one of: body, headers or " "statusCode in the response object). Response received: %s", lambda_response) return ServiceErrorResponses.lambda_failure_response() return self.service_response(body, headers, status_code) def _get_current_route(self, flask_request): """ Get the route (Route) based on the current request :param request flask_request: Flask Request :return: Route matching the endpoint and method of the request """ endpoint = flask_request.endpoint method = flask_request.method route_key = self._route_key(method, endpoint) route = self._dict_of_routes.get(route_key, None) if not route: LOG.debug( "Lambda function for the route not found. This should not happen because Flask is " "already configured to serve all path/methods given to the service. " "Path=%s Method=%s RouteKey=%s", endpoint, method, route_key) raise KeyError("Lambda function for the route not found") return route # Consider moving this out to its own class. Logic is started to get dense and looks messy @jfuss @staticmethod def _parse_lambda_output(lambda_output, binary_types, flask_request): """ Parses the output from the Lambda Container :param str lambda_output: Output from Lambda Invoke :return: Tuple(int, dict, str, bool) """ json_output = json.loads(lambda_output) if not isinstance(json_output, dict): raise TypeError("Lambda returned %{s} instead of dict", type(json_output)) status_code = json_output.get("statusCode") or 200 headers = CaseInsensitiveDict(json_output.get("headers") or {}) body = json_output.get("body") or "no data" is_base_64_encoded = json_output.get("isBase64Encoded") or False try: status_code = int(status_code) if status_code <= 0: raise ValueError except ValueError: message = "statusCode must be a positive int" LOG.error(message) raise TypeError(message) # If the customer doesn't define Content-Type default to application/json if "Content-Type" not in headers: LOG.info( "No Content-Type given. Defaulting to 'application/json'.") headers["Content-Type"] = "application/json" if LocalApigwService._should_base64_decode_body( binary_types, flask_request, headers, is_base_64_encoded): body = base64.b64decode(body) return status_code, headers, body @staticmethod def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded): """ Whether or not the body should be decoded from Base64 to Binary Parameters ---------- binary_types list(basestring) Corresponds to self.binary_types (aka. what is parsed from SAM Template flask_request flask.request Flask request lamba_response_headers dict Headers Lambda returns is_base_64_encoded bool True if the body is Base64 encoded Returns ------- True if the body from the request should be converted to binary, otherwise false """ best_match_mimetype = flask_request.accept_mimetypes.best_match( [lamba_response_headers["Content-Type"]]) is_best_match_in_binary_types = best_match_mimetype in binary_types or '*/*' in binary_types return best_match_mimetype and is_best_match_in_binary_types and is_base_64_encoded @staticmethod def _construct_event(flask_request, port, binary_types): """ Helper method that constructs the Event to be passed to Lambda :param request flask_request: Flask Request :return: String representing the event """ identity = ContextIdentity(source_ip=flask_request.remote_addr) endpoint = PathConverter.convert_path_to_api_gateway( flask_request.endpoint) method = flask_request.method request_data = flask_request.get_data() request_mimetype = flask_request.mimetype is_base_64 = LocalApigwService._should_base64_encode( binary_types, request_mimetype) if is_base_64: LOG.debug( "Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda." ) request_data = base64.b64encode(request_data) if request_data: # Flask does not parse/decode the request data. We should do it ourselves request_data = request_data.decode('utf-8') context = RequestContext(resource_path=endpoint, http_method=method, stage="prod", identity=identity, path=endpoint) event_headers = dict(flask_request.headers) event_headers["X-Forwarded-Proto"] = flask_request.scheme event_headers["X-Forwarded-Port"] = str(port) # APIGW does not support duplicate query parameters. Flask gives query params as a list so # we need to convert only grab the first item unless many were given, were we grab the last to be consistent # with APIGW query_string_dict = LocalApigwService._query_string_params( flask_request) event = ApiGatewayLambdaEvent(http_method=method, body=request_data, resource=endpoint, request_context=context, query_string_params=query_string_dict, headers=event_headers, path_parameters=flask_request.view_args, path=flask_request.path, is_base_64_encoded=is_base_64) event_str = json.dumps(event.to_dict()) LOG.debug( "Constructed String representation of Event to invoke Lambda. Event: %s", event_str) return event_str @staticmethod def _query_string_params(flask_request): """ Constructs an APIGW equivalent query string dictionary Parameters ---------- flask_request request Request from Flask Returns dict (str: str) ------- Empty dict if no query params where in the request otherwise returns a dictionary of key to value """ query_string_dict = {} # Flask returns an ImmutableMultiDict so convert to a dictionary that becomes # a dict(str: list) then iterate over for query_string_key, query_string_list in flask_request.args.lists(): query_string_value_length = len(query_string_list) # if the list is empty, default to empty string if not query_string_value_length: query_string_dict[query_string_key] = "" else: # APIGW doesn't handle duplicate query string keys, picking the last one in the list query_string_dict[query_string_key] = query_string_list[-1] return query_string_dict @staticmethod def _should_base64_encode(binary_types, request_mimetype): """ Whether or not to encode the data from the request to Base64 Parameters ---------- binary_types list(basestring) Corresponds to self.binary_types (aka. what is parsed from SAM Template request_mimetype str Mimetype for the request Returns ------- True if the data should be encoded to Base64 otherwise False """ return request_mimetype in binary_types or "*/*" in binary_types
closest_margin = _amount_to_margin(band, closest_amount) return band._apply_margin(target_price, closest_margin) def _amount_to_margin(band, amount): # returns the margin that matches to the corrosponding amount. # min_amount -> min_margin etc... if amount == band.min_amount: return band.min_margin elif amount == band.avg_amount: return band.avg_margin else: return band.max_margin def _find_closest(val1, val2, target): return val2 if target - val1 >= val2 - target else val1 if __name__ == '__main__': airswap_app = AirswapMarketMakerKeeper(sys.argv[1:]) app.add_url_rule('/getOrder', view_func=airswap_app.r_get_order, methods=["POST"]) app.add_url_rule('/getQuote', view_func=airswap_app.r_get_quote, methods=["POST"]) app.register_error_handler(CustomException, airswap_app._error_handler) airswap_app.main()
def create_app(): app = Flask(__name__) app.register_error_handler(404, page_not_found) app.config.from_object(config_by_name[FLASK_LEVEL]) os.environ["FLASK_ENV"] = config_by_name[FLASK_LEVEL].FLASK_ENV return app
params = request.form interest = params['interest'] objs = storage.query("Borrower") borrower_list = [] for obj in objs: if obj.__dict__['interest'] >= int(interest): borrower_list.append(obj) print(borrower_list) return render_template('borrow.html', objs=borrower_list) @app.route('/lend', methods=['GET', 'POST']) def lend(): lenders_list = [] if request.method == 'POST': params = request.form interest = params['interest'] objs = storage.query("Lender") lenders_list = [] for obj in objs: if obj.__dict__['interest'] <= int(interest): lenders_list.append(obj) print(lenders_list) return render_template('lend.html', objs=lenders_list) if __name__ == "__main__": app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True app.register_error_handler(404, page_not_found) app.run(host=host, port=5000, debug=True)
def instantiate_app_with_views(context, app_path_prefix): app = Flask( "dagster-ui", static_url_path=app_path_prefix, static_folder=os.path.join(os.path.dirname(__file__), "./webapp/build"), ) schema = create_schema() subscription_server = DagsterSubscriptionServer(schema=schema) # Websocket routes sockets = Sockets(app) sockets.add_url_rule( "{}/graphql".format(app_path_prefix), "graphql", dagster_graphql_subscription_view(subscription_server, context), ) # HTTP routes bp = Blueprint("routes", __name__, url_prefix=app_path_prefix) bp.add_url_rule( "/graphiql", "graphiql", lambda: redirect("{}/graphql".format(app_path_prefix), 301) ) bp.add_url_rule( "/graphql", "graphql", DagsterGraphQLView.as_view( "graphql", schema=schema, graphiql=True, graphiql_template=PLAYGROUND_TEMPLATE.replace("APP_PATH_PREFIX", app_path_prefix), executor=Executor(), context=context, ), ) bp.add_url_rule( # should match the `build_local_download_url` "/download/<string:run_id>/<string:step_key>/<string:file_type>", "download_view", download_log_view(context), ) bp.add_url_rule( "/download_debug/<string:run_id>", "download_dump_view", download_dump_view(context), ) # these routes are specifically for the Dagit UI and are not part of the graphql # API that we want other people to consume, so they're separate for now. # Also grabbing the magic global request args dict so that notebook_view is testable bp.add_url_rule("/dagit/notebook", "notebook", lambda: notebook_view(request.args)) bp.add_url_rule("/dagit_info", "sanity_view", info_view) index_path = os.path.join(os.path.dirname(__file__), "./webapp/build/index.html") def index_view(_path): try: with open(index_path) as f: return ( f.read() .replace('href="/', 'href="{}/'.format(app_path_prefix)) .replace('src="/', 'src="{}/'.format(app_path_prefix)) .replace( '<meta name="dagit-path-prefix"', '<meta name="dagit-path-prefix" content="{}"'.format(app_path_prefix), ) ) except FileNotFoundError: raise Exception( """Can't find webapp files. Probably webapp isn't built. If you are using dagit, then probably it's a corrupted installation or a bug. However, if you are developing dagit locally, your problem can be fixed as follows: cd ./python_modules/ make rebuild_dagit""" ) app.app_protocol = lambda environ_path_info: "graphql-ws" app.register_blueprint(bp) app.register_error_handler(404, index_view) # if the user asked for a path prefix, handle the naked domain just in case they are not # filtering inbound traffic elsewhere and redirect to the path prefix. if app_path_prefix: app.add_url_rule("/", "force-path-prefix", lambda: redirect(app_path_prefix, 301)) CORS(app) return app
response = err.get_response() print('response', err, err.get_response()) response.data = dumps({ "code": err.code, "name": "System Error", "message": err.get_description(), }) response.content_type = 'application/json' return response APP = Flask(__name__) CORS(APP) APP.config['TRAP_HTTP_EXCEPTIONS'] = True APP.register_error_handler(Exception, defaultHandler) def create_server_data_obj(): """ a function to create a server_data object for this active server Input: - None Output: - (obj) a server_data object either read from file or create as new """ if data_storage.does_file_exist(): print("Found local storage, loading the server state...") return data_storage.load_state()
class TwitchFollowServer(object): def __init__(self, logger, chatbot=None): self.app = Flask(__name__, static_url_path="") add_configuration(self) self.logger = logger self.chatbot = chatbot self.add_url_rules() self.server_thread = None self.dispatcher = None self.server = None def bad_request(self, error): return make_response(jsonify({'error': 'Bad request'}), 400) def unauthorized(self): return make_response(jsonify({'error': 'Unauthorized access'}), 401) def not_found(self, error): return make_response(jsonify({'error': 'Not found'}), 404) def internal_server_error(self, error): return make_response(jsonify({'error': 'Internal server error'}), 500) def add_url_rules(self): self.app.add_url_rule('/api/v1.0/new_follower', 'new_follower', self.new_follower, methods=['GET', 'POST']) self.app.add_url_rule('/auth/twitch/callback', 'oauth_handler', self.oauth_handler, methods=['GET', 'POST']) self.app.register_error_handler(400, self.bad_request) self.app.register_error_handler(404, self.not_found) self.app.register_error_handler(500, self.internal_server_error) def oauth_handler(self): self.logger.debug(f"Handling a request: {request}") result = make_response(jsonify({'success': 'OAuth response'}), 202) return result def new_follower(self): self.logger.debug(f"Handling a request: {request}") result = make_response(jsonify({'error': 'Bad request'}), 400) if request.method == 'GET': self.logger.debug("Twitch responded to our subscription request") if 'hub.challenge' in request.args: self.logger.debug("Sending the challenge response to Twitch") result = make_response(request.args['hub.challenge']) elif request.method == 'POST': self.logger.debug( "We received a follower notification from Twitch") if hasattr(request, 'data'): data = json.loads(request.data) data = data['data'][0] follow = f"{data['from_name']} is now following {data['to_name']}" self.logger.debug(follow) if self.chatbot is not None: self.chatbot.new_follower = follow result = make_response( jsonify({'success': 'Follower notification'}), 202) return result def server_function(self): self.dispatcher = wsgiserver.WSGIPathInfoDispatcher({'/': self.app}) self.server = wsgiserver.WSGIServer(self.dispatcher, host=self.host, port=self.port) try: self.server.start() except KeyboardInterrupt: self.logger("Stopping server due to keyboard interrupt") self.server.stop() def start(self): try: self.server_thread = threading.Thread(target=self.server_function) self.server_thread.daemon = True self.server_thread.start() except: self.logger.error(traceback.format_exc()) return False return True def stop(self): self.server.stop() self.server_thread.join()
def init_error_handlers(app: Flask): """Add custom errors handlers""" from airflow.www import views app.register_error_handler(500, views.show_traceback) app.register_error_handler(404, views.circles)
def create_app(test_config=None): """ The flask application factory. To run the app somewhere else you can: ``` from api import create_app app = create_app() if __main__ == "__name__": app.run() """ app = Flask(__name__) CORS(app) # add CORS # check environment variables to see which config to load env = os.environ.get("FLASK_ENV", "dev") # for configuration options, look at api/config.py if test_config: # purposely done so we can inject test configurations # this may be used as well if you'd like to pass # in a separate configuration although I would recommend # adding/changing it in api/config.py instead # ignore environment variable config if config was given app.config.from_mapping(**test_config) else: app.config.from_object( config[env]) # config dict is from api/config.py # logging formatter = RequestFormatter( "%(asctime)s %(remote_addr)s: requested %(url)s: %(levelname)s in [%(module)s: %(lineno)d]: %(message)s" ) if app.config.get("LOG_FILE"): fh = logging.FileHandler(app.config.get("LOG_FILE")) fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) app.logger.addHandler(fh) strm = logging.StreamHandler() strm.setLevel(logging.DEBUG) strm.setFormatter(formatter) app.logger.addHandler(strm) app.logger.setLevel(logging.DEBUG) root = logging.getLogger("core") root.addHandler(strm) # decide whether to create database if env != "prod": db_url = app.config["SQLALCHEMY_DATABASE_URI"] #if not database_exists(db_url): # create_database(db_url) # register sqlalchemy to this app from api.models import db db.init_app(app) # initialize Flask SQLALchemy with this flask app Migrate(app, db) # import and register blueprints from api.views import main # why blueprints http://flask.pocoo.org/docs/1.0/blueprints/ app.register_blueprint(main.main) # register error Handler app.register_error_handler(Exception, all_exception_handler) return app
else: check_symbols = True # To reduce computation issues on single-threaded server, institute a timeout # for requests. If it takes longer than this to process, return an error. # This cannot interrupt numpy's computation, so care must be taken in selecting # a value for MAX_REQUEST_COMPUTATION_TIME. try: with TimeoutProtection(MAX_REQUEST_COMPUTATION_TIME): response_dict = check(test_str, target_str, symbols, check_symbols, description) return jsonify(**response_dict) except TimeoutException, e: print "ERROR: %s - Request took too long to process, aborting!" % type(e).__name__ print "=" * 50 error_dict = dict(target=target_str, test=test_str, error="Request took too long to process!") return jsonify(**error_dict) @app.route("/", methods=["GET"]) def ping(): return jsonify(code=200) if __name__ == "__main__": # Make sure all outgoing error messages are in JSON format. # This will only work provided debug=False - otherwise the debugger hijacks them! for code in default_exceptions.iterkeys(): app.register_error_handler(code, make_json_error) # Then run the app app.run(port=5000, host="0.0.0.0", debug=False)
for pid in pid_list: os.kill(int(pid), signal.SIGKILL) t0 = time.time() template_dir = os.path.join(os.path.dirname(__file__), "templates") server = Flask(__name__, static_url_path="", template_folder=template_dir) cfg = Config( os.path.abspath( os.path.join(cmdline_options.hwr_directory, "mxcube-server-config.yml"))) server.config.from_object(cfg.FLASK) server.register_error_handler(Exception, exception_handler) _session = Session() _session.init_app(server) socketio = SocketIO(manage_session=False, cors_allowed_origins=cfg.FLASK.ALLOWED_CORS_ORIGINS) socketio.init_app(server) # the following test prevents Flask from initializing twice # (because of the Reloader) if not server.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true": logging.getLogger("MX3.HWR").info("Starting MXCuBE3...") atexit.register(kill_processes)
"""A generic error handler""" return render_template(template, message=message), code def not_found(message=None): """A generic 404 handler""" message = message or 'Page not found.' return error(404, message, 'errors/404.html') def internal_server_error(message=None): """A generic 500 handler""" message = message or 'Something went wrong.' return error(500, message, 'errors/500.html') app.register_error_handler(404, not_found) app.register_error_handler(500, internal_server_error) @app.context_processor def catchy_thing(): return dict(catchy=random.choice([ 'is awesome!', 'is sweeter than honey!', 'makes my mouth water!', 'is the cat\'s pajamas!', ('is a very mysterious and powerful site and it\'s mystery is only ' 'exceeded by it\'s power.'), 'is a banana stand.', 'can do the kessel run in 11 parsecs.', ]))
class Server: """ REST API server """ auth = HTTPBasicAuth() def __init__(self): self.process = None self.app = Flask(__name__) self.api = Api(self.app) # initialize SSL context self.context = ('appqos.crt', 'appqos.key') self.api.add_resource(Apps, '/apps') self.api.add_resource(App, '/apps/<app_id>') self.api.add_resource(Pools, '/pools') self.api.add_resource(Pool, '/pools/<pool_id>') self.api.add_resource(Stats, '/stats') self.api.add_resource(Caps, '/caps') self.api.add_resource(Reset, '/reset') self.app.register_error_handler(RestError, Server.error_handler) def start(self, host, port, debug=False): """ Start REST server Parameters: host: address to bind to port: port to bind to debug(bool): Debug flag Returns: 0 on success """ for ssl_ctx_file in self.context: if not os.path.isfile(ssl_ctx_file): log.error("SSL cert or key file missing.") return -1 self.process = multiprocessing.Process(target=self.app.run, kwargs={ 'host': host, 'port': port, 'ssl_context': self.context, 'debug': debug, 'use_reloader': False, 'processes': 1 }) self.process.start() return 0 def terminate(self): """ Terminates server """ os.kill(self.process.pid, signal.SIGINT) sleep(1) if self.process.is_alive(): self.process.terminate() self.process.join() @staticmethod def error_handler(error): """ Error handler Parameters: error: error """ response = {"message": error.message} return json.dumps(response), error.code @staticmethod @auth.verify_password def verify(username, password): """ Authenticate user, HTTP Basic Auth Parameters: username: Username password: Password Returns: Authentication result (bool) """ if not (username and password): return False if 'auth' in common.CONFIG_STORE.get_config(): if username == common.CONFIG_STORE.get_config()['auth']['username'] and \ password == common.CONFIG_STORE.get_config()['auth']['password']: return True return False
from flask import Flask, Blueprint from flask.ext.sqlalchemy import SQLAlchemy import os import os.path as op # Initialize app app = Flask(__name__) app.debug = True app.config.from_object('config') #os.environ['PYTHON_EGG_CACHE'] = '/tmp/tmp2' #db = SQLAlchemy(app) from werkzeug.exceptions import default_exceptions, HTTPException from app.views import error_handler for exception in default_exceptions: app.register_error_handler(exception, error_handler) from app.views import mod as mainModule app.register_blueprint(mainModule) # For full text search #import flask.ext.whooshalchemy as whooshalchemy #from models import File, Gene, Condition #whooshalchemy.whoosh_index(app, File) #whooshalchemy.whoosh_index(app, Gene) #whooshalchemy.whoosh_index(app, Condition)
class ApiServer(RPC): """ This class runs api server and provides rpc.rpc functionality to it This class starts a non-blocking thread the api server runs within """ def check_auth(self, username, password): return (safe_str_cmp(username, self._config['api_server'].get('username')) and safe_str_cmp(password, self._config['api_server'].get('password'))) def __init__(self, freqtrade) -> None: """ Init the api server, and init the super class RPC :param freqtrade: Instance of a freqtrade bot :return: None """ super().__init__(freqtrade) self._config = freqtrade.config self.app = Flask(__name__) self._cors = CORS(self.app, resources={ r"/api/*": { "supports_credentials": True, "origins": self._config['api_server'].get( 'CORS_origins', []) } }) # Setup the Flask-JWT-Extended extension self.app.config['JWT_SECRET_KEY'] = self._config['api_server'].get( 'jwt_secret_key', 'super-secret') self.jwt = JWTManager(self.app) self.app.json_encoder = ArrowJSONEncoder self.app.teardown_appcontext(shutdown_session) # Register application handling self.register_rest_rpc_urls() if self._config.get('fiat_display_currency', None): self._fiat_converter = CryptoToFiatConverter() thread = threading.Thread(target=self.run, daemon=True) thread.start() def cleanup(self) -> None: logger.info("Stopping API Server") self.srv.shutdown() def run(self): """ Method that runs flask app in its own thread forever. Section to handle configuration and running of the Rest server also to check and warn if not bound to a loopback, warn on security risk. """ rest_ip = self._config['api_server']['listen_ip_address'] rest_port = self._config['api_server']['listen_port'] logger.info(f'Starting HTTP Server at {rest_ip}:{rest_port}') if not IPv4Address(rest_ip).is_loopback: logger.warning( "SECURITY WARNING - Local Rest Server listening to external connections" ) logger.warning( "SECURITY WARNING - This is insecure please set to your loopback," "e.g 127.0.0.1 in config.json") if not self._config['api_server'].get('password'): logger.warning( "SECURITY WARNING - No password for local REST Server defined. " "Please make sure that this is intentional!") # Run the Server logger.info('Starting Local Rest Server.') try: self.srv = make_server(rest_ip, rest_port, self.app) self.srv.serve_forever() except Exception: logger.exception("Api server failed to start.") logger.info('Local Rest Server started.') def send_msg(self, msg: Dict[str, str]) -> None: """ We don't push to endpoints at the moment. Take a look at webhooks for that functionality. """ pass def rest_dump(self, return_value): """ Helper function to jsonify object for a webserver """ return jsonify(return_value) def rest_error(self, error_msg): return jsonify({"error": error_msg}), 502 def register_rest_rpc_urls(self): """ Registers flask app URLs that are calls to functonality in rpc.rpc. First two arguments passed are /URL and 'Label' Label can be used as a shortcut when refactoring :return: """ self.app.register_error_handler(404, self.page_not_found) # Actions to control the bot self.app.add_url_rule(f'{BASE_URI}/token/login', 'login', view_func=self._token_login, methods=['POST']) self.app.add_url_rule(f'{BASE_URI}/token/refresh', 'token_refresh', view_func=self._token_refresh, methods=['POST']) self.app.add_url_rule(f'{BASE_URI}/start', 'start', view_func=self._start, methods=['POST']) self.app.add_url_rule(f'{BASE_URI}/stop', 'stop', view_func=self._stop, methods=['POST']) self.app.add_url_rule(f'{BASE_URI}/stopbuy', 'stopbuy', view_func=self._stopbuy, methods=['POST']) self.app.add_url_rule(f'{BASE_URI}/reload_config', 'reload_config', view_func=self._reload_config, methods=['POST']) # Info commands self.app.add_url_rule(f'{BASE_URI}/balance', 'balance', view_func=self._balance, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/count', 'count', view_func=self._count, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/daily', 'daily', view_func=self._daily, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/edge', 'edge', view_func=self._edge, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/logs', 'log', view_func=self._get_logs, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/profit', 'profit', view_func=self._profit, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/performance', 'performance', view_func=self._performance, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/status', 'status', view_func=self._status, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/version', 'version', view_func=self._version, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/show_config', 'show_config', view_func=self._show_config, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/ping', 'ping', view_func=self._ping, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/trades', 'trades', view_func=self._trades, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/trades/<int:tradeid>', 'trades_delete', view_func=self._trades_delete, methods=['DELETE']) # Combined actions and infos self.app.add_url_rule(f'{BASE_URI}/blacklist', 'blacklist', view_func=self._blacklist, methods=['GET', 'POST']) self.app.add_url_rule(f'{BASE_URI}/whitelist', 'whitelist', view_func=self._whitelist, methods=['GET']) self.app.add_url_rule(f'{BASE_URI}/forcebuy', 'forcebuy', view_func=self._forcebuy, methods=['POST']) self.app.add_url_rule(f'{BASE_URI}/forcesell', 'forcesell', view_func=self._forcesell, methods=['POST']) @require_login def page_not_found(self, error): """ Return "404 not found", 404. """ return self.rest_dump({ 'status': 'error', 'reason': f"There's no API call for {request.base_url}.", 'code': 404 }), 404 @require_login @rpc_catch_errors def _token_login(self): """ Handler for /token/login Returns a JWT token """ auth = request.authorization if auth and self.check_auth(auth.username, auth.password): keystuff = {'u': auth.username} ret = { 'access_token': create_access_token(identity=keystuff), 'refresh_token': create_refresh_token(identity=keystuff), } return self.rest_dump(ret) return jsonify({"error": "Unauthorized"}), 401 @jwt_refresh_token_required @rpc_catch_errors def _token_refresh(self): """ Handler for /token/refresh Returns a JWT token based on a JWT refresh token """ current_user = get_jwt_identity() new_token = create_access_token(identity=current_user, fresh=False) ret = {'access_token': new_token} return self.rest_dump(ret) @require_login @rpc_catch_errors def _start(self): """ Handler for /start. Starts TradeThread in bot if stopped. """ msg = self._rpc_start() return self.rest_dump(msg) @require_login @rpc_catch_errors def _stop(self): """ Handler for /stop. Stops TradeThread in bot if running """ msg = self._rpc_stop() return self.rest_dump(msg) @require_login @rpc_catch_errors def _stopbuy(self): """ Handler for /stopbuy. Sets max_open_trades to 0 and gracefully sells all open trades """ msg = self._rpc_stopbuy() return self.rest_dump(msg) @rpc_catch_errors def _ping(self): """ simple poing version """ return self.rest_dump({"status": "pong"}) @require_login @rpc_catch_errors def _version(self): """ Prints the bot's version """ return self.rest_dump({"version": __version__}) @require_login @rpc_catch_errors def _show_config(self): """ Prints the bot's version """ return self.rest_dump(self._rpc_show_config()) @require_login @rpc_catch_errors def _reload_config(self): """ Handler for /reload_config. Triggers a config file reload """ msg = self._rpc_reload_config() return self.rest_dump(msg) @require_login @rpc_catch_errors def _count(self): """ Handler for /count. Returns the number of trades running """ msg = self._rpc_count() return self.rest_dump(msg) @require_login @rpc_catch_errors def _daily(self): """ Returns the last X days trading stats summary. :return: stats """ timescale = request.args.get('timescale', 7) timescale = int(timescale) stats = self._rpc_daily_profit( timescale, self._config['stake_currency'], self._config.get('fiat_display_currency', '')) return self.rest_dump(stats) @require_login @rpc_catch_errors def _get_logs(self): """ Returns latest logs get: param: limit: Only get a certain number of records """ limit = int(request.args.get('limit', 0)) or None return self.rest_dump(self._rpc_get_logs(limit)) @require_login @rpc_catch_errors def _edge(self): """ Returns information related to Edge. :return: edge stats """ stats = self._rpc_edge() return self.rest_dump(stats) @require_login @rpc_catch_errors def _profit(self): """ Handler for /profit. Returns a cumulative profit statistics :return: stats """ stats = self._rpc_trade_statistics( self._config['stake_currency'], self._config.get('fiat_display_currency')) return self.rest_dump(stats) @require_login @rpc_catch_errors def _performance(self): """ Handler for /performance. Returns a cumulative performance statistics :return: stats """ stats = self._rpc_performance() return self.rest_dump(stats) @require_login @rpc_catch_errors def _status(self): """ Handler for /status. Returns the current status of the trades in json format """ try: results = self._rpc_trade_status() return self.rest_dump(results) except RPCException: return self.rest_dump([]) @require_login @rpc_catch_errors def _balance(self): """ Handler for /balance. Returns the current status of the trades in json format """ results = self._rpc_balance( self._config['stake_currency'], self._config.get('fiat_display_currency', '')) return self.rest_dump(results) @require_login @rpc_catch_errors def _trades(self): """ Handler for /trades. Returns the X last trades in json format """ limit = int(request.args.get('limit', 0)) results = self._rpc_trade_history(limit) return self.rest_dump(results) @require_login @rpc_catch_errors def _trades_delete(self, tradeid): """ Handler for DELETE /trades/<tradeid> endpoint. Removes the trade from the database (tries to cancel open orders first!) get: param: tradeid: Numeric trade-id assigned to the trade. """ result = self._rpc_delete(tradeid) return self.rest_dump(result) @require_login @rpc_catch_errors def _whitelist(self): """ Handler for /whitelist. """ results = self._rpc_whitelist() return self.rest_dump(results) @require_login @rpc_catch_errors def _blacklist(self): """ Handler for /blacklist. """ add = request.json.get("blacklist", None) if request.method == 'POST' else None results = self._rpc_blacklist(add) return self.rest_dump(results) @require_login @rpc_catch_errors def _forcebuy(self): """ Handler for /forcebuy. """ asset = request.json.get("pair") price = request.json.get("price", None) trade = self._rpc_forcebuy(asset, price) if trade: return self.rest_dump(trade.to_json()) else: return self.rest_dump({"status": f"Error buying pair {asset}."}) @require_login @rpc_catch_errors def _forcesell(self): """ Handler for /forcesell. """ tradeid = request.json.get("tradeid") results = self._rpc_forcesell(tradeid) return self.rest_dump(results)
from backend.views.users import user_blueprint from backend.views.products import product_blueprint from backend.views.prices import price_blueprint from backend.views.businesses import business_blueprint from backend.views.ocr import ocr_blueprint from backend.utils import json_error app = Flask(__name__, static_folder="frontend") app.config["PROPAGATE_EXCEPTIONS"] = False app.config["SECRET_KEY"] = '\x85\xe7\x98?L\xfaKa2\xbdQ\xef\xa5&\x03\x17\x9bj\x17 \xbc\xc8j\xbb' json_error_500 = partial(json_error, status_code=500) app.register_error_handler(500, json_error_500) # Configure logging log_format = logging.Formatter("%(asctime)s [%(name)s.%(funcName)s():%(lineno)d]\n\t%(levelname)8s: %(message)s\n") logger = logging.getLogger() stderr_handler = logging.StreamHandler() stderr_handler.setLevel(logging.DEBUG) stderr_handler.setFormatter(log_format) logger.addHandler(stderr_handler) file_handler = RotatingFileHandler("web.log", maxBytes=50000, backupCount=2) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(log_format)
def is_accessible(self): return current_user.is_authenticated def inaccessible_callback(self, name, **kwargs): if not self.is_accessible(): return redirect(url_for('admin.login_view', next=request.url)) def error_handler(error): return render_template("error.html", error=url_for('admin.index'), uuid=str(uuid4())) for cls in HTTPException.__subclasses__(): app.register_error_handler(cls, error_handler) #change admin wiht / -> CustomAdminIndexView url='/' admin = Admin(app, "@", index_view=CustomAdminIndexView(url='/'), base_template='base.html', template_mode='bootstrap3') admin.add_link( CustomMenuLink(name='', category='', url="https://github.com/qeeqbox/analyzer", icon_type='glyph', icon_value='glyphicon-star')) admin.add_link(
def instantiate_app_with_views( context: IWorkspaceProcessContext, schema, app_path_prefix, target_dir=os.path.dirname(__file__), graphql_middleware=None, include_notebook_route=False, ) -> Flask: app = Flask( "dagster-ui", static_url_path=app_path_prefix, static_folder=os.path.join(target_dir, "./webapp/build"), ) subscription_server = DagsterSubscriptionServer(schema=schema) # Websocket routes sockets = Sockets(app) sockets.add_url_rule( f"{app_path_prefix}/graphql", "graphql", dagster_graphql_subscription_view(subscription_server, context), ) # HTTP routes bp = Blueprint("routes", __name__, url_prefix=app_path_prefix) bp.add_url_rule("/graphiql", "graphiql", lambda: redirect(f"{app_path_prefix}/graphql", 301)) bp.add_url_rule( "/graphql", "graphql", DagsterGraphQLView.as_view( "graphql", schema=schema, graphiql=True, graphiql_template=PLAYGROUND_TEMPLATE, context=context, middleware=graphql_middleware, ), ) bp.add_url_rule( # should match the `build_local_download_url` "/download/<string:run_id>/<string:step_key>/<string:file_type>", "download_view", download_log_view(context), ) bp.add_url_rule( "/download_debug/<string:run_id>", "download_dump_view", download_dump_view(context), ) # these routes are specifically for the Dagit UI and are not part of the graphql # API that we want other people to consume, so they're separate for now. # Also grabbing the magic global request args dict so that notebook_view is testable if include_notebook_route: bp.add_url_rule("/dagit/notebook", "notebook", lambda: notebook_view(context, request.args)) bp.add_url_rule("/dagit_info", "sanity_view", info_view) index_path = os.path.join(target_dir, "./webapp/build/index.html") telemetry_enabled = is_dagit_telemetry_enabled(context.instance) def index_view(*args, **kwargs): # pylint: disable=unused-argument try: with open(index_path) as f: rendered_template = render_template_string(f.read()) return (rendered_template.replace( 'href="/', f'href="{app_path_prefix}/').replace( 'src="/', f'src="{app_path_prefix}/').replace( "__PATH_PREFIX__", app_path_prefix).replace( '"__TELEMETRY_ENABLED__"', str(telemetry_enabled).lower()).replace( "NONCE-PLACEHOLDER", uuid.uuid4().hex)) except FileNotFoundError: raise Exception( """Can't find webapp files. Probably webapp isn't built. If you are using dagit, then probably it's a corrupted installation or a bug. However, if you are developing dagit locally, your problem can be fixed as follows: cd ./python_modules/ make rebuild_dagit""") bp.add_url_rule("/", "index_view", index_view) bp.add_url_rule("/<path:path>", "catch_all", index_view) bp.context_processor(lambda: {"app_path_prefix": app_path_prefix}) app.app_protocol = lambda environ_path_info: "graphql-ws" app.before_request(initialize_counts) app.register_blueprint(bp) app.register_error_handler(404, index_view) app.after_request(return_counts) CORS(app) return app
import os from flask import Flask from flask import render_template from flask_restful import Api from shield_app.utils.route_utils import error_handler from shield_app.api.route import Certificate current_path = os.path.dirname(os.path.abspath(__file__)) ui_path = os.path.join(current_path, os.pardir, "shield_ui") app = Flask("shield", template_folder=ui_path, static_folder=ui_path + os.sep + 'static') app.register_error_handler(Exception, error_handler) api = Api(app) api.add_resource(Certificate, '/v1/certifiates', '/v1/certifiates/<certid>', '/v1/certificates/download/<type>/<resource_id>') @app.route('/') def homepage(): return render_template('index.html')
# Initializing Orator db = Orator(app) @app.errorhandler(Exception) def all_exception_handler(error): client.captureException() return jsonify({500: 'Oops. Something went wrong'}), 500 @app.errorhandler(404) def page_not_found(e): # note that we set the 404 status explicitly client.captureException() return jsonify({404: 'Page not found'}), 404 @app.errorhandler(404) def page_not_authorize(e): # note that we set the 404 status explicitly client.captureException() return jsonify({401: 'Not authorize'}), 401 if __name__ == "__main__": app.register_error_handler(Exception, all_exception_handler) app.register_error_handler(404, page_not_found) app.register_error_handler(401, page_not_authorize) app.run(host="0.0.0.0", port=5000, threaded=True)
class LocalLambdaInvokeService(BaseLocalService): def __init__(self, lambda_runner, port, host, stderr=None): """ Creates a Local Lambda Service that will only response to invoking a function Parameters ---------- lambda_runner samcli.commands.local.lib.local_lambda.LocalLambdaRunner The Lambda runner class capable of invoking the function port int Optional. port for the service to start listening on host str Optional. host to start the service on stderr io.BaseIO Optional stream where the stderr from Docker container should be written to """ super(LocalLambdaInvokeService, self).__init__(lambda_runner.is_debugging(), port=port, host=host) self.lambda_runner = lambda_runner self.stderr = stderr def create(self): """ Creates a Flask Application that can be started. """ self._app = Flask(__name__) path = '/2015-03-31/functions/<function_name>/invocations' self._app.add_url_rule(path, endpoint=path, view_func=self._invoke_request_handler, methods=['POST'], provide_automatic_options=False) # setup request validation before Flask calls the view_func self._app.before_request(LocalLambdaInvokeService.validate_request) self._construct_error_handling() @staticmethod def validate_request(): """ Validates the incoming request The following are invalid 1. The Request data is not json serializable 2. Query Parameters are sent to the endpoint 3. The Request Content-Type is not application/json 4. 'X-Amz-Log-Type' header is not 'None' 5. 'X-Amz-Invocation-Type' header is not 'RequestResponse' Returns ------- flask.Response If the request is not valid a flask Response is returned None: If the request passes all validation """ flask_request = request request_data = flask_request.get_data() if not request_data: request_data = b'{}' request_data = request_data.decode('utf-8') try: json.loads(request_data) except ValueError as json_error: LOG.debug("Request body was not json. Exception: %s", str(json_error)) return LambdaErrorResponses.invalid_request_content( "Could not parse request body into json: No JSON object could be decoded" ) if flask_request.args: LOG.debug("Query parameters are in the request but not supported") return LambdaErrorResponses.invalid_request_content( "Query Parameters are not supported") request_headers = flask_request.headers log_type = request_headers.get('X-Amz-Log-Type', 'None') if log_type != 'None': LOG.debug("log-type: %s is not supported. None is only supported.", log_type) return LambdaErrorResponses.not_implemented_locally( "log-type: {} is not supported. None is only supported.". format(log_type)) invocation_type = request_headers.get('X-Amz-Invocation-Type', 'RequestResponse') if invocation_type != 'RequestResponse': LOG.warning( "invocation-type: %s is not supported. RequestResponse is only supported.", invocation_type) return LambdaErrorResponses.not_implemented_locally( "invocation-type: {} is not supported. RequestResponse is only supported." .format(invocation_type)) def _construct_error_handling(self): """ Updates the Flask app with Error Handlers for different Error Codes """ self._app.register_error_handler( 500, LambdaErrorResponses.generic_service_exception) self._app.register_error_handler( 404, LambdaErrorResponses.generic_path_not_found) self._app.register_error_handler( 405, LambdaErrorResponses.generic_method_not_allowed) def _invoke_request_handler(self, function_name): """ Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming request and invoking the Local Lambda Function Parameters ---------- function_name str Name of the function to invoke Returns ------- A Flask Response response object as if it was returned from Lambda """ flask_request = request request_data = flask_request.get_data() if not request_data: request_data = b'{}' request_data = request_data.decode('utf-8') stdout_stream = io.BytesIO() stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging) try: self.lambda_runner.invoke(function_name, request_data, stdout=stdout_stream_writer, stderr=self.stderr) except FunctionNotFound: LOG.debug('%s was not found to invoke.', function_name) return LambdaErrorResponses.resource_not_found(function_name) lambda_response, lambda_logs, is_lambda_user_error_response = \ LambdaOutputParser.get_lambda_output(stdout_stream) if self.stderr and lambda_logs: # Write the logs to stderr if available. self.stderr.write(lambda_logs) if is_lambda_user_error_response: return self.service_response( lambda_response, { 'Content-Type': 'application/json', 'x-amz-function-error': 'Unhandled' }, 200) return self.service_response(lambda_response, {'Content-Type': 'application/json'}, 200)