【问题标题】:Failed to run python flask app (404, 405 response code)python flask app运行失败(404、405响应码)
【发布时间】:2018-08-12 02:32:36
【问题描述】:

做第二个 CS50 项目,我要做的第一件事是创建一个 index.html 页面,我必须在其中输入用户名并显示它。我必须使用 SocketIO 来让其他用户也能看到它。

当我运行我的 Flask 应用程序并转到页面时,我在控制台中收到以下文本:

flask run
 * Serving Flask-SocketIO app "main.py"
 * Forcing debug mode on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 399-480-796
127.0.0.1 - - [2018-08-12 05:17:54] "GET / HTTP/1.1" 200 1123 0.008075
127.0.0.1 - - [2018-08-12 05:17:55] "GET /index.js HTTP/1.1" 404 342 0.000796
127.0.0.1 - - [2018-08-12 05:17:55] "GET /static/index.js HTTP/1.1" 404 342 0.000821
127.0.0.1 - - [2018-08-12 05:17:55] "GET /static/index.js HTTP/1.1" 404 342 0.003149

但是当我按下“Enter”按钮时,它会因“不允许的方法”而失败,而我在控制台中看到的是:

127.0.0.1 - - [2018-08-12 05:18:01] "POST / HTTP/1.1" 405 323 0.003737

project_folder/main.py:

from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config["SECRET_KEY"] = 'dev'
socketio = SocketIO(app)

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

@socketio.on("new user")
def new(data):
    username = data["username"]
    emit('plus user', {'username': username}, broadcast=True)

project_folder/templates/layout.html:

<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
    <script type='text/javascript' src='index.js'></script>
    <script src='{{ url_for('static', filename='index.js') }}'></script>
  </head>
  <body>
    <div class="container">
      {% block body %}
      {% endblock %}
    </div>
  </body>
</html>

project_folder/templates/index.html:

{% extends "layout.html" %}

{% block title %}
  Sign In
{% endblock %}

{% block body %}

  <form action="{{ url_for('index') }}" method='post'>

    <h1>Hi! In this chat room you can be whoever you want.</h1>
    <h2>The only thing I ask you is to tell me the name I'll be calling you.</h2>
    <h3>You don't have to tell me your real name.</h3>
    <h4>Enjoy.</h4>
    <br>

    <div class="form-group">
      <input class="form-control" name='username' autofocus placeholder="Username">
    </div>

    <div class="formgroup">
      <button id='newuser' class='btn btn-primary' data-new='username'>Enter</button>
    </div>

    <ul id="users"></ul>
  </form>

{% endblock %}

project_folder/templates/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', () => {

    document.querySelector('#newuser').onclick = () => {
      const username = newuser.dataset.new;
      socket.emit('new user', {'username': username})
    };
  });

});

// When a new user has registered , add to the ul
socket.on('plus user', data => {
  const li = document.createElement('li');
  li.innerHTML = data.username;
  document.querySelector('#users').append(li);
});

这几乎是相同的任务,我从讲座视频中提取了大约 90% 的代码,但并没有错。我做错了什么?

【问题讨论】:

    标签: python flask socket.io


    【解决方案1】:

    在 Layout.html 中

    您将 Index.Js 路由到错误的文件夹,或者将静态替换为模板,如下所示

    <script src='{{ url_for('templates', filename='index.js') }}'></script>
    

    或者在根目录下新建一个文件夹static,即project_folder 如果您想使用:

    <script src='{{ url_for('static', filename='index.js') }}'></script>
    

    通常首选第二种方式。

    【讨论】:

    • 我尝试了第一种方法,它会导致错误“BuildError:无法使用值 ['filename'] 为端点 'templates' 构建 url。你的意思是“静态”吗?所以我对第二种方式有疑问。如果我创建一个名为“static”的文件夹并将“index.js”文件放在这里,我如何从我的 layout.html 文件中引用它?
    • 哦,是的!我忘记了如果您尝试更改静态目录,那么您需要告诉 Flask 配置您将使用其他一些文件夹,您可以通过 app["STATIC_FOLDER"]="YourFolderName" 执行此操作。我猜但不太确定,您只需将 &lt;script src='{{ url_for('static', filename='index.js') }}'&gt;&lt;/script&gt; 放在 layout.html 中,其余工作将由 url_for 函数完成
    【解决方案2】:

    您的路由似乎有问题。您的表单提交到“index”的 URL 模式,但您的路由仅处理“/”路由。

    改变

    @app.route("/")
    

    在 main.py 中跟随:

    @app.route("/index")
    

    【讨论】:

    • 我想这很好,因为如果我更改路由,我会收到此错误:“在服务器上找不到请求的 URL。如果您手动输入了 URL,请检查您的拼写并重试。”
    猜你喜欢
    • 2018-07-05
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多