2015-05-19 46 views
1

我知道这可能是微不足道的,但我似乎无法弄清楚如何将我的网页上的用户提交的数据发送到服务器端。我正在制作一个简单的网络应用程序,它接收用户的单词,然后使用Python来计算服务器端的音节数。使用Flask的表单处理

我渲染页面使用烧瓶:

@app.route('/') 
def hello(): 
    webPage = open('pg.html','r') 
    return webPage.read() 

JavaScript我有一个form

<form method="get"><br><br> 
    Enter a Word: <br> 
<input type="text" name="name"><br><br> 
<input type="submit" value="Submit"> 
     </form> 

当用户提交一个词来这种形式,我怎么跟Python找回?

我读过约​​和POST方法,但我仍然很困惑。

+1

表单是对操作的“POST”请求。看看[this](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms) –

回答

0

考虑到你知道关于GETPOST,这里是重要的位。

显示家庭(你好)页面现在

from flask import render_template 

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

,在hello.html(注意动作和方法):如果你注意到

<html> 
    <head></head> 
    <body> 
     <form method="POST" action="/testpost"> 
      Enter a Word: <br> 
      <input type="text" name="name"><br><br> 
      <input type="submit" value="Submit"> 
     </form> 
    </body> 
</html> 

,方法是POST这意味着,你的数据是作为POST发送到服务器的。现在处理POST要求,我们可以考虑以下因素:

现在POST处理

@app.route('/testpost', methods = ['POST']) 
def postTesting(): 
    name = request.form['name'] 
    print name #This is the posted value 

你看,request.form包含解析表单数据。

+0

现在,有一个问题,究竟是什么action =“/ testpost “干嘛?是否创建一个新页面? –

+0

@DeseanAbraham这是你的'POST'的URL。 (一个程序的URI)所以,当你说:'action =“/ testpost”',它表示一个URL为带有POST数据的“http:// localhost/testpost”。 (考虑localhost是你的托管服务器) –

+0

如果你想发送数据,这是必要的。 (不是唯一的方式)。 “testpost”只是一个例子。你可以提供你想要的任何URI名称。它会将您的数据发布到该URI。检查[this](http://stackoverflow.com/questions/3477333/what-is-the-difference-between-post-and-get)和[this](https://developer.mozilla.org/en- US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) –