HTML форма (python, flask): у кнопки есть уникальный параметр для метода - PullRequest
0 голосов
/ 13 апреля 2020

У меня сейчас хорошая форма HTML, которая вызывает метод с помощью кнопки.

Я хочу создать несколько новых кнопок, которые вызывают один и тот же метод, но каждая из которых передает свой параметр.

Конкретный c вариант использования: моя кнопка прямо сейчас выбирает случайный альбом с get_random_album().

Я хочу сделать "Джаз", "Классика" и "Рок" кнопки, которые соответственно вызывают get_random_album(genre=<genre>).

MVE:

from flask import Flask,redirect
# Below import commented out for MVE
# from discogs import get_random_album

# TODO: look at more advanced form builders

# Create app instance
app = Flask(__name__)

# Create homepage with button
@app.route("/")
def home():
    return """
    <html><body>
    <h2> Spin yo records </h2>
        <form action="/query">
            <input type='submit' value="I'm Feeling Lucky">
    </body></html>
    """

# Backend query to discogs
@app.route("/query")
def link():
    # return redirect(get_random_album())
    # Real implementation commented out
    # Scratch implementation here
    def get_random_album(genre=None):
        url = "https://www.google.com" 
        if genre == 'Jazz':
            return url + "/search?q=jazz"
        if genre == 'Classical':
            return url + "/search?q=classical"
        if genre == 'Rock':
            return url + "/search?q=rock"
        return url

    return redirect(get_random_album())
# Run app
if __name__ == "__main__":
    app.run(debug=True,port=600)

Фактический проект

1 Ответ

1 голос
/ 13 апреля 2020

Сначала создайте кнопки с тем же name, но с разными value

@app.route("/")
def home():
    return """
    <html>
    <body>
    <h2> Spin yo records </h2>

        <form action="/query">
            <input type="submit" name="selected_genre" value="Jazz">
            <input type="submit" name="selected_genre" value="Classic">
            <input type="submit" name="selected_genre" value="Rock">
            <input type="submit" name="selected_genre" value="I'm Feeling Lucky">
        </form>
    </body>
    </html>
    """

И затем вы можете выбрать value с помощью request и имя, используемое в кнопках

from flask import request
import random

@app.route("/query")
def link():
    allowed_values = ('Jazz', 'Classic', 'Rock')

    genre = request.args.get("selected_genre")

    # "I'm Feeling Lucky"
    if genre not in allowed_values:
        genre = random.choice(allowed_values)

    genre = genre.lower()

    url = f"https://www.google.com/search?q={genre}" 

    return redirect(url)

Полный пример

from flask import Flask, redirect, request
import random

app = Flask(__name__)

@app.route("/")
def home():
    return """
    <html>
    <body>
    <h2> Spin yo records </h2>

        <form action="/query">
            <input type="submit" name="selected_genre" value="Jazz">
            <input type="submit" name="selected_genre" value="Classic">
            <input type="submit" name="selected_genre" value="Rock">
            <input type="submit" name="selected_genre" value="I'm Feeling Lucky">
        </form>
    </body>
    </html>
    """


@app.route("/query")
def link():
    allowed_values = ('Jazz', 'Classic', 'Rock')

    genre = request.args.get("selected_genre")

    if genre not in allowed_values:
        genre = random.choice(allowed_values)

    genre = genre.lower()

    url = f"https://www.google.com/search?q={genre}" 

    return redirect(url)


if __name__ == "__main__":
    app.run(debug=True,port=600)

В предыдущей версии он отправляет value в URL ie. /query?selected_genre=Rock - чтобы каждый мог видеть это или просто попытаться использовать собственное значение. И именно поэтому я использовал allowed_values, чтобы заблокировать его.

Чтобы скрыть выбранный жанр от URL, вы должны использовать:

  • <form ... method="POST">
  • @app.route(..., methods=['GET', 'POST']) (или methods=['POST'])
  • request.form вместо request.args

Полный пример

from flask import Flask, redirect, request
import random

app = Flask(__name__)

@app.route("/")
def home():
    return """
    <html>
    <body>
    <h2> Spin yo records </h2>

        <form action="/query" method="POST">
            <input type="submit" name="selected_genre" value="Jazz">
            <input type="submit" name="selected_genre" value="Classic">
            <input type="submit" name="selected_genre" value="Rock">
            <input type="submit" name="selected_genre" value="I'm Feeling Lucky">
        </form>
    </body>
    </html>
    """

@app.route("/query", methods=['GET', 'POST'])
def link():
    allowed_values = ('Jazz', 'Classic', 'Rock')

    genre = request.form.get("selected_genre")

    if genre not in allowed_values:
        genre = random.choice(allowed_values)

    genre = genre.lower()

    url = f"https://www.google.com/search?q={genre}" 

    return redirect(url)


if __name__ == "__main__":
    app.run(debug=True, port=600)

Если хотите чтобы использовать другой текст на кнопке, но при этом отправлять тот же value, тогда вам может потребоваться скрытый <input> с value, но тогда каждая кнопка будет нуждаться в разделении <form>

@app.route("/")
def home():
    return """
    <html>
    <body>
    <h2> Spin yo records </h2>

        <form action="/query" method="POST">
            <input type="hidden" value="Jazz" name="selected_genre">
            <input type="submit" value="The Best Jazz Music">
        </form>

        <form action="/query" method="POST">
            <input type="hidden" value="Classic" name="selected_genre">
            <input type="submit" value="The Best Classic Music">
        </form>

        <form action="/query" method="POST">
            <input type="hidden" value="Rock" name="selected_genre">
            <input type="submit" value="The Best Rock Music">
        </form>

        <form action="/query" method="POST">
            <input type="hidden" value="random" name="selected_genre">
            <input type="submit" value="I'm Feeling Lucky">
        </form>
    </body>
    </html>
    """

Или вам придется использовать <button> вместо <input>

@app.route("/")
def home():
    return """
    <html>
    <body>
    <h2> Spin yo records </h2>
        <form action="/query" method="POST">
            <button type="submit" name="selected_genre" value="Jazz">The Best Jazz Music</button>
            <button type="submit" name="selected_genre" value="Classic">The Best Classic Music</button>
            <button type="submit" name="selected_genre" value="Rock">The Best Rock Music</button>
            <button type="submit" name="selected_genre" value="random">I'm Feeling Lucky</button>
        </form>
    </body>
    </html>
    """
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...