用flask静态服务器运行angular


之所以用这种方案,主要是比nodejs express静态服务器还简单,而且打包成exe更方便,node+pkg打包成1个exe文件,不利于更新angular工程,而flask+cx_freeze打包,文件夹结构还在,直接更新angular工程代码就好。

一、支持angular的flask静态服务器

参考 https://stackoverflow.com/questions/54147782/how-to-use-angular-build-assets-inside-python-flask-static

假定angularbuild之后的dist文件夹(build之后 indexl.html所在的目录)是package.nw,放在flask工程根目录static里

一个app.py就可以搞定:

from flask import Flask, render_template
from flask_cors import CORS

app = Flask(__name__, static_url_path = '',  static_folder= 'static/package.nw', template_folder='static/package.nw')
app.config['SECRET_KEY'] = 'secret!'
app.config['JSON_AS_ASCII'] = False

CORS(app, supports_credentials=True)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    print('package.nw静态服务器')
    app.run(host='0.0.0.0', port=5000)

3个参数,但其实是从2方面配置:

1  flask从什么文件夹读取静态文件

2  flask用什么url发布静态文件

1 static_url_path = '' 必须有。

这是描述静态文件在url里http://host:port/之后的访问路径。index.html里如何通过url访问到静态文件

如果没有这句,打开index.html后,会跟着出现请求其他静态js ico文件时 flask报404错误。

flask默认静态资源都是有前缀的:形如host/static/XXX.js,html模板里也得这么写。  但angular打包的index.html引用时资源,都是没有/static的:比如各个