Flask: Difference between revisions
From charlesreid1
(→Routes) |
|||
| Line 69: | Line 69: | ||
return jsonify(d) | return jsonify(d) | ||
</pre> | </pre> | ||
===Rendering templates=== | |||
This example shows how to take an integer variable from the URL and use it on an HTML template page: | |||
<pre> | |||
from flask import Flask, render_template | |||
... | |||
@app.route('/sample/<int:sample_number>') | |||
def sample(sample_number): | |||
render_template('sample.html') | |||
</pre> | |||
The contents of <code>sample.html</code> are given below: | |||
<pre> | |||
<html> | |||
<head> | |||
<title>{{title}}</title> | |||
</head> | |||
<body> | |||
<h2>{{title}}</h2> | |||
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula.</p> | |||
</body> | |||
</html> | |||
</pre> | |||
===Raising errors=== | ===Raising errors=== | ||
Revision as of 13:42, 23 August 2018
Basics
Basic App
Run a Flask app that is bound to all network interfaces on the host, and listens on port 5000:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
If host and port are not specified, flask will only listen on the local network interface on port 5000.
if __name__ == '__main__':
app.run(debug=True)
Routes
Simple hello world route
A simple hello world route:
from flask import Flask
...
@app.route('/hello')
def hello():
return "Hello, World!"
Returning HTML
To return HTML, we can return it in a string:
from flask import Flask
...
@app.route('/get_html')
def get_html():
return "<h2>Flask Returns HTML Code</h2>"
Returning JSON
If we are writing an API, we want routes that return JSON. we can use Flask's jsonify function:
from flask import Flask, jsonify
...
@app.route('/list')
def list():
d = {'a' : 1, 'b' : 2, 'c' : 3}
return jsonify(d)
Rendering templates
This example shows how to take an integer variable from the URL and use it on an HTML template page:
from flask import Flask, render_template
...
@app.route('/sample/<int:sample_number>')
def sample(sample_number):
render_template('sample.html')
The contents of sample.html are given below:
<html>
<head>
<title>{{title}}</title>
</head>
<body>
<h2>{{title}}</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula.</p>
</body>
</html>
Raising errors
To abort with a 400 (server error), use the abort function
from flask import Flask, abort
...
@app.route('/how_to_abort')
def how_to_abort():
import random
if random.random() < 0.5:
abort(400)
else:
return "<h2>Hi there!</h2>"
POST Endpoints
To deal with data sent via a POST request, use the request variable, imported from Flask:
from flask import Flask, jsonify, abort, request
...
@app.route('/qwerty', methods=['POST'])
def qwerty():
if not request.json:
abort(400)
data = request.json
if
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
abort(400)
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
}
tasks.append(task)
return jsonify({'task': task}), 201
and the corresponding output when we POST data to the server:
$ curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://localhost:5000/todo/api/v1.0/tasks
HTTP/1.0 201 Created
Content-Type: application/json
Content-Length: 104
Server: Werkzeug/0.8.3 Python/2.7.3
Date: Mon, 20 May 2013 05:56:21 GMT
{
"task": {
"description": "",
"done": false,
"id": 3,
"title": "Read a book"
}
}
Packaging Flask Apps
Deploying Flask Web App as Submodule
Instructions for deploying a Flask web app as a submodule in a Python module:
First, your directory structure will look something like this:
README.md
setup.py
mymodule/
__init__.py
submodule1/
submodule2/
webapp/
__init__.py
additional_routes.py
templates/
[...]
static/
[...]
Next, your setup.py file will look something like this:
config = {
'description': 'My Module',
'install_requires': ['flask'],
'packages': ['mymodule','mymodule.submodule1','mymodule.submodule2','mymodule.webapp'],
'include_package_data' : True,
'package_data' : {
'templates' : 'mymodule/webapp/templates/*',
'static' : 'mymodule/webapp/static/*'
},
'scripts': [],
'name': 'mulch',
'zip_safe' : False
}
setup(**config)
The key lines here are include_package_data and package_data, which will also install your non-Python template and static files with your module.
Now you can install your module with python setup.py install, and your module is available to use from anywhere.
To create an instance of your module's web app from anywhere, follow these steps:
1. Install the module
2. Import the webapp submodule:
from mymodule.webapp import *
3. Start the webapp:
app.run(debug=True)
Voila!
Resources
Basics
The Flask mega tutorial is really handy: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
Micro blog example: https://stormpath.com/blog/build-a-flask-app-in-30-minutes
Bundling
Official flask site: patterns for distributing flask apps: http://flask.pocoo.org/docs/patterns/distribute/
Packaging a flask app: http://www.plankandwhittle.com/packaging-a-flask-web-app/