我正在尝试运行一个简单的Flask API,但无法正常工作。我对Python的经验不是很丰富,因此发现错误并解决它非常具有挑战性。如果有人可以提供帮助,我将不胜感激。
系统设置为:
这些是要求:
@Document(collection = Constants.SLOTS)
@Entity
public class FilledSlot extends AbstractMongoEntity {
private String slotKey;
private String slotValue;
public FilledSlot(){
}
@PersistenceConstructor
public FilledSlot(String slotKey, String slotValue){
setSlotKey(slotKey);
setSlotValue(slotValue);
}
public String getSlotKey() {
return slotKey;
}
public void setSlotKey(String slotKey) {
this.slotKey = slotKey;
}
public String getSlotValue() {
return slotValue;
}
public void setSlotValue(String slotValue) {
this.slotValue = slotValue;
}
@Override
public String toString() {
return "FilledSlot{" +
"slotKey='" + slotKey + '\'' +
", slotValue='" + slotValue + '\'' +
", _id='" + _id + '\'' +
'}';
}
}
我的项目结构如下:
$ pip freeze
ansimarkup==1.4.0
asn1crypto==0.24.0
better-exceptions-fork==0.2.1.post6
certifi==2019.3.9
cffi==1.12.3
chardet==3.0.4
Click==7.0
colorama==0.4.1
cryptography==2.7
Flask==1.0.3
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10.1
loguru==0.2.5
MarkupSafe==1.1.1
pycparser==2.19
Pygments==2.4.2
pyOpenSSL==19.0.0
PySocks==1.7.0
requests==2.22.0
six==1.12.0
urllib3==1.24.2
Werkzeug==0.15.4
这是app.py代码:
├── statsapi
│ ├── data_store.py
├── app.py
├── client.py
├── requirements.txt
data_store.py代码:
#!/usr/bin/env python
from flask import Flask, request, jsonify
from loguru import logger
from statsapi import data_store
app = Flask(__name__)
# Creating an endpoint
@app.route("/data", methods=["POST"])
def save_data():
# setting log for this action
logger.info(f"Saving data...")
# transform content requisition to json
content = request.get_json()
# save in a module just the "data" field
# The uuid of the data
uuid = data_store.save(content["data"])
# set log for las action
logger.info(f"Data saved with UUID `{uuid}` successfully")
# define information to be returned
return jsonify({"status": "success",
"message": "data saved successfully",
"uuid": uuid})
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
和client.py代码:
#!/usr/bin/env python
from uuid import uuid4
# Create a dictionary to keep things in memory
_in_memory_storage = dict()
# Save received data in memory giving an uuid
def save(data):
data_uuid = uuid4()
_in_memory_storage[data_uuid] = data
return data_uuid
client.py应该向API发送一些数据,但是在调用时它会返回以下长错误消息:
#!/usr/bin/env python
import requests
def send(data):
response = requests.post("http://localhost:5000/data", json={"data": data})
print(response.json())
def main():
send([1, 2, 3, 4])
if __name__ == "__main__":
main()
正如我所说,我距离成为一名Python专家还很遥远,因此我将非常感谢您的帮助。
答案 0 :(得分:0)
我认为这可能是您的端口已被其他应用程序提供服务,请尝试更改烧瓶端口。
我在本地成功使用了你的代码
尝试这样的事情
main.py
import data_store
from flask import Flask, request, jsonify
app = Flask(__name__)
# Creating an endpoint
@app.route("/data", methods=["POST"])
def save_data():
# setting log for this action
print(f"Saving data...")
# transform content requisition to json
content = request.get_json()
# save in a module just the "data" field
# The uuid of the data
uuid = data_store.save(content["data"])
# set log for las action
print(f"Data saved with UUID `{uuid}` successfully")
# define information to be returned
return jsonify({"status": "success",
"message": "data saved successfully",
"uuid": uuid})
if __name__ == "__main__":
app.run(port=8000)
data_store.py
from uuid import uuid4
# Create a dictionary to keep things in memory
_in_memory_storage = dict()
# Save received data in memory giving an uuid
def save(data):
data_uuid = uuid4()
_in_memory_storage[data_uuid] = data
print(f"Cached value => {_in_memory_storage}")
return data_uuid
client.py
import requests
def send(data):
response = requests.post("http://localhost:8000/data", json={"data": data})
print(response.json())
def main():
send([1, 2, 3, 4])
if __name__ == "__main__":
main()
当它像这样测试成功
→ python client.py
{'message': 'data saved successfully', 'status': 'success', 'uuid': '050b02c2-e67e-44f7-b6c9-450106d8b40e'}
烧瓶记录器
→ python main.py
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
Saving data...
Cached value => {UUID('050b02c2-e67e-44f7-b6c9-450106d8b40e'): [1, 2, 3, 4]}
Data saved with UUID `050b02c2-e67e-44f7-b6c9-450106d8b40e` successfully
127.0.0.1 - - [06/Jun/2021 12:51:35] "POST /data HTTP/1.1" 200 -
答案 1 :(得分:0)
可能与问题不完全相关,但它可能会帮助面临类似问题的人。
我遇到了类似的问题,但就我而言,这是因为 docker 容器。当容器 #1 使用请求 api 连接到容器 #2 时,它失败了,因为两个容器都不在一个网络中。
所以我将我的 docker-compose 文件修改为
networks:
default:
external: true
name: <network_name>
使用请求连接时,请确保提前创建docker网络并将host修改为容器#2的docker服务名称。
所以使用 http://<docker_service_name>:8000/api
而不是 http://127.0.0.1:8000/api