首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >415异常Cherrypy webservice

415异常Cherrypy webservice
EN

Stack Overflow用户
提问于 2015-01-20 16:04:58
回答 2查看 3K关注 0票数 6

我正在尝试构建一个Cherrypy/。我已经花了一整天的时间研究如何使跨域ajax请求成为可能。终于起作用了,但现在我有下一期了。我想我已经知道解决方案了,但我不知道如何实现它。问题是,当我发送ajax请求时,Cherrypy服务器响应如下:

代码语言:javascript
复制
415 Unsupported Media Type

Expected an entity of content type application/json, text/javascript

Traceback (most recent call last):  File "/Library/Python/2.7/site-packages/cherrypy/_cprequest.py", line 663, in respond    self.body.process()  File "/Library/Python/2.7/site-packages/cherrypy/_cpreqbody.py", line 996, in process    super(RequestBody, self).process()  File "/Library/Python/2.7/site-packages/cherrypy/_cpreqbody.py", line 538, in process    self.default_proc()  File "/Library/Python/2.7/site-packages/cherrypy/_cperror.py", line 411, in __call__    raise selfHTTPError: (415, u'Expected an entity of content type application/json, text/javascript')    

我找到并尝试测试的解决方案是将这一行添加到配置中:

代码语言:javascript
复制
'tools.json_in.force': False

因此,我尝试在下面的代码中实现它:

代码语言:javascript
复制
import cherrypy
import json
import sys

class RelatedDocuments:

def index(self):
    return "Hello World!"

@cherrypy.tools.json_out()
@cherrypy.tools.json_in()
def findRelated(self, **raw):
    #Get JSON message form request
    request = cherrypy.request.json
    result = []

    #SOME CODE...

    return result;

# Expose the index method through the web. CherryPy will never
# publish methods that don't have the exposed attribute set to True.
index.exposed = True
findRelated.exposed = True

def CORS():
    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'webserver.conf')
config = {
    'global': {
        'server.socket_host':'127.0.0.1',
        'server.socket_port': 8080,
        'log.error_file' : 'Web.log',
        'log.access_file' : 'Access.log'
    },
    '/': {
        'tools.CORS.on': True
    }
}

if __name__ == '__main__':
    cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)

    cherrypy.quickstart(RelatedDocuments(),config=config)

我在tools.CORS.on行下添加了配置行,但这不起作用。接下来我尝试了这个:

代码语言:javascript
复制
cherrypy.config.update({
    'tools.json_in.force': False,
});

eiter..next没有工作,我试图在findRelated方法之上实现这个方法:

代码语言:javascript
复制
@cherrypy.config(**{'tools.json_in.force': False})

所有的实现都给了我500个错误,如果有人能帮我的话,我真的很感激。提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-21 11:08:37

我意识到这个问题实际上是关于http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0的。CORS 规范定义简单CORS请求的以下条件:

  • 方法:GETHEADPOST
  • 标题:AcceptAccept-LanguageContent-LanguageContent-Type
  • Cotent-type头值:application/x-www-form-urlencodedmultipart/form-datatext/plain

否则,CORS请求并不简单,并在实际请求之前使用飞行前选项请求,以确保其符合要求。这是好的CORS如何-to

因此,如果您想保持简单,您可能想要恢复到正常的application/x-www-form-urlencoded。否则,您需要正确处理飞行前请求。下面是工作示例(不要忘记添加localhost别名)。

代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Add localhost alias, `proxy` , in /etc/hosts.
'''


import cherrypy


config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}


def cors():
  if cherrypy.request.method == 'OPTIONS':
    # preflign request 
    # see http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
    cherrypy.response.headers['Access-Control-Allow-Methods'] = 'POST'
    cherrypy.response.headers['Access-Control-Allow-Headers'] = 'content-type'
    cherrypy.response.headers['Access-Control-Allow-Origin']  = '*'
    # tell CherryPy no avoid normal handler
    return True
  else:
    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'

cherrypy.tools.cors = cherrypy._cptools.HandlerTool(cors)


class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <head>
      <meta content='text/html; charset=utf-8' http-equiv='content-type'>
      <title>CORS AJAX JSON request</title>
      <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
      <script type='text/javascript'>
        $(document).ready(function()
        {
          $('button').on('click', function()
          {
            $.ajax({
              'type'        : 'POST',
              'dataType'    : 'JSON',
              'contentType' : 'application/json',
              'url'         : 'http://proxy:8080/endpoint',
              'data'        : JSON.stringify({'foo': 'bar'}),
              'success'     : function(response)
              {
                console.log(response);  
              }
            });
          })
        });
      </script>
      </head>
      <body>
        <button>make request</button>
      </body>
      </html>
    '''

  @cherrypy.expose
  @cherrypy.config(**{'tools.cors.on': True})
  @cherrypy.tools.json_in()
  @cherrypy.tools.json_out()
  def endpoint(self):
    data = cherrypy.request.json
    return data.items()


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)
票数 4
EN

Stack Overflow用户

发布于 2015-01-20 18:32:14

一般来说,如果你选择了一个工具,那么你最好使用它,而不是对抗它。CherryPy告诉您,对于JSON输入,它希望请求具有application/jsontext/javascript内容类型。

这是cherrypy.lib.jsontools.json_in的代码

代码语言:javascript
复制
def json_in(content_type=[ntou('application/json'), ntou('text/javascript')],
            force=True, debug=False, processor=json_processor):

    request = cherrypy.serving.request
    if isinstance(content_type, basestring):
        content_type = [content_type]

    if force:
        if debug:
            cherrypy.log('Removing body processors %s' %
                         repr(request.body.processors.keys()), 'TOOLS.JSON_IN')
        request.body.processors.clear()
        request.body.default_proc = cherrypy.HTTPError(
            415, 'Expected an entity of content type %s' %
            ', '.join(content_type))

    for ct in content_type:
        if debug:
            cherrypy.log('Adding body processor for %s' % ct, 'TOOLS.JSON_IN')
        request.body.processors[ct] = processor

force除了删除现有的主体处理器之外,什么也不做。如果将force设置为False,则需要告诉CherryPy如何处理发送给它的请求体。

或者,更好的方法是使用CherryPy并告诉它正确的内容类型。对于jQuery,它非常简单:

代码语言:javascript
复制
 jQuery.ajax({
    'type'        : 'POST',
    'dataType'    : 'JSON',
    'contentType' : 'application/json',
    'url'         : '/findRelated',
    'data'        : JSON.stringify({'foo': 'bar'})
 });
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28049898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档