【问题标题】:Is HTTP Post blocked by Cloud9?HTTP Post 是否被 Cloud9 阻止?
【发布时间】:2014-12-15 17:39:51
【问题描述】:

我一直在 Cloud9 ide 上使用 Python/Flask。到目前为止很有趣。但是当我尝试向我的测试项目添加 http 帖子时,Flask 返回 403 或 500。据我所知,当我附加数据或发送 POST 方法时,“请求”对象为无。但这没有任何意义。这很简单,据我所知应该可以工作。这是蟒蛇:

from flask import Flask, jsonify, abort, request
@app.route('/test', methods = ['POST'])
def post():
    print ('started')
    print request
    if request.method == 'POST':
        something = request.get_json()
        print something

Flask 运行正常。我可以点击 GET url,返回数据就好了。当我登陆“打印请求”时出现错误,因为请求为无。

谢谢,

【问题讨论】:

  • 您如何将数据附加到帖子中?你能举个例子吗?
  • 我正在使用 Postman 进行测试。我用表单数据和原始数据尝试过,但请求总是无。

标签: python flask cloud9-ide


【解决方案1】:

这里有两个问题:

  • 您收到 500 错误

  • “某事”总是无

第一个问题是因为你没有从你的路由函数返回任何东西。

127.0.0.1 - - [15/Dec/2014 15:08:59] "POST /test HTTP/1.1" 500 -
Traceback (most recent call last):
  ...snip...
  ValueError: View function did not return a response

您可以通过在函数末尾添加 return 语句来解决此问题。不要忘记它必须是一个字符串。

@app.route('/hi', methods = ['POST'])
def post():
    return "Hello, World!"

第二个问题不是它看起来的那样。我怀疑该对象不是无,但返回字符串表示的函数返回无,所以这就是打印的内容。试试print type(request) 看看它的实际效果。

我认为您想要访问的是form 字段。这是一个完整的例子:

from flask import Flask, request

app = Flask(__name__) 

@app.route('/test', methods = ['POST'])
def post():
    print type(request)
    if request.method == 'POST':
        print request.form
    return str(request.form)

app.run(debug=True)

【讨论】:

  • 这里的两个陷阱是“必须返回一个字符串”。我确定它已记录在案,但我只是没有看到它。 response.get_json() 没有做任何事情。但是,是的,我想看到的确实是 request.form。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多