def base_app(): global app app = Flask('backend') app.config.overrides = {} logging.info('Connecting to database...') engine = create_engine(backend.settings.db_connection) app.engine = engine base = automap_base() base.prepare(engine, reflect=True) session = Session(engine) app.base = base app.session = session app.Decl_Base = declarative_base() from backend.models import Members app.Decl_Base.metadata.create_all(app.engine) # Create the Flask-Restless API manager. app.api_manager = flask.ext.restless.APIManager(app, session=app.session) app.api_manager.create_api(Members, methods=['GET', 'POST', 'PATCH', 'DELETE'], collection_name='members') return app @app.route("/shutdown", methods=["POST"]) # pragma: no cover def shutdown(): # pragma: no cover logging.info('shutting down server') shutdown_server() return "server shutting down"
def create_app(): """Application factory.""" app = Flask(__name__) app.register_blueprint(user_bp) app.session = session configure(app) return app
def create_app(): """REANA Server application factory.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT) app = Flask(__name__) app.config.from_object('reana_server.config') app.secret_key = "hyper secret key" app.session = Session Babel(app) FlaskMenu(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) # Register Invenio OAuth endpoints app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) # Register API routes from .rest import gitlab, ping, secrets, users, workflows # noqa app.register_blueprint(ping.blueprint, url_prefix='/api') app.register_blueprint(workflows.blueprint, url_prefix='/api') app.register_blueprint(users.blueprint, url_prefix='/api') app.register_blueprint(secrets.blueprint, url_prefix='/api') app.register_blueprint(gitlab.blueprint, url_prefix='/api') return app
def create_app(config_mapping=None): """Create REANA-Job-Controller application.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT) app = Flask(__name__) app.secret_key = "mega secret key" app.session = Session app.config.from_object(config) if config_mapping: app.config.from_mapping(config_mapping) if "htcondorcern" in app.config["SUPPORTED_COMPUTE_BACKENDS"]: app.htcondor_executor = ThreadPoolExecutor(max_workers=1) with app.app_context(): app.config["OPENAPI_SPEC"] = build_openapi_spec() from reana_job_controller.rest import blueprint # noqa app.register_blueprint(blueprint, url_prefix="/") # Close session after each request app.teardown_request(shutdown_session) # Close session on app teardown app.teardown_appcontext(shutdown_session) return app
def create_app(db_uri: str = "sqlite://"): """ Create a Flask application instance. Initializes the database, app routes, and extensions. :param db_uri: Database uri """ app = Flask('featuresreq') # Intialize the datbase engine = create_engine(db_uri) session_factory.configure(bind=engine) session = flask_scoped_session(session_factory, app) app.session = session # Register blueprints app.register_blueprint(bp) # Bootstrap the database models and Clients @app.before_first_request def bootstrap_client_models(): Base.metadata.create_all(engine) for c in ("a", "b", "c"): name = "Client {}".format(c.upper()) client = session.query(Client).filter( func.lower(Client.name) == name.lower()).first() if client is None: client = Client(name=name) session.add(client) session.commit() return app
def create_app(config_class=Config): application = Flask(__name__) application.config.from_object(config_class) application.engine = create_engine(config_class.SQLALCHEMY_DATABASE_URI) Session = sessionmaker(bind=application.engine) application.session = Session() migrate.init_app(application, Base) return application
def create(): app = Flask(__name__) app.register_blueprint(routes.endpoints) session = _make_session() app.session = session return app
def create_app(config_file_path: str = None, config_dict: Dict[str, Any] = None): """ This method will create a new flask application with the wanted config. @param config_file_path python file that contain parameter(s) @param config_dict a python dict that contain parameter(s) """ app = Flask(__name__, static_url_path='') # create the application instance if config_file_path: # update config from file app.config.from_pyfile(config_file_path) elif config_dict: # update config from dict app.config.update(config_dict) # verify directories set in the config files exists verify_directories_exist(app) if __name__ != '__main__': init_logger(app) # define the sqlite file database, BEWARE ! if you modify it, you need to modify models/base.py app.config.update( SQLALCHEMY_DATABASE_URI=app.config['DATABASE_URI']) # Connecting to the database with the settings of the app db.init_app(app) app.session = db.session # create a statificationProcess object with the configuration app.statifProcess = StatificationProcess.StatificationProcess( s_logger=app.name, s_repository_path=app.config['STATIC_REPOSITORY'], s_python_path=app.config['PYTHONPATH'], s_urls=app.config['URLS'], s_domains=app.config['DOMAINS'], s_log_file=app.config['LOGFILE'], s_project_directory=app.config['PROJECT_DIRECTORY'], s_pid_file=app.config['PIDFILE'], s_lock_file=app.config['LOCKFILE'], s_crawler_progress_counter_file=app.config['CRAWLER_PROGRESS_COUNTER_FILE'], s_delete_files=app.config['DELETE_FILES'], s_delete_directories=app.config['DELETE_DIRECTORIES'], s_url_regex=app.config['URL_REGEX'], s_url_replacement=app.config['URL_REPLACEMENT'], s_database_uri=app.config['DATABASE_URI'] ) app.register_blueprint(cornetto) db.create_all(app=app) return app
def create_app(config_mapping=None): """REANA Workflow Controller application factory.""" app = Flask(__name__) app.config.from_object('reana_workflow_controller.config') if config_mapping: app.config.from_mapping(config_mapping) app.secret_key = "super secret key" # Register API routes from .rest import restapi_blueprint # noqa app.register_blueprint(restapi_blueprint, url_prefix='/api') app.session = Session return app
def create_app(config_mapping=None): """REANA Server application factory.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT, force=True) app = Flask(__name__) app.config.from_object("reana_server.config") if config_mapping: app.config.from_mapping(config_mapping) app.secret_key = "hyper secret key" app.session = Session Babel(app) FlaskMenu(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) # Register Invenio OAuth endpoints app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) # Register API routes from .rest import ( config, gitlab, ping, secrets, status, users, workflows, info, ) # noqa app.register_blueprint(ping.blueprint, url_prefix="/api") app.register_blueprint(workflows.blueprint, url_prefix="/api") app.register_blueprint(users.blueprint, url_prefix="/api") app.register_blueprint(secrets.blueprint, url_prefix="/api") app.register_blueprint(gitlab.blueprint, url_prefix="/api") app.register_blueprint(config.blueprint, url_prefix="/api") app.register_blueprint(status.blueprint, url_prefix="/api") app.register_blueprint(info.blueprint, url_prefix="/api") @app.teardown_appcontext def shutdown_session(response_or_exc): """Close session on app teardown.""" current_app.session.remove() return response_or_exc return app
def create_app(): """REANA Server application factory.""" app = Flask(__name__) app.config.from_object('reana_server.config') app.secret_key = "hyper secret key" # Register API routes from .rest import ping, workflows, users # noqa app.register_blueprint(ping.blueprint, url_prefix='/api') app.register_blueprint(workflows.blueprint, url_prefix='/api') app.register_blueprint(users.blueprint, url_prefix='/api') app.session = Session CORS(app) return app
def create_app(): app = Flask(__name__, instance_relative_config=False) app.config.from_object(AppConfig) app.session = db_session login_manager.init_app(app) with app.app_context(): from .home import home from .auth import auth from . import callbacks app.register_blueprint(home.home_bp) app.register_blueprint(auth.auth_bp) from .plotlydash.dashboard import create_dashboard app = create_dashboard(app) return app
def create_app(): app = Flask(__name__) app.config.from_pyfile('config.py') app.register_blueprint(root.mod, url_prefix='/') app.register_blueprint(admin.mod, url_prefix='/wechat-admin') app.register_blueprint(u.mod, url_prefix='/u') scheduler = APScheduler() scheduler.init_app(app) scheduler.start() with app.app_context(): app.admin = Admin() app.msg_logger = MsgLogger() app.location = LocationDB() app.session = SessionDB() app.wisedu = WiseduDB() return app
def create_app(): """REANA Server application factory.""" logging.basicConfig( level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT ) app = Flask(__name__) app.config.from_object('reana_server.config') app.secret_key = "hyper secret key" # Register API routes from .rest import ping, secrets, users, workflows # noqa app.register_blueprint(ping.blueprint, url_prefix='/api') app.register_blueprint(workflows.blueprint, url_prefix='/api') app.register_blueprint(users.blueprint, url_prefix='/api') app.register_blueprint(secrets.blueprint, url_prefix='/api') app.session = Session CORS(app) return app
def create_app(config_mapping=None): """REANA Workflow Controller application factory.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT) app = Flask(__name__) app.config.from_object('reana_workflow_controller.config') if config_mapping: app.config.from_mapping(config_mapping) app.secret_key = "super secret key" # Register API routes from reana_workflow_controller.rest import ( workflows_session, workflows_status, workflows_workspace, workflows, ) # noqa app.register_blueprint(workflows_session.blueprint, url_prefix='/api') app.register_blueprint(workflows.blueprint, url_prefix='/api') app.register_blueprint(workflows_status.blueprint, url_prefix='/api') app.register_blueprint(workflows_workspace.blueprint, url_prefix='/api') app.session = Session return app
def get_app(): config = configparser.ConfigParser() config.readfp(open(settings_file)) engine = create_engine(config.get(config_section, 'uri')) Session = sessionmaker(bind=engine) app = Flask(__name__) @app.before_request def before_request(): g.session = Session() @app.after_request def session_commit(response): session = getattr(g, 'session', None) if session is not None: if response.status_code // 200 == 1: g.session.commit() else: g.session.rollback() return response app.session = Session() return app
def base_app(): """Flask application fixture.""" config_mapping = { 'AVAILABLE_WORKFLOW_ENGINES': 'serial', 'SERVER_NAME': 'localhost:5000', 'SECRET_KEY': 'SECRET_KEY', 'TESTING': True, 'SHARED_VOLUME_PATH': '/tmp/test', 'SQLALCHEMY_DATABASE_URI': 'sqlite:///', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, } app = Flask(__name__) app.config.from_mapping(config_mapping) app.secret_key = "hyper secret key" # Register API routes from reana_server.rest import ping, workflows, users, secrets # noqa app.register_blueprint(ping.blueprint, url_prefix='/api') app.register_blueprint(workflows.blueprint, url_prefix='/api') app.register_blueprint(users.blueprint, url_prefix='/api') app.register_blueprint(secrets.blueprint, url_prefix='/api') app.session = Session return app
dot_env = realpath(join(root_dir, "../.env")) flask_templates_dir = realpath(join(dirname(__file__), "templates")) app = Flask(__name__, template_folder=flask_templates_dir) app.basic_auth = BasicAuth(app) app.config["TEMPLATES_DIR"] = flask_templates_dir app.config["DATAFRAMES_DIR"] = realpath(join(dirname(__file__), "dataframes")) UPLOAD_FOLDER = join(root_dir, "uploads") ALLOWED_EXTENSIONS = set( [".docx", ".xlsx", ".txt", ".pdf", ".png", ".jpg", ".jpeg", ".gif"]) app.secret_key = "development key" app.session = Session() app.config['SESSION_PERMANENT'] = True app.config['SESSION_TYPE'] = 'filesystem' app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=5) # The maximum number of items the session stores # before it starts deleting some, default 500 app.config['SESSION_FILE_THRESHOLD'] = 100 app.session.init_app(app) app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0 app.config["CACHE_TYPE"] = "null" app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = "******" app.config["MAIL_PASSWORD"] = "******"
# We use SQLite in memory. # This has a downside that the database is lost when the server is restarted. # In the future we want to use an on-disk database. # Set on-disk database with a location set by an environment variable. # See https://github.com/calmoo/todo_api/issues/9. SQLALCHEMY_DATABASE_URL = "sqlite://" app = Flask(__name__) # Start the database and create database tables. # This is inspired by # https://towardsdatascience.com/use-flask-and-sqlalchemy-not-flask-sqlalchemy-5a64fafe22a4 # We have to use the StaticPool class to run the database in memory. engine = create_engine(SQLALCHEMY_DATABASE_URL, poolclass=StaticPool) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) models.Base.metadata.create_all(bind=engine) app.session = scoped_session(SessionLocal) # We use "PROPAGATE_EXCEPTIONS" so that errors are sent to the client. # This allows us to put breakpoints in endpoints. app.config["PROPAGATE_EXCEPTIONS"] = True # The JWT_SECRET_KEY is used to create a user's session token. # If this leaks then a bad actor could impersonate any user. # We use JWT because it allows a user to authenticate with a token provided by # the server after login # We use an environment variable so that each instance of the server can have # a different secret key. # We do not have a default secret key because if a user runs this in production # we do not want there to be any chance that they have not # set a JWT secret key. app.config["JWT_SECRET_KEY"] = os.environ["JWT_SECRET_KEY"]
from contextlib import contextmanager from datetime import datetime import _strptime # https://bugs.python.org/issue7980 from flask import Flask, request, jsonify, _app_ctx_stack from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from models.models import Base, Sensor, LoraEvent db_url = "sqlite:///../ttn/src/sensors/target/data/lora.mqtt.db" engine = create_engine(db_url, echo=False) Base.metadata.create_all(engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) app = Flask(__name__) app.session = scoped_session(SessionLocal, scopefunc=_app_ctx_stack.__ident_func__) app.debug = True @contextmanager def session_scope(): """ Provide a transactional scope around a series of operations""" session = app.session try: yield session session.commit() except: session.rollback() raise finally: session.close()
patch_all() from psycogreen.gevent import patch_psycopg patch_psycopg() using_gevent = True else: using_gevent = False app = Flask(__name__) app.config.from_object('ooi_status.default_settings') if 'OOISTATUS_SETTINGS' in os.environ: app.config.from_envvar('OOISTATUS_SETTINGS') app.json_encoder = StatusJsonEncoder app.engine = create_engine(app.config['MONITOR_URL']) app.metadata_engine = create_engine(app.config['METADATA_URL']) app.sessionmaker = sessionmaker(bind=app.engine) app.session = scoped_session(app.sessionmaker) app.metadata_sessionmaker = sessionmaker(bind=app.metadata_engine) app.metadata_session = scoped_session(app.metadata_sessionmaker) MetadataBase.query = app.session.query_property() MonitorBase.query = app.session.query_property() if using_gevent: app.engine.pool._use_threadlocal = True import ooi_status.api.views
from sqlalchemy.orm import scoped_session from app.database import db_session from flask_jwt_extended import (JWTManager, jwt_required, create_access_token, get_jwt_identity) #def create_app(test_config=None): # App init app = Flask(__name__, instance_relative_config=True) # App config app.config.from_mapping(SECRET_KEY='dev', ) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app, resources={r"/.*": {"origins": "http://localhost"}}) app.session = scoped_session(db_session, scopefunc=_app_ctx_stack.__ident_func__) # Init plugins bcrypt = Bcrypt(app) # Database from app.database import * init_app(app) # JWT app.config['JWT_SECRET_KEY'] = 'super-secret' jwt = JWTManager(app) # Load endpoints from . import users app.register_blueprint(users.bp)
import flask from flask import Flask, render_template, redirect import re MAX_LOG_LINE_LEN = 1500 app = Flask(__name__) app.session = None def commify(number): number = str(number) processing = 1 regex = re.compile(r"^(-?\d+)(\d{3})") while processing: (number, processing) = regex.subn(r"\1,\2", number) return number @app.route("/togglepause") def pause(): # Flip our state app.session.is_paused = not app.session.is_paused return redirect('/') @app.route('/test-case/<int:crash_id>') def test_case(crash_id): return render_template("test-case.html", crashinfo=app.session.procmon_results.get(crash_id, None), test_case=app.session.test_case_data(crash_id))
from sqlalchemy.orm import sessionmaker from models import Base, User, Restaurant, MenuItem app = Flask(__name__) import modules.views import modules.api import modules.signin engine = create_engine('sqlite:///app.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() app.session = session ############################################### # HELPER FUNCTIONS ############################################## def createUser(login_session): newUser = User(name=login_session['username'], email=login_session['email'], picture=login_session['picture']) session.add(newUser) session.commit() return session.query(User)\ .filter_by(email=login_session['email'])\ .first() app.createUser = createUser
from util.query import operator_categories import util.query import util.session_holder with open("config.json") as f: config = json.load(f) app = Flask(__name__) app.register_blueprint(location_list.blueprint) engine = sqlalchemy.create_engine(config["database-string"], echo=config.get("echo-sql", False)) session_local = sqlalchemy.orm.sessionmaker(autocommit=True, autoflush=True, bind=engine) app.session = sqlalchemy.orm.scoped_session( session_local, scopefunc=_app_ctx_stack.__ident_func__) util.session_holder.session = app.session locale.setup_copperswallow_strings(app.session) def no(*args, **kwargs): return # Monkeypatch our autocommitting autoflushing session to do nothing with that app.session.flush = no class UnauthenticatedException(Exception): pass
using_gevent = True else: using_gevent = False app = Flask(__name__) app.config.from_object('ooi_status.default_settings') if 'OOISTATUS_SETTINGS' in os.environ: app.config.from_envvar('OOISTATUS_SETTINGS') app.json_encoder = StatusJsonEncoder app.engine = create_engine(app.config['MONITOR_URL']) app.metadata_engine = create_engine(app.config['METADATA_URL']) app.sessionmaker = sessionmaker(bind=app.engine) app.session = scoped_session(app.sessionmaker) app.metadata_sessionmaker = sessionmaker(bind=app.metadata_engine) app.metadata_session = scoped_session(app.metadata_sessionmaker) MetadataBase.query = app.session.query_property() MonitorBase.query = app.session.query_property() if using_gevent: app.engine.pool._use_threadlocal = True import ooi_status.api.views
from flask import Flask, render_template, redirect import re app = Flask(__name__) app.session = None def commify(number): number = str(number) processing = 1 regex = re.compile(r"^(-?\d+)(\d{3})") while processing: (number, processing) = regex.subn(r"\1,\2", number) return number @app.route("/togglepause") def pause(): # Flip our state app.session.is_paused = not app.session.is_paused return redirect('/') @app.route('/view_crash/<int:crash_id>') def view_crash(crash_id): return render_template("view_crash.html", crashinfo=app.session.procmon_results[crash_id]) @app.route("/") def index(): crashes = []
from flask import Flask, _app_ctx_stack from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_migrate import Migrate from sbs.models.database import SessionLocal, engine, Base from sqlalchemy.orm import scoped_session, Session app = Flask(__name__) # app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:root@localhost/banking_system" db_session = scoped_session(SessionLocal, scopefunc=_app_ctx_stack.__ident_func__) app.session = db_session app.secret_key = "MySecureBankingApp" login_manager = LoginManager(app) bcrypt = Bcrypt(app) Base.query = db_session.query_property() from routes import * from sbs.utils import PrivilegeLevels def create_tables(): Base.metadata.create_all(bind=engine) def init(): admin_user = '******' admin_password = bcrypt.generate_password_hash('admin') emp_id = 'E0001'
from flask import Flask, request, jsonify from flask_cors import CORS from sqlalchemy.orm import scoped_session import models from db import local_session, engine, Base app = Flask(__name__) CORS(app) app.session = scoped_session(local_session) ############ client commands ########## @app.cli.command('db_create') def db_create(): Base.metadata.create_all(bind=engine) print("Database Created!") @app.cli.command('db_drop') def db_drop(): app.session.close() Base.metadata.drop_all(bind=engine) print("Database Dropped!") @app.cli.command('db_seed') def db_seed(): earth = models.Locations( city='Sydney', planet='Earth', capacity=50,
# This dict is called on every .html document. # We initialize it here in case all the fields aren't defined by the view method. page = {'title': '', 'url': '', 'description': ''} pages = FlatPages(app) # SITE CONFIG # Most of these vars are used on the site in some way. # We store them here and then pass them to the template (you see them as response.app....) with app.app_context(): app.url_root = '/' app.page = page app.sessions = [ '2011a', '2012a', '2012b', '2013a', '2014a', '2015a', '2016a', '2017a' ] #***HC - append the next session app.session = '2017a' #***HC CURRENT SESSION - replace with the next session # THE WEEK WE START PUBLISHING THE WEEK... need to figure out how we know when to end it. app.theweek = { '2017a': date(2017, 1, 23), '2016a': date(2016, 2, 20) } #***HC - append app.session_dates = { '2017a': [date(2017, 1, 13), date(2017, 5, 11)], '2016a': [date(2016, 1, 13), date(2016, 5, 11)] } #***HC - append try: days = json.load(open('_input/days_%s.json' % app.session)) weeks = json.load(open('_input/weeks_%s.json' % app.session)) app.recent = {'week': weeks[-1], 'day': days[-1]} except: app.recent = {'week': '', 'day': ''}
import app.index.routes as index import app.sensors.routes as sensors import app.statistic.routes as statistic import app.token.routes as token import app.users.routes as users from config import Config # Setup app app = Flask(__name__) app.auth = auth app.config.from_object(Config) app.cassandra_auth_provider = PlainTextAuthProvider(username=app.config['CASSANDRA_USERNAME'], password=app.config['CASSANDRA_PASSWORD']) app.cluster = Cluster([app.config['CASSANDRA_CLUSTER_HOST']], auth_provider=app.cassandra_auth_provider) app.session = app.cluster.connect() app.session.set_keyspace('kaspa') connection.register_connection('clusterKaspa', session=app.session) connection.set_default_connection('clusterKaspa') models.DEFAULT_KEYSPACE = 'kaspa' app.register_blueprint(auth.mod) app.register_blueprint(index.mod) app.register_blueprint(sensors.mod) app.register_blueprint(statistic.mod) app.register_blueprint(token.mod) app.register_blueprint(users.mod)
from flask import Flask import datetime import os import sys from .config import * from .MongoSession import MongoSession import pymongo app = Flask(__name__) DOMAIN = ".arheneos.com" if sys.platform != 'darwin' else None app.static_folder = f"../../{staticFolder}" app.template_folder = f"../../{templateFolder}" app.config['JWT_KEY'] = 'secret' app.config['JSON_AS_ASCII'] = False app.config['SESSION_COOKIE_DOMAIN'] = DOMAIN app.config['REMEMBER_COOKIE_DOMAIN'] = DOMAIN app.config['REMEMBER_COOKIE_SECURE'] = sys.platform != 'darwin' app.config['REMEMBER_COOKIE_HTTPONLY'] = sys.platform != 'darwin' app.config['COOKIE_HTTPONLY'] = True app.config['COOKIE_SECURE'] = True app.config['SEND_FILE_MAX_AGE_DEFAULT'] = datetime.timedelta(days=30) app.config['SESSION_COOKIE_SECURE'] = sys.platform != 'darwin' FORK_SAFE_MONGO_CLIENT = pymongo.MongoClient('localhost', 27017, **{"maxPoolSize": 1024, "connectTimeoutMS": 10000, "socketTimeoutMS": 10000, "waitQueueTimeoutMS": 10000}) app.session = MongoSession(FORK_SAFE_MONGO_CLIENT)
def create_app(): Base.metadata.create_all(bind=engine) util.load_env() app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) app.session = scoped_session(SessionLocal, scopefunc=_app_ctx_stack.__ident_func__) app.json_encoder = util.AppModelEncoder # cache = Cache(app) if os.environ['FLASK_ENV'] != 'production': @app.route('/') def show_top(): TOP_AUTHORS_LIMIT = 4 fake_quote = app.session.query(FakeQuote).filter_by( id=TOP_QUOTE_ID).first() authors = app.session.query(Author) \ .order_by(func.random()) \ .limit(TOP_AUTHORS_LIMIT) \ .all() for author in authors: books = app.session.query(Book) \ .filter(Book.author_id==author.id) \ .order_by(Book.title) \ .limit(CHILDREN_LIMIT) \ .all() setattr(author, 'books', books) book_count = app.session.query(Book) \ .filter(Book.author_id==author.id) \ .count() setattr(author, 'book_count', book_count) return render_template('top.html', fake_quote=fake_quote, authors=authors) @app.route('/fake_quotes/random/') def show_random_quote(): # Pick Random Fake Quote fake_quote = app.session.query(FakeQuote).order_by( func.random()).first() # return render_fake_quote_page(fake_quote) return redirect( url_for('show_fake_quote', fake_quote_id=fake_quote.id, profile=request.args.get('profile', 0))) @app.route('/fake_quotes/<fake_quote_id>') def show_fake_quote(fake_quote_id): # When invalid id is passed, just redirect to random page if not util.is_uuid(fake_quote_id): return redirect(url_for('show_random_quote')) fake_quote = app.session.query(FakeQuote).filter( FakeQuote.id == fake_quote_id).first() if fake_quote == None: return redirect(url_for('show_random_quote')) return render_fake_quote_page(fake_quote) @app.route('/original_authors') def list_authors(): page = get_page() offset = get_offset(page) authors = app.session.query(Author) \ .order_by(Author.name_kana) \ .offset(offset) \ .limit(PER_PAGE) \ .all() for author in authors: books = app.session.query(Book) \ .filter(Book.author_id==author.id) \ .order_by(Book.title) \ .limit(CHILDREN_LIMIT) \ .all() setattr(author, 'books', books) book_count = app.session.query(Book) \ .filter(Book.author_id==author.id) \ .count() setattr(author, 'book_count', book_count) pagination = get_pagenate(page, Author) return render_template('original_author_list.html', authors=authors, pagination=pagination) @app.route('/fake_authors') def list_fake_authors(): page = get_page() offset = get_offset(page) fake_authors = app.session.query(FakeAuthor) \ .order_by(FakeAuthor.name) \ .offset(offset) \ .limit(PER_PAGE) \ .all() return render_fake_author_book_list(page, '', fake_authors) def render_fake_author_book_list(page, author, fake_authors, query_filter=None): for fake_author in fake_authors: fake_books = app.session.query(FakeBook) \ .filter(FakeBook.fake_author_id==fake_author.id) \ .order_by(FakeBook.title) \ .limit(CHILDREN_LIMIT) \ .all() setattr(fake_author, 'fake_books', fake_books) fake_book_count = app.session.query(FakeBook) \ .filter(FakeBook.fake_author_id==fake_author.id) \ .count() setattr(fake_author, 'fake_book_count', fake_book_count) pagination = get_pagenate(page, FakeAuthor, query_filter) return render_template('fake_list.html', fake_authors=fake_authors, author=author, pagination=pagination) @app.route('/original_quotes/<quote_id>/fake_quotes') def list_fake_quotes_by_quote(quote_id): page = get_page() offset = get_offset(page) # When invalid id is passed, just redirect to random page if not util.is_uuid(quote_id): return redirect(url_for('show_random_quote')) quote = app.session.query(Quote) \ .filter(Quote.id==quote_id) \ .first() if quote == None: return redirect(url_for('show_random_quote')) query_filter = (FakeQuote.quote_id == quote_id) fake_quotes = app.session.query(FakeQuote) \ .filter(query_filter) \ .order_by(FakeQuote.text) \ .offset(offset) \ .limit(PER_PAGE) \ .all() pagination = get_pagenate(page, FakeQuote, query_filter) return render_template('fake_quote_list.html', quote=quote, fake_quotes=fake_quotes, pagination=pagination) @app.route('/original_authors/<author_name>/fake_authors') def list_all_fake_books(author_name): page = get_page() offset = get_offset(page) author = app.session.query(Author).filter_by( name=author_name).first() if author == None: flash(random_not_found_message(author_name)) return abort(404) fake_authors = app.session.query(FakeAuthor) \ .filter(FakeAuthor.author_id==author.id) \ .order_by(FakeAuthor.name) \ .offset(offset) \ .limit(PER_PAGE) \ .all() query_filter = (FakeAuthor.author_id == author.id) return render_fake_author_book_list(page, author, fake_authors, query_filter) @app.route('/fake_authors/<fake_author_name>/fake_books') def list_fake_books(fake_author_name): fake_author = app.session.query(FakeAuthor).filter_by( name=fake_author_name).first() if fake_author == None: flash(random_not_found_message(fake_author_name)) return abort(404) page = page = get_page() offset = get_offset(page) query_filter = (FakeBook.fake_author_id == fake_author.id) # .order_by(asc(collate(FakeBook.title, 'ja-x-icu'))) \ fake_books = app.session.query(FakeBook) \ .filter(query_filter) \ .order_by(FakeBook.title) \ .offset(offset) \ .limit(PER_PAGE) \ .all() pagination = get_pagenate(page, FakeBook, query_filter) return render_template('fake_book_list.html', fake_author=fake_author, fake_books=fake_books, pagination=pagination) @app.route('/books/<book_id>/quotes') def list_quotes_by_book(book_id): if not util.is_uuid(book_id): return redirect(url_for('show_random_quote')) book = app.session.query(Book) \ .filter_by(id=book_id).first() if book == None: return redirect(url_for('show_random_quote')) page = page = get_page() offset = get_offset(page) query_filter = (Quote.book_id == book_id) quotes = app.session.query(Quote) \ .filter(query_filter) \ .order_by(Quote.text) \ .offset(offset) \ .limit(PER_PAGE) \ .all() pagination = get_pagenate(page, Quote, query_filter) return render_template('quote_list.html', book=book, quotes=quotes, pagination=pagination) # @app.errorhandler(404) # def not_found(e): # return render_template('404.html') # if os.environ['FLASK_ENV'] == 'production': # @app.errorhandler(Exception) # def handle_exception(e): # print(e) # app.session.rollback() # return render_template('500.html') @app.teardown_appcontext def remove_session(*args, **kwargs): app.session.remove() # Utility functions def random_not_found_message(name): # これも生成する? message = random.choice(['は聞いたことがありませんね', 'の取り扱いはありません', '...?有名な人?']) return '{}{}'.format(name, message) def get_pagenate(page, model_class, filters=None): msg = " " # "全{total}人中 {start} - {end}人表示中</b>" query = app.session.query(model_class) if filters is not None: query = query.filter(filters) total = query.count() record_name = model_class.__table__.name pagination = Pagination(page=page, display_msg=msg, per_page=PER_PAGE, total=total, record_name=record_name) return pagination def get_offset(page): return PER_PAGE * (page - 1) def get_page(): return request.args.get(get_page_parameter(), type=int, default=1) # Common rendering function def render_fake_quote_page(fake_quote): # prev_fake_quote_id = get_prev_fake_quote(fake_quote) # next_fake_quote_id = get_next_fake_quote(fake_quote) prev_fake_quote_id = None next_fake_quote_id = None return render_template( 'quote.html', fake_quote=fake_quote, twitter_share=get_twitter_share_info(fake_quote), profile_image_idx=get_profile_image_idx(), prev_fake_quote_id=prev_fake_quote_id, next_fake_quote_id=next_fake_quote_id, ) # def get_next_fake_quote(current_fake_quote): # next_quote = app.session.query(FakeQuote) \ # .filter(FakeQuote.id!=current_fake_quote.id) \ # .filter(FakeQuote.text > current_fake_quote.text) \ # .order_by(FakeQuote.text) \ # .first() # return next_quote.id if next_quote is not None else None # def get_prev_fake_quote(current_fake_quote): # prev_quote = app.session.query(FakeQuote) \ # .filter(FakeQuote.id!=current_fake_quote.id) \ # .filter(FakeQuote.text < current_fake_quote.text) \ # .order_by(FakeQuote.text) \ # .first() # return prev_quote.id if prev_quote is not None else None def get_twitter_share_info(fake_quote): MAX_LENGTH = 100 share_url = urllib.parse.quote( url_for('show_fake_quote', fake_quote_id=fake_quote.id, _external=True)) text = '{}\n\n{}『{}』'.format(fake_quote.text, fake_quote.fake_book.fake_author.name, fake_quote.fake_book.title) if len(text) >= MAX_LENGTH: text = text[:MAX_LENGTH] + '...' share_text = urllib.parse.quote(text) return {'url': share_url, 'text': share_text} def get_profile_image_idx(): MAX_PROFILE_INDEX = 2 request_profile = request.args.get('profile', 0) try: idx = int(request_profile) except ValueError: idx = 0 return MAX_PROFILE_INDEX if idx > MAX_PROFILE_INDEX else idx ##################### # JSON API ##################### @app.route('/api/fake_quotes/random') def api_random_fake_quotes(): query = app.session.query(FakeQuote.id) # If fake_quote_id is passed, get another one fake_quote_id = request.args.get('fake_quote_id', None) if fake_quote_id is not None and util.is_uuid(fake_quote_id): query = query.filter(FakeQuote.id != fake_quote_id) fake_quote = query.order_by(func.random()).first() print('fake_quote') print(fake_quote.id) return api_fake_quote_by_id(str(fake_quote.id)) # Id List @app.route('/api/authors/id_list') def api_authors_id_list(): return json_res_id_list(Author, Author.name_kana) @app.route('/api/books/id_list') def api_books_id_list(): return json_res_id_list(Book, Book.title) @app.route('/api/quotes/id_list') def api_quotes_id_list(): return json_res_id_list(Quote, Quote.text) @app.route('/api/fake_authors/id_list') def api_fake_authors_id_list(): return api_fake_authors_list() # return json_res_id_list(FakeAuthor, FakeAuthor.name) @app.route('/api/fake_books/id_list') def api_fake_books_id_list(): return json_res_id_list(FakeBook, FakeBook.title) @app.route('/api/fake_quotes/id_list') def api_fake_quotes_id_list(): return api_fake_quotes_list() # return json_res_id_list(FakeQuote, FakeQuote.text) @app.route('/api/fake_quotes/random_id_list') def api_fake_quotes_random_id_list(): order_field = func.random() # query = app.session.query(FakeQuote.id) # If fake_quote_id is passed, get another one filters = None fake_quote_id = request.args.get('fake_quote_id', None) if fake_quote_id is not None and util.is_uuid(fake_quote_id): # query = query.filter() filters = (FakeQuote.id != fake_quote_id) return json_res_id_list(FakeQuote, order_field, filters) # @app.route('/api/fake_quotes/id_list') # def api_random_fake_quotes_id_list(): # List @app.route('/api/authors/list') def api_authors_list(): # return jsonify(get_model_dict_list(Author, Author.name_kana)) authors_result = get_model_dict_list(Author, Author.name_kana) result = set_children_list(authors_result, Author, Book, Book.title) return jsonify(result) @app.route('/api/fake_authors/list') def api_fake_authors_list(): fake_authors_result = get_model_dict_list(FakeAuthor, FakeAuthor.name) offset = int(request.args.get('offset', 0)) limit = int(request.args.get('limit', 10)) m_list = app.session.query( FakeAuthor ) \ .join(Author) \ .order_by( Author.name_kana, FakeAuthor.name ) \ .limit(limit) \ .offset(offset) \ .all() fake_authors_result = { 'id_list': [m.to_dict()['id'] for m in m_list], 'result_list': [m.to_dict() for m in m_list], 'total': total_count(FakeAuthor, None), 'next_offset': get_next_offset(offset, limit, m_list) } result = set_children_list(fake_authors_result, FakeAuthor, FakeBook, FakeBook.title) return jsonify(result) @app.route('/api/fake_quotes/list') def api_fake_quotes_list(): offset = int(request.args.get('offset', 0)) limit = int(request.args.get('limit', 10)) m_list = app.session.query( FakeQuote ) \ .join(FakeBook, FakeQuote.fake_book_id==FakeBook.id) \ .join(FakeAuthor, FakeBook.fake_author_id==FakeAuthor.id) \ .join(Quote, FakeQuote.quote_id==Quote.id) \ .join(Book, Quote.book_id==Book.id) \ .join(Author, Book.author_id==Author.id) \ .order_by( Author.name_kana, Book.title, Quote.text, FakeAuthor.name, FakeBook.title, FakeQuote.text ) \ .limit(limit) \ .offset(offset) \ .all() data = { 'id_list': [m.to_dict()['id'] for m in m_list], 'result_list': [m.to_dict() for m in m_list], 'total': total_count(FakeQuote, None), 'next_offset': get_next_offset(offset, limit, m_list) } return jsonify(data) def set_children_list(parent_result, Parent, Child, sort_key): for parent_dict in parent_result['result_list']: parent_filter = (getattr( Child, util.fk_column_name(Parent)) == parent_dict['id']) children = app.session.query(Child) \ .filter(parent_filter) \ .order_by(sort_key) \ .limit(CHILDREN_LIMIT) \ .all() child_prefex = util.singular_table_name(Child) parent_dict[child_prefex + '_list'] = [child.to_dict() for child in children] parent_dict[child_prefex + '_total'] = app.session.query( Child).filter(parent_filter).count() return parent_result # Get by Fake Quote ID. Get all related info @app.route('/api/fake_quotes/<fake_quote_id>') def api_fake_quote_by_id(fake_quote_id): # print(fake_quote_id) # print("fake_quote_id") if not util.is_uuid(fake_quote_id): return abort(404) fake_quote = app.session.query(FakeQuote).filter( FakeQuote.id == fake_quote_id).first() if fake_quote == None: return abort(404) quote = fake_quote.original_quote return jsonify(fake_quote=fake_quote.to_dict(), fake_book=fake_quote.fake_book.to_dict(), fake_author=fake_quote.fake_book.fake_author.to_dict(), quote=quote.to_dict(), book=quote.book.to_dict(), author=quote.book.author.to_dict()) # @app.route('/api/authors/<author_id>') # def api_author_by_id(author_id): # print(author_id) # print("author_id") # if not util.is_uuid(author_id): # print('Not') # return abort(404) # author = app.session.query(Author).filter(Author.id==author_id).first() # print("author") # print(author) # if author == None: # return abort(404) # return jsonify( # author=author.to_dict() # ) # # // For testing # @app.route('/api/quotes/<quote_id>') # def api_quote_by_id(quote_id): # if not util.is_uuid(quote_id): # print('Not') # return abort(404) # quote = app.session.query(Quote).filter(Quote.id==quote_id).first() # if quote == None: # return abort(404) # return jsonify( # quote=quote.to_dict() # ) # def json_res_list(model, order_field, filters=None, only_id=False): # return jsonify(get_model_dict_list(model, order_field, filters, only_id)) def get_model_dict_list(model, order_field, filters=None, only_id=False): offset = int(request.args.get('offset', 0)) limit = int(request.args.get('limit', 10)) query = app.session.query(model) if filters is not None: query = query.filter(filters) m_list = query.order_by(order_field) \ .limit(limit) \ .offset(offset) \ .all() result_list = [] if only_id: result_list = [m.to_dict()['id'] for m in m_list] else: result_list = [m.to_dict() for m in m_list] return { 'result_list': result_list, 'total': total_count(model, filters), 'next_offset': get_next_offset(offset, limit, m_list) } def total_count(model, filters): query = app.session.query(model) if filters is not None: query = query.filter(filters) return query.count() def json_res_id_list(model, order_field, filters=None): offset = int(request.args.get('offset', 0)) limit = int(request.args.get('limit', 10)) query = app.session.query(model) if filters is not None: query.filter(filters) m_list = query.order_by(order_field) \ .limit(limit) \ .offset(offset) \ .all() id_list = [m.to_dict()['id'] for m in m_list] return jsonify(id_list=id_list, next_offset=get_next_offset(offset, limit, m_list)) def get_next_offset(offset, limit, result): next_offset = offset + limit if result == None or (result != None and len(result) < limit): next_offset = -1 # Tmp Code for local if os.environ['FLASK_ENV'] != 'production': next_offset = -1 # TODO: Make this as default for local return next_offset # ########### # Children List @app.route('/api/authors/<author_id>/books/list') def api_books_by_author_id(author_id): result = children_by_parent_id(Author, author_id, Book, Book.title) # for fake_author in result['children_list']: # fake_books = app.session.query(FakeBook) \ # .filter(FakeBook.fake_author_id==fake_author['id']) \ # .order_by(FakeBook.title) \ # .limit(CHILDREN_LIMIT) \ # .all() # fake_author['fake_book_list'] = [fake_book.to_dict() for fake_book in fake_books] # books = app.session.query(Book) \ # .filter(Book.author_id==author_id) \ # .order_by(Book.title) \ # .all() # result['book_list'] = [book.to_dict() for book in books] return jsonify(result) # http://localhost:5000/api/authors/8995788f-77f5-4f5e-a1c3-9dcb9283eac2/fake_authors/list @app.route('/api/authors/<author_id>/fake_authors/list') def api_fake_authors_by_author_id(author_id): result = children_by_parent_id(Author, author_id, FakeAuthor, FakeAuthor.name) for fake_author in result['children_list']: fake_books = app.session.query(FakeBook) \ .filter(FakeBook.fake_author_id==fake_author['id']) \ .order_by(FakeBook.title) \ .limit(CHILDREN_LIMIT) \ .all() fake_author['fake_book_list'] = [ fake_book.to_dict() for fake_book in fake_books ] books = app.session.query(Book) \ .filter(Book.author_id==author_id) \ .order_by(Book.title) \ .all() result['book_list'] = [book.to_dict() for book in books] return jsonify(result) # /api/fake_authors/204499f0-b836-4d79-9644-e9454b8f0fb2/fake_books/lis @app.route('/api/fake_authors/<fake_author_id>/fake_books/list') def api_fake_books_by_fake_author_id(fake_author_id): result = children_by_parent_id(FakeAuthor, fake_author_id, FakeBook, FakeBook.title) # Add Original author = app.session.query(Author) \ .filter(Author.id==result['fake_author']['author_id']) \ .first() result['author'] = author.to_dict() result['book_list'] = [book.to_dict() for book in author.books] return jsonify(result) @app.route('/api/books/<book_id>/quotes/list') def api_quotes_by_book_id(book_id): result = children_by_parent_id(Book, book_id, Quote, Quote.text) # Add Original author = app.session.query(Author) \ .filter(Author.id==result['book']['author_id']) \ .first() result['author'] = author.to_dict() return jsonify(result) # /http://127.0.0.1:5000/api/quotes/8e7cdd6a-0cf9-446a-9529-57efc7b742fb/fake_quotes/list?offset=0&limit=100 @app.route('/api/quotes/<quote_id>/fake_quotes/list') def api_fake_quotes_by_quote_id(quote_id): result = children_by_parent_id(Quote, quote_id, FakeQuote, FakeQuote.text) # Add Original book = app.session.query(Book) \ .filter(Book.id==result['quote']['book_id']) \ .first() result['book'] = book.to_dict() result['author'] = book.author.to_dict() # Add Fake Parent for fake_quote in result['children_list']: fake_book = app.session.query(FakeBook) \ .filter(FakeBook.id==fake_quote['fake_book_id']) \ .first() fake_quote['fake_book'] = fake_book.to_dict() fake_quote['fake_author'] = fake_book.fake_author.to_dict() return jsonify(result) @app.route('/api/fake_books/<fake_book_id>/fake_quotes/list') def api_fake_quotes_by_fake_book_id(fake_book_id): result = children_by_parent_id(FakeBook, fake_book_id, FakeQuote, FakeQuote.text) # Add Original book = app.session.query(Book) \ .filter(Book.id==result['fake_book']['book_id']) \ .first() result['book'] = book.to_dict() result['author'] = book.author.to_dict() # Add Parent fake_author = app.session.query(FakeAuthor) \ .filter(FakeAuthor.id==result['fake_book']['fake_author_id']) \ .first() result['fake_author'] = fake_author.to_dict() return jsonify(result) def children_by_parent_id(Parent, parent_id, Child, sort_key): if not util.is_uuid(parent_id): return abort(404) parent = app.session.query(Parent).filter( Parent.id == parent_id).first() if parent == None: return abort(404) # Use pager per Child model filters = (getattr(Child, util.fk_column_name(Parent)) == parent_id) children_list_result = get_model_dict_list(Child, sort_key, filters) # util.singular(parent.__tablename__) child_key_prefix = util.singular_table_name(Child) return { util.singular_table_name(Parent): parent.to_dict(), # child_key_prefix + '_list': children_list_result['result_list'], # child_key_prefix + '_total': children_list_result['total'], # child_key_prefix + '_next_offset': children_list_result['next_offset'], 'children_list': children_list_result['result_list'], 'children_total': children_list_result['total'], 'children_next_offset': children_list_result['next_offset'] } @app.after_request def add_header(response): response.headers.add("Access-Control-Allow-Origin", "*") return response return app
OK = 'okay' app = Flask(__name__, static_url_path='') app.debug = True app.config.from_object('config') app.ccConfig = {} app.ccState = {} app.state = {'ip': ccLib.getMyIPAddress()} app.aws = ccLib.AWS() app.aws.createKeypairs() app.aws.pushSecurityGroups('worker') app.queue = ccLib.Job app.session = ccLib.initDB() @app.route('/') def index(): """ Return the main html page. """ # return 'hello' return app.send_static_file('index.html') #=================================== # Workers/Nodes/AWS @app.route('/api/regions') def regions(): """ Get the list of regions