-
Notifications
You must be signed in to change notification settings - Fork 0
/
4. http_methods.py
60 lines (47 loc) · 1.63 KB
/
4. http_methods.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# coding: utf-8
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
'''
By default, the Flask route responds to the GET requests.
However, this preference can be altered
by providing methods argument to route() decorator.
'''
'''
Create an HTML form and use the POST method to send form data to a URL.
Save the following script as login.html
<html>
<body>
<form action = "http://localhost:5000/login/" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
'''
@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name
@app.route('/login/', methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success', name = user))
else:
user = request.args.get('nm')
return redirect(url_for('success', name = user))
if __name__ == '__main__':
app.run(debug = True)
'''
Open login.html in the browser, enter name in the text field and click Submit.
Form data is POSTed to the URL in action clause of form tag.
http://localhost/login is mapped to the login() function.
Since the server has received data by POST method,
value of ‘nm’ parameter obtained from the form data is obtained by
user = request.form['nm']
If data received on server is by the GET method,
The value of ‘nm’ parameter is obtained by
user = request.args.get(‘nm’)
note: args is dictionary object
containing a list of pairs of form parameter and its corresponding value.
'''