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



我是Flask框架的新手。我制作了一个应用程序,应该提供一些NLP-NER结果。当我使用 GET 卷曲时,该应用程序运行良好,但在执行此操作时,我必须对 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配合使用正常。请帮帮我解决这个问题。

您应该知道数据将以urlencoding 形式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."

同样无处不在。

最新更新