def create_app(config_name): app = Flask(config_name) app.config.from_object(config[config_name]) config[config_name].init_app(app) Markdown(app) _dir = os.path.dirname(os.path.abspath(__file__)) app.template_folder = os.path.join(_dir, "templates") app.static_folder = os.path.join(_dir, "static") return app
def create_app(source=None, config=None): app = Flask("flaskrst") # Set default config values app.config.setdefault('MODULES', {}) app.config.setdefault('STYLESHEETS', []) app.config.setdefault('FEEDS', []) # Load config if config: app.config.from_pyfile(config) config_loaded = True # maybe there is a file declared by env elif 'FLASK_RST_CONFIG' in os.environ: app.config.from_envvar('FLASK_RST_CONFIG') config_loaded = True # no config loaded try again later after source setting else: config_loaded = False # Set source path if source: app.config['SOURCE'] = source elif 'FLASK_RST_SOURCE' in os.environ: app.config['SOURCE'] = os.environ['FLASK_RST_SOURCE'] else: # Use current working directory as source app.config['SOURCE'] = os.getcwd() # If no config already loaded than is a config maybe in source path if not config_loaded: config_path = os.path.join(app.config['SOURCE'], 'config.py') app.config.from_pyfile(config_path, silent=True) # Set path of static folder if 'STATIC_FOLDER' in app.config: app.static_folder = app.config['STATIC_FOLDER'] else: # Is a static folder called _static in source path? source_static_folder = os.path.join(app.config['SOURCE'], "_static") if os.path.isdir(source_static_folder): app.static_folder = source_static_folder # Load flask-rst modules manager.init_app(app) manager.load_from_config() # Add some jinja globals and context processors app.jinja_env.globals['date'] = date app.context_processor(inject_navigation) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 return app
def create_app(config=None): app = Flask( __name__, template_folder='templates') app.config.from_pyfile('_settings.py') if isinstance(config, dict): app.config.update(config) elif config: app.config.from_pyfile(os.path.abspath(config)) app.static_folder = app.config.get('STATIC_FOLDER') app.config.update({'SITE_TIME': datetime.utcnow()}) register_hooks(app) register_jinja(app) register_database(app) register_mail(app) register_admin(app) register_routes(app) register_whoosh(app) # register_babel(app) return app
def create_app(config=None): app = Flask(__name__, template_folder='views') app.static_folder = os.path.abspath('static') app.config.from_pyfile('configs/default.py') production_config = os.path.join(os.path.dirname(__file__), 'configs/production.py') if os.path.exists(production_config): app.config.from_pyfile(production_config) if isinstance(config, dict): app.config.update(config) elif config: app.config.from_pyfile(os.path.abspath(config)) register_hook(app) register_celery(app) register_celery_beat(app) register_oauth(app) register_curator(app) register_jinja2(app) register_database(app) register_route(app) return app
def create_app(): app = Flask( __name__.split('.')[0], template_folder='../templates', static_url_path=None, static_folder=None ) env = Development if os.environ.get('APPLICATION_ENV', '') == 'Production': env = Production app.config.from_object(env) # Load config items into jinja settings for key, val in app.config.items(): if key.startswith('JINJA'): setattr(app.jinja_env, key[6:].lower(), val) register_controllers(app) register_errorhandlers(app) register_extensions(app) app.static_folder = '../public/' app.add_url_rule(app.config['STATIC_URL_PATH'] + '/<path:filename>', endpoint='static', view_func=app.send_static_file ) signal.signal(signal.SIGUSR1, sig_handler) signal.signal(signal.SIGUSR2, sig_handler) return app
def create_app(config_name): app = Flask(config_name) app.config.from_object(config[config_name]) config[config_name].init_app(app) app_admin.init_app(app) babel.init_app(app) celery.init_app(app) bootstrap.init_app(app) db.init_app(app) with app.app_context(): print current_app.name db.create_all() login_manager.init_app(app) app_admin.base_template = 'layout.html' from main import main as main_blueprint from admin import admin as admin_blueprint from auth import auth as auth_blueprint app.register_blueprint(main_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') import os.path _dir = os.path.dirname(os.path.abspath(__file__)) app.template_folder = os.path.join(_dir, 'templates') app.static_folder = os.path.join(_dir, 'static') return app
def create_app(config=None): config = 'dev' if config is None else config app = Flask(__name__) app.config.from_object('main.config.' + config) # DB global db db = Connection(app.config['MONGO_HOST'], app.config['MONGO_PORT'])[app.config['MONGO_DB']] # Cache global cache cache = redis.Redis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB']) # Static resources app.static_folder = app.config['STATIC_DIR'] # Templating app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') from main.server.controllers import gui, api app.register_blueprint(gui.blueprint) app.register_blueprint(api.blueprint, url_prefix='/api') return app
def create_app(config=None): config = 'dev' if config is None else config app = Flask(__name__) app.config.from_object('glu.config.' + config) # Static content app.static_folder = app.config.get('STATIC_DIR', 'assets') # Use pyjade templates app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') # Cache global cache cache = redis.Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) from glu.views.api import api from glu.views.site import site app.register_blueprint(site) app.register_blueprint(api, url_prefix='/api') return app
def createApp(): app = Flask(__name__, template_folder=config.TEMPLATE_FOLDER, static_folder=config.STATIC_FOLDER) app.config.from_object(config) app.template_folder = app.config['TEMPLATE_FOLDER'] app.static_folder = app.config['STATIC_FOLDER'] return app
def create_app(config_name): app = Flask(__name__, static_url_path='') app.static_folder = 'static' app.template_folder = 'templates' config[config_name].init_app(app) app.config.from_object(config[config_name]) db.init_app(app) login_manager.init_app(app) login_manager.session_protection = 'basic' login_manager.login_view = 'user.login' principal.init_app(app) identity_config(app) toolbar.init_app(app) cdn.init_app(app) app.jinja_env.filters['date'] = date from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .user import user as user_blueprint app.register_blueprint(user_blueprint) from .vendor import vendor as vendor_blueprint app.register_blueprint(vendor_blueprint, url_prefix='/vendor') from .item import item as item_blueprint app.register_blueprint(item_blueprint, url_prefix='/item') from .distributor import distributor as distributor_blueprint app.register_blueprint(distributor_blueprint, url_prefix='/distributor') from .operation import operation as operation_blueprint app.register_blueprint(operation_blueprint, url_prefix='/operation') from .privilege import privilege as privilege_blueprint app.register_blueprint(privilege_blueprint, url_prefix='/privilege') from .service import service as service_blueprint app.register_blueprint(service_blueprint, url_prefix='/service') @app.after_request def set_csrf_token_cookie(response): csrf_token = getattr(request, 'csrf_token', None) if csrf_token is not None: response.set_cookie('csrf_token', csrf_token, max_age=3600) return response @app.errorhandler(404) def page_not_found(error): return render_template('user/404.html'), 404 if config_name != 'testing': from app import statisitc with app.app_context(): statisitc.init_statistic() return app
def watch(self): # Setup Flask app, which will be our dev server from flask import Flask server = Flask(__name__, static_folder="dist") server.static_folder = self.dist @server.route(self.url_prefix) def index(): return server.send_static_file('index.html') @server.route('%s<path:path>' % self.url_prefix) def everything_else(path): # urls that end with a / are prolem index-wrapping if path.endswith("/"): path = "%sindex.html" % path try: # send_static_file will guess the correct MIME type return server.send_static_file(path) except NotFound: # If the file doesn't exist, assume it should # be an html file. return server.send_static_file("%s.html" % path) # Assign self to closure variable parent = self class RenderOnChangeHandler(FileSystemEventHandler): """ Restart and when anything in src changes. """ def on_modified(self, *args, **kwargs): parent.render() # Loading templates and classes over and over # causes gradual memory usage to creep up. # The garbage collector should fire every # after automatic renders to prevent this. gc.collect() # Setup observer logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') observer = Observer() observer.schedule(RenderOnChangeHandler(), self.src, recursive=True) observer.start() try: # Run Simple python server server.run() except KeyboardInterrupt: observer.stop() observer.join()
def create_app(): ''' Create flask app.''' app = Flask(__name__) app.config.from_object(config) app.template_folder = app.config['TEMPLATE_FOLDER'] app.static_folder = app.config['STATIC_FOLDER'] return app
def create_app(): select_default_settings() app = Flask(__name__) app.config.from_object(os.environ.get('MINIFICTION_SETTINGS')) default_handler.setLevel(app.config['LOGLEVEL']) logging.basicConfig(level=app.config['LOGLEVEL'], format=app.config['LOGFORMAT']) app.static_folder = app.config['STATIC_ROOT'] app.extra_css = [] app.extra_js = [] if app.config['UMASK'] is not None: if isinstance(app.config['UMASK'], str): app.config['UMASK'] = int(app.config['UMASK'], 8) os.umask(app.config['UMASK']) if app.config['TESTING']: if not os.path.isdir(app.config['TESTING_DIRECTORY']): os.makedirs(app.config['TESTING_DIRECTORY']) elif os.listdir(app.config['TESTING_DIRECTORY']): raise RuntimeError('Testing directory %r is not empty' % app.config['TESTING_DIRECTORY']) init_bl() configure_user_agent(app) configure_i18n(app) configure_cache(app) configure_forms(app) configure_users(app) configure_error_handlers(app) configure_views(app) configure_admin_views(app) configure_ajax(app) configure_errorpages(app) configure_templates(app) if not app.config['SPHINX_DISABLED']: configure_search(app) configure_celery(app) configure_captcha(app) configure_story_voting(app) configure_misc(app) configure_development(app) configure_frontend(app) configure_sidebar(app) app.context_processor(templates_context) init_plugins(app) database.configure_for_app(app) return app
def create_app(): """Create the Flask app.""" app = Flask("modelconvert", static_folder=None) app.config.from_object('modelconvert.settings') app.config.from_envvar('MODELCONVERT_SETTINGS', silent=True) # configure custom static path for serving files during # development app.static_folder = app.config['STATIC_PATH'] app.add_url_rule('/static/<path:filename>', endpoint='static', view_func=app.send_static_file) # custom template path, fall back to default jinja_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(app.config['TEMPLATE_PATH']), app.jinja_loader, ]) app.jinja_loader = jinja_loader configure_logging(app) app.register_blueprint(frontend) app.register_blueprint(api, url_prefix='/api') celery.add_defaults(app.config) # configure error handlers @app.errorhandler(403) def forbidden_page(error): return render_template("403.html"), 403 @app.errorhandler(404) def page_not_found(error): return render_template("404.html"), 404 @app.errorhandler(500) def server_error_page(error): return render_template("500.html"), 500 if app.config['DEBUG']: from werkzeug.wsgi import SharedDataMiddleware app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/preview': app.config["DOWNLOAD_PATH"] }) return app
def create_app(config=None, app_name=None): if app_name is None: app_name = DEFAULT_APP_NAME app = Flask(app_name) app.template_folder = os.path.join(os.path.dirname(__file__), '_templates') app.static_folder = os.path.join(os.path.dirname(__file__), "_static") configure_app(app, config) configure_extensions(app) configure_template_filters(app) configure_blue_print(app, DEFAULT_BLUEPRINTS) return app
def create_app(config=None): app = Flask(__name__, template_folder='templates') app.config.from_pyfile('config.py') env = EnvConfig() env.init_app(app, 'BOOKMARKS_') if isinstance(config, dict): app.config.update(config) elif config: app.config.from_pyfile(os.path.realpath(config)) app.static_folder = app.config.get('STATIC_FOLDER') register_exts(app) register_bps(app) return app
def create_app(): app = Flask(__name__, template_folder='views') app.static_folder = os.path.abspath('public') app.config.from_pyfile('../config/default.py') register_database(app) register_csrf(app) register_jwt(app) register_socketio(app) register_routes(app) register_api(app) register_view_filters(app) reigster_not_found(app) return app
def create_app(config=None): config = 'dev' if config is None else config app = Flask(__name__) app.config.from_object('main.config.' + config) # Static resources app.static_folder = app.config['STATIC_DIR'] # Templating app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') from main.server.controllers import gui, api app.register_blueprint(gui.blueprint) app.register_blueprint(api.blueprint, url_prefix='/api') return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) # import and register main app from core import core app.register_blueprint(core) # --- # import and register packages # from packages.auth import auth # app.register_blueprint(main_blueprint) # --- # Set views folders app.template_folder = app.config['TEMPLATES_FOLDER'] app.static_folder = app.config['STATIC_FOLDER'] return app
def create_app(config=None): app = Flask(__name__, template_folder='templates',) app.config.from_pyfile('_settings.py') if 'ARCTIC_SETTINGS' in os.environ: app.config.from_envvar('ARCTIC_SETTINGS') if isinstance(config, dict): app.config.update(config) elif config: app.config.from_pyfile(os.path.abspath(config)) app.static_folder = app.config.get('STATIC_FOLDER') app.config.update({'SITE_TIME': datetime.datetime.utcnow()}) #register_jinja(app) #register_babel(app) register_routers(app) register_log(app) return app
def create_app(config=None): app = Flask(__name__) config = config or {} app.config.update(config) app.static_folder = app.config.get(keys.STATIC_FOLDER) app.api = get_api_instance(app.config) flask_gravatar.Gravatar(app) env = ViewEnvironment(app.api, app.config) app.register_blueprint(lang.create_blueprint(env), url_prefix='/lang') app.register_blueprint(auth.create_blueprint(env), url_prefix='/auth') app.register_blueprint(users.create_blueprint(env), url_prefix='/users') app.register_blueprint(games.create_blueprint(env), url_prefix='/games') app.register_blueprint(teams.create_blueprint(env), url_prefix='/teams') app.register_blueprint(notifications.create_blueprint(env), url_prefix='/notifications') create_logger(app) create_filters(app) create_bundles(app) create_main_views(app) initialize_cloudinary(app) return app
def create_app(mode="production", static_path="./static", templates_path="./templates", instance_path="./instance") -> Flask: import os # from .utils.celery_maker import make_celery # from .utils.fileChecker import fileChecker from .utils.verify_user_constrains import verify from src.database.db import init_app, distroy_db, init_db from warnings import warn from werkzeug.utils import ImportStringError app = Flask(__name__) # configuring application app.config.from_object("configs.default_settings") if mode == "development": app.config.from_object("configs.development_settings") else: if mode != "production": warn("FLASK_ENV was set as an unrecognized value, " + "application is falling back on production mode") try: app.config.from_object("configs.production_settings") except ImportStringError: pass # call in the verify function to validate application configuration verify(app) # if the secret key is none or the mode is production # we want to get the secret key from the environment variable if app.config.get('SECRET_KEY') is None \ or mode == "production": if os.environ.get("SURVISTA_SECRET_KEY") is None: if mode == "production": raise ValueError( "SURVISTA_SECRET_KEY must be set as an environment " + "variable for production environments") else: raise ValueError( "SECRET_KEY was not set in the settings thus must be " + "provided in the SURVISTA_SECRET_KEY environment variable") app.config['SECRET_KEY'] = os.environ['SURVISTA_SECRET_KEY'] elif os.environ.get('SURVISTA_SECRET_KEY') is not None: app.config['SECRET_KEY'] = os.environ['SURVISTA_SECRET_KEY'] if app.config.get("NEOMODEL_DATABASE_URI") is None \ or mode == "production": if os.environ.get('SURVISTA_NEOMODEL_DATABASE_URI') is None: if mode == "production": raise ValueError( "SURVISTA_NEOMODEL_DATABASE_URI must be set as an " + "environment variable for production environments") else: raise ValueError( "NEOMODEL_DATABASE_URI was not set in the settings " + "thus must be provided in the " + "SURIVISTA_NEOMODEL_DATABASE_URI environment variable") app.config['NEOMODEL_DATABASE_URI'] = \ os.environ['SURVISTA_NEOMODEL_DATABASE_URI'] elif os.environ.get("SURVISTA_NEOMODEL_DATABASE_URI") is not None: app.config['NEOMODEL_DATABASE_URI'] = \ os.environ['SURVISTA_NEOMODEL_DATABASE_URI'] if not os.path.isabs(static_path): static_path = os.path.abspath(static_path) if not os.path.isdir(static_path): raise FileNotFoundError( f'static folder was not able to be found {static_path}') app.static_folder = static_path if not os.path.isabs(templates_path): templates_path = os.path.abspath(templates_path) if not os.path.isdir(templates_path): raise FileNotFoundError('templates folder was not able to be found') app.template_folder = templates_path if not os.path.isabs(instance_path): instance_path = os.path.abspath(instance_path) if not os.path.isdir(instance_path): os.mkdir(instance_path) app.instance_path = instance_path init_app(app) @app.cli.command("init-db") def initialise_database(): init_db(app) @app.cli.command("teardown-db") def distroy_database(): distroy_db(app) # Celery configuration area return app
from flask import Flask, session, request, jsonify, render_template import os, json app = Flask('alpa') app.static_folder = '/root/static' app.template_folder = '/root/templates' app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' #@app.before_first_request #def _declareStuff(): # if not os.path.exists(os.path.join(app.static_folder, 'data.json')): # with open(os.path.join(app.static_folder, 'data.json'), 'w'): pass @app.route("/") def hello(): return render_template('index.html') @app.route("/retrieve", methods=['GET', 'POST']) def retrieve(): if request.method == 'POST': req_data = request.get_json() data = {} filename = os.path.join(app.static_folder, 'data.json') if os.stat(filename).st_size != 0: with open(filename) as blog_file: data = json.load(blog_file) if req_data['server'] in data: ses = data[req_data['server']] total = ses['total']
#https://zonacoding.com/article/penerapan-mvc-di-flask-python from flask import Flask ## import Flask dari package flask app = Flask(__name__) app.static_folder = 'static' from app.controllers import *
import glob import logging import sys LOG_FORMAT = "%(asctime)s %(levelname)s %(pathname)s %(lineno)d: %(message)s" app = Flask(__name__) app.config.from_object(util.get_config(sys.argv[2])) app.register_blueprint(awards) app.register_blueprint(champions) app.register_blueprint(h2h_records) app.register_blueprint(matchup_history) app.register_blueprint(playoffs) app.register_blueprint(recap) app.register_blueprint(standings) app.static_folder = "web/static" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = app.config.get("DB_URI") db.init_app(app) query = Query(db) app.config['QUERY'] = query @app.template_filter() def points_format(value): return "{:,}".format(value) @app.template_filter() def percentage_format(value): return "{:.4f}".format(value)
def wants_json(self): mimes = json_mimetypes mimes.append('text/html') best = self.accept_mimetypes.best_match(mimes) return best in json_mimetypes and \ self.accept_mimetypes[best] > \ self.accept_mimetypes['text/html'] app = Flask(__name__) app.config.from_object(config) app.request_class = JSONRequest app.jinja_env.filters['datetime'] = format_datetime app.jinja_env.filters['isodatetime'] = lambda d: d.isoformat() + 'Z' app.jinja_env.filters['format_currency'] = format_currency app.static_folder = 'static' redis_conn = redis.from_url(app.config['REDIS_URL']) app.session_interface = session.RedisSessionInterface(redis_conn) csrf = SeaSurf(app) db = SQLAlchemy(app) migrate = Migrate(app, db) login_manager = LoginManager() login_manager.login_view = "auth.login" login_manager.init_app(app) from wuvt import admin app.register_blueprint(admin.bp, url_prefix='/admin')
from flask import Flask, render_template, request app = Flask(__name__) app.static_folder = '../static' @app.route('/', methods=['GET', 'POST']) def form(): return render_template('form.html') @app.route('/hello', methods=['GET', 'POST']) def hello(): return render_template('greeting.html', say=request.form['say'], to=request.form['to'], campus=request.form['campus']) if __name__ == '__main__': app.run()
import os from pathlib import Path from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.template_folder = os.path.abspath('./frontend/templates') app.static_folder = os.path.abspath('./frontend/static') app.secret_key = "DOC_PATTERN_LABELING_KEY" ## SQLite Database db_path = os.path.join(os.path.dirname(__file__), '../db/app.sqlite') Path(db_path).parent.mkdir(parents=True, exist_ok=True) db_uri = 'sqlite:///{}'.format(db_path) # sqlite:////absolute/path/to/foo.db app.config['SQLALCHEMY_DATABASE_URI'] = db_uri app.config[ 'SQLALCHEMY_ECHO'] = False # Set this configuration to True if you want to see all of the SQL generated. app.config[ 'SQLALCHEMY_TRACK_MODIFICATIONS'] = False # To suppress this warning db = SQLAlchemy(app) # Why imported at very end? # The bottom import is a workaround to circular imports, a common problem with Flask applications. # route.py needs to import the 'app' variable defined in this script, so putting one of the reciprocal imports at # the bottom avoids the error that results from the mutual references between these two files. from src import routes from src.database import models, initdb
import os import re import datetime from flask import (Flask, request, abort, url_for, redirect, session, render_template, flash) from flask_restful import (reqparse, abort, Api, Resource, fields, marshal_with) from flask import request app = Flask(__name__) app.static_folder = 'project_files/budget/static' app.template_folder = 'project_files/budget/templates' api = Api(app) app.config.update(dict(DEBUG=True, SECRET_KEY='development key')) #--------------------------------------------------------- # Data setup: purchases = {} categories = {} #--------------------------------------------------------- # Resources: purchase_parser = reqparse.RequestParser(bundle_errors=True) purchase_parser.add_argument('name', type=str, required=True, location='json') purchase_parser.add_argument('amount', type=float, required=True, location='json')
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager app = Flask(__name__) app.debug = True app.template_folder = 'templates' app.static_folder = 'templates/static' app.config['SECRET_KEY'] = 'L1bR4rY_M4N4g3m3nt' app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/library?charset=utf8' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['PER_PAGE'] = 10 db = SQLAlchemy(app) login_manager = LoginManager(app) login_manager.login_view = "app.view.login" from .view import view as view_blueprint app.register_blueprint(view_blueprint) from app.models import Admin @login_manager.user_loader def load_user(userid): return Admin.get(userid)
import os import sys import logging from uuid import uuid4 from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = 'qwertyuioplkjhgfdsazxcvbnm' root_path = os.path.abspath('.') sys.path.insert(0, root_path) app.static_folder = os.path.join(app.root_path, "static") db = SQLAlchemy(app) import heroku_db logging.basicConfig(level=logging.INFO) Env = 'live' if Env == 'dev': app.debug = True app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/vbi' else: app.debug = False app.config['SQLALCHEMY_DATABASE_URI'] = heroku_db.db_config app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False import routes
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger utils.setLogFileName() log = logpy.logging.getLogger(__name__) template_dir = os.path.abspath('./resource/university/') # setting for render_template app = Flask(__name__, template_folder=template_dir) # app.config['UPLOAD_FOLDER'] = './univer/upload' app.config['MAX_CONTENT_LENGTH'] = 128 * 1024 * 1024 # 16MB api = Api(app) controller.setup_route(api) controller_sso.setup_route(api) controller_recaptcha.setup_route(api) controller_university.setup_route(api) # setting for send_from_directory app.static_folder = os.path.abspath("resource/university/") app.static_url_path = os.path.abspath("resource/university/") app.config['CORS_HEADERS'] = 'Content-Type' if __name__=="__main__": # utils.setLogFileName() try: if not os.path.exists("./data_for_KG/"): os.makedirs("./data_for_KG/") except OSError as e: log.info(e) sched = BackgroundScheduler() sched.start() sched.add_job(utils.setLogFileName, CronTrigger.from_crontab('59 23 * * *')) # controller.transmitProcess(None) # sched.add_job(controller.transmitProcess, CronTrigger.from_crontab(const.TRANSMIT_CRON), [None])
import os from flask import Flask, jsonify, abort, make_response, render_template from flask_httpauth import HTTPBasicAuth app = Flask(__name__, static_url_path="") # pylint: disable=invalid-name app.config.from_object("config") app.debug = True auth = HTTPBasicAuth() # pylint: disable=invalid-name # This is the path to the upload directory app.config["UPLOAD_FOLDER"] = "uploads" # These are the extension that we are accepting to be uploaded app.config["ALLOWED_EXTENSIONS"] = set( ["txt", "pdf", "png", "jpg", "jpeg", "gif", "py"]) # create upload folder if not exist if not os.path.exists(app.config["UPLOAD_FOLDER"]): os.makedirs(app.config["UPLOAD_FOLDER"]) # redefine jinja start/end string to avoid conflict with AngularJS app.jinja_env.variable_start_string = "{[{ " app.jinja_env.variable_end_string = " }]}" # use different static/templates folder with different mode if not app.debug: app.template_folder = "build/templates" app.static_folder = "build/static" else: app.template_folder = "src/templates" app.static_folder = "src/static"
import os import xbmcaddon from flask import Flask __addonpath__ = xbmcaddon.Addon(id="script.webui").getAddonInfo("path") app = Flask(__name__) app.root_path = __addonpath__ app.static_path = "/static" app.static_folder = os.path.join(__addonpath__, "resources", "static") app.template_folder = os.path.join(__addonpath__, "resources", "templates") app.add_url_rule(app.static_path + "/<path:filename>", endpoint="static", view_func=app.send_static_file) from jinja2 import FileSystemLoader app.jinja_loader = FileSystemLoader(os.path.join(__addonpath__, "resources", "templates"))
import os from flask import Flask, jsonify, abort, make_response, render_template from flask_httpauth import HTTPBasicAuth app = Flask(__name__, static_url_path="") # pylint: disable=invalid-name app.config.from_object("config") app.debug = True auth = HTTPBasicAuth() # pylint: disable=invalid-name # This is the path to the upload directory app.config["UPLOAD_FOLDER"] = "uploads" # These are the extension that we are accepting to be uploaded app.config["ALLOWED_EXTENSIONS"] = set(["txt", "pdf", "png", "jpg", "jpeg", "gif", "py"]) # create upload folder if not exist if not os.path.exists(app.config["UPLOAD_FOLDER"]): os.makedirs(app.config["UPLOAD_FOLDER"]) # redefine jinja start/end string to avoid conflict with AngularJS app.jinja_env.variable_start_string = "{[{ " app.jinja_env.variable_end_string = " }]}" # use different static/templates folder with different mode if not app.debug: app.template_folder = "build/templates" app.static_folder = "build/static" else: app.template_folder = "src/templates" app.static_folder = "src/static"
from flask import Flask import os, sys, subprocess # import custom file from constants import Constants app = Flask(__name__, static_url_path=None) app.static_url_path='/templates/static' app.static_folder = app.root_path + app.static_url_path from routes import Routes if __name__ == '__main__': app.run(host='0.0.0.0', port=33, debug=True)
""" Endpoint where sending chat messages which get passed into the database. :return: Either a generic 200 response or 401 depending on whether or not user is properly logged in. """ if session and session["logged_in"]: username = session["username"] json_data = request.get_json() message = json_data["message"] m.store_message(username, message) okay = make_response("") return okay else: error = make_response("") error.data = "not allowed to send the message" error.status_code = 401 return error @app.route("/getmessages", methods=["GET"]) def get_messages(): """ Grab all the chat messages and send it back to the chat interface as json. :return: json chat messages """ return jsonify({"messages": m.Messages}) if __name__ == "__main__": app.static_folder = "../static/" app.run("0.0.0.0", debug=True)
from flask import Flask,render_template, request, url_for from durable.lang import * import string #app aconfiguration app = Flask(__name__) app.debug = True app.static_folder = 'static' #static folder enabled cardstatus = "" #global variable to hold the card status card_number = "" #function to alter the global variale data def get_response(val): global cardstatus cardstatus = val #durable rules built to detect the card with ruleset('CardDetect'): @when_all(m.subject.matches('3[47][0-9]{13}')) def amex(c): get_response("Amex Card") @when_all(m.subject.matches('4[0-9]{12}([0-9]{3})?')) def visa(c): get_response("Visa Card") @when_all(m.subject.matches('(5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|2720)[0-9]{12}')) def mastercard(c): get_response("Master Card")
upc = request.args.get("product_upc") name = request.args.get("product_name") manufacturer = request.args.get("product_manufacturer") ingredients = request.args.get("product_ingredients") default_source = "user:"******"REMOTE_ADDR"] date = time.strftime("%m/%d/%y %T") entry_tuple = (name, default_source, upc, manufacturer, date, ingredients) command = """INSERT INTO Experimental(item, data_source, gtin_upc, manufacturer, date_modified, ingredients) Values(?,?,?,?,?,?)""" connection = sqlite3.connect("food_db.db") cur = connection.cursor() cur.execute(command, entry_tuple) connection.commit() connection.close() return render_template("product_submission.html", prod_name=name, prod_upc=upc) @app.route("/submit_product.html") def route_product_page(): return render_template("submit_product.html") if __name__ == "__main__": app.static_folder = "static" app.run(debug=True)
flash("<b>Invalid login details!</b>", "danger") else: referrer = request.referrer or url_for("index") return render_template("login.html", referrer=referrer) @app.route('/logout') def logout(): session.pop('user', None) session.pop('admin', None) return redirect(request.referrer or url_for("index")) @app.context_processor def register_helpers(): return {"is_authorized_for": lambda owner: is_authorized(owner, session)} if not os.path.isfile("/var/lib/ffmap/secret_key"): open("/var/lib/ffmap/secret_key", "wb").write(os.urandom(24)) os.chmod("/var/lib/ffmap/secret_key", 0o600) app.secret_key = open("/var/lib/ffmap/secret_key", "rb").read() if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) else: app.template_folder = "/usr/share/ffmap/templates" app.static_folder = "/usr/share/ffmap/static" #app.debug = True
from flask_pymongo import PyMongo import xgboost as xgb import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import seaborn as sns import joblib from sklearn.preprocessing import MinMaxScaler, StandardScaler, LabelEncoder linear_model = joblib.load("models/LR.h5") xgb_model = joblib.load("models/xgbmodel.h5") #rf_model = joblib.load("models/rf.h5") app = Flask(__name__) app.static_folder = "templates/static" @app.route("/") def index(): return render_template("index.html") @app.route("/predict", methods=["GET", "POST"]) def predict(): if request.method == "POST": testdf = [] boroughtype = int(request.form["boroughradio"]) roomtype = int(request.form["roomtyperadio"]) review_input = request.form["reviewmonth"] avail_input = request.form["availability"]
# # improved from: https://codepen.io/asommer70/post/serving-a-static-directory-with-flask # # Flask server, woo! # from flask import Flask, request, redirect, url_for, send_from_directory import logging _moduleLogger = logging.getLogger(__name__) _moduleLogger.addHandler(logging.NullHandler()) # Setup Flask app. app = Flask(__name__) app.debug = True app.static_folder = '.' # Routes @app.route('/') def root(): _moduleLogger.debug('Serving Index') return app.send_static_file('index.html') @app.route('/<path:file>') def static_proxy(file): # send_static_file will guess the correct MIME type # _moduleLogger.debug('Path: %s', path) _moduleLogger.debug('File: %s', file) # dest = os.path.join(path, file.strip('/'))
# @Docs : main # @Source : from flask import Flask, Blueprint from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from flask_sqlalchemy import SQLAlchemy import config from . import common from . import extends from . import plugins logger = common.ConsoleLogger('flask') app = Flask(__name__) app.static_folder = config.STATIC_FOLDER app.template_folder = config.TEMPLATE_FOLDER app.secret_key = '1!@#$%^&*()' app.config.from_object(config) db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) def __register_blueprint_models(): # 注册模块信息 try: from .views import BLUEPRINT_MODELS if not isinstance(BLUEPRINT_MODELS, (tuple, list, set)): raise AssertionError(
from pathlib import Path from flask import Flask, render_template, request, jsonify from flask_cors import CORS from tpe import * import json app = Flask(__name__) CORS(app) # setup directories app_dir = Path(app.root_path) app.template_folder = app_dir.parent / "build" app.static_folder = app_dir.parent / "build" / "static" root_dir = app_dir.parent / "tpe-server" / "new_cfgen" @app.route("/") def homepage(): return render_template("index.html") @app.route("/generate_markov", methods=["POST"]) def generate_markov(): request_data = json.loads(request.data) text_name = request_data.get("textName") current = request_data.get("current") n = request_data.get("n") complete_sentence = request_data.get("completeSentence") print(text_name) assert len(current) >= n or len(current) == 0 m = MarkovChain(n=n, root_path=root_dir)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import json from os.path import dirname from os.path import join from flask import Flask from app.dashboard.views import DashboardResource app = Flask(__name__) app.template_folder = join(dirname(__file__), 'templates') app.static_folder = join(dirname(__file__), 'static') class UserConfig(dict): """ loads the json configuration file """ def _string_decode_hook(self, data): rv = {} for key, value in data.iteritems(): if isinstance(key, unicode): key = key.encode('utf-8') if isinstance(value, unicode): value = value.encode('utf-8') rv[key] = value return rv def __init__(self): dict.__init__(self)
""" # 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,OPTIONS') response.headers.add('Access-Control-Allow-Credentials', 'true') response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Pragma"] = "no-cache" response.headers["Expires"] = "0" response.headers['Cache-Control'] = 'public, max-age=0' return response APP_STATIC_PATH = os.getcwd() APP.static_folder = APP_STATIC_PATH APP.template_folder = APP_STATIC_PATH UPLOAD_FOLDER = os.path.join(os.getcwd(), 'uploads') ALLOWED_EXTENSIONS = set(['pts']) APP.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @APP.route('/', methods=['GET']) @cross_origin() def index(): """ Index Page. """ return render_template('index.html')
products = session.query(Product).all() if request.method == 'POST': name = request.form['name'] qty = request.form['qty'] error1 = error_input(name, products, "Product %s is alreade exist" % name, "product is Empty") error2 = error_qty(qty) # result = valed(error_input(name, products, 'newProduct.html', "Product %s is alreade exist" % name, "product is Empty", items)) if error1 == None and error2 == "" : EditProduct(product_id, name, request.form['location'], qty) flash("product "+name+ " is edit!") return redirect(url_for('inventoryProduct')) else: if error1 == None: error1 = "" return render_template('editProduct.html', error = error1 + "\n" + error2, product_id=product_id, items=items ,nameproduct=editProduct.name,locationid=editProduct.locationproduct, qty=editProduct.qyt) else: return render_template('editProduct.html',product_id=product_id, items=items ,nameproduct=editProduct.name,locationid=editProduct.locationproduct, qty=editProduct.qyt) TEMPLATE_DIR = os.path.abspath('./templates') STATIC_DIR = os.path.abspath('./static') if __name__ == "__main__": app.secret_key = 'super_secret_key' app.debug = True app.template_folder = TEMPLATE_DIR app.static_folder = STATIC_DIR app.run(host='0.0.0.0', port=5000)
if os.path.isfile(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(e) continue app = Flask(__name__) app.root_path = os.path.join(os.getcwd(), 'api') print(app.root_path) app.template_folder = os.path.join(os.getcwd(), 'api/templates') print(app.template_folder) app.static_folder = os.path.join(os.getcwd(), 'api/static') print(os.path.isdir(app.template_folder)) print(os.path.isdir(app.static_folder)) print() print(os.listdir(app.template_folder)) print(os.listdir(app.static_folder)) UPLOAD_FOLDER = os.path.join(os.getcwd(), 'api/uploads') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/') def hello_world(): return render_template('home_al.html', filename='#')
from werkzeug.datastructures import FileStorage import mysql.connector import json import string import requests import random from twilio.rest import Client import config from devices import device_blueprint from intrusions import intrusion_blueprint from deviceapi import deviceapi_blueprint from settings import settings_blueprint twilio_client = Client(config.account_sid, config.auth_token) app = Flask(__name__) app.static_folder = 'assets' app.config['UPLOAD_FOLDER'] = "/files" headers = {'content-type': 'application/json'} app.register_blueprint(device_blueprint) app.register_blueprint(intrusion_blueprint) app.register_blueprint(deviceapi_blueprint, url_prefix="/api") app.register_blueprint(settings_blueprint) @app.route("/upload/<edgeconnector>", methods=['POST']) def upload_file(edgeconnector): f = request.files['file'] print(f.filename) f.save("assets/" + secure_filename(f.filename)) conn = mysql.connector.connect(host='localhost', user='******',
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager application = Flask(__name__) application.config.from_object('config') db = SQLAlchemy(application) application.static_folder = 'static'
flash("<b>Invalid login details!</b>", "danger") else: referrer = request.referrer or url_for("index") return render_template("login.html", referrer=referrer) @app.route('/logout') def logout(): session.pop('user', None) return redirect(request.referrer or url_for("index")) @app.context_processor def register_helpers(): return { "is_authorized_for": lambda owner: is_authorized(owner, session) } if not os.path.isfile("/var/lib/ffmap/secret_key"): open("/var/lib/ffmap/secret_key", "wb").write(os.urandom(24)) os.chmod("/var/lib/ffmap/secret_key", 0o600) app.secret_key = open("/var/lib/ffmap/secret_key", "rb").read() if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) else: app.template_folder = "/usr/share/ffmap/templates" app.static_folder = "/usr/share/ffmap/static" #app.debug = True
import os import bcrypt import db import forms from werkzeug.middleware.proxy_fix import ProxyFix from flask import Flask, render_template, request, session, redirect path = os.path.dirname(os.path.abspath(__file__)) app = Flask(__name__) app.config.from_pyfile('config.py') app.template_folder = os.path.join(path, 'templates') app.static_folder = os.path.join(path, 'static') @app.route('/') def home(): if 'username' in session: return redirect('/tasks') return render_template('index.html') @app.route('/login', methods=['POST']) def login(): form = forms.AccountForm(request.form) if not form.validate(): return render_template('error.html', message='Invalid login'), 400
from flask import Flask from core.services import postgres # blueprints from web_client import web_client from identity import identity from authentication import authentication from authorization import authorization # app app = Flask(__name__) # file storage app.static_folder = '../../client/static' app.template_folder = '../../client/templates' # config app.config.from_object('core.config.default') # app.config.from_object('core.config.development') # app.config.from_object('core.config.production') # services postgres.app = app postgres.init_app(app) # blueprints app.register_blueprint(web_client) app.register_blueprint(identity, url_prefix='/api') app.register_blueprint(authentication, url_prefix='/api') app.register_blueprint(authorization, url_prefix='/api')
from flask import Flask, send_from_directory, safe_join from text_analysis import model import os import json import subprocess from flask import request from flask_cors import CORS, cross_origin import pandas as pd app = Flask(__name__) app.static_folder = "webui" cors = CORS(app, resources={r"/*": {"origins": "*"}}) standards_dir = 'standards' json_output_dir = 'output' ieee_standards = 'IEEE-standards_rev1.csv' df_ieee = pd.read_csv(os.path.join(standards_dir, 'IEEE-standards_rev1.csv'), index_col=0) @app.route('/') def index(): #return 'ASSESS app is online now!' return send_from_directory('webui/', 'index.html') @app.route('/<any(css, js, img, fonts, sound):folder>/<path:filename>') def toplevel_static(folder, filename): filename = safe_join(folder, filename) cache_timeout = app.get_send_file_max_age(filename) return send_from_directory(app.static_folder,
import zipfile import re from flask import Flask, jsonify, request from flask.views import MethodView from flasgger import Swagger app = Flask(__name__, instance_relative_config=True) app.config['GATLING_PATH'] = '/opt/gatling' app.config['SIM_PATH'] = app.config['GATLING_PATH']+'/user-files/simulations/' app.config['REPORT_PATH'] = app.config['GATLING_PATH']+'/results/' app.config['TMP_PATH'] = '' app.config['DEBUG'] = False app.debug = app.config['DEBUG'] app.static_url_path = app.config['TMP_PATH'] app.static_folder = app.config['TMP_PATH'] app.config.from_envvar('CONFIG_FILE', silent=True) _GATLING_PATH = app.config['GATLING_PATH'] _SIM_PATH = app.config['SIM_PATH'] _REPORT_PATH = app.config['REPORT_PATH'] _TMP_PATH = app.config['TMP_PATH'] app.config['SWAGGER'] = { "swagger_version": "2.0", # headers are optional, the following are default # "headers": [ # ('Access-Control-Allow-Origin', '*'), # ('Access-Control-Allow-Headers', "Authorization, Content-Type"), # ('Access-Control-Expose-Headers', "Authorization"), # ('Access-Control-Allow-Methods', "GET, POST, PUT, DELETE, OPTIONS"),
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.openid import OpenID from flask.ext.mail import Mail from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD app = Flask(__name__) app.config.from_object('config') static_folder = app.config.get('STATIC_FOLDER1') if static_folder is not None: app.static_folder = static_folder db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) oid = OpenID(app, os.path.join(basedir, 'tmp')) lm.login_view = 'login' mail = Mail(app) if not app.debug: import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS,
return render_template("photo_set.html", **context) @app.route("/video/<slug>") def video(slug): video = db.video_by_slug(slug) if not video: raise NotFound("No such video.") context = ctx.get_for_path(["Video", "All", video["title"]]) context["video"] = video return render_template("video.html", **context) # @app.route('/blog/', defaults = {'page':0}) # @app.route('/blog/<int:page>') # def blog(page): # page = page # context = ctx.get_for_path(['Blog']) # context['posts'] = db.get_blog_posts(skip=page*POSTS_PER_PAGE,size=POSTS_PER_PAGE) # total_posts = db.get_total_blog_posts() # if page > 0: # context['prev_page'] = page-1 # if total_posts > (page+1)*POSTS_PER_PAGE: # context['next_page'] = page+1 # return render_template('blog.html', **context) if __name__ == "__main__": if not settings.DEBUG: app.static_folder = "assets" app.run(debug=settings.DEBUG)
import os from flask import Flask APP_DIR = os.path.dirname(__file__) app = Flask(__name__) app.static_folder = os.path.join(APP_DIR, 'static') from app import views
from flask import Flask from promua_test_app.views import * from flask_wtf import CsrfProtect import __config as config app = Flask(__name__) # configure app app.config.from_object(config) # setup extensions csrf_protect = CsrfProtect() # init extensions csrf_protect.init_app(app) login_manager.init_app(app) # setup static and templates app.template_folder = "promua_test_app/templates" app.static_folder = "promua_test_app/static" # register handlers app.before_request(before_request) app.teardown_appcontext(teardown_app_context) # register views IndexView.register(app) UserView.register(app) if __name__ == '__main__': app.run()
from flask import (Flask, request, abort, jsonify, make_response, render_template) from flask_socketio import SocketIO, emit import pandas as pd import lightgbm as lgb from utils import (BASELINE_MODEL, BAD_REQUEST, STATUS_OK, NOT_FOUND, SERVER_ERROR, PORT, FRAUD_THRESHOLD, DATABASE_FILE, TABLE_LOCATIONS) from utils import connect_to_database, select_random_row app = Flask(__name__) # app app.static_folder = 'static' # define static folder for css, img, js app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.errorhandler(BAD_REQUEST) def bad_request(error): return make_response(jsonify({'error': 'Bad request'}), BAD_REQUEST) @app.errorhandler(NOT_FOUND) def not_found(error): return make_response(jsonify({'error': 'Not found'}), NOT_FOUND) @app.errorhandler(SERVER_ERROR) def server_error(error): return make_response(jsonify({'error': 'Server error'}), SERVER_ERROR)