我有一个应用程序,其中前端是通过VUE和后端是FastAPI,通信是通过WebSocket完成的.

目前,前端允许用户输入一个术语,该术语被发送到后端以生成自动补全,还可以对返回json的URL执行搜索.在其中,我将这个json保存在前端文件夹中.之后,后端将有问题的术语的自动补全数据返回到前端.前端显示自动完成和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 e.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"]
}
]

推荐答案

在使用@Chris在HTTP上的提示后,经过一些研究,我设法解决了我的问题.以下是解决方案.

在我的后端FastAPI文件中,我实现了HTTPX Async(来自@Chris的技巧).在返回JSON之后,我获取了自动补全项并将其添加到JSON的第一个位置.从而将具有AutoComplete和HTTPX数据的JSON返回到Vue(前端).

FastAPI文件:

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 e.vue文件中,我做了一些小的更改. 首先,我将EstepeJson.vue文件合并到AutoComplete e.vue中,特别是html中的json读取部分. 其次,在data:Function(){}中,我又添加了一个名为myJson:[]的对象.

第三,在ReceiveText方法中,我更改了从WebSocket接收数据的方式.现在,我使用JSON.parse将Event.data转换为JSON.然后,我使用Shift方法获取json中的第一个位置,并从文件中删除该数据.最后,将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>

Python相关问答推荐

找到相对于列表索引的当前最大值列表""

基于多个数组的多个条件将值添加到numpy数组

应用指定的规则构建数组

Python:从目录内的文件导入目录

一维不匹配两个数组上的广义ufunc

将像素信息写入文件并读取该文件

Match-Case构造中的对象可调用性测试

如何将验证器应用于PYDANC2中的EACHY_ITEM?

搜索结果未显示.我的URL选项卡显示:http://127.0.0.1:8000/search?";,而不是这个:";http://127.0.0.1:8000/search?q=name";

PySpark:使用重置对窗口进行计数

如何 Select 包含一定字符串和数字的单元格?

设置邮箱附件的文件类型

PythonC扩展比Numba JIT快吗?

.yml不会在专用环境中安装来自.requirements.txt的软件包

Django在两个领域进行连接

第一行中的Pandas 按条件替换

如何为查询创建动态ORDER BY表达式

用于判断x=()的&Quot;isInstance()和Not&Quot;vs&Quot;==&Quot;

如何根据两个日期之间的周数复制行?

如何从直接URL和间接URL中提取文件扩展名?