📜 ⬆️ ⬇️

Tic Tac Toe, Part 4: Interacting with the Flask backend using HTTP

Tic Tac Toe, Part 0: Comparing Svelte and React
Tic Tac Toe, Part 1: Svelte and Canvas 2D
Tic Tac Toe, Part 2: Undo / Redo with state storage
Tic Tac Toe, Part 3: Undo / Redo with commands storage
Tic Tac Toe, Part 4: Interacting with the Flask backend using HTTP

In this article we will look at the interaction of a web application on Svelte from the previous article with a backend on Flask using HTTP requests. It turned out that raising the container with the backend application on Flask is faster than on Boost.Beast , so I made an example with Flask . Do not worry, the example with Boost.Beast will be a little later.


Project installation

It is assumed that docker and docker-compose are installed on the computer.


We clone the project on your computer:


git clone https://github.com/nomhoi/tic-tac-toe-part4.git 

We start containers:


 cd tic-tac-toe-part4 docker-compose up -d 

We build the web application:


 cd front npm install npm run-script build 

Open the browser at http: // localhost . On a Windows machine, we recognize the IP docker of the machine, usually it is http://192.168.99.100 .


We see that the button Get random number appears on the right. By clicking on this button, the web application accesses the backend - executes the http: // localhost / number request and receives a random number from 0 to 8, inclusive, from it. This number is used to perform a software click with the mouse on the game field, the history.push method is called, and a cross or a zero appears on the game field. If the cell is already occupied, the message busy appears.


Docker containers

Recently on Habré a wonderful article on docker and docker-compose for beginners, you can read. Here I will point out only the moments related to our project. Consider the docker-compose.yml file. We have two services: nginx and flask .


docker-compose.yml:


 version: "3.5" services: nginx: image: nginx:alpine container_name: nginx volumes: - ./front/public:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf:ro ports: - "80:80" depends_on: - flask networks: - backend flask: build: context: flask/ dockerfile: Dockerfile ports: - "5000:5000" volumes: - ./flask:/code environment: FLASK_ENV: development networks: - backend networks: backend: name: backend 

The nginx service starts the nginx web server under which our web application runs. The flask service starts the Flask server with our small backend application.


Frontend

The web application was taken from the previous article and placed in the front folder. Another Dispatcher component was added to the project, which coordinates the interaction between the web application and the backend.


Dispatcher.svelte:


 <script> import { history, status } from './stores.js'; import { Command } from './helpers.js'; let promise = null; async function getRandomNumber() { const res = await fetch(`number`); const text = await res.text(); if (res.ok) { let i = parseInt(text); if ($status === 1 || $history.state.squares[i]) return text + ' - busy'; history.push(new Command($history.state, i)); return text; } else { throw new Error(text); } } function handleClick() { promise = getRandomNumber(); } //setInterval(handleClick, 500); </script> {#if $status > 0} <button disabled> Get random number </button> {:else} <button on:click={handleClick}> Get random number </button> {/if} {#await promise} <p>...</p> {:then number} <p>Respond from backend: {number}</p> {:catch error} <p style="color: red">{error.message}</p> {/await} 

The code is almost entirely taken from this example . By clicking the Get random number button in the getRandomNumber () function, the request is executed using the URI http: // localhost / number , nginx sends a request to the backend, and it returns a random number. This number is used to add a step to the history.
The address http: // localhost / number can be entered in a separate tab of the browser and see that different numbers are returned on request.


In the nginx web server settings, the following configuration was added to the default configuration file default.conf :


 location /number { proxy_pass http://flask:5000; } 

With this setting, the request is sent to the backend server.


Backend

The basis for setting up the flask service is here: https://docs.docker.com/compose/gettingstarted/ .


App.py:


 from flask import Flask from random import randrange app = Flask(__name__) @app.route('/number') def number(): return str(randrange(9)) 

When a request arrives at the address / number , the number () function is called. By code, you can see that a random number is returned in the range from 0 to 8 inclusive.


Conclusion

Usually messages in web applications are transmitted in JSON format. But this is not a complicated thing and so can be done.


In the following articles, it makes sense to consider the implementation of a multiplayer web application when one player plays with another player through a common web server. You can consider the option when the player plays with an intelligent agent with the implementation of the application logic on the server itself, and not in the frontend application.


GitHub Repository

https://github.com/nomhoi/tic-tac-toe-part4


')

Source: https://habr.com/ru/post/460621/


All Articles