python - 如何让 Swift HTTP POST 命中 Flask 服务器?

标签 python ios rest swift

我正在尝试将一些数据发布到 Flask 服务器,其代码如下:

@app.route('/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        abort(400)

    task = {
        'title': request.json['title'],
        'description': request.json.get('description', ""),
    }

    return jsonify({'task' : task}), 201

当我运行它时,它工作正常,我可以使用 curl 成功发出 POST 请求,上面的后端有预期的行为,命令行有预期的返回值。但是,我想使用 Swift 向该服务器发帖,但遇到了麻烦。我已经按照详细说明此行为 here 的教程进行操作。特别是,我将代码放在我的 AppDelegate.swift 中,以便在应用程序启动后立即执行。完整代码在发布的链接中,但为了引用,我也在下面发布了它:

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login"))
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var params = ["username":"jameson", "password":"password"] as Dictionary<String, String>

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Body: \(strData)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr)'")
         }
         else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                var success = parseJSON["success"] as? Int
                println("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")
            }
        }
    })

    task.resume()
    return true
}

但是,当我启动这个应用程序时,我的 xcode 中记录了以下内容

Response: <NSHTTPURLResponse: 0x7fc4dae218a0> { URL: http://localhost:5000/task } { status code: 404, headers {
    "Content-Length" = 26;
    "Content-Type" = "application/json";
    Date = "Tue, 07 Oct 2014 19:22:57 GMT";
    Server = "Werkzeug/0.9.6 Python/2.7.5";
} }
Body: {
  "error": "Not found"
}
Succes: nil

我一直在处理这个问题并修改输入,后端似乎很好,但我想知道这个前端有什么问题,不幸的是,Swift 文档目前在这一点上还没有实际意义并且似乎是目前唯一适用于 RESTful API 调用的解决方案。

最佳答案

你的 flask 路由是 '/tasks' 并且你正试图发布到 http://localhost:5000/task。这是错字,还是您是复数失败的受害者?

关于python - 如何让 Swift HTTP POST 命中 Flask 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26244109/

相关文章:

ios - UITableView 在显示图像 Swift 时滞后

ios - 移动 map View 后如何保持用户位置居中

java - 如何对 GET 请求中返回的数据进行分页

.net - 在多个.NET应用之间进行通信的最有效方法

python - 将自定义滚动函数应用于具有日期时间索引的 pandas 数据框

python - 如何用 numpy 在 Cython 中表示 inf 或 -inf?

python - 如何使用 pandas 高效地执行行操作?

Python:在 pyppeteer 中保持打开浏览器并创建 CDPSession

ios - 使用未声明的标识符 searchBar

javascript - 仅当 Angular 从资源对象检索数据时才选择选项元素