【问题标题】:How to use <input> in Flask如何在 Flask 中使用 <input>
【发布时间】:2020-07-18 15:44:42
【问题描述】:

我想使用来自 html 的输入作为我的 Flask 中的一个函数:

from flask import Flask, url_for, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)   
    
@app.route("/")
def homepage() :
    return render_template("index.html", make_cards = make_cards(user_deck), make_cards_u = user_cards(), result = find_winner(user_deck, computer_deck))
    
class user_cards (FlaskForm):
    SUITS = StringField('suits', validators=[DataRequired()])
   
    SEQUENCE = StringField('stringfield', validators=[DataRequired()])
    
    submit = SubmitField('Check!')

    
if __name__ == '__main__':
    # print(poker_hand_ranking(["10H", "JH", "QH", "AH", "KH"]))
    user_deck = user_cards()
    computer_deck = make_cards(user_deck)
    find_winner(user_deck, computer_deck)
    app.run(debug=True)
  

我希望这个程序与用户交互,所以我没有定义make_cards_u,并且想要卡片的用户输入。所以我的HTML如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF=8">
        <title> Poker Game </title>
        <link rel="stylesheet" href ="{{url_for('static', filename='css/style.css')}}">
    </head>
    
    <body>
        <h1> Welcome to Gaming Poker</h1>
        <h3>Computer cards: {{make_cards}} <br>
        Your cards: <input> {{make_cards_u}} </input> </h3>
        <h2>Results: {{result}}</h2>
    </body>
</html>

但是,我收到一个错误

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that
needed to interface with the current application object in some way.
To solve this, set up an application context with app.app_context(). 
See the documentation for more information.

我的其他python代码如下:

SEQUENCE = ['2', '3', '4', '5', '6', '7', '8', '9', '10',
            'J', 'Q', 'K', 'A']
VALUES = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
          '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
SUITS = ['S', 'H', 'C', 'D']

# The computer gets 5 cards
def make_cards(deck = None): 
    result_deck = set()
    while (len(result_deck) < 5):
        card = random.choice(SEQUENCE) + random.choice(SUITS)
        if (deck != None):
            if (card not in deck): 
                result_deck.add(card)
        else:
            result_deck.add(card)
    return list(result_deck)

def find_winner(user_deck, computer_deck):
    user_rank = poker_hand_ranking(user_deck)
    computer_rank = poker_hand_ranking(computer_deck)
    if (user_rank[0] < computer_rank[0]):
        print('Winner is user')
    elif (user_rank[0] > computer_rank[0]):
        print('Winner is computer')
    else:
        print('Draw!')
    print('User:', user_deck, user_rank[1])
    print('Computer:', computer_deck, computer_rank[1])

另外,我有在 if elif 语句中定义变量的代码,这太长了,无法提出这个问题。 poker_hand_ranking 定义如下:

def poker_hand_ranking(deck):
    hand = deck
    suits = sorted([card[-1] for card in hand])
    faces = sorted([card[:-1] for card in hand])
    if is_royal_flush(hand, suits, faces):
        return 1, "You have a Royal Flush"
    elif is_straight_flush(hand, suits, faces):
        return 2, "You have a Straight Flush"
    elif is_four_of_a_kind(hand, suits, faces):
        return 3, "You have four of a Kind"
    elif is_full_house(hand, suits, faces):
        return 4, "You have a full House"
    elif is_flush(hand, suits, faces):
        return 5, "You have a flush"
    elif is_straight(hand, suits, faces):
        return 6, "You have a straight"
    elif is_three_of_a_kind(hand, suits, faces):
        return 7, "You have a three of a Kind"
    elif is_two_pairs(hand, suits, faces):
        return 8, "You have a two Pair"
    elif is_one_pair(hand, suits, faces):
        return 9, "You have a pair"
    else:
        #if none of these counts:
        return 10, "High Card"

如何让用户输入在 Flask 中进行交互?

【问题讨论】:

  • 在问题中包含make_cardsfind_winner 方法。
  • @arsho 谢谢你,我已经这样做了!

标签: python html flask flask-wtforms


【解决方案1】:

您可以使用模板中的表单user_cards 创建一个HTML 表单,然后在flask 代码中处理提交的值。

您可以使用生成的卡片组检查用户提交的值,然后决定谁赢得游戏。

这是我的方法。由于我没有扑克游戏的全部逻辑,所以我随机返回了扑克手牌排名。你可以用原来的方法替换它。

目录结构:

.
├── requirements.txt
├── sample_form.py
└── templates
    └── index.html

requirements.txt:

click==7.1.2
Flask==1.1.2
Flask-WTF==0.14.3
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
Werkzeug==1.0.1
WTForms==2.3.1

sample_form.py:

import random
from flask import Flask, url_for, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)   
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

SEQUENCE = ['2', '3', '4', '5', '6', '7', '8', '9', '10',
            'J', 'Q', 'K', 'A']
VALUES = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
          '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
SUITS = ['S', 'H', 'C', 'D']

# The computer gets 5 cards
def make_cards(deck = None): 
    result_deck = set()
    while len(result_deck) < 5:
        card = random.choice(SEQUENCE) + random.choice(SUITS)
        if deck != None:
            if card not in deck: 
                result_deck.add(card)
        else:
            result_deck.add(card)
    return list(result_deck)

def find_winner(user_deck, computer_deck):
    user_rank = poker_hand_ranking(user_deck)
    computer_rank = poker_hand_ranking(computer_deck)
    if user_rank[0] < computer_rank[0]:
        return 'Winner is user'
    elif user_rank[0] > computer_rank[0]:
        return 'Winner is computer'
    else:
        return 'Draw!'

def poker_hand_ranking(deck):
    return random.choice(["some", "many"])

class user_cards(FlaskForm):
    suits = StringField('suits', validators=[DataRequired()])   
    sequence = StringField('sequence', validators=[DataRequired()])    
    submit = SubmitField('Check!')
    
@app.route("/", methods=['GET', 'POST'])
def homepage():
    card_form = user_cards()
    if card_form.validate_on_submit():
        user_deck = ["{}{}".format(card_form.suits.data,
                                   card_form.sequence.data)]
        computer_deck = make_cards()
        result = find_winner(user_cards, computer_deck)
        return render_template('index.html', form=card_form,
                               user_deck=user_deck,
                               computer_deck=computer_deck,
                               result=result)
    return render_template('index.html', form=card_form)

templates/index.html:

<html>
<head>
    <title>
        Card Form
    </title>
</head>
<body>
    <h1> Welcome to Gaming Poker</h1>
    <h2>Input Cards</h2>
    <form method="POST" action="/">
        {{ form.csrf_token }}
        {{ form.suits.label }} {{ form.suits(size=20) }}
        {{ form.sequence.label }} {{ form.sequence(size=20) }}
        {{ form.submit }}
    </form>    

    {% if computer_deck %}
    <h3>Computer cards: {{computer_deck}} </h3>
    {% endif %}

    {% if user_deck %}
    <h3>Your cards: {{user_deck}}</h3>
    {% endif %}

    {% if result %}
    <h2>Results: {{result}}</h2>
    {% endif %}
        
</body>
</html>

输出:

表单提交前:

表单提交后:

免责声明:

我实际上并没有选择正确的获胜者。请包括你的逻辑。希望我的 sn-ps 将帮助您了解如何使用 Flask-wtf 包在 Flask 中使用表单。

参考:

【讨论】:

  • 一个名为“'user_cards'的实例没有'data'成员pylint(no-member)的问题在我尝试时发生了
  • 我想,这是对pylint 的警告。您需要安装所需的软件包。提交表单后user_cards 具有包含表单数据的data 属性。
  • 对不起一个愚蠢的问题,但我正在自学。我需要安装哪些软件包?
  • 我已经更新了部分代码。尝试当前的烧瓶代码。我认为您已经安装了所需的软件包。如果没有,安装requirements.txt中提到的包。
  • 你试过我的sn-ps吗?我建议首先运行我的代码。然后尝试插入您的逻辑。在您的代码中,您正在 __main__ 块中进行操作,这可能会出现上述错误。
猜你喜欢
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 2021-09-29
  • 2021-08-10
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多