from google_login import validate_token from persistence import Persistence from token_generator import encode_auth_token, decode_auth_token from user import User from usercommentvoted import UserCommentVoted from usercontributionvoted import UserContributionVoted app = Flask(__name__, static_folder='./static') CORS(app) SWAGGER_URL = '/api/docs' swagger_path = os.environ['SWAGGER'] swagger_yml = load(open(swagger_path, 'r'), Loader=Loader) blueprint = get_swaggerui_blueprint(SWAGGER_URL, swagger_path, config={'spec': swagger_yml}) app.register_blueprint(blueprint, url_prefix=SWAGGER_URL) @app.route('/') def home(): contributions = Contribution.get_news_home(repository) username = decode_auth_token(request.cookies.get('token')) if username is not None: contributions_voted = UserContributionVoted.get_voted(repository, username) for c in contributions: c.voted = c['id'] in [cv['contribution_id'] for cv in contributions_voted] aux = Comment.get_number_comments_by_contribution(repository, str(c['id'])) c['n_comments'] = aux[0]['n_comments'] user = User.get(repository, username)
from app import app from flask import Blueprint, jsonify from flask_swagger import swagger from flask_swagger_ui import get_swaggerui_blueprint SWAGGER_URL = "/api/docs" API_URL = "http://*****:*****@swag.route("/spec") def spec(): return jsonify(swagger(app)) swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ "app_name": "Fidelio" } )
from flask_swagger_ui import get_swaggerui_blueprint SWAGGER_URL = "/swagger-ui" # URL for exposing Swagger UI API_URL = "/swagger/" # Call factory function to create our blueprint swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ "layout": "BaseLayout", "deepLinking": "true", }, # Swagger UI config overrides oauth_config={ "clientId": "Zeu4TO3koxp6ubeebSMbgb0DRLbjLT69", "scopeSeparator": " ", "additionalQueryStringParams": {}, }, )
from flask_swagger_ui import get_swaggerui_blueprint #from flask_swagger import swagger #from wtforms import StringField, PasswordField, BooleanField, SubmitField #from pyppeteer import launch from flask_restplus import Resource, Api from pyppe import html_to_pdf import asyncio #import json app = Flask(__name__) api = Api(app, version='1.0', title='Sample API', description='A sample API') SWAGGER_URL = '/swagger' API_URL = '/static/swagger.yml' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "HTML to PDF"}) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) app.config['SECRET_KEY'] = '123' # model = api.model('Name Model', # {'path_page': fields.String(required = True, # description="Page URL", # help="")}) @app.route('/', methods=['GET', 'POST']) def index(): form = InterfaceForm() if form.validate_on_submit(): flash('Path is: {}'.format(form.path.data))
from flask_swagger_ui import get_swaggerui_blueprint from flask import Flask from sqlalchemy import create_engine, MetaData app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile('config.py') # swagger specific # SWAGGER_URL = '/swagger' API_URL = '/static/swagger.yaml' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "GENE-SEARCH-REST-API" } ) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) # end swagger specific # connection = "mysql://{user}@{host}:{port}/{database}".format(user=app.config['USER'], host=app.config['HOST'], port=app.config['PORT'], database=app.config['DATABASE']) engine = create_engine(connection) metadata = MetaData(bind=engine) from app import views
import datetime from app import app from db_conf import mysql from flask import jsonify from flask import flash, request, Flask from flask_restful import Resource, Api from flask_swagger_ui import get_swaggerui_blueprint import os app = Flask(__name__) api = Api(app, prefix="/api/v1") ### swagger specific ### SWAGGER_URL = '/api/v1/swagger' API_URL = '/schema/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "Contact_API_Code_Challenge"}) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### #app.register_blueprint(request_api.get_blueprint()) # 1 Operations: POST / GET / PUT / PATCH / DELETE # 2 Delete operation just updates the status in DB (Soft Delete). # 3 All queries involving the active flow (GET / PUT / PATCH) will ignore all such entries with the condition ‘del_flag = true’ # 4 By default when a new record is created in database. del_flag is set to False # 5 PUT and PATCH operation do not allow updating the primary fields(first_name, last_name, dob and gender) #This class holds the functions for adding and retreiving Contact Collections. Input body is expected to be an arry class Contact_Collection(Resource): #This function adds Contact identifocation information in Identification table, gets the id and adds cmmunication and address information against that identification id.
import json from ir_eval.ranking.main import ranked_retrieval from ir_eval.ranking.movie_search import ranked_movie_search import re import time from ir_eval.preprocessing import preprocess from api.utils.cache import ResultsCache from query_completion.model import predict_next_word app = Flask(__name__) CORS(app) SWAGGER_URL = '/api/docs' API_URL = '/static/swagger.json' swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "TTDS Movie Search"}) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) db = get_db_instance() cache = ResultsCache.instance( ) # Usage: cache.get(params, which_cache), cache.store(params, output, which_cache) QUOTES_CACHE = 'quotes' MOVIES_CACHE = 'movies' @app.route('/') def home(): return 'Hello, World!' def merge_lists(l1, l2, key):
app.config.from_mapping({ "CACHE_TYPE": "simple", "CACHE_DEFAULT_TIMEOUT": 3600, }) cache = Cache(app) ################################################## # SWAGGER DOCUMENTATION SWAGGER_URL = '/docs' API_DEF_URL = "http://%s:%s/swagger.json" % (config['swagger']['host'], config['swagger']['port']) swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_DEF_URL, config={'app_name': "CDLI Numeral Conversion"}, ) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) ################################################## # DECORATORS to enforce proper request format # and allow JSONP GET requests: def enforce_params(required=[]): """ Decorator to enforce that a flask endpoint only accepts json-formatted queries, and to enforce that required parameters are present.
def init_app(self, app, host="localhost", port=5000, prefix="", app_db=None, json_encoder=SAFRSJSONEncoder, swaggerui_blueprint=True, **kwargs): """ API and application initialization """ if not isinstance(app, Flask): raise TypeError("'app' should be Flask.") if app_db is None: self.db = DB app.json_encoder = json_encoder app.request_class = SAFRSRequest app.response_class = SAFRSResponse app.url_map.strict_slashes = False if app.config.get("DEBUG", False): log.setLevel(logging.DEBUG) # Register the API blueprint if swaggerui_blueprint is True: swaggerui_blueprint = get_swaggerui_blueprint( prefix, "{}/swagger.json".format(prefix), config={ "docExpansion": "none", "defaultModelsExpandDepth": -1 }) app.register_blueprint(swaggerui_blueprint, url_prefix=prefix) swaggerui_blueprint.json_encoder = JSONEncoder for conf_name, conf_val in kwargs.items(): setattr(self, conf_name, conf_val) for conf_name, conf_val in app.config.items(): setattr(self, conf_name, conf_val) self.config.update(app.config) @app.before_request def handle_invalid_usage(): return @app.before_request def init_ja_data(): # ja_data holds all data[] that will be encoded g.ja_data = set() g.ja_included = set() # pylint: disable=unused-argument,unused-variable @app.teardown_appcontext def shutdown_session(exception=None): """cfr. http://flask.pocoo.org/docs/0.12/patterns/sqlalchemy/""" self.db.session.remove()
"""A Python Flask REST API BoilerPlate (CRUD) Style""" import argparse import os from flask import Flask, jsonify, make_response from flask_cors import CORS from flask_swagger_ui import get_swaggerui_blueprint from routes import request_api import settings APP = Flask(__name__) ### swagger specific ### SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "rest-api-demo"}) APP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### APP.register_blueprint(request_api.get_blueprint()) @APP.errorhandler(400) def handle_400_error(_error): """Return a http 400 error to client""" return make_response(jsonify({'error': 'Misunderstood'}), 400) @APP.errorhandler(401) def handle_401_error(_error): """Return a http 401 error to client"""
def create_app(config: Configuration, tnc_pool: TNCPool, sids_relay: SIDSRelay) -> Flask: """ Creates a flask app for the api. """ log = logging.getLogger(__name__) static_folder = os.path.join(util.get_root(), config.get_conf("Client", "static-files-path")) app = Flask(__name__, static_url_path="", static_folder=static_folder) CORS(app) if not config.get_conf("Client", "debug-log"): server_log = logging.getLogger("werkzeug") server_log.setLevel(logging.WARN) # swagger specific swagger_url = "/api/docs" api_url = "/api/static/swagger.yaml" swaggerui_blueprint = get_swaggerui_blueprint( swagger_url, api_url, config={ "app_name": "Estcube 2 Telemetry API" } ) app.register_blueprint(swaggerui_blueprint, url_prefix=swagger_url) # end swagger specific @app.route("/api/sids/status", methods=["GET"]) def get_sids_status(): return jsonify(sids_relay.get_status()), 200 @app.route("/api/sids/toggle", methods=["POST"]) def toggle_relay(): response_json = request.get_json() current_relay_status = response_json["Mission Control"]["relay-enabled"] config.set_conf(section="Mission Control", element="relay-enabled", value=current_relay_status) if current_relay_status: threading.Thread(target=sids_relay.relay_unrelayed_packets, daemon=True).start() return response_json, 200 @app.route("/api/tnc/<name>/status", methods=["GET"]) def get_tnc_connection_check(name: str): if tnc_pool is None: return jsonify({"error": "TNC Pool is not defined."}), 500 res = tnc_pool.check_tnc(name) return jsonify({"name": name, "status": res.name}), 200 @app.route("/api/tnc/Main/start", methods=["POST"]) def post_tnc_main_start(): if tnc_pool is None: return jsonify({"error": "TNC Pool is not defined."}), 500 tnc_pool.connect_main_tnc() return "", 204 @app.route("/api/tnc/<name>/stop", methods=["POST"]) def post_tnc_connection_stop(name: str): if tnc_pool is None: return jsonify({"error": "TNC Pool is not defined."}), 500 tnc_pool.stop_tnc(name) return "", 204 @app.route("/api/conf", methods=["GET"]) def getconf(): """ Returns the whole current configuration object. """ res = config.get_all_conf() return jsonify(res) @app.route("/api/conf/constraints", methods=["GET"]) def get_constraints(): """ Returns all of the constraints for the configuration. """ constrs = config.get_constraints() return jsonify(constrs) @app.route("/api/conf/full", methods=["GET"]) def get_full_conf(): res = config.get_conf_with_constraints() return res @app.route("/", methods=["GET"]) def get_index(): return send_file(os.path.join(static_folder, "index.html")) @app.errorhandler(404) def not_found(e): return send_file(os.path.join(static_folder, "index.html")) @app.route("/api/static/<path:path>") def send_static(path): return send_from_directory("static", path) @app.route("/api/conf", methods=["POST"]) def post_set_conf(): some_json = request.get_json() try: for i in some_json: for j in some_json[i]: config.set_conf(section=i, element=j, value=some_json[i][j]) except: _, error, _ = sys.exc_info() return jsonify({"Error": "{err}".format(err=error)}), 500 return jsonify(some_json), 200 return app
from flask import Flask, request, jsonify from flask_cors import CORS from bs4 import BeautifulSoup import requests from flask_swagger_ui import get_swaggerui_blueprint app = Flask(__name__) CORS(app) ### swagger ### SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "socialmedia-image-scapel" } ) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger ### @app.route('/dribbble/', methods=['GET']) def dribbble(): # Retrieve the username from url parameter name = request.args.get("name", None) # For debugging print(f"got name {name}") source = requests.get(f"https://dribbble.com/{name}").text
try: my_ip = get_node_ip() except: pass else: SWAGGER_URL = '/api/docs' swagger_address = getenv("SWAGGER_HOST", my_ip) if settings['use_ssl']: API_URL = 'https://{}/api/swagger.json'.format(swagger_address) elif LISTEN == '127.0.0.1' or swagger_address != my_ip: API_URL = "http://{}/api/swagger.json".format(swagger_address) else: API_URL = "http://{}:{}/api/swagger.json".format(swagger_address, PORT) swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "Screenly API"}) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) ################################ # Views ################################ @app.route('/') @auth_basic def viewIndex(): player_name = settings['player_name'] my_ip = get_node_ip() resin_uuid = getenv("RESIN_UUID", None) ws_addresses = []
import argparse import os from flask import Flask, jsonify, make_response from flask_cors import CORS from flask_swagger_ui import get_swaggerui_blueprint import request_api APP = Flask(__name__) ### swagger specific ### SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "Rebecca-Flask-Rest-UserManagement"}) APP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### APP.register_blueprint(request_api.get_blueprint()) @APP.errorhandler(400) def handle_400_error(_error): """Return a http 400 error to client""" return make_response(jsonify({'error': 'Misunderstood'}), 400) @APP.errorhandler(401) def handle_401_error(_error): """Return a http 401 error to client"""
def setup_swaggerui(app): SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "Auth Server"}) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
from flask import Flask from flask_cors import CORS from flask_swagger_ui import get_swaggerui_blueprint app = Flask(__name__) app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog' CORS(app) SWAGGER_URL = '/swagger' API_URL = '../static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "Backend Info" } ) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) from backend.routing import routes
HOST = sys.argv[1] if len(sys.argv) > 1 else "0.0.0.0" PORT = 5000 # Create the database db.create_all() with app.app_context(): # Create a user user = User(name="test", email="em@il") api = Api(app, api_spec_url="/api/swagger", host="{}:{}".format(HOST, PORT), schemes=["http"]) # Expose the User object api.expose_object(User) # Set the JSON encoder used for object to json marshalling app.json_encoder = SAFRSJSONEncoder # Register the API at /api/docs swaggerui_blueprint = get_swaggerui_blueprint("/api", "/api/swagger.json") app.register_blueprint(swaggerui_blueprint, url_prefix="/api") @app.route("/") def goto_api(): return redirect("/api") print("Starting API: http://{}:{}/api".format(HOST, PORT)) # app.run(host=HOST, port = PORT)
conf = config.DevelopmentConfig app.config.from_object(conf) cors = CORS(app, resources={r"/*": {"origins": "*"}}) """ API Routes """ api.add_resource(Account, '/account') api.add_resource(Login, '/login') api.add_resource(Todolist, '/lists') api.add_resource(TodolistId, '/lists/<int:id_list>') api.add_resource(TodolistIdTodo, '/lists/todos/<int:id_list>') api.add_resource(TodolistIdTodoId, '/lists/todos/<int:id_list>/<int:id_todo>') """ Swagger """ @app.route("/swagger") def swaggerController(): swag = swagger(app) swag['info']['version'] = config.APP_VERSION swag['info']['title'] = config.API_NAME return jsonify(swag) swaggerui_blueprint = get_swaggerui_blueprint( conf.SWAGGER_URL, conf.DATA_SWAGGER, config={'app_name': "Flask API"}, ) app.register_blueprint(swaggerui_blueprint, url_prefix=conf.SWAGGER_URL)
# Register Routes app.register_blueprint(orderRoutes) ### Swagger Documentation ### @app.route('/swagger.json') def send_file(): return send_from_directory(app.static_folder, 'swagger.json') SWAGGER_URL = '/api-docs' API_URL = '/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "Orders-API" } ) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### #### App #### if __name__ == '__main__': ip = '0.0.0.0' port = app.config['APP_PORT'] debug = app.config['DEBUG'] # execute flask web server app.run(
SQLALCHEMY_DATABASE_URI= 'mysql+mysqlconnector://root:Meh@8567@user_db/user' # SQLALCHEMY_DATABASE_URI='mysql+mysqlconnector://root:Meh@8567@localhost:3306/user' )) models.db_init_app(app) models.ma_init_app(app) models.create_tables(app) app.register_blueprint(user_api_blueprint) SWAGGER_URL = '/api/docs' API_URL = '/api/user/docs.json' swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, ) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) @login_manager.user_loader def load_user(user_id): return models.User.query.filter_by(id=user_id).first() @login_manager.request_loader def load_user_from_request(request): # try to login using Basic Auth api_key = request.headers.get('Authorization') if api_key:
app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, cors_allowed_origins="*") SWAGGER_URL = '/api/docs' # URL for exposing Swagger UI (without trailing '/') # Our API url (can of course be a local resource) API_URL = 'http://localhost:5000/static/swagger.json' # Call factory function to create our blueprint swaggerui_blueprint = get_swaggerui_blueprint( # Swagger UI static files will be mapped to '{SWAGGER_URL}/dist/' SWAGGER_URL, API_URL, config={ # Swagger UI config overrides 'app_name': "Test application" }, # oauth_config={ # OAuth config. See https://github.com/swagger-api/swagger-ui#oauth2-configuration . # 'clientId': "your-client-id", # 'clientSecret': "your-client-secret-if-required", # 'realm': "your-realms", # 'appName': "your-app-name", # 'scopeSeparator': " ", # 'additionalQueryStringParams': {'test': "hello"} # } ) app.register_blueprint(swaggerui_blueprint) @app.before_first_request def init_database(): db.create_all() print("frist")
import os import traceback from flask import Flask, jsonify, request, Response from flask_swagger_ui import get_swaggerui_blueprint application = Flask(__name__) ### swagger specific ### SWAGGER_URL = "/documentation" API_URL = "/static/openapi.json" SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={"app_name": "CARAMLService"}) application.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### @application.route("/", methods=["GET", "POST"]) def welcome(): response_text = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>CARA ML Service</title> <h2>Welcome to !</h2> <p></p>""" return response_text @application.route("/do_stuff", methods=["POST"]) def do_stuff(): content = request.get_json(silent=True) try: # do something return jsonify(content), 200
from .serializers import KqueenJSONEncoder from .storages.etcd import EtcdBackend from flask import Flask from flask_jwt import JWT from flask_swagger_ui import get_swaggerui_blueprint from werkzeug.contrib.cache import SimpleCache import logging logger = logging.getLogger(__name__) cache = SimpleCache() swagger_url = '/api/docs' api_url = '/api/v1/swagger' swaggerui_blueprint = get_swaggerui_blueprint(swagger_url, api_url, config={'docExpansion': 'list'}) def create_app(config_file=None): app = Flask(__name__, static_folder='./asset/static') app.json_encoder = KqueenJSONEncoder app.register_blueprint(api, url_prefix='/api/v1') app.register_blueprint(metrics, url_prefix='/metrics') app.register_blueprint(swaggerui_blueprint, url_prefix=swagger_url) # load configuration config = current_config(config_file) config.setup_policies()
# Create a user and a book and add the book to the user.books relationship user = User(name="thomas", email="em@il") book = Book(name="test_book") for i in range(100): user = User(name="test_name_" + str(i)) user.books.append(book) api = Api(app, api_spec_url=API_PREFIX + "/swagger", host="{}:{}".format(HOST, PORT)) # Expose the database objects as REST API endpoints api.expose_object(User) api.expose_object(Book) # Set the JSON encoder used for object to json marshalling app.json_encoder = SAFRSJSONEncoder @app.route("/") def goto_api(): """Create a redirect from / to /api""" return redirect(API_PREFIX) # Register the API at /api/docs swaggerui_blueprint = get_swaggerui_blueprint( API_PREFIX, API_PREFIX + "/swagger.json") app.register_blueprint(swaggerui_blueprint, url_prefix=API_PREFIX) print("Starting API: http://{}:{}{}".format(HOST, PORT, API_PREFIX)) print(dir(api)) print(api.endpoints) app.run(host=HOST, port=PORT)
from flask_migrate import Migrate # from flask_restful import Api from flask_sqlalchemy import SQLAlchemy, get_debug_queries from flask_swagger_ui import get_swaggerui_blueprint import config app = Flask(__name__) app.config.from_object(config.Config) db = SQLAlchemy(app) migrate = Migrate(app, db) api = flask_restful.Api(app) SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': 'IMDb приложение'}) app.register_blueprint( SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) # привязыв. наш URL '/swagger' к нашему приложению app.debug = True def sql_debug(response): queries = list(get_debug_queries()) total_duration = 0.0 for q in queries: total_duration += q.duration print('=' * 80) print(' SQL Queries - {0} Queries Executed in {1}ms'.format(
app.register_blueprint(blueprint_nlp, url_prefix="/api/v1/ner") with app.test_request_context(): # register all swagger documented functions here for fn_name in app.view_functions: if fn_name == "static": continue print(f"Loading swagger docs for function: {fn_name}") view_fn = app.view_functions[fn_name] spec.path(view=view_fn) @app.route("/api/swagger.json") def create_swagger_spec(): return jsonify(spec.to_dict()) if __name__ == "__main__": #################### # FOR DEVELOPMENT #################### """Definition of the Swagger UI Blueprint.""" SWAGGER_URL = "/api/docs" API_URL = "/api/swagger.json" # Call factory function to create our blueprint swagger_ui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={"app_name": "My App"} ) app.register_blueprint(swagger_ui_blueprint, url_prefix=SWAGGER_URL) app.run(host="0.0.0.0", port=3001, debug=True)
from flask import Flask, request, render_template, session from flask import redirect from functools import wraps import os from flask_swagger_ui import get_swaggerui_blueprint app = Flask(__name__) app.secret_key = "secretkey" app.config["UPLOADED_PHOTOS_DEST"] = "static" ### swagger specific ### SWAGGER_URL = "/swagger" API_URL = "/static/swagger.json" SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ "app_name": "Seans-Python-Flask-REST-Boilerplate"} ) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### books = [ { "author": "Hernando de Soto", "country": "Peru", "language": "English", "pages": 209, "title": "The Mystery of Capital", "year": 1970, }, { "author": "Hans Christian Andersen", "country": "Denmark", "language": "Danish", "pages": 784,
def create_app(char_limit=-1, req_limit=-1, batch_limit=-1, ga_id=None, debug=False, frontend_language_source="en", frontend_language_target="en", frontend_timeout=500): from app.init import boot boot() from app.language import languages app = Flask(__name__) # For faster access language_map = {} for l in languages: language_map[l.code] = l.name if debug: app.config['TEMPLATES_AUTO_RELOAD'] = True # Map userdefined frontend languages to argos language object. if frontend_language_source == "auto": frontend_argos_language_source = type('obj', (object, ), { 'code': 'auto', 'name': 'Auto Detect' }) else: frontend_argos_language_source = next( iter([l for l in languages if l.code == frontend_language_source]), None) frontend_argos_language_target = next( iter([l for l in languages if l.code == frontend_language_target]), None) # Raise AttributeError to prevent app startup if user input is not valid. if frontend_argos_language_source is None: raise AttributeError( f"{frontend_language_source} as frontend source language is not supported." ) if frontend_argos_language_target is None: raise AttributeError( f"{frontend_language_target} as frontend target language is not supported." ) if req_limit > 0: from flask_limiter import Limiter limiter = Limiter(app, key_func=get_remote_address, default_limits=["%s per minute" % req_limit]) @app.errorhandler(400) def invalid_api(e): return jsonify({"error": str(e.description)}), 400 @app.errorhandler(500) def server_error(e): return jsonify({"error": str(e.description)}), 500 @app.errorhandler(429) def slow_down_error(e): return jsonify({"error": "Slowdown: " + str(e.description)}), 429 @app.route("/") def index(): return render_template('index.html', gaId=ga_id, frontendTimeout=frontend_timeout) @app.route("/languages") def langs(): """ Retrieve list of supported languages --- tags: - translate responses: 200: description: List of languages schema: id: languages type: array items: type: object properties: code: type: string description: Language code name: type: string description: Human-readable language name (in English) 429: description: Slow down schema: id: error-slow-down type: object properties: error: type: string description: Reason for slow down """ return jsonify([{'code': l.code, 'name': l.name} for l in languages]) # Add cors @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', "Authorization, Content-Type") response.headers.add('Access-Control-Expose-Headers', "Authorization") response.headers.add('Access-Control-Allow-Methods', "GET, POST") response.headers.add('Access-Control-Allow-Credentials', "true") response.headers.add('Access-Control-Max-Age', 60 * 60 * 24 * 20) return response @app.route("/translate", methods=['POST']) def translate(): """ Translate text from a language to another --- tags: - translate parameters: - in: formData name: q schema: oneOf: - type: string example: Hello world! - type: array example: ['Hello world!'] required: true description: Text(s) to translate - in: formData name: source schema: type: string example: en required: true description: Source language code - in: formData name: target schema: type: string example: es required: true description: Target language code responses: 200: description: Translated text schema: id: translate type: object properties: translatedText: oneOf: - type: string - type: array description: Translated text(s) 400: description: Invalid request schema: id: error-response type: object properties: error: type: string description: Error message 500: description: Translation error schema: id: error-response type: object properties: error: type: string description: Error message 429: description: Slow down schema: id: error-slow-down type: object properties: error: type: string description: Reason for slow down """ if request.is_json: json = request.get_json() q = json.get('q') source_lang = json.get('source') target_lang = json.get('target') else: q = request.values.get("q") source_lang = request.values.get("source") target_lang = request.values.get("target") if not q: abort(400, description="Invalid request: missing q parameter") if not source_lang: abort(400, description="Invalid request: missing source parameter") if not target_lang: abort(400, description="Invalid request: missing target parameter") batch = isinstance(q, list) if batch and batch_limit != -1: batch_size = len(q) if batch_limit < batch_size: abort(400, description= "Invalid request: Request (%d) exceeds text limit (%d)" % (batch_size, batch_limit)) if char_limit != -1: if batch: chars = sum([len(text) for text in q]) else: chars = len(q) if char_limit < chars: abort( 400, description= "Invalid request: Request (%d) exceeds character limit (%d)" % (chars, char_limit)) if source_lang == 'auto': candidate_langs = list( filter(lambda l: l.lang in language_map, detect_langs(q))) if len(candidate_langs) > 0: candidate_langs.sort(key=lambda l: l.prob, reverse=True) if debug: print(candidate_langs) source_lang = next( iter([ l.code for l in languages if l.code == candidate_langs[0].lang ]), None) if not source_lang: source_lang = 'en' else: source_lang = 'en' if debug: print("Auto detected: %s" % source_lang) src_lang = next(iter([l for l in languages if l.code == source_lang]), None) tgt_lang = next(iter([l for l in languages if l.code == target_lang]), None) if src_lang is None: abort(400, description="%s is not supported" % source_lang) if tgt_lang is None: abort(400, description="%s is not supported" % target_lang) translator = src_lang.get_translation(tgt_lang) try: if batch: return jsonify({ "translatedText": [translator.translate(text) for text in q] }) else: return jsonify({"translatedText": translator.translate(q)}) except Exception as e: abort(500, description="Cannot translate text: %s" % str(e)) @app.route("/frontend/settings") def frontend_settings(): """ Retrieve frontend specific settings --- tags: - frontend responses: 200: description: frontend settings schema: id: frontend-settings type: object properties: charLimit: type: integer description: Character input limit for this language (-1 indicates no limit) frontendTimeout: type: integer description: Frontend translation timeout language: type: object properties: source: type: object properties: code: type: string description: Language code name: type: string description: Human-readable language name (in English) target: type: object properties: code: type: string description: Language code name: type: string description: Human-readable language name (in English) """ return jsonify({ 'charLimit': char_limit, 'frontendTimeout': frontend_timeout, 'language': { 'source': { 'code': frontend_argos_language_source.code, 'name': frontend_argos_language_source.name }, 'target': { 'code': frontend_argos_language_target.code, 'name': frontend_argos_language_target.name } } }) swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "LibreTranslate" @app.route("/spec") def spec(): return jsonify(swag) SWAGGER_URL = '/docs' # URL for exposing Swagger UI (without trailing '/') API_URL = '/spec' # Call factory function to create our blueprint swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL) app.register_blueprint(swaggerui_blueprint) return app
from hashlib import sha256 from flask_cors import CORS, cross_origin from flask_swagger_ui import get_swaggerui_blueprint # ************************** authentification JWT microservice **************************# # inputs : username/email , password # # outputs : access_token , refresh_token # # ***************************************************************************************# app = Flask(__name__) ### swagger specific ### SWAGGER_URL = '/auth/swagger' API_URL = '/static/swagger.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={'app_name': "JWT Authentification microservice"}) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### cors = CORS(app, resources={r"/*": {"origins": "*"}}) api = Api(app, prefix="/auth") # cros config app.config['CORS_HEADERS'] = 'application/json' # JWT Config app.config['JWT_SECRET_KEY'] = '4Si_S8A' jwt = JWTManager(app)
pass else: SWAGGER_URL = '/api/docs' swagger_address = getenv("SWAGGER_HOST", my_ip) if settings['use_ssl']: API_URL = 'https://{}/api/swagger.json'.format(swagger_address) elif LISTEN == '127.0.0.1' or swagger_address != my_ip: API_URL = "http://{}/api/swagger.json".format(swagger_address) else: API_URL = "http://{}:{}/api/swagger.json".format(swagger_address, PORT) swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "Screenly API" } ) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) ################################ # Views ################################ @app.route('/') @auth_basic def viewIndex(): player_name = settings['player_name']
#!/usr/bin/python3 import json from flask import Flask, jsonify, request, Response from flask_swagger_ui import get_swaggerui_blueprint import MemUsageMonitor app = Flask(__name__) ### swagger specific ### SWAGGER_URL = '/api' API_URL = '/static/swagger_3.json' SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint( SWAGGER_URL, # Swagger UI static files will be mapped to '{SWAGGER_URL}/dist/' API_URL, config={'app_name': "Memory usage API"}) app.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL) ### end swagger specific ### mum = MemUsageMonitor.MemUsageMonitor() # curl -d '{"threshold":40}' -H "Content-Type: application/json" -X POST http://<IP>:5000/memusage @app.route('/') def index(): helpMsg = { "/": "This help message", "/memusage": "Memory usage", "/memusage POST data {'threshold' : 40}": "Change mem usage threshold" }