17
WEB 2/2 Olivier Rovellotti Python

Ns python-flask

Embed Size (px)

Citation preview

Page 1: Ns python-flask

WEB 2/2

Olivier Rovellotti

Python

Page 2: Ns python-flask
Page 3: Ns python-flask
Page 4: Ns python-flask

Pourquoi un “Template Engine”?

• Le code est plus clair : on sait où est le code HTML et on ne doit pas chercher dans le code

• Si un jour vous voulez modifier l'affichage, vous savez quelle partie du code éditer

• Si vous travaillez avec un graphiste, ou un intégrateur vous pouvez leur fournir juste ces fichiers

Page 5: Ns python-flask

CSS

Template HTML

Python

Page 6: Ns python-flask

Exemple

{% extends "layout.html" %}

{% block body %}

<ul> {% for user in users %}

<li><a href="{{ user.url }}">{{ user.username }}</a></li>

{% endfor %}

</ul>

{% endblock %}

Page 7: Ns python-flask

pip install jinja2

Page 8: Ns python-flask

Hello world

>>> from jinja2 import Template

>>> template = Template('Hello {{ name }}!')

>>> template.render(name='John Doe')

'Hello John Doe!'

Page 9: Ns python-flask

Plus fort !

>>> from jinja2 import Template

>>> template = Template(‘{% for user in users %} <li>{{ user }}</li> {% endfor %} ')

>>> template.render(users=['oli',‘momo',‘michmich'])

' <li>oli</li> <li>momo</li> <li>michmich</li> '

Page 10: Ns python-flask

Transformer ce code

print("Content-type: text/html; charset=utf-8\n")

liste={"Alban":"0688774455", "olivier":"0609576653", "AARON":"0688774455"}

print ("<ol>")

for cle, valeur in liste.items():

html = "<li><i>"+cle+"</i> " + "<b>" + valeur + "</b></br> </li>“

print(html)

print ("</ol>")

Page 11: Ns python-flask
Page 12: Ns python-flask

pip install Flask

Page 13: Ns python-flask

Routeur.py

from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello_world():

return 'Hello, World!'

Page 14: Ns python-flask

Lancer le serveur

Set FLASK_APP= Routeur.py

flask run

* Serving Flask app "flasktest"

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

127.0.0.1 - - [14/Nov/2017 23:19:40] "GET / HTTP/1.1" 200 -

Page 15: Ns python-flask

Router

@app.route('/')

def index(): return 'Index Page'

@app.route('/hello')

def hello(): return 'Hello, World'

Page 16: Ns python-flask

Router intelligent

@app.route('/user/<username>')

def show_user_profile(username): # show the user profile for that user

return 'User %s' % username

@app.route('/post/<int:post_id>')

def show_post(post_id): # show the post with the given id, the id is an integer

return 'Post %d' % post_id

Page 17: Ns python-flask

Twitter: @orovellottiwww.natural-solutions.eu

Merci

[email protected]