Home Web Front-end JS Tutorial Vue.js+Flask makes mobile app

Vue.js+Flask makes mobile app

Jun 14, 2018 pm 02:56 PM
vue.js Single Page

This time I will bring you Vue.js Flask to make a mobile app. What are the precautions for making a mobile app with Vue.js Flask? The following is a practical case, let’s take a look.

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.

Complete source code, you can find it here: https://github.com/oleg-agapov/flask-vue-spa

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
Copy after login

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
Copy after login

Via 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
Copy after login

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>
Copy after login
and

// About.vue
<template>
<p>
<p>About</p>
</p>
</template>
Copy after login

We will use them to correctly identify 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 'vue'
import Router from 'vue-router'
const routerOptions = [
{ path: '/', component: 'Home' },
{ path: '/about', component: 'About' }
]
const routes = routerOptions.map(route => {
return {
...route,
component: () => import(`@/components/${route.component}.vue`)
}
})
Vue.use(Router)
export default new Router({
routes,
mode: 'history'
})
Copy after login
If you try typing

localhost:8080

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

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, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
Copy after login
Change them to

index: path.resolve(__dirname, '../../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../../dist'),
Copy after login

so the HTML, CSS, and JS of the /dist folder will be in 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
Copy after login
To run in a virtual environment (MacOS):

$ source venv/bin/activate
Copy after login

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

Installation in a virtual environment:

(venv) pip install Flask
Copy after login

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

(venv) cd ..
(venv) touch run.py
Copy after login

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('/')
def index():
return render_template("index.html")
Copy after login

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
Copy after login

这将启动本地主机上的Web服务器: localhost:5000 上的 FLASK_APP 服务器端的启动文件, flask_debug = 1 将运行在调试模式。如果一切正确,你会看到熟悉的主页,你已经完成了对Vue的设置。

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

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template("index.html")
Copy after login

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

添加404页

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

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

const routerOptions = [
{ path: '/', component: 'Home' },
{ path: '/about', component: 'About' },
{ path: '*', component: 'NotFound' }
]
Copy after login

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

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

现在运行的前端服务器再次 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('/api/random')
def random_number():
response = {
'randomNumber': randint(1, 100)
}
return jsonify(response)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template("index.html")
Copy after login

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

{
"randomNumber": 36
}
Copy after login

你可以通过本地浏览测试这个路径: 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>
Copy after login

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

  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
Copy after login

打开 home.vue 再在 <script> 部分添加一些变化:

import axios from 'axios'
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 =&gt; {
this.randomNumber = response.data.randomNumber
})
.catch(error =&gt; {
console.log(error)
})
}
}
Copy after login

在顶部,我们需要引用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
Copy after login

你可以阅读文档,更好的解释你要使你的服务器怎么样使用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": "*"}})
Copy after login

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

更新:

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

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

import requests
@app.route('/', defaults={'path': ''})
@app.route('/&lt;path:path&gt;')
def catch_all(path):
if app.debug:
return requests.get('http://localhost:8080/{}'.format(path)).text
return render_template("index.html")
Copy after login

很优雅的魔法:sparkles:!

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

 

 

后记

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

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

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue封装轻量级文件上传组件

使用iScroll做出网页内容滚动

The above is the detailed content of Vue.js+Flask makes mobile app. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to develop a single-page web application using Golang How to develop a single-page web application using Golang Jun 05, 2023 am 09:51 AM

How to develop a single-page web application using Golang

Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Nov 16, 2022 pm 08:43 PM

Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project

Use vue-cropper to crop images in the vue project Use vue-cropper to crop images in the vue project Oct 31, 2022 pm 07:16 PM

Use vue-cropper to crop images in the vue project

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Explore how to write unit tests in Vue3

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

In-depth discussion of how vite parses .env files

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Let's talk in depth about reactive() in vue3

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

A brief analysis of how to handle exceptions in Vue3 dynamic components

See all articles