2014-09-16 12 views
48

Đây là mã của tôi:Làm cách nào để đặt tiêu đề phản hồi trong Flask?

@app.route('/hello', methods=["POST"]) 
def hello(): 
    resp = make_response() 
    resp.headers['Access-Control-Allow-Origin'] = '*' 
    return resp 

Tuy nhiên, khi tôi thực hiện một yêu cầu từ trình duyệt đến máy chủ của tôi, tôi nhận được lỗi này:

XMLHttpRequest cannot load http://localhost:5000/hello. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 

Tôi cũng đã cố gắng tiếp cận này, thiết lập các tiêu đề phản ứng "sau" yêu cầu:

@app.after_request 
def add_header(response): 
    response.headers['Access-Control-Allow-Origin'] = '*' 
    return response 

Không súc sắc. Tôi nhận được lỗi tương tự. Có cách nào để chỉ đặt tiêu đề phản hồi trong hàm tuyến đường không? Một cái gì đó như thế này sẽ là lý tưởng:

@app.route('/hello', methods=["POST"]) 
    def hello(response): # is this a thing?? 
     response.headers['Access-Control-Allow-Origin'] = '*' 
     return response 

nhưng tôi không thể tìm thấy anyway để làm điều này. Hãy giúp tôi.

EDIT

nếu tôi cuộn tròn url với một yêu cầu POST như vậy:

curl -iX POST http://localhost:5000/hello 

tôi nhận được câu trả lời này:

HTTP/1.0 500 INTERNAL SERVER ERROR 
Content-Type: text/html 
Content-Length: 291 
Server: Werkzeug/0.9.6 Python/2.7.6 
Date: Tue, 16 Sep 2014 03:58:42 GMT 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 
<title>500 Internal Server Error</title> 
<h1>Internal Server Error</h1> 
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p> 

Bất kỳ ý tưởng?

Trả lời

48

Bạn có thể làm được điều này khá dễ dàng:

@app.route("/") 
def home(): 
    resp = flask.Response("Foo bar baz") 
    resp.headers['Access-Control-Allow-Origin'] = '*' 
    return resp 

Nhìn vào flask.Responseflask.make_response()

Nhưng điều gì đó nói với tôi bạn có một vấn đề khác, bởi vì after_request nên đã xử lý nó một cách chính xác quá.

EDIT
Tôi chỉ nhận thấy bạn đang sử dụng make_response đó là một trong những cách để làm điều đó. Như tôi đã nói trước đây, after_request cũng đã hoạt động. Hãy thử nhấn endpoint qua curl và xem những gì các tiêu đề là:

curl -i http://127.0.0.1:5000/your/endpoint 

Bạn sẽ thấy

> curl -i 'http://127.0.0.1:5000/' 
HTTP/1.0 200 OK 
Content-Type: text/html; charset=utf-8 
Content-Length: 11 
Access-Control-Allow-Origin: * 
Server: Werkzeug/0.8.3 Python/2.7.5 
Date: Tue, 16 Sep 2014 03:47:13 GMT 

Ghi nhận header Access-Control-Allow-Origin.

CHỈNH SỬA 2
Như tôi nghi ngờ, bạn đang nhận được 500 để bạn không đặt tiêu đề như bạn nghĩ. Thử thêm app.debug = True trước khi bạn khởi động ứng dụng và thử lại. Bạn sẽ nhận được một số đầu ra cho bạn thấy nguyên nhân gốc rễ của vấn đề.

Ví dụ:

@app.route("/") 
def home(): 
    resp = flask.Response("Foo bar baz") 
    user.weapon = boomerang 
    resp.headers['Access-Control-Allow-Origin'] = '*' 
    return resp 

Cung cấp cho một trang lỗi html định dạng độc đáo, với điều này ở phía dưới (hữu ích cho lệnh curl)

Traceback (most recent call last): 
... 
    File "/private/tmp/min.py", line 8, in home 
    user.weapon = boomerang 
NameError: global name 'boomerang' is not defined 
+0

Hãy xem chỉnh sửa. Tôi gặp lỗi 500. – dopatraman

2

Công việc này đối với tôi

from flask import Flask 
from flask import Response 

app = Flask(__name__) 

@app.route("/") 
def home(): 
    resp = Response("") 
    resp.headers['Access-Control-Allow-Origin'] = '*' 
    return resp 

if __name__ == "__main__": 
    app.run() 
7

Sử dụng make_response của Bình giống như

@app.route("/") 
def home(): 
    resp = make_response("hello") #here you could use make_response(render_template(...)) too 
    resp.headers['Access-Control-Allow-Origin'] = '*' 
    return resp 

Từ flask docs,

flask.make_response(*args)

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

+1

Làm thế nào về một đoạn mã để chứng minh? –

+0

Bạn có thể gửi các yêu cầu trong args: http://flask.pocoo.org/docs/0.10/api/#flask.Flask.make_response – tokland

Các vấn đề liên quan