useflask
和 vue-cli
Scaffolding, developmentvue3.x
Version of thePython with the typeScript web
project
Vue3. X has been around for a long time now, and there are already a number of UI library developers and companies using version 3.
Github Address: github.com/18055975947… Code cloud address: gitee.com/guoqiankun/…
Create a project
1. Use firstpyCharm
createpython-flask-vue-web
project
File directory
.Heavy Exercises ── ─ heavy Exercises ── heavy exercisesCopy the code
2. Use it in a foldervue create vue-web
createvue3.x
Version of the project
. ├ ─ ─ app. Py ├ ─ ─ the static ├ ─ ─ templates ├ ─ ─ venv └ ─ ─ the vue webCopy the code
3. Addvue.config.js
file
Don’t add anything to it yet
module.exports = {}
Copy the code
4. Start the project
cd vue-web
yarn serve
Copy the code
5. Modifyvue.config.js
file
We developflask web
Project, finally passedrender_template
To import files, but invue
Approved in the projectyarn run build
The generated file is invue-web
File, so configure oneoutputDir
和 indexPath
-
outputDir
- Type:
string
- Default:
'dist'
- When running
vue-cli-service build
Is the directory of the production environment build files generated by
- Type:
-
indexPath
- Type:
string
- Default:
'index.html'
- Specified generated
index.html
The output path of (relative tooutputDir
). It could be an absolute path.
- Type:
module.exports = {
outputDir: '.. /static'.indexPath: '.. /templates/index.html'
}
Copy the code
Why to ConfigureoutputDir
和 indexPath
- We use the
pycharm
Create items from above for usetree
According to the folder directory shown, yestemplates
Template folder andstatic
Resources folder - The use of
vue-cli3.x
Projects generated by and above versions are not packagedstatic
Folder, onlyjs
和css
Folders while we passFlask
There can only be one path to import static resources, so thejs
、css
A parent folder
6,yarn run build
packaging
tree -I "venv|*node_modules*" -L 2
-i does not display the venv and node_modules directories
-l 2 Displays two levels
. ├ ─ ─ app. Py ├ ─ ─ the static │ ├ ─ ─ CSS │ ├ ─ ─ the favicon. Ico │ ├ ─ ─ img │ └ ─ ─ js ├ ─ ─ templates │ └ ─ ─ index. The HTML └ ─ ─ vue - web ├ ─ ─ Package. The json ├ ─ ─ public ├ ─ ─ the SRC ├ ─ ─ tsconfig. Json ├ ─ ─ vue. Config. Js └ ─ ─ yarn. The lockCopy the code
Index.html, js, CSS, and img are all in the specified folder
Second, preview the project
We package the project through YARN Run Build and file it in the corresponding folder
At this point, go back to our app.py file and introduce index.html
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world() :
return render_template('index.html')
if __name__ == '__main__':
app.run()
Copy the code
Run the Python file
You can see
Running on http://127.0.0.1:5000/
Browser open error found, JS, CSS file 404, only the first HTML file can be found
404 is displayed in pyCharm’s console as well
3. Modify the project
1. Modifyvue.config.js
file
File error 404, meaning wrong path
We configure the assetsDir item in vue.config.js
- assetsDir
- Type:
string
- Default:
' '
- The directory (relative to outputDir) where generated static resources (JS, CSS, IMG, fonts) are placed.
- Type:
module.exports = {
outputDir: '.. /static'.indexPath: '.. /templates/index.html'.assetsDir: 'static/'
}
Copy the code
The purpose of configuring the assetsDir item is to load static resources and generated JS, CSS, img, etc. into the static folder
Yarn Run Build Package
Static folder contents in python-flask-vue-web
Tree static/ Displays the contents of the static folder
The static / ├ ─ ─ the favicon. Ico └ ─ ─ the static ├ ─ ─ CSS │ └ ─ ─ app. Ca79b516. CSS ├ ─ ─ img │ └ ─ ─ logo. 82 b9c7a5. PNG └ ─ ─ js ├ ─ ─ About.71B95CE9.js ├─ About.71B95CE9.js.map ├─ app.f47513F4.js ├─ app.f47513F4.js └ ─ ─ the chunk - vendors. 24202124. Js. The mapCopy the code
2. Modifyapp.py
file
Add static resource directories to the app created by Flask
from flask import Flask, render_template
app = Flask(__name__,
static_folder='./static/static')
@app.route('/')
def hello_world() :
return render_template('index.html')
if __name__ == '__main__':
app.run()
Copy the code
3. Runpython
file
Re-open http://127.0.0.1:5000/
You can see that the javascript, CSS, img import is normal, and the page is displayed normally, but there is a favicon.ico 404…
So it’s time to introduce static resources into the project
Add static resources to the project
1. favicon.ico
Path to modify
- In the first
vue-web/public/
Create a folderstatic
folder - the
favicon.ico
In thestatic
folder
Manu-web /public/ ├─ ├─ faviconCopy the code
- Modify the
vue-web/public/
Under folderindex.html
The file,favicon.ico
Change the import path of
<link rel="icon" href="static/favicon.ico">
Copy the code
yarn run build
packagingvue
project- Rerun the
app.py
file - Re-open the browser
http://127.0.0.1:5000/
At this point, favicon.ico can be loaded normally
2. Add a static to the projectjs
, e.g.jquery.js
- the
jquery.js
In thestatic
folder
├─ └─ vue-web/public/ exercises ├─ faviconCopy the code
index.html
File importjquery.js
<script src="static/jquery.js"></script>
Copy the code
- in
home.vue
In the print$
<script lang="ts">
import { defineComponent } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src
declare global {
interface Window {
'$': any; }}export default defineComponent({
name: 'Home'.components: {
HelloWorld
},
mounted () {
console.log(window. $)}})</script>
Copy the code
You can see the logs in the VUE front-end project we are running
yarn run build
packaging- Rerun the
app.py
File, openpython
的http://127.0.0.1:5000/
To view the page
At this point, the path introduction of favicon.ico and static resources is correct, and the project can be developed normally
3. This is normalvue
Projects can be developed
The front end can be developed according to the normal vUE development mode, and the back end python can be written according to the Python code.
Five, front and rear endajax
request
The front-end Web page needs to call the interface in Python, which is the most important point in the separation of the front and back ends
1. app.py
To write an interface that returns a random number/api/getRandomNum
from flask import Flask, render_template, jsonify
import random
app = Flask(__name__,
static_folder='./static/static')
@app.route('/')
def hello_world() :
return render_template('index.html')
@app.route('/api/getRandomNum')
def get_random_num() :
res = {
'getRandomNum': random.randint(1.100)}return jsonify(res)
if __name__ == '__main__':
app.run()
Copy the code
Rerun theapp.py
file
2. vue
Project introductionaxios
vue
中yarn add axios
- in
main.ts
The introduction ofaxios
import axios from 'axios'
const app = createApp(App)
app.provide('axios', axios)
Copy the code
- in
home.vue
The use ofaxios
For the request
<script lang="ts">
import { defineComponent, inject } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src
declare global {
interface Window {
'$': any; }}export default defineComponent({
name: 'Home'.components: {
HelloWorld
},
setup () {
const axios: any = inject('axios')
axios.get('http://localhost:5000/api/getRandomNum').then((res: object) = > {
console.log(res)
}).catch((e: any) = > {
console.log(e)
})
}
})
</script>
Copy the code
yarn serve
When the page is opened, an error message is displayed, indicating a cross-domain error
3. Solve the inter-domain interface problem
- Flask-CORS
A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
Flask extension, for handling cross-source resource sharing (CORS), makes cross-source AJAX possible.
pip install flask_cors
app.py
The introduction offlask_cors
- Cross domain processing
from flask import Flask, render_template, jsonify
from flask_cors import CORS
import random
app = Flask(__name__,
static_folder='./static/static')
CORS(app)
@app.route('/')
def hello_world() :
return render_template('index.html')
@app.route('/api/getRandomNum')
def get_random_num() :
res = {
'getRandomNum': random.randint(1.100)}return jsonify(res)
if __name__ == '__main__':
app.run()
Copy the code
- Rerun the
app.py
file - The refresh
vue
project
As you can see, the interface can now request normally and return normally.
At this point, both the front and back end projects can be developed normally,ajax
It can also be requested normally
Vi. Package and run the project
yarn run build
packagingvue
The front-end projectapp.py
File to run- Open the
http://127.0.0.1:5000/#/
View the project
The code address
- Github address: github.com/18055975947…
- Code cloud address: gitee.com/guoqiankun/…
The resources
- flask-cors
Denver annual essay | 2020 technical way with me The campaign is under way…