begin process at 2012 05 24 00:29:06
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Réseau & internet

 > GÉNÉRATEUR HTML POUR L'UTILISATION DE PYTHON EN CGI

GÉNÉRATEUR HTML POUR L'UTILISATION DE PYTHON EN CGI


 Information sur la source

Note :
Aucune note
Catégorie :Réseau & internet Classé sous :html, cgi, page web Niveau :Débutant Date de création :17/12/2009 Date de mise à jour :17/12/2009 22:31:48 Vu / téléchargé :2 608 / 62

Auteur : Just_1

Ecrire un message privé
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note

 Description

Ma première contribution au monde de l'Open Source :D
Bon d'accord, c'est une maigre contribution...


EXPLICATIONS / PRISE EN MAIN

HTMLOutput est une classe très simple (malgré les commentaires en Anglais) qui permet de générer une page XHTML à partir de 2 éléments seulement:
- un titre (+ un titre de page)
- un contenu

Dans l'ordre:
1) appel de la classe
2) ajout d'un ou plusieurs éléments de titre
3) ajout des éléments de contenu
4) récupération du résultat pour affichage
Pour un exemple, voir l'archive ZIP.


PERSONNALISATION

La balise de titre (pour ceux qui connaissent un peu l'HTML) est définie en appelant la classe (h1, h2, ... h6, ou même div, p, ou quoique ce soit d'autre).

Pour utiliser une feuille de styles CSS, il faut modifier la ligne 70:
<link rel="stylesheet" type="text/css" href="stylesheet.css" />

Pour supprimer le tableau d'en-tête pouvant contenir des infos additionnelles sur la page, supprimez les lignes 79 à 83. Si vous voulez les conserver, éditez-les!


UTILISATION

Je l'avais développé pour utiliser Python (version 2.5) en CGI sur un serveur web, et je me dits que ça peut certainement servir à d'autres pour créer des pages web simples sans se prendre la tête.
Un exemple d'utilisation est donné dans l'archive ZIP.

Source

  • #! /usr/bin/python -u
  • ###################################################################
  • # created by Justin MASSIOT, august 2008 #
  • ###################################################################
  • """
  • To insert a stylesheet (CSS, Cascading Style Sheet), you have to edit the line 70:
  • <link rel="stylesheet" type="text/css" href="stylesheet.css" />
  • To delete the author headers, delete lines 79 to 83; otherwise edit them!
  • """
  • __doc__ = """
  • This file is useful for Python scripts executed as CGI scripts (on a webserver for example).
  • It offers the possibility to simply create an XHTML output to display in a webbrowser.
  • Usage:
  • 1) begin by calling the HTMLOutput class => HTMLOutput()
  • 2) you can add a title calling add_title(title) (can be called several times)
  • 3) you can add content to the page calling add_content(content) (can be called several times)
  • 4) you MUST call footer() to finish HTML standard tags, but over all to output the final result (otherwise nothing will be printed!)
  • ** NB ** :
  • The page always starts with those two essential lines:
  • print "Content-type: text/html"
  • print
  • => it specifies that the page produces an HTML output
  • """
  • import string, os.path
  • ############################################################ 60
  • # class for CGI execution of Python scripts,
  • # which deals with the correct format for HTML output
  • ############################################################ 60
  • class HTMLOutput:
  • def __init__(self, HTMLpageTitle, HTMLtitleTag, HTMLcontent=''):
  • # this file returns HTML content, so we specify it!
  • self.HTMLheader = "Content-type: text/html\n"
  • self.innerHTMLheader = "<!-- This program is running in HTML/CGI-Python mode. -->\n"
  • # HTML page constructor
  • self.titleTag = HTMLtitleTag
  • self.innerHTMLheader += self.header(HTMLpageTitle)
  • self.innerHTMLtitle = ""
  • if HTMLcontent != "": self.innerHTMLpageContent = HTMLcontent
  • else: self.innerHTMLpageContent = ""
  • def header(self, title):
  • # HTTP head and HTML filehead
  • HTMLheader = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n'
  • HTMLheader += '\t\t"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n\n'
  • HTMLheader += '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">\n\n'
  • # HTML <head> tag
  • HTMLheader += '<!-- file head -->\n'
  • HTMLheader += '<head>\n'
  • HTMLheader += '\t<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n'
  • HTMLheader += '\t<link rel="stylesheet" type="text/css" href="stylesheet.css" />\n'
  • HTMLheader += '\t<title>'+ title +'</title>\n'
  • HTMLheader += '</head>\n'
  • HTMLheader += '<!-- end file head -->\n\n\n'
  • # HTML <body> tag begins here
  • HTMLheader += '<!-- HTML visible content -->\n'
  • HTMLheader += '<body>\n'
  • # creator signature
  • HTMLheader += '<table style="width: 100%;">\n'
  • HTMLheader += '<tr><td style="text-align: left;">Links or pieces of information</td>\n'
  • HTMLheader += '<td style="text-align: right;">Author name here</td></tr>\n'
  • HTMLheader += '</table>\n\n'
  • return HTMLheader
  • def footer(self):
  • # add HTML title end
  • if len(self.innerHTMLtitle) != 0: # if title exists, tag must be closed
  • self.innerHTMLtitle += '\n</'+ self.titleTag +'>\n'
  • #self.innerHTMLtitle += '\n<p>&nbsp;</p>'
  • # add HTML content
  • if len(self.innerHTMLpageContent) != 0:
  • self.innerHTMLpageContent = "\n" + self.innerHTMLpageContent # new line
  • # HTML page end
  • HTMLfooter = '\n</body>\n'
  • HTMLfooter += '<!-- end HTML visible content -->\n\n'
  • HTMLfooter += '</html>\n'
  • # print HTTP headers (impossible to return for technical reasons)
  • print self.HTMLheader
  • print # end of HTTP headers
  • # return the whole page : HTTP headers, HTML headers, title, content, and footer
  • return self.innerHTMLheader + self.innerHTMLtitle + self.innerHTMLpageContent + HTMLfooter
  • def add_title(self, HTMLtitle):
  • # add a title (or several) to the page
  • innerHTMLopenTitle = '<'+ self.titleTag +' style="text-align: center;">'
  • if string.find(self.innerHTMLtitle, innerHTMLopenTitle) == -1: # the first time a title is added
  • self.innerHTMLtitle = innerHTMLopenTitle + "\n\t" + HTMLtitle
  • else: # a title already exists
  • self.innerHTMLtitle += "\n\t" + HTMLtitle
  • def add_content(self, HTMLcontent): # add content to the HTML visible page
  • self.innerHTMLpageContent += HTMLcontent + "\n"
  • ############################################################ 60
#! /usr/bin/python -u

###################################################################
# created by Justin MASSIOT, august 2008                          #
###################################################################


"""
To insert a stylesheet (CSS, Cascading Style Sheet), you have to edit the line 70:
<link rel="stylesheet" type="text/css" href="stylesheet.css" />

To delete the author headers, delete lines 79 to 83; otherwise edit them!
"""


__doc__ = """

This file is useful for Python scripts executed as CGI scripts (on a webserver for example).
It offers the possibility to simply create an XHTML output to display in a webbrowser.


Usage:
1) begin by calling the HTMLOutput class => HTMLOutput()
2) you can add a title calling add_title(title) (can be called several times)
3) you can add content to the page calling add_content(content) (can be called several times)
4) you MUST call footer() to finish HTML standard tags, but over all to output the final result (otherwise nothing will be printed!)

** NB ** :
The page always starts with those two essential lines:
print "Content-type: text/html"
print
=> it specifies that the page produces an HTML output

"""



import string, os.path

############################################################ 60
# class for CGI execution of Python scripts,
# which deals with the correct format for HTML output
############################################################ 60
class HTMLOutput:
    
    def __init__(self, HTMLpageTitle, HTMLtitleTag, HTMLcontent=''):
        # this file returns HTML content, so we specify it!
        self.HTMLheader = "Content-type: text/html\n"

        self.innerHTMLheader = "<!-- This program is running in HTML/CGI-Python mode. -->\n"
        
        # HTML page constructor
        self.titleTag = HTMLtitleTag
        self.innerHTMLheader += self.header(HTMLpageTitle)
        self.innerHTMLtitle = ""
        if HTMLcontent != "": self.innerHTMLpageContent = HTMLcontent
        else: self.innerHTMLpageContent = ""


    def header(self, title):
        # HTTP head and HTML filehead
        HTMLheader = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n'
        HTMLheader += '\t\t"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n\n'
        HTMLheader += '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">\n\n'
        
        # HTML <head> tag
        HTMLheader += '<!-- file head -->\n'
        HTMLheader += '<head>\n'
        HTMLheader += '\t<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n'
        HTMLheader += '\t<link rel="stylesheet" type="text/css" href="stylesheet.css" />\n'
        HTMLheader += '\t<title>'+ title +'</title>\n'        
        HTMLheader += '</head>\n'
        HTMLheader += '<!-- end file head -->\n\n\n'

        # HTML <body> tag begins here
        HTMLheader += '<!-- HTML visible content -->\n'
        HTMLheader += '<body>\n'

        # creator signature
        HTMLheader += '<table style="width: 100%;">\n'
        HTMLheader += '<tr><td style="text-align: left;">Links or pieces of information</td>\n'
        HTMLheader += '<td style="text-align: right;">Author name here</td></tr>\n'
        HTMLheader += '</table>\n\n'

        return HTMLheader


    def footer(self):
        # add HTML title end
        if len(self.innerHTMLtitle) != 0: # if title exists, tag must be closed
            self.innerHTMLtitle += '\n</'+ self.titleTag +'>\n'
            #self.innerHTMLtitle += '\n<p>&nbsp;</p>'

        # add HTML content
        if len(self.innerHTMLpageContent) != 0:
            self.innerHTMLpageContent = "\n" + self.innerHTMLpageContent # new line
        
        # HTML page end        
        HTMLfooter = '\n</body>\n'
        HTMLfooter += '<!-- end HTML visible content -->\n\n'
        HTMLfooter += '</html>\n'

        # print HTTP headers (impossible to return for technical reasons)
        print self.HTMLheader
        print # end of HTTP headers
        
        # return the whole page : HTTP headers, HTML headers, title, content, and footer
        return self.innerHTMLheader + self.innerHTMLtitle + self.innerHTMLpageContent + HTMLfooter

    
    def add_title(self, HTMLtitle):
        # add a title (or several) to the page
        innerHTMLopenTitle = '<'+ self.titleTag +' style="text-align: center;">'
        if string.find(self.innerHTMLtitle, innerHTMLopenTitle) == -1: # the first time a title is added
            self.innerHTMLtitle = innerHTMLopenTitle + "\n\t" + HTMLtitle
        else: # a title already exists
            self.innerHTMLtitle += "\n\t" + HTMLtitle
    

    def add_content(self, HTMLcontent): # add content to the HTML visible page
        self.innerHTMLpageContent += HTMLcontent + "\n"
############################################################ 60

 Conclusion

Une classe pour créer rapidement des pages HTML à la volée à partir de vos scripts Python.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

17 décembre 2009 22:31:48 :
Niveau passé de "initié" à "débutant".

 Sources de la même categorie

SOCKET MULTITHREAD SIMPLE par Guillamue06
TRANSFERT DE FICHIER PAR SOCKET par Guillamue06
Source avec une capture AUTO-FOLLOW/UNFOLLOW [TWITTER] EN [PERL] UTILISANT NET::TWIT... par GeroXXXX
Source avec Zip PINGEUR RÉSEAU par jeanbleo44
Source avec Zip Source avec une capture LISTING ET LOGS DES CONNEXIONS ET DECONNEXIONS DE MACHINES Q... par saigneurdushi

 Sources en rapport avec celle ci

SCRIPT CGI MAILER GENERIQUE par kabot23
Source avec Zip INFORMATIONS SUR UN ISBN DEPUIS INTERNET par lepecheur
Source avec Zip Source avec une capture CRÉER UNE PAGE HTML (AVEC INTERFACE GRAPHIQUE) par aera group
Source avec Zip Source avec une capture ALBUMEUR PHOTO: SCRIPT DE CRÉATION D'ALBUM PHOTO EN HTML À P... par vychnou
Source avec une capture CONVERTISSEUR FICHIER CAML -> FICHIER HTML par jpountz

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Help : Python/DB/CGI [ par Chill_Sik ] Bonjour à tous, voila qqjours que je me casse les dents sur un petit problème alors je me décide a appeler "au secour" car on ne sait jamais que certa comment créer un fichier HTML avec Python [ par anwaarber ] salut a tous,j'ai un probl&#232;me lors de la cr&#233;ation d'un fichier HTML avec pythonsurtout quand je fait passer des variables dans le code :def Python peut être interpreté par un navigateur comme dans html [ par rabikisa ] Est-ce possible d'interpreter python à partir d'un navigateur si on utilise une base de données gadfly?(comme les pages html quoi...)si possible comme Script Python pour html [ par aera group ] Bonjour, je uis actuelement au chapitre 17 du tutoriel de Gérard Swinnen : Apprendre à programmer avec Python (téléchargable sur http://www.cifen.ulg. html [ par MimiEtude ] slt tous le monde!!!pouvez  vous m'expliquer le sens ou bien la fonction de cette instruction?&lt;meta name="MSSmartTagsPreventParsing" content="TRUE" Modifier titre page html [ par miniimoi ] Bonjour,je dois créer un proxy en python pour un projet et il faut que je recupere le titre de la page html et le modifier.Je suis novice dans ce doma recupérer le contenu html d'1 site [ par sakusou ] salut à tous, Je dois récupérer le contenu html d'un site web à partir de l'url en python, pour faire ça, j'ai pensé à d'abord récupérer l'arborescenc click sur un bouton html [ par ziedff ] je veux cliquer sur un bouton HTML en utilisant du code Python


Nos sponsors


Sondage...

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 4,852 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales