在Python Flask应用程序中发送对OPTIONS的响应

时间:2015-05-20 22:28:22

标签: python http flask

我有一个python Flask监听器在端口8080上等待。我希望另一个进程对该端口进行一系列POST。监听器的代码如下。

#!/usr/bin/env python2
from __future__ import print_function
from flask import Flask, request
from werkzeug import secure_filename
from datetime import datetime
import os, traceback, sys 
import zlib
import ssl 
import json
import os
import base64

app = Flask('__name__')

@app.route('/',methods=['GET','POST','OPTIONS'])                                                                                                                                         
def recive_fe_events():
    try:
        data = request.get_data()

        if request.content_length < 20000 and request.content_length != 0:
            filename = 'out/{0}.json'.format(str(datetime.now()))
            with open(filename, 'w') as f:
                 f.write(data)

            print('Wrote', filename)
        else:
            print("Request too long", request.content_length)
            content = '{{"status": 413, "content_length": {0}, "content": "{1}"}}'.format(request.content_length, data)
            return content, 413 
    except:
        traceback.print_exc()
        return None, status.HTTP_500_INTERNAL_SERVER_ERROR

    return '{"status": 200}\n'

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=False,port=8080)

但是每当我尝试触发一个事件被推送到上面的监听器时。我似乎得到OPTIONS而不是POST

192.168.129.75 - - [20/May/2015 14:33:45] "OPTIONS / HTTP/1.1" 200 -
192.168.129.75 - - [20/May/2015 14:33:45] "OPTIONS / HTTP/1.1" 200 -
192.168.129.75 - - [20/May/2015 14:33:51] "OPTIONS / HTTP/1.1" 200 -
192.168.129.75 - - [20/May/2015 14:33:51] "OPTIONS / HTTP/1.1" 200 -

对我的客户的调查显示,它希望responseOPTIONS中有以下标志。

Access-Control-Allow-Origin          value_1
Access-Control-Allow-Methods         value_2      
Access-Control-Allow-Headers         value_3

如何将上述response格式化为OPTIONS,以便我的服务器可以开始从客户端接收POST条消息。

1 个答案:

答案 0 :(得分:0)

您需要为CORS设置应用程序。最简单的方法是使用Flask-CORS