井字游戏第0部分:比较苗条和反应
井字游戏第1部分:Svelte and Canvas 2D
井字游戏第2部分:无状态复原/重做
井字游戏,第3部分:使用命令存储撤消/重做
井字游戏第4部分:使用HTTP与Flask后端交互
在本文中,我们将考虑使用HTTP请求将上一篇文章中的Svelte Web应用程序与Flask后端进行交互。 事实证明,在Flask上使用后端应用程序来提高容器的速度比在Boost.Beast上更快 ,因此我以Flask为例。 不用担心, Boost.Beast示例将在稍后。
项目安装
假定在计算机上安装了docker和docker-compose。
我们在您的计算机上克隆项目:
git clone https://github.com/nomhoi/tic-tac-toe-part4.git
发射容器:
cd tic-tac-toe-part4 docker-compose up -d
我们构建Web应用程序:
cd front npm install npm run-script build
在http:// localhost打开浏览器。 在Windows机器上,我们找出机器的IP泊坞站,通常是http://192.168.99.100 。
我们看到在右侧显示了获取随机数按钮。 通过单击此按钮,Web应用程序访问后端-执行请求http:// localhost / number并从中接收一个0到8之间的一个随机数。 此数字用于在运动场上执行程序鼠标单击,调用history.push方法,十字形或零出现在运动场上。 如果该单元已被占用,则会显示一条忙消息。
Docker容器
最近, 枢纽上刊登了一篇关于docker和docker-compose的新手文章 。 在这里,我仅指出与我们的项目有关的问题。 考虑docker-compose.yml文件。 我们提供两项服务: nginx和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
Nginx服务将启动运行我们的Web应用程序的Nginx Web服务器。 flask服务通过我们的小型后端应用程序启动Flask服务器。
前端
该Web应用程序取自上一篇文章,并放在前面的文件夹中。 另一个Dispatcher组件已添加到项目中,该组件负责协调Web应用程序和后端之间的交互。
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(); } </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}
该代码几乎完全取自该示例 。 通过单击getRandomNumber()函数中的“ 获取随机数”按钮,使用URI http:// localhost / number发出请求,nginx将请求传递到后端,并返回一个随机数。 此数字用于增加故事的步骤。
您可以在单独的浏览器选项卡中输入地址http:// localhost / number ,然后看到根据请求返回了不同的数字。
在Nginx Web服务器设置中,以下设置已添加到default.conf默认配置文件中:
location /number { proxy_pass http://flask:5000; }
由于此设置,后端请求被传输到服务器。
后端
在这里获取配置Flask服务的基础: 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))
当请求到达地址/数字时 ,将调用number()函数。 该代码显示返回的随机数范围为0到8(含0和8)。
结论
通常,Web应用程序中的消息以JSON格式发送。 但是,可以通过这种方式完成如此困难的事情。
在以下文章中,当一个玩家通过公共Web服务器与另一个玩家一起玩时,考虑多用户Web应用程序的实现是有意义的。 当播放器与智能代理一起使用时,可以在服务器本身(而不是前端应用程序)中实现应用程序逻辑的实现时考虑该选项。
GitHub存储库
https://github.com/nomhoi/tic-tac-toe-part4