We will not cover:
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
@app.route('/index')
def index():
return render_template("index.html")
@app.route('/purchase/<int:product_id>', methods=['POST'])
def purchase(product_id):
quantity = request.form['quantity']
# ... make restful API calls with form data
return jsonify({'txn_id': '42'})
@app.route('/quote', methods=['GET'])
def quote():
if request.method == 'GET':
plan = request.args.get('pricing-plan')
# ... make restful API calls with data
return jsonify({'quote': '£25'})
if __name__ == 'main':
app.run()
Flask is a micro web framework, that can also be used to build a rich API.
Flask simplifies two things:
"... bridges Werkzeug [a WSGI application] to Jinja2 to handle templating."
Read more: flask.pocoo.org/docs/design
$ tree ~/projects/flask-api-proxy
|- flask_proxy.py
|- flask_proxy_tests.py
|- requirements.txt
|- static
|- img
|- kitten.jpg
|- css
|- style.css
|- js
|- jquery-1.7.2.js
|- templates
|- index.html
This is the basis for any Flask application.
You can further extend this by using libraries (eg. SQLAlchemy, Flask-OAuth) if you need to, but the idea is to use Flask as the foundation for web apps, and build up your application by adding extensions.
$ tree ~/projects/talent-curator |- runserver.py |- requirements.txt |- talent_curator |- __init__.py |- apps |- core |- __init__.py |- views.py |- models.py |- profile |- settings |- __init__.py |- common.py |- development.py |- production.py |- database.py |- decorators.py |- static |- img |- css |- js |- scss |- templates |- profile |- index.html |- base.html |- index.html
@app.route('/candidates/list') @login_required def list(): return render_template('list.html', candidates={}) def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: return redirect( url_for('main_blueprint.login', next=request.url)) return f(*args, **kwargs) return decorated_function
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Candidate(Base): __tablename__ = 'candidates' id = Column(Integer, primary_key=True) first_name = Column(String(100)) last_name = Column(String(100)) def __init__(self, first_name, last_name=None): self.first_name = first_name self.last_name = last_name
More advanced usage of Flask, using:
1 / 48
#