def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) os.makedirs(app.config['STORAGE'], exist_ok=True) db.init_app(app) humanize = Humanize(app) migrate.init_app(app, db) login.init_app(app) app.hashids = Hashids(alphabet=app.config['HASHIDS_ALPHABET'], min_length=app.config['HASHIDS_MIN_LEN'], salt=app.config['HASHIDS_SALT']) from app.auth import bp as auth_bp # noqa: E402 app.register_blueprint(auth_bp, url_prefix='/auth') from app.misc_routes import bp as misc_routes_bp # noqa: E402 app.register_blueprint(misc_routes_bp) from app.profile import bp as profile_bp # noqa: E402 app.register_blueprint(profile_bp, url_prefix='/profile') from app.file import bp as file_bp # noqa: E402 app.register_blueprint(file_bp, url_prefix='/file') from app.auth import uid_str app.add_template_global(name='uid_str', f=uid_str) app.add_template_global(name='humanize', f=humanize) app.add_template_global(name='hashids_encode', f=app.hashids.encode) return app
def init_blueprints(blueprints): '''initialize blueprints and jinja environment''' app.jinja_loader = PackageLoader(__name__, 'templates') for bp in blueprints: app.register_blueprint(bp.bp) humanize = Humanize(app) app.jinja_env.auto_reload = True return app
def create_app(config={}): app = Flask(__name__, instance_relative_config=True) app.config.update(config) app.register_blueprint(views_blueprint) app.register_blueprint(api_blueprint) app.register_blueprint(pubsub_blueprint) Humanize(app) # auth_init_app(app) app.logger.setLevel(logging.INFO) return app
def init(): """connect views and configure templates, then return app""" # TODO(ben) : Make sure all these views are still used and prune if not app.register_blueprint(login.bp) app.register_blueprint(home.bp) app.register_blueprint(signup.bp) app.register_blueprint(news.bp, url_prefix='/news') app.register_blueprint(search.bp) app.register_blueprint(about.bp) app.register_blueprint(teamprofile.bp) app.register_blueprint(memberprofile.bp) app.register_blueprint(leaderboard.bp) app.register_blueprint(logout.bp) app.register_blueprint(fundraiser.bp) app.register_blueprint(create_fundraiser.bp) app.register_blueprint(account_management.bp) app.register_blueprint(partnering.bp) app.register_blueprint(account_deleted.bp) app.register_blueprint(shelterprofile.bp) app.register_blueprint(avatar_upload.bp) app.register_blueprint(donate.bp) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER humanize = Humanize(app) locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') @app.template_filter() def format_currency(value): return locale.currency(value, symbol=True, grouping=True) @humanize.localeselector def get_locale(): return 'en_US' @app.context_processor def provideloginform(): loginform = login.LoginForm(flask.request.form) return {'loginform': loginform} @app.context_processor def dynamic_data(): texts = pyg.web.db.web.session.query(pyg.web.models.Text).filter_by( route_id=str(flask.request.url_rule)) text_dict = {x.slug: x.text for x in texts} return {'text': text_dict} @app.context_processor def user_session(): usersession = flask.session return usersession return app
def load(app): dir_path = os.path.dirname(os.path.realpath(__file__)) template_path = os.path.join(dir_path, 'bots.html') Humanize(app) @app.route('/admin/bots/', methods=['GET']) def bot_monitor(): with open(template_path) as template_file: template = template_file.read() bot_wrangler = BotWrangler() bots = bot_wrangler.get_all_bots() print(bots) return render_template_string(template, bots=bots)
def register_extensions(app): """ Import and register flask extensions and initialize with app object """ from app.assets import env env.init_app(app) from app.extensions import db db.init_app(app) # XXX avoids "RuntimeError: application not registered on db instance and # no application bound to current context" when accessing db outside of app # context db.app = app from flask_migrate import Migrate from sqlalchemy.exc import ArgumentError migrate = Migrate() # XXX SQLite chokes on constraint changes without this with app.app_context(): try: render_as_batch = db.engine.url.drivername == 'sqlite' # XXX this happens during a test except ArgumentError: render_as_batch = True migrate.init_app(app, db, render_as_batch=bool(render_as_batch)) from flaskext.markdown import Markdown Markdown(app, extensions=app.config.get('MARKDOWN_EXTENSIONS', [])) from flask_humanize import Humanize Humanize(app) from app.extensions import oidc oidc.init_app(app) from flask_security import Security from app.extensions import user_datastore from app.blueprints.base.models import Role, User user_datastore.role_model = Role user_datastore.user_model = User Security(app, user_datastore)
def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False heroku = Heroku(app) humanize = Humanize(app) from frank.model import db, migrate db.init_app(app) migrate.init_app(app, db) from .views.home import homepage from .calendar.views import calendar app.register_blueprint(homepage) app.register_blueprint(calendar, url_prefix='/calendar') return { 'app': app, 'heroku': heroku, 'humanize': humanize, 'db': db, 'migrate': migrate, }
def to_python(self, value): try: return datetime.datetime.strptime(value, '%y%m%d').date() except ValueError: try: datetime.datetime.strptime(value, '%Y-%m-%d').date() except ValueError: return datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S') def to_url(self, value): return value.isoformat(timespec='seconds') app.url_map.converters['datetime'] = DateTimeConverter class DateConverter(BaseConverter): def to_python(self, value): try: return datetime.datetime.strptime(value, '%y%m%d').date() except ValueError: return datetime.datetime.strptime(value, '%Y-%m-%d').date() def to_url(self, value): return value.isoformat() app.url_map.converters['date'] = DateConverter humanize = Humanize(app)
from os.path import basename import sqlalchemy from flask import Flask, request, jsonify, url_for from flask.templating import render_template from flask_humanize import Humanize from littleutils import DecentJSONEncoder, withattrs, group_by_attr from werkzeug.routing import PathConverter from birdseye.db import Database from birdseye.utils import short_path, IPYTHON_FILE_PATH, fix_abs_path, is_ipython_cell app = Flask('birdseye') app.jinja_env.auto_reload = True Humanize(app) class FileConverter(PathConverter): regex = '.*?' app.url_map.converters['file'] = FileConverter db = Database() Session = db.Session Function = db.Function Call = db.Call
def create_app(config={}): app = Flask(__name__, instance_relative_config=True) app.config.update(config) app.register_blueprint(views) Humanize(app) return app
return self.app(environ, start_response) app = Flask(__name__) CORS(app) if secrets.DIFFERENT_PROXY_PATH: app.wsgi_app = ReverseProxied(app.wsgi_app) app.debug = secrets.DEBUG app.secret_key = secrets.DEBUG_KEY app.config['DEBUG_TB_INTERCEPT_REDIRECTS '] = False babel = Babel(app) humanize_filter = Humanize(app) bootstrap = Bootstrap(app) app.config['BOOTSTRAP_SERVE_LOCAL'] = secrets.BOOTSTRAP_SERVE_LOCAL csrf = CSRFProtect(app) wtforms_json.init() socketio = SocketIO(app) log_formatter = logging.Formatter( "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s") handler = RotatingFileHandler(secrets.LOGFILE, maxBytes=10000, backupCount=1) handler.setLevel(logging.INFO) handler.setFormatter(log_formatter)
from slugify import slugify basicConfig(format="%(asctime)s\t- %(levelname)s\t- %(message)s", level=INFO) app = Flask(__name__) app.config["TELERIVET_API_KEY"] = environ["TELERIVET_API_KEY"] app.config["WEBHOOK_SECRET"] = environ["WEBHOOK_SECRET"] app.config["SQLALCHEMY_DATABASE_URI"] = environ.get( "DATABASE_URL") or "sqlite:///dev.db" db = SQLAlchemy(app) mn = minify(app) hz = Humanize(app) ev = DotEnv(app) @hz.localeselector def get_locale(): return "pt_BR" # Models class Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) slug = db.Column(db.String(50), unique=True, nullable=False) def __repr__(self):
@_generative() def without_no_load_balance_comment(self): self._apply_no_load_balance_comment = False def _compile_context(self, *arg, **kw): context = BaseQuery._compile_context(self, *arg, **kw) if self._apply_no_load_balance_comment: context.statement._apply_no_load_balance_comment = True return context cache = Cache() db = SQLAlchemy(metadata=metadata, query_class=PrefixedQuery) ini_config = INIConfig() humanise = Humanize() toolbar = DebugToolbarExtension() lm = LoginManager() csrf = CSRFProtect() def url_for_other_page(page): return restricted_url(_page=page) def restricted_url(endpoint=None, include=None, exclude=None, **single_args): if endpoint is None: endpoint = request.endpoint if endpoint == request.endpoint: args = MultiDict(request.view_args)
from flask_login import LoginManager from flask_assets import Environment from flask_humanize import Humanize from resrv.models import User # init flask assets assets_env = Environment() login_manager = LoginManager() login_manager.login_view = "main.login" login_manager.login_message_category = "warning" humanize = Humanize() @login_manager.user_loader def load_user(userid): return User.query.get(userid)
def h(request): if 'app' not in request.fixturenames: return app = request.getfuncargvalue('app') return Humanize(app)