python之如何在python中使用flask_restplus在swagger ui上使用*********隐藏密码
jyk
阅读:21
2024-11-24 20:56:43
评论:0
嗨,下面是我的运行代码,可以通过以下 URL 访问:
http://127.0.0.1:5000/api/documentation
from flask import Flask, Blueprint
from flask_restplus import Api, Resource, fields
app = Flask(__name__)
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint, doc='/documentation') #,doc=False
app.register_blueprint(blueprint)
app.config['SWAGGER_UI_JSONEDITOR'] = True
login_details = api.model('LoginModel',{'user_name' : fields.String('The Username.'),'pass_word' : fields.String('The password.'),})
# pass_word = api.model('Pwd', {'pass_word' : fields.String('The password.')})
credentials = []
python = {'user_name' : '1234','pwd':'23213413'}
credentials.append(python)
@api.route('/login')
class Language(Resource):
@api.marshal_with(login_details, envelope='the_data',mask='pass_word')
def get(self):
return credentials
@api.expect(login_details)
@api.marshal_with(login_details, envelope='the_data',mask='pass_word')
def post(self):
login_details = api.payload
print(login_details)
login_details['id'] = len(credentials) + 1
credentials.append(login_details)
return {'result' : 'credentials added'}, 201
if __name__ == '__main__':
app.run(debug=True)
当我进入 swagger UI 时,你能告诉我应该怎么做才能用 ***** 隐藏密码,并且值应该正确传递给参数。
请您参考如下方法:
根据 flask-restful documentation关于Models,你可以在开头看到 fields.Raw
上课可以带 format
parameter :
它可以:
modify how the value of existing object keys should be presented
所以你可以用这个
format
值为
'password'
的参数,如
Swagger documentation about data types 中所述在“字符串”部分下:
An optional format modifier serves as a hint at the contents and format of the string. OpenAPI defines the following built-in string formats:
[...]
password – a hint to UIs to mask the input
所以你可以使用这个
format='password'
就像在您的字段定义中一样:
pass_word = fields.String('The password.', format='password')
但问题是您使用的是
expect
装饰器,标准
Model
定义,它不允许您轻松自定义请求解析器。我建议使用
Marshmallow能够更好地控制对象序列化。
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。