Flask и Python, метод не разрешен при попытке чтения из формы - PullRequest
0 голосов
/ 16 февраля 2019

Я хочу прочитать четыре имени пользователя из формы, бросить их в def index и затем установить переменную ilu, зависит от того, сколько строк username1 и т. Д. Не являются пустыми строками, но после того, как я ввожу имена пользователей и нажимаю gotowe Кнопка Я получаю метод не разрешен: (

Я видел другие подобные вопросы здесь, но извините, я не могу понять решения.

Это мой первый раз здесь, я прошу прощения за всеошибки в этом вопросе. Я потерял почти всю надежду: <Я не знаю, что делать. </p>

nazwy_graczy.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block form %}

    <form method="post" action="http://localhost:5000/index">
        <div>
            <p><input type="text" class="form-control" id="username1" name="username" placeholder="Wpisz nazwę użytkownika"></p>
            <p><input type="text" class="form-control" id="username2" name="username" placeholder="Wpisz nazwę użytkownika"></p>
            <p><input type="text" class="form-control" id="username3" name="username" placeholder="Wpisz nazwę użytkownika"></p>
            <p><input type="text" class="form-control" id="username4" name="username" placeholder="Wpisz nazwę użytkownika"></p>
        </div>

    </form>

<a href="/index"><button type="submit" class="btn btn-primary">Gotowe</button></a>


{% endblock %}

</body>
</html>

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Strona</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    {% extends "hand1.html" %}
    {% block tabela%}

     <table style="width:100%">
      <tr>
        <th>Gracz</th>
        <th>Phase</th>
        <th>Punkty</th>
      </tr>

      <tr style="text-align=center; ">
        <td>{{user1}}</td>
        <td>{{point}}</td>
        <td>{{phase}}</td>
      </tr>
        <tr style="text-align=center; ">
        <td>{{user2}}</td>
        <td>{{point}}</td>
        <td>{{phase}}</td>
      </tr>
        <tr style="text-align=center; ">
        <td>{{user3}}</td>
        <td>{{point}}</td>
        <td>{{phase}}</td>
      </tr>
        <tr style="text-align=center; ">
        <td>{{user4}}</td>
        <td>{{point}}</td>
        <td>{{phase}}</td>
      </tr>

    </table>
    {% endblock %}
</body>
</html>

app.py:

from flask import Flask, render_template, request
from players import Player
import engine
import cards
from random import shuffle

app = Flask(__name__)

# globals start  -----------------------------------------------------

rejected_card = cards.CardsNumbers(1, 1)
dash_length = 140
Q = 0
real_players = []
real_players_f_phases = []
player_decks = []
main_deck = []
players_phases = []
players_names = []
is_new_game = True

# globals end  -------------------------------------------------------


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


@app.route('/index', methods=['GET, POST'])
def index():
    global players_names
    global ilu
    if request.method == 'POST':
        user1 = request.form['username1']
        user2 = request.form['username2']
        user3 = request.form['username3']
        user4 = request.form['username4']

        players_names = [user1, user2, user3, user4]
        ilu = 0

        for u in list(players_names):
            if u != '':
                ilu += 1
    else:
        return 0

    return render_template('index.html', ilu=ilu, user1=user1, user2=user2, user3=user3, user4=user4)


@app.route('/hand1')
def hand1():
    global players_names
    global is_new_game
    global ilu

    if is_new_game:
        is_new_game = False

        new_game(ilu)

    user = players_names[0]
    user.sort_cards_by_number()

    return render_template('hand1.html', hand1=user.show_cards())


def new_game(uniq_amount):
    global real_players
    global real_players_f_phases
    global players_decks
    global main_deck
    global players_phases
    global players_names
    global Q

    Q = engine.queue(uniq_amount)

    all_cards = cards.rozdaj_karty(uniq_amount)
    players_decks = all_cards[0:-1]
    main_deck = all_cards[-1]
    shuffle(main_deck)

    for i in range(uniq_amount):
        real_players.append(Player(players_names[i], players_decks[i]))

    for i in range(len(real_players)):
        real_players_f_phases.append(False)


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

Просмотр источника страниц:

Первая страница:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="post" action="http://localhost:5000/index">
    <div>
        <p><input type="text" class="form-control" id="username1" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
        <p><input type="text" class="form-control" id="username2" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
        <p><input type="text" class="form-control" id="username3" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
        <p><input type="text" class="form-control" id="username4" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
    </div>

    <input type="submit" value="Submit">
</form>


</body>
</html>

Ошибка:

<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>werkzeug.exceptions.HTTPException.wrap.&lt;locals&gt;.newcls: 400 Bad Request: KeyError: 'username1' // Werkzeug Debugger</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css"
        type="text/css">
    <!-- We need to make sure this has a favicon so that the debugger does
         not by accident trigger a request to /favicon.ico which might
         change the application state. -->
    <link rel="shortcut icon"
        href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
    <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script type="text/javascript">
      var TRACEBACK = 140589934758992,
          CONSOLE_MODE = false,
          EVALEX = true,
          EVALEX_TRUSTED = false,
          SECRET = "NYIRoPSadEHEGDJ1PkU6";
    </script>
  </head>
  <body style="background-color: #fff">
    <div class="debugger">
<h1>werkzeug.exceptions.BadRequestKeyError</h1>
<div class="detail">
  <p class="errormsg">werkzeug.exceptions.HTTPException.wrap.&lt;locals&gt;.newcls: 400 Bad Request: KeyError: 'username1'</p>
</div>
<h2 class="traceback">Traceback <em>(most recent call last)</em></h2>
<div class="traceback">

  <ul><li><div class="frame" id="frame-140589917417656">
  <h4>File <cite class="filename">"/usr/local/lib/python3.7/dist-packages/flask/app.py"</cite>,
      line <em class="line">2309</em>,
      in <code class="function">__call__</code></h4>
  <div class="source"><pre class="line before"><span class="ws"></span> 
    def __call__(self, environ, start_response):
        """The WSGI server calls the Flask application object as the
        WSGI application. This calls :meth:`wsgi_app` which can be
        wrapped to applying middleware."""
        return self.wsgi_app(environ, start_response)
 
    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.name,

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 2295 , в wsgi_app

            try:
                ctx.push()
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)
        finally:

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 1741 , в handle_exception

            # if we want to repropagate the exception, we can attempt to
            # raise it with the whole traceback in case we can do that
            # (the function was actually called from the except part)
            # otherwise, we just raise the error again
            if exc_value is e:
                reraise(exc_type, exc_value, tb)
            else:
                raise e
 
        self.log_exception((exc_type, exc_value, tb))
        if handler is None:

Файл "/usr/local/lib/python3.7/dist-packages/flask/_compat.py", строка 35 , в ререйзе

    from io import StringIO
 
    def reraise(tp, value, tb=None):
        if value.__traceback__ is not tb:
            raise value.with_traceback(tb)
        raise value
 
    implements_to_string = _identity
 
else:
    text_type = unicode

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 2292 , в wsgi_app

        ctx = self.request_context(environ)
        error = None
        try:
            try:
                ctx.push()
                response = self.full_dispatch_request()
            except Exception as e:
                error = e
                response = self.handle_exception(e)
            except:
                error = sys.exc_info()[1]

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 1815 , в full_dispatch_request

            request_started.send(self)
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
        except Exception as e:
            rv = self.handle_user_exception(e)
        return self.finalize_request(rv)
 
    def finalize_request(self, rv, from_error_handler=False):
        """Given the return value from a view function this finalizes
        the request by converting it into a response and invoking the

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 1718 , в handle_user_exception

            return self.handle_http_exception(e)
 
        handler = self._find_error_handler(e)
 
        if handler is None:
            reraise(exc_type, exc_value, tb)
        return handler(e)
 
    def handle_exception(self, e):
        """Default exception handling that kicks in when an exception
        occurs that is not caught.  In debug mode the exception will

Файл "/usr/local/lib/python3.7/dist-packages/flask/_compat.py", строка 35 , в ререйзе

    from io import StringIO
 
    def reraise(tp, value, tb=None):
        if value.__traceback__ is not tb:
            raise value.with_traceback(tb)
        raise value
 
    implements_to_string = _identity
 
else:
    text_type = unicode

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 1813 , в full_dispatch_request

        self.try_trigger_before_first_request_functions()
        try:
            request_started.send(self)
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
        except Exception as e:
            rv = self.handle_user_exception(e)
        return self.finalize_request(rv)
 
    def finalize_request(self, rv, from_error_handler=False):

Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 1799 , в dispatch_request

        # request came with the OPTIONS method, reply automatically
        if getattr(rule, 'provide_automatic_options', False) \
           and req.method == 'OPTIONS':
            return self.make_default_options_response()
        # otherwise dispatch to the handler for that endpoint
        return self.view_functions[rule.endpoint](**req.view_args)
 
    def full_dispatch_request(self):
        """Dispatches the request and on top of that performs request
        pre and postprocessing as well as HTTP exception catching and
        error handling.

Файл "/root/PycharmProjects/projekt_ig/app.py", строка 35 , в индексе

@app.route('/index', methods=['POST'])
def index():
    global players_names
    global ilu
    if request.method == 'POST':
        user1 = request.form['username1']
        user2 = request.form['username2']
        user3 = request.form['username3']
        user4 = request.form['username4']
 
        players_names = [user1, user2, user3, user4]

Файл "/usr/local/lib/python3.7/dist-packages/werkzeug/datastructures.py", строка 431 , в __getitem __

        """
        if key in self:
            lst = dict.__getitem__(self, key)
            if len(lst) > 0:
                return lst[0]
        raise exceptions.BadRequestKeyError(key)
 
    def __setitem__(self, key, value):
        """Like :meth:`add` but removes an existing key first.
 
        :param key: the key for the value.
werkzeug.exceptions.HTTPException.wrap. .newcls: 400 Неверный запрос: KeyError: 'username1'

Это дружественная для копирования / вставки версия трассировки.Вы также можете вставить эту трассировку в gist :создать пасту

Трассировка (последний вызов был последним): Файл "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 2309, в __call__, возвращает файл self.wsgi_app (environment, start_response) "/ usr/local/lib/python3.7/dist-packages/flask/app.py ", строка 2295, в ответе wsgi_app = self.handle_exception (e) файл" /usr/local/lib/python3.7/dist-packages/flask / app.py ", строка 1741, в ререйзе handle_exception (exc_type, exc_value, tb) Файл" /usr/local/lib/python3.7/dist-packages/flask/_compat.py ", строка 35, в ререйзеФайл значения "/usr/local/lib/python3.7/dist-packages/flask/app.py", строка 2292, в ответе wsgi_app = self.full_dispatch_request () File "/usr/local/lib/python3.7/dist-packages / flask / app.py ", строка 1815, в full_dispatch_request rv = self.handle_user_exception (e) Файл" /usr/local/lib/python3.7/dist-packages/flask/app.py ", строка 1718, в handle_user_exception reraise (exc_type, exc_value, tb) Файл "/usr/local/lib/python3.7/dist-packages/flask/_compat.py", строка 35, в файле повышения значения reraise "/ usr / local / lib / python3.7 / dist-packages / flask / app.py ", строка 1813, в файле full_dispatch_request rv = self.dispatch_request ()" /usr/local/lib/python3.7/dist-packages/flask/app.py ", строка 1799, в dispatch_request возвращает self.view_functions [rule.endpoint] (** req.view_args) Файл" /root/PycharmProjects/projekt_ig/app.py ", строка 35, в индексе user1 = request.form ['username1 '] Файл "/usr/local/lib/python3.7/dist-packages/werkzeug/datastructures.py", строка 431, в __getitem__ поднять исключений..newcls: 400 Неверный запрос: KeyError: 'username1'
Отладчик обнаружил исключение в вашем приложении WSGI.Теперь вы можете посмотреть трассировку, которая привела к ошибке. Если вы включите JavaScript, вы также можете использовать дополнительные функции, такие как выполнение кода (если включена функция evalex), автоматическое вставление исключений и многое другое.

Консоль заблокирована

Консоль заблокирована и ее необходимо разблокировать, введя PIN-код.Вы можете найти PIN-код, распечатанный на стандартном выходе вашегооболочка, которая запускает сервер.

PIN:Подтвердите Пин

Ответы [ 2 ]

0 голосов
/ 17 февраля 2019

Я нашел ответ!Все, что мне нужно было сделать, это различить name в <input type="text" class="form-control" id="username1" name="username1" placeholder="Wpisz nazwę użytkownika">

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    {% block form %}

        <form method="post" action="http://localhost:5000/index">
            <div>
                <p><input type="text" class="form-control" id="username1" name="username1" placeholder="Wpisz nazwę użytkownika"></p>
                <p><input type="text" class="form-control" id="username2" name="username2" placeholder="Wpisz nazwę użytkownika"></p>
                <p><input type="text" class="form-control" id="username3" name="username3" placeholder="Wpisz nazwę użytkownika"></p>
                <p><input type="text" class="form-control" id="username4" name="username4" placeholder="Wpisz nazwę użytkownika"></p>
            </div>

        </form>
0 голосов
/ 16 февраля 2019

Попробуйте изменить nazwy_graczy.html что-то вроде:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="post" action="http://localhost:5000/index">
    <div>
        <p><input type="text" class="form-control" id="username1" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
        <p><input type="text" class="form-control" id="username2" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
        <p><input type="text" class="form-control" id="username3" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
        <p><input type="text" class="form-control" id="username4" name="username" placeholder="Wpisz nazwę użytkownika">
        </p>
    </div>

    <input type="submit" value="Submit">
</form>


</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...