【问题标题】:Cherrypy handling "no 'Access-Control-Allow-Origin' header is present" errorCherrypy 处理“不存在 'Access-Control-Allow-Origin' 标头”错误
【发布时间】:2014-11-02 05:12:36
【问题描述】:

周末 chrome 似乎已经更新,现在阻止了我的跨域请求:

我有一台服务器、两个域和一个需要在另一台上加载的共享网络图标字体。我宁愿不强迫cherrypy知道它服务于哪个域(镜像或主域),因为为此我不妨克隆所有代码。

我的 chrome console.log 错误信息是:

Font from origin 'http://djotjog.com' has been blocked from loading by Cross-Origin Resource Sharing policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://storylearning.org' is therefore not allowed access. 

在cherrypy中,我尝试启用此功能,但文档很粗略。这是我尝试过的:

class root:
def stest(self, **kw):
    cherrypy.response.headers['Content-Type'] = 'text/html'
    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
    html = some_function()
    return html

def CORS():
    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" 
if __name__=="__main__":
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)  

cherrypy.config.update({
'environment': 'production',
'log.screen': False,
'log.error_file':'cperror.log',
'server.socket_host': '127.0.0.1',
'server.socket_port': 15722,
'server.thread_pool': 2,
'server.thread_pool_max': 2

那么在cherrypy上处理跨域请求的正确方式是什么?

【问题讨论】:

    标签: python-2.7 cors cherrypy cross-domain-policy


    【解决方案1】:

    首先,如果你说它是一面镜子,为什么会出现问题,这是很不清楚的。如果它真的是一面镜子,那么您只需要使用相对 URL (/path/to/your/font.otf) 来引用您的字体文件。

    其次,至少在 FF 和 IE 中,网络字体自 2010 年起就受到 CORS 的约束(请参阅 bugreport)。这种行为实际上是设计使然(参见spec)。因此,如果您曾经在这些浏览器中测试过您的网站,您应该会看到同样的结果。

    第三,如果您说的是部分镜像,那么以下内容应该可以满足您的需求。

    app.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    
    import os
    
    import cherrypy
    from cherrypy.lib import static
    
    
    path   = os.path.abspath(os.path.dirname(__file__))
    config = {
      'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 8
      },
      '/font' : {
        'tools.corsstaticdir.on'  : True,
        'tools.corsstaticdir.dir' : os.path.join(path, 'font'),
        # This is a workaround for CherryPy flaw  where they set ``section`` 
        # tool config variable in ``cherrypy._cpdispatch.Dispatcher.set_conf`` 
        # exclusivety for ``staticdir`` tool (http://goo.gl/EGIIvA).
        'tools.corsstaticdir.section' : '/font',    
      }  
    }
    
    
    def corsstaticdir(section, dir, root = '', match = '', content_types = None, index = '', debug = False):
      cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
      return static.staticdir(section, dir, root, match, content_types, index, debug)
    
    cherrypy.tools.corsstaticdir = cherrypy._cptools.HandlerTool(corsstaticdir)
    
    
    class App:
    
      @cherrypy.expose
      def index(self):
        return static.serve_file(os.path.join(path, 'index.html')) 
    
    
    if __name__ == '__main__':
      cherrypy.quickstart(App(), '/', config)
    

    index.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv='content-type' content='text/html; charset=utf-8'/>
    <title>CORS font</title>
    <style type='text/css'>
      @font-face {
        font-family : YourFontRegular;
        font-weight : normal;
        font-style  : normal;      
        src         : url('http://anotherdomain/font/Quicksand-Regular.otf');
      }
      p {
        font-family : YourFontRegular;
      }
    </style>
    </head>
    <body>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam placerat lacinia tortor. Nulla viverra, dolor nec malesuada congue, lectus quam dictum tellus, at malesuada nisl tortor quis ligula. Donec aliquam id arcu quis consectetur. Sed vitae turpis quis metus consequat vulputate.</p>
    </body>
    </html>
    

    【讨论】:

    • 谢谢。由于规范说,“字体通常不会跨域加载,除非作者特别采取措施允许跨域加载。” -- 我需要知道如何启用它。我在两个域上有两个cherrypy 实例,以及一个在一个域上有字体文件的静态服务器。您建议我将另一个域设置为将该静态服务器作为相同的相对链接以避免这种情况,对吗?这可能很棘手。相对地图不相同。
    • 我已经写过,如果这两个域不是全镜像,至少你说的相对路径不一样是对的,就用工具吧,corsstaticdir,我贡献了.将字体放在一个目录中,配置工具以使用该目录,就可以开始了。
    • 我稍后会试一试。现在我已经修复了要匹配的相对路径,所以我可以只使用相对链接,并且现在修复了 CORS 错误消息。花费的时间少了很多(尝试启用 CRS 一个小时后 5 分钟)
    猜你喜欢
    • 2015-01-24
    • 2017-11-30
    • 2016-11-06
    • 1970-01-01
    • 2014-01-20
    • 2018-10-28
    • 2019-08-15
    • 2017-02-21
    • 2015-09-28
    相关资源
    最近更新 更多