将React连接到烧瓶项目



我第一次遇到一个项目,其中后端用Python(framework flask(编写,前端用React编写。现在是时候在这两个部分之间连接一些功能了。

该项目的本质是用户上传一个文件,看到它的显示(名称(,可以单击转换按钮并接收不同格式的文件。前端部分已经编写好,后端部分也在那里,我需要连接这两个部分,这样通过点击convert按钮(这是React部分(,Python代码就会运行。

第二天我一直在阅读和观看最佳实践,但我什么都没成功,我希望你能帮助我。

所以,按顺序。

接下来,它被传递给父DisplaySelectedFile组件。DisplaySelectedFile负责显示用于选择文件的按钮(SelectFileButton(、显示文件本身、用于启动转换的按钮以及我们不感兴趣的其他一些元素

export default function DisplaySelectedFile() {
const [fileName, setFileName] = useState(null);
const [showCard, setShowCard] = useState(false);
const handleSelectFile = useCallback(
(file) => {
setFileName(file);
file && setShowCard(true);
},
[setFileName, setShowCard]
);

return (
<div>
...
</div>
);
}

我认为问题应该是如何设计DisplaySelectedFile组件。

您可以与后端人员讨论关于/convert端点的第一个选项。端点/convert应该支持返回上传过程的回调onUploadProgress

可以轮询的第二个选项调用/status端点来获取上传过程。下面是一个示例代码:

export default function DisplaySelectedFile() {
const [fileName, setFileName] = useState(null);
const [currentFile, setCurrentFile] = useState(undefined); // store the current upload file
const [showCard, setShowCard] = useState(false);
// save the files to the state
const selectFile = (event) => {
// I'm assuming that you support upload single file
const file = event.target.files[0];
setCurrentFile(file);
setFileName(file?.name); 
};
const getFile = async(task_id) => {
const interval = setInterval(() => {
fetch(`http://www.yourEnpoint.com/status?id=${task_id}`, { // Your GET endpoint
method: 'GET',
headers: {
// Content-Type may need to be completely **omitted**
// or you may need something
"Content-Type": "You will perhaps need to define a content-type here"
},
}).then((context) => {
if(context?.get_link) {
clearInterval(interval)
}
})
}, 500)
}
const handleConvert = () => {
fetch('http://www.yourEnpoint.com/transcript', { // Your POST endpoint
method: 'POST',
headers: {
// Content-Type may need to be completely **omitted**
// or you may need something
"Content-Type": "You will perhaps need to define a content-type here"
},
body: currentFile // This is your file object
}).then((response) => {
return getFile(response.task_id);
})
.then((context) => {
console.log(context); // Please do the further steps
})
.catch(() => {
console.log("Could not upload the file!");
setCurrentFile(undefined);
});
setCurrentFile(undefined);
}
return (
<div>
<SelectFileButton onChange={selectFile} />
<div>
{showCard && (
<TableHead sx={styles.CommonStyle}>
<TableRow >

<TableCell sx={styles.CellStyleFileName}>
{fileName}
</TableCell>

<TableCell sx={styles.CellStyleButtonAndCross}>
<ConvertFileButton onClick={handleConvert}></ConvertFileButton>
</TableCell>
</TableRow>
</TableHead>
)}
</div>
</div>
);
}

最新更新