from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager gem = Flask(__name__) gem.config.from_object(Config) db = SQLAlchemy(gem) migrate = Migrate(gem, db) login = LoginManager(gem) login.login_view = 'login' from gem import routes, models
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:
def init_db(app): db = SQLAlchemy(app) migrate = Migrate(app, db) return db, migrate
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
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
# project/__init__.py import os from flask import Flask from flask_cors import CORS from flask_debugtoolbar import DebugToolbarExtension from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate # instantiate the extensions db = SQLAlchemy() migrate = Migrate() toolbar = DebugToolbarExtension() def create_app(script_info=None): # instantiate the app app = Flask(__name__) # enable CORS CORS(app) # set config app_settings = os.getenv('APP_SETTINGS') app.config.from_object(app_settings) # set up extensions
import json from rq import Queue from rq.job import Job from worker import conn from flask import Flask, render_template, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from stop_words import stops from collections import Counter from bs4 import BeautifulSoup app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) migrate = Migrate(app, db) q = Queue(connection=conn) from models import Result # noqa workaround for circular import def sanitize_url(url): return url if 'http://' in url or 'https://' in url else f'https://{url}' def count_and_save_words(url): errors = [] try: r = requests.get(sanitize_url(url)) except Exception:
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)
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 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
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_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)
import os from flask import Flask, request, jsonify, url_for from flask_migrate import Migrate from flask_swagger import swagger from flask_cors import CORS from flask_jwt_simple import ( JWTManager, jwt_required, create_jwt, get_jwt_identity ) from utils import APIException, generate_sitemap from models import db, Person app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False MIGRATE = Migrate(app, db) db.init_app(app) CORS(app) # Setup the Flask-JWT-Simple extension app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this! jwt = JWTManager(app) # Provide a method to create access tokens. The create_jwt() # function is used to actually generate the token @app.route('/login', methods=['POST']) def login(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400
def register_extensions(app): db.app = app db.init_app(app) migrate = Migrate(app, db)
from flask_mail import Mail from flask_moment import Moment from flask_uploads import configure_uploads, IMAGES, UploadSet app = Flask(__name__) app.config.from_object(Config) images = UploadSet('images', IMAGES) clips = UploadSet('videos', extensions=('mp4')) configure_uploads(app, (images, clips)) bootstrap = Bootstrap(app) db = SQLAlchemy(app) migrate = Migrate(app, db, render_as_batch=True) login = LoginManager(app) login.login_view = 'login' #points to the url_for('login') to handle the view avatars = Avatars(app) mail = Mail(app) moment = Moment(app) if not app.debug: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
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'
for line in open('.env'): kv = regex.sub("", line).strip() if '=' not in kv: continue name, value = kv.split('=', 1) os.environ[name] = value from sirius.web import webapp from sirius.fake import commands as fake_commands from sirius.emulate import commands as emulate_commands from flask_script import Manager, Shell from flask_migrate import Migrate, MigrateCommand app = webapp.create_app(os.getenv('FLASK_CONFIG', 'default')) manager = Manager(app) migrate = Migrate(app, webapp.db) def make_shell_context(): return dict(app=app, db=webapp.db) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) manager.add_command('fake', fake_commands.fake_manager) manager.add_command('emulate', emulate_commands.manager) @manager.command def deploy(): """Run deployment tasks."""
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",
@login.user_loader def load_user(id): return User.query.get(int(id)) # Tell flask about our seed commands app.cli.add_command(seed_commands) app.config.from_object(Config) app.register_blueprint(user_routes, url_prefix='/api/users') app.register_blueprint(auth_routes, url_prefix='/api/auth') app.register_blueprint(sticker_routes, url_prefix='/api/stickers') app.register_blueprint(post_routes, url_prefix='/api/posts') app.register_blueprint(stickerpacks_routes, url_prefix='/api/stickerpacks') db.init_app(app) Migrate(app, db, compare_type=True) # Application Security CORS(app) # Since we are deploying with Docker and Flask, # we won't be using a buildpack when we deploy to Heroku. # Therefore, we need to make sure that in production any # request made over http is redirected to https. # Well......... @app.before_request def https_redirect(): if os.environ.get('FLASK_ENV') == 'production': if request.headers.get('X-Forwarded-Proto') == 'http':
"""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)