简体   繁体   English

使用 jQuery 集成 Flask 和 ReactJS

[英]Integrating Flask and ReactJS with the use of jQuery

TL;DR: How am I able to integrate/implement a jQuery code(please see below) into ReactJS? TL;DR:我如何能够将 jQuery 代码(请参见下文)集成/实现到 ReactJS 中?

Greetings everyone.问候大家。 Amateur user of ReactJS and Flask here. ReactJS 和 Flask 的业余用户在这里。 I'm just looking for a solution on how to integrate a jQuery code into ReactJS or even other alternatives considering the implementation in the lifecycle becomes different into ReactJS.我只是在寻找关于如何将 jQuery 代码集成到 ReactJS 中的解决方案,或者考虑到生命周期中的实现与 ReactJS 不同,甚至其他替代方案。

Currently, this snippet (kindly see the boilerplate jQuery code below) communicates with Flask's CRUD operations very well which sends the chosen image from FileReader() in base64 form and responds with the corresponding prediction (by an ML model) when the #predict-button is pressed.目前,这个片段(请参阅下面的样板 jQuery 代码)与 Flask 的 CRUD 操作很好地通信,它以 base64 形式从FileReader()发送所选图像,并在#predict-button时响应相应的预测(通过 ML 模型)被按下。

<body>
    <input id="image-selector" type="file">
    <button id="predict-button">Predict</button>
    <p style="font-weight:bold">Predictions</p>
    <p>foo1: <span id="foo1"></span></p>
    <p>foo2:   <span id="foo2"></span></p>
    <p>foo3:   <span id="foo3"></span></p>
    <img id="selected-image" src=""/>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>
let base64Image;
    $("#image-selector").change(function() {
        let reader = new FileReader();
        reader.onload = function(e) {
            let dataURL = reader.result;
            $('#selected-image').attr("src",dataURL);
            base64Image = dataURL.replace("data:image/jpeg;base64,","");
        }
        reader.readAsDataURL($("#image-selector")[0].files[0]);
        $("#foo1").text("");
        $("#foo2").text("");
        $("#foo3").text("");
    });

    $("#predict-button").click(function(event){
        let message = {
            image: base64Image
        }
        console.log(message);
        $.post("http://127.0.0.1:5000/predict",JSON.stringify(message),function(response){
            $("#foo1").text(response.prediction.foo1.toFixed(6));
            $("#foo2").text(response.prediction.foo2.toFixed(6));
            $("#foo3").text(response.prediction.foo3.toFixed(6));
            console.log(response);
        });
    });
</script>
</body>

Not to mention, I don't need the FileReader() anymore as I have this function captureShot() from 'react-webcam' in ReactJS which returns a base64 encoded string of the current webcam image.更不用说,我不再需要FileReader()了,因为我有这个函数captureShot()来自 ReactJS 中的“react-webcam”,它返回当前网络摄像头图像的 base64 编码字符串。

  captureShot = () => {
    const screenshot = this.webcam.getScreenshot();
    this.setState({ imageData: screenshot });

  }

These kind of questions arise:会出现这样的问题:

  1. Can this be implemented in ReactJS?这可以在 ReactJS 中实现吗?
  2. If so, how?如果是这样,如何? Will it be through ComponentDidMount() or inside the render() ?是通过ComponentDidMount()还是在render()内部?
  3. If not, is using Express the way to do the CRUD operations in ReactJS en route to Flask?如果没有,是否使用 Express 在 ReactJS 中执行 CRUD 操作到 Flask 的方式?

Any kind of help would be highly appreciated.任何形式的帮助将不胜感激。 Thank you very much for your time and consideration.非常感谢您的时间和考虑。

This question is probably too broad for SO, but the short answer is "yes" you can do this.这个问题对于SO来说可能太宽泛了,但简短的回答是“是”,你可以这样做。 To get you thinking in the React way is probably the best I can offer for an answer without building it for you.让你以 React 的方式思考可能是我能提供的最好的答案,而无需为你构建它。

Your image-selector div will become a React component.您的image-selector div 将成为 React 组件。 It will have an onChange prop that will point to a custom class method where you can do the rest of your business logic.它将有一个onChange道具,该道具将指向一个自定义类方法,您可以在其中执行其余的业务逻辑。 Your predict-button will similarly become a component, this time with onClick as your prop.您的predict-button将类似地成为一个组件,这次使用onClick作为您的道具。 Since you are running all your functions as a response to an action, you don't need any bootstrapped data in constructor or componentDidMount .由于您正在运行所有函数作为对操作的响应,因此在constructorcomponentDidMount不需要任何引导数据。

You can use native fetch or similar libraries to replace your $.post call too.您也可以使用本机fetch或类似的库来替换您的$.post调用。 In the end you won't need any of your jQuery code, but if you convert your code piece-by-piece, you will get there and learn a lot along the way.最后,您将不需要任何 jQuery 代码,但如果您逐段转换代码,您将到达那里并在此过程中学到很多东西。 I suggest using Create React App for an easy way into the architecture.我建议使用 Create React App 来轻松进入架构。

My sheer excitement of asking this odd question surely have baffled three downvoters ha.我问这个奇怪问题的纯粹兴奋肯定让三个投票者感到困惑。 Thank you for the kind advice @jmargolisvt, I've managed to do it and my Flask server can now finally communicate well with my ReactJS - project is donezo!感谢@jmargolisvt 的善意建议,我已经做到了,我的 Flask 服务器现在终于可以与我的 ReactJS 进行良好的通信了——项目已经完成!

Here's the solution just in-case anyone's interested.这是解决方案,以防万一有人感兴趣。

export default class App extends Component { 
constructor(props){
    super(props);
    this.state = {
      bar: { foo1: null, foo2: null, foo3: null },
    }
  }

captureShot = () => {
    const screenshot = this.webcam.getScreenshot();
    let base64Image = screenshot.replace("data:image/jpeg;base64,","");
    this.setState({ 
      imageData: screenshot,
     });

    let message = {
      image: base64Image
    }

   fetch('http://127.0.0.1:5000/', {
    method: 'post',
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify(message)
    })
  .then((response) => {
    console.log(response);
    return response.json();  
  })
  .then((data) => {
    this.setState( {
      bar: {
        foo1: (data.prediction.foo1.toFixed(3)),
        foo2: (data.prediction.foo2.toFixed(3)),
        foo3: (data.prediction.foo3.toFixed(3)),
      }
    })   
  })
   .catch(error => this.setState({ error,  bar: { foo1: null, foo2: null, foo3: null }, }));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM