sexta-feira, 10 de fevereiro de 2012

Instalação do Vagrant no windows


Precisa de um ambiente que simule o servidor onde fará o deploy do projeto? Cansado de lidar com as diferenças entre sistemas operacionais, versões etc?

Esta semana tive a oportunidade de conhecer o Vagrant. Um sistema que trabalha com a API do Virtual Box. Nele é possível de uma maneira fácil criar uma máquina virtual com as características que precisar para simular o ambiente online.

O tutorial abaixo mostra um resumo do que li a respeito para  criar uma VM com Ubuntu, python2.6, virtualenv, etc.

  1. Baixe e instale a Oracle VM Virtual Box (https://www.virtualbox.org/wiki/Downloads
  2. Baixe e instale o Ruby (http://rubyinstaller.org/downloads/
  3. Baixe o Development Kit (http://rubyinstaller.org/downloads/
    1. Installation Instructions (https://github.com/oneclick/rubyinstaller/wiki/Development-Kit
      1. While installation is (in general) simple, please ensure you carefully follow each step below. 
      2. Preparation 
      3. If you previously installed the legacy DevKit devkit-3.4.5r3-20091110.7z, its artifacts were extracted into each Ruby installation and need to be manually removed. Remove the gcc.bat, make.bat, and sh.bat stub batch files in <RUBY_INSTALL_DIR>\bin and the <RUBY_INSTALL_DIR>\devkit subdirectory for each Ruby installation using the legacy DevKit. 
      4. If you previously installed one of the legacy self-extracting DevKit’s, follow the SFX DevKit upgrade instructions. 
    2. Download Files 
      1. The current DevKit is available at the RubyInstaller download page with older versions available at the archives page. As backup, check our GitHub downloads page. 
    3. Extract Files 
      1. Left double-click the self-extracting executable (SFX) downloaded from Step 2 and choose a directory (without spaces) to install the DevKit artifacts into. For example, C:\DevKit. NOTE: the SFX is really a 7-Zip archive with a bit of embedded magic. If you already have 7-Zip installed, you can simply right-click it and extract it’s contents as you would a normal 7z archive. In the instructions that follow, the directory that you selected is identified as <DEVKIT_INSTALL_DIR>. 
    4. Run Installation Scripts 
      1. cd <DEVKIT_INSTALL_DIR> from Step 3 above. 
      2. ruby dk.rb init to generate the config.yml file to be used later in this Step. Your installed Rubies will be listed there (only those installed by a RubyInstaller package are detected at present). 
      3. edit the generated config.yml file to include installed Rubies not automagically discovered or remove Rubies you do not want to use the DevKit with. 
      4. [optional] ruby dk.rb review to review the list of Rubies to be enhanced to use the DevKit and verify the changes you made to it are correct. 
      5. finally, ruby dk.rb install to DevKit enhance your installed Rubies. This step installs (or updates) an operating_system.rb file into the relevant directory needed to implement a RubyGems pre_install hook and a devkit.rb helper library file into <RUBY_INSTALL_DIR>\lib\ruby\site_ruby. NOTE: you may need to use the --force option to update (with backup of the originals) the above mentioned files as discussed at the SFX DevKit upgrade FAQ entry. 
    5. Test Installation 
  4. Confirm your Ruby environment is correctly using the DevKit by running gem install rdiscount --platform=ruby. RDiscount should install correctly and you should see Temporarily enhancing PATH to include DevKit... in the screen messages. Next run ruby -rubygems -e "require 'rdiscount'; puts RDiscount.new('**Hello RubyInstaller**').to_html" to confirm that the rdiscount gem is working. 
  5. Adicione o caminho da pasta bin do ruby da instalção feita no Path. Ex. C:\Ruby193\bin 
  6. Execute o comando: gem install vagrant 
  7. Antes de criar sua maquina, crie uma pasta para abrigar os arquivos de configuraçao: 
    1. mkdir vagrant-machine 
    2. cd vagrant-machine 
    3. vagrant box add lucid32 http://files.vagrantup.com/lucid32.box
    4. vagrant init lucid32 
    5. vagrant up 
    6. Acesse via ssh a maquina virtual: 
    7. pelo putty, conecte em vagrant@127.0.0.1 na porta 2222, com a senha vagrant 
  8. Instale os pacotes de desenvolvimento: 
    1. sudo apt-get install python2.6 python2.6-dev libxml2-dev libxslt1-dev python-libxml2 python-setuptools git-core build-essential libxml2-dev libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev libgeoip-dev memcached libmemcached-dev python-mysqldb libmysqlclient16-dev python-virtualenv 
    2. Se por ventura der algo errado, tente o mesmo comando acima mas adicione no fim o --fix-missing
  9. É necessário a instalação de alguns pacotes para tudo funcionar perfeitamente, além dos acima. Execute os comandos abaixo, caso não instalar como comando acima:
    1. sudo apt-get update
    2. sudo apt-get install mysql-client
    3. sudo apt-get install libmysqlclient16-dev
    4. sudo apt-get install python-virtualenv
    5. sudo apt-get build-dep python-imaging
  10. Vá até a home do usuário e rode o comando abaixo para atualizar o apt-get e outros pacotes: 
    1. sudo sh postinstall.sh
    2. Vá no VagrantFile no diretorio que instalou o passo 6.a e edite. 
    3. Descomente a linha: # config.vm.forward_port 80, 8080 e configure para as portas que deseja utilizar no windows quando rodar os projetos. Ex: 
      1. config.vm.forward_port 8000, 8000 
      2. # config.vm.forward_port 9000, 9000
  11. Reinicie o Vagrant com o comando: vagrant reload no seu prompt do windows

O tutorial acima funciona e estou utilizando-o a muito tempo. Depois de um tempo, apareceu a seguinte mensagem:
New release 'precise' available.
Run 'do-release-upgrade' to upgrade to it.

Tentei atualizar e tive problemas. Perdeu-se o compartilhamento da pasta com o Windows, bem como problemas para instalação dos pacotes PIL e MySQL-python.

Resolvi com a reinstalação do começo, sem fazer esta atualização.

hasta!

terça-feira, 7 de fevereiro de 2012

Filtrar apenas os usuários staff no admin

Quando utilizamos a autenticação provida pelo django, um problema é que sempre que entramos no change list do Auth User, lá tem todos os usuários que podem fazer login, tanto no front quanto no admin.

Para isso basta colocar o código abaixo em qualquer arquivo admin.py:


from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class StaffAdmin(UserAdmin):
"""
Esta classe recria as propriedades do admin do model auth.User
"""
list_filter = ( 'is_active', 'is_superuser' )
date_hierarchy = 'date_joined'
save_on_top = True

def queryset(self, request):
qs = super( UserAdmin, self ).queryset( request )
qs = qs.exclude( is_staff=False )
return qs


admin.site.unregister( User )
admin.site.register( User, StaffAdmin )


Se ainda preferir deixar separado, pode criar um arquivo admin.py na raiz do projeto e incluir o nome da pasta ( fornecido no startproject ) no INSTALLED_APPS.

hasta!