class RestApp(Flask): def __init__(self): super().__init__(__name__) # TODO: apply proper CORS values CORS(self) config = get_config() self.config.from_object(config) self.url_map.strict_slashes = False self.app_context().push() self.rebar = Rebar() self.rebar.add_handler_registry(version_1_registry) self.rebar.init_app(app=self) self.flask_marshmallow = FlaskMarshmallow(app=self) self.secret_key = config.API_SECRET_KEY self.login_manager = LoginManager() self.login_manager.init_app(app=self) self.login_manager.unauthorized_callback = raise_unauthorized self._init_logger() self._init_db_client() def _init_logger(self): base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) logging.config.fileConfig(f"{base_dir}/logging.conf") self.custom_logger = logging.getLogger("barter") self.custom_logger.setLevel( logging.DEBUG if self.config["DEBUG"] else logging.INFO) def _init_db_client(self): supported_models = () sql_db_name = self.config["POSTGRESQL_DB_NAME"] sql_host = self.config["POSTGRESQL_DB_HOST"] sql_username = self.config["POSTGRESQL_DB_USERNAME"] self.custom_logger.info( f"Binding models to PSQL DB {sql_db_name} from " f"{sql_username}@{sql_host}...") self.postgre_client = PostgresqlDatabase( sql_db_name, host=sql_host, port=self.config["POSTGRESQL_DB_PORT"], user=sql_username, password=self.config["POSTGRESQL_DB_PASSWORD"], ) self.postgre_client.bind(supported_models, bind_refs=False, bind_backrefs=False)
def create_app(self): app = Flask(__name__) @app.route("/errors", methods=["GET"]) def a_terrible_handler(): raise errors.Conflict(msg=TestErrors.ERROR_MSG) @app.route("/uncaught_errors", methods=["GET"]) def an_even_worse_handler(): raise ArithmeticError() @app.route("/verbose_errors", methods=["GET"]) def a_fancy_handler(): raise errors.Conflict( msg=TestErrors.ERROR_MSG, additional_data={"foo": "bar"} ) @app.route("/route_that_fails_validation", methods=["GET"]) def validation_fails_handler(): raise BadRequest() @app.route("/slow", methods=["GET"]) def a_slow_handler(): raise SystemExit() Rebar().init_app(app=app) return app
def __init__(self): super().__init__(__name__) # TODO: apply proper CORS values CORS(self) config = get_config() self.config.from_object(config) self.url_map.strict_slashes = False self.app_context().push() self.rebar = Rebar() self.rebar.add_handler_registry(version_1_registry) self.rebar.init_app(app=self) self.flask_marshmallow = FlaskMarshmallow(app=self) self.secret_key = config.API_SECRET_KEY self.login_manager = LoginManager() self.login_manager.init_app(app=self) self.login_manager.unauthorized_callback = raise_unauthorized self._init_logger() self._init_db_client()
def create_app(self): app = Flask(__name__) Rebar().init_app(app=app) class Schema(validation.RequestSchema): foo = fields.Integer(required=True) bar = fields.Boolean() baz = validation.CommaSeparatedList(fields.Integer()) @app.route("/stuffs", methods=["GET"]) def query_string_handler(): params = get_query_string_params_or_400(schema=Schema()) return response(data=params) return app
def create_app(self): app = Flask(__name__) Rebar().init_app(app=app) class NestedSchema(validation.RequestSchema): baz = fields.List(fields.Integer()) class Schema(validation.RequestSchema): foo = fields.Integer(required=True) bar = fields.Email() nested = fields.Nested(NestedSchema) @app.route("/stuffs", methods=["POST"]) def json_body_handler(): data = get_json_body_params_or_400(schema=Schema) return response(data) return app
def create_app(self): app = Flask(__name__) @app.route('/errors', methods=['GET']) def a_terrible_handler(): raise errors.Conflict(msg=TestErrors.ERROR_MSG) @app.route('/uncaught_errors', methods=['GET']) def an_even_worse_handler(): raise ArithmeticError() @app.route('/verbose_errors', methods=['GET']) def a_fancy_handler(): raise errors.Conflict(msg=TestErrors.ERROR_MSG, additional_data={'foo': 'bar'}) Rebar().init_app(app=app) return app
import marshmallow as m from flask_rebar import Rebar from flask_rebar import HeaderApiKeyAuthenticator from flask_rebar import compat from flask_rebar.swagger_generation import SwaggerV2Generator, SwaggerV3Generator rebar = Rebar() registry = rebar.create_handler_registry() swagger_v2_generator = SwaggerV2Generator() swagger_v3_generator_with_hidden = SwaggerV3Generator(include_hidden=True) normal_swagger_v3_generator = SwaggerV3Generator() authenticator = HeaderApiKeyAuthenticator(header="x-auth") default_authenticator = HeaderApiKeyAuthenticator(header="x-another", name="default") class HeaderSchema(m.Schema): user_id = compat.set_data_key(field=m.fields.String(required=True), key="X-UserId") class FooSchema(m.Schema): __swagger_title__ = "Foo" uid = m.fields.String() name = m.fields.String() class NestedFoosSchema(m.Schema): data = m.fields.Nested(FooSchema, many=True)
from functools import partial from flask import Flask from flask_cors import CORS from flask_login import LoginManager from flask_migrate import Migrate from flask_rebar import Rebar from flask_sqlalchemy import SQLAlchemy # Globally accessible libraries from JDISCTF.flask_login_authenticator import FlaskLoginAuthenticator, register_authenticators from config import Config DB = SQLAlchemy() MIGRATE = Migrate() REBAR = Rebar() LOGIN_MANAGER = LoginManager() REGISTRY = REBAR.create_handler_registry(prefix="/api") REGISTRY.set_default_authenticator(FlaskLoginAuthenticator()) # make columns non-nullable by default, most of them should be DB.Column = partial(DB.Column, nullable=False) # register authenticator for Swagger register_authenticators(REGISTRY) def create_app(test_config=None) -> Flask: """Initialize the core application""" app = Flask(__name__, instance_relative_config=True)
# # Development server runner # # Invoke w/: FLASK_ENV=development flask run ############################################################################## NAME="nakedpad_api" import os from flask import Flask #from flask_marshmallow import Marshmallow from flask_rebar import Rebar # Need to setup rebar before importing decorated routes rebar = Rebar() # All handler URL rules will be prefixed by '/v1' registry = rebar.create_handler_registry(prefix='/api/v1') # Import controllers for flask_rebar from .controllers import ( documents, health, ) # Import database from . import database # Factory method to create our application def create_app(config_file=None):
from logging.config import dictConfig from flask import Flask from flask_rebar import Rebar, SwaggerV3Generator from app.logging.config import config rebar = Rebar() v1_registry = rebar.create_handler_registry( prefix='/v1', swagger_path='/apidocs', swagger_ui_path='/apidocs-ui', swagger_generator=SwaggerV3Generator( title="Face Recognition", description="Face Recognition REST Service using DLIB")) def create_app() -> Flask: dictConfig(config=config) app = Flask(__name__) app.config.from_envvar("APP_CONFIG") rebar.init_app(app) return app
from flask import Flask from flask_migrate import Migrate from flask_rebar import Rebar from flask_sqlalchemy import SQLAlchemy rebar = Rebar() registry = rebar.create_handler_registry(prefix="/api") db = SQLAlchemy() migrate = Migrate(db=db) def create_app() -> Flask: app = Flask(__name__) app.config.from_envvar("APP_CONFIG") rebar.init_app(app) db.init_app(app) migrate.init_app(app) return app
from flask import Flask from marshmallow import fields, pre_dump, pre_load from flask_rebar import ( Rebar, errors, HeaderApiKeyAuthenticator, Tag, SwaggerV2Generator, ) from flask_rebar.validation import RequestSchema, ResponseSchema rebar = Rebar() # Rebar will create a default swagger generator if none is specified. # However, if you want more control over how the swagger is generated, you can # provide your own. # Here we've specified additional metadata for operation tags. generator = SwaggerV2Generator( tags=[Tag(name="todo", description="Operations for managing TODO items.")]) registry = rebar.create_handler_registry(swagger_generator=generator) # Just a mock database, for demonstration purposes todo_id_sequence = 0 todo_database = {} # Rebar relies heavily on Marshmallow. # These schemas will be used to validate incoming data, marshal outgoing # data, and to automatically generate a Swagger specification.
from flask_rebar import Rebar from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate rebar = Rebar() db = SQLAlchemy() migrate = Migrate(db=db)
import logging from logging.config import dictConfig from flask import Flask from flask_apscheduler import APScheduler from flask_caching import Cache from flask_cors import CORS from flask_migrate import Migrate from flask_rebar import HeaderApiKeyAuthenticator, Rebar from flask_sqlalchemy import SQLAlchemy from backend.logger import config dictConfig(config) rebar = Rebar() registry = rebar.create_handler_registry( swagger_path=None, swagger_ui_path=None ) cache = Cache() cors = CORS() db = SQLAlchemy() migrate = Migrate() scheduler = APScheduler() def create_app(): app = Flask(__name__) app.config.from_pyfile('config.py')
from logging.config import dictConfig from flask import Flask from flask_rebar import Rebar from app.entities.db import db from app.logging.config import config rebar = Rebar() v1_registry = rebar.create_handler_registry(prefix='/v1', swagger_path='/apidocs', swagger_ui_path='/apidocs-ui') def create_app() -> Flask: app = Flask(__name__) app.config.from_envvar("APP_CONFIG") rebar.init_app(app) db.init_app(app) dictConfig(config) return app
from flask import Flask, request from marshmallow import fields from flask_rebar import RequestSchema, Rebar from videotime.video_manager import manager rebar = Rebar() registry = rebar.create_handler_registry() class ProcessReturnSchema(RequestSchema): message = fields.String(required=True) class ProcessVideoSchema(RequestSchema): url = fields.String(required=True) @registry.handles(rule="/") def hello(): return "VideoTime! www.videotime.me" @registry.handles(rule="/process", method='POST', request_body_schema=ProcessVideoSchema(), response_body_schema=ProcessReturnSchema()) def process_video(): body = rebar.validated_body manager.process_video(body['url']) return {"message": "processing"}