Flask textarea到Python Def()

时间:2017-10-17 00:11:55

标签: python flask

基本上我要做的是:

我有一个带有Textarea的简单HTML页面来输入一堆文本,我的用例是每行上的单个代码,如下所示:

1234
5678
1456
etc.

理想情况下,我希望将其纳入Python并能够处理数据并返回结果。所以让我们开始简单,然后将每一行作为一个单独的条目,并在一个函数上运行它,在它前面添加单词“Hi”所以结果是:

Hi 1234
Hi 5678
etc.

到目前为止,我找到了这个工作示例,但我倾向于在尝试某些事情时打破它。

HTML:

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Enter some text</h1>
   <form action="submit" id="textform" method="post">
    <textarea name="text">Hello World!</textarea>
    <input type="submit" value="Submit">
</form>
</body>
</html>

的Python:

From flask import Flask, request
app = Flask(__name__)

@app.route('/')
def main_form():
    return '<form action="submit" id="textform" method="post"><textarea name="text">Hello World!</textarea><input type="submit" value="Submit"></form>'

@app.route('/submit', methods=['POST'])
def submit_textarea():
    return "You entered: {}".format(request.form["text"])

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

示例:

我尝试将textarea提取为字符串,然后将其返回到以下页面:

x = format(request.form["text"]) 
return x

任何帮助或指导将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以使用以下行访问和存储textarea中的文字:

@app.route('/submit', methods=['POST'])
def submit_textarea():
    # store the given text in a variable
    text = request.form.get("text")

    # split the text to get each line in a list
    text2 = text.split('\n')

    # change the text (add 'Hi' to each new line)
    text_changed = ''.join(['<br>Hi ' + line for line in text2])
    # (i used <br> to materialize a newline in the returned value)

    return "You entered: {}".format(text_changed)