Building simple web services application with Flask
Flask is a framework for building WSGI applications.
pip install flask
download postman www.postman.com/product/rest-client/
Let's start with building a simple Hello World application
ROUTING
Use the route() decorator to bind a function to a URL
pip install flask
download postman www.postman.com/product/rest-client/
Let's start with building a simple Hello World application
ROUTING
Use the route() decorator to bind a function to a URL
from flask import Flask #create a Flask application #the argument to Flask is the name of the application's module #since we are running our application in a single file, leave it as __name__ app=Flask(__name__) #relative path to the root of your application @app.route('/') def hello_world(): return 'Hello World!' app.run()
from flask import Flask app=Flask(__name__) @app.route('/input') def input(): return 'receive input here' @app.route('/output') def output(): return 'display output here' app.run()
Let's display a meaningful data as part of our output - GET method
from flask import Flask, jsonify app=Flask(__name__) data=[{'fname':'Steve', 'lname':'Jobbs'},{'fname':'Bill', 'lname':'Gates'}] @app.route('/input') def input(): return 'input here' @app.route('/data', methods=['GET']) def get_data(): return jsonify({'data' : data}) app.run(debug = True)
You can JSONinfy any combination of maps and lists, however the top outer collection cannot be a list.
You can use the URL path to pass the data to the function call:
You can use the URL path to pass the data to the function call:
from flask import Flask, jsonify from markupsafe import escape app=Flask(__name__) data=[{'fname':'Steve', 'lname':'Jobbs'},{'fname':'Bill', 'lname':'Gates'}] @app.route('/input') def input(): return 'input here' @app.route('/data', methods=['GET']) def get_data(): return jsonify({'data' : data}) @app.route('/data/<int:id>', methods=['GET']) def get_data_byid(id): return jsonify({'data' : data[id]}) @app.route('/data/<key>/<value>', methods=['GET']) def get_data_byname(key, value): for item in data: if item[escape(key)] == escape(value): return jsonify({'data' : item}) app.run(debug = True)
Converter Types
Templating
Flask uses Jinja for templating
Flask will look for templates in the templates folder.
Flask will look for templates in the templates folder.
from flask import Flask from flask import render_template app=Flask(__name__) @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name) app.run(debug = True)
html in the templates/hello.html file
<title>Hello HTML</title> {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello, World!</h1> {% endif %}
Creating POST methods:
from flask import Flask, jsonify, request, abort app=Flask(__name__) data=[{'fname':'Steve', 'lname':'Jobbs'},{'fname':'Bill', 'lname':'Gates'}] @app.route('/createperson', methods=['POST']) def create_person(): print(request.json) if not request.json or not 'person' in request.json: abort(400) data.append(request.json['person']) return jsonify({'data' : data}), 201 @app.route('/data', methods=['GET']) def get_data(): return jsonify({'data' : data}) @app.route('/data/', methods=['GET']) def get_data_byid(id): return jsonify({'data' : data[id]}) app.run(debug = True)
Sample POSTMAN request
http://127.0.0.1:5000/createperson
{"person":{"fname":"sergey", "lname":"brin"}}
Processing GET (Query) parameters:
from flask import Flask, jsonify, request, abort app=Flask(__name__) data=[{'fname':'Steve', 'lname':'Jobbs'},{'fname':'Bill', 'lname':'Gates'}] @app.route('/createperson', methods=['POST']) def create_person(): print(request.json) if not request.json or not 'person' in request.json: abort(400) data.append(request.json['person']) return jsonify({'data' : data}), 201 @app.route('/search', methods=['GET']) def search_data(): query = request.args.get('query', '') for item in data: if item['fname'] == query or item['lname'] == query: return jsonify({'data' : [item]}) return jsonify({}) @app.route('/data', methods=['GET']) def get_data(): return jsonify({'data' : data}) @app.route('/data/', methods=['GET']) def get_data_byid(id): return jsonify({'data' : data[id]}) app.run(debug = True)
Processing Images with Web Services
from flask import Flask, send_file, request, abort, make_response from PIL import Image from PIL import ImageFilter app=Flask(__name__) @app.route('/processimage', methods=['POST']) def processimage(): f = request.files['file'] im = Image.open(f) im = im.filter(ImageFilter.BLUR) im.save("images/site.png") return send_file("images/site.png", mimetype='image/png') app.run(debug = True)
file
mario_png64.png |
Handling Session
from flask import Flask, session, redirect, url_for, request from markupsafe import escape app = Flask(__name__) # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: #session object is provided to you, like request return 'Logged in as {}'.format(escape(session['username'])) return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): #this part is executed after the submit if request.method == 'POST': session['username'] = request.form['username'] #url_for can be used to reverse-lookup the url for a method return redirect(url_for('index')) #by default the submit button will submit into the same URL #and come back as a form POST request return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) app.run(debug = True)