Python返回以获取JS函数

时间:2019-08-06 13:01:54

标签: javascript python flask fetch

我有一个JS调用Python函数。这是JS调用:

fetch('/ws/invoice/checkDoublon', {
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json'
    },
    body    : JSON.stringify({
        'invoiceNumber' : invoiceNumber.val(),
        'vatNumber'     : vatNumber.val(),
        'id'            : $('#pdfId').val()
    })
}).then(function(response) {
    console.log(response)
});

我的Python代码是这样的(我正在使用Flask):

@bp.route('/ws/invoice/checkDoublon',  methods=['POST'])
@login_required
def checkInvoiceDoublon():
if request.method == 'POST':
    data            = request.get_json()
    invoiceNumber   = data['invoiceNumber']
    vatNumber       = data['vatNumber']
    invoiceId       = data['id']

    _vars   = init()
    _db     = _vars[0]
    _cfg    = _vars[1].cfg

    # Check if there is already an invoice with the same vat_number and invoice number. If so, verify the rowid to avoid detection of the facture currently processing
    res = _db.select({
        'select'    : ['rowid, count(*) as nbInvoice'],
        'table'     : ['invoices'],
        'where'     : ['supplier_VAT = ?', 'invoiceNumber = ?'],
        'data'      : [vatNumber, invoiceNumber]
    })[0]

    if res['nbInvoice'] == 1 and res['rowid'] != invoiceId or res['nbInvoice'] > 1 :
         return 'Duplicate', 200
    else:
         return 'Not duplicate', 200

所有这些工作正常,但是console.log(response)根本没有显示我想要的来自Python的自定义返回“不重复”或“重复”。它仅显示OK为response.statusText,因为我返回了HTTP代码200

如何在JS代码上检索自定义消息?如果使用fetch而不是ajax,效果可能会很好

预先感谢

3 个答案:

答案 0 :(得分:2)

这是因为fetch返回了一个Response,您需要在其中调用.text().json()这两个返回包含您的数据的Promise对象或字符串,具体取决于您选择的对象

您的js看起来像这样

fetch('/ws/invoice/checkDoublon', {
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json'
    },
    body : JSON.stringify({
        'invoiceNumber' : invoiceNumber.val(),
        'vatNumber'     : vatNumber.val(),
        'id'            : $('#pdfId').val()
    })
  }).then(function(response) {
    response.json().then(function(data) {
      // here data is the object containing your datas
    })
    // or
    response.text().then(function(value) {
      // here value is the string returned by your python script
      let data = JSON.parse(value) // this line transform the string into the same object you get by calling .json() above
    })
});

答案 1 :(得分:0)

您需要从Flask后端返回有效的JSON响应

答案 2 :(得分:0)