Kvo*_*ute 3 javascript python flask
我正在尝试使用 Flask 访问一个 csv 文件和两个 json 文件,这些文件保存在名为 static 的文件夹中。即使我在代码中提到了静态文件夹,我的 map.js 文件运行时仍然遇到以下 404 问题。
"GET / HTTP/1.1" 200
"GET /%7B%7B%20url_for('static',%20filename%20=%20'topo_E08000025.json')%20%7D%7D HTTP/1.1" 404
"GET /%7B%7B%20url_for('static',%20filename%20=%20'/static/sampleproperty3.csv')%20%7D%7D HTTP/1.1" 404
"GET /%7B%7B%20url_for('static',%20filename%20=%20'/static/sampleproperty3.csv')%20%7D%7D HTTP/1.1" 404
Run Code Online (Sandbox Code Playgroud)
我到处都看过,但似乎无法弄清楚出了什么问题。
我希望代码能够获取静态文件夹中的数据,而不是返回 404 错误。
蟒蛇代码:
from flask import Flask,render_template, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('map.html')
if __name__== '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
地图html代码:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://rawgit.com/nstrayer/slid3r/master/dist/slid3r.js"></script>
<script src = "https://unpkg.com/topojson@3.0.2/dist/topojson.js"></script>
<script src = "https://d3js.org/colorbrewer.v1.min.js"></script>
<script src = "{{ url_for('static', filename = 'mapFunctions.js') }}"></script>
<link rel="stylesheet" href= "{{ url_for('static', filename = 'map.css') }}">
</head>
<body style = "background-color:gray">
<script src = 'static/map.js' ></script>
</body>
Run Code Online (Sandbox Code Playgroud)
地图 JavaScript 代码:
const svgHeight = 550;
const svgWidth = $(window).width(); // Uses Jquery to find the width of the window and set the svg width to that so it fills up the entire window
const svgPadding = 500;
let active = d3.select(null);
let filteredData ;
let radicusScale ;
let selected;
let originalTranslation ;
let locationLsoas = d3.json("topo_E08000025.json");
let locationWards = d3.json("topo_ward.json");
let properties = d3.csv("sampleproperty3.csv");
Run Code Online (Sandbox Code Playgroud)
使用渲染的 HTML 文件render_template应位于templates文件夹下,而不是static.
这些 HTML 文件使用的文件(CSS/JS)应位于static文件夹下。
我强烈建议使用像 PyCharm 这样的 IDE 并从一个空白flask项目开始。这将为您提供一个开始模板。
供您参考,示例层次结构应如下所示:
|static/
|---css/
|------style.css
|templates/
|---index.html
|app.py
Run Code Online (Sandbox Code Playgroud)
我的 app.py 代码:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template("index.html")
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
我的 index.html 代码(注意我访问 css 文件的方式):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" type="text/css">
</head>
<body>
<h1>Header</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。祝你好运。