【问题标题】:CURL request is not capturing data in Flask app when passed request using POST使用 POST 传递请求时,CURL 请求未在 Flask 应用程序中捕获数据
【发布时间】:2020-06-03 19:32:34
【问题描述】:

我是 Flask 框架的新手。我制作了一个应用程序,它可以提供一些 NLP-NER 结果。当我使用 GET 进行 CURL 时,该应用程序可以正常工作,但是在执行此操作时,我必须对需要一些时间的 URL 进行编码。我想使用 POST 并将数据发送到应用程序。我尝试了提到的各种方法,但无法找到解决方案。这是我使用 cURL 发送的内容。

curl -X POST http://localhost:5000/ner -d "text=I am avinash"

错误:未提供文本字段。请指定要处理的文本。(基础)Avinashs-MBP:NER avinash.chourasiya$

这是我的烧瓶应用:

import spacy, sys, json
from spacy import displacy
import flask
from flask import request

nlp = spacy.load('en_core_web_sm')
app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/',methods=['POST'])
def home():
    return "<h1>Spacy NLP Demo</h1><p>This site is a prototype API for Spacy NLP</p>"

@app.route('/ner', methods=['POST'])
def ner():
    print(request.args,"The post is working, but it is not reading the requests")
    if 'text' in request.args:
         text = request.args['text']
    else:
         return "Error: No text field provided. Please specify text to process."

    #Limit the text size to 10K characters for safety
    print("text len: ", len(text))
    text = request.args['text']
    truncated_text = text[:10000]
    doc = nlp(truncated_text)

    ents = []
    for sent in doc.sents:
        for span in sent.ents:
            ent = {"verbatim": span.text, "ent_type": span.label_, "hit_span_start": span.start_char, "hit_span_end": span.end_char }
            ents.append(ent)


    return json.dumps(ents)
 app.run()

这个应用程序与 GET 一起工作得很好。请帮帮我。

【问题讨论】:

    标签: python curl flask request


    【解决方案1】:

    您应该知道数据将从curlurlencoded 格式 发送。因此,要从该 POST 请求中获取数据,您必须使用 request.form 而不是 request.args

    所以,ner() 方法应该是这样的:

    @app.route('/ner', methods=['POST'])
    def ner():
        print(request.form,"The post is working, but it is not reading the requests")
        if 'text' in request.form:
            text = request.form['text']
        else:
            return "Error: No text field provided. Please specify text to process."
    
        #Limit the text size to 10K characters for safety
        print("text len: ", len(text))
        text = request.form['text']
        ...
        ...
    

    【讨论】:

      【解决方案2】:

      您正在执行post 并期待get 格式的数据。

      你需要从form获取数据。

          text = request.form.get("text")
          if not text:
              return "Error: No text field provided. Please specify text to process."
      

      到处都是。

      【讨论】:

        猜你喜欢
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多