【问题标题】:Accessing HTML form data inside Python/Flask [duplicate]在 Python/Flask 中访问 HTML 表单数据 [重复]
【发布时间】:2019-04-27 14:44:45
【问题描述】:

我正在与一个使用 Flask 的项目的合作伙伴合作,该项目需要将一个(可变)JSON 对象从 HTML 文件传递​​到 app.py 文件,从而查询我们的数据库。我的伙伴使用文本输入字段成功地编写了一个版本,将检索到的记录打印到控制台。但是,我们在实现下拉菜单时已经进行了相当多的更改,但我们无法让事情再次正常工作。

就目前而言,我可以 ping app.py 文件并返回一个虚拟响应(例如,将“hello”打印到控制台),但我似乎无法访问我通过传递的实际数据JSON 对象。 (我什至还没有弄乱数据库——只是试图操纵对象。)最近,我得到一个 GET (url) 500 (INTERNAL SERVER ERROR),当我使用 POST 方法时也是如此。

我已经阅读了很多关于类似问题的讨论(hereherehere,仅举几例)并尝试了几种不同的方法。我想我一定是在表单上做错了,而且解决方案似乎应该相当简单,但我没有太多运气弄明白。

这里是相关的 HTML 和 Javscript:

<!-- establish the Flask form which will send the selected airports to the Python code and database -->
<form name="selected_route" id="selected_route" method="GET">

    <p>Departure</p>
    <p>
        <!-- dropdown menu for departure state -->
        <select name="departure_state" id="departure_state" onChange="changeDepAirport(this.value);">
        </select>

        <!-- dropdown menu for departure airport, generated by choice of state -->
        <select name="departure_airport" id="departure_airport">
        <option value="" disabled selected>Select an airport</option>
        </select>
    </p>

    <p>Arrival</p>
    <p>
        <!-- dropdown menu for arrival state -->
        <select name="arrival_state" id="arrival_state" onChange="changeArrivAirport(this.value);">
        </select>

        <!-- dropdown menu for arrival airport, generated by choice of state -->
        <select name="arrival_airport" id="arrival_airport">
        <option value="" disabled selected>Select an airport</option>
        </select>
    </p>

    <!-- submit button for the departure and arrival parameters, which will visualize the data for that route -->
    <p>
        <button name="go" id="go" type="submit" onclick="retrieveRouteData()">Go!</button>
    </p>
</form>

<script>
// function to retrieve the data for the selected route
function retrieveRouteData() {
    departure_airport = document.getElementById("departure_airport").value;
    arrival_airport = document.getElementById("arrival_airport").value;
    route_object = { "departure_airport" : departure_airport,
                        "arrival_airport" : arrival_airport};
    console.log(route_object);

    testAj(function(output){
        console.log("1")
        console.log(output)
    });

    function testAj(handleData) {
        $(document).ready(function() {
            $('form').submit(function (e) {
                var url = "{{ url_for('test') }}"; // send the data here
                $.ajax({
                    type: "GET",
                    url: url,
                    data: route_object,
                    success: function (data) {
                        console.log(data)  // display the returned data in the console.
                    }
                });
                e.preventDefault(); // block the traditional submission of the form.
            });
        });
    };
 };

 generateStateLists(); // calls the function to populate the initial dropdowns

 </script>

这里是 Python 代码:

from flask import Flask, jsonify, render_template, redirect, url_for, g, Response, request
from flask_cors import CORS
from flask_wtf import FlaskForm
from wtforms import StringField
from pymongo import MongoClient
from bson import json_util
from bson.json_util import dumps
import json
import os

app = Flask(__name__)
app.secret_key = ####

@app.route('/')
def home():
    print("come to home")
    return render_template('home.html')

# send json file
@app.route('/send')
def send():
    return "<a href=%s>file</a>" % url_for('static', filename='StateCityCode.json')


@app.route('/test', methods=['GET'])
def test():
    data = request.get_json()
    return data

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)

提前感谢您的帮助!

【问题讨论】:

  • 使用request.get_json(force=True)强制flask将请求数据解析为json,而不考虑内容类型

标签: javascript python jquery ajax flask


【解决方案1】:

在发送和设置调用的 json 标头之前尝试对 json 数据进行字符串化,如下所示:

$.ajax({
                    type: "POST",
                    dataType: "json",
                    url: url,
                    data: JSON.stringify(route_object),
                    contentType: "application/json;charset=utf-8"
                    success: function (data) {
                        console.log(data)  // display the returned data in the console.
                    }
                });

【讨论】:

  • 这成功了!非常感谢。
【解决方案2】:

使用flask,您可以轻松访问HTML 表单元素。查看以下代码。

HTML:

<form action="" method="POST">
    <label> Username </label>
    <input type="text" name="username" value={{request.form.username}}>
    <label> Password </label>
    <input type=”"password" name="password" value={{request.form.password}}>

    <button type=”submit”> Submit </button>
</form>

Python:

def login()
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # code that uses the data you've got
        # in our case, checking if the user exists
        # and logs them in, if not redirect to sign up
    else:
        # an exception

基本上,您可以通过 request.form 访问应该连接到数据库的元素。

编辑: 如果要直接在 Python 中搜索表单元素,可以使用以下代码:

import cgi
form = cgi.FieldStorage()
searchterm =  form.getvalue('username')
searchterm =  form.getvalue('password')

【讨论】:

  • 这对我来说很有意义,我之前曾根据我发现的另一个讨论尝试过这种语法,但仍然没有运气。下面的解决方案对我有用,但如果其他人遇到这个问题,这个解决方案似乎也很有用。感谢您的帮助!
【解决方案3】:

我认为问题出现在您的代码中的以下行:

var url = "{{ url_for('test') }}"; // send the data here

为了使用 Jinja 将数据传递给 javascript,您可能需要对数据进行转义。见here

尝试在你的javascript代码中打印出url的值,看看url是否正确

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多