View
254
Download
4
Category
Preview:
Citation preview
What is Flask?
• Project released on April 1, 2010 • Strips away the magic inherent in most other frameworks • Par:al toward MVC design paDern • Templa:ng -‐ Jinja2 • ORM -‐ SQLAlchemy • Form Handling -‐ WTForms
Flask Directory Structure Iden:fies the applica:on as a python module for easy portability and ini:alizes
the Flask object
Contains routes/handlers, actually the controller, but called view because it does template
rendering.
Sta:c assets like JS, CSS, and images
Jinja templates (.html extension is just a standard)
Templa;ng
• Injec:ng HTML with python strings • Jinja2 -‐ Most popular Python templa:ng engine • Generates dynamic content • /templates directory
The Request Object
• Proper:es • form -‐ Mul:Dict on POST or PUT requests • args -‐ Mul:Dict from parsing the query string • cookies -‐ dict with cookie contents • headers • method -‐ request method • path -‐ route • and many more...
The Response Object
• Proper:es • headers • status -‐ string representa:on of the response status (e.g. 'OK') • status_code -‐ integer value for response status (e.g. 200) • data -‐ return data, oben html • mimetype
Database
• ORM -‐ Object Rela:onal Mapping • Accessing a database from Python • Translates database en::es into objects • Table object, Column object, Row object • SQLAlchemy -‐ Python ORM that also is a flask extension
Flask Directory Structure Iden:fies the applica:on as a python module for easy portability and ini:alizes
the Flask object
Contains routes/handlers, actually the controller, but called view because it does template
rendering.
Sta:c assets like JS, CSS, and images
Jinja templates (.html extension is just a standard)
Power of the ORM
• Make your models smarter • Avoid wri:ng SQL • OOP • Complex database opera:ons with small amount of code
• Color.query.filter_by(color='red') • User.query.get(42) • Message.query.order_by('display_order').all()
Forms
• WTForms/wcorms_alchemy • Very useful in conjunc:on with SQLAlchemy • Forms as objects • Rendered in the templates
Python Tools
• Virtualenv • Python environment • Install deps here • Benefit -‐ easily manage deps • Drawback -‐ Not portable
• Pip • pip freeze > requirements.txt • pip install -‐r requirements.txt
• PEX • "Python Executable"
Recommended