<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
<channel>
    <title>Posteet: python</title> 
    <link>http://www.posteet.com/</link> 
    <description>Recent posteets posted to Posteet</description>
    <ttl>60</ttl>

    
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/posteet_python" /><feedburner:info uri="posteet_python" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
        <title>obtener la url final</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/sBgtV9cO5oA/2106</link>
        <description>
        <![CDATA[<pre>import urllib2
f = urllib2.urlopen('https://graph.facebook.com/macks.r2r/picture')
print f.geturl()</pre> <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a>  <a href="http://www.posteet.com/tags/tips">[tips]</a>  <a href="http://www.posteet.com/tags/urllib2">[urllib2]</a>  <a href="http://www.posteet.com/tags/urls">[urls]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Tue, 19 Oct 2010 01:25:21 +0200</pubDate>

            <category>python</category>
            <category>soluciones</category>
            <category>tips</category>
            <category>urllib2</category>
            <category>urls</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2106</feedburner:origLink></item>

  
    <item>
        <title>Trabajando con archivos y directorios | Python</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/zSe_c7js9nk/2105</link>
        <description>
        <![CDATA[<pre>Trabajando con archivos y directorios con Python¶
Listado de archivos en un directorio¶

Para buscar todos los archivos con una extensión, por ejemplo .jpg:

import glob
lista = glob.glob(&quot;*.jpg&quot;)

Para listar todos los archivos de un directorio:

import os
ficheros = os.listdir('/home/alumno/ejercicios/python') # linux
ficheros = os.listdir(r'c:Documents and SettingsalumnoEscritorioejerciciospython') #windows: cuidado con el caracter 

Directorio actual:

os.getcwd()
os.curdir

Tipos de ficheros¶

print michero, 'es un', 
if os.path.isfile(mifichero):
    print 'fichero'
if os.path.isdir(mifichero):
    print 'directorio'
if os.path.islink(mifichero):
    print 'enlace'

Último acceso a un fichero¶

ultimo_acceso = os.path.getatime('foto.jpg')
ultima_modificacion = os.path.getmtime('foto.jpg')
tiempo_en_dias = (time.time()- ultimo_acceso)/ (60*60*24)
print tiempo_en_dias

Eliminar ficheros y directorios¶

os.remove('mifoto.jpg')
for foto in glob.glob('*.jpg') + glob.glob('*.tif'):
    os.remove(foto)

Eliminar directorio:

import shutil
shutil.rmtree('midirectorio')

Copiar y renombrar ficheros¶

import shutil
shutil.copy(mifichero, copiafichero)

# copia también tiempo de último acceso y última modificación
shutil.copy2(mifichero, copiafichero)

# copia un árbol de directorios
shutil.copytree(raiz_de_directorio, copia_directorio)

Manipulando los paths y nombres¶

Rutas

&gt;&gt;&gt; os.path.split('/home/alumno/python/ejercicios/ej1.py')
('/home/alumno/python/ejercicios', 'ej1.py')
&gt;&gt;&gt; os.path.basename('/home/alumno/python/ejercicios/ej1.py')
'ej1.py'
&gt;&gt;&gt; os.path.dirname('/home/alumno/python/ejercicios/ej1.py')
'/home/alumno/python/ejercicios'

Extensiones

&gt;&gt;&gt; os.path.splitext('pelicula.avi')
('pelicula', '.avi')

Crear y moverse entre directorios¶

directorioOriginal = os.getcwd()
directorio = os.path.join(os.pardir, 'miNuevoDir')
if not os.path.isdir(directorio):
    os.mkdir(directorio)
os.chdir(directorio)
...
os.chdir(directorioOriginal) # vuelve al directorio inicial
os.chdir(os.environ['HOME']) # cambia al directorio home</pre> <a href="http://www.posteet.com/tags/ficheros">[ficheros]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/tips">[tips]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Wed, 13 Oct 2010 18:24:18 +0200</pubDate>

            <category>ficheros</category>
            <category>python</category>
            <category>tips</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2105</feedburner:origLink></item>

  
    <item>
        <title>agregar funciones a la plantilla jinja</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/jCT4b9_BYFY/2104</link>
        <description>
        <![CDATA[<pre>#---libs/date.py
def format_date(value, format=&quot;%d/%m/%Y %H:%M:%S&quot;):
	return value.strftime(format)

#-----settings
from libs.filters import format_date
from jinja2 import Environment, FileSystemLoader
TEMPLATE_ENV.filters[&quot;format_date&quot;] = format_date

#---template
&lt;td&gt;{{ h.date|format_date('%d/%m/%Y') }}&lt;/td&gt;</pre> <a href="http://www.posteet.com/tags/jinja">[jinja]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a>  <a href="http://www.posteet.com/tags/tips">[tips]</a>  <a href="http://www.posteet.com/tags/tornado">[tornado]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Wed, 06 Oct 2010 00:52:07 +0200</pubDate>

            <category>jinja</category>
            <category>python</category>
            <category>soluciones</category>
            <category>tips</category>
            <category>tornado</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2104</feedburner:origLink></item>

  
    <item>
        <title>python - twitter</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/TzHu0_TnvPk/2095</link>
        <description>
        <![CDATA[<pre>#instalar python - twitter http://code.google.com/p/python-twitter/downloads/list

import twitter
import re
api      = twitter.Api(username, password)
#1. actualizar el estado
 api.PostUpdate('Tweet desde python ;)') #

#2. recuperar tus posts con links a otros uasuarios o los hashtags
    statuses = api.GetUserTimeline()
    posts=[]

    for s in statuses:
        tweet = s.text;
        hash_regex = re.compile(r'#[0-9a-zA-Z+_]*',re.IGNORECASE)
        user_regex = re.compile(r'@[0-9a-zA-Z+_]*',re.IGNORECASE)
        savelog(hash_regex,'hashR')
        savelog(smart_str(tweet),'tweet')
        for tt in user_regex.finditer(tweet):
            url_tweet = tt.group(0).replace('@','')
            tweet = tweet.replace(tt.group(0),
                    '&lt;a href=&quot;http://twitter.com/'+
                    url_tweet+'&quot; title=&quot;'+
                    tt.group(0)+'&quot;&gt;'+
                    tt.group(0)+'&lt;/a&gt;')

        for th in hash_regex.finditer(tweet):
                url_hash = th.group(0).replace('#','%23')
                if len ( th.group(0) ) &gt; 2:
                    tweet = tweet.replace(th.group(0),
                            '&lt;a href=&quot;http://search.twitter.com/search?q='+
                            url_hash+'&quot; title=&quot;'+
                            th.group(0)+'&quot;&gt;'+
                            th.group(0)+'&lt;/a&gt;');

        posts.append({'summary': tweet})</pre> <a href="http://www.posteet.com/tags/api">[api]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/twitter">[twitter]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Fri, 06 Aug 2010 19:27:04 +0200</pubDate>

            <category>api</category>
            <category>python</category>
            <category>twitter</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2095</feedburner:origLink></item>

  
    <item>
        <title>PIL +  pasar todos los formatos a jpg</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/_ZoqEDTWigU/2090</link>
        <description>
        <![CDATA[<pre>image = Image.open(imageField)
if image.mode != &quot;RGB&quot;:
    image = image.convert(&quot;RGB&quot;)
    #big
    image.save('image.jpg')</pre> <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/PIL">[PIL]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Wed, 21 Jul 2010 22:42:56 +0200</pubDate>

            <category>django</category>
            <category>PIL</category>
            <category>python</category>
            <category>soluciones</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2090</feedburner:origLink></item>

  
    <item>
        <title>extender auth_user django modificando campos -- (aplicando herencia)</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/VmN_aG9eAjU/2083</link>
        <description>
        <![CDATA[<pre>#1
from django.db import models
from django.contrib.auth.models import User, UserManager

class CustomUser(User):
    birthday = models.DateField()
    activation_key = models.CharField(max_length=255, blank=True, default='')
    photo_url = models.CharField(max_length=50, blank=True) # cant incrementada de votaciones
    User._meta.get_field('username')._unique = False
    User._meta.get_field('email')._unique = True
    User._meta.get_field_by_name('username')[0].max_length=75

#2 save child class
from users.models import CustomUser
def saveCustomUsers(request):
    usr = CustomUser()
    usr.username = 'macks'
    usr.password = '123456'
    usr.activation_key = 'sfsdf123456'
    usr.birthday = datetime.now()
    usr.photo_url = 'image.jpg'
    usr.save()</pre> <a href="http://www.posteet.com/tags/clases">[clases]</a>  <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/herencia">[herencia]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Fri, 25 Jun 2010 19:42:32 +0200</pubDate>

            <category>clases</category>
            <category>django</category>
            <category>herencia</category>
            <category>python</category>
            <category>soluciones</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2083</feedburner:origLink></item>

  
    <item>
        <title>incluir variables generales a la plantilla-- inclusion tags</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/-8oaCF9OjNw/2079</link>
        <description>
        <![CDATA[<pre>#agregar templatetags a APPS de settings

1.-
apps/templatetags/userInfoTag.py

# -*- coding: utf-8 -*-
from django import template
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User

register = template.Library()
@register.inclusion_tag('admin/users/inclusionTags/userRecordsTags.html', takes_context=True)
def userRecords(context):
    request = context['request']
    user = get_object_or_404(User, id=request.user.id)
    userName = user.first_name + ' ' + user.last_name
   
    return {'userName': userName}

2.-
apps/templatetags/__init__.py
from django.template import add_to_builtins
add_to_builtins('templatetags.userInfoTag')

3.-
templates/admin/users/inclusionTags/userRecordsTags.html
{{ userName }} # return value of userInfotag.py

4.- 

#se puede usar la plantilla userRecords.html en culaquiera otra plantilla

templates/admin/users/indexSuccess.html
&lt;td&gt;{% userRecords %}&lt;/td&gt;  #def userRecords</pre> <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a>  <a href="http://www.posteet.com/tags/utiles">[utiles]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Wed, 16 Jun 2010 19:35:53 +0200</pubDate>

            <category>django</category>
            <category>python</category>
            <category>soluciones</category>
            <category>utiles</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2079</feedburner:origLink></item>

  
    <item>
        <title>descargar images en disco</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/aiLt4GvYW9M/2073</link>
        <description>
        <![CDATA[<pre>def downloadImage(self):
    img_url = 'http://img1cdn.adoosimg.com/b195d543e38e349deac032b41be043c7-1-5.jpg'
    imgName = 'b195d543e38e349deac032b41be043c7-1-5.jpg'
    imgN = &quot;peque_%s&quot;%imgName.replace('5.','7.') if imgName[-5:]=='5.jpg' else imgName
   
    file_path = &quot;%s/adoos/%s&quot; % (settings.UPLOAD_PATH, imgN)
    downloaded_image = file(file_path, &quot;wb&quot;)

    image_on_web = urllib.urlopen(img_url)
    while True:
        buf = image_on_web.read(65536)
        if len(buf) == 0:
            break
        downloaded_image.write(buf)
    downloaded_image.close()
    image_on_web.close()

    return  file_path</pre> <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a>  <a href="http://www.posteet.com/tags/tips">[tips]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Thu, 29 Apr 2010 00:20:37 +0200</pubDate>

            <category>django</category>
            <category>python</category>
            <category>soluciones</category>
            <category>tips</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2073</feedburner:origLink></item>

  
    <item>
        <title>validacion de form. no espacios en blanco ni caracterres especiales</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/oaR73cBQibc/2069</link>
        <description>
        <![CDATA[<pre>def __validateVideoName(videoname):
    import string
    rs = False
    if videoname:
        whiteSpace = False if re.search(' ',videoname) else True
        specialChar = True if re.compile('[a-zA-Z0-9._-]+$').match(videoname) else False
        if whiteSpace and specialChar:
            rs = True
            
    return rs</pre> <a href="http://www.posteet.com/tags/custom">[custom]</a>  <a href="http://www.posteet.com/tags/expresiones regulares">[expresiones regulares]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Tue, 13 Apr 2010 23:03:57 +0200</pubDate>

            <category>custom</category>
            <category>expresiones regulares</category>
            <category>python</category>
            <category>soluciones</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2069</feedburner:origLink></item>

  
    <item>
        <title>salto de linea en notepad de windows</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/ZIOnSHNfsas/2067</link>
        <description>
        <![CDATA[<pre>dsc = ['uno','dos','tres']
line = &quot;&quot;&quot;#%d# rn
%s rnrn&quot;&quot;&quot; % (i+1, dsc)</pre> <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Tue, 06 Apr 2010 23:55:34 +0200</pubDate>

            <category>python</category>
            <category>soluciones</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2067</feedburner:origLink></item>

  
    <item>
        <title>remover html tags y espaacios</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/w3ERx3XdVDI/2066</link>
        <description>
        <![CDATA[<pre>def remove_html_tags(data):
    p = re.compile(r'&lt;[^&lt;]*?/?&gt;')
    return p.sub('', data)


Here is another function to remove more than one consecutive white spaces:

def remove_extra_spaces(data):
    p = re.compile(r's+')
    return p.sub(' ', data)</pre> <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Tue, 06 Apr 2010 21:54:26 +0200</pubDate>

            <category>python</category>
            <category>soluciones</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2066</feedburner:origLink></item>

  
    <item>
        <title>convertir string a lista - python</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/woIABirDfBc/2063</link>
        <description>
        <![CDATA[<pre>string = '[1,2,3]'
list = eval(string)
print list
[1, 2, 3]</pre> <a href="http://www.posteet.com/tags/listas">[listas]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/string">[string]</a>  <a href="http://www.posteet.com/tags/tips">[tips]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Tue, 30 Mar 2010 00:24:49 +0200</pubDate>

            <category>listas</category>
            <category>python</category>
            <category>string</category>
            <category>tips</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2063</feedburner:origLink></item>

  
    <item>
        <title>Sacar imagenes de un video con ffmpeg</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/uEDXMatdb9Q/2058</link>
        <description>
        <![CDATA[<pre>import commands
import os

def execute():
        cmd = 'c:/ffmpeg/ffmpeg.exe -y -itsoffset -4 -i c:/input.mpg -vframes 1 -s 100x90 -f image2 c:/uploads/img_gen.jpg'
        #c = commands.getoutput(cmd) # linux
        c = os.system(self.cmd) #windows
        return c</pre> <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/ffmpeg">[ffmpeg]</a>  <a href="http://www.posteet.com/tags/librerias">[librerias]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a>  <a href="http://www.posteet.com/tags/tests">[tests]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Fri, 12 Mar 2010 18:15:50 +0100</pubDate>

            <category>django</category>
            <category>ffmpeg</category>
            <category>librerias</category>
            <category>python</category>
            <category>soluciones</category>
            <category>tests</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2058</feedburner:origLink></item>

  
    <item>
        <title>Generar miniaturas con PIL</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/iBaJC8u_iP8/2057</link>
        <description>
        <![CDATA[<pre>def testImages(request):
    from PIL import Image
    path = ('c:/images/soluciones__1.jpg')
    #content = 'c:/images/soluciones1.jpg'
    content = 'c:/images/image.gif'
    image = Image.open(content)
    image.thumbnail((200,150), Image.ANTIALIAS)
    image.save(path, image.format)
    savelog(image.format)
    del image</pre> <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/PIL">[PIL]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/tests">[tests]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Fri, 12 Mar 2010 18:12:44 +0100</pubDate>

            <category>django</category>
            <category>PIL</category>
            <category>python</category>
            <category>tests</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2057</feedburner:origLink></item>

  
    <item>
        <title>manipular datos de una bd externa con django</title>
        <link>http://feedproxy.google.com/~r/posteet_python/~3/Cw3cvfsAnD4/2056</link>
        <description>
        <![CDATA[<pre>from django.db import load_backend, transaction, connection

#manipular datos de una bd externa

def sincronizeDB(self):
        myBackend = load_backend('mysql') # or 'mysql', 'sqlite3', 'oracle'
        myConnection = myBackend.DatabaseWrapper({
            'DATABASE_HOST': '192.168.1.11',
            'DATABASE_NAME': 'agenciaperu_local',
            'DATABASE_OPTIONS': {},
            'DATABASE_PASSWORD': &quot;&quot;,
            'DATABASE_PORT': &quot;&quot;,
            'DATABASE_USER': &quot;root&quot;,})
        # Now we can do all the standard raw sql stuff with myConnection.
        myCursor = myConnection.cursor()        
        id = 22
        name = &quot;tecnologia para jos&quot;
        slug = &quot;tecnologia_para_jos&quot;
        row = myCursor.execute(&quot;INSERT INTO category(name, slug )  values(%s,%s);&quot;, [name, slug])
        row = myConnection._commit()
        #row = transaction.rollback_unless_managed()  -----&gt; sería cuando trabajamos en local

# select simple
        #row = myCursor.execute(&quot;select *from category where id = %s and highlight = %s;&quot;,[id,0])
        myCursor.fetchall()</pre> <a href="http://www.posteet.com/tags/django">[django]</a>  <a href="http://www.posteet.com/tags/mysql">[mysql]</a>  <a href="http://www.posteet.com/tags/python">[python]</a>  <a href="http://www.posteet.com/tags/soluciones">[soluciones]</a> ]]>        </description>
        <dc:creator>macks</dc:creator>
        <pubDate>Thu, 04 Mar 2010 21:19:49 +0100</pubDate>

            <category>django</category>
            <category>mysql</category>
            <category>python</category>
            <category>soluciones</category>
    
    <feedburner:origLink>http://www.posteet.com/view/2056</feedburner:origLink></item>


</channel>
</rss>

