【发布时间】:2019-03-22 11:34:59
【问题描述】:
尝试在本地运行烧瓶应用程序时遇到以下问题:我使用了 URL_FOR 并直接尝试指定我的 index.js 文件的路径,但它总是加载一个 不同的 index.js 当我尝试在本地运行烧瓶应用程序时。
文件夹设置:
folder with source code of sample projects from a course i'm doing
-project1
--templates
---index.html
--static
---index.js
--application.py
-project2
--templates
---index.html
--static
---index.js
--application.py
-project3
--templates
---index.html
--static
---index.js
--application.py
-...
--> 假设我现在在终端中的 project2 中。
我正在运行 export FLASK_APP=application.py,然后是 python3 -m flask run,它按照以下方式在 localhost 5000 上为应用程序提供服务:
* Serving Flask-SocketIO app "application.py"
* Forcing debug mode off
到目前为止看起来还不错。然而,有趣的是——> 当我导航到 http://127.0.0.1:5000/ 和 inspect 时,它总是引用我的 /project1/static 文件夹中的 index.js。
我在 index.html 中所做的事情:
<!DOCTYPE html>
<html>
<head>
<script src="{{ url_for('static', filename='index.js') }}"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<title>Vote</title>
</head>
<body>
<ul id="votes">
</ul>
<hr>
<button data-vote="yes">Yes</button>
<button data-vote="no">No</button>
<button data-vote="maybe">Maybe</button>
</body>
</html>
我的 index.js 是什么样子的:
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// When connected, configure buttons
socket.on('connect', () => {
// Each button should emit a "submit vote" event
document.querySelectorAll('button').forEach(button => {
button.onclick = () => {
const selection = button.dataset.vote;
socket.emit('submit vote', {'selection': selection});
};
});
});
// When a new vote is announced, add to the unordered list
socket.on('announce vote', data => {
const li = document.createElement('li');
li.innerHTML = `Vote recorded: ${data.selection}`;
document.querySelector('#votes').append(li);
});
});
我的 application.py 是什么样子的:
import os
import requests
from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("submit vote")
def vote(data):
selection = data["selection"]
emit("announce vote", {"selection": selection}, broadcast=True)
if __name__ == '__main__':
app.run()
我的答案
- 我自己找到了一种有趣的方法来修复它:如果我只是将它重命名为“main.js”并引用它,它就可以工作。
问题
- 知道这里有什么问题吗?我是否以错误的方式引用 index.js?
- 不可能在一个父文件夹中不能有多个 index.js 文件……对吧?
【问题讨论】:
标签: javascript python flask