Home >Web Front-end >JS Tutorial >Example of using Vue.js and Flask to build a single-page App

Example of using Vue.js and Flask to build a single-page App

亚连
亚连Original
2018-05-26 17:38:471565browse

This article mainly introduces an example of using Vue.js and Flask to build a single-page App. I think it is quite good. I will share it with you now and give it as a reference. Let’s take a look together

In this tutorial, we will explain how to connect a vue.js single-page application with the Flask backend.

Generally speaking, if you just want to use the vue.js library through Flask templates, there is no problem. However, there is actually an obvious problem that Jinja (template engine) also uses double braces for rendering like Vue.js, but it is only a passable solution.

I would like a different example. If I need to build a single-page application (the application is composed of a single page, vue-router in HTML5's History-mode and other more useful features) using vue.js, provided by Flask Web Serve? Simply put it should be like this, like this:

Flask serves index.html which contains my vue.js App. For front-end development I use Webpack, which provides all the cool features.

Flask has an API side that I can access from my SPA.

I have access to the API side, even when I'm running Node.js for front-end development.

Sounds interesting? So let's do it like this.

Client

I will use Vue CLI to generate a basic vue.js App. If you haven't installed it yet, run:

$ npm install -g vue-cli

The client and backend code will be split into different folders. Initialize the front-end part to run the trace:

$ mkdir flaskvue
$ cd flaskvue
$ vue init webpack frontend

Through the installation wizard. My setup is:

Vue only builds at runtime.

Install Vue-router.

Use ESLint to check the code.

Select an ESLint standard preset.

Do not try out Karma Mocha for unit testing.

Do not use Nightwatch to build end-to-end tests.

ok, next:

$ cd frontend
$ npm install
# after installation
$ npm run dev

Now you can start installing the

vue.js

application. Let's start by adding some pages. Add

home.vue

and about.vue to the frontend/src/components folder. They are very simple, like this:

// Home.vue
<template>
<p>
<p>Home page</p>
</p>
</template>

and

// About.vue
<template>
<p>
<p>About</p>
</p>
</template>

We will use them Correctly identifies our current location (according to the address bar). Now we need to change the

frontend/src/router/index.js

file to use our new component:

import Vue from &#39;vue&#39;
import Router from &#39;vue-router&#39;
const routerOptions = [
{ path: &#39;/&#39;, component: &#39;Home&#39; },
{ path: &#39;/about&#39;, component: &#39;About&#39; }
]

const routes = routerOptions.map(route => {
return {
...route,
component: () => import(`@/components/${route.component}.vue`)
}

})

Vue.use(Router)
export default new Router({
routes,
mode: &#39;history&#39;
})

If you try Enter

localhost:8080

and localhost:8080/about and you should see the corresponding pages.

We are almost ready to build a project and are able to create a static resource file bundle. Before that, let's redefine the output directories for them. Find the next settings in

frontend/config/index.js

:

index: path.resolve(__dirname, &#39;../dist/index.html&#39;),
assetsRoot: path.resolve(__dirname, &#39;../dist&#39;),

Change them to

index: path.resolve(__dirname, &#39;../../dist/index.html&#39;),
assetsRoot: path.resolve(__dirname, &#39;../../dist&#39;),

So the HTML, CSS, and JS of the /dist folder will be in the same level directory /frontend. Now you can run

$ npm run build

to create a package.

Backend

For the Flask server, I will be using Python version 3.6. Create a new subfolder in

/flaskvue

to store the backend code and initialize the virtual environment:

$ mkdir backend
$ cd backend
$ virtualenv -p python3 venv

In order to run in the virtual environment ( MacOS):

$ source venv/bin/activate

This document needs to be activated in Windows (http://pymote.readthedocs.io/en/latest/install/windows_virtualenv.html) .

Installation in a virtual environment:

(venv) pip install Flask

Now let’s write the code for the Flask server. Create the root directory file run.py:

(venv) cd ..
(venv) touch run.py

Add the next code to this file:

from flask import Flask, render_template
app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")

@app.route(&#39;/&#39;)
def index():
return render_template("index.html")

This code is slightly different from Flask's **"Hello World"** code. The main difference is that we specify the location to store static files and templates in the folder

/dist

to distinguish them from our front-end folder. Run the Flask server in the root folder:

(venv) FLASK_APP=run.py FLASK_DEBUG=1 flask run

This will start the web server on localhost:

localhost:5000

FLASK_APP Server-side startup file, flask_debug = 1 will run in debug mode. If everything is correct, you will see the familiar home page and you have completed setting up Vue.

同时,如果您尝试输入/about页面,您将面临一个错误。Flask抛出一个错误,说找不到请求的URL。事实上,因为我们使用了HTML5的History-Mode在Vue-router需要配置Web服务器的重定向,将所有路径指向index.html。用Flask做起来很容易。将现有路由修改为以下:

@app.route(&#39;/&#39;, defaults={&#39;path&#39;: &#39;&#39;})
@app.route(&#39;/<path:path>&#39;)
def catch_all(path):
return render_template("index.html")

现在输入网址localhost:5000/about 将重新定向到index.html和vue-router将处理路由。

添加404页

因为我们有一个包罗万象的路径,我们的Web服务器在现在已经很难赶上404错误,Flask将所有请求指向index.html(甚至不存在的页面)。所以我们需要处理未知的路径在vue.js应用。当然,所有的工作都可以在我们的路由文件中完成。

在frontend/src/router/index.js添加下一行:

const routerOptions = [
{ path: &#39;/&#39;, component: &#39;Home&#39; },
{ path: &#39;/about&#39;, component: &#39;About&#39; },
{ path: &#39;*&#39;, component: &#39;NotFound&#39; }
]

这里的路径'*'是一个通配符, Vue-router 就知道除了我们上面定义的所有其他任何路径。现在我们需要更多的创造 NotFound.vue 文件在**/components**目录。试一下很简单:

// NotFound.vue
<template>
<p>
<p>404 - Not Found</p>
</p>
</template>

现在运行的前端服务器再次 npm run dev ,尝试进入一些毫无意义的地址例如: localhost:8080/gljhewrgoh 。您应该看到我们的“未找到”消息。

添加API端

我们的 vue.js/flask 教程的最后一个例子将是服务器端API创建和调度客户端。我们将创建一个简单的Api,它将从1到100返回一个随机数。

打开run.py并添加:

from flask import Flask, render_template, jsonify
from random import *

app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")

@app.route(&#39;/api/random&#39;)

def random_number():
response = {
&#39;randomNumber&#39;: randint(1, 100)
}
return jsonify(response)

@app.route(&#39;/&#39;, defaults={&#39;path&#39;: &#39;&#39;})
@app.route(&#39;/<path:path>&#39;)
def catch_all(path):

return render_template("index.html")

首先我导入random库和jsonify函数从Flask库中。然后我添加了新的路由 /api/random 来返回像这样的JSON:

{
"randomNumber": 36
}

你可以通过本地浏览测试这个路径: localhost:5000/api/random。

此时服务器端工作已经完成。是时候在客户端显示了。我们来改变home.vue组件显示随机数:

<template>
<p>
<p>Home page</p>
<p>Random number from backend: {{ randomNumber }}</p>
<button @click="getRandom">New random number</button>
</p>

</template>
<script>
export default {
data () {
return {
randomNumber: 0
}
},

methods: {
getRandomInt (min, max) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
},

getRandom () {
this.randomNumber = this.getRandomInt(1, 100)
}
},

created () {
this.getRandom()
}

}
</script>

在这个阶段,我们只是模仿客户端的随机数生成过程。所以,这个组件就是这样工作的:

  1. 在初始化变量 randomNumber 等于0。

  2. 在methods部分我们通过 getRandomInt(min, max) 功能来从指定的范围内返回一个随机数, getrandom 函数将生成随机数并将赋值给 randomNumber

  3. 组件方法 getrandom 创建后将会被调用来初始化随机数

  4. 在按钮的单击事件我们将用 getrandom 方法得到新的随机数

现在在主页上,你应该看到前端显示我们产生的随机数。让我们把它连接到后端。

为此目的,我将用 axios 库。它允许我们用响应HTTP请求并用 Json 返回 JavaScript Promise 。我们安装下它:

(venv) cd frontend
(venv) npm install --save axios

打开 home.vue 再在 3f1c4e4b6b16bbbd69b2ee476dc4f83a 部分添加一些变化:

import axios from &#39;axios&#39;
methods: {
getRandom () {
// this.randomNumber = this.getRandomInt(1, 100)
this.randomNumber = this.getRandomFromBackend()
},

getRandomFromBackend () {
const path = `http://localhost:5000/api/random`
axios.get(path)
.then(response => {
this.randomNumber = response.data.randomNumber
})
.catch(error => {
console.log(error)
})
}
}

在顶部,我们需要引用Axios库。然后有一个新的方法 getrandomfrombackend 将使用Axios异步调用API和检索结果。最后, getrandom 方法现在应该使用 getrandomfrombackend 函数得到一个随机值。

保存文件,到浏览器,运行一个开发服务器再次刷新 localhost:8080 。你应该看到控制台错误没有随机值。但别担心,一切都正常。我们得到了 CORS 的错误意味着Flask服务器API默认会关闭其他Web服务器(在我们这里,vue.js App是在 Node.js服务器上运行的应用程序)。如果你 npm run build 项目,那在 localhost:5000 (如Flask服务器)你会看到App在工作的。但是,每次对客户端应用程序进行一些更改时,都创建一个包并不十分方便。

让我们用打包了CORS插件的Flask,将使我们能够创建一个API访问规则。插件叫做FlaskCORS,让我们安装它:

(venv) pip install -U flask-cors

你可以阅读文档,更好的解释你要使你的服务器怎么样使用CORS。我将使用特定的方法,并将**{“origins”: “*”}**应用于所有/api/*路由(这样每个人都可以使用我的API端)。在run.py加上:

from flask_cors import CORS
app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

有了这种改变,您就可以从前端调用服务端。

更新:

事实上,如果你想通过Flask提供静态文件不需要CORS。感谢Carson Gee的下面的这一招。

这个主意是这样的。如果应用程序在调试模式下,它只会代理我们的前端服务器。否则(在生产中)只为静态文件服务。所以我们这样做:

import requests
@app.route(&#39;/&#39;, defaults={&#39;path&#39;: &#39;&#39;})
@app.route(&#39;/<path:path>&#39;)
def catch_all(path):

if app.debug:

return requests.get(&#39;http://localhost:8080/{}&#39;.format(path)).text

return render_template("index.html")

很优雅的魔法:sparkles:!

现在有了一个完整的全栈**(full-stack) 应用程序,用您最喜爱 Vue.js Flask**技术构建。

 

 

后记

最后,我想就如何改进这个解决方案谈几句话。

首先利用CORS,如果你想让你的API端访问外部的服务器。否则的话只需要使用代理服务器与前端开发技巧。

另一个改进是避免客户端硬编码API路由。也许你需要考虑一些API端点的字典。因此,当您更改API路由时,只需刷新一个字典即可。前端仍然有一个有效的端点。

通常在开发过程中,你将至少有2个终端窗口:一个是Flask和另一个是vue.js。在生产中可以摆脱Vue而只单独运行Node.js服务器。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

解决微信返回上一页,页面中的AJAX的请求,对Get请求无效的问题

ajax实现异步文件或图片上传功能

AJAX用于判定用户是否注册

The above is the detailed content of Example of using Vue.js and Flask to build a single-page App. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn