def setUp(self): # setup files and dirs self.tempdir = TemporaryDirectory() temp = self.tempdir.name self.hb_root = Path(temp, 'hidebound').as_posix() os.makedirs(self.hb_root) self.root = Path(temp, 'projects').as_posix() os.makedirs(self.root) self.create_files(self.root) # setup app app = flask.Flask(__name__) swg.Swagger(app) app.register_blueprint(api.API) self.context = app.app_context() self.context.push() self.app = self.context.app api.DATABASE = None api.CONFIG = None self.api = api self.client = self.app.test_client() self.app.config['TESTING'] = True self.specs = lbt.relative_path( __file__, '../core/test_specifications.py').absolute().as_posix()
def prepare() -> flask.Flask: """Prepares application object. Returns (Flask): Flask application object. """ logger = prepare_logging() config = load_yaml(defaults.APP_DIR / 'config.yaml') wav_folder = defaults.APP_DIR / 'wavs' wav_folder.mkdir(exist_ok=True, parents=True) hparams_tacotron = HParams.from_yaml(config['encoder_hparams_path']) hparams_wg = HParams.from_yaml(config['vocoder_hparams_path']) hparams_tacotron.n_symbols = 152 evaluator = get_evaluator( evaluator_classname=config['evaluator_classname'], encoder_hparams=hparams_tacotron, encoder_checkpoint_path=config['encoder_checkpoint_path'], vocoder_hparams=hparams_wg, vocoder_checkpoint_path=config['vocoder_checkpoint_path'], use_denoiser=config['use_denoiser'], device=config['device']) # Flask application app, basic_auth = prepare_app(config['basic_auth_username'], config['basic_auth_password']) flasgger.Swagger(app) _add_app_routes(app, basic_auth, evaluator, wav_folder, logger) logger.info('All application objects have been initialized successfully.') return app
def setUp(self): # create temp dir and write config to it self.config = self.get_partial_config() self.tempdir = TemporaryDirectory() self.root = self.tempdir.name self.data_path = Path(self.root, 'transactions.csv').as_posix() self.data = self.get_data() self.data.to_csv(self.data_path, index=False) self.config['data_path'] = self.data_path self.config_path = Path(self.root, 'config.json').as_posix() with open(self.config_path, 'w') as f: json.dump(self.config, f) # setup app app = flask.Flask(__name__) swg.Swagger(app) app.register_blueprint(api.API) app.api = api.API self.context = app.app_context() self.context.push() self.app = self.context.app self.app.api.database = None api.config = None self.client = self.app.test_client() self.app.config['TESTING'] = True
def _main(): # application_path: ~/backend/ application_path = Path(path.abspath(__file__)).parent dist_folder = str(Path(application_path, "dist")) serve_port = 9797 # creates the Flask application instance app = Flask(__name__, static_folder=dist_folder, template_folder=dist_folder) register_blueprints(app, 'blueprints', ['./blueprints']) app.config.update({'DEBUG': False}) @app.route('/') def index(): """ index.html is located in dist/index.html; after executing "npm run build", dist folder will be automatically generated in backend/dist this setting is configured in vue.config.js, which deploys dist folder to backend/dist if frontend has been changed, please remember to run "npm run build" please do not change anything manually in dist folder or the location of it """ return render_template("index.html") @app.errorhandler(Exception) def handle_all_exception(e: Exception): print(e) return jsonify({ 'error': True, 'message': type(e).__name__ + ': ' + str(e), }), 500 app.config['SWAGGER'] = { 'title': 'API of CCC Assignment 2', 'swagger_version': '2.0', } swagger = flasgger.Swagger(app) # allow cors on all domains. we just ignore security issue CORS(app) # creates the Socket.IO socket instance socket_io = SocketIO(app, cors_allowed_origins="*") socketio_server = { 'msg-parser': MsgParserSocketIOServer(socketio=socket_io, namespace='/msg-parser', application_path=application_path) } try: print(f'Launch browser into http://localhost:{serve_port}') socket_io.run(app, host='0.0.0.0', port=serve_port, debug=False) except KeyboardInterrupt: return 0
import os import json from flask import (Flask, jsonify, request, g) import flasgger import zmq import base64 app = Flask(__name__) swagger = flasgger.Swagger(app) # connexion serveur zmq (service tokendealer port 7000) context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://*****:*****@app.route('/api/ressource', methods=['GET']) @flasgger.swag_from('docs/verify_token.yml') def verify_token(): # on récupère le token depuis le paramètre token de notre requête token = request.args.get('token', default='*', type=str) try: # envoi au tokendealer du token pour validation socket.send_json({"validate_token": token}) # réception de la réponse du token dealer message = socket.recv_json() # si le message de retour indique que le token est valide alors on retourne la ressource protégée if message['valid']: with open("secret.jpg", "rb") as img_file:
# -*- coding: utf-8 -*- """Extensions for BEL Commons.""" import flasgger import flask_bootstrap import flask_mail import flask_security from bel_commons.core import FlaskBio2BEL, PyBELSQLAlchemy __all__ = [ 'bootstrap', 'mail', 'security', 'swagger', 'bio2bel', 'db', ] bootstrap = flask_bootstrap.Bootstrap() mail = flask_mail.Mail() security = flask_security.Security() swagger = flasgger.Swagger() bio2bel = FlaskBio2BEL() db = PyBELSQLAlchemy()
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logger = logging.getLogger(__name__) app = flask.Flask(__name__) app.config['JSON_AS_ASCII'] = False app.config['SWAGGER'] = { 'doc_dir': os.path.join( ROOT_DIR, 'apidoc', ), 'openapi': '3.0.2' } swagger = flasgger.Swagger( app, template_file=os.path.join(app.config['SWAGGER']['doc_dir'], 'template.yml') ) def get_client(): return injector.get(DatastoreConfiguration).client def fetch_books(): client = get_client() query = client.query(kind='Book') return list(query.fetch()) def create_book():
import dash_core_components as dcc import dash_html_components as html import flasgger as swg import flask import hidebound.server.api as api import hidebound.server.components as components import hidebound.server.server_tools as server_tools from hidebound.core.config import Config # ------------------------------------------------------------------------------ ''' Hidebound service used for displaying and interacting with Hidebound database. ''' APP = flask.Flask(__name__) # type: Union[flask.Flask, dash.Dash] swg.Swagger(APP) APP.register_blueprint(api.API) APP = components.get_dash_app(APP) CONFIG_PATH = None # type: Union[str, Path, None] @APP.server.route('/static/<stylesheet>') def serve_stylesheet(stylesheet): # type: (str) -> flask.Response ''' Serve stylesheet to app. Args: stylesheet (str): stylesheet filename. Returns:
import flask import flasgger import flasgger.utils as swag_utils import rest_api.flask_app_apidocs as apidocs import rest_api.text as text api = flask.Flask(__name__) api.register_blueprint(text.text_api) swagger_template = { "swagger": "2.0", "info": { "title": "Celery Demo API", "description": "Demo of Flask and Celery in action.", "version": "0.0.1" }, "basePath": "/" } swagger = flasgger.Swagger(api, template=swagger_template) @api.route('/', methods=['GET']) @swag_utils.swag_from(apidocs.INDEX) def index(): """ Confirm that the flask app is running. """ greeting = { 'message': "Hello there", 'docs': '/apidocs/' } return flask.jsonify(greeting)
import db STATIC_DIRS = ['static'] DEBUG = bool(os.environ.get('DONILLA_DEBUG', True)) LOGGER = logging.getLogger('donilla.web') APP = flask.Flask('donilla') APP.config['SECRET_KEY'] = os.environ.get('DONILLA_SESSIONS_KEY', os.urandom(24)) DEFAULT_LIMIT = '100 per minute' LIMITER = flask_limiter.Limiter(APP, key_func=flask_limiter.util.get_remote_address, default_limits=[DEFAULT_LIMIT]) APP.config['SWAGGER'] = api_spec.CONFIG BLUEPRINT = flask.Blueprint('api', __name__) flasgger.Swagger(APP) CORS(APP) class MissingFields(Exception): 'Request if missing required fields.' @APP.errorhandler(429) def ratelimit_handler(error): 'Custom error for rate limiter.' msg = 'Rate limit exceeded for {}. Allowed rate: {}'.format( flask.request.url, error.description) LOGGER.info(msg) return flask.make_response(flask.jsonify({'code': 429, 'error': msg}), 429)
def create(): """ Method to get the Flask application object. Returns: flask.Flask: The Flask application, as configured in `etc/rest.yaml`. Raises: ImportError: One of the resource classes of the `urls` key in the `mappings` section of the `etc/rest.yaml` configuration file could not be retrieved. """ # inititialize application app = flask.Flask(__name__) app.debug = common.config.get('rest', 'debug') if app.debug: print('(Re)loaded application...') # inititialize REST cors = flask_cors.CORS(app, resources={r'*': {'origins': '*'}}) api = flask_restful.Api( app) # see https://github.com/flask-restful/flask-restful/issues/116 # default root resource class RootResource(flask.views.MethodView): def get(self): return { 'service_name': common.config.get('rest', 'service_name'), 'service_version': common.config.get('rest', 'service_version'), 'documentation_url': '/apidocs', } api.add_resource(RootResource, '/') # iterate over mappings and integrate them into the Flask application rest_mappings = common.config.get('rest', 'mappings') for m, mapping in enumerate(rest_mappings): url = mapping['url'] resource_fullpath = mapping['resource'] module_name_lastindex = resource_fullpath.rfind('.') # retrieve module module_path = resource_fullpath[:module_name_lastindex] module = __import__(module_path, fromlist=['']) # retrieve resource resource_path = resource_fullpath[module_name_lastindex + 1:] try: resource = getattr(module, resource_path) except AttributeError: raise ImportError( 'No resource named `%s` in `%s`, check your configuration file' % ( resource_path, module_path, )) # add decorator resource.decorators = [common.decorators.ResourceDecorator] + list( getattr(resource, 'decorators', [])) # associate resource with URL resource_name = '%d_%s' % (m, resource.__name__) api.add_resource(resource, url, endpoint=resource_name) # API documentation swagger_config = flasgger.Swagger.DEFAULT_CONFIG.copy() for index, header in enumerate(swagger_config['headers']): if header[0] == 'Access-Control-Allow-Methods': swagger_config['headers'][index] = ( 'Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH') swagger_config['specs'][0].update( version=common.config.get('rest', 'service_version'), title='%s service documentation' % (common.config.get('rest', 'service_name') or '', ), description='Documentation for the access points on API ' + (common.config.get('rest', 'service_name') or ''), ) flasgger.Swagger(app, config=swagger_config) # that's all, folks! return app