我们的项目有两个应用程序。一个是用于前端的NextJS,另一个是用于后端的Flask应用。这两个应用程序位于DigitalOcean中的两个不同的应用程序中。现在通常是为了避免CORS错误,我将Flask应用配置为:
app = Flask(__name__, instance_relative_config=True, template_folder="templates")
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['CORS_METHODS'] = ["GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"]
cors = CORS(app)
通常这可以正常工作,我可以毫无问题地访问后端中的所有端点。但是我们还向flask应用添加了服务器发送事件。代码是这样的:
from queue import Queue
from collections import defaultdict
class Publisher(object):
"""
Contains a list of subscribers that can can receive updates.
Each subscriber can have its own private data and may subscribe to
different channel.
"""
END_STREAM = {}
def __init__(self):
"""
Creates a new publisher with an empty list of subscribers.
"""
self.subscribers_by_channel = defaultdict(list)
def _get_subscribers_lists(self, channel):
if isinstance(channel, str):
yield self.subscribers_by_channel[channel]
else:
for channel_name in channel:
yield self.subscribers_by_channel[channel_name]
def get_subscribers(self, channel='default channel'):
"""
Returns a generator of all subscribers in the given channel.
`channel` can either be a channel name (e.g. "secret room") or a list
of channel names (e.g. "['chat', 'global messages']"). It defaults to
the channel named "default channel".
"""
for subscriber_list in self._get_subscribers_lists(channel):
yield from subscriber_list
def _publish_single(self, data, queue):
"""
Publishes a single piece of data to a single user. Data is encoded as
required.
"""
str_data = str(data)
for line in str_data.split('\n'):
queue.put('data: {}\n'.format(line))
queue.put('\n')
def publish(self, data, channel='default channel'):
"""
Publishes data to all subscribers of the given channel.
`channel` can either be a channel name (e.g. "secret room") or a list
of channel names (e.g. "['chat', 'global messages']"). It defaults to
the channel named "default channel".
If data is callable, the return of `data(properties)` will be published
instead, for the `properties` object of each subscriber. This allows
for customized events.
"""
# Note we call `str` here instead of leaving it to each subscriber's
# `format` call. The reason is twofold: this caches the same between
# subscribers, and is not prone to time differences.
if callable(data):
for queue, properties in self.get_subscribers(channel):
value = data(properties)
if value:
self._publish_single(value, queue)
else:
for queue, _ in self.get_subscribers(channel):
self._publish_single(data, queue)
def subscribe(self, channel='default channel', properties=None, initial_data=[]):
"""
Subscribes to the channel, returning an infinite generator of
Server-Sent-Events.
`channel` can either be a channel name (e.g. "secret room") or a list
of channel names (e.g. "['chat', 'global messages']"). It defaults to
the channel named "default channel".
If `properties` is passed, these will be used for differentiation if a
callable object is published (see `Publisher.publish`).
If the list `initial_data` is passed, all data there will be sent
before the regular channel process starts.
"""
queue = Queue()
properties = properties or {}
subscriber = (queue, properties)
for data in initial_data:
self._publish_single(data, queue)
for subscribers_list in self._get_subscribers_lists(channel):
subscribers_list.append(subscriber)
return self._make_generator(queue)
def _make_generator(self, queue):
"""
Returns a generator that reads data from the queue, emitting data
events, while the Publisher.END_STREAM value is not received.
"""
while True:
data = queue.get()
if data is Publisher.END_STREAM:
return
yield data
def close(self):
"""
Closes all active subscriptions.
"""
for channel in self.subscribers_by_channel.values():
for queue, _ in channel:
queue.put(Publisher.END_STREAM)
channel.clear()
if __name__ == '__main__':
# Starts an example chat application.
# Run this module and point your browser to http://localhost:5000
import cgi
import flask
from flask_cors import CORS
from flask_cors import cross_origin
publisher = Publisher()
app = flask.Flask(__name__, instance_relative_config=True, static_folder='static', static_url_path='')
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['CORS_METHODS'] = ["GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"]
cors = CORS(app)
@app.route('/publish', methods=['POST'])
@cross_origin()
def publish():
sender_username = flask.request.form['username']
chat_message = flask.request.form['message']
template = '<strong>{}</strong>: {}'
full_message = template.format(cgi.escape(sender_username),
cgi.escape(chat_message))
def m(subscriber_username):
if subscriber_username != sender_username:
return full_message
publisher.publish(m)
return ''
@app.route('/subscribe')
@cross_origin()
def subscribe():
username = flask.request.args.get('username')
return flask.Response(publisher.subscribe(properties=username),
content_type='text/event-stream')
@app.route('/')
@cross_origin()
def root():
return app.send_static_file('chat.html')
app.run(threaded=True)
这是此用法示例
@some_page.route('/sse', methods=['GET'])
@cross_origin()
def some_sse_page():
return flask.Response(publisher.subscribe(), content_type='text/event-stream')
并且此代码触发 SSE publisher.publish(json.dumps([{"success": True}]))
。
它基本上将json文件发送到前端
在前端,我们使用EventSource
来获取数据。
到目前为止,该系统已在本地完美运行。但是,当我们要在生产环境上运行此系统时,会引发以下错误:
从源访问“ https:// backendapp”上的资源 CORS政策已阻止“ https:// frontendapp”:否 请求中出现“ Access-Control-Allow-Origin”标头 从源访问'https:// backendapp / sse'上的资源 CORS政策已阻止“ https:// frontendapp”:否 请求中出现“ Access-Control-Allow-Origin”标头 资源。
我们仅针对SSE方法得到此错误。所有其他方法也可以在生产中完美运行。 我们尝试过的是
@cross_origin
作为装饰器,添加默认方法
对Flask主应用程序和 SSE 应用程序进行 CORS 配置。Allow-Access-Control-Origin
标头
(我认为这是行不通的,因为您无法覆盖默认值
标头)由于我们在数字海洋中使用了App平台,因此无法更改服务器配置。 那么我们如何在生产中使用SSE。预先感谢