简体   繁体   中英

@app.route returns html and @api.route returns string

I use Flask for setting up APIs. For some simple tests I return html tags. Using Flask_restplus however returns a string. I would like to know why and how I could change this? Of course I could use Jinja but I'd like to know how to change this in this small example.

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)

As commented @app.route returns html and @api.route returns a string

Here is the code:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM