"…mais ce serait peut-être l'une des plus grandes opportunités manquées de notre époque si le logiciel libre ne libérait rien d'autre que du code…"

Archives du 21 janvier 2008

Comment poster du code python avec WordPress ? -> [sourcecode language="python"']xxxx [/sourcecode]

Publié par patrick le janvier 21, 2008

Pour poster du code python, il faut utiliser dans la fenêtre de composition visuel de l’éditeur et placer le code python entre les balises suivantes: balises python

'['sourcecode language="python"']'  xxxx [/sourcecode]

supprimer les '' autour de '[' et ']'

Source: http://www.edwardandrewrobinson.com/source_code_to_wordpress.txt

Exemple 1:

indentation python
#This
#is an example
#of what your source code will look like
x = True
if x:
    print 'hello world'

Exemple 2:

sourcecode_python1.png
from django.utils.translation import ugettext as _
def my_view(request):
    output = _("Welcome to my site.")
    return HttpResponse(output)

Exemple 3:



exemple 3
def my_view(request):
    sentence = 'Welcome to my site.'
    output = _(sentence)
    return HttpResponse(output)

Publié dans blogs, python, Web applications, wordpress | Tagué: | Poster un commentaire »

Twisted : le moteur réseau événementiel écrit en Python + scapy l’outil python très puissant d’analyse de paquets + kamaelia le framework python développé par la BBC

Publié par patrick le janvier 21, 2008

Dans Linux-Fr, on parle du passage de NuLog de PHP à Python (utilisation de Twisted). C’est donc une bonne occasion de parler de Twisted.

- http://linuxfr.org/2008/01/18/23582.html ("Sécurité : Nulog 2 est disponible Posté par _gryzor_ (display_envoyermessageperso(‘_gryzor_’);). Modéré le vendredi 18 janvier. isadmin(’23582′)

Voici la 2ème génération de l’incontournable outil d’analyse de fichiers journaux de pare-feu. Nulog2, presque 6 ans après la v1, s’appuie toujours sur un format de journalisation SQL, mais présente les informations de manière plus synthétique, et beaucoup plus exploitable.
Au menu des nouveautés :

  • Réécriture complète du code, passage de PHP à Python avec Twisted Matrix ;
  • Génération à la volée de diagrammes et de camemberts, au souhait de l’utilisateur ;
  • Personnalisation totale de la page d’accueil, pour chaque utilisateur ;
  • Refonte de l’ergonomie de l’outil et de la manipulation des critères d’affichage des connexions réseaux ;
  • Possibilités de recherches beaucoup plus avancées ;
  • Export des données affichées en CSV pour traitement personnalisé ;
  • Passage à la licence GPLv3.

Bien entendu, Nulog2, permet, comme la v1, d’exploiter des logs authentifiés par un pare-feu NuFW. Il est donc très simple de créer ses propres indicateurs à placer sur sa page d’accueil, par exemple "Histogramme des derniers paquets droppés des trois dernières heures de l’IP 10.56.140.47 ou de l’utilisateur Martin".

Voir:

- http://en.wikipedia.org/wiki/Twisted_%28software%29 ("Twisted is an event-driven network programming framework written in Python and licensed under the MIT License. Twisted projects variously support TCP, UDP, SSL/TLS, IP Multicast, Unix domain sockets, a large number of protocols (including HTTP, NNTP, IMAP, SSH, IRC, FTP, and others), and much more. Twisted is based on the event-driven programming paradigm, which means that users of Twisted write short callbacks which are called by the framework...Deferreds Central to the Twisted application model is the concept of a deferred (elsewhere called a future). A deferred is a value which has not been computed yet, for example because it needs data from a remote peer. Deferreds can be passed around, just like regular objects, but cannot be asked for their value. Each deferred supports a callback chain. When the deferred gets the value, it is transferred through the callback chain, with the result of each callback being the input for the next one. This allows operating on the values of a deferred without knowing what they are…")

Twisted

- http://twistedmatrix.com/trac/wiki/Downloads  ("Source Checkout .To checkout code from the repository, use: 

svn co svn://svn.twistedmatrix.com/svn/Twisted/trunk  Twisted")

- http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/84317 ("Easy threading with Futures. Although Python’s thread syntax is nicer than in many languages, it can still be a pain if all one wants to do is run a time-consuming function in a separate thread, while allowing the main thread to continue uninterrupted. A Future provides a legible and intuitive way to achieve such an end.")

- http://linuxfr.org/2008/01/18/23582.html ("Explications du passage de PHP à Python par Eric Leblond. La question est mieux posée dans le sujet que dans le corps du message. Il y a en effet deux choses séparées : 1) le passage d’un langage à un framework et 2) le passage de PHP à Python
Le choix 1 est simple : J’ai commencé à travaillé sur nulog 1) (connu comme ulog-php à l’époque) aux alentours de 2001/2002 . La notion de framework n’était pas encore bien implantée (voir même n’existait pas). Début 2007, nulog commençait à devenir difficile à faire évoluer et nous avons donc décidé de lancer un projet de réécriture au sein d’INL (dont je fais parti). Le projet Nulog 2 a ainsi été initié avec dès le départ la décision d’utiliser un framework et une architecture MVC. Le choix 2) s’explique par plusieurs points: Grandes qualités du framework Twisted, notamment capacité à offrir des vues dans des protocoles variés (SOAP, XML-RPC, IRC, HTTP). Présence de bons développeurs Python à INL, développeurs capable d’épauler Romain Bignon, développeur principal de Nulog 2. Langage PHP trop laxiste et surtout lié au web alors que l’on souhaitait ne pas se limiter à ce media. L’ensemble de ces raisons nous ont fait abandonner PHP pour passer à Python/Twisted
.")

- le numéro 100 de Linux Magazine p.72 "Utilisez Twisted, un moteur réseau événementiel écrit en Python et sous licence MIT" écrit par Sylvain de Tilly.

- http://nufw.org/ ("NuFW ajoute la notion d’utilisateurs aux règles de filtrage. Le projet s’appuie sur Netfilter, la couche pare-feu du noyau Linux et est disponible sous licence GPLv3.")

- http://software.inl.fr/trac/wiki/EdenWall/NuLog2 ("Nulog2 is a complete rewrite of Nulog the historical filtering log analysis solution from INL. Nulog2 is an application build upon Twisted, an advanced Python framework…You can also directly checkout subversion source:

svn co http://software.inl.fr/svn/mirror/edenwall/nulog2/trunk/ nulog2

Nulog2′s Source are available for browsing…")

- http://inl.fr/ ("INL propose des solutions Logiciels Libres aux entreprises et administrations qui cherchent des services et produits fiables et sécurisés. Nous fournissons des produits intégrés de haut niveau, autour de solutions bien connues, comme Spamassassin, Postfix, Apache, etc, auxquelles nous contribuons. Nous menons également des développements innovants, à la pointe des technologies actuelles au bénéfice de la communauté du Logiciel Libre.")

- http://wiki.python.org/moin/WebServers ("TwistedMatrix includes a very scalable web server written in Python.")

- http://wiki.python.org/moin/TwistedMatrix ("*NOT* just framework for WebProgramming. Includes a scalable and safe web server that outperforms apache in terms of security and scalability")

Sujet lié à la sécurité et au réseau: scapy

- http://linuxfr.org/2007/10/27/23264.html ("Scapy est un utilitaire Open Source en Python développé par Philippe Biondi, cet outil vous permet de disséquer, de forger, de recevoir et d’émettre des paquets (et des trames) de données pour un grand nombre de protocoles que vous pourrez également décoder : DNS, DHCP, ARP, SNMP, ICMP, IP, TCP, UDP. L’un des seuls points faibles connu à ce jour, concernant Scapy, est son manque de documentation officielle ou non, notamment francophone, permettant de le destiner à un plus large public que les experts du domaine ; partant de ce constat, le site Secuobs.com, spécialisé dans le domaine de la sécurité informatique, met à disposition de tous un document venant combler une partie de ce manque. Vous y apprendrez notamment comment installer et configurer Scapy ainsi que les rêgles rudimentaires relatives à son utilisation (commandes basiques et avancées) et à la manipulation de paquets (et de trames) de données dont un exemple de génération de graphiques 2D/3D à partir des résultats d’un traceroute réalisé à l’aide de Scapy.

")

- http://trac.secdev.org/scapydoc-com/wiki/FRscapydoc ("D’après la documentation officielle (man scapy), Scapy est un puissant programme interactif de manipulation de paquets. Il peut forger ou décoder les paquets d’un grand nombre de protocoles, les émettre, les capturer, faire correspondre des requêtes et des réponses et bien plus encore. Il permet la manipulation de la plupart des outils de scan, traceroute, de sonde, de tests unitaires, d’attaques ou de découverte de réseau (il remplace facilement hping, 85% de nmap, arpspoof, arp-sk, arping, tcpdump, tethereal, p0f, etc.). Il se comporte également très bien sur un grand nombre de tâches qu’un grand nombre de programme n’est pas en mesure de manipuler, comme envoyer des trames invalides, injecter vos propres trames 802.11, combiner des techniques (VLAN hopping+ARP cache poisoning, VOIP decoding sur canal chiffré en WEP…), etc.Scapy est écrit en python, parce que le python, c’est bien. Personne n’a besoin de comparer Python à Ruby. Par contre, tout le monde se sent obligé de comparer Ruby à Python. À vous d’en tirer les conclusions.)")

- http://trac.secdev.org/scapydoc-com/wiki/FrInstall ("Scapy est un logiciel écrit en langage Python qui se rapproche de la famille des langages de script. Pour pouvoir utiliser Scapy, il suffit donc de posséder un interpréteur de commande Python.

Commencez par télécharger le script avec l’une des méthodes suivantes :

  • La dernière version issue du dépôt (recommandé, mis à jour régulièrement)
  • Le tarball, version 1.1.1 (peu mis à jour)

Il vous suffit de copier le script dans le répertoire de votre librairie python actuelle :

wget http://hg.secdev.org/scapy/raw-file/tip/scapy.py
cp scapy.py /var/lib/python-support/python2.4/

Il peut être intéressant de créer un lanceur directement dans le répertoire d’exécution des binaires de l’utilisateur :

$ cat /usr/bin/scapy
#!/bin/sh
exec /usr/bin/python /var/lib/python-support/`pyversions -d`/scapy.py

Si vous possédez une distribution GNU/Linux :

aptitude install scapy
urpmi scapy

Il existe également un portage pour l’OS privatif de Microsoft :

Vous avez maintenant les outils nécessaires, passons à la mise en pratique")

- pour information, Philippe Biondy prépare un numéro spécial sur Python pour Linux Magazine (source http://lists.afpy.org/mailman/listinfo/afpy-membres)

======================

Kamaelia

http://en.wikipedia.org/wiki/Kamaelia  ("Kamaelia is a free software/open source Python-based systems-development tool and concurrency framework produced by BBC Research. Kamaelia applications are produced by linking independent components together. These components communicate entirely through "inboxes" and "outboxes" (queues) largely removing the burdens of thread-safety and IPC from the developer. This also makes components reusable in different systems, allows easy unit testing and results in parallelism (between components) by default. Components are generally implemented as generators – a method more light-weight than allocating a thread to each (though this is also supported). As a result, switching between the execution of components in Kamaelia systems is very fast. Applications that have been produced using Kamaelia include a Freeview digital video recorder, a network-shared whiteboard, a 3D GUI, an HTTP Server, an audio mixer, a stream multicasting system and a simple BitTorrent client.")

- http://kamaelia.sourceforge.net/Introduction ("A key aim of Kamaelia is to enable even novice programmers to create scalable and safe concurrent systems, quickly and easily. Lego/K’nex for programmers. For people. For building things. It’s about making concurrency on systems easier to use, so easy you forget that you’re using it. It’s been done once before, spectacularly well, so well many people forget it’s there, a key example – unix pipelines. However it’s been done in hardware since day 1, since that’s how hardware works. One day, I sat back and realised that network systems looked almost identical in nature to the asynchronous hardware systems, conceptually, with one major exception. In hardware, you don’t know who your buffers are connected to via wires. You have a protocol for getting that information over (be it a clock, or handshake circuits) but no other knowledge. Kamaelia was borne, technology wise, from the idea "what if we developed software like hardware" – each component with no direct knowledge of any other. Similar to programs in a unix pipeline. This is proving to be a very useful approach. Kamaelia is the result. Kamaelia is divided into 2 sections:

  • Axon – this is a framework, developed by application spikes, for wrapping active objects. Specifically these are generators (mainly) and threads. The resulting library at it’s core is pretty simple – a novice programmer can learn python one week and implement their own version in about a week.
  • Kamaelia – this is the toy box – a library of components you can take and bolt together, and customise. This includes components for TCP/multicast clients and servers, backplanes, chassis, Dirac video encoding & decoding, Vorbis decoding, pygame & Tk based user interfaces and Tk, visualisation tools, presentation tools, games tools…

The reason for concurrency here isn’t because we’re after performance, but due to the problems we’re facing are naturally
concurrent – millions of people watching content
. Therefore, the aim is to make dealing with this concurrency simple/easy, or natural/fun. Hence the lego/K’nex analogy
.
")

- http://kamaelia.sourceforge.net/Repository ("Checking out a working copy

From the command line:

You can check out the whole repository, but be warned, we use alot of branches – so your initial checkout may be rather large! You can also view the repository contents from a web browser here. There are more details about the subversion service on sourceforge.net. Keeping abreast of check-ins:
Keep tabs on the check-ins we make by subscribing to the kamaelia-commits mailing list.
")

- http://yeoldeclue.com/cgi-bin/blog/blog.cgi ("un blog très original")

- http://darkness.codefu.org/wordpress/ ("Kamaelia looks interesting. The system of “wiring” components together feels right to me; I was first exposed to this in NesC. However, the implementation needs to be updated to support the new features of generators in Python 2.5, as the current syntax strikes me as rather ugly. In fact, it looks like Kamaelia needs a recent release, period: the last one I saw was from 2006… (As a side note: everything should be easy_installable. Kamaelia and Twisted are not, though Twisted has ongoing work to this end".)

- http://yeoldeclue.com/cgi-bin/blog/blog.cgi?rm=viewpost&nodeid=1200187974 ("Interesting wishlist for kamaelia (and others, but I’m interested from a kamaelia perspective) here: http://darkness.codefu.org/wordpress/2007/12/26/295
I’m not sure I buy all the criticisms, and feel they’re more a wish-list in terms of improvements specific points mentioned about kamaelia as (IMO) potential wishlist items:
")")

Publié dans 2008, Internet, MVC, network applications, python, Sécurité informatique | Tagué: , , | Poster un commentaire »

Nouvelles de python pour la semaine du 14 au 20 janvier 2008

Publié par patrick le janvier 21, 2008

En vrac, quelques nouvelles de python

================================
- http://highscalability.com/youtube-architecture ("- encore sur la liste Tutor, on apprend que YouTube emploie Python: YouTube grew incredibly fast, to over 100 million video views per day, with only a handful of people responsible for scaling the site. How did they manage to deliver all that video to all those users? And how have they evolved since being acquired by Google?

Information Sources

  • Google Video

    Platform

  • Apache
  • Python
  • Linux (SuSe)
  • MySQL
  • psyco, a dynamic python->C compiler
  • lighttpd for video instead of Apache

    What’s Inside?

    The Stats

  • Supports the delivery of over 100 million videos per day.
  • Founded 2/2005
  • 3/2006 30 million video views/day
  • 7/2006 100 million video views/day
  • 2 sysadmins, 2 scalability software architects
  • 2 feature developers, 2 network engineers, 1 DBA
  • Web Servers

  • NetScalar is used for load balancing and caching static content.
  • Run Apache with mod_fast_cgi.
  • Requests are routed for handling by a Python application server.
  • Application server talks to various databases and other informations sources to get all the data and formats the html page.
  • Can usually scale web tier by adding more machines.
  • The Python web code is usually NOT the bottleneck, it spends most of its time blocked on RPCs.
  • Python allows rapid flexible development and deployment. This is critical given the competition they face.
  • Usually less than 100 ms page service times.
  • Use psyco, a dynamic python->C compiler that uses a JIT compiler approach to optimize inner loops.
  • For high CPU intensive activities like encryption, they use C extensions.
  • Some pre-generated cached HTML for expensive to render blocks.
  • Row level caching in the database.
  • Fully formed Python objects are cached.
  • Some data are calculated and sent to each application so the values are cached in local memory. This is an underused strategy. The fastest cache is in your application server and it doesn’t take much time to send precalculated data to all your servers. Just have an agent that watches for changes, precalculates, and sends….)
  • =============================
    - http://www.oreillynet.com/onlamp/blog/2008/01/pymotw_threading.html ("Doug Hellman’s Python Module of the Week is all about threading.")

    - http://www.python.org/dev/peps/pep-0369/ ("This PEP proposes enhancements for the import machinery to add post import hooks. It is intended primarily to support the wider use of abstract base classes that is expected in Python 3.0.The PEP originally started as a combined PEP for lazy imports and post import hooks. After some discussion on the python-dev mailing list the PEP was parted in two separate PEPs ")

    - http://www.python.org/dev/peps/pep-3119/ (… Abstract This is a proposal to add Abstract Base Class (ABC) support to Python 3000. It proposes:

    • A way to overload isinstance() and issubclass().
    • A new module abc which serves as an "ABC support framework". It defines a metaclass for use with ABCs and a decorator that can be used to define abstract methods.
    • Specific ABCs for containers and iterators, to be added to the collections module.

    Much of the thinking that went into the proposal is not about the specific mechanism of ABCs, as contrasted with Interfaces or Generic Functions (GFs), but about clarifying philosophical issues like "what makes a set", "what makes a mapping" and "what makes a sequence". There’s also a companion PEP 3141, which defines ABCs for numeric types. Acknowledgements Talin wrote the Rationale below [1] as well as most of the section on ABCs vs. Interfaces. For that alone he deserves co-authorship. The rest of the PEP uses "I" referring to the first author. In the domain of object-oriented programming, the usage patterns for interacting with an object can be divided into two basic categories, which are ‘invocation’ and ‘inspection’. Invocation means interacting with an object by invoking its methods. Usually this is combined with polymorphism, so that invoking a given method may run different code depending on the type of an object. Inspection means the ability for external code (outside of the object’s methods) to examine the type or properties of that object, and make decisions on how to treat that object based on that informationone of the criticisms of inspection by classic OOP theorists is the lack of formalisms and the ad hoc nature of what is being inspected. In a language such as Python, in which almost any aspect of an object can be reflected and directly accessed by external code, there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking ‘is this object a mutable sequence container?’, one can look for a base class of ‘list’, or one can look for a method named ‘__getitem__’. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positivesThis PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object’s inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance(), and the presence of a particular ABC means that the test has passed…Specification The specification follows the categories listed in the abstract:

    • A way to overload isinstance() and issubclass().
    • A new module abc which serves as an "ABC support framework". It defines a metaclass for use with ABCs and a decorator that can be used to define abstract methods.
    • Specific ABCs for containers and iterators, to be added to the collections module.")

    - http://www.webfaction.com/demos/django ("How to install a real-life Django application on our servers. Watch Demo")

    - http://www.vulnerabilite.com/securite-open-source-audit-faille-coverity-actualite-20080110223332.html ("Doté d’une enveloppe initiale de 300 000 dollars, le programme Open Source Hardening Project a été lancé en mars 2006 avec pour mécène le département américain de la sécurité intérieure ( DHS ). Ce programme dont la conduite a été confiée à l’Université de Standford et à la société Coverity, a pour objectif de passer au crible le code de plusieurs logiciels open source (écrits en C et C++) parmi les plus populaires afin d’identifier les failles présentes, et ainsi contribuer au renforcement de leur sécurité... La société basée à San Francisco a par ailleurs défini plusieurs niveaux dans le processus de correction de bugs, soit 3 au total et a annoncé mardi que 11 projets open source ont atteint le niveau le plus élevé ( Rung 2 ). En raison des efforts fournis pour assurer de façon proactive l’intégrité et la sécurité des applications développées, Coverity indique que les entreprises et particuliers peuvent choisir avec encore plus de confiance les logiciels open source suivants : Amanda, NTP, OpenPAM, OpenVPN, Overdose, Perl, PHP, Postfix, Python, Samba et TCL... Si tous les logiciels contrôles ne peuvent pas encore prétendre au Rung 2, certains le pourront dans les prochains mois mais en attendant, Firefox ou encore Apache restent cantonnés au Rung 1 (86 projets), voire au Rung 0 (173 projets) comme nmap ce qui signifie que les bugs détectés n’ont pas encore été corrigés")

    - http://holdenweb.blogspot.com/2008/01/resolver-released.html ("In yet another piece of good news for Python fans, Resolver Systems have released their first product. It’s a spreadsheet that you can manipulate in Python, and it’s received a lot of interest from the financial communities on both sides of the Atlantic. [You would not believe how much of the world's financial dealing is controlled and managed by spreadsheets; it's really quite scary]. Resolver One is written in IronPython by a team which includes the Fuzzyman (occasionally also known as Michael Foord), of Voidspace Techie Blog fame, and it’s currently the largest product developed in that languages, with a total codebase (including tests) of over 100 kloc. The company is bravely making the product available (though not, I believe, as open source) free for non-commercial use.")

    Publié dans 2008, Ironpython, python, Web applications, Web Frameworks | Tagué: , , , , , | Poster un commentaire »

     
    Suivre

    Recevez les nouvelles publications par mail.

    Joignez-vous à 35 followers