使用服务器发送的事件访问Flask端点时出现CORS错误

如何解决使用服务器发送的事件访问Flask端点时出现CORS错误

我们的项目有两个应用程序。一个是用于前端的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,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__,static_folder='static',static_url_path='')
        
    app.config['CORS_HEADERS'] = 'Content-Type'
    app.config['CORS_METHODS'] = ["GET","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 配置。
  • 通过EventSourc发送Allow-Access-Control-Origin标头 (我认为这是行不通的,因为您无法覆盖默认值 标头)

由于我们在数字海洋中使用了App平台,因此无法更改服务器配置。 那么我们如何在生产中使用SSE。预先感谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-