I want to make a web application using React and Python flask

Introduction

Since I started to be involved in front development with React at work, I created a simple web application that also serves as an output practice.

I couldn't think of any idea what kind of app to use, so I used the word-separating script that I had at hand mecab and received the input text at the front desk. It is a very simple application that divides the data on the server side and displays the result at the front desk. (Since the main purpose was to study the part that connects react and flask, I'm not sure that the appearance and functions of the app have not been created at all.)

As the title suggests, it is implemented with React on the front side and python flask on the server side.

The script implemented this time is available at here.

Finished product

screen app_top.png

Try to divide app_res.png

Implementation environment

OS: Ubuntu 18.04.2 LTS
Python: 3.6
flask==1.0.2

npm: 6.14.7

I will not touch on the environment construction of react this time, but the official tutorial is also substantial in Japanese and it was very helpful.

This is also highly recommended.

Implement

Diagram

The configuration of the application implemented this time is as follows (main part only).

app_architect.png

Server side

The server side has the following configuration.

backend/
   ├─ requirements.txt
   ├─ server.py
   └─ utils.py

server.py is the code that launches the flask server.

The address and port are specified at the bottom with ʻapp.run (host = '127.0.0.1', port = 5000)`.

server.py


from flask import Flask
from flask import request, make_response, jsonify
from flask_cors import CORS
from utils import wakati

app = Flask(__name__, static_folder="./build/static", template_folder="./build")
CORS(app) #Cross Origin Resource Sharing

@app.route("/", methods=['GET'])
def index():
    return "text parser:)"

@app.route("/wakati", methods=['GET','POST'])
def parse():
    #print(request.get_json()) # -> {'post_text': 'Test test test'}
    data = request.get_json()
    text = data['post_text']

    res = wakati(text)
    response = {'result': res}
    #print(response)
    return make_response(jsonify(response))

if __name__ == "__main__":
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

The @ app.route ("/ wakati ", methods = ['GET','POST') part receives the text from the front, divides it, and then returns it to the front. Get the content posted from the front by data = request.get_json () in json format. It takes out the necessary data from here, performs some processing (functions, puts it in the DB, etc.), converts it to json format like response = {'result': res}, and returns it to the front.

(Supplement: What is CORS) This rule is required to enable access to another resource (= cross-site HTTP request). Without this, you will not be able to access the flask server launched from the front side. --Reference: https://aloerina01.github.io/blog/2016-10-13-1

Front side

This time, I used the template of create-react-app. (Here is very easy to understand how to set up and use create-react-app!)

The front side has the following structure (only the main files are listed).

frontend/app/
   ├─ node_modules/
   ├─ public/
   ├─ src/
   |   ├─ App.css
   |   ├─ App.js
   |   ├─ index.js
   |   └─ ...
   └─ ...

I rewrote ʻApp.js` in the automatically generated template as follows.

App.js


import React from 'react';
import './App.css';
import Axios from 'axios';

//function App() {
export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1>text parser</h1>
          <form onSubmit={this.handleSubmit}>
            <label>
              <textarea name="text" cols="80" rows="4" value={this.state.value} onChange={this.handleChange} />
            </label>
            <br/>
            <input type="submit" value="Parse" />
          </form>
        </header>
      </div>
    );
  }


  wakati = text => {
    //console.log("input text >>"+text)
    Axios.post('http://127.0.0.1:5000/wakati', {
      post_text: text
    }).then(function(res) {
      alert(res.data.result);
    })
  };

  handleSubmit = event => {
    this.wakati(this.state.value)
    event.preventDefault();
  };

  handleChange = event => {
    this.setState({ value: event.target.value });
  };
}

export default App;

The following parts of this are used to communicate with the server side.

  wakati = text => {
    //console.log("input text >>"+text)
    Axios.post('http://127.0.0.1:5000/wakati', {
      post_text: text
    }).then(function(res) {
      alert(res.data.result);
    })
  };

Post the value of this.state.value to http://127.0.0.1:5000/wakati set up in server.py. After being processed on the server side, the returned result value is displayed in the browser by ʻalert (res.data.result);`.

move

Launch a terminal for the front end / back end respectively and execute the following command.

Server side

$ cd backend
$ python server.py

Front side

$ cd frontend/app
$ yarn start

You can use the app by accessing localhost: 3000 from your browser (it will start automatically with yarn start).

in conclusion

This time, I implemented a simple web application using React and Python flask. It's simple, but it's great because you can easily implement a web application in a short time.

Since I am training at the front desk, I am still not sure about the appearance and functions, so I would appreciate your opinions and advice. Thank you for reading until the end!

Recommended Posts

I want to make a web application using React and Python flask
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I tried to make a todo application using bottle with python
I want to make a game with Python
(Python) Try to develop a web application using Django
[Python] I want to make a nested list a tuple
Creating a web application using Flask ②
Creating a web application using Flask ①
Creating a web application using Flask ③
I tried to make a stopwatch using tkinter in python
I want to make input () a nice complement in python
I want to build a Python environment
I tried to make a Web API
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
I tried to make a regular expression of "date" using Python
I tried to make a 2channel post notification application with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to create a karaoke sound source by separating instruments and vocals using Python
I want to make matplotlib a dark theme
I tried web scraping using python and selenium
I made a web application in Python that converts Markdown to HTML
I want to create a window in Python
I want to email from Gmail using Python.
Create a web map using Python and GDAL
Steps to develop a web application in Python
[Streamlit] I hate JavaScript, so I make a web application only with Python
I want to make C ++ code from Python code!
Start a web server using Bottle and Flask (I also tried using Apache)
I tried to create a sample to access Salesforce using Python and Bottle
I want to write to a file with Python
I tried to make a ○ ✕ game using TensorFlow
I want to pass an argument to a python function and execute it from PHP on a web server
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
Let's make an A to B conversion web application with Flask! From scratch ...
[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
I tried to make a simple mail sending application with tkinter of Python
I want to make a music player and file music at the same time
I want to exe and distribute a program that resizes images Python3 + pyinstaller
WEB scraping with python and try to make a word cloud from reviews
I want to create a web application that uses League of Legends data ①
Create a web app that converts PDF to text using Flask and PyPDF2
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to generate a UUID quickly (memorandum) ~ Python ~
I want to transition with a button in flask
I want to handle optimization with python and cplex
Parse and visualize JSON (Web application ⑤ with Python + Flask)
I want to work with a robot in python.
How to make a Python package using VS Code
[Python] I tried running a local server using flask
I want to run a quantum computer with Python
Web application with Python + Flask ② ③
Web application with Python + Flask ④
If you want to make a Windows application (exe) that can be actually used now using only Python
[Python] I want to add a static directory with Flask [I want to use something other than static]
[Mac] I want to make a simple HTTP server that runs CGI with Python
I want to write a triple loop and conditional branch in one line in python
Try to make it using GUI and PyQt in Python
I want to make a blog editor with django admin
[Python] I want to get a common set between numpy