Upload
michal-hatak
View
171
Download
4
Embed Size (px)
Citation preview
FLASK - ÚVOD DO PYTHONU
MICHAL HATÁK
INTRO
DIFFERENCES BETWEEN PHP AND PYTHON
▸ whitespace significant
▸ library for everything
▸ full language (not only websites)
▸ module system
INTRO
PACKAGE SYSTEM
▸ PIP - very similar to composer
▸ pip install <package name>
▸ pip install -f <requirements.txt>
INTRO
VIRTUAL ENVIRONMENTS
▸ isolated python environment
▸ contains python executables > multiple python version on one system
INTRO
THE GOAL
▸ basic web app using Flask framework (very similar to Nette)
▸ little showcase
PREPARE PROJECT
FIRST STEPS
▸ create virualenv $ virtualenv venv$ . venv/bin/activate
▸ install Flask framework $ pip install Flask
#1
APP.PY
from flask import Flask
app = Flask(__name__)
@app.route('/') def hello_world(): return 'Hello World!'
if __name__ == '__main__': app.debug = True app.run() # default 127.0.0.1:5000
#2
APP.PY
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<name>') def hello(name): return render_template("hello.html", name=name)
if __name__ == '__main__': app.debug = True app.run() # default 127.0.0.1:5000
TEMPLATES/HELLO.HTML
<!DOCTYPE html> <html lang="en"> <head> <title>My First Website</title> </head> <body> Hello <strong>{{ name }}</strong> Hello <strong>{{ name | reverse }}</strong> {{ "%s - %s" | format("Hello", name) }} </body> </html>
#3
INSTALL
▸ $ pip install wtforms flask-wtf
TEMPLATES/LAYOUT.HTML
<!DOCTYPE html> <html lang="en"> <head> <title>My First Website</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %}
{% block body %}{% endblock %} </body> </html>
FORMS.PY
from flask_wtf import Form from wtforms import StringField, SubmitField, validators
class GreetingsForm(Form): name = StringField(label="Enter your name: ", validators=[validators.DataRequired()]) submit = SubmitField("Greet!")
APP.PY
from flask import (Flask, render_template, request, flash, redirect, url_for)
from forms import GreetingsForm
app = Flask(__name__)
@app.route('/hello-form', methods=["GET", "POST"]) def hello_form(): form = GreetingsForm(request.form)
if form.validate_on_submit(): flash("Hello" + form.name.data) return redirect(url_for("hello_form"))
return render_template("hello-form.html", form=form)
TEMPLATES/HELLO-FORM.HTML
{% extends "layout.html" %} {% block body %} <form method="post" action="{{ url_for("hello_form") }}"> {{ form.hidden_tag() }}
<label>{{ form.name.label.text }}</label> {{ form.name() }}
{{ form.submit() }} </form> {% endblock %}