Showing posts with label Python code. Show all posts
Showing posts with label Python code. Show all posts

Tuesday, June 7, 2016

Dominate creating and manipulating HTML documents


Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API. It allows you to write HTML pages in pure Python very concisely, which eliminate the need to learn another template language, and to take advantage of the more powerful features of Python.

Simple Image Gallery

import glob
from dominate import document
from dominate.tags import *

photos = glob.glob('photos/*.jpg')

with document(title='Photos') as doc:
    h1('Photos')
    for path in photos:
        div(img(src=path), _class='photo')

with open('gallery.html', 'w') as f:
    f.write(doc.render())


Result:

<!DOCTYPE html>
<html>
  <head>
    <title>Photos</title>
  </head>
  <body>
    <h1>Photos</h1>
    <div class="photo">
      <img src="photos/IMG_5115.jpg">
    </div>
    <div class="photo">
      <img src="photos/IMG_5117.jpg">
    </div>
  </body>
</html>

in stackoverflow creating html in python

Tuesday, May 24, 2016

Python and HTML files

Python Phrasebook Covers

url parse

from urllib.parse import urlparse, urlunparse, urljoin
print("=== 0801_url_parse.py ===")

URLscheme = "http"
URLlocation = "www.python.org"
URLpath = "lib/module-urlparse.html"

modList = ("urllib", "urllib2", "httplib", "cgilib")

#Distribution de l'adresse dans un tuple
print("Recherche Google parsée pour urlparse")
parsedTuple = urlparse("http://www.google.com/search?hl=en&q=urlparse&btnG=Google+Search")
print(parsedTuple)

#Fusion de liste en URL
print("\nPage de document Python non parsée")
unparsedURL = urlunparse((URLscheme, URLlocation, URLpath, '', '', ''))
print("\t" + unparsedURL)

#Fusion du chemin avec le nouveau fichier pour créer
#la nouvelle URL
print("\nPages Python supplémentaires utilisant join")
for mod in modList:
    newURL = urljoin(unparsedURL, "module-%s.html" % (mod))
    print("\t" + newURL)

#Jointure du chemin au sous-chemin pour créer une nouvelle URL
print("\nPages Python avec jointures de sous-chemins")
newURL = urljoin(unparsedURL, "/module-urllib2/request-objects.html")
print("\t" + newURL)



html open

import urllib.request
print("=== 0802_html_open.py ===")

webURL = "http://www.python.org"
localURL = "file:\\tmp\default2.html"

#Ouverture de l'URL sur le Web
u = urllib.request.urlopen(webURL)
buffer = u.read()
print("Lecture web ***")
print(u.info())
print("%d octets de %s.\n" % (len(buffer), u.geturl()))

#Ouverture de l'URL en local
print("Lecture d'un fichier local ***")
print(localURL)
u = urllib.request.urlopen(localURL)
buffer = u.read()
print(u.info())
print("%d octets de %s.\n" % (len(buffer), u.geturl()))
print(buffer)


html links

from html.parser import HTMLParser
import urllib.request, urllib.parse, urllib.error
import sys
print("=== 0803_html_links.py ===")

#Definition du parseur HTML
class parseurLiens(HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            for name,value in attrs:
                if name == 'href':
                    print(value)
                    print((self.get_starttag_text()))

#Creation d'une instance du parseur HTML
monParseur = parseurLiens()

#Ouverture du fichier HTML
data = urllib.request.urlopen("http://www.python.org/index.html").read()
monParseur.feed(data.decode('utf-8'))
monParseur.close()


html images

from html.parser import HTMLParser
import urllib.request, urllib.parse, urllib.error
import sys
print("=== 0804_html_images.py ===")

urlString = "http://www.python.org"

#Enregistrement du fichier d'image sur le disque
def lireFicIMA(addr):
    u = urllib.request.urlopen(addr)
    data = u.read()

    splitPath = addr.split('/')
    fName = splitPath.pop()
    print("Stockage local de %s" % fName)

    f = open(fName, 'wb')
    f.write(data)
    f.close()

#Définition du parseur HTML
class parseImage(HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == 'img':
            for name,value in attrs:
                if name == 'src':
                    lireFicIMA(urlString + "/" + value)

#Création de l'instance du parseur HTML
monParseur = parseImage()

#Ouverture du fichier HTML
u = urllib.request.urlopen(urlString)
print("Ouverture de l'URL =============================")
print(u.info())

#Alimentation du fichier HTML dans le parseur
data = u.read()
monParseur.feed(data.decode('utf-8'))
monParseur.close()
print("Les fichiers sont dans le dossier courant")


html text

from html.parser import HTMLParser
import urllib.request
print("=== 0805_html_text.py ===")

urlText = []

#Définition du parseur HTML
class parseurTexte(HTMLParser):
    def handle_data(self, data):
        if data != '\n':
            urlText.append(data)

#Création de l'instance du parseur HTML
monParseur = parseurTexte()

#Alimentation du fichier HTML dans le parseur
data = urllib.request.urlopen("http://docs.python.org/lib/module-HTMLParser.html").read()
monParseur.feed(data.decode('utf-8'))
monParseur.close()
for unBloc in urlText:
    print(unBloc


html cookie

import os
import urllib.request, urllib.error
import http.cookiejar
print("=== 0806_html_cookie.py ===")

cookieFile = "cookie.dat"
testURL = 'http://maps.google.com'

#Creation de l'instance de cookie jar
boiteACooky = http.cookiejar.LWPCookieJar()

#Creation de l'objet opener HTTPCookieProcessor
opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(boiteACooky))

#Installation de l'opener HTTPCookieProcessor
urllib.request.install_opener(opener)

#Creation de l'objet Request
r = urllib.request.Request(testURL)

#Ouverture du fichier HTML
h = urllib.request.urlopen(r)
print("En-tete de la page \n======================")
print(h.info())

print("Cookies de la page \n======================")
for ind, cookie in enumerate(boiteACooky):
  print("%d - %s" % (ind, cookie))

#Enregistrement des cookies
boiteACooky.save(cookieFile)


html quotes

from html.parser import HTMLParser
import urllib.request, urllib.parse, urllib.error
import sys
print("=== 0807_html_quotes.py ===")

localURL = "file:\\tmp\default.html"

#Definition du parseur HTML
class parseAttrs(HTMLParser):
    def init_parser (self):
        self.pieces = []

    def handle_starttag(self, tag, attrs):
        fixedAttrs = ""
        for name, value in attrs:
            fixedAttrs += "%s=\"%s\" " % (name, value)
            self.pieces.append("<%s %s>" % (tag, fixedAttrs))

    def handle_charref(self, name):
        self.pieces.append("&#%s;" % (name))

    def handle_endtag(self, tag):
        self.pieces.append("</%s>" % (tag))

    def handle_entityref(self, ref):
        self.pieces.append("&%s" % (ref))

    def handle_data(self, text):
        self.pieces.append(text)

    def handle_comment(self, text):
        self.pieces.append("<!-%s->" % (text))

    def handle_pi(text):
        self.pieces.append("<?%s>" % (text))

    def handle_decl(self, text):
        self.pieces.append("<!%s>" % (text))

    def parsed (self):
        return "".join(self.pieces)

#Creation d'une instance du parseur HTML
parseAttrib = parseAttrs()

#Initialisation des donnees de parseur
parseAttrib.init_parser()

#Alimentation du fichier HTML dans le parseur
data = urllib.request.urlopen(localURL).read()
parseAttrib.feed(data.decode('utf-8'))

#Affichage du contenu du fichier original
print("Fichier original\n========================")
print(data)

#Affichage du fichier parse
print("\nFichier final\n========================")
print(parseAttrib.parsed())

parseAttrib.close()



in Brad Dayley, Python 3 (Python Phrasebook), L'essentiel du code et des commandes, peason.fr

Sunday, May 15, 2016

Python CGI Database (4 of 4)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3
import cgi

print "Content-Type: application/xhtml+xml; charset=utf-8\n"

print '<!DOCTYPE html>'
print '<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">'
print '<head>'
print '    <title>eCarnet - Employées d un service</title>'
print '</head>'
print '<body>'

form = cgi.FieldStorage()
id_service = str(form["matricule"].value)
nom = str(form["nom"].value)
prenom = str(form["prenom"].value)
matricule = str(form["matricule"].value)
tel_fixe = str(form["tel_fixe"].value)

db_connection = sqlite3.connect('database.test-01.db')
db_connection.row_factory = sqlite3.Row
cursor = db_connection.cursor()
cursor.execute("INSERT INTO employe(matricule, prenom, nom, tel_fixe, id_service) VALUES (?, ?, ?, ?, ?)", (matricule, prenom, nom, tel_fixe, id_service))
db_connection.commit()
db_connection.close()

print '    <h1>Ajout de l employé - ' + prenom + ' ' + nom + ' -</h1>'
print '    <p>' + prenom + ' ' + nom + ' a bien été ajouté dans la base de données</p>'
print '    <p><a href="eCarnet_home.py">Retour au eCarnet.</a></p>'
print ' </body>'
print ' </html>'

Python CGI Database (3 of 4)

# -*- coding: utf-8 -*-

import sqlite3
import cgi

print "Content-Type: application/xhtml+xml; charset=utf-8\n"

print '<!DOCTYPE html>'
print '<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">'
print '<head>'
print '    <title>eCarnet - Employées d un service</title>'
print '</head>'
print '<body>'

form = cgi.FieldStorage()
service_id = str(form["service"].value)
db_connection = sqlite3.connect('database.test-01.db')
db_connection.row_factory = sqlite3.Row
cursor = db_connection.cursor()
cursor.execute("SELECT emplacement FROM service WHERE id=" + service_id)
row = cursor.fetchone()
service_nom = str(row['emplacement'])

print '    <h1>Employés du service - ' + service_nom + ' -</h1>'

cursor.execute("SELECT prenom, nom, tel_fixe FROM employe WHERE id_service=" + service_id)
rows = cursor.fetchall()

print '    <ol>'
for row in rows:
    print '        <li>' + row['prenom'] + ', ' +row['nom'] + ', ' + row['tel_fixe'] + '</li>'
print '    </ol>'
print '</body>'
print '</html>'

db_connection.close()

Python CGI Database (2 of 4)

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3

print "Content-Type: application/xhtml+xml; charset=utf-8\n"

print '<!DOCTYPE html>'
print '<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">'
print '<head>'
print '    <title>eCarnet - Home</title>'
print '</head>'
print '<body>'
print '    <h1>Bienvenue sur eCarnet de ULB</h1>'
print '    <h2>Employés</h2>'

# Connection à la base de données
#db_connection = sqlite3.connect('database.sqlite3')
db_connection = sqlite3.connect('database.test-01.db')
db_connection.row_factory = sqlite3.Row
cursor = db_connection.cursor()

# Sélection des enregistrements
cursor.execute("SELECT prenom, nom, tel_fixe FROM employe")

# Création de la liste des employées
rows = cursor.fetchall()
print '    <ol>'
for row in rows:
    print'        <li>' +row['prenom'] + ' ' +row['nom'] + ', ' +row['tel_fixe'] + '  </li>'
print '    </ol>'
   
# Formulaire de recherche des employés d'un service   
print '    <h2>Employés par service</h2>'
print '    <form action="eCarnet_service.py" method="get">'
print '    <p><select name="service">'
cursor.execute ("SELECT id, nom, emplacement From service")
rows = cursor.fetchall()
for row in rows:
    print '            <option value="' + str(row['id']) + '">' + row['emplacement'] + '</option>'
print '    </select>'
print '        <input type="submit" value="Lister" /></p>'
print '    </form>'

# Formulaire d'ajout d'un nouvel employé   
print '    <h2>Ajouter un nouvel employé</h2>'
print '    <form action="eCarnet_add_employee.py" method="get">'
print '    <p>Prénom : <input type="text" name="prenom" /></p>'
print '    <p>Nom : <input type="text" name="nom" /></p>'
print '    <p>Matricule : <input type="text" name="matricule" /></p>'
print '    <p>Tèl. fixe : <input type="text" name="tel_fixe" /></p>'
print '    <p>Service : <select name="service">'
for row in rows:
    print '            <option value="' + str(row['id']) + '">' + row['emplacement'] + '</option>'
print '        </select>'
print '        <input type="submit" value="Ajouter" /></p>'
print '    </form>'  
print '</body>'
print '</html>'

db_connection.close()

Python CGI Database (1 of 4)

<?xml version=“1.0” encoding=“utf-8”?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
    <head>
        <meta charset="UTF-8">
        <!--<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />-->
        <title>Université libre de Bruxelles</title>
    </head>
    <body>
    <img src="logo_ulb.png" alt="Logo de l'ULB" width="656" height="80" />
    <h1>Bienvenue sur le site de l'ULB</h1>
    <section>
        <h2>Que voulez-vous consulter ?</h2>
        <ul>
            <li><a href="status.html">Les statuts de l'université</a></li>
            <li><a href="/cgi-bin/eCarnet_home.py">Le carnet d'adresses des employés</a></li>
            <li><a href="ca.html">La composition du Conseil d'Aministration</a></li>
        </ul>
    </section>
    </body>
</html>

Python CGI Web Server

#! Path to Python.exe "C:\Web development\Python27\python.exe"

from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler

httpd = HTTPServer(('', 8080), CGIHTTPRequestHandler)
print("Demarrage du serveur web...")
httpd.serve_forever()

Thursday, May 12, 2016

Python and AJAX tutorial for beginners with web.py and jQuery

Kooneiform

Request methods

... a zipped copy of the files in this tutorial, you can get it here. Run app.py and then point your browser to http://localhost:8080 (on Windows; use the appropriate address for your setup).