def register_exts(app): db.init_app(app) db.app = app cache.init_app(app) migrate = Migrate() migrate.init_app(app, db) register_login(app) if not app.config.get('TESTING'): register_admins(app)
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 flask_humanize import Humanize Humanize(app) from flask_security import Security from app.extensions import user_datastore from app.main.models import AnonymousUser, Role, User user_datastore.role_model = Role user_datastore.user_model = User Security(app, user_datastore, anonymous_user=AnonymousUser) from app.extensions import notify notify.init_app(app) from app.oidc_client import OIDCClient OIDCClient(app) from app.extensions import pay pay.init_app(app)
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)
ENV = os.getenv("FLASK_ENV") static_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../public/') app = Flask(__name__) app.url_map.strict_slashes = False # database condiguration if os.getenv("DATABASE_URL") is not None: app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') else: app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////tmp/test.db" app.config["JWT_SECRET_KEY"] = "4GeeksAcademyGroup4" jwt = JWTManager(app) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False MIGRATE = Migrate(app, db) db.init_app(app) # Allow CORS requests to this API CORS(app) # add the admin setup_admin(app) # Add all endpoints form the API with a "api" prefix app.register_blueprint(api, url_prefix='/api') # Handle/serialize errors like a JSON object @app.errorhandler(APIException) def handle_invalid_usage(error): return jsonify(error.to_dict()), error.status_code
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_restful import Api from flask_jwt_extended import JWTManager from flask_marshmallow import Marshmallow from flask_cors import CORS api = Api() cors = CORS() db = SQLAlchemy() jwt = JWTManager() ma = Marshmallow() migrate = Migrate()
~~~~~~~~~~~~~~~~~ app module of mscolab This file is part of mss. :copyright: Copyright 2016-2021 by the mss team, see AUTHORS. :license: APACHE-2.0, see LICENSE for details. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from flask_migrate import Migrate from mslib.mscolab.models import db from mslib.mscolab.server import _app as app # in memory database for testing # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' migrate = Migrate(app, db, render_as_batch=True)
def create_app(config=None): """Create the Flask app instance that is used throughout the application. Args: config: Path to configuration file as a string or an object with config directives. Returns: Application object (instance of flask.Flask). """ # Setup the Flask app and load the config. app = Flask(__name__, template_folder='templates', static_folder='static') if not config: config = '/etc/timesketch.conf' if isinstance(config, six.text_type): os.environ['TIMESKETCH_SETTINGS'] = config try: app.config.from_envvar('TIMESKETCH_SETTINGS') except IOError: sys.stderr.write( 'Config file {0} does not exist.\n'.format(config)) sys.exit() else: app.config.from_object(config) # Make sure that SECRET_KEY is configured. if not app.config['SECRET_KEY']: sys.stderr.write('ERROR: Secret key not present. ' 'Please update your configuration.\n' 'To generate a key you can use openssl:\n\n' '$ openssl rand -base64 32\n\n') sys.exit() # Plaso version that we support if app.config['UPLOAD_ENABLED']: try: from plaso import __version__ as plaso_version except ImportError: sys.stderr.write('Upload is enabled, but Plaso is not installed.') sys.exit() app.config['PLASO_VERSION'] = plaso_version # Setup the database. configure_engine(app.config['SQLALCHEMY_DATABASE_URI']) db = init_db() # Alembic migration support: # http://alembic.zzzcomputing.com/en/latest/ migrate = Migrate() migrate.init_app(app, db) # Register blueprints. Blueprints are a way to organize your Flask # Flask application. See this for more information: # http://flask.pocoo.org/docs/latest/blueprints/ app.register_blueprint(auth_views) app.register_blueprint(home_views) app.register_blueprint(sketch_views) # Setup URL routes for the API. api_v1 = Api(app, prefix='/api/v1') for route in V1_API_ROUTES: api_v1.add_resource(*route) # Register error handlers # pylint: disable=unused-variable @app.errorhandler(ApiHTTPError) def handle_api_http_error(error): """Error handler for API HTTP errors. Returns: HTTP response object (instance of flask.wrappers.Response) """ return error.build_response() # Setup the login manager. login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'user_views.login' # This is used by the flask_login extension. # pylint: disable=unused-variable @login_manager.user_loader def load_user(user_id): """Based on a user_id (database primary key for a user) this function loads a user from the database. It is used by the Flask-Login extension to setup up the session for the user. Args: user_id: Integer primary key for the user. Returns: A user object (Instance of timesketch.models.user.User). """ return User.query.get(user_id) # Setup CSRF protection for the whole application CSRFProtect(app) return app
app = Flask(__name__) # creates the flask app ######## FLASK-UPLOADS ############### photos_folder_rel_path = 'fantaso/static' photos_folder_full_path = getcwd() photos_folder = 'products' photos = UploadSet('photos', IMAGES) # Flask-Uploads app.config['UPLOADED_PHOTOS_DEST'] = join(photos_folder_rel_path, photos_folder) # Flask-Uploads app.config.from_object(Config) # imports app configuration from config.py configure_uploads(app, photos) ######## FLASK-UPLOADS ############### db = SQLAlchemy(app) # create database connection object migrate = Migrate(app, db) # creates a migration object for the app db migrations]\ # mail = Mail(app) # TO MANAGE THE MIGRATIONS WITH FLASK-SCRIPT WITH PYTHON EXTERNAL SCRIPTS > goes together to migrations for migraing db # server = Server(host = '192.168.1.17', port = 8000, debug = True) manager = Manager(app) manager.add_command('db', MigrateCommand) manager.add_command('runserver', Server(host=None, port=None)) ############################# # Begin Import Models ############################# from fantaso.bp_shop.models import Product, Order, ProductImage # from fantaso.bp_shop.models import Product, Order # from fantaso.models import Farm, Field, DailyFieldInput, Crop # from fantaso.models import Agrimodule, Agrisensor, Measurement, Agripump, Pump
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from app import app, db migrate = Migrate() DATABASE_URI = getattr(app.config, 'SQLALCHEMY_DATABASE_URI', '') is_sqlite = DATABASE_URI.startswith('sqlite:') migrate.init_app(app, db, render_as_batch=is_sqlite) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
def add_sqlalchemy(self): db.init_app(self) migrate = Migrate() migrate.init_app(self, db)
def create_flask_app(environment): app = Flask(__name__, instance_relative_config=True, static_folder=None, template_folder='./api/emails/templates') app.config.from_object(app_configuration[environment]) app.config['BUNDLE_ERRORS'] = True try: from api import models except ImportError: from moov_backend.api import models # to allow cross origin resource sharing CORS(app) # initialize SQLAlchemy models.db.init_app(app) # initilize migration commands Migrate(app, models.db) # initilize api resources api = Api(app) environment = os.getenv("FLASK_CONFIG") # to redirect all incoming requests to https if environment.lower() == "production": sslify = SSLify(app, subdomains=True, permanent=True) # Landing page @app.route('/') def index(): return "Welcome to the MOOV Api" ## ## Actually setup the Api resource routing here ## api.add_resource(RouteResource, '/api/v1/route', '/api/v1/route/', endpoint='single_route') # User routes api.add_resource(UserResource, '/api/v1/user', '/api/v1/user/', endpoint='user_endpoint') api.add_resource(UserAuthorizationResource, '/api/v1/user_authorization', '/api/v1/user_authorization/', endpoint='user_authorization_endpoint') # Driver routes api.add_resource(DriverResource, '/api/v1/driver', '/api/v1/driver/', endpoint='single_driver') api.add_resource(DriverConfirmRideResouce, '/api/v1/driver_confirm_ride', '/api/v1/driver_confirm_ride/', endpoint='driver_confirm_endpoint') # Authentication routes api.add_resource(UserSignupResource, '/api/v1/signup', '/api/v1/signup/', endpoint='singup_user') api.add_resource(UserLoginResource, '/api/v1/login', '/api/v1/login/', endpoint='login_endpoint') # Transaction routes api.add_resource(TransactionResource, '/api/v1/transaction', '/api/v1/transaction/', endpoint='single_transaction') api.add_resource(AllTransactionsResource, '/api/v1/all_transactions', '/api/v1/all_transactions/', endpoint='all_transactions') # Profile Page routes api.add_resource(BasicInfoResource, '/api/v1/basic_info', '/api/v1/basic_info/', endpoint='user_basic_info') # Free Ride routes api.add_resource(FreeRideResource, '/api/v1/free_ride', '/api/v1/free_ride/', endpoint='free_ride_endpoint') # Notification routes api.add_resource(NotificationResource, '/api/v1/notification', '/api/v1/notification/', endpoint='single_notification') # Forgot Password routes api.add_resource(ForgotPasswordResource, '/api/v1/forgot_password', '/api/v1/forgot_password/', endpoint='forgot_password') # School routes api.add_resource(SchoolResource, '/api/v1/all_schools', '/api/v1/all_schools/', endpoint='all_schools') # handle default 404 exceptions with a custom response @app.errorhandler(404) def resource_not_found(exception): response = jsonify(dict(status='fail', data={ 'error':'Not found', 'message':'The requested URL was' ' not found on the server. If you entered the URL ' 'manually please check and try again' })) response.status_code = 404 return response # both error handlers below handle default 500 exceptions with a custom response @app.errorhandler(500) def internal_server_error(error): response = jsonify(dict(status=error,error='Internal Server Error', message='The server encountered an internal error and was' ' unable to complete your request. Either the server is' ' overloaded or there is an error in the application')) response.status_code = 500 return response if environment.lower() == "production": # handles 500 exception on production @app.errorhandler(Exception) def unhandled_exception(error): response = jsonify(dict( status='error', data={ 'error': 'Unhandle Error', 'message': 'The server encountered an internal error and was unable to complete your request.' } )) response.status_code = 500 app.logger.error(repr(error)) return response return app
def setup_db(app, database_path=database_path): app.config["SQLALCHEMY_DATABASE_URI"] = database_path app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.app = app db.init_app(app) migrate = Migrate(app, db)
from flask import Flask #import flask to create object from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager app = Flask(__name__) #myFlaskObj has been created app.config.from_object(Config) login = LoginManager(app) login.login_view = 'login' db = SQLAlchemy(app) #create the db object represent the database migrate = Migrate(app, db) #create the migrate object @app.before_first_request def create_table(): from application.models import User db.create_all() from application import routes, models
def create_app(config=None): """Create the Flask app instance that is used throughout the application. Args: config: Path to configuration file as a string or an object with config directives. Returns: Application object (instance of flask.Flask). """ # Setup the Flask app and load the config. app = Flask(__name__, template_folder=u'templates', static_folder=u'static') if not config: config = u'/etc/timesketch.conf' if isinstance(config, unicode): os.environ[u'TIMESKETCH_SETTINGS'] = config try: app.config.from_envvar(u'TIMESKETCH_SETTINGS') except IOError: sys.stderr.write( u'Config file {0} does not exist.\n'.format(config)) sys.exit() else: app.config.from_object(config) # Make sure that SECRET_KEY is configured. if not app.config[u'SECRET_KEY']: sys.stderr.write(u'ERROR: Secret key not present. ' u'Please update your configuration.\n' u'To generate a key you can use openssl:\n\n' u'$ openssl rand -base64 32\n\n') sys.exit() # Plaso version that we support if app.config[u'UPLOAD_ENABLED']: try: from plaso import __version__ as plaso_version except ImportError: sys.stderr.write(u'Upload is enabled, but Plaso is not installed.') sys.exit() app.config[u'PLASO_VERSION'] = plaso_version # Setup the database. configure_engine(app.config[u'SQLALCHEMY_DATABASE_URI']) db = init_db() # Alembic migration support: # http://alembic.zzzcomputing.com/en/latest/ migrate = Migrate() migrate.init_app(app, db) # Register blueprints. Blueprints are a way to organize your Flask # Flask application. See this for more information: # http://flask.pocoo.org/docs/latest/blueprints/ app.register_blueprint(auth_views) app.register_blueprint(home_views) app.register_blueprint(sketch_views) # Setup URL routes for the API. api_v1 = Api(app, prefix=u'/api/v1') for route in V1_API_ROUTES: api_v1.add_resource(*route) # Setup URL routes for the experimental API. api_experimental = Api(app, prefix=u'/api/experimental') for route in EXP_API_ROUTES: api_experimental.add_resource(*route) # Register error handlers # pylint: disable=unused-variable @app.errorhandler(ApiHTTPError) def handle_api_http_error(error): """Error handler for API HTTP errors. Returns: HTTP response object (instance of flask.wrappers.Response) """ return error.build_response() # Setup the login manager. login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = u'user_views.login' # This is used by the flask_login extension. # pylint: disable=unused-variable @login_manager.user_loader def load_user(user_id): """Based on a user_id (database primary key for a user) this function loads a user from the database. It is used by the Flask-Login extension to setup up the session for the user. Args: user_id: Integer primary key for the user. Returns: A user object (Instance of timesketch.models.user.User). """ return User.query.get(user_id) # Setup CSRF protection for the whole application CSRFProtect(app) return app
def create_app(config_name): log_config_path = os.path.join( Path(__file__).parent.absolute(), 'log/logger.conf') if not (os.path.isfile(log_config_path)): assert os.environ.get( 'LOG_FILE' ), 'É necessário informar o path do arquivo de configuração do log!' log_config_path = os.environ.get('LOG_FILE') logging.config.fileConfig(log_config_path) logging.getLogger(__name__).info('Criando objeto da aplicação') app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py') db.init_app(app) login_manager.init_app(app) login_manager.login_message = "Você precisa estar logado para acessar esta página!" login_manager.login_view = "auth.login" Bootstrap(app) migrate = Migrate(app, db) logging.getLogger(__name__).info('Registrando blueprints') app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(auth) app.register_blueprint(home) @app.errorhandler(403) def forbidden(error): return render_template('errors/403.html', title='Acesso proibido'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('errors/404.html', title='Página não encontrada'), 404 @app.errorhandler(500) def internal_server_error(error): return render_template('errors/500.html', title='Erro genérico'), 500 import dropshipping.api.categorias.resources as api_categoria import dropshipping.api.fornecedores.resources as api_fornecedor import dropshipping.api.produtos.resources as api_produto api = Api(app) api.add_resource(api_categoria.CategoriaAPI, '/api/v1/categoria/<int:id>') api.add_resource(api_categoria.ListaCategoriaAPI, '/api/v1/categoria') api.add_resource(api_fornecedor.FornecedorAPI, '/api/v1/fornecedor/<int:id>') api.add_resource(api_fornecedor.ListaFornecedorAPI, '/api/v1/fornecedor') api.add_resource(api_produto.ProdutoAPI, '/api/v1/produto/<int:id>') api.add_resource(api_produto.ListaProdutoAPI, '/api/v1/produto') return app
def create_app(): global app_created if not app_created: BlueprintsManager.register(app) Migrate(app, db) app.config.from_object(env('APP_CONFIG', default='config.ProductionConfig')) if not app.config['SECRET_KEY']: if app.config['PRODUCTION']: app.logger.error( 'SECRET_KEY must be set in .env or environment variables in production' ) exit(1) else: random_secret = secrets.token_hex() app.logger.warning( f'Using random secret "{ random_secret }" for development server. ' 'This is NOT recommended. Set proper SECRET_KEY in .env or environment variables' ) app.config['SECRET_KEY'] = random_secret db.init_app(app) if app.config['CACHING']: cache.init_app(app, config={'CACHE_TYPE': 'simple'}) else: cache.init_app(app, config={'CACHE_TYPE': 'null'}) stripe.api_key = 'SomeStripeKey' app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static' app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.setLevel(logging.ERROR) # set up jwt app.config['JWT_HEADER_TYPE'] = 'JWT' app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1) app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=365) app.config['JWT_ERROR_MESSAGE_KEY'] = 'error' app.config['JWT_TOKEN_LOCATION'] = ['cookies', 'headers'] app.config['JWT_REFRESH_COOKIE_PATH'] = '/v1/auth/token/refresh' app.config['JWT_SESSION_COOKIE'] = False app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['refresh'] _jwt = JWTManager(app) _jwt.user_loader_callback_loader(jwt_user_loader) _jwt.token_in_blacklist_loader(is_token_blacklisted) # setup celery app.config['CELERY_BROKER_URL'] = app.config['REDIS_URL'] app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL'] app.config['CELERY_ACCEPT_CONTENT'] = ['json', 'application/text'] CORS(app, resources={r"/*": {"origins": "*"}}) AuthManager.init_login(app) if app.config['TESTING'] and app.config['PROFILE']: # Profiling app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) # development api with app.app_context(): from app.api.admin_statistics_api.events import event_statistics from app.api.auth import auth_routes from app.api.custom.attendees import attendee_blueprint from app.api.bootstrap import api_v1 from app.api.celery_tasks import celery_routes from app.api.event_copy import event_copy from app.api.exports import export_routes from app.api.imports import import_routes from app.api.uploads import upload_routes from app.api.users import user_misc_routes from app.api.orders import order_misc_routes from app.api.role_invites import role_invites_misc_routes from app.api.auth import authorised_blueprint from app.api.admin_translations import admin_blueprint from app.api.orders import alipay_blueprint from app.api.settings import admin_misc_routes from app.api.server_version import info_route from app.api.custom.orders import ticket_blueprint from app.api.custom.orders import order_blueprint from app.api.custom.invoices import event_blueprint app.register_blueprint(api_v1) app.register_blueprint(event_copy) app.register_blueprint(upload_routes) app.register_blueprint(export_routes) app.register_blueprint(import_routes) app.register_blueprint(celery_routes) app.register_blueprint(auth_routes) app.register_blueprint(event_statistics) app.register_blueprint(user_misc_routes) app.register_blueprint(attendee_blueprint) app.register_blueprint(order_misc_routes) app.register_blueprint(role_invites_misc_routes) app.register_blueprint(authorised_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(alipay_blueprint) app.register_blueprint(admin_misc_routes) app.register_blueprint(info_route) app.register_blueprint(ticket_blueprint) app.register_blueprint(order_blueprint) app.register_blueprint(event_blueprint) add_engine_pidguard(db.engine) if app.config[ 'SQLALCHEMY_DATABASE_URI' # pytype: disable=attribute-error ].startswith("sqlite://"): sqlite_datetime_fix() sa.orm.configure_mappers() if app.config['SERVE_STATIC']: app.add_url_rule( '/static/<path:filename>', endpoint='static', view_func=app.send_static_file ) # sentry if not app_created and 'SENTRY_DSN' in app.config: sentry_sdk.init( app.config['SENTRY_DSN'], integrations=[ FlaskIntegration(), RedisIntegration(), CeleryIntegration(), SqlalchemyIntegration(), ], ) # redis redis_store.init_app(app) # Initialize Extensions shell.init_app(app) limiter.init_app(app) app_created = True return app
def setup_db(app): db.app = app db.init_app(app) Migrate(app, db)
""" The flask application package. """ import os from flask import Flask, render_template, url_for, views from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate lm = LoginManager() basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( basedir, "survey.db") app.config['SECRET_KEY'] = 'this-is-my-secret' db = SQLAlchemy(app) lm.init_app(app) lm.session_protection = "strong" lm.login_view = "login" migrate = Migrate(app, db) from .views import *
def init_db(app): db = SQLAlchemy(app) migrate = Migrate(app, db) return db, migrate
def register_extensions(app): db.app = app db.init_app(app) migrate = Migrate(app, db)
from config.constants import Constants from coverage import coverage from flask import current_app from youngs_server.helpers.image_helper import save_json_image, generate_image_url from youngs_server import app from flask_migrate import Migrate, MigrateCommand from flask_script import Shell, Manager, Server from youngs_server.models.host_models import Member, Question, Review, Lecture from youngs_server.youngs_app import db, youngs_redis from youngs_server.common.time_util import today_obj, now_datetime from youngs_server.youngs_app import log app.config['RUN'] = False manager = Manager(app) migrate = Migrate() migrate.init_app(app, db, directory="./migrations") base_dir = os.path.dirname(os.getcwd()) config_dir = os.path.join(base_dir, 'app_server/config') server = Server(host="0.0.0.0", port=8082) manager.add_command('db', MigrateCommand) @manager.command def initall(): createdb() initmember() initlecture() initquestion() initreview() initredis()
def create_app(config=None): """Create the Flask app instance that is used throughout the application. Args: config: Path to configuration file as a string or an object with config directives. Returns: Application object (instance of flask.Flask). """ # Setup the Flask app and load the config. app = Flask( __name__, template_folder=u'ui/templates', static_folder=u'ui/static') if not config: config = u'/etc/timesketch.conf' if isinstance(config, unicode): os.environ[u'TIMESKETCH_SETTINGS'] = config try: app.config.from_envvar(u'TIMESKETCH_SETTINGS') except IOError: sys.stderr.write( u'Config file {0} does not exist.\n'.format(config)) sys.exit() else: app.config.from_object(config) # Make sure that SECRET_KEY is configured. if not app.config[u'SECRET_KEY']: sys.stderr.write(u'ERROR: Secret key not present. ' u'Please update your configuration.\n' u'To generate a key you can use openssl:\n\n' u'$ openssl rand -base64 32\n\n') sys.exit() # Setup the database. configure_engine(app.config[u'SQLALCHEMY_DATABASE_URI']) db = init_db() # Alembic migration support: # http://alembic.zzzcomputing.com/en/latest/ migrate = Migrate() migrate.init_app(app, db) # Register blueprints. Blueprints are a way to organize your Flask # Flask application. See this for more information: # http://flask.pocoo.org/docs/latest/blueprints/ app.register_blueprint(user_views) app.register_blueprint(home_views) app.register_blueprint(sketch_views) app.register_blueprint(story_views) # Setup URL routes for the API. api_v1 = Api(app, prefix=u'/api/v1') api_v1.add_resource(SketchListResource, u'/sketches/') api_v1.add_resource(SketchResource, u'/sketches/<int:sketch_id>/') api_v1.add_resource( AggregationResource, u'/sketches/<int:sketch_id>/aggregation/') api_v1.add_resource(ExploreResource, u'/sketches/<int:sketch_id>/explore/') api_v1.add_resource(EventResource, u'/sketches/<int:sketch_id>/event/') api_v1.add_resource( EventAnnotationResource, u'/sketches/<int:sketch_id>/event/annotate/') api_v1.add_resource(ViewListResource, u'/sketches/<int:sketch_id>/views/') api_v1.add_resource( ViewResource, u'/sketches/<int:sketch_id>/views/<int:view_id>/') api_v1.add_resource(UploadFileResource, u'/upload/') api_v1.add_resource(TaskResource, u'/tasks/') api_v1.add_resource( StoryListResource, u'/sketches/<int:sketch_id>/stories/') api_v1.add_resource( StoryResource, u'/sketches/<int:sketch_id>/stories/<int:story_id>/') # Register error handlers # pylint: disable=unused-variable @app.errorhandler(ApiHTTPError) def handle_api_http_error(error): """Error handler for API HTTP errors. Returns: HTTP response object (instance of flask.wrappers.Response) """ return error.build_response() # Setup the login manager. login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = u'user_views.login' # This is used by the flask_login extension. # pylint: disable=unused-variable @login_manager.user_loader def load_user(user_id): """Based on a user_id (database primary key for a user) this function loads a user from the database. It is used by the Flask-Login extension to setup up the session for the user. Args: user_id: Integer primary key for the user. Returns: A user object (Instance of timesketch.models.user.User). """ return User.query.get(user_id) # Setup CSRF protection for the whole application CsrfProtect(app) return app
from flask import url_for from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_login import current_user # from flask_user import LoginManager from flask_login import login_required from config import Config from external_modules import get_user_info app = Flask(__name__) app.config.from_object(Config) database = SQLAlchemy(app) migrate = Migrate(app, database) login_manager = LoginManager(app) login_manager.login_view = 'login.login_page' app.config['UPLOAD_FOLDER'] = 'data/load_files/' app.config['ALLOWED_EXTENSIONS'] = {'txt', 'doc', 'docx'} app.config['USER_ROLES'] = { 'admin': 'Администратор', 'manager': 'Менеджер', 'executor': 'Исполнитель', 'multi': 'ФС-режим', 'debug': 'Отладчик', } app.config['PATH_TO_CHEMA'] = 'data/chemas/' app.config['PATH_TO_ANN'] = 'data/annotation/' app.config['PATH_TO_INFINITY_LOAD'] = 'static/instruction_mini.txt'
"""初始化app核心对象 配置相关插件 """ from flask import Flask from flask_migrate import Migrate from app.config import config, DevelopmentConfig, ProdConfig, TestConfig from app.web.models import db from app.web.template_env import str_time app = Flask(__name__) migrate = Migrate() migrate.init_app(app, db) #其他的初始化对象 def create_app(): """初始化""" app.config.from_object(config) # 初始化数据库 db.init_app(app) # 配置文件 # 自定义的错误处理机制 # 模板过滤器注册 # 注册蓝图 from app.web import web
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from pyrwbs.config import Config app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy() db.init_app(app) from pyrwbs.models import TestStep, TestDesStep, TestCase, Run, CaseCollector, Collection migrate = Migrate() migrate.init_app(app, db) from .views import *
from .serialization import Binary from .config import get_config __all__ = ("create_app", "db", "migrate", "login", "babel", "celery", "md") CONFIG = get_config() # build flask app app = Flask(__name__) app.config.from_object(CONFIG) # setup flask extensions csrf = CSRFProtect(app=app) db = SQLAlchemy(app=app) migrate = Migrate(app=app, db=db) babel = Babel(app=app) login = LoginManager(app=app) login.login_view = "auth.login" login.login_message = _l("Please log in to access this page.") cache = Cache(app=app, config={"CACHE_TYPE": "simple"}) mail = Mail(app=app) htmlmin = HTMLMIN(app=app) md = Markdown( extensions=[ "markdown.extensions.sane_lists", "markdown.extensions.nl2br", "markdown.extensions.codehilite", "pymdownx.extra", "pymdownx.arithmatex", "pymdownx.smartsymbols",
from flask import Flask, render_template, request, redirect, url_for, abort, flash, session from flask_migrate import Migrate, MigrateCommand from sqlalchemy.orm.exc import NoResultFound from flask_script import Manager from flask_mail import Mail from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore, login_required, current_user, user_registered import datetime from cloudinary import uploader app = Flask(__name__) app.config.from_object('kickstarter.default_settings') manager = Manager(app) db = SQLAlchemy(app) migrate = Migrate(app, db) migrate.init_app(app, db, render_as_batch=True) manager.add_command('db', MigrateCommand) from kickstarter.models import * from forms import ExtendedRegisterForm user_datastore = SQLAlchemyUserDatastore(db, Member, Role) security = Security(app, user_datastore, register_form=ExtendedRegisterForm) mail = Mail(app) import stripe stripe.api_key = app.config["STRIPE_API_KEY"] from mixpanel import Mixpanel
def create_app(config_filename="config.development.Config", app_name=None, register_blueprints=True): # App configuration app = Flask(app_name or __name__) app_settings = os.getenv("APP_SETTINGS", config_filename) print(f" * Loading config: '{app_settings}'") try: cfg = import_string(app_settings)() except ImportError: print(" *** Cannot import config ***") cfg = import_string("config.config.BaseConfig") print(" *** Default config loaded, expect problems ***") if hasattr(cfg, "post_load"): print(" *** Doing some magic") cfg.post_load() app.config.from_object(cfg) app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1) Bootstrap(app) app.jinja_env.add_extension("jinja2.ext.with_") app.jinja_env.add_extension("jinja2.ext.do") app.jinja_env.globals.update(is_admin=is_admin) if HAS_SENTRY: sentry_sdk.init( app.config["SENTRY_DSN"], integrations=[SentryFlaskIntegration(), SentryCeleryIntegration()], release=f"{VERSION} ({GIT_VERSION})", ) print(" * Sentry Flask/Celery support activated") print(" * Sentry DSN: %s" % app.config["SENTRY_DSN"]) if app.debug: app.jinja_env.auto_reload = True logging.basicConfig(level=logging.DEBUG) # Logging if not app.debug: formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]") file_handler = RotatingFileHandler("%s/errors_app.log" % os.getcwd(), "a", 1000000, 1) file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) app.logger.addHandler(file_handler) CORS(app, origins=["*"]) if app.debug: logging.getLogger("flask_cors.extension").level = logging.DEBUG mail = Mail(app) # noqa: F841 migrate = Migrate(app, db) # noqa: F841 lgtm [py/unused-local-variable] babel = Babel(app) # noqa: F841 app.babel = babel template = { "swagger": "2.0", "info": { "title": "reel2bits API", "description": "API instance", "version": VERSION }, "host": app.config["AP_DOMAIN"], "basePath": "/", "schemes": ["https"], "securityDefinitions": { "OAuth2": { "type": "oauth2", "flows": { "authorizationCode": { "authorizationUrl": f"https://{app.config['AP_DOMAIN']}/oauth/authorize", "tokenUrl": f"https://{app.config['AP_DOMAIN']}/oauth/token", "scopes": { "read": "Grants read access", "write": "Grants write access", "admin": "Grants admin operations", }, } }, } }, "consumes": ["application/json", "application/jrd+json"], "produces": ["application/json", "application/jrd+json"], } db.init_app(app) # ActivityPub backend back = Reel2BitsBackend() ap.use_backend(back) # Oauth config_oauth(app) # Setup Flask-Security security = Security( app, user_datastore) # noqa: F841 lgtm [py/unused-local-variable] @FlaskSecuritySignals.password_reset.connect_via(app) @FlaskSecuritySignals.password_changed.connect_via(app) def log_password_reset(sender, user): if not user: return add_user_log(user.id, user.id, "user", "info", "Your password has been changed !") @FlaskSecuritySignals.reset_password_instructions_sent.connect_via(app) def log_reset_password_instr(sender, user, token): if not user: return add_user_log(user.id, user.id, "user", "info", "Password reset instructions sent.") @FlaskSecuritySignals.user_registered.connect_via(app) def create_actor_for_registered_user(app, user, confirm_token): if not user: return actor = create_actor(user) actor.user = user actor.user_id = user.id db.session.add(actor) db.session.commit() @babel.localeselector def get_locale(): # if a user is logged in, use the locale from the user settings identity = getattr(g, "identity", None) if identity is not None and identity.id: return identity.user.locale # otherwise try to guess the language from the user accept # header the browser transmits. We support fr/en in this # example. The best match wins. return request.accept_languages.best_match(AVAILABLE_LOCALES) @babel.timezoneselector def get_timezone(): identity = getattr(g, "identity", None) if identity is not None and identity.id: return identity.user.timezone @app.before_request def before_request(): _config = Config.query.first() if not _config: flash(gettext("Config not found"), "error") cfg = { "REEL2BITS_VERSION_VER": VERSION, "REEL2BITS_VERSION_GIT": GIT_VERSION, "app_name": _config.app_name, "app_description": _config.app_description, } if GIT_VERSION: cfg["REEL2BITS_VERSION"] = "{0}-{1}".format(VERSION, GIT_VERSION) else: cfg["REEL2BITS_VERSION"] = VERSION g.cfg = cfg @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response # Tracks files upload set sounds = UploadSet("sounds", AUDIO) configure_uploads(app, sounds) # Album artwork upload set artworkalbums = UploadSet("artworkalbums", Reel2bitsDefaults.artwork_extensions_allowed) configure_uploads(app, artworkalbums) # Track artwork upload set artworksounds = UploadSet("artworksounds", Reel2bitsDefaults.artwork_extensions_allowed) configure_uploads(app, artworksounds) # User avatars avatars = UploadSet("avatars", Reel2bitsDefaults.avatar_extensions_allowed) configure_uploads(app, avatars) # Total max size upload for the whole app patch_request_class(app, app.config["UPLOAD_TRACK_MAX_SIZE"]) app.flake_id = FlakeId() if register_blueprints: from controllers.main import bp_main app.register_blueprint(bp_main) from controllers.admin import bp_admin app.register_blueprint(bp_admin) # ActivityPub from controllers.api.v1.well_known import bp_wellknown app.register_blueprint(bp_wellknown) from controllers.api.v1.nodeinfo import bp_nodeinfo app.register_blueprint(bp_nodeinfo) from controllers.api.v1.ap import bp_ap # Feeds from controllers.feeds import bp_feeds app.register_blueprint(bp_feeds) # API app.register_blueprint(bp_ap) from controllers.api.v1.auth import bp_api_v1_auth app.register_blueprint(bp_api_v1_auth) from controllers.api.v1.accounts import bp_api_v1_accounts app.register_blueprint(bp_api_v1_accounts) from controllers.api.v1.timelines import bp_api_v1_timelines app.register_blueprint(bp_api_v1_timelines) from controllers.api.v1.notifications import bp_api_v1_notifications app.register_blueprint(bp_api_v1_notifications) from controllers.api.tracks import bp_api_tracks app.register_blueprint(bp_api_tracks) from controllers.api.albums import bp_api_albums app.register_blueprint(bp_api_albums) from controllers.api.account import bp_api_account app.register_blueprint(bp_api_account) from controllers.api.reel2bits import bp_api_reel2bits app.register_blueprint(bp_api_reel2bits) # Pleroma API from controllers.api.pleroma_admin import bp_api_pleroma_admin app.register_blueprint(bp_api_pleroma_admin) # OEmbed from controllers.api.oembed import bp_api_oembed app.register_blueprint(bp_api_oembed) # Iframe from controllers.api.embed import bp_api_embed app.register_blueprint(bp_api_embed) swagger = Swagger( app, template=template) # noqa: F841 lgtm [py/unused-local-variable] # SPA catchalls for meta tags from controllers.spa import bp_spa app.register_blueprint(bp_spa) @app.route("/uploads/<string:thing>/<path:stuff>", methods=["GET"]) @cross_origin(origins="*", methods=["GET", "HEAD", "OPTIONS"], expose_headers="content-length", send_wildcard=True) def get_uploads_stuff(thing, stuff): if app.testing or app.debug: directory = safe_join(app.config["UPLOADS_DEFAULT_DEST"], thing) app.logger.debug(f"serving {stuff} from {directory}") return send_from_directory(directory, stuff, as_attachment=True) else: app.logger.debug(f"X-Accel-Redirect serving {stuff}") resp = Response("") resp.headers[ "Content-Disposition"] = f"attachment; filename={stuff}" resp.headers[ "X-Accel-Redirect"] = f"/_protected/media/{thing}/{stuff}" resp.headers[ "Content-Type"] = "" # empty it so Nginx will guess it correctly return resp def render_tags(tags): """ Given a dict like {'tag': 'meta', 'hello': 'world'} return a html ready tag like <meta hello="world" /> """ for tag in tags: yield "<{tag} {attrs} />".format( tag=tag.pop("tag"), attrs=" ".join([ '{}="{}"'.format(a, html.escape(str(v))) for a, v in sorted(tag.items()) if v ]), ) @app.errorhandler(404) def page_not_found(msg): excluded = ["/api", "/.well-known", "/feeds", "/oauth/authorize"] if any([request.path.startswith(m) for m in excluded]): return jsonify({"error": "page not found"}), 404 html = get_spa_html(app.config["REEL2BITS_SPA_HTML"]) head, tail = html.split("</head>", 1) request_tags = get_request_head_tags(request) default_tags = get_default_head_tags(request.path) unique_attributes = ["name", "property"] final_tags = request_tags skip = [] for t in final_tags: for attr in unique_attributes: if attr in t: skip.append(t[attr]) for t in default_tags: existing = False for attr in unique_attributes: if t.get(attr) in skip: existing = True break if not existing: final_tags.append(t) head += "\n" + "\n".join(render_tags(final_tags)) + "\n</head>" return head + tail @app.errorhandler(403) def err_forbidden(msg): if request.path.startswith("/api/"): return jsonify({"error": "access forbidden"}), 403 pcfg = { "title": gettext("Whoops, something failed."), "error": 403, "message": gettext("Access forbidden"), "e": msg, } return render_template("error_page.jinja2", pcfg=pcfg), 403 @app.errorhandler(410) def err_gone(msg): if request.path.startswith("/api/"): return jsonify({"error": "gone"}), 410 pcfg = { "title": gettext("Whoops, something failed."), "error": 410, "message": gettext("Gone"), "e": msg } return render_template("error_page.jinja2", pcfg=pcfg), 410 if not app.debug: @app.errorhandler(500) def err_failed(msg): if request.path.startswith("/api/"): return jsonify({"error": "server error"}), 500 pcfg = { "title": gettext("Whoops, something failed."), "error": 500, "message": gettext("Something is broken"), "e": msg, } return render_template("error_page.jinja2", pcfg=pcfg), 500 @app.after_request def set_x_powered_by(response): response.headers["X-Powered-By"] = "reel2bits" return response # Register CLI commands app.cli.add_command(commands.db_datas) app.cli.add_command(commands.users) app.cli.add_command(commands.roles) app.cli.add_command(commands.tracks) app.cli.add_command(commands.system) return app
app.config['ENV'] = 'development' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this! app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_SSL'] = True app.config[ 'MAIL_USERNAME'] = '******' #La cuenta de correo electronico de donde saldran los correos app.config['MAIL_PASSWORD'] = '' app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'static') jwt = JWTManager(app) db.init_app(app) Migrate(app, db) CORS(app) bcrypt = Bcrypt(app) mail = Mail(app) manager = Manager(app) manager.add_command("db", MigrateCommand) @app.route("/") def root(): return render_template('index.html') @app.route('/login', methods=['POST']) def login(): if not request.is_json:
"""Manage module to migrate to db""" import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import create_app, db from app.models.command import Command app = create_app() # pylint: disable=invalid-name app.config.from_object(os.environ["APP_SETTINGS"]) migrate = Migrate(app, db) # pylint: disable=invalid-name manager = Manager(app) # pylint: disable=invalid-name # Manager Commands manager.add_command("db", MigrateCommand) @manager.command def seed(): "Load initial commands into database." def upsert_cmd(cmd): """Update cmd if exists, insert otherwise""" old_cmd = db.session.query(Command).filter( Command.cmd == cmd.cmd).first() if old_cmd: old_cmd.bot_name = cmd.bot_name db.session.merge(old_cmd)