当使用POST传递请求时,CURL请求未在Flask应用程序中捕获数据

2024-04-26 17:39:35 发布

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

我是Flask框架的新手。我已经做了一个应用程序,它应该提供一些NLP-NER结果。当我使用GET时,这个应用程序可以很好地运行,但是在执行此操作时,我必须对URL进行编码,这需要一些时间。我想使用POST并将数据发送到应用程序。我尝试过上述各种方法,但找不到解决办法。这就是我使用cURL发送的内容

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

错误:未提供文本字段。请指定要处理的文本。(基本)avinash 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配合使用效果良好。请帮我解决这个问题


Tags: textimportapp应用程序flaskfornlpspacy
2条回答

您应该知道数据将以URL编码的形式从curl发送。因此,要从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']
    ...
    ...

您正在执行post操作,需要get格式的数据

您需要从form获取数据

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

到处都是这样

相关问题 更多 >