<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gustavo Henrique.net &#187; python</title>
	<atom:link href="http://www.gustavohenrique.net/brogui/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gustavohenrique.net/brogui</link>
	<description>Só mais um blog com Wordpress</description>
	<lastBuildDate>Tue, 29 Jun 2010 00:00:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Django usando Pisa para converter HTML para PDF</title>
		<link>http://www.gustavohenrique.net/brogui/2010/02/django-usando-pisa-para-converter-html-para-pdf/</link>
		<comments>http://www.gustavohenrique.net/brogui/2010/02/django-usando-pisa-para-converter-html-para-pdf/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 18:02:49 +0000</pubDate>
		<dc:creator>gustavohenrique</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[pisa]]></category>

		<guid isPermaLink="false">http://www.gustavohenrique.net/brogui/?p=235</guid>
		<description><![CDATA[
Pisa é um conversor de HTML/XHTML/CSS para PDF, escrito em Python e baseado nas bibliotecas Reportlab, PyPDF, TechGame Networks CSS e HTML5lib. Seu foco principal não é gerar páginas perfeitas para impressão, mas utilizar HTML e CSS para gerar PDFs dentro de aplicações.
A instalação pode ser feita através do código no site do projeto ou [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.gustavohenrique.net/brogui/wp-content/uploads/2010/02/tower_pisa.jpg"><img src="http://www.gustavohenrique.net/brogui/wp-content/uploads/2010/02/tower_pisa.jpg" alt="Torre de Pisa" title="Torre de Pisa" width="130" height="200" class="aligncenter size-full wp-image-236" /></a></p>
<p>Pisa é um conversor de HTML/XHTML/CSS para PDF, escrito em Python e baseado nas bibliotecas Reportlab, PyPDF, TechGame Networks CSS e HTML5lib. Seu foco principal não é gerar páginas perfeitas para impressão, mas utilizar HTML e CSS para gerar PDFs dentro de aplicações.<br />
A instalação pode ser feita através do código no <a href="http://pypi.python.org/pypi/pisa/" target="_blank">site do projeto</a> ou pelo comando <code>easy_install pisa</code>.</p>
<p>Crie um arquivo chamado <code>report.py</code> dentro do diretório do projeto contendo o código abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># -*- coding: utf-8 -*-</span>
<span style="color: #ff7700;font-weight:bold;">from</span> django <span style="color: #ff7700;font-weight:bold;">import</span> http
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">template</span>.<span style="color: black;">loader</span> <span style="color: #ff7700;font-weight:bold;">import</span> get_template
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">template</span> <span style="color: #ff7700;font-weight:bold;">import</span> Context
<span style="color: #ff7700;font-weight:bold;">import</span> ho.<span style="color: black;">pisa</span> <span style="color: #ff7700;font-weight:bold;">as</span> pisa
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">cStringIO</span> <span style="color: #ff7700;font-weight:bold;">as</span> <span style="color: #dc143c;">StringIO</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">cgi</span>, <span style="color: #dc143c;">os</span>
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> fetch_resources<span style="color: black;">&#40;</span>uri, rel<span style="color: black;">&#41;</span>:
    path = <span style="color: #483d8b;">'/path/para/diretorio/contendo/imagens/a/serem/exibidas'</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> path
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> write_to_pdf<span style="color: black;">&#40;</span>template_src, context_dict, filename<span style="color: black;">&#41;</span>:
    template = get_template<span style="color: black;">&#40;</span>template_src<span style="color: black;">&#41;</span>
    context = Context<span style="color: black;">&#40;</span>context_dict<span style="color: black;">&#41;</span>
    html  = template.<span style="color: black;">render</span><span style="color: black;">&#40;</span>context<span style="color: black;">&#41;</span>
    result = <span style="color: #dc143c;">StringIO</span>.<span style="color: #dc143c;">StringIO</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    pdf = pisa.<span style="color: black;">pisaDocument</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">StringIO</span>.<span style="color: #dc143c;">StringIO</span><span style="color: black;">&#40;</span>html.<span style="color: black;">encode</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;UTF-8&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>, result, link_callback=fetch_resources<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> pdf.<span style="color: black;">err</span>:
        response = http.<span style="color: black;">HttpResponse</span><span style="color: black;">&#40;</span>mimetype=<span style="color: #483d8b;">'application/pdf'</span><span style="color: black;">&#41;</span>
        response<span style="color: black;">&#91;</span><span style="color: #483d8b;">'Content-Disposition'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">'attachment; filename=%s.pdf'</span> <span style="color: #66cc66;">%</span> filename
        response.<span style="color: black;">write</span><span style="color: black;">&#40;</span>result.<span style="color: black;">getvalue</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> response
    <span style="color: #ff7700;font-weight:bold;">return</span> http.<span style="color: black;">HttpResponse</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Problema ao gerar PDF: %s'</span> <span style="color: #66cc66;">%</span> <span style="color: #dc143c;">cgi</span>.<span style="color: black;">escape</span><span style="color: black;">&#40;</span>html<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>E agora, dentro de uma <code>view</code>, é preciso importar o arquivo <code>report.py</code> e chamar a função <code>write_to_pdf</code> para fazer a conversão:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># views.py</span>
<span style="color: #ff7700;font-weight:bold;">from</span> report <span style="color: #ff7700;font-weight:bold;">import</span> write_to_pdf
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> listar_clientes_cadastrados<span style="color: black;">&#40;</span>request<span style="color: black;">&#41;</span>:
    clientes = Cliente.<span style="color: black;">objects</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> write_to_pdf<span style="color: black;">&#40;</span><span style="color: #483d8b;">'relatorio.html'</span>, <span style="color: black;">&#123;</span><span style="color: #483d8b;">'clientes'</span>: clientes<span style="color: black;">&#125;</span>, <span style="color: #483d8b;">'nome_do_arquivo_pdf'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>A função <code>write_to_pdf</code> recebe como parâmetro o nome do arquivo HTML que será convertido, as variáveis que serão tratadas dentro desse arquivo e o nome que o arquivo PDF sem a extensão. Retorna o download do arquivo PDF.</p>
<p>Conforme citado no início do post, a conversão não é perfeita. Por exemplo, às vezes uma tabela apresenta mínimas deformações, não fica igual como na versão HTML. Apesar disso Pisa é uma ótima solução que muitas vezes ajuda bastante e, como puderam ver, é muito fácil de usar.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Compartilhe esse artigo</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://buzz.yahoo.com/submit?submitUrl=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;submitHeadline=Django+usando+Pisa+para+converter+HTML+para+PDF&amp;submitSummary=" rel="nofollow" title="Adicionar ao&nbsp;Buzz"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/buzz.png" title="Adicionar ao&nbsp;Buzz" alt="Adicionar ao&nbsp;Buzz" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;title=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;Del.icio.us"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/delicious.png" title="Adicionar ao&nbsp;Del.icio.us" alt="Adicionar ao&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;title=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;digg"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/digg.png" title="Adicionar ao&nbsp;digg" alt="Adicionar ao&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F" rel="nofollow" title="Adicionar ao&nbsp;Facebook"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/facebook.png" title="Adicionar ao&nbsp;Facebook" alt="Adicionar ao&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;title=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;Google Bookmarks"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/google.png" title="Adicionar ao&nbsp;Google Bookmarks" alt="Adicionar ao&nbsp;Google Bookmarks" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.mister-wong.com/index.php?action=addurl&amp;bm_url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;bm_description=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;Mister Wong"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/misterwong.png" title="Adicionar ao&nbsp;Mister Wong" alt="Adicionar ao&nbsp;Mister Wong" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.netscape.com/submit/?U=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;T=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;Netscape"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/netscape.png" title="Adicionar ao&nbsp;Netscape" alt="Adicionar ao&nbsp;Netscape" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;title=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;reddit"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/reddit.png" title="Adicionar ao&nbsp;reddit" alt="Adicionar ao&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;title=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;Stumble Upon"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Adicionar ao&nbsp;Stumble Upon" alt="Adicionar ao&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F" rel="nofollow" title="Adicionar ao&nbsp;Technorati"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/technorati.png" title="Adicionar ao&nbsp;Technorati" alt="Adicionar ao&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://tipd.com/submit.php?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F" rel="nofollow" title="Adicionar ao&nbsp;Tip'd"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/tipd.png" title="Adicionar ao&nbsp;Tip'd" alt="Adicionar ao&nbsp;Tip'd" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Django+usando+Pisa+para+converter+HTML+para+PDF+@+http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F" rel="nofollow" title="Adicionar ao&nbsp;Twitter"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/twitter.png" title="Adicionar ao&nbsp;Twitter" alt="Adicionar ao&nbsp;Twitter" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F02%2Fdjango-usando-pisa-para-converter-html-para-pdf%2F&amp;t=Django+usando+Pisa+para+converter+HTML+para+PDF" rel="nofollow" title="Adicionar ao&nbsp;Yahoo My Web"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/yahoo.png" title="Adicionar ao&nbsp;Yahoo My Web" alt="Adicionar ao&nbsp;Yahoo My Web" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.gustavohenrique.net/brogui/2010/02/django-usando-pisa-para-converter-html-para-pdf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Acessando BD Firebird através do KinterbasDB no Python</title>
		<link>http://www.gustavohenrique.net/brogui/2010/01/acessando-firebird-atraves-do-kinterbasdb-no-python/</link>
		<comments>http://www.gustavohenrique.net/brogui/2010/01/acessando-firebird-atraves-do-kinterbasdb-no-python/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 15:00:12 +0000</pubDate>
		<dc:creator>gustavohenrique</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[firebird]]></category>

		<guid isPermaLink="false">http://www.gustavohenrique.net/brogui/?p=226</guid>
		<description><![CDATA[
KinterbasDB é uma biblioteca open source para Python que possibilita acessar banco de dados Firebird e algumas versões do Interbase.
O download pode ser feito na página do projeto.
Após o download, descompacte o pacote kinterbasdb-3.2.src.tar.gz.
Abra um terminal, entre no diretório onde o kinterbasdb foi descompactado e execute o comando python setup.py build. O script de instalação, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.gustavohenrique.net/brogui/wp-content/uploads/2010/01/firebird-icon.gif"><img src="http://www.gustavohenrique.net/brogui/wp-content/uploads/2010/01/firebird-icon.gif" alt="firebird-icon" title="firebird-icon" width="66" height="67" class="aligncenter size-full wp-image-229" /></a></p>
<p>KinterbasDB é uma biblioteca open source para Python que possibilita acessar banco de dados Firebird e algumas versões do Interbase.<br />
O download pode ser feito na <a href="http://kinterbasdb.sourceforge.net/" target="_blank">página do projeto</a>.</p>
<p>Após o download, descompacte o pacote <code>kinterbasdb-3.2.src.tar.gz</code>.<br />
Abra um terminal, entre no diretório onde o kinterbasdb foi descompactado e execute o comando <code>python setup.py build</code>. O script de instalação, setup.py, automaticamente vai detectar as informações necessárias pelo compilador C.<br />
Se não ocorreu nenhum erro, execute o comando <code>python setup.py install</code> para instalar no diretório padrão de módulos do Python (varia de acordo com a distro).</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">root@localhost: ~# wget http://downloads.sourceforge.net/project/kinterbasdb/kinterbasdb/kinterbasdb-3.2/kinterbasdb-3.2.src.tar.gz?use_mirror=ufpr
root@localhost: ~# tar zxvf kinterbasdb-3.2.src.tar.gz
root@localhost: ~# python setup.py build
Succeeded:
  /usr/bin/python setup.py build
root@localhost: ~# python setup.py install</pre></div></div>

<p>Para testar se foi instalado corretamente:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">root@localhost: ~# python -c &quot;import kinterbasdb as k; print k.__version__&quot;
(3, 2, 0, 'final', 0)
root@localhost: ~#</pre></div></div>

<p>É possível que apareça uma mensagem de erro em distros baseadas no Ubuntu:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
kinterbasdb.OperationalError: (-901, 'begin transaction: \n  invalid parameter in transaction parameter block')</pre></div></div>

<p>Para corrigir esse problema é preciso usar uma outra versão do arquivo <code>__init__.py</code>.<br />
Faça o download em <a href="https://firebird.svn.sourceforge.net/svnroot/firebird/qa/trunk/kinterbasdb/__init__.py" target="_blank">https://firebird.svn.sourceforge.net/svnroot/firebird/qa/trunk/kinterbasdb/__init__.py</a> e substitua o arquivo existente no diretório <code>kinterbasdb</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">root@localhost: ~# wget https://firebird.svn.sourceforge.net/svnroot/firebird/qa/trunk/kinterbasdb/__init__.py
root@localhost: ~# mv __init__.py /usr/lib/python2.5/site-packages/kinterbasdb/</pre></div></div>

<p>Exemplo para Firebird-2.1 em servidor Windows:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> kinterbasdb
conn = kinterbasdb.<span style="color: black;">connect</span><span style="color: black;">&#40;</span>
    host=<span style="color: #483d8b;">'192.168.0.2'</span>,
    database=<span style="color: #483d8b;">'C:<span style="color: #000099; font-weight: bold;">\\</span>Dados<span style="color: #000099; font-weight: bold;">\\</span>meubanco.fdb'</span>,
    <span style="color: #dc143c;">user</span>=<span style="color: #483d8b;">'sysdba'</span>,
    password=<span style="color: #483d8b;">'masterkey'</span>
<span style="color: black;">&#41;</span>
cur = conn.<span style="color: black;">cursor</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
cur.<span style="color: black;">execute</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'SELECT id, nome, telefone FROM tabela'</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> <span style="color: black;">&#40;</span><span style="color: #008000;">id</span>, nome, telefone<span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">in</span> cur:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'ID: %s, Nome: %s, Fone: %s'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">id</span>, nome, telefone<span style="color: black;">&#41;</span></pre></div></div>

<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Compartilhe esse artigo</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://buzz.yahoo.com/submit?submitUrl=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;submitHeadline=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python&amp;submitSummary=" rel="nofollow" title="Adicionar ao&nbsp;Buzz"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/buzz.png" title="Adicionar ao&nbsp;Buzz" alt="Adicionar ao&nbsp;Buzz" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;title=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;Del.icio.us"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/delicious.png" title="Adicionar ao&nbsp;Del.icio.us" alt="Adicionar ao&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;title=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;digg"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/digg.png" title="Adicionar ao&nbsp;digg" alt="Adicionar ao&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F" rel="nofollow" title="Adicionar ao&nbsp;Facebook"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/facebook.png" title="Adicionar ao&nbsp;Facebook" alt="Adicionar ao&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;title=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;Google Bookmarks"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/google.png" title="Adicionar ao&nbsp;Google Bookmarks" alt="Adicionar ao&nbsp;Google Bookmarks" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.mister-wong.com/index.php?action=addurl&amp;bm_url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;bm_description=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;Mister Wong"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/misterwong.png" title="Adicionar ao&nbsp;Mister Wong" alt="Adicionar ao&nbsp;Mister Wong" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.netscape.com/submit/?U=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;T=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;Netscape"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/netscape.png" title="Adicionar ao&nbsp;Netscape" alt="Adicionar ao&nbsp;Netscape" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;title=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;reddit"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/reddit.png" title="Adicionar ao&nbsp;reddit" alt="Adicionar ao&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;title=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;Stumble Upon"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Adicionar ao&nbsp;Stumble Upon" alt="Adicionar ao&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F" rel="nofollow" title="Adicionar ao&nbsp;Technorati"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/technorati.png" title="Adicionar ao&nbsp;Technorati" alt="Adicionar ao&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://tipd.com/submit.php?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F" rel="nofollow" title="Adicionar ao&nbsp;Tip'd"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/tipd.png" title="Adicionar ao&nbsp;Tip'd" alt="Adicionar ao&nbsp;Tip'd" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python+@+http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F" rel="nofollow" title="Adicionar ao&nbsp;Twitter"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/twitter.png" title="Adicionar ao&nbsp;Twitter" alt="Adicionar ao&nbsp;Twitter" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2010%2F01%2Facessando-firebird-atraves-do-kinterbasdb-no-python%2F&amp;t=Acessando+BD+Firebird+atrav%C3%A9s+do+KinterbasDB+no+Python" rel="nofollow" title="Adicionar ao&nbsp;Yahoo My Web"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/yahoo.png" title="Adicionar ao&nbsp;Yahoo My Web" alt="Adicionar ao&nbsp;Yahoo My Web" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.gustavohenrique.net/brogui/2010/01/acessando-firebird-atraves-do-kinterbasdb-no-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Script Python acessando classes do Django</title>
		<link>http://www.gustavohenrique.net/brogui/2009/12/script-python-acessando-classes-do-django/</link>
		<comments>http://www.gustavohenrique.net/brogui/2009/12/script-python-acessando-classes-do-django/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 09:00:04 +0000</pubDate>
		<dc:creator>gustavohenrique</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gustavohenrique.net/brogui/?p=163</guid>
		<description><![CDATA[Há uns dias atrás eu precisei criar um relatório com dados obtidos de um BD MySQL usado por um projeto em Django. Esse relatório deveria ser enviado no mesmo horário todos os dias. Sendo assim, criei um script em Python para executar essa tarefa e adicionei uma chamada à ele no Cron (agendador de tarefas [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.gustavohenrique.net/brogui/wp-content/uploads/2009/12/django_python.jpg"><img src="http://www.gustavohenrique.net/brogui/wp-content/uploads/2009/12/django_python.jpg" alt="" title="Django e Python" width="120" height="83" class="size-full wp-image-170" /></a><br />
Há uns dias atrás eu precisei criar um relatório com dados obtidos de um BD MySQL usado por um projeto em Django. Esse relatório deveria ser enviado no mesmo horário todos os dias. Sendo assim, criei um script em Python para executar essa tarefa e adicionei uma chamada à ele no Cron (agendador de tarefas do Linux).<br />
A primeira idéia que eu tive foi usar código SQL para obter os dados. Mas aí veio o desânimo: Eu teria que digitar muito. Pensei que se usasse o ORM do Django, em poucas linhas eu conseguiria os dados que preciso. Foi então que decidi usar as classes do Django, montar a estrutura do relatório a partir de um template HTML e enviar por e-mail.<br />
<span id="more-163"></span></p>
<h2>Utilizando as classes do projeto</h2>
<p>Vamos supor nesse exemplo que o nome projeto em Django seja <b>meuprojeto</b>, a aplicação <b>minhaapp</b> e o script <b>relatorio.py</b>. Nomes nada criativos, eu sei, mas se você entendeu&#8230; é isso que importa.<br />
Então vamos criar o arquivo <b>/usr/bin/relatorio.py</b> contendo as linhas abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/python</span>
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">core</span>.<span style="color: black;">management</span> <span style="color: #ff7700;font-weight:bold;">import</span> setup_environ
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>, <span style="color: #dc143c;">datetime</span>, settings
PROJECT_PATH = <span style="color: #483d8b;">'/home/usuario/www/django/meuprojeto'</span>
<span style="color: #dc143c;">sys</span>.<span style="color: black;">path</span>.<span style="color: black;">insert</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, PROJECT_PATH<span style="color: black;">&#41;</span>
setup_environ<span style="color: black;">&#40;</span>settings<span style="color: black;">&#41;</span></pre></div></div>

<p>O código acima é tudo que se precisa para usar o projeto dentro do script.<br />
Como exemplo, vamos criar a classe <i>Relatorio</i>, importar a aplicação em Django e instanciar as classes que queremos usar:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Importamos a classe Cliente</span>
<span style="color: #ff7700;font-weight:bold;">from</span> minhaapp.<span style="color: black;">models</span> <span style="color: #ff7700;font-weight:bold;">import</span> Cliente
&nbsp;
<span style="color: #808080; font-style: italic;"># Classe para trabalhar com o projeto em Django</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Relatorio<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> teste_exibir_clientes_cadastrados<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        clientes = Cliente.<span style="color: black;">objects</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> clientes
&nbsp;
<span style="color: #808080; font-style: italic;"># Instanciamos a classe Relatorio e executamos o método</span>
rel = Relatorio<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
rel.<span style="color: black;">teste_exibir_clientes_cadastrados</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Agora no terminal:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">$ sudo chmod +x /usr/bin/relatorio.py
$ relatorio.py</pre></div></div>

<p>Viram como é fácil trabalhar com o projeto em Django em outro ambiente?!<br />
Agora só falta renderizar um template e enviar o resultado por e-mail.</p>
<h2>Renderizando um template</h2>
<p>Temos o template <b>relatorio.html</b> localizado no diretório de templates do projeto:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html lang=&quot;pt-br&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
&lt;title&gt;Relatório de Clientes Cadastrados&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Clientes cadastrados&lt;/h2&gt;
{% for cliente in clientes %}
    Nome: {{ cliente.nome }}&lt;br&gt;
{% endfor %}
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>Vamos obter os clientes cadastrados, passar o resultado ao template e enviar um e-mail no formato HTML contendo o template renderizado.<br />
O script final deve ficar assim:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/python</span>
&nbsp;
<span style="color: #483d8b;">&quot;&quot;&quot;Dependendo da distro o caminho para o python acima pode ser outro&quot;&quot;&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">core</span>.<span style="color: black;">management</span> <span style="color: #ff7700;font-weight:bold;">import</span> setup_environ
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>, <span style="color: #dc143c;">datetime</span>, settings
PROJECT_PATH = <span style="color: #483d8b;">'/home/gustavo/www/django/meuprojeto'</span>
<span style="color: #dc143c;">sys</span>.<span style="color: black;">path</span>.<span style="color: black;">insert</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, PROJECT_PATH<span style="color: black;">&#41;</span>
setup_environ<span style="color: black;">&#40;</span>settings<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">email</span>.<span style="color: black;">MIMEMultipart</span> <span style="color: #ff7700;font-weight:bold;">import</span> MIMEMultipart
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">email</span>.<span style="color: black;">MIMEText</span> <span style="color: #ff7700;font-weight:bold;">import</span> MIMEText
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">email</span>.<span style="color: black;">MIMEImage</span> <span style="color: #ff7700;font-weight:bold;">import</span> MIMEImage
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">smtplib</span> <span style="color: #ff7700;font-weight:bold;">import</span> SMTP
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">email</span>.<span style="color: black;">Charset</span>
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">unicodedata</span> <span style="color: #ff7700;font-weight:bold;">import</span> normalize
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Relatorio<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot;
        Construtor da classe
        &quot;&quot;&quot;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">charset</span> = <span style="color: #483d8b;">'utf-8'</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">smtp_server</span> = <span style="color: #483d8b;">'smtp.provedor.com.br'</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">smtp_user</span> = <span style="color: #483d8b;">'usuario'</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">smtp_pass</span> = <span style="color: #483d8b;">'senha'</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">sender</span> = <span style="color: #483d8b;">'meu@email.com.br'</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">sender_name</span> = <span style="color: #483d8b;">'Meu Nome Completo'</span>
&nbsp;
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> render<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, context, template<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;&quot;
        Retorna o template renderizado
        &quot;&quot;&quot;</span>
&nbsp;
        <span style="color: #ff7700;font-weight:bold;">if</span> template:
            t = loader.<span style="color: black;">get_template</span><span style="color: black;">&#40;</span>template<span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">return</span> t.<span style="color: black;">render</span><span style="color: black;">&#40;</span>Context<span style="color: black;">&#40;</span>context<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> enviar_relatorio<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        clientes = Cliente.<span style="color: black;">objects</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;"># Se nao houver clientes cadastrados...</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> clientes.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">0</span>:
            <span style="color: #ff7700;font-weight:bold;">print</span> u<span style="color: #483d8b;">'Erro: Nenhum cliente cadastrado. O e-mail não foi enviado.'</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #808080; font-style: italic;"># Passa os clientes cadastrados para a variavel clientes no template</span>
            context = <span style="color: black;">&#123;</span><span style="color: #483d8b;">'clientes'</span>: clientes<span style="color: black;">&#125;</span>
&nbsp;
            <span style="color: #808080; font-style: italic;"># Obtem o template renderizado </span>
            html = <span style="color: #008000;">self</span>.<span style="color: black;">render</span><span style="color: black;">&#40;</span>context, <span style="color: #483d8b;">'relatorio.html'</span><span style="color: black;">&#41;</span>
&nbsp;
            <span style="color: #808080; font-style: italic;"># A funcao normalize remove caracteres acentuados</span>
            html = normalize<span style="color: black;">&#40;</span><span style="color: #483d8b;">'NFKD'</span>,html<span style="color: black;">&#41;</span>.<span style="color: black;">encode</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'ASCII'</span>,<span style="color: #483d8b;">'ignore'</span><span style="color: black;">&#41;</span>
&nbsp;
            <span style="color: #808080; font-style: italic;"># Mais detalhes sobre o módulo email, consulte a docuemtacao do python     </span>
            msg_principal = MIMEMultipart<span style="color: black;">&#40;</span><span style="color: #483d8b;">'related'</span><span style="color: black;">&#41;</span>
            msg_principal<span style="color: black;">&#91;</span><span style="color: #483d8b;">'Subject'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">'Relatorio de clientes'</span>
            msg_principal<span style="color: black;">&#91;</span><span style="color: #483d8b;">'From'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">'%s &lt;%s&gt;'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">sender</span>, <span style="color: #008000;">self</span>.<span style="color: black;">sender_name</span><span style="color: black;">&#41;</span>
            msg_principal<span style="color: black;">&#91;</span><span style="color: #483d8b;">'To'</span><span style="color: black;">&#93;</span> =  <span style="color: #483d8b;">'%s &lt;%s&gt;'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>recipient, recipient_name<span style="color: black;">&#41;</span>
            msg_principal.<span style="color: black;">preamble</span> = <span style="color: #483d8b;">'This is a multi-part message in MIME format.'</span>
&nbsp;
            msg_alternativa = MIMEMultipart<span style="color: black;">&#40;</span><span style="color: #483d8b;">'alternative'</span><span style="color: black;">&#41;</span>
            msg_alternativa.<span style="color: black;">attach</span><span style="color: black;">&#40;</span>MIMEText<span style="color: black;">&#40;</span>html, <span style="color: #483d8b;">'html'</span>, _charset=<span style="color: #008000;">self</span>.<span style="color: black;">charset</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            msg_principal.<span style="color: black;">attach</span><span style="color: black;">&#40;</span>msg_alternativa<span style="color: black;">&#41;</span>
            msg_alternativa.<span style="color: black;">attach</span><span style="color: black;">&#40;</span>MIMEText<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Essa e uma mensagem alternativa'</span>, _charset=<span style="color: #008000;">self</span>.<span style="color: black;">charset</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            msg_alternativa.<span style="color: black;">attach</span><span style="color: black;">&#40;</span>MIMEText<span style="color: black;">&#40;</span>html, <span style="color: #483d8b;">'html'</span>, _charset=<span style="color: #008000;">self</span>.<span style="color: black;">charset</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
            <span style="color: #808080; font-style: italic;"># Tenta enviar o email</span>
            <span style="color: #ff7700;font-weight:bold;">try</span>:
                smtp = SMTP<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
                smtp.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">smtp_server</span><span style="color: black;">&#41;</span>
                smtp.<span style="color: black;">login</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">smtp_user</span>, <span style="color: #008000;">self</span>.<span style="color: black;">smtp_pass</span><span style="color: black;">&#41;</span>
                smtp.<span style="color: black;">sendmail</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">sender</span>, recipient, msg_principal.<span style="color: black;">as_string</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
                smtp.<span style="color: black;">quit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">except</span>:
                <span style="color: #ff7700;font-weight:bold;">print</span> u<span style="color: #483d8b;">'Erro: Não foi possível enviar o e-mail.'</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;"># Instanciamos a classe Relatorio e executamos o método</span>
rel = Relatorio<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
rel.<span style="color: black;">enviar_relatorio</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<h2>Conclusão</h2>
<p>Acessar o ORM do Django por um script Python permite criar muitas coisas interessantes. Imagine criar um projeto no Django e usar suas classes e métodos em um projeto Python + QT por exemplo? E scripts produzindo logs em banco de dados em vez de jogar na tela ou no Syslog, tornando possível a visualização em ambiente web?<br />
A imaginação é o limite.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Compartilhe esse artigo</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://buzz.yahoo.com/submit?submitUrl=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;submitHeadline=Script+Python+acessando+classes+do+Django&amp;submitSummary=" rel="nofollow" title="Adicionar ao&nbsp;Buzz"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/buzz.png" title="Adicionar ao&nbsp;Buzz" alt="Adicionar ao&nbsp;Buzz" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;title=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;Del.icio.us"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/delicious.png" title="Adicionar ao&nbsp;Del.icio.us" alt="Adicionar ao&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;title=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;digg"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/digg.png" title="Adicionar ao&nbsp;digg" alt="Adicionar ao&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F" rel="nofollow" title="Adicionar ao&nbsp;Facebook"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/facebook.png" title="Adicionar ao&nbsp;Facebook" alt="Adicionar ao&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;title=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;Google Bookmarks"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/google.png" title="Adicionar ao&nbsp;Google Bookmarks" alt="Adicionar ao&nbsp;Google Bookmarks" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.mister-wong.com/index.php?action=addurl&amp;bm_url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;bm_description=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;Mister Wong"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/misterwong.png" title="Adicionar ao&nbsp;Mister Wong" alt="Adicionar ao&nbsp;Mister Wong" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.netscape.com/submit/?U=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;T=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;Netscape"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/netscape.png" title="Adicionar ao&nbsp;Netscape" alt="Adicionar ao&nbsp;Netscape" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;title=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;reddit"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/reddit.png" title="Adicionar ao&nbsp;reddit" alt="Adicionar ao&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;title=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;Stumble Upon"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Adicionar ao&nbsp;Stumble Upon" alt="Adicionar ao&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F" rel="nofollow" title="Adicionar ao&nbsp;Technorati"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/technorati.png" title="Adicionar ao&nbsp;Technorati" alt="Adicionar ao&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://tipd.com/submit.php?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F" rel="nofollow" title="Adicionar ao&nbsp;Tip'd"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/tipd.png" title="Adicionar ao&nbsp;Tip'd" alt="Adicionar ao&nbsp;Tip'd" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Script+Python+acessando+classes+do+Django+@+http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F" rel="nofollow" title="Adicionar ao&nbsp;Twitter"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/twitter.png" title="Adicionar ao&nbsp;Twitter" alt="Adicionar ao&nbsp;Twitter" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F12%2Fscript-python-acessando-classes-do-django%2F&amp;t=Script+Python+acessando+classes+do+Django" rel="nofollow" title="Adicionar ao&nbsp;Yahoo My Web"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/yahoo.png" title="Adicionar ao&nbsp;Yahoo My Web" alt="Adicionar ao&nbsp;Yahoo My Web" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.gustavohenrique.net/brogui/2009/12/script-python-acessando-classes-do-django/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Instalando a PIL na KingHost</title>
		<link>http://www.gustavohenrique.net/brogui/2009/01/instalando-a-pil-na-kinghost/</link>
		<comments>http://www.gustavohenrique.net/brogui/2009/01/instalando-a-pil-na-kinghost/#comments</comments>
		<pubDate>Thu, 15 Jan 2009 12:48:48 +0000</pubDate>
		<dc:creator>gustavohenrique</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[KingHost]]></category>
		<category><![CDATA[PIL]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gustavohenrique.net/brogui/?p=64</guid>
		<description><![CDATA[Recentemente terminei um projeto e, após todos os testes, chegou a hora do deploy &#8211; a implementação no servidor de produção. Então, logo de primeira o site não rodou. Analisando as mensagens de debug percebi que a classe ImageField que eu estava usando necessita da PIL (Python Image Library) e o servidor de hospedagem (KingHost) [...]]]></description>
			<content:encoded><![CDATA[<p>Recentemente terminei um projeto e, após todos os testes, chegou a hora do deploy &#8211; a implementação no servidor de produção. Então, logo de primeira o site não rodou. Analisando as mensagens de debug percebi que a classe ImageField que eu estava usando necessita da PIL (Python Image Library) e o servidor de hospedagem (KingHost) não a possui. Após várias buscas sem sucesso no google, entrei no canal de IRC #python-br o qual consegui uma grande ajuda do amigo &#8220;nosklo&#8221; e resolvi compartilhar a dica para instalar a PIL no diretório do projeto feito em Django e hospedado na <a href="http://www.kinghost.net" target="_blank">KingHost</a>.</p>
<p>Primeiro é necessário que você tenha instalado na sua máquina de desenvolvimento a PIL, rodando em ambiente Linux.<br />
O processo de instalação consiste em copiar o diretório PIL e o arquivo PIL.pth para dentro do diretório do projeto criado com o Django. Após copiar, remova todos os arquivos .pyc do diretório PIL, deixando apenas os arquivos .py e .so.</p>
<p>Ex.:<br />
<code><br />
[gu@notebook]$ ls<br />
minhapp    __init__.py   manage.py   PIL  PIL.pth   settings.py   templates   urls.py<br />
</code></p>
<p>No meu notebook com Ubuntu instalado, o diretório PIL e o arquivo PIL.pth encontram-se em <code>/usr/lib/python2.5/site-packages</code>. No servidor da KingHost a versão do Python é a 2.4 porém assim mesmo funcionou.<br />
Caso alguém não consiga, estou disponibilizando a versão que utilizo com sucesso aqui: <a href="http://www.gustavohenrique.net/files/pil.tar.gz">www.gustavohenrique.net/files/pil.tar.gz</a></p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Compartilhe esse artigo</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://buzz.yahoo.com/submit?submitUrl=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;submitHeadline=Instalando+a+PIL+na+KingHost&amp;submitSummary=" rel="nofollow" title="Adicionar ao&nbsp;Buzz"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/buzz.png" title="Adicionar ao&nbsp;Buzz" alt="Adicionar ao&nbsp;Buzz" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;title=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;Del.icio.us"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/delicious.png" title="Adicionar ao&nbsp;Del.icio.us" alt="Adicionar ao&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;title=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;digg"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/digg.png" title="Adicionar ao&nbsp;digg" alt="Adicionar ao&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F" rel="nofollow" title="Adicionar ao&nbsp;Facebook"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/facebook.png" title="Adicionar ao&nbsp;Facebook" alt="Adicionar ao&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;title=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;Google Bookmarks"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/google.png" title="Adicionar ao&nbsp;Google Bookmarks" alt="Adicionar ao&nbsp;Google Bookmarks" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.mister-wong.com/index.php?action=addurl&amp;bm_url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;bm_description=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;Mister Wong"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/misterwong.png" title="Adicionar ao&nbsp;Mister Wong" alt="Adicionar ao&nbsp;Mister Wong" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.netscape.com/submit/?U=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;T=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;Netscape"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/netscape.png" title="Adicionar ao&nbsp;Netscape" alt="Adicionar ao&nbsp;Netscape" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;title=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;reddit"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/reddit.png" title="Adicionar ao&nbsp;reddit" alt="Adicionar ao&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;title=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;Stumble Upon"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Adicionar ao&nbsp;Stumble Upon" alt="Adicionar ao&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F" rel="nofollow" title="Adicionar ao&nbsp;Technorati"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/technorati.png" title="Adicionar ao&nbsp;Technorati" alt="Adicionar ao&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://tipd.com/submit.php?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F" rel="nofollow" title="Adicionar ao&nbsp;Tip'd"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/tipd.png" title="Adicionar ao&nbsp;Tip'd" alt="Adicionar ao&nbsp;Tip'd" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Instalando+a+PIL+na+KingHost+@+http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F" rel="nofollow" title="Adicionar ao&nbsp;Twitter"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/twitter.png" title="Adicionar ao&nbsp;Twitter" alt="Adicionar ao&nbsp;Twitter" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2009%2F01%2Finstalando-a-pil-na-kinghost%2F&amp;t=Instalando+a+PIL+na+KingHost" rel="nofollow" title="Adicionar ao&nbsp;Yahoo My Web"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/yahoo.png" title="Adicionar ao&nbsp;Yahoo My Web" alt="Adicionar ao&nbsp;Yahoo My Web" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.gustavohenrique.net/brogui/2009/01/instalando-a-pil-na-kinghost/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Django com MySQL, JQuery, Ajax e JSON &#8211; Parte 1</title>
		<link>http://www.gustavohenrique.net/brogui/2008/11/django-com-mysql-jquery-ajax-e-json-parte-1/</link>
		<comments>http://www.gustavohenrique.net/brogui/2008/11/django-com-mysql-jquery-ajax-e-json-parte-1/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 15:23:28 +0000</pubDate>
		<dc:creator>gustavohenrique</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gustavohenrique.net/site/?p=3</guid>
		<description><![CDATA[Introdução
Django é um framework MVC para desenvolvimento web escrito em python. Proporciona velocidade no desenvolvimento, código limpo e organizado e uma poderosa ferramenta de administração.
Essa é a primeira parte de uma série de artigos sobre como criar um sistema de gestão de provedor de internet utilizando Django, MySQL, Javascript (JQuery), Ajax com JSON, CSS e [...]]]></description>
			<content:encoded><![CDATA[<h2>Introdução</h2>
<p>Django é um framework MVC para desenvolvimento web escrito em python. Proporciona velocidade no desenvolvimento, código limpo e organizado e uma poderosa ferramenta de administração.<br />
Essa é a primeira parte de uma série de artigos sobre como criar um sistema de gestão de provedor de internet utilizando Django, MySQL, Javascript (JQuery), Ajax com JSON, CSS e Linux.  No momento abordaremos apenas a parte de cadastro de clientes.<br />
Para melhor entendimento, é desejável conhecimento básico em desenvolvimento web, Python e Linux.<br />
Instalação, características, manual e outras informações podem ser encontradas no site Django Brasil.<br />
<span id="more-7"></span></p>
<h2>Sobre o Sistema </h2>
<p>Como forma de estudo, resolvi portar as funcionalidades básicas de um sistema antigo que desenvolvi em PHP para Django. Trata-se de um sistema de gestão de provedor de internet, que possibilita o cadastro de clientes, controle de banda, regras de firewall, fluxo de caixa e relatórios gerenciais, interagindo com ferramentas em ambiente Linux. Chamaremos nosso sistema de Sigep &#8211; Sistema de Gestão de Provedor. Nome nada criativo, eu sei, mas vamos deixar assim mesmo.</p>
<h2>Iniciando </h2>
<p>O sistema completo será desenvolvido em Linux, utilizando softwares específicos para o mesmo. É possível desenvolver em Windows e MacOS X, porém o ambiente de produção necessariamente deve ser Linux. Abaixo a descrição do ambiente de desenvolvimento utilizado:</p>
<p>Sistema Operacional: Ubuntu 8.04<br />
IDE/Editor: Komodo Edit para códigos do Django e Geany 0.13 para HTML e CSS<br />
Banco de Dados: MySQL 5.0<br />
Linguagem: Python: 2.5 e Django 1.0</p>
<h3>Instalação</h3>
<p>Não será abordado o processo de instalação nesse artigo. No site www.djangobrasil.com tem um ótimo tutorial de instalação em Windows e Linux.</p>
<h3>Projeto Vs. Aplicação </h3>
<p>Em Django, projeto é o sistema no todo e aplicação é um módulo desse sistema. No nosso projeto Sigep, teremos várias aplicações (módulos), que são: cliente, rede, relatório, etc. Você pode criar uma única aplicação contendo toda funcionalidade do sistema, porém isso deixaria o código mais extenso e de difícil manutenção.</p>
<h3>Criando o Projeto </h3>
<p>Abra um terminal, entre no diretorio onde deseja trabalhar e crie o projeto com o script django-admin.py.<br />
<code><br />
gu@notebook:~$ mkdir projetos<br />
gu@notebook:~$ cd projetos<br />
gu@notebook:~$ django-admin.py startproject sigep<br />
gu@notebook:~$ cd sigep<br />
gu@notebook:~$ ls sigep<br />
__init__.py  manage.py  settings.py  urls.py<br />
</code></p>
<p>O django-admin.py criou um diretório com o nome do projeto contendo os seguintes arquivos:</p>
<p><code>__init__.py</code>: Arquivo vazio. Serve apenas para identificar que é um pacote python<br />
<code>manage.py</code>: Script para gerenciar o projeto no django<br />
<code>settings.py</code>: Arquivo de configuração do projeto<br />
<code>urls.py</code>: Onde é definido o mapeamento das URLs</p>
<h3>Configurando o Projeto</h3>
<p>Vamos editar o arquivo settings.py e incluir as linhas abaixo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
LOCAL = <span style="color: #ff7700;font-weight:bold;">lambda</span> <span style="color: #66cc66;">*</span>args:<span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span>__file__<span style="color: black;">&#41;</span>, <span style="color: #66cc66;">*</span>args<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>
As linhas acimas criam uma função para retornar o caminho absoluto do diretório do nosso projeto. Agora vamos alterar as seguintes variáveis:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="python" style="font-family:monospace;">DATABASE_ENGINE = <span style="color: #483d8b;">'mysql'</span>
DATABASE_NAME = <span style="color: #483d8b;">'sigepdjango'</span>
DATABASE_USER = <span style="color: #483d8b;">'usuario_do_mysql_aki'</span>
DATABASE_PASSWORD = <span style="color: #483d8b;">'senha_do_usuario_do_mysql_aki'</span>
&nbsp;
TIME_ZONE = <span style="color: #483d8b;">'America/Sao_Paulo'</span>
&nbsp;
LANGUAGE_CODE = <span style="color: #483d8b;">'pt-br'</span>
&nbsp;
MEDIA_ROOT = LOCAL<span style="color: black;">&#40;</span><span style="color: #483d8b;">'files'</span><span style="color: black;">&#41;</span>
&nbsp;
TEMPLATE_DIRS = <span style="color: black;">&#40;</span>
    LOCAL<span style="color: black;">&#40;</span><span style="color: #483d8b;">'templates'</span><span style="color: black;">&#41;</span>
<span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>
O que fizemos acima foi configurar o projeto para acessar nosso banco de dados no MySQL, ajustar o timezone e idioma de acordo com o Brasil, setar o MEDIA_ROOT, que é o diretório onde nossos arquivos externos serão armazenados e definir o diretório templates onde nossos arquivos HTML ficarão.<br />
Agora vamos criar nossa aplicação.</p>
<!-- Social Bookmarks BEGIN -->
<div class="social_bookmark">
<a><strong><em>Compartilhe esse artigo</em></strong></a>
<br />
<div class="d">
<br />
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://buzz.yahoo.com/submit?submitUrl=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;submitHeadline=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1&amp;submitSummary=" rel="nofollow" title="Adicionar ao&nbsp;Buzz"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/buzz.png" title="Adicionar ao&nbsp;Buzz" alt="Adicionar ao&nbsp;Buzz" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://del.icio.us/post?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;title=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;Del.icio.us"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/delicious.png" title="Adicionar ao&nbsp;Del.icio.us" alt="Adicionar ao&nbsp;Del.icio.us" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;title=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;digg"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/digg.png" title="Adicionar ao&nbsp;digg" alt="Adicionar ao&nbsp;digg" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F" rel="nofollow" title="Adicionar ao&nbsp;Facebook"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/facebook.png" title="Adicionar ao&nbsp;Facebook" alt="Adicionar ao&nbsp;Facebook" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;title=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;Google Bookmarks"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/google.png" title="Adicionar ao&nbsp;Google Bookmarks" alt="Adicionar ao&nbsp;Google Bookmarks" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.mister-wong.com/index.php?action=addurl&amp;bm_url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;bm_description=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;Mister Wong"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/misterwong.png" title="Adicionar ao&nbsp;Mister Wong" alt="Adicionar ao&nbsp;Mister Wong" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.netscape.com/submit/?U=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;T=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;Netscape"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/netscape.png" title="Adicionar ao&nbsp;Netscape" alt="Adicionar ao&nbsp;Netscape" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://reddit.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;title=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;reddit"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/reddit.png" title="Adicionar ao&nbsp;reddit" alt="Adicionar ao&nbsp;reddit" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;title=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;Stumble Upon"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/stumbleupon.png" title="Adicionar ao&nbsp;Stumble Upon" alt="Adicionar ao&nbsp;Stumble Upon" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F" rel="nofollow" title="Adicionar ao&nbsp;Technorati"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/technorati.png" title="Adicionar ao&nbsp;Technorati" alt="Adicionar ao&nbsp;Technorati" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://tipd.com/submit.php?url=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F" rel="nofollow" title="Adicionar ao&nbsp;Tip'd"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/tipd.png" title="Adicionar ao&nbsp;Tip'd" alt="Adicionar ao&nbsp;Tip'd" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://twitter.com/home/?status=Check+out+Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1+@+http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F" rel="nofollow" title="Adicionar ao&nbsp;Twitter"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/twitter.png" title="Adicionar ao&nbsp;Twitter" alt="Adicionar ao&nbsp;Twitter" /></a>
<a onclick="window.open(this.href, '_blank', 'scrollbars=yes,menubar=no,height=600,width=750,resizable=yes,toolbar=no,location=no,status=no'); return false;" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u=http%3A%2F%2Fwww.gustavohenrique.net%2Fbrogui%2F2008%2F11%2Fdjango-com-mysql-jquery-ajax-e-json-parte-1%2F&amp;t=Django+com+MySQL%2C+JQuery%2C+Ajax+e+JSON+%26%238211%3B+Parte+1" rel="nofollow" title="Adicionar ao&nbsp;Yahoo My Web"><img class="social_img" src="http://www.gustavohenrique.net/brogui/wp-content/plugins/social-bookmarks/images/yahoo.png" title="Adicionar ao&nbsp;Yahoo My Web" alt="Adicionar ao&nbsp;Yahoo My Web" /></a>
<br />
</div>
</div>
<!-- Social Bookmarks END -->
]]></content:encoded>
			<wfw:commentRss>http://www.gustavohenrique.net/brogui/2008/11/django-com-mysql-jquery-ajax-e-json-parte-1/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
