簡體   English   中英

每當我嘗試登錄時,我都會收到“405:此 URL 不允許使用的方法”我做錯了什么?

[英]Whenever I try to log in, I receive "405: Method not allowed for this URL" What am I doing wrong?

我已經在這里搜索並發現了一些非常相似的問題,但是由於我是 Python 新手,我發現調試此代碼非常困難。

我正在制作一個簡單的博客應用程序,帶有一個用於登錄的數據庫。 它在 IDE 上完美運行,但是當我嘗試登錄時,我收到 405 錯誤並且“不允許使用方法”。

我做錯了什么?

from flask import Flask, render_template, request, session, \
flash, redirect, url_for, g
import sqlite3


SECRET_KEY = 'abc12345678910111213'
# configuration
DATABASE = 'blog.db'

app = Flask(__name__)
app.config.from_object(__name__)

USERNAME = 'admin'
PASSWORD = 'admin'

def connect_db():
    return sqlite3.connect(app.config['DATABASE'])

@app.route('/', methods=['GET', 'POST'])
def login():
    error = None
    status_code = 200
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME'] or \
            request.form['password'] != app.config['PASSWORD']:
        error = 'Invalid Credentials. Please Try again!'
    status_code = 401
else:
    session['logged_in'] = True
    return redirect(url_for('main'))
return render_template('login.html', error=error), status_code

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

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('login'))


if __name__ == '__main__':
    app.run(debug=True)

這是模板:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Welcome, Friends!</title>
</head>
<body>
 <div class="container">
     {% for message in get_flashed_messages() %}
         <div class="flash">{{ message }}</div>
     {% endfor %}
     {% if error %}
         <p class="error"><strong>Error:</strong> {{ error }}</p>
     {% endif %}
     <!--inheritance-->
     {% block content %}
     {% endblock %}
     <!--end inheritance-->
 </div>
</body>
</html>

您需要在main端點的允許方法中包含POST方法:

@app.route('/main', methods=['GET', 'POST'])
def main():
    # ...
    pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM