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.
screen
Try to divide
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.
The configuration of the application implemented this time is as follows (main part only).
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
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);`.
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).
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