import webapp2 class HelloWorld(webapp2.RequestHandler): def get(self): self.response.write('Hello Udacity CS253!') def post(self): nom=self.request.get('nom') ip=self.request.remote_addr self.response.write('Hello %s' % nom) app = webapp2.WSGIApplication([ ('/hello', HelloWorld), ('/', birthday.MainPage), ('/thanks', birthday.ThanksHandler)] ,debug=True)
- name: jinja2 version: latestDans main.py
import jinja2 import os template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) class BaseHandler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render(self, template, **kw): self.write(render_str(template, **kw))
{{var}}
. On peut aussi inclure du code python sous la forme: {% code %}
Exemple de template:
{% for art in arts %} <div class="art"> <div class="art-title">{{art.title}}</div> <pre class="art-body">{{art.art}}</pre> </div> {% endfor %}Autre exemple de template:
{% if img_url %} <img src={{img_url}}> {% endif %}
{% block content %}{% endblock %}Dans les fichiers HTML dérivés insérer:
{% extends "base.html" %} {% block content %} Mon contenu... {% endblock %}
def render_front(self, title="", art="", error=""): arts = db.GqlQuery("SELECT * FROM Art ORDER BY created DESC") self.render("front.html", title=title, art=art, error = error, arts = arts)
import sqlite3 db = sqlite3.connect(':memory:') #base en RAM db.execute('create table links ' + '(id integer, submitter_id integer, submitted_time integer, ' + 'votes integer, title text, url text)') for link in links: db.execute('insert into links values (?, ?, ?, ?, ?, ?)', link) def query(): c = db.execute("select * from links") #curseur results=c.fetchall() #print results for link_tuple in c: link = Link(*link_tuple) # *=passer tous les arguments print link.votes def query2(): c = db.execute("SELECT * FROM LINKS WHERE ID=2") link = c.fetchone() #tuplé nbVotes=link[3]
from google.appengine.ext import db class Art(db.Model): title = db.StringProperty(required = True) art = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True) modified = db.DateTimeProperty(auto_now = True) #autres types: Integer, Float, Date. if title and art: a = Art(title = title, art = art) a.put() #INSERT arts = db.GqlQuery("SELECT * FROM Art ORDER BY created DESC")
def add(title,content): post = Post(title = title, content = content) post.put() #INSERT return post.key().id() def getPost(p_id): p_id=int(p_id) key = db.Key.from_path('Post', int(p_id)) #Premier argument: l'entité post = db.get(key) return post
import urllib2 p=urllib2.urlopen('http://www.example.com/') pageHTML=p.read() print p.getcode() #200 ou 404 par exemple print p.headers['content-type'] print p.headers['server'] print urllib.urlencode(dictionnaire) >> nom=toto&valeur=12