General
Install
Local Server
App
app.route(rule, options)
- create a URL for the function
- rule, represents the URL defined
- options, a list of parameters to be forwarded to the underlying Rule object
app.run(host, port, debug, options)
- runs the application on the local development server
- host, default is 127.0.0.1, set to 0.0.0.0 to have server available externally
- port, default is 5000
- debug, True, provides debug information, will reload the app if the code changes; False, otherwise
- options, to be forwarded underlying Werkzeug server
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<h1>Hello World</h1>'
if __name__ == '__main__':
app.run(debug=True)
Define URL
from flask import Flask
app = Flask(__name__)
@app.route('/hello_temp')
def hello_world():
return '<h1>Hello World</h1>'
if __name__ == '__main__':
app.run(debug=True)
http://127.0.0.1:5000/hello_temp
rule, the URL rule as string
endpoint, the registration key for a URL, used to reference the route from other parts of your application
view_func, the function to call
from flask import Flask
app = Flask(__name__)
def hello_world():
return '<h1>Hello World</h1>'
app.add_url_rule('/hello_temp', 'hello_world', hello_world)
if __name__ == '__main__':
app.run(debug=True)
http://127.0.0.1:5000/hello_temp
Variable
URL Route Registrations
from flask import Flask
app = Flask(__name__)
@app.route('/hello/<int:id>')
def hello_world(id):
return '<h1>Hello, '+str(id)+'</h1>'
if __name__ == '__main__':
app.run(debug=True)
http://127.0.0.1:5000/hello/100 # Hello, 100
http://127.0.0.1:5000/hello/world # Not Found
HTTP methods
By default, the Flask route responds to the GET requests
# 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.py
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/success/')
def success(name):
return 'welcome %s' % name
@app.route('/login', methods = ['POST'])
def login():
# POST
user = request.form['nm']
return redirect(url_for('success',name = user))
if __name__ == '__main__':
app.run(debug = True)
login.html
# login.html
<html>
<body>
<form action = "http://localhost:5000/login" method = "get">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
# app.py
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/success/')
def success(name):
return 'welcome %s' % name
@app.route('/login')
def login():
# GET
user = request.args.get('nm')
return redirect(url_for('success',name = user))
if __name__ == '__main__':
app.run(debug = True)
login.html
Reference