def test(config): """Test the given Flask configuration. If configured correctly, an error will be tracked by Exceptional for your app. Unlike the initialized extension, this test will post data to Exceptional, regardless of the configured ``DEBUG`` setting. :param config: The Flask application configuration object to test. Accepts either :class:`flask.Config` or the object types allowed by :meth:`flask.Config.from_object`. """ context = getattr(stack.top, "exceptional_context", None) app = Flask(__name__) exceptional = Exceptional() if isinstance(config, Config): app.config = config else: app.config.from_object(config) assert "EXCEPTIONAL_API_KEY" in app.config app.debug = False app.testing = False exceptional.init_app(app) app.testing = True @app.route("/exception") def exception(): setattr(stack.top, "exceptional_context", context) message = "Congratulations! Your application is configured for Exceptional error tracking." # NOQA raise Exception(message) with app.test_client() as client: client.get("/exception") json.loads(g.exceptional)
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) #Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) #Setup the data model with app.app_context(): model = get_model() model.init_app(app) from .app import appview app.register_blueprint(appview, url_prefix='') @app.errorhandler(500) def server_error(e): return """ An internal error occurred:<pre>{}</pre> """.format(e), 500 return app
def app(): app = Flask(__name__) app.debug = True app.testing = True @app.context_processor def expose_current_timestamp(): return { 'now': datetime.now(), } @app.route('/naturalday') def naturalday(): return render_template_string("{{ now|humanize('naturalday') }}") @app.route('/naturaltime') def naturaltime(): return render_template_string("{{ now|humanize('naturaltime') }}") @app.route('/naturaldelta') def naturaldelta(): return render_template_string("{{ value|humanize('naturaldelta') }}", value=timedelta(days=7)) return app
def test_menu_render(): menu = decorators.menu menu.clear() app = Flask(__name__) app.testing = True @menu("Hello World", group_name="admin") class Hello(object): @menu("Index") def index(self): pass @menu("Page 2") def index2(self): pass @menu("Monster") class Monster(object): @menu("Home") def maggi(self): pass with app.test_client() as c: c.get("/") assert len(menu.render()) == 2
def app_error_handler(request): """Flask app error handler fixture.""" app = Flask('myapp') # Creation of a fake theme error template file. temp_dir = tempfile.mkdtemp() invenio_theme_dir = os.path.join(temp_dir, 'invenio_theme') os.mkdir(invenio_theme_dir) fake_file = open(os.path.join(invenio_theme_dir, 'fake.html'), 'w+') fake_file.write("{# -*- coding: utf-8 -*- -#}" "<!DOCTYPE html>{% block message %}" "{% endblock message %}") fake_file.close() # Adding the temporal path to jinja engine. app.jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(temp_dir), app.jinja_loader ]) # Setting by default fake.html as a THEME_ERROR_TEMPLATE app.config['THEME_ERROR_TEMPLATE'] = 'invenio_theme/fake.html' # Tear down method to clean the temp directory. def tear_down(): shutil.rmtree(temp_dir) request.addfinalizer(tear_down) app.testing = True Babel(app) InvenioI18N(app) InvenioTheme(app) return app
def create_app(self): app = Flask(__name__) app.config.update({"OAUTH1_PROVIDER_ENFORCE_SSL": False}) app.debug = True app.testing = True app.secret_key = "development" return app
def setUp(self): # Create an Flask application instance for testing. app = Flask(__name__) app.secret_key = 'testkey' app.testing = True app.config.update(CURRENT_CONFIG) # Attach routes for testing values in the app config. @app.route('/test_default_config/<config_key>/') def test_default_config(config_key): self.assertEqual(CURRENT_CONFIG[config_key], app.config[config_key]) return '' @app.route('/test_overridden_config/<config_key>/<value_expected>/') def test_overridden_config(config_key, value_expected): self.assertEqual(value_expected, app.config[config_key]) return '' # Attach the ConfigOverride to the created app ConfigOverride(app) # instance available for testing self.app = app
def _get_flask_app(roles=False, **kwargs): db = SQLAlchemy('sqlite:///:memory:') auth = authcode.Auth( SECRET_KEY, db=db, roles=roles, password_minlen=3, **kwargs) User = auth.User db.create_all() user = User(login=u'meh', password='******') db.add(user) user2 = User(login=u'foo', password='******') db.add(user2) db.commit() app = Flask('test') app.secret_key = os.urandom(32) app.testing = True @app.route('/protected/') @auth.protected() def protected(): return u'Welcome' authcode.setup_for_flask(auth, app) auth.session = {} return auth, app, user
def setup_app(debug=False, testing=False, production=False, config='dev', gae=False, **kwargs): from flask import Flask # Passing __name__ for reference point on where your code and resources are # This will influence a default template location # http://flask.pocoo.org/docs/api/#flask.Flask app = Flask(__name__, **kwargs) app.debug = debug # WARNING: setting True will disable login_manager decorators app.testing = testing import website.settings app.config.from_object(website.settings) import importlib logging.debug("Additional settings: %s" % "website.settings_"+config) cfg = importlib.import_module("website.settings_"+config) logging.debug("Loaded website.settings_%s" % config) app.config.from_object(cfg) # Enable jinja2 extensions app.jinja_env.add_extension('jinja2.ext.loopcontrols') app.jinja_env.add_extension('jinja2.ext.with_') from ext.relative_templates import RelativeInclude app.jinja_env.add_extension(RelativeInclude) #app.jinja_env.add_extension('compressor.contrib.jinja2ext.CompressorExtension') if gae and not production: # enable jinja debugging info in GAE SDK # http://jinja.pocoo.org/docs/faq/#my-tracebacks-look-weird-what-s-happening from google.appengine.tools.devappserver2.python import sandbox sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Register the Bookshelf CRUD blueprint. from .user_crud import user_crud app.register_blueprint(user_crud, url_prefix='/users') # Add a default root route. @app.route("/") def index(): return redirect(url_for('user_crud.list')) return app
def create_app(config, debug=False, testing=False, config_overrides=None): """Application factory """ # define the WSGI application object flask_app = Flask(__name__) # configuration flask_app.config.from_object(config) flask_app.debug = debug flask_app.testing = testing if config_overrides: flask_app.config.update(config_overrides) # initialize the database db.init_app(flask_app) # blueprints from app.users import users_blueprint flask_app.register_blueprint(users_blueprint) # flask-restful from app.users import UserListAPI, UserAPI api = Api(prefix='/api/v0') api.add_resource(UserListAPI, '/users', endpoint='users') api.add_resource(UserAPI, '/users/<id>', endpoint='user') api.init_app(flask_app) cors = CORS(resources={r'/api/*': {'origins': '*'}}) cors.init_app(flask_app) return flask_app
def _runFlask(self, gw, port): """ :param gw: Gateway :type gw: smsframework.Gateway.Gateway :return: :rtype: """ # Init flask app = Flask(__name__) app.debug = True app.testing = True # Register gateway receivers gw.receiver_blueprints_register(app, prefix='/sms') # Stop manually @app.route('/kill', methods=['GET','POST']) def kill(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() return '' # Run app.run('0.0.0.0', port, threaded=False, use_reloader=False, passthrough_errors=True)
def gen_app(config): """Generate a fresh app.""" app = Flask('testapp') app.testing = True app.config.update(**config) FlaskCLI(app) FlaskMenu(app) Babel(app) Mail(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) with app.app_context(): db.create_all() app.test_request_context().push() datastore = app.extensions['invenio-accounts'].datastore datastore.create_user( email="*****@*****.**", password='******', active=True) datastore.create_user( email="*****@*****.**", password='******', active=True) datastore.create_user( email="*****@*****.**", password='******', active=True) datastore.commit() return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # [START setup_logging] if not app.testing: client = google.cloud.logging.Client(app.config['PROJECT_ID']) handler = CloudLoggingHandler(client) # Attaches the handler to the root logger setup_logging(handler) logging.getLogger().setLevel(logging.INFO) # [END setup_logging] # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Initalize the OAuth2 helper. oauth2.init_app( app, scopes=['email', 'profile'], authorize_callback=_request_user_info) # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True oauth2.storage.delete() return redirect(request.referrer or '/') # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/books') # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) # Add an error handler. This is useful for debugging the live application, # however, you should disable the output of the exception for production # applications. @app.errorhandler(500) def server_error(e): return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.format(e), 500 return app
def test_error_unexpected_exception_testing(): test_app = Flask(__name__) test_app.testing = True with test_app.test_request_context(): msg = 'missing stuff' error = Exception(msg) with assert_raises(Exception): api.error_handler(error)
def create_flask_app(db_url): app = Flask(__name__) (app.db_session, app.db_metadata, app.db_engine) = init_db(db_url) app.debug = os.environ.get('DEBUG') == 'True' app.testing = os.environ.get('TESTING') == 'True' @app.teardown_request def shutdown_session(exception=None): app.db_session.remove() return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: client = google.cloud.logging.Client(app.config['PROJECT_ID']) # Attaches a Google Stackdriver logging handler to the root logger client.setup_logging(logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Initalize the OAuth2 helper. oauth2.init_app( app, scopes=['email', 'profile'], authorize_callback=_request_user_info) # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True oauth2.storage.delete() return redirect(request.referrer or '/') # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/books') # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) # Add an error handler that reports exceptions to Stackdriver Error # Reporting. Note that this error handler is only used when debug # is False @app.errorhandler(500) def server_error(e): client = error_reporting.Client(app.config['PROJECT_ID']) client.report_exception( http_context=error_reporting.build_flask_context(request)) return """ An internal error occurred. """, 500 return app
def app(request): # XXX: __name__ doesn't work due to a bug in Flask / an optional method not # implemented by a py.test meta path loader. py.test has the method in the # trunk version, so let's change this to __name__ when that version comes # out, currently we are at pytest 2.3.5 app = Flask('__main__') app.config['SECRET_KEY'] = b'secret' app.testing = True return app
def create_app(self): app = Flask(__name__) app.testing = True app.secret_key = "secret" app.config["WTF_HIDDEN_TAG"]="div" @app.route("/", methods=("GET", "POST")) def index(): form = MyForm() if form.validate_on_submit(): name = form.name.data.upper() else: name = '' return render_template("index.html", form=form, name=name) @app.route("/simple/", methods=("POST",)) def simple(): form = SimpleForm() form.validate() assert form.meta.csrf assert not form.validate() return "OK" @app.route("/two_forms/", methods=("POST",)) def two_forms(): form = SimpleForm() assert form.meta.csrf assert form.validate() assert form.validate() form2 = SimpleForm() assert form2.meta.csrf assert form2.validate() return "OK" @app.route("/hidden/") def hidden(): form = HiddenFieldsForm() return render_template("hidden.html", form=form) @app.route("/ajax/", methods=("POST",)) def ajax_submit(): form = MyForm() if form.validate_on_submit(): return jsonify(name=form.name.data, success=True, errors=None) return jsonify(name=None, #errors=form.errors, success=False) return app
def app(): _app = Flask(__name__) _app.secret_key = "anything" _app.testing = True @_app.route("/") def index(): return "index" return _app
def make_app(): app = Flask(__name__) # Load configuration. conf_file = os.environ.get("CONFIG", None) if not conf_file: raise Exception("Missing CONFIG environment variable with the configuration") app.config.from_pyfile(conf_file) if app.config['DEBUG']: app.testing = True return app
def test_render_as_xml(): app = Flask(__name__) app.testing = True @app.route("/") @decorators.render_as_xml def index(): return {"test": "ok"} with app.test_client() as c: data = c.get("/").data assert '<?xml version="1.0"' in data
def test_render_as_json(): import json app = Flask(__name__) app.testing = True @app.route("/") @decorators.render_as_json def index(): return {"test": "ok"} with app.test_client() as c: assert {"test": "ok"} == json.loads(c.get("/").data)
def create_app(info): app = Flask(__name__) app.testing = True @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST']) def yyy_get_post(x, y): pass @app.route('/zzz_post', methods=['POST']) def aaa_post(): pass return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Initalize the OAuth2 helper. oauth2.init_app( app, scopes=['email', 'profile'], authorize_callback=_request_user_info) # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] oauth2.storage.delete() return redirect(request.referrer or '/') # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/books') # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) # Create a health check handler. Health checks are used when running on # Google Compute Engine by the load balancer to determine which instances # can serve traffic. Google App Engine also uses health checking, but # accepts any non-500 response as healthy. @app.route('/_ah/health') def health_check(): return 'ok', 200 return app
def test_custom_templates(): db = SQLAlchemy('sqlite:///:memory:') options = { 'template_sign_in': 'sign-in.html', 'template_sign_out': 'sign-out.html', 'template_reset': 'reset-password.html', 'template_reset_email': 'reset-password-email.html', 'template_change_password': '******', } inbox = [] def send_email(user, subject, msg): inbox.append(msg) auth = authcode.Auth(SECRET_KEY, db=db, **options) User = auth.User db.create_all() user = User(login=u'meh', password='******') db.add(user) db.commit() custom_templates = os.path.join( os.path.dirname(__file__), 'custom_templates' ) app = Flask('test', template_folder=custom_templates) app.secret_key = os.urandom(32) app.testing = True authcode.setup_for_flask(auth, app, send_email=send_email) auth.session = {} client = app.test_client() resp = client.get(auth.url_sign_in) assert resp.data == b'OK SIGN IN' resp = client.get(auth.url_reset_password) assert resp.data == b'OK RESET PASSWORD' data = dict(login=user.login, _csrf_token=auth.get_csrf_token()) resp = client.post(auth.url_reset_password, data=data) assert inbox[0] == 'OK RESET PASSWORD EMAIL' auth.login(user) resp = client.get(auth.url_change_password) assert resp.data == b'OK CHANGE PASSWORD' url = '{0}?_csrf_token={1}'.format(auth.url_sign_out, auth.get_csrf_token()) resp = client.get(url) assert resp.data == b'OK SIGN OUT'
def make_app(app_name): app = Flask(app_name) # Load configuration. # conf_file = os.environ.get("CONFIG", None) # if not conf_file: # raise Exception("Missing CONFIG environment variable with the configuration") # app.config.from_pyfile(conf_file) app.config.from_object('config') if app.config['DEBUG']: app.testing = True return app
def create_app(config): app = Flask(__name__) app.debug = True app.testing = True app.config['SECRET_KEY'] = 'so secret' for key, value in config.items(): app.config[key] = value @app.route('/') def index(): return render_template('index.html') return app
def create_app(): app = Flask(__name__) app.debug = True app.testing = False import config app.config.from_object(config) app.config['SHELF_PAGES'] = { "index": (IndexPage, IndexPageModelView), "contact": (ContactPage, ContactPageModelView), } with app.app_context(): db.init_app(app) db.create_all() babel = Babel(app) shlf = Shelf(app) shlf.init_db(db) dview = DashboardView() shlf.init_admin(index_view=dview) shlf.init_security(User, Role) shlf.load_plugins(( "shelf.plugins.dashboard", "shelf.plugins.i18n", "shelf.plugins.library", "shelf.plugins.page", "shelf.plugins.preview", "shelf.plugins.workflow", "shelf.plugins.wysiwyg", "shelf.plugins.ecommerce", )) init_admin(shlf.admin, db.session) shlf.setup_plugins() page = shlf.get_plugin_by_class(PagePlugin) page.register_pages(app, shlf.db) init_views(app) init_filters(app) return app
def create_app(config=None, debug=False, testing=False, config_overrides=None): """ Create the flask application Args: config flask configuration (python file) debug flask app mode testing flask app mode config_overrides a dictionary given if config has to be overrides """ app = Flask(__name__, static_folder='templates') if config is not None: app.config.from_object(config) app.debug = debug app.testing = testing # import controllers from .controllers import init_app # load all routes with controllers init_app(app) if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) # Add an error handler. This is useful for debugging the live application, # however, you should disable the output of the exception for production # applications. @app.errorhandler(500) def server_error(e): return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace """.format(e), 500 # @app.errorhandler(404) # def not_found_error(e): # return """ # The requested page can't be found: <pre>{}</pre> # """.format(e), 404 return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) app.config['SESSION_COOKIE_NAME'] = "connect.sid" app.config['SESSION_TYPE'] = 'redis' # session็ฑปๅไธบredis app.config['SESSION_PERMANENT'] = False # ๅฆๆ่ฎพ็ฝฎไธบTrue๏ผๅๅ ณ้ญๆต่งๅจsessionๅฐฑๅคฑๆใ app.config['SESSION_USE_SIGNER'] = False # ๆฏๅฆๅฏนๅ้ๅฐๆต่งๅจไธsession็cookieๅผ่ฟ่กๅ ๅฏ app.config['SESSION_KEY_PREFIX'] = 'sess:' # ไฟๅญๅฐsessionไธญ็ๅผ็ๅ็ผ app.config['SESSION_REDIS'] = redis.Redis(host='127.0.0.1', port=6379) #app.session_interface = MySessionInterface() Session(app) #se=Session #se.init_app(app) # [START init_app] # Initalize the OAuth2 helper. #oauth2.init_app( # app, # scopes=['email', 'profile'], # authorize_callback=_request_user_info) # # [END init_app] # [START logout] # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True #oauth2.storage.delete() return redirect(request.referrer or '/') # [END logout] @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = get_model().readUser(username) print(user) #session['username'] #for record in records: if user: if username == user["user"] and password == user["Pass"]: session['profile'] = user return redirect(url_for('index')) return ''' <div style="margin-top: 20%;margin-left:50%;margin-right:50%"> <form method="post"> <p>USER:<input type=text name=username> <p>PASS:<input type=password name=password> <p><input type=submit value=Login> </form> </div> ''' # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/lessons') # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) @app.route("/sess") def showsess(): #s = json.dumps(session, indent=4, sort_keys=True) print("*set session aa 1*") if (session['profile'] != None): if (session['profile'].get('aa') != None): print(session['profile'].get('aa')) session["profile"]["aa"] = 1 + session["profile"].get("aa") else: session["profile"]["aa"] = 0 print(session) print("*2*") return str(session["profile"]["user"]) @app.route("/profile") def showprofile(): #s = json.dumps(session, indent=4, sort_keys=True) print("*profile 1*") print(session) print("*profile 2*") return str(session["profile"]["user"]) # Add an error handler. This is useful for debugging the live application, # however, you should disable the output of the exception for production # applications. @app.errorhandler(500) def server_error(e): return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.format(e), 500 return app
def create_rebar_app(rebar): app = Flask("RebarTest") app.testing = True rebar.init_app(app) return app
def create_app(): app = Flask(__name__, static_folder=None) app.testing = True return app
def app(request): app = Flask(request.module.__name__) app.test_client_class = TestClient app.testing = True return app
from nltk.chat.util import Chat, reflections from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() import pickle import numpy as np # from keras.models import load_model # model = load_model('chatbot_model.h5') import json # import random # intents = json.loads(open('intents.json').read()) # words = pickle.load(open('words.pkl','rb')) # classes = pickle.load(open('classes.pkl','rb')) app = Flask(__name__) app.testing = False app.secret_key = 'super secret key' app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True app.config['MAIL_DEFAULT_SENDER'] = '*****@*****.**' app.config['MAIL_ASCII_ATTACHMENTS'] = True app.config['DEBUG'] = True mail = Mail(app) model_nltk = pickle.load(open("nltk.pkl", 'rb')) # english_bot = ChatBot("Chatterbot", storage_adapter='chatterbot.storage.SQLStorageAdapter',
def create_app(config_class=Config): global config app = Flask(__name__) # Flask configs config = config_class app.config['SECRET_KEY'] = config.secretKey # SQLAlchemy configs app.config['SQLALCHEMY_DATABASE_URI'] = config.sqlAlchemyDatabaseUri app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Flask Mail configs app.config['MAIL_SERVER'] = config.mailServer app.config['MAIL_PORT'] = config.mailPort app.config['MAIL_USE_TLS'] = config.mailUseTls app.config['MAIL_USERNAME'] = config.mailUsername app.config['MAIL_PASSWORD'] = config.mailPassword app.testing = config.testing db.init_app(app) migrate.init_app(app, db) login.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) babel.init_app(app) from app import models from app.auth import routes from app.auth import bp as auth_bp from app.errors import bp as errors_bp from app.main import bp as main_bp app.register_blueprint(errors_bp) app.register_blueprint(auth_bp, url_prefix='/auth') app.register_blueprint(main_bp) if not app.debug and not app.testing and config.mailServer: auth = None if config.mailUsername or config.mailPassword: auth = (config.mailUsername, config.mailPassword) secure = None if config.mailUseTls: secure = () mail_handler = SMTPHandler(mailhost=(config.mailServer, config.mailPort), fromaddr='no-reply@' + config.mailServer, toaddrs=config.admins, subject='Microblog Failure', credentials=auth, secure=secure) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/microblog.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('Microblog startup') return app
def app(): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:" app.testing = True return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Create a health check handler. Health checks are used when running on # Google Compute Engine by the load balancer to determine which instances # can serve traffic. Google App Engine also uses health checking, but # accepts any non-500 response as healthy. @app.route('/_ah/health') def health_check(): return 'ok', 200 # Initalize the OAuth2 helper. oauth2.init_app(app, scopes=['email', 'profile'], authorize_callback=_request_user_info) # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True oauth2.storage.delete() return redirect(request.referrer or '/') # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/books') # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) # Add an error handler. This is useful for debugging the live application, # however, you should disable the output of the exception for production # applications. @app.errorhandler(500) def server_error(e): return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.format(e), 500 return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) # TODO: # client = google_cloud_logging.Client(app.config['PROJECT_ID']) # # Attaches a Google Stackdriver logging handler to the root logger # client.setup_logging(logging.INFO) # Setup the data model. with app.app_context(): model.init_app(app) # Initalize the OAuth2 helper. # oauth2.init_app( # app, # scopes=['email', 'profile'], # authorize_callback=_request_user_info) # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True # oauth2.storage.delete() return redirect(request.referrer or '/') # Register the Layers CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/layers') # Add a default root route. # @oauth2.required @app.route("/") def index(): # TODO return redirect(url_for('crud.list')) # TODO: # @app.route("/settings") # Add an error handler that reports exceptions to Stackdriver Error # Reporting. Note that this error handler is only used when debug # is False @app.errorhandler(500) def server_error(exc): return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.format(exc), 500 # TODO: # client = error_reporting.Client(app.config['PROJECT_ID']) # client.report_exception( # http_context=error_reporting.build_flask_context(request)) # return """ # An internal error occurred. # """, 500 return app
for name in get_enabled_dataset_names(): dataset = get_dataset(name) source = dataset.get_dataset_schemas().get_read_schema() if isinstance(source, TableSchema): table_name = source.get_table_name() if (table_name, ) not in clickhouse_tables: return False return True except Exception: return False application = Flask(__name__, static_url_path='') application.testing = settings.TESTING application.debug = settings.DEBUG sentry_sdk.init(dsn=settings.SENTRY_DSN, integrations=[FlaskIntegration(), GnuBacktraceIntegration()], release=os.getenv('SNUBA_RELEASE')) @application.errorhandler(BadRequest) def handle_bad_request(exception: BadRequest): cause = getattr(exception, '__cause__', None) if isinstance(cause, json.errors.JSONDecodeError): data = {'error': {'type': 'json', 'message': str(cause)}} elif isinstance(cause, jsonschema.ValidationError): data = {
def create(env=None) -> Flask: """ Create a Flask app and configure it. Set the environment by setting FLASK_ENV as environment variable (also possible in .env). Or, overwrite any FLASK_ENV setting by passing an env in directly (useful for testing for instance). """ from flexmeasures.utils.config_utils import read_config, configure_logging from flexmeasures.utils.app_utils import install_secret_key from flexmeasures.utils.error_utils import add_basic_error_handlers # Create app configure_logging( ) # do this first, see http://flask.pocoo.org/docs/dev/logging/ # we're loading dotenv files manually & early (can do Flask.run(load_dotenv=False)), # as we need to know the ENV now (for it to be recognised by Flask()). load_dotenv() app = Flask("flexmeasures") if env is not None: # overwrite app.env = env if env == "testing": app.testing = True # App configuration read_config(app) if app.debug and not app.testing and not app.cli: print(app.config) add_basic_error_handlers(app) app.mail = Mail(app) FlaskJSON(app) cors = CORS(app) # configure Redis (for redis queue) if app.testing: from fakeredis import FakeStrictRedis app.queues = dict( forecasting=Queue(connection=FakeStrictRedis(), name="forecasting"), scheduling=Queue(connection=FakeStrictRedis(), name="scheduling"), ) else: redis_conn = Redis( app.config["FLEXMEASURES_REDIS_URL"], port=app.config["FLEXMEASURES_REDIS_PORT"], db=app.config["FLEXMEASURES_REDIS_DB_NR"], password=app.config["FLEXMEASURES_REDIS_PASSWORD"], ) """ FWIW, you could use redislite like this (not on non-recent os.name=="nt" systems or PA, sadly): from redislite import Redis redis_conn = Redis("MY-DB-NAME", unix_socket_path="/tmp/my-redis.socket", ) """ app.queues = dict( forecasting=Queue(connection=redis_conn, name="forecasting"), scheduling=Queue(connection=redis_conn, name="scheduling"), ) # Some basic security measures if not app.env == "documentation": install_secret_key(app) SSLify(app) # Register database and models, including user auth security measures from flexmeasures.data import register_at as register_db_at register_db_at(app) # Register the API from flexmeasures.api import register_at as register_api_at register_api_at(app) # Register the UI from flexmeasures.ui import register_at as register_ui_at register_ui_at(app) # Profile endpoints (if needed, e.g. during development) @app.before_request def before_request(): if app.config.get("FLEXMEASURES_PROFILE_REQUESTS", False): g.start = time.time() @app.teardown_request def teardown_request(exception=None): if app.config.get("FLEXMEASURES_PROFILE_REQUESTS", False): diff = time.time() - g.start if all( [kw not in request.url for kw in ["/static", "favicon.ico"]]): app.logger.info( f"[PROFILE] {str(round(diff, 2)).rjust(6)} seconds to serve {request.url}." ) return app
def init_test_client(): app = Flask(__name__) make_api(app) app.testing = True return app.test_client()
app.config.from_object('config') lm = LoginManager() lm.init_app(app) lm.login_view = 'login' lm.session_protection = "strong" #oid = OpenID(app, os.path.join(basedir, 'tmp')) db = SQLAlchemy(app) bcrypt = Bcrypt(app) mail = Mail(app) app.testing = RECAPTCHA_TESTING from app import models, views @lm.user_loader def load_user(id): return models.User.query.get(int(id)) if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler(LOGFILE, 'a', 1 * 1024 * 1024, 10) file_handler.setFormatter( logging.Formatter(
def create_app(testing=None, test_config=None): app = Flask(__name__) app.testing = testing setup_db(app) CORS(app) @app.route('/') def get_greeting(): excited = '' if 'EXCITED' in os.environ: excited = os.environ['EXCITED'] greeting = "Hello" if excited == 'true': greeting = greeting + "!!!!!" return greeting @app.route('/coolkids') def be_cool(): return "Be cool, man, be coooool! You're almost a FSND grad!" @app.route('/api/stats') @requires_auth('view:actors') def show_stats(payload): return jsonify({'movies': Movie.query.count(), 'actors': Actor.query.count()}) @app.route('/api/actors') @requires_auth('view:actors') @paginated_request def show_actors(pagination, payload): gender_values = list(map(lambda value: int(value), request.args.getlist('genders[]'))) name = request.args.get('name') sort_function = None pagination['per_page'] = get_per_page(pagination['per_page'], RECORDS_PER_PAGE) if 'sort_field' in pagination: field = getattr(Actor, pagination['sort_field']) sort_function = getattr(field, pagination['sort_order']) query = Actor.query if sort_function is not None: query = query.order_by(sort_function()) if (gender_values is not None) and (len(gender_values) > 0): enum_objs = list(map(lambda value: GenderEnum(value), gender_values)) query = query.filter(Actor.gender.in_(enum_objs)) if is_empty_string(name): query = query.filter(Actor.name.ilike('%' + name + '%')) if (0 != pagination['per_page']) and (0 != pagination['current_page']): actors = query.paginate(per_page=pagination['per_page'], page=pagination['current_page']) if 0 == len(actors.items): abort(404) return jsonify({ 'actors': list(map(lambda actor: actor.format(), actors.items)), 'totalCount': actors.total, 'currentPage': pagination['current_page'], 'perPage': pagination['per_page'], 'filters': {'genders': gender_values}, 'sortField': pagination['sort_field'] if 'sort_field' in pagination else '', 'sortOrder': pagination['sort_order'] if 'sort_order' in pagination else '', 'success': True }) else: actors = query.all() if 0 == len(actors): abort(404) return jsonify({ 'actors': list(map(lambda actor: actor.format(), actors)), }) @app.route('/api/actors', methods=['POST']) @requires_auth('create:actor') def create_actors(payload): print('New actor: ') print(request.json) name = request.json['name'] age = int(request.json['age']) if 'age' in request.json else 0 if (name is None) or ('' == name) or (len(name) < 5): print('Invalid name provided') abort(422) if (age is None) or (3 > age) or (99 < age): print('Invalid age provided') abort(422) try: gender = GenderEnum(request.json['gender']) new_artist = Actor(name=name, age=age, gender=gender) result = new_artist.save_to_db() return jsonify({ 'success': result, 'artist': new_artist.format(), }) except ValueError: print('Invalid gender provided') abort(422) @app.route("/api/actors/<int:actor_id>", methods=['DELETE']) @requires_auth('delete:actor') def delete_actor(payload, actor_id): actor = Actor.query.filter_by(id=actor_id).first() try: actor.delete_from_db() return jsonify({'success': True}) except: abort(500) @app.route("/api/actors/<int:actor_id>", methods=['PATCH']) @requires_auth('edit:actor') def update_actor(payload, actor_id): try: actor = Actor.query.filter_by(id=actor_id).first() if 'name' in request.json: actor.name = request.json['name'] if 'age' in request.json: actor.age = int(request.json['age']) if 'gender' in request.json: actor.gender = GenderEnum(request.json['gender']) actor.update() return jsonify({ 'success': True, 'artist': actor.format() }) except Exception as e: print(e) abort(422) @app.route('/api/movies') @requires_auth('view:movies') @paginated_request def show_movies(pagination, payload): if 'get_all' in pagination: movie_list = Movie.query.order_by(Movie.release.desc()).all() return jsonify({ 'movies': list(map(lambda movie: movie.format(), movie_list)) }) else: pagination['per_page'] = get_per_page(pagination['per_page'], RECORDS_PER_PAGE) title = request.args.get('title') field = getattr(Movie, pagination['sort_field']) sort_function = getattr(field, pagination['sort_order']) query = Movie.query if sort_function is not None: query = query.order_by(sort_function()) if is_empty_string(title): query = query.filter(Movie.title.ilike('%' + title + '%')) movies = query.paginate(per_page=pagination['per_page'], page=pagination['current_page']) return jsonify({ 'movies': list(map(lambda movie: movie.format(), movies.items)), 'totalCount': movies.total, 'currentPage': pagination['current_page'], 'perPage': pagination['per_page'], 'success': True }) @app.route('/api/movies', methods=['POST']) @requires_auth('create:movie') def create_movies(payload): print('New movie: ') print(request.json) title = request.json['title'] release = int(request.json['releaseDate']) if 'releaseDate' in request.json else 0 if (title is None) or ('' == title) or (len(title) < 5): print('Invalid title provided') abort(422) if (release is None) or (0 == release): print('Invalid release provided') abort(422) new_movie = Movie(title=title, release=release) result = new_movie.save_to_db() return jsonify({ 'success': result, 'movie': new_movie.format(), }) @app.route("/api/movies/<int:movie_id>", methods=['PATCH']) @requires_auth('edit:movie') def update_movie(payload, movie_id): try: movie = Movie.query.filter_by(id=movie_id).first() if 'title' in request.json: movie.title = request.json['title'] if 'releaseDate' in request.json: movie.release = int(request.json['releaseDate']) movie.update() return jsonify({ 'success': True, 'movie': movie.format() }) except Exception as e: print(e) abort(422) @app.route("/api/movies/<int:movie_id>", methods=['DELETE']) @requires_auth('delete:movie') def delete_movie(payload, movie_id): movie = Movie.query.filter_by(id=movie_id).first() try: movie.delete_from_db() return jsonify({'success': True}) except: abort(500) @app.route('/api/crews', methods=['GET']) @requires_auth('update:crew') def get_crew_list(payload): crew_list = Crew.query.all() if len(crew_list) == 0: abort(404) try: return jsonify({ 'crews': list(map(lambda crew: crew.format(), crew_list)), 'success': True, }) except Exception as e: print(e) abort(422) @app.route('/api/crews', methods=['POST']) @requires_auth('update:crew') def assign_crew(payload): print('New crew: ') movie_id = request.json['movie_id'] artist_list = request.json['artists'] if movie_id is None: print('No movie found') abort(422) records = Crew.query.filter(Crew.movie_id == request.json['movie_id']).all() if len(records) > 0: for record in records: record.delete_from_db() if artist_list is not None: try: for val in artist_list: new_crew = Crew(actor_id=val, movie_id=movie_id) new_crew.save_to_db() return jsonify({'success': True, 'result': request.json}) except Exception as e: print(e) abort(422) else: print('No artist list found') abort(422) # Error Handling ''' Example error handling for unprocessable entity ''' @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "Unprocessable" }), 422 ''' Handles no resource found error ''' @app.errorhandler(404) def unprocessable(error): return jsonify({ "success": False, "error": 404, "message": "Provided resource cannot be found" }), 404 ''' Handles unauthorized access error ''' @app.errorhandler(401) def unprocessable(error): return jsonify({ "success": False, "error": 401, "message": "Unauthorized access" }), 401 @app.errorhandler(403) def no_permission_granted(error): return jsonify({ "success": False, "error": 403, "message": "No permission granted" }), 403 return app
def create_app(self): app = Flask(__name__) app.debug = True app.testing = True app.secret_key = 'development' return app
def create_app(debug=APP_DEBUG, testing=APP_TESTING, config_overrides=None): """ :param config: :param debug: :param testing: :param config_overrides: :return: """ app = Flask(__name__) app.debug = debug app.testing = testing app.config['JSON_AS_ASCII'] = False if config_overrides: app.config.update(config_overrides) @app.route('/api/health') def health_check(): """ :return: """ response = { 'status_code': 200, 'status_msg': 'health is ok', } return make_response(jsonify(response)), 200 @app.route('/') @app.route('/api') def index(): """ :return: """ return redirect('/api/health') #\@app.errorhandler(204) # ๆ็ซ ใๆๅณใใชใใฆใใใใๅคๅฎใใชใใฃใ @app.errorhandler(400) # ใชใฏใจในใใไธๆญฃใงใใใๅฎ็พฉใใใฆใใชใใกใฝใใใไฝฟใใชใฉใใฏใฉใคใขใณใใฎใชใฏใจในใใใใใใๅ ดๅใซ่ฟใใใใ @app.errorhandler(401) # ่ช่จผใๅฟ ่ฆใงใใใBasic่ช่จผใDigest่ช่จผใชใฉใ่กใใจใใซไฝฟ็จใใใใ @app.errorhandler(403) # ็ฆๆญขใใใฆใใใใชใฝใผในใซใขใฏใปในใใใใจใๆๅฆใใใใ @app.errorhandler(404) # ๆชๆคๅบใใชใฝใผในใ่ฆใคใใใชใใฃใใ @app.errorhandler(405) # ่จฑๅฏใใใฆใใชใใกใฝใใใ่จฑๅฏใใใฆใใชใใกใฝใใใไฝฟ็จใใใใจใใใ @app.errorhandler(406) # ๅ็ใงใใชใใAccept้ข้ฃใฎใใใใซๅ็ใงใใชใๅ ๅฎนใๅซใพใใฆใใๅ ดๅใซ่ฟใใใใ @app.errorhandler(408) # ใชใฏใจในใใฟใคใ ใขใฆใใใชใฏใจในใใๆ้ไปฅๅ ใซๅฎไบใใฆใใชใๅ ดๅใซ่ฟใใใใ @app.errorhandler(413) # ใใคใญใผใใๅคงใใใใใใชใฏใจในใใจใณใใฃใใฃใใตใผใใฎ่จฑๅฎน็ฏๅฒใ่ถ ใใฆใใๅ ดๅใซ่ฟใใ @app.errorhandler(500) # ใตใผใๅ ้จใจใฉใผใใตใผใๅ ้จใซใจใฉใผใ็บ็ใใๅ ดๅใซ่ฟใใใใ @app.errorhandler(503) # ใตใผใในๅฉ็จไธๅฏใใตใผใในใไธๆ็ใซ้่ฒ ่ทใใกใณใใใณในใงไฝฟ็จไธๅฏ่ฝใงใใใ def server_error(e): """ :param e: :return: """ response = { 'status_code': int(e.code), 'status_msg': str(e) } return make_response(jsonify(response)), e.code #main api @app.route('/api/wifi/addPoints', methods=['POST']) def add_points(): if request.method == 'POST': req = request.get_json()["datas"] logp("Start add points for {} count".format(len(req))) points = [] sql_query = "SELECT" + " name, Y(geoPoint), X(geoPoint) FROM " + TABLE_NAME sql_result = execute_sql(sql_query, is_get=True) if sql_result is dict and sql_result['sql_status'] == 'error': abort(500) for point in tqdm(req): samedata = [d for d in sql_result if d['name'] == point['name'] and d['X(geoPoint)'] == point['longitude'] and d['Y(geoPoint)'] == point['latitude']] if len(samedata) != 0: continue points.append([point['name'], point['ssid'], point['address'], point['postCode'],point['hpUrl'], 'POINT({} {})'.format(point['longitude'], point['latitude'])]) if sql_add_query(points)['sql_status'] == 'error': abort(500) logp("add {} data".format(len(points))) logp("Finish add points") response = { 'status_code': 200, 'status_msg': 'success', } return make_response(jsonify(response)), 200 @app.route('/api/wifi/updatePoints', methods=['POST']) def update_points(): if request.method == 'POST': req = request.get_json()["datas"] logp("Start update points for {} count".format(len(req))) points = [] for point in tqdm(req): if point['id'] is None: abort(400) points.append([point['name'], point['ssid'], point['address'], point['postCode'],point['hpUrl'], 'POINT({} {})'.format(point['longitude'], point['latitude']), point['id']]) if sql_update_query(points)['sql_status'] == 'error': abort(500) logp("Finish update points") response = { 'status_code': 200, 'status_msg': 'success', } return make_response(jsonify(response)), 200 @app.route('/api/wifi/getPoints', methods=['GET']) def get_points(): if request.method == 'GET': name_keyword = request.args.get('name') id = request.args.get('id') latitude = request.args.get('latitude') longitude = request.args.get('longitude') distance = request.args.get('distance') count = request.args.get('count') if name_keyword is not None: if not name_keyword != "": abort(400) response = { 'datas': sql_get_by_name_query(name_keyword), 'status_code': 200, 'status_msg': 'success', } return make_response(jsonify(response)), 200 elif id is not None: if not id != "": abort(400) response = { 'datas': sql_get_by_id_query(id), 'status_code': 200, 'status_msg': 'success', } return make_response(jsonify(response)), 200 elif latitude is not None and longitude is not None and distance is not None: if not (latitude != "" and longitude != "" and distance != ""): abort(400) response = { 'datas': sql_get_by_distance_query(float(latitude), float(longitude), float(distance), count), 'status_code': 200, 'status_msg': 'success', } return make_response(jsonify(response)), 200 else: response = { 'datas': sql_get_all_query(), 'status_code': 200, 'status_msg': 'success', } return make_response(jsonify(response)), 200 def sql_add_query(points): sql_query = "INSERT INTO " + TABLE_NAME + "(name, ssid, address, postCode, hpUrl, geoPoint) \ VALUES(?, ?, ?, ?, ?, GeomFromText(?))" values = points return execute_sql(sql_query, values) def sql_get_by_distance_query(latitude, longitude, distance, count): longitude_distance = 0.01097 * distance / 1000 latitude_distance = 0.00901 * distance / 1000 sql_query = "SELECT" + " id, name, ssid, address, postCode, hpUrl, Y(geoPoint), X(geoPoint) FROM " + TABLE_NAME \ + " WHERE MBRIntersects(GeomFromText(?), geoPoint)" params = ['LineString({} {}, {} {})'.format(longitude - longitude_distance, latitude - latitude_distance, longitude + longitude_distance, latitude + latitude_distance)] points = execute_sql(sql_query, params, True) sorted_points = sorted(points, key=lambda x: (x["Y(geoPoint)"] - latitude) ** 2 + (x["X(geoPoint)"] - longitude) ** 2) if count is None or (type(count) == str and not count.isdigit()): return sorted_points else: return sorted_points[:int(count)] def sql_get_by_name_query(name): # sql_query = "SELECT" + " id, name, ssid, address, postCode, hpUrl, Y(geoPoint), X(geoPoint) FROM " + TABLE_NAME \ # + " WHERE (name LIKE '{0}%' OR address LIKE '{0}%')".format(name, name) sql_query = "SELECT" + " id, name, ssid, address, postCode, hpUrl, Y(geoPoint), X(geoPoint) FROM " + TABLE_NAME \ + " WHERE (name LIKE ? OR address LIKE ?)" params = ['%'+name+'%', '%'+name+'%'] return execute_sql(sql_query, params, True) def sql_get_by_id_query(id): sql_query = "SELECT" + " id, name, ssid, address, postCode, hpUrl, Y(geoPoint), X(geoPoint) FROM " + TABLE_NAME \ + " WHERE id == ?" params = [id] return execute_sql(sql_query, params, True) def sql_get_all_query(): sql_query = "SELECT" + " id, name, ssid, address, postCode, hpUrl, Y(geoPoint), X(geoPoint) FROM " + TABLE_NAME params = [] return execute_sql(sql_query, params, True) def sql_update_query(points): sql_query = "UPDATE " + TABLE_NAME \ + " SET name = ?, ssid = ?, address = ?, postCode = ?, hpUrl = ?, geoPoint = GeomFromText(?)" + " WHERE id == ?" values = points return execute_sql(sql_query, values) def execute_sql(sql_query, params=(), is_get=False): print(sql_query) try: if is_get: data = pdsql.read_sql(sql_query, con, params=params).to_dict('records') return data else: cur.executemany(sql_query, params) con.commit() return {'sql_status': 'ok'} except sqlite3.Error as e: abort(400) return {'sql_status': 'error'} return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: client = google.cloud.logging.Client(app.config['PROJECT_ID']) # Attaches a Google Stackdriver logging handler to the root logger client.setup_logging(logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Create a health check handler. Health checks are used when running on # Google Compute Engine by the load balancer to determine which instances # can serve traffic. Google App Engine also uses health checking, but # accepts any non-500 response as healthy. @app.route('/_ah/health') def health_check(): return 'ok', 200 # Initalize the OAuth2 helper. oauth2.init_app( app, scopes=['email', 'profile'], authorize_callback=_request_user_info) # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True oauth2.storage.delete() return redirect(request.referrer or '/') # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/books') # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) # Add an error handler that reports exceptions to Stackdriver Error # Reporting. Note that this error handler is only used when Debug # is False @app.errorhandler(500) def server_error(e): client = error_reporting.Client(app.config['PROJECT_ID']) client.report_exception( http_context=error_reporting.build_flask_context(request)) return """ An internal error occurred. """, 500 return app
def create_app(config, ssl=True, debug=False, testing=False, config_overrides=None): app = Flask(__name__, static_folder=os.path.abspath('./static')) app.config.from_object(config) if ssl: SSLify(app) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: pass # Initialize the OAuth2 helper. # ref - https://developers.google.com/identity/protocols/OAuth2WebServer?hl=en#incrementalAuth # ref - https://github.com/google/google-api-php-client/issues/1064 additional_kwargs = { 'include_granted_scopes': 'true', 'access_type': 'offline', 'ApprovalPrompt': 'force' } oauth2.init_app(app, scopes=[ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ], authorize_callback=request_user_info, **additional_kwargs, prompt='consent') # Add a logout handler. @app.route('/logout') def logout(): # Delete the user's profile and the credentials stored by oauth2. del session['profile'] session.modified = True oauth2.storage.delete() return redirect('https://mail.google.com/mail/u/0/?logout&hl=en') # Register the Consent CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/consent') # Add a default root route. @app.route("/") @app.route("/index") def index(): return render_template('index.html') # Add an error handler that reports exceptions to Stackdriver Error # Reporting. Note that this error handler is only used when debug # is False @app.errorhandler(500) def server_error(): return render_template('error.html') return app
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) if not app.testing: client = google.cloud.logging.Client(app.config['PROJECT_ID']) # Attaches a Google Stackdriver logging handler to the root logger client.setup_logging(logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Register the Bookshelf CRUD blueprint. # from .crud import crud # app.register_blueprint(crud, url_prefix='/') # Add a default root route. @app.route("/") def index(): return render_template('index.html') @app.route("/feedback", methods=['GET', 'POST']) def submit_feedback(): if request.method == 'POST': data = request.form.to_dict(flat=True) if len(data['message']) > 1000: flash('Error: Shorten your text description to less than 1000 characters.') return redirect(url_for('index')) feedback = get_model().create(data) flash('Thank you for your feedback') return redirect(url_for('index')) return redirect(url_for('index')) @app.route('/predict', methods=['GET', 'POST']) def predict_file(): if request.method == 'POST': data = request.form.to_dict(flat=True) if len(data['desc']) > 1000: flash('Error: Shorten your text description to less than 1000 characters.') return redirect(url_for('index')) #if 'image' not in request.files: # flash('No file part') # return redirect(url_for('index')) # If an image was uploaded, update the data to point to the new image. # [START image_url] image_file = request.files.get('image') if not image_file: image_url="/static/dogs/default_dog.jpg" image_file = image_url #flash('Error: Please provide an image file.') #return redirect(url_for('index')) dog_vec = default_dog_vec else: image_url = upload_image_file(image_file) img = image.load_img(image_file, target_size=(299, 299)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = preprocess_input(img) dog_vec = generate_dog_features([img, 0]) # [END image_url] # [START image_url2] #image_url = upload_image_file(image_file) data['imageUrl'] = image_url # [END image_url2] data['datetime'] = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%M%S") messages = [data['desc']] best_guess = np.argmax(dog_vec) if best_guess == 114: messages.append("""Are you sure this is a dog? Well, I'll give you recommendations, but I doubt they'll be good.""") data['best_guess'] = int(best_guess) data['best_guess_str'] = index_to_breed[best_guess] dog_text_vec = vectorize_words(embeddings_index, tokenize_input(data['desc'])) image_similarity = cosine_similarity(avg_breed_mat, dog_vec[0]) text_similarity = cosine_similarity(breed_glove_mat, dog_text_vec.reshape(1, -1)) image_max = np.max(image_similarity) text_max = np.max(text_similarity) if image_max: image_similarity /= image_max if text_max: text_similarity /= text_max weight = 0.5 combined_sim = weight*image_similarity + (1-weight)*text_similarity guesses = np.argsort(combined_sim.T)[0][::-1] labels = ["notdog" if guess == 114 else index_to_breed[guess].split("-", 1)[0] for guess in guesses[:3]] breeds = ["not_dog" if guess == 114 else index_to_breed[guess].split("-", 1)[1] for guess in guesses[:3]] urls = [dogtime_url_dict[breed.lower()] for breed in breeds] breeds = [url.split("/")[-1].replace("-", " ").replace("_", " ").title() \ for url in urls] breeds = [breed if breed else "not dogs" for breed in breeds] data['recommendations'] = [int(guess) for guess in guesses[:3]] data['recommendations_str'] = breeds labels_breeds_urls = zip(labels, breeds, urls) dog = get_model().create(data) return render_template('predict_image.html', image_url=image_url, messages=messages, labels_breeds_urls = labels_breeds_urls, timestamp = data['datetime']) return redirect(url_for('index')) # Add an error handler. This is useful for debugging the live application, # however, you should disable the output of the exception for production # applications. #@app.errorhandler(500) def server_error(e): client = error_reporting.Client(app.config['PROJECT_ID']) client.report_exception( http_context=error_reporting.build_flask_context(request)) return """ An internal error occurred. """, 500 return app
from web.cepesp.routes import lang from web.cepesp.routes.api import athena_query_api, athena_status_api, athena_result_api, athena_api, columns_api from web.cepesp.routes.error import handle_error from web.cepesp.routes.filters import asset_filter from web.cepesp.routes.lang import lang from web.cepesp.routes.queries import consulta_tse, consulta_candidatos, consulta_legendas, consulta_votos, \ consulta_bem_candidato, consulta_filiados, consulta_secretarios, consulta_tse_2 from web.cepesp.routes.sql import sql from web.cepesp.routes.static import home, about, others, about_state_secretaries, static_from_root, documentation, \ spatial2_docs from web.cepesp.utils.session import get_locale application = Flask(__name__) application.env = FLASK_ENV application.secret_key = APP_SECRET_KEY application.testing = APP_DEBUG if BUGSNAG_API_KEY: import bugsnag import bugsnag.flask bugsnag.configure(api_key=BUGSNAG_API_KEY, project_root="/web", release_stage=FLASK_ENV) bugsnag.flask.handle_exceptions(application) babel = Babel(application) babel.localeselector(get_locale) application.register_error_handler(Exception, handle_error) application.add_template_filter( lambda fl: asset_filter(fl, application.root_path), "asset")
def app(): app = Flask(__name__) app.testing = True return app
def app(): res = Flask(__name__) res.testing = True return res
) from .database import init_db, db_session from .api import api from .auth import auth from .auth.routes import oauth from .superadmin import superadmin if FLASK_ENV not in DEVELOPMENT_ENVS: # Restrict which hosts we trust when not in dev/test. This works by causing # anything accessing the request URL (i.e. `request.url` or similar) to # throw an exception if it doesn't match one of the values in this list. Request.trusted_hosts = [str(urlparse(HTTP_ORIGIN).hostname)] # pragma: no cover app = Flask(__name__, static_folder=None) app.wsgi_app = ProxyFix(app.wsgi_app) # type: ignore app.testing = FLASK_ENV == "test" T = Talisman( app, force_https_permanent=True, session_cookie_http_only=True, feature_policy="camera 'none'; microphone 'none'; geolocation 'none'", # TODO: Configure webpack to use a nonce: https://webpack.js.org/guides/csp/. content_security_policy={ "default-src": "'self'", "script-src": "'self' 'unsafe-inline'", "style-src": "'self' 'unsafe-inline'", }, ) app.secret_key = SESSION_SECRET init_db()
from wtforms import StringField, PasswordField, SelectField from wtforms.validators import DataRequired from autobook import Autobooker, LoginException DEBUG = os.environ.get("DEBUG", False) SECRET_KEY = os.environ['SECRET_KEY'] RECAPTCHA_PUBLIC_KEY = os.environ['RECAPTCHA_PUBLIC_KEY'] RECAPTCHA_PRIVATE_KEY = os.environ['RECAPTCHA_PRIVATE_KEY'] app = Flask(__name__, static_url_path='', static_folder='static', template_folder='templates') app.config.from_object(__name__) app.testing = DEBUG csrf = CSRFProtect(app) logging.basicConfig(level="INFO", format="%(asctime)s:%(levelname)s: %(message)s") class LoginForm(FlaskForm): username = StringField('Username (email)', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) month = SelectField('Month', coerce=int) recaptcha = RecaptchaField() def get_driver(): chrome_options = ChromeOptions()
) content, headers = _fetch_content_and_headers( path, query, headers={'User-Agent': USER_AGENT}) content = create_standard_json_from_metno(content, days) else: # WWO tweaks query_string += "&extra=localObsTime" query_string += "&includelocation=yes" content, headers = _fetch_content_and_headers(path, query) content = add_translations(content, lang) return content, 200, headers if __name__ == "__main__": #app.run(host='0.0.0.0', port=5001, debug=False) #app.debug = True if len(sys.argv) == 1: bind_addr = "0.0.0.0" SERVER = WSGIServer((bind_addr, PROXY_PORT), APP) SERVER.serve_forever() else: print('running single request from command line arg') APP.testing = True with APP.test_client() as c: resp = c.get(sys.argv[1]) print('Status: ' + resp.status) # print('Headers: ' + dumps(resp.headers)) print(resp.data.decode('utf-8'))
# /users/?roles=~Admin # GET /users/?name=[Jane,John] # post patch and put with a form data # -- features needs to be implemented # -- Not yet implemented # sort after multiple fields and use '-' for signaling descending order # GET /users/?roles=#0 # find value in array (simple and complex array) # search in structures ?subelement.field = 3 # test not just date but time too # -- # todo: try class based discovery before regular expression matching flask_app = Flask(__name__) flask_app.config['SECRET_KEY'] = 'S0m3S3cr3tC0nt3nt!' flask_app.testing = True @pytest.fixture def app(): return flask_app @pytest.fixture def user_dict(): return { "birth_date": "1980-06-30T00:00:00", "description": "some description", "name": "some_user", "password": "******", "roles": ["User", "Admin", "Operator"]
import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration sentry_sdk.init(integrations=[FlaskIntegration()], traces_sample_rate=0.1) # Set up database if not testing if not TEST_MODE: database.DB.initialize_database(user=os.environ['OPENDC_DB_USERNAME'], password=os.environ['OPENDC_DB_PASSWORD'], database=os.environ['OPENDC_DB'], host=os.environ.get( 'OPENDC_DB_HOST', 'localhost')) # Set up the core app FLASK_CORE_APP = Flask(__name__) FLASK_CORE_APP.testing = TEST_MODE FLASK_CORE_APP.config['SECRET_KEY'] = os.environ['OPENDC_FLASK_SECRET'] FLASK_CORE_APP.json_encoder = JSONEncoder # Set up CORS support CORS(FLASK_CORE_APP) compress = Compress() compress.init_app(FLASK_CORE_APP) SOCKET_IO_CORE = flask_socketio.SocketIO(FLASK_CORE_APP, cors_allowed_origins="*") API_VERSIONS = {'v2'}
import os, sys from flask import Flask, flash, request, redirect, url_for, send_from_directory from flask import render_template from werkzeug.utils import secure_filename from subprocess import call, check_output reload(sys) sys.setdefaultencoding('utf8') UPLOAD_FOLDER = './uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf']) SERVER_PORT = 5001 app = Flask(__name__) app.secret_key = b'*l/fjsd%9feFJ23ยง$8wr9sjf09' app.testing = True app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['SERVER_PORT'] = SERVER_PORT def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/index') @app.route('/') def index(): return redirect('/upload')
def create_app(config, debug=False, testing=False, config_overrides=None): app = Flask(__name__) app.config.from_object(config) app.debug = debug app.testing = testing if config_overrides: app.config.update(config_overrides) # Configure logging if not app.testing: logging.basicConfig(level=logging.INFO) # Setup the data model. with app.app_context(): model = get_model() model.init_app(app) # Register the Bookshelf CRUD blueprint. from .crud import crud app.register_blueprint(crud, url_prefix='/hotels') #DO SAME REGISTRATION FOR ALL COMPONENTS # Add a default root route. @app.route("/") def index(): return redirect(url_for('crud.list')) # Add an error handler. This is useful for debugging the live application, # however, you should disable the output of the exception for production # applications. @app.errorhandler(500) def server_error(e): return """ An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.format(e), 500 @app.context_processor def processorDef(): def format_pics(pics): return pics.split(',')[0] return dict(format_pics=format_pics) @app.context_processor def processorDef(): def format_str(string1, index): return string1.split(',')[index] return dict(format_str=format_str) from .model_cloudsql import hotelSchema, customerSchema, db from flask_graphql import GraphQLView app.add_url_rule('/graphql/hotels', view_func=GraphQLView.as_view( 'graphqlHotel', schema=hotelSchema, graphiql=True, context={'session': db.session})) app.add_url_rule('/graphql/customers', view_func=GraphQLView.as_view( 'graphqlCustomer', schema=customerSchema, graphiql=True, context={'session': db.session})) @app.teardown_appcontext def shutdown_session(exception=None): db.session.remove() return app
try: import flask_social_blueprint except ImportError: # in case we run it from the repo, put that repo on path import sys sys.path.append( os.path.join(os.path.dirname(os.path.dirname(SRC_DIR)), "src")) from flask import Flask app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder=STATIC_FOLDER, static_url_path=STATIC_URL) app.debug = DEBUG app.testing = DEBUG # WARNING: this will disable login_manager decorators # ------------------------------------------------------------- # Load settings from separate modules # ------------------------------------------------------------- import website.settings app.config.from_object(website.settings) config = "website.settings_prd" if PRODUCTION else "website.settings_dev" import importlib try: cfg = importlib.import_module(config) logging.debug("Loaded %s" % config) app.config.from_object(cfg) except ImportError: