[英]How to post JSON data from JavaScript frontend to FastAPI backend?
[英]How to return json from FastAPI (Backend) with websocket to vue (Frontend)
我有一个应用程序,其中前端是通过 Vue,后端是 FastAPI,通过 websocket 进行通信。
目前,前端允许用户输入一个术语,该术语被发送到后端以生成自动完成,并且还对返回 json 的 URL 执行搜索。其中,我将这个 json 保存在前端文件夹中。 之后,后端将相关术语的自动完成数据返回给前端。 前端显示 aucomplete 以及 json 数据。
但是,稍微研究了一下,发现有一种方法可以将请求url返回的json发送给Vue(前端),而不必保存在本地,避免了报错不允许执行更多不止一次。
我当前的代码如下。 对于 FastAPI(后端):
@app.websocket("/")
async def predict_question(websocket: WebSocket):
await websocket.accept()
while True:
input_text = await websocket.receive_text()
autocomplete_text = text_gen.generate_text(input_text)
autocomplete_text = re.sub(r"[\([{})\]]", "", autocomplete_text)
autocomplete_text = autocomplete_text.split()
autocomplete_text = autocomplete_text[0:2]
resp = req.get('www.description_url_search_='+input_text+'')
datajson = resp.json()
with open('/home/user/backup/AutoComplete/frontend/src/data.json', 'w', encoding='utf-8') as f:
json.dump(datajson, f, ensure_ascii=False, indent=4)
await websocket.send_text(' '.join(autocomplete_text))
文件 App.vue(前端):
<template>
<div class="main-container">
<h1 style="color:#0072c6;">Title</h1>
<p style="text-align:center; color:#0072c6;">
Version 0.1
<br>
</p>
<Autocomplete />
<br>
</div>
<div style="color:#0072c6;">
<JsonArq />
</div>
<div style="text-align:center;">
<img src="./components/logo-1536.png" width=250 height=200 alt="Logo" >
</div>
</template>
<script>
import Autocomplete from './components/Autocomplete.vue'
import JsonArq from './components/EstepeJSON.vue'
export default {
name: 'App',
components: {
Autocomplete,
JsonArq: JsonArq
}
}
</script>
<style>
.main-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: 'Fredoka', sans-serif;
}
h1 {
font-size: 3rem;
}
@import url('https://fonts.googleapis.com/css2?family=Fredoka&display=swap');
</style>
components目录下的autocomplete.vue文件:
<template>
<div class="pad-container">
<div tabindex="1" @focus="setCaret" class="autocomplete-container">
<span @input="sendText" @keypress="preventInput" ref="editbar" class="editable" contenteditable="true"></span>
<span class="placeholder" contenteditable="false">{{autoComplete}}</span>
</div>
</div>
</template>
<script>
export default {
name: 'Autocomplete',
data: function() {
return {
autoComplete: "",
maxChars: 75,
connection: null
}
},
mounted() {
const url = "ws://localhost:8000/"
this.connection = new WebSocket(url);
this.connection.onopen = () => console.log("connection established");
this.connection.onmessage = this.receiveText;
},
methods: {
setCaret() {
const range= document.createRange()
const sel = window.getSelection();
const parentNode = this.$refs.editbar;
if (parentNode.firstChild == undefined) {
const emptyNode = document.createTextNode("");
parentNode.appendChild(emptyNode);
}
range.setStartAfter(this.$refs.editbar.firstChild);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
},
preventInput(event) {
let prevent = false;
// handles capital letters, numbers, and punctuations input
if (event.key == event.key.toUpperCase()) {
prevent = true;
}
// exempt spacebar input
if (event.code == "Space") {
prevent = false;
}
// handle input overflow
const nChars = this.$refs.editbar.textContent.length;
if (nChars >= this.maxChars) {
prevent = true;
}
if (prevent == true) {
event.preventDefault();
}
},
sendText() {
const inputText = this.$refs.editbar.textContent;
this.connection.send(inputText);
},
receiveText(event) {
this.autoComplete = event.data;
}
}
}
</script>
components目录下的estepeJSON.ue文件:
<template>
<div width="80%" v-for="regList in myJson" :key="regList" class="container">
<table>
<thead>
<tr>
<th>Documento</th>
</tr>
</thead>
<tbody>
<tr v-for="countryList in regList[2]" :key="countryList">
<td style="visibility: visible">{{ countryList}}</td>
</tr>
</tbody>
</table>
</div>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
/>
</template>
<script>
import json from "@/data.json";
export default {
name: "EstepeJson",
data() {
return {
myJson: json,
};
},
};
</script>
URL返回的JSON示例:
[
{
"Title": "SOFT-STARTER",
"Cod": "Produto: 15775931",
"Description": "A soft-starter SSW7000 permite o controle de partida/parada e proteção de motores.",
"Technical_characteristics": ["Corrente nominal", "600 A", "Tensão nominal", "4,16 kV", "Tensão auxiliar", "200-240 V", "Grau de proteção", "IP41", "Certificação", "CE"]
},
{
"Title": "SOFT-STARTER SSW",
"Cod": "Produto: 14223395",
"Description": "A soft-starter SSW7000 permite o controle de partida/parada e proteção de motores de indução trifásicos de média tensão.",
"Technical_characteristics": ["Corrente nominal", "125 A", "Tensão nominal", "6,9 kV", "Tensão auxiliar", "200-240 V", "Grau de proteção", "IP54/NEMA12", "Certificação", "CE"]
}
]
首先,我强烈建议您使用httpx
而不是使用 Python requests
模块(这会阻止事件循环,有关更多详细信息,请参见此处),它也提供异步 API 。 查看此答案和此答案以获取更多详细信息和工作示例。
其次,要将data
发送为 JSON,您需要使用await websocket.send_json(data)
,如Starlette 文档中所述。 如Starlette 的websockets
源代码所示,Starlette/FastAPI 在调用send_json()
function 时将使用text = json.dumps(data)
(序列化您传递的data
)。因此,您需要传递一个 Python dict
object。类似于requests
, 在httpx
中你可以在响应 object 上调用 .json .json()
方法来获取响应数据作为字典,然后将data
传递给send_json()
。
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import httpx
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get('/')
async def get():
return HTMLResponse(html)
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
# here use httpx to issue a request as demonstrated in the linked answers above
# r = await client.send(...
await websocket.send_json(r.json())
只需使用json.dumps(mydata)
将您的数据转换为 json 字符串
使用@Chris 在 HTTP 上的提示,经过一些研究,我设法解决了我的问题。 以下是决议。
在我的后端 FastAPI 文件中,我实现了 HTTPX 异步(来自@Chris 的提示)。 在返回 JSON 之后,我将自动完成项添加到 JSON 的第一个 position 中。从而返回到 Vue(前端)一个带有自动完成和 HTTPX 数据的 JSON。
文件快速API:
async def predict_question(websocket: WebSocket):
await manager.connect(websocket)
input_text = await websocket.receive_text()
if not input_text:
await manager.send_personal_message(json.dumps([]), websocket)
else:
autocomplete_text = text_gen.generate_text(input_text)
autocomplete_text = re.sub(r"[\([{})\]]", "", autocomplete_text)
autocomplete_text = autocomplete_text.split()
autocomplete_text = autocomplete_text[0:2]
resp = client.build_request("GET", 'www.description_url_search_='+input_text+'')
r = await client.send(resp)
datajson = r.json()
datajson.insert(0, ' '.join(autocomplete_text))
await manager.send_personal_message(json.dumps(datajson), websocket)
在 Autocomplete.vue 文件中,我做了一些小改动。 首先我将EstepeJson.vue文件合并到Autocomplete.vue中,特别是html中的json读取部分。其次在data:function(){}中我又添加了一个object,叫做myJson:[]。
第三,在receiveText方法中我改变了从websocket接收数据的方式。因为现在我有JSON.parse将event.data转换为JSON。然后我使用shift方法取json中的第一个position并删除这个数据从文件中。 最后,将 json 返回给 myjson 变量。
文件自动完成.vue:
<template>
<div class="pad-container">
<div tabindex="1" @focus="setCaret" class="autocomplete-container">
<span @input="sendText" @keypress="preventInput" ref="editbar" class="editable" contenteditable="true"></span>
<span class="placeholder" data-ondeleteId="#editx" contenteditable="false">{{autoComplete}}</span>
</div>
</div>
<div v-for="regList in myJson" :key="regList" class="container" >
<table>
<thead>
<tr>
<th>Documento</th>
</tr>
</thead>
<tbody>
<tr v-for="countryList in regList[2]" :key="countryList">
<td style="visibility: visible">{{ countryList}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
...
data: function() {
return {
autoComplete: "",
maxChars: 75,
connection: null,
myJson: []
}
},
.....
...
receiveText(event) {
let result = JSON.parse(event.data)
this.autoComplete = result.shift();
this.myJson = result
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.