Flask听POST请求

2024-05-07 01:03:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Flask来检索由javascript生成的坐标值。烧瓶代码:

from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash, jsonify


@app.route('/geo', methods= ['GET', 'POST'])
def geo():
    return render_template('geo.html')


@app.route('/postmethod', methods = ['GET', 'POST'])
def get_post_location():
    where = request.form['location']
    return where

控制台日志:

XHR finished loading: POST "http://127.0.0.1:5000/postmethod".

JAVASCRIPT

^{pr2}$

问题

我该如何听这个,以便将where发送到其他脚本?在

编辑:

全面回溯(在PJ和我的回答之后get_json(silent=False)

127.0.0.1 - - [19/Mar/2017 23:20:26] "GET /geo HTTP/1.1" 200 -
data: {}
127.0.0.1 - - [19/Mar/2017 23:20:27] "POST /postmethod HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/vitorpatalano/Documents/Code/Apps/App/app/app.py", line 134, in get_post_location
    where = data['location']
KeyError: 'location'

Tags: inpyselfappflaskrequestpackagesline
1条回答
网友
1楼 · 发布于 2024-05-07 01:03:17

这个问题与将数据从javascript发送到Flask的方式有关。编码的“位置”信息不是字符串值,而是一个对象或JSON。在

所以,您真正需要做的是在Javascript和Flask之间来回发送信息(JSON)

下面是如何实现这一点。您需要直接使用$.ajax()方法,而不是jQuery$.post()方法。在

更新:将我的代码更新为本地计算机上的完整工作示例。调用$.ajax()方法太早…需要将它移到对地理位置服务的调用范围内。在

关于链接和管理异步调用流的另一个问题是Promise库。在

Javascript/HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Geolocation</title>
    <meta charset="utf-8">
    <! jquery >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <style>
        #map {height: 100%;}
        html, body {height: 100%;margin: 0;padding: 0;}
    </style>
</head>
<body>
    <div id="map"></div>
    <script>

    function initMap() {
        var pos = {},
            map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: -34.397, lng: 150.644},
                zoom: 6
            }),
            infoWindow = new google.maps.InfoWindow({map: map});

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Smells like coffee...');
            map.setCenter(pos);

            $.ajax({
                type: "POST",
                url: "/postmethod",
                contentType: "application/json",
                data: JSON.stringify({location: pos}),
                dataType: "json",
                success: function(response) {
                    console.log(response);
                },
                error: function(err) {
                    console.log(err);
                }
            });

            }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
            });
        } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
        }
    }

    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
    }

    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBr8V0XkaNFYkNXcP6eJc76b6YutvizwNw&callback=initMap">
    </script>
</body>
</html>

在Flask中,现在可以使用get_json()方法,该方法将在python中重现用javascript编码的数据结构。您应该使用Flaskjsonify()返回对javascript调用的响应。在

Python:

^{pr2}$

相关问题 更多 >