def create_app(): application = Flask(__name__) application.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI # application.config['BABEL_DEFAULT_LOCALE'] = 'ru-ru' application.config['SECRET_KEY'] = SECRET_KEY application.permanent_session_lifetime = timedelta(minutes=30) Triangle(application) assets.init_app(application) api.init_app(application) api.application = application db.init_app(application) admin.init_app(application) login_manager.init_app(application) application.db = db application.api = api babel = Babel(application) @babel.localeselector def get_locale(): return request.accept_languages.best_match(["ru"]) init_logging(application) return application
def create_app(config): app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page app.register_blueprint(remedy) from admin import admin admin.init_app(app) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous() db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager
def create_app(config_name): app = Flask(__name__, instance_relative_config=1) app.config.from_object(config_name) app.config.from_pyfile("config.py") from model import db db.init_app(app) from utilities import cache cache.init_app(app) from admin import admin admin.init_app(app) from security import security security.init_app(app) from main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def create_app(config): app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page, server_error app.register_blueprint(remedy) # Register a custom error handler for production scenarios if app.debug is not True: app.error_handler_spec[None][500] = server_error app.error_handler_spec[None][Exception] = server_error from admin import admin admin.init_app(app) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda : current_user.is_authenticated db.init_app(app) from flask_wtf.csrf import CsrfProtect CsrfProtect(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # Enable logging for production environments if app.debug is not True: logging.basicConfig(stream=sys.stderr) file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20) file_handler.setLevel(logging.WARNING) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) # Configure proxies for WSGI if app.wsgi_app is not None: from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager
def create_app(config_name): app = Flask(config_name) app.config.from_object(config[config_name]) # 全局响应头 @app.after_request def after_request(response): if "Access-Control-Allow-Origin" not in response.headers.keys(): response.headers['Access-Control-Allow-Origin'] = '*' if request.method == 'OPTIONS': response.headers['Access-Control-Allow-Methods'] = 'DELETE, GET, POST, PUT' headers = request.headers.get('Access-Control-Request-Headers') if headers: response.headers['Access-Control-Allow-Headers'] = headers return response # 自定义错误日志 handler = logging.FileHandler('app.log', encoding='UTF-8') logging_format = logging.Formatter( '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s') handler.setFormatter(logging_format) app.logger.addHandler(handler) def init_login(): login_manager = login.LoginManager() login_manager.setup_app(app) # Create user loader function @login_manager.user_loader def load_user(user_id): return AdminUser.objects(id=user_id).first() # 注册所有蓝图 for bp_name in blueprints: bp = import_string(bp_name) app.register_blueprint(bp) config[config_name].init_app(app) babel = Babel(app) db.init_app(app) docs.init_app(app) admin.init_app(app) init_login() limiter.init_app(app) db.register_connection( db='mark', alias="mark", port=PORT, username=NAME, password=PWD ) # 跨域 CORS(app, supports_credentials=True) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) from admin import admin admin.init_app(app) return app
def init_extensions(app): db.init_app(app) import models login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): return User.get(user_id) admin.init_app(app)
def create_app(config=DevConfig): app = Flask(__name__) app.config.from_object(config) config.init_app(app) admin.init_app(app) db.init_app(app) return app
def init(app): # --> Extension setup db.init_app(app) admin.init_app(app) modules["migrate"] = Migrate(app, db) modules["user_datastore"] = SQLAlchemyUserDatastore(db, User, Role) modules["security"] = Security(app, modules["user_datastore"], confirm_register_form=MyRegisterForm) # --> Register blueprints from modules.play.play import play app.register_blueprint(play, url_prefix='/play') from modules.api.core import api_core app.register_blueprint(api_core, url_prefix='/kcsapi') # Declare API v1 blueprints. from modules.api.v1.user import api_user from modules.api.v1.actions import api_actions app.register_blueprint(api_user, url_prefix='/kcsapi') app.register_blueprint(api_actions, url_prefix='/kcsapi') # Declare API v2 blueprints. from modules.api.v2.AdmiralAPI import AdmiralAPIv2 from modules.api.v2.DockAPI import DockAPIv2 app.register_blueprint(AdmiralAPIv2, url_prefix='/api/v2/admiral') app.register_blueprint(DockAPIv2, url_prefix='/api/v2/docks') from modules.resources import resources app.register_blueprint(resources, url_prefix='/kcs') # --> Base application routes @app.route('/') def index(): return render_template('index.html') @app.route('/kcs/<path:path>') def kcs(path): return send_from_directory('kcs', path) # --> Signals @user_logged_in.connect_via(app) def u_logged_in(sender, user): """ Regenerate the API token every login. """ user.api_token = generate_api_token()
def create_app(environment='Development'): """ :param environment: is either Development/Production/Testing """ if environment is None: environment = 'Development' app = Flask(__name__) app.config.from_object(f'config.{environment}Config') @app.route('/', methods=['GET']) def temp_main_function(): """ temporary main function to test app, debug and testing status todo:move it to another endpoint :return: status:dict """ return { 'status': 'API is up and running:))', 'ENV': app.config['ENV'], 'DEBUG': app.config['DEBUG'], 'TESTING': app.config['TESTING'], 'elasticsearch_status': 'ready' if elastic.ping() else 'broken' } app.register_blueprint(calculator) app.register_blueprint(users) app.register_blueprint(foods) app.register_blueprint(blog) db.init_app(app) migrate.init_app(app) jwt.init_app(app) mail.init_app(app) admin.init_app(app) # configuring CORS settings CORS(app, resources=app.config['CORS_RESOURCES']) if app.debug: app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True) # enabling whitenoise app.wsgi_app = WhiteNoise(app.wsgi_app) for static_folder in app.config['STATIC_FOLDERS']: app.wsgi_app.add_files(static_folder) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) CsrfProtect(app) from .main import main as main_blueprint from .resources import main as resource_blueprint app.register_blueprint(main_blueprint) app.register_blueprint(resource_blueprint) from admin import admin, login_manager admin.init_app(app) login_manager.init_app(app) return app
def create_app(config=cfg.current_config): app = Flask(__name__, static_folder=config.IMAGE_DIR) app.config.from_object(config) db.app = app db.init_app(app) Migrate(app, db) admin.init_app(app) login_manager.init_app(app) app.register_blueprint(webhook_bp, url_prefix='/webhook') app.register_blueprint(index_bp, url_prefix='/') app.before_first_request(init_bot) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) admin.init_app(app) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) toolbar.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
def create_app(): #APP init app = Flask(__name__) app.config.from_object('config.DevelopmentConfig') #THEMES init Themes(app, app_identifier='app') #MAIL init from flask_mail import Mail mail = Mail(app) #DATABASE init from models import db db.init_app(app) #MIGRATIONS init migrate = Migrate(app, db) with app.app_context(): #User init from flask_user import SQLAlchemyAdapter, UserManager from users import User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) #db finalization db.create_all() #API - is for IOT, or mobile from models import DummyObject, DummyFile manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db) manager.create_api(DummyObject) manager.create_api(DummyFile) #ADMIN - is for basic crud for trained users from admin import admin admin.init_app(app) #MEMBER VIEWS from member import MemberView MemberView.register(app) #upload example from flask_admin.contrib.fileadmin import FileAdmin path = os.path.join(os.path.dirname(__file__), app.config['UPLOAD_FOLDER']) admin.add_view(FileAdmin(path, '/uploads/', name='Uploads')) #sqlmodel example from flask_admin.contrib.sqla import ModelView admin.add_view(ModelView(DummyObject, db.session)) #DASHBOARD - is for customer login pages #I'll have to make that custom return app, migrate
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) db.init_app(app) login_manager.init_app(app) bootstrap.init_app(app) csrf.init_app(app) from admin import admin admin.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') print u'app.create_app已启动,login_view为', login_manager.login_view return app
def create_app(config): app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page app.register_blueprint(remedy) from admin import admin admin.init_app(app) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda: not current_user.is_anonymous( ) db.init_app(app) from flask_wtf.csrf import CsrfProtect CsrfProtect(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from admin import admin from .admin.views import MyModelView,MyAdminIndexView from .models import Role, User, Post, Category, Tag admin.init_app(app, index_view=MyAdminIndexView()) admin.add_view(MyModelView(Role, db.session)) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Post, db.session)) admin.add_view(MyModelView(Category, db.session)) admin.add_view(MyModelView(Tag, db.session)) from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app
from flask.ext.migrate import Migrate from jinja2 import evalcontextfilter, Markup, escape from db import * from assets import assets from admin import admin from forms import * app = Flask(__name__) app.config.from_object('config') app.config.from_object('keys') mail = Mail(app) db.init_app(app) assets.init_app(app) admin.init_app(app) migrate = Migrate(app, db) class MyUserDatastore(SQLAlchemyUserDatastore): def create_user(self, **kwargs): if not 'profile' in kwargs: kwargs['profile'] = Profile() return super(SQLAlchemyUserDatastore, self).create_user(**kwargs) user_datastore = MyUserDatastore(db, User, Role) security = Security(app, user_datastore)
request, make_response, jsonify, ) from db import ( db, migrate, ) from models.user import User from models.post import Post from admin import admin app = Flask(__name__) app.config.from_pyfile("configs.py") admin.init_app(app) db.init_app(app) ## db.init_app(app) migrate.init_app(app, db) # 로그인 되있으면 메인, 아니면 로그인창 @app.route("/") def hello(): return login() @app.route("/main")
def init(app): # --> Jinja2 Env Update app.jinja_env.globals.update(__builtins__=__builtins__) # --> URI setup app.config["SQLALCHEMY_DATABASE_URI"] = \ "postgresql://{}:{}@{}:{}/{}".format(app.config["DB_USERNAME"], app.config["DB_PASSWORD"], app.config["DB_HOSTNAME"], app.config["DB_PORT"], app.config["DB_DATABASE"]) # --> Extension setup db.init_app(app) admin.init_app(app) mail = Mail() mail.init_app(app) modules["migrate"] = Migrate(app, db) modules["user_datastore"] = SQLAlchemyUserDatastore(db, User, Role) modules["security"] = Security(app, modules["user_datastore"], confirm_register_form=MyRegisterForm) # --> Admiral load on each request def admiral_load(): api_token = request.values.get('api_token', None) if api_token is None: logger.warning("No API Key -> Skipping request") abort(403) user = db.session.query(User).filter( User.api_token == api_token).first() if user is None: logger.warning("Unknown API Key -> {}".format(api_token)) abort(404) g.admiral = user.admiral if user.admiral else Admiral().create(user) # Update resources. curr_t = datetime.datetime.utcnow() lastaction = g.admiral.last_action if not lastaction: lastaction = curr_t delta = (curr_t - lastaction).total_seconds() / 60 if delta < 0: # wat logger.warn("Now - lastaction for admiral {} negative?".format( user.nickname)) return delta = int(delta) g.admiral.resources.add(*((delta * 3) for _ in range(3)), baux=delta * 2) # Update action time g.admiral.last_action = curr_t db.session.add(g.admiral) db.session.commit() # --> Set up blueprints from kancolle.api import api_actions api_actions.before_request(admiral_load) app.register_blueprint(api_actions, url_prefix='/kcsapi') from kancolle.api import api_member api_member.before_request(admiral_load) app.register_blueprint(api_member, url_prefix='/kcsapi/api_get_member') from kancolle.api import api_init api_init.before_request(admiral_load) app.register_blueprint(api_init, url_prefix='/kcsapi') from kancolle.api import api_user api_user.before_request(admiral_load) app.register_blueprint(api_user, url_prefix='/kcsapi') from kancolle.api import api_mission api_mission.before_request(admiral_load) app.register_blueprint(api_mission, url_prefix='/kcsapi/api_req_mission') @app.route('/play') def p_index(): if hasattr(current_user, 'api_token'): api_token = current_user.api_token return render_template('play/index.html', api_token=api_token) else: return redirect('/account/login') # --> Base application routes @app.route('/') def index(): return render_template('index.html') @app.route('/kcs/<path:path>') def kcs(path): return send_from_directory('kcs', path) # --> Signals @user_logged_in.connect_via(app) def u_logged_in(sender, user): """ Regenerate the API token every login. """ user.api_token = generate_api_token()
def register_blueprints(app): # Prevents circular imports from views import posts app.register_blueprint(posts) from admin import admin admin.init_app(app)
def create_app(config): """ Creates a Flask application based on the provided configuration object. Args: config: The configuration object. """ app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page, server_error app.register_blueprint(remedy) # Register a custom error handler for production scenarios if app.debug is not True: app.error_handler_spec[None][500] = server_error app.error_handler_spec[None][Exception] = server_error from admin import admin admin.init_app(app) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda: current_user.is_authenticated db.init_app(app) from flask_wtf.csrf import CsrfProtect CsrfProtect(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # Enable logging for production environments if app.debug is not True: logging.basicConfig(stream=sys.stderr) file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20) file_handler.setLevel(logging.WARNING) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) # Configure proxies for WSGI if app.wsgi_app is not None: from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager