Shalabh Aggarwal
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello to the World of Flask!' if __name__ == '__main__': app.run()
$ pip install virtualenv $ virtualenv my_flask_app_name $ cd my_flask_app_name/Source $ activate $ pip install flask
$ deactivate
app = Flask(__name__) app.config['DEBUG'] = True
app.debug = True
app.run(debug=True)
app.config.from_object('myapplication.default_settings')
app.config.from_object(name) #To load from same file
app.config.from_envvar('PATH_TO_CONFIG_FILE')
class BaseConfig(object): 'Base config class' SECRET_KEY = 'A random secret key' DEBUG = True TESTING = False NEW_CONFIG_VARIABLE = 'my value' class ProductionConfig(BaseConfig): 'Production specific config' DEBUG = False SECRET_KEY = open('/path/to/secret/file').read() class StagingConfig(BaseConfig): 'Staging specific config' DEBUG = True class DevelopmentConfig(BaseConfig): 'Development environment specific config' DEBUG = True TESTING = True SECRET_KEY = 'Another random secret key'
app.config.from_object('configuration.DevelopmentConfig')
my_app/ - app.py - config.py - __init__.py - static/ - css/ - js/ - images/ - logo.png
<img src='/static/images/logo.png'>
my_app/ - app.py - instance/ - config.cfg
app = Flask(__name__, instance_path='/absolute/path/to/instance/folder')
app = Flask( __name__, instance_path='path/to/instance/folder', instance_relative_config=True ) app.config.from_pyfile('config.cfg', silent=True)
from flask import Blueprint hello = Blueprint('hello', __name__) @hello.route('/') @hello.route('/hello') def hello_world(): return MESSAGES['default']
from flask import Flask from my_app.hello.views import hello app = Flask(__name__) app.register_blueprint(hello)
SQLAlchemy
for relational database systems.pip install flask-sqlalchemy
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ('DATABASE_URI')
postgresql://yourusername:yourpassword@localhost/yournewdb
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) from my_app.catalog.views import catalog app.register_blueprint(catalog) db.create_all()
db.create_all()
, which tells the application to create all the tables in the database specified. So, as soon as the application runs, all the tables will be created if they are not already there.from my_app import db class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) price = db.Column(db.Float) def __init__(self, name, price): self.name = name self.price = price def __repr__(self): return '<Product %d>' % self.id
from flask import request, jsonify, Blueprint from my_app import app, db from my_app.catalog.models import Product catalog = Blueprint('catalog', __name__) @catalog.route('/') @catalog.route('/home') def home(): return "Welcome to the Catalog Home." @catalog.route('/product/<id>') def product(id): product = Product.query.get_or_404(id) return f'Product - {product.name}, {product.price}' @catalog.route('/products') def products(): products = Product.query.all() res = {} for product in products: res[product.id] = { 'name': product.name, 'price': str(product.price) } return jsonify(res) @catalog.route('/product-create', methods=['POST',]) def create_product(): name = request.form.get('name') price = request.form.get('price') product = Product(name, price) db.session.add(product) db.session.commit() return 'Product created.'
from my_app import db class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) price = db.Column(db.Float) category_id = db.Column(db.Integer,db.ForeignKey('category.id')) category = db.relationship( 'Category', backref=db.backref('products', lazy='dynamic') ) def __init__(self, name, price, category): self.name = name self.price = price self.category = category def __repr__(self): return '<Product %d>' % self.id class Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) def __init__(self, name): self.name = name def __repr__(self): return '<Category %d>' % self.id
from my_app.catalog.models import Product, Category @catalog.route('/products') def products(): products = Product.query.all() res = {} for product in products: res[product.id] = { 'name': product.name, 'price': product.price, 'category': product.category.name } return jsonify(res) @catalog.route('/product-create', methods=['POST',]) def create_product(): name = request.form.get('name') price = request.form.get('price') categ_name = request.form.get('category') category = Category.query.filter_by(name=categ_name).first() if not category: category = Category(categ_name) product = Product(name, price, category) db.session.add(product) db.session.commit() return 'Product created.' @catalog.route('/categories') def categories(): categories = Category.query.all() res = {} for category in categories: res[category.id] = { 'name': category.name } for product in category.products: res[category.id]['products'] = { 'id': product.id, 'name': product.name, 'price': product.price } return jsonify(res)
@app.route('/a-get-request') def get_request(): bar = request.args.get('foo', 'bar') return 'A simple Flask request where foo is %s' % bar @app.route('/a-post-request', methods=['POST']) def post_request(): bar = request.form.get('foo', 'bar') return 'A simple Flask request where foo is %s' % bar
def get_request(): bar = request.args.get('foo', 'bar') return 'A simple Flask request where foo is %s' % bar app = Flask(__name__) app.add_url_rule('/a-get-request', view_func=get_request)
@catalog.route('/products') @catalog.route('/products/<int:page>') def products(page=1): products = Product.query.paginate(page, 10).items res = {} for product in products: res[product.id] = { 'name': product.name, 'price': product.price, 'category': product.category.name } return jsonify(res)
from flask import render_template @catalog.route('/') @catalog.route('/home') def home(): return render_template('home.html') @catalog.route('/product/<id>') def product(id): product = Product.query.get_or_404(id) return render_template('product.html', product=product)
{% extends 'base.html' %} {% block container %} <h1>Welcome to the Catalog Home</h1> <a href="{{ url_for('catalog.products') }}">Click here to see the catalog</a> {% endblock %}
{% extends 'home.html' %} {% block container %} <div class="top-pad"> <h1>{{ product.name }}<small> {{ product.category.name }}</small></h1> <h4>{{ product.company }}</h4> <h3>{{ product.price }}</h3> </div> {% endblock %}