Thiago Avelino Desenvolvedor Python, Django e MongoDB



May archive

Python Web ou Django (Framework MVC Design Pattern)

May 25, 2010

Bom hoje temos alguns Framework (MVC) Python na web, vou estar comparando o source Python Web com Django, simplesmente ficou mais somples.

Python Web:

#!/usr/bin/python

import MySQLdb

print "Content-Type: text/html"
print
print "<title>Books</title>"
print ""
print "<h1>Books</h1>"
print "<ul>"
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
    print "<li>%s</li>" % row[0]
print "</ul>"
print ""
connection.close()

Django (MVC Design Pattern):

# models.py (the database tables)

from django.db import models

class Book(models.Model):
    name = models.CharField(maxlength=50)
    pub_date = models.DateField()

# views.py (the business logic)

from django.shortcuts import render_to_response
from models import Book

def latest_books(request):
    book_list = Book.objects.order_by('-pub_date')[:10]
    return render_to_response('latest_books.html', {'book_list': book_list})

# urls.py (the URL configuration)

from django.conf.urls.defaults import *
import views

urlpatterns = patterns('',
    (r'latest/$', views.latest_books),
)

# latest_books.html (the template)

<title>Books</title>

<h1>Books</h1><ul>{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %} </ul>

pyBotIRC Bot em Python para IRC

May 23, 2010

Bot simples usando socket no Python:

import sys
import socket
import string

HOST="irc.freenode.net"
PORT=6667
NICK="pyAvelino"
IDENT="pyAvelino"
REALNAME="pyBotIRC"
readbuffer=""
CHANNELINIT="#channel"

s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
s.send('JOIN %s\r\n' % CHANNELINIT)

while 1:
# readbuffer=readbuffer+s.recv(1024)
readbuffer=s.recv(1024)
print readbuffer
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop( )

for line in temp:
    line=string.rstrip(line)
    line=string.split(line)

    if(line[0]=="PING"):
        s.send("PONG %s\r\n" % line[1])