【问题标题】:Flask: request method not picking up the datetime value from web form via AJAXFlask:请求方法不通过 AJAX 从 Web 表单中获取日期时间值
【发布时间】:2019-03-21 16:30:51
【问题描述】:

我正在创建一个 Web 表单,其中一个两个字段是 datetime 数据类型。然后我通过 AJAX 将此表单数据传递给服务器。下面是代码 JQuery sn-p。

$(document).ready(function(){
$('#btnSubmit').click(function(){
var start = $("#start").val();
var end = $("#end").val();
$.ajax({
        type:'POST',
        url: '/interuption',

        data: $('#formint').serializeArray(),
        success: function(response){
                alert(response);
                },
        error: function(error){
                console.log(error);
            }
    });

});
});

关联的HTML如下:

<form id = "formint" class="myForm" method= "post" action="/interuption">
<th>
<label>Start Time Stamp
<input id = "start" type="datetime-local" name="start_timestamp" required>
</label>
</th>

<th>
<label>End Time Stamp
<input id ="end" type="datetime-local" name="end_timestamp" required>
</label>
</th>
</form>

在服务器端,我使用的是 Flask。我正在使用request.form.get 方法来检索datetime。然后我试图将它推送到 MS SQL Server。下面是 Python 代码 sn-ps。

cnxn = pyodbc.connect(#credentials)
cursor=cnxn.cursor()
query_insert = "INSERT INTO test.dbo.testFeed(start_timestamp,end_timestamp) 
VALUES (?,?)"

@app.route('/interuption',methods = ['GET','POST'])
def interuption():
    try:
        data_1 = datetime.datetime.strptime(request.form.get('start'),%Y-%m-%d %H-%M-%S')
        data_2 = datetime.datetime.strptime(request.form.get('end'),%Y-%m-%d %H-%M-%S')
        if data_1 and data_2:
            cursor.execute(query_insert,(data_1,data_2))
            cnxn.commit()
            cnxn.close()
            return json.dumps({'status':'OK'})
        else:
            return json.dumps({'error':'data has not been insterted!!'})
     except Exception as e:
         return json.dumps({'excp':str(e)})
    return render_template('form.html')

当我运行上述代码时,我收到如下错误

{"excp": "time data 'None' does not match format '%Y-%m-%d %H-%M-%S'"}

显然request.form.get 没有从网络表单中获取任何价值。

我怎样才能摆脱这个?

【问题讨论】:

    标签: ajax datetime flask


    【解决方案1】:

    当将表单数据作为键值对发送到服务器时,键将是&lt;input&gt;(不是id)的name attr,因此您应该尝试使用request.form.get('start_timestamp')request.form.get('end_timestamp')

    【讨论】:

    • 谢谢格雷。我还有一个疑问,request.form['field']request.form.get['field']有什么区别
    • 这几乎就像您使用 dict 所做的一样。如果您传递一个不存在的密钥,dict['badkey'] 将抛出一个 KeyError 异常(在 Flask 中,这将是一个 400 Bad Request 响应),但 dict.get('badkey') 将返回 None。此外,您可以使用get() 设置默认值(例如dict.get('key', 'default value'))。
    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    相关资源
    最近更新 更多