我使用Flask设置API。对于一些简单的测试,我返回html标签。但是,使用Flask_restplus返回一个字符串。我想知道为什么以及如何更改此设置?当然,我可以使用Jinja,但我想在这个小示例中知道如何更改此设置。
from flask import Flask, request
from flask_restplus import Resource, Api, fields
app = Flask(__name__)
api = Api(app)
# This code returns HTML
@app.route('/test1')
def language():
language = request.args.get('language')
message = '<h1>Hello world! I speak {}</h1>'.format(language)
return message
# This code returns string e.g. '<h1>Hello wolrd! I speak english</h1>
@api.route('/hello')
class HelloWorld(Resource):
def get(self):
language = request.args.get('language')
message = '<h1>Hello world! I speak {}</h1>'.format(language)
return message
if __name__ == '__main__':
app.debug = True
app.run(port=4996)
如评论所示,@ app.route返回html,@ api.route返回字符串
答案 0 :(得分:1)
代码如下:
from flask import Flask, request, jsonify, Response
from flask_restplus import Resource, Api, fields
app = Flask(__name__)
api = Api(app)
# This code returns HTML
@app.route('/test1')
def language():
language = request.args.get('language')
message = '<h1>Hello world! I speak {}</h1>'.format(language)
return message
def output_html(data, code, headers=None):
resp = Response(data, mimetype='text/html', headers=headers)
resp.status_code = code
return resp
# This code returns string e.g. '<h1>Hello wolrd! I speak english</h1>
@api.route('/hello')
class HelloWorld(Resource):
def get(self):
language = request.args.get('language')
message = '<h1>Hello world! I speak {}</h1>'.format(language)
return output_html(message, 200)
if __name__ == '__main__':
app.debug = True
app.run(port=4996)