本文整理汇总了Python中flasgger.Swagger方法的典型用法代码示例。如果您正苦于以下问题:Python flasgger.Swagger方法的具体用法?Python flasgger.Swagger怎么用?Python flasgger.Swagger使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flasgger
的用法示例。
在下文中一共展示了flasgger.Swagger方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_app
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def create_app():
# setting the static_url_path to blank serves static files from the web root
app = Flask(__name__, static_url_path='')
app.config.from_object(__name__)
Swagger(app, template_file='definitions.yaml')
app.redis = Redis.from_url(app.config['REDIS_URL'])
app.task_queue = rq.Queue('recon-tasks', connection=app.redis)
@app.after_request
def disable_cache(response):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
@app.route('/')
def index():
return render_template('index.html', workspaces=recon._get_workspaces())
from recon.core.web.api import resources
app.register_blueprint(resources)
return app
示例2: return_test
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def return_test(size):
"""
another test return
---
properties:
result:
type: string
description: The test
default: 'test2'
"""
size = int(size)
return {"result": "test2" * size}
# Flask endpoints with flasgger docstrings are automatically registered.
# The first line of the docstring is used as the summary/
# The following lines (before '---') are used as the description.
# YAML after '---' defines the Swagger path schema.
示例3: requires_basic_auth
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def requires_basic_auth(f):
"""Decorator to require HTTP Basic Auth for your endpoint."""
def check_auth(username, password):
return username == "guest" and password == "secret"
def authenticate():
return Response(
"Authentication required.", 401,
{"WWW-Authenticate": "Basic realm='Login Required'"},
)
@wraps(f)
def decorated(*args, **kwargs):
# NOTE: This example will require Basic Auth only when you run the
# app directly. For unit tests, we can't block it from getting the
# Swagger specs so we just allow it to go thru without auth.
# The following two lines of code wouldn't be needed in a normal
# production environment.
if __name__ != "__main__":
return f(*args, **kwargs)
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
示例4: get
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def get(self):
"""
If we set "parse" is True in Flasgger app, we will get parsed and
validated data stored in "flask.request.parsed_data".
In "parsed_data", different location's var stored in different key,
there is a map between RequestParser's location and swagger
doc's "in" parameter, eg: 'query' -> 'args'.See
"Swagger.SCHEMA_LOCATIONS" for more locations
"""
return jsonify(
[{'name': 'test', 'id': 1,
'type': request.parsed_data['args']['type']},
{'name': 'test2', 'id': 2,
'type': request.parsed_data['args']['type']}])
示例5: get_specs_data
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def get_specs_data(mod):
"""
return all specs dictionary for some app
"""
# for each example app in /examples folder
client = mod.app.test_client()
# init swag if not yet inititalized (no-routes example)
specs_route = None
specs_data = {}
if getattr(mod.app, 'swag', None) is None:
_swag = Swagger()
_swag.config['endpoint'] = str(random.randint(1, 5000))
_swag.init_app(mod.app)
# get all the specs defined for the example app
else:
try:
flasgger_config = mod.swag.config
if flasgger_config.get('swagger_ui') is False:
return specs_data
specs_route = flasgger_config.get('specs_route', '/apidocs/')
except AttributeError:
pass
if specs_route is None:
specs_route = '/apidocs/'
apidocs = client.get('?'.join((specs_route, 'json=true')))
specs = json.loads(apidocs.data.decode("utf-8")).get('specs')
for spec in specs:
# for each spec get the spec url
url = spec['url']
response = client.get(url)
decoded = response.data.decode("utf-8")
specs_data[url] = json.loads(decoded)
return specs_data
示例6: __init__
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def __init__(self, app=None):
self.app = app
self.swagger = Swagger()
if app:
self.init_app(app)
示例7: create_flask_app
# 需要导入模块: import flasgger [as 别名]
# 或者: from flasgger import Swagger [as 别名]
def create_flask_app(self):
try:
from flask import Flask, request
from flask_compress import Compress
from flask_cors import CORS
from flask_json import FlaskJSON, as_json, JsonError
from bert_serving.client import ConcurrentBertClient
from flasgger import Swagger
except ImportError:
raise ImportError('BertClient or Flask or its dependencies are not fully installed, '
'they are required for serving HTTP requests.'
'Please use "pip install -U bert-serving-server[http]" to install it.')
# support up to 10 concurrent HTTP requests
bc = ConcurrentBertClient(max_concurrency=self.args.http_max_connect,
port=self.args.port, port_out=self.args.port_out,
output_fmt='list', ignore_all_checks=True)
app = Flask(__name__)
app.config['SWAGGER'] = {
'title': 'Colors API',
'uiversion': 3,
'openapi': '3.0.2'
}
swag = Swagger(app, template_file='bertApi.openapi.yaml')
logger = set_logger(colored('PROXY', 'red'))
@app.route('/status/server', methods=['GET'])
@as_json
def get_server_status():
return bc.server_status
@app.route('/status/client', methods=['GET'])
@as_json
def get_client_status():
return bc.status
@app.route('/encode', methods=['POST'])
@as_json
def encode_query():
data = request.form if request.form else request.json
try:
logger.info('new request from %s' % request.remote_addr)
return {'id': data['id'],
'result': bc.encode(data['texts'], is_tokenized=bool(
data['is_tokenized']) if 'is_tokenized' in data else False)}
except Exception as e:
logger.error('error when handling HTTP request', exc_info=True)
raise JsonError(description=str(e), type=str(type(e).__name__))
CORS(app, origins=self.args.cors)
FlaskJSON(app)
Compress().init_app(app)
return app