useflaskvue-cliScaffolding, developmentvue3.xVersion of thePython with the typeScript webproject

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 firstpyCharmcreatepython-flask-vue-webproject

File directory

.Heavy Exercises ── ─ heavy Exercises ── heavy exercisesCopy the code

2. Use it in a foldervue create vue-webcreatevue3.xVersion of the project

. ├ ─ ─ app. Py ├ ─ ─ the static ├ ─ ─ templates ├ ─ ─ venv └ ─ ─ the vue webCopy the code

3. Addvue.config.jsfile

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.jsfile

We developflask webProject, finally passedrender_templateTo import files, but invueApproved in the projectyarn run buildThe generated file is invue-webFile, so configure oneoutputDirindexPath

  • outputDir

    • Type: string
    • Default: 'dist'
    • When runningvue-cli-service buildIs the directory of the production environment build files generated by
  • indexPath

    • Type: string
    • Default: 'index.html'
    • Specified generatedindex.htmlThe output path of (relative tooutputDir). It could be an absolute path.
module.exports = {
  outputDir: '.. /static'.indexPath: '.. /templates/index.html'
}
Copy the code

Why to ConfigureoutputDirindexPath

  1. We use thepycharmCreate items from above for usetreeAccording to the folder directory shown, yestemplatesTemplate folder andstaticResources folder
  2. The use ofvue-cli3.xProjects generated by and above versions are not packagedstaticFolder, onlyjscssFolders while we passFlaskThere can only be one path to import static resources, so thejscssA parent folder

6,yarn run buildpackaging

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.jsfile

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.
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.pyfile

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. Runpythonfile

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.icoPath to modify

  1. In the firstvue-web/public/Create a folderstaticfolder
  2. thefavicon.icoIn thestaticfolder
Manu-web /public/ ├─ ├─ faviconCopy the code
  1. Modify thevue-web/public/Under folderindex.htmlThe file,favicon.icoChange the import path of
<link rel="icon" href="static/favicon.ico">
Copy the code
  1. yarn run buildpackagingvueproject
  2. Rerun theapp.pyfile
  3. Re-open the browserhttp://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

  1. thejquery.jsIn thestaticfolder
├─ └─ vue-web/public/ exercises ├─ faviconCopy the code
  1. index.htmlFile importjquery.js
<script src="static/jquery.js"></script>  
Copy the code
  1. inhome.vueIn 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

  1. yarn run buildpackaging
  2. Rerun theapp.pyFile, openpythonhttp://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 normalvueProjects 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 endajaxrequest

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.pyTo 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.pyfile

2. vueProject introductionaxios

  1. vueyarn add axios
  2. inmain.tsThe introduction ofaxios
import axios from 'axios'

const app = createApp(App)

app.provide('axios', axios)
Copy the code
  1. inhome.vueThe use ofaxiosFor 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
  1. yarn serveWhen the page is opened, an error message is displayed, indicating a cross-domain error

3. Solve the inter-domain interface problem

  1. 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.

  1. pip install flask_cors
  2. app.pyThe introduction offlask_cors
  3. 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
  1. Rerun theapp.pyfile
  2. The refreshvueproject

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,ajaxIt can also be requested normally

Vi. Package and run the project

  1. yarn run buildpackagingvueThe front-end project
  2. app.pyFile to run
  3. Open thehttp://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…