sourcecode

Python Flask, 콘텐츠 유형 설정 방법

copyscript 2022. 10. 27. 22:21
반응형

Python Flask, 콘텐츠 유형 설정 방법

저는 플라스크를 사용하고 있으며 get request에서 XML 파일을 반송합니다.콘텐츠 유형을 xml로 설정하려면 어떻게 해야 합니까?

예.

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    header("Content-type: text/xml")
    return xml

다음과 같이 시도합니다.

from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    return Response(xml, mimetype='text/xml')

실제 Content-Type은 mimtype 파라미터와 charset(기본값은 UTF-8)에 기초하고 있습니다.

응답(및 요청) 오브젝트는 http://werkzeug.pocoo.org/docs/wrappers/에 기재되어 있습니다.

이렇게 심플하다

x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}

도움이 되었으면 좋겠다

업데이트: python 2.x와 python 3.x 모두와 함께 작동하며 "복수 헤더" 문제(복수의 중복된 헤더를 방출할 수 있음)를 제거하므로 아래 방법을 사용하십시오.

from flask import Response
r = Response(response="TEST OK", status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r

나는 @Simon Sapin의 답변을 좋아하고 상향 투표했다.하지만 저는 조금 다른 방법을 택해서 저만의 데코레이터를 만들었습니다.

from flask import Response
from functools import wraps

def returns_xml(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        r = f(*args, **kwargs)
        return Response(r, content_type='text/xml; charset=utf-8')
    return decorated_function

다음과 같이 사용합니다.

@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
    xml = 'foo'
    return xml

이게 조금 더 편한 것 같아요.

make_response 메서드를 사용하여 데이터에 대한 응답을 얻을 수 있습니다.그런 다음 mimtype 속성을 설정합니다.마지막으로 다음 응답을 반환합니다.

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

사용하시는 경우Response직접, 다음과 같은 설정을 통해 반응을 사용자 정의할 수 있는 기회를 잃게 됩니다.app.response_class.그make_response메서드는app.responses_class응답 오브젝트를 만듭니다.이 항목에서는 자체 클래스를 만들고 응용 프로그램에서 해당 클래스를 글로벌하게 사용하도록 추가할 수 있습니다.

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse  
from flask import Flask, render_template, make_response
app = Flask(__name__)

@app.route('/user/xml')
def user_xml():
    resp = make_response(render_template('xml/user.html', username='Ryan'))
    resp.headers['Content-type'] = 'text/xml; charset=utf-8'
    return resp

다음의 방법(python3.6.2)을 시험할 수 있습니다.

케이스 1:

@app.route('/hello')
def hello():

    headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
    response = make_response('<h1>hello world</h1>',301)
    response.headers = headers
    return response

케이스 2:

@app.route('/hello')
def hello():

    headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
    return '<h1>hello world</h1>',301,headers

플라스크를 사용하고 있습니다.그리고 만약 당신이 json을 반환하고 싶다면, 다음과 같이 쓸 수 있습니다.

import json # 
@app.route('/search/<keyword>')
def search(keyword):

    result = Book.search_by_keyword(keyword)
    return json.dumps(result),200,{'content-type':'application/json'}


from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):

    result = Book.search_by_keyword(keyword)
    return jsonify(result)

보통 오브젝트를 직접 작성할 필요는 없습니다.그러면 이 오브젝트는 사용자가 알아서 처리해 줍니다.

from flask import Flask, make_response                                      
app = Flask(__name__)                                                       

@app.route('/')                                                             
def index():                                                                
    bar = '<body>foo</body>'                                                
    response = make_response(bar)                                           
    response.headers['Content-Type'] = 'text/xml; charset=utf-8'            
    return response

한 가지 더 말씀드리자면, 아무도 에 대해 언급하지 않은 것 같습니다.

after_this_request

이 요구 후에 함수를 실행합니다.이는 응답 개체를 수정하는 데 유용합니다.함수는 응답 개체를 전달하고 동일한 개체 또는 새 개체를 반환해야 합니다.

에서 실행할 수 있도록 코드는 다음과 같습니다.

from flask import Flask, after_this_request
app = Flask(__name__)

@app.route('/')
def index():
    @after_this_request
    def add_header(response):
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return response
    return '<body>foobar</body>'

언급URL : https://stackoverflow.com/questions/11773348/python-flask-how-to-set-content-type

반응형