Python Web Development

Outline

Outline

Outline

Outline

-1. Who am I and what am I doing here?

I'm Simon

0. Intro

Python Web Development

Web Frameworks

1. Python

Python

Python

Python - Styleguide

Python - Installation

Python Examples - Hello world

			# hello_1.py
print("Hello world!")
		
			$ python hello_1.py
		

Python Examples - Comments

			# I'm a single line comment
			# We arrrr
			# pirates! (And a multi line comment!)
			'''
			So arrrr we!
			'''
		

Python Examples - Iterating

			list_example = [1, 2, 3, 4, 5, 6]
			for element in list_example:
				print(element)
			for element in reversed(list_example):
				print(element)
		

Python Examples - Classes

			class A:
				def __init__(self): # Constructor
					self.variable = 42
					self._protected_variable = 23
					self.__private_variable = 5
				def say_hi(self):
					print("Hi Consolis!")
		

Python Examples - Exception handling

			try:
				some_method()
			except some_exception as e:
				print(e)
				# raise
		

Python - Package management

Python - Package management

			pip install ${package}
			pip uninstall ${package}
			pip list
		
			pip freeze > requirements.txt
			pip install -r requirements.txt
		

Python - Virtual environments

			pip install virtualenv
		

Python - Activating virtual environment

			virtualenv venv
			source venv/bin/activate
			(venv)${PS1}
		

Python - Modules

What's a module in Python?

Python - Module example

			# consol.py
			def say_hi():
				print("Hi ConSolis!")
		
			# main.py
			import consol
			consol.say_hi()
		

Python - Packages

And what's a package?

2. Flask

Flask

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions

Flask

Flask - Project structure

			- flask/  <- Project folder
			|- shoutbox/  <- Application subfolder
			 |- __init__.py  <- shoutbox package
			|- venv/  <- Virtual environment
			|- run.py  <- Script to run application
		

Flask - Setup

			git clone https://github.com/s1hofmann/shoutbox.git
git checkout tags/flask_init
		

Flask - Setup

			virtualenv venv
		
			source venv/bin/activate or venv\Scripts\activate
		
			pip install flask
		

Flask - Setup

Flask - Hello world

			# shoutbox/shoutbox_app.py
from flask import Flask
__all__ = ['app'] # Added for imports
app = Flask(__name__)
@app.route('/')
def index():
	return "Hello world!"
		

Flask - Hello world

			# shoutbox/__init__.py
from .shoutbox_app import *
		

Flask - Hello world

			# run.py
#!venv/bin/python
import shoutbox
if __name__ == "__main__":
	shoutbox.app.run()
		

Flask - Hello world

			venv/bin/python run.py
		
			* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
		

Flask - Request routing

			@app.route('/')  # Route decorator
def index():  # View function
	return "Hello world!"
		

Flask - Request routing

			@app.route('/hello/‹string:username›')  # Route decorator
def say_hi(username):  # View function
	pass
		

Flask - Routing exercise

Flask - Request hooks

Hook Description
@before_first_request Runs before the very first request
@before_request Runs before every request
@after_request Runs after every successful request
@teardown_request Runs after every request

Flask - Responses

			@app.index('/')
			def index():
				return ("Hello world!", 204)
		

Flask - Templates

Flask - Template variables

			

{{ template_var }}

Flask - Template blocks

			{% block $name %}
			{% endblock %}
		

Flask - Template inheritance

			{% extends 'super_template.html' %}
		

Flask - Template inheritance

			{% block derived %}
{{ super() }}
{% endblock %}
		

Flask - Template includes

			{% include 'other_template.html' %}
		

Flask - Template control structures

			{% if $condition %} 
	statement
{% else %} 
	other_statement 
{% endif %}
		

Flask - Template loops

			{% for element in elements %} 
	statement
{% endfor %}
		

Flask - Templates exercise

			@app.route('/hello/‹string:username›')
def say_hi(username):
    return render_template(...)
	

Shortcut!

			git checkout tags/webforms_init
			pip install -r requirements.txt
		

What's next?

Flask - WebForms

			pip install flask-wtf
		

Flask - WebForms

Flask - WebForms

			from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
    name = StringField('name', validators=[DataRequired()])
	submit = SubmitField('submit')
		

Flask - WebForms exercise

Intermission - Flask config

			# shoutbox/shoutbox_app.py
app.config['SECRET_KEY'] = "Don't tell anyone!"
		

Flask - WebForms

			@app.route('/shout/', methods=["GET", "POST"])
		

Flask - Persistence

			git checkout tags/database_init
			pip install flask-sqlalchemy
		

Flask - Persistence

name type
id INTEGER
username TEXT
text TEXT

Flask - Persistence

Flask - Persistence

			# shoutbox/shoutbox_app.py
db = SQLAlchemy(app)
		

Flask - Defining persistence models

			class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Text)
    email = db.Column(db.Text)

    def __init__(self, username, email):
        self.username = username
        self.email = email
		

Flask - Defining persistence models

Flask - Cyclic imports

Summary

Thank's for your attention!

Find me on Github: @s1hofmann

Appendix A - External configuration

			class Config:
    SECRET_KEY = 'hard to guess'
    DEBUG = False
    SQLALCHEMY_DATABASE_URI = 'sqlite:///shoutbox.db'
		
			app.config.from_object($config_object)
		

Appendix B - Logging

			app.logger.debug('A value for debugging')
app.logger.error('An error occurred')
		

Appendix C - Custom error pages

			@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404
		

Appendix D - Crash reporting

			from raven.contrib.flask import Sentry
sentry = Sentry()
sentry.init_app(app, dsn=$sentry_key)
		

That's it!

This time for real!