[Tarsis Azevedo] Django Trick: Hospedagem grátis no Alwaysdata

January 26th, 2012

Quem programa em django, sente falta de um Heroku[1], como no rails para fazer deploy e colocar a aplicaçao online mais rapido e de graça.

Obervação: Existe um serviço que tem essa proposta, ser um Heroku pra Django, é o Djangy (https://www.djangy.com/), Porem ele esta em teste! Voce pode entrar e pedir um convite. Eu ja pedi mas nao foi aceito ainda! =/

 

Uma Solução…

… pra esse problema é o alwaysdata.com . Eles tem varios planos de hospedagem, e um deles é totalmente free!!! xD

Assim, voce pode desenvolver sua aplicação e ja colocar no ar! 

Facil assim?

Sim, fácil assim!! A interface deles é muito simples. Você configura seu servidor com a versão do python/django que usa com 1 clique.

Depois é só enviar a aplicação via ssh para o server, seguir os passos deles pra deploy[2] e pronto, sua aplicação django estará no ar!!!

Que massa! Isso é perfeito!

Não!

Ele tem alguns pequenos problemas:

  1. Algumas partes importantes do site estao em frances
    • pagina da wiki que ensina o deploy e o acesso via ssh
  2. Não tem um script ou deploy automatizado como o Heroku
    • Isso pode ser feito com um shell script simples(No proximo artigo deste blog)
    • Pra agilizar, voce pode habilitar o acesso ao ssh sem senha[3]
  3. O plano é fraco
    1. Mas, se seu objetivo é só “testar” em produção ele te atende!
    2. É uma forma de aprender fazendo 
    3. E é de graça!!!

Até a proxima pessoal,

Abraços.

[1]http://heroku.com/

[2]http://wiki.alwaysdata.com/wiki/D%C3%A9ployer_une_application_Django

[3]http://tarsisazevedo.posterous.com/truque-ssh-sem-senha

 

 


[Tarsis Azevedo] Truque Ssh: Sem Senha

January 26th, 2012

Voce tem que acessar um servidor muitas vezes ao dia, e esta cansado de digitar senha toda hora? Voce nao aguenta mais gravar mil senhas? Tem que digitar todas as mil senhas para tentar acessar sua maquina remota?

Seus problemas acabaram!!!

Voce só vai precisar de:

  • Um terminal linux
  • Senha da maquina que vc acessa (E só mais uma vez, eu garanto)
  • Alguns comandos linux.
    • Atenção: se voce nao é muito experiente em linux, peça ajuda de um adulto xD,

Tudo pronto? Entao…

Abra o terminal e digite:

ssh-keygen -t rsa

Bom agora voce vai ver as seguintes mensagens:

Enter file in which to save the key (/home/user1/.ssh/id_rsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

 

APENAS TECLE ENTER PARA TODAS!!!!


Agora faça o seguinte:

scp ~/.ssh/id_rsa.pub root@sua_maquina_remota:~

Se isso deu certo, agora acesse sua maquina:

ssh root@sua_maquina_remota

Estando na maquina faça o seguinte:

cat id_rsa.pub » .ssh/authorized_keys

Se o diretorio .ssh nao existir, crie-o assim: mkdir .ssh

Feito isso, apenas saia da maquina remota e tente acessar novamente.

Agora voce nao precisa mais de senhas!!!

Porem

Existe uma lei do universo que diz o seguinte: se algo pode dar errado, vai dar errado, entao…

Se depois de seguir todos esses passos, voce encontrar com esse erro:

 

“agent admitted failure to sign using the key”

Basta fazer o seguinte na maquina local, nao na maquina remota:

 

sudo apt-get install ssh-add

Por fim..

deixe seu feedback(problemas, sugestoes, etc) nos comentarios.

Obrigado, e até a proxima pessoal!

Referencias:

http://polishlinux.org/apps/ssh-tricks/

http://www.pedropereira.net/ssh-sem-senha-autenticacao-atraves-de-certificados-rsa/

http://www.baptiste-wicht.com/2010/07/tip-how-to-solve-agent-admitted-failure-to-sign-using-the-key-error/


[Igor Sobreira] Book review: Being Geek

December 29th, 2011

Published on: 28/12/2011 23:50h

I’ve finished reading this book, Being Geek, by Michael Lopp, an experienced engineering manager from Silicon Valley. And recommend it…

It’s a book about geeks professionalism, career. I liked the way the author exposes his ideas, he’s clear and pragmatic. Right in the second chapter there are these three questions I think it’s worth pointing out:

  1. Are you actively defining the technical direction for your product?
  2. Do you understand what you need to do in order to grow?
  3. Are you hitting your dates? Are you meeting your commitments? Are you doing what you say you’re going to do?

That’s it! That’s what you need to ask yourself every day. Those answers will make you realize if this job is being useful for you to archive your professional goal in your life.

Later in the book he talks about task management, to-do lists and so on. And a very interesting one he calls “The Trickle List”. This is not a simple to-do list for that day. It’s a list of tasks you do every day with a bigger goal in mind, in the future. If you want to be a better engineer, every day you may want to learn something, improve on something, read something. I suddenly realized I was missing this list…

Well, I liked the book. I was not very excited reading the first chapters. But as I continued reading it just got better and better. The author writes comfortably about our career, being an engineer or a manager. The book is full of good advices based on experience. Hiring process, remote working, giving presentations, etc.

By Igor Sobreira

[Igor Sobreira] Command line interface to FMS Admin

December 26th, 2011

Published on: 25/12/2011 13:29h

I’ve been working with Flash Media Server for the last 8 months now, and
one tool that really annoys me is the Administration Console. I miss a
command line interface to accomplish tasks like see all live streams, reload
an app, etc.

That’s why I’ve started the fms-admin-api. It’s a command line
client to Flash Media Server Administration API.
Since it’s written in ruby, it’s possible to use the ruby client class directly.
Use rubygems to install:


$ gem install fms-admin-api

The way it works is really simple. Here is an example: there is a reloadApp() method available
that accepts the arguments host, auser,
apswd and appInst. The command line interface just replaces
from camelCase syntax to underscore:


$ fmsapi reload_app –host=fms.example.com –auser=fms –apswd=secret –app_inst=live

There are improvements to be made
and help is welcome.

By Igor Sobreira

[Tiago Peczenyj] FFmpeg new version

December 22nd, 2011

Changelog for 0.9 version.

Entries are sorted chronologically from oldest to youngest within each release, releases are sorted from youngest to oldest.

version 0.9:

- openal input device added
- boxblur filter added
- BWF muxer
- Flash Screen Video 2 decoder
- lavfi input device added
- added avconv, which is almost the same for now, except
for a few incompatible changes in the options, which will hopefully make them
easier to use. The changes are:
* The options placement is now strictly enforced! While in theory the
options for ffmpeg should be given in [input options] -i INPUT [output
options] OUTPUT order, in practice it was possible to give output options
before the -i and it mostly worked. Except when it didn’t – the
behavior was
a bit inconsistent. In avconv, it is not possible to mix input and output
options. All non-global options are reset after an input or
output filename.
* All per-file options are now truly per-file – they apply only to the next
input or output file and specifying different values for different files
will now work properly (notably -ss and -t options).
* All per-stream options are now truly per-stream – it is possible to
specify which stream(s) should a given option apply to. See the Stream
specifiers section in the avconv manual for details.
* In ffmpeg some options (like -newvideo/-newaudio/…) are irregular in the
sense that they’re specified after the output filename instead of before,
like all other options. In avconv this irregularity is removed,
all options
apply to the next input or output file.
* -newvideo/-newaudio/-newsubtitle options were removed. Not only were they
irregular and highly confusing, they were also redundant. In
avconv the -map
option will create new streams in the output file and map input streams to
them. E.g. avconv -i INPUT -map 0 OUTPUT will create an output stream for
each stream in the first input file.
* The -map option now has slightly different and more powerful syntax:
+ Colons (‘:’) are used to separate file index/stream type/stream index
instead of dots. Comma (‘,’) is used to separate the sync
stream instead
of colon.. This is done for consistency with other options.
+ It’s possible to specify stream type. E.g. -map 0:a:2 creates an
output stream from the third input audio stream.
+ Omitting the stream index now maps all the streams of the given type,
not just the first. E.g. -map 0:s creates output streams for all the
subtitle streams in the first input file.
+ Since -map can now match multiple streams, negative mappings were
introduced. Negative mappings disable some streams from an already
defined map. E.g. ‘-map 0 -map -0:a:1′ means ‘create output
streams for
all the stream in the first input file, except for the second audio
stream’.
* There is a new option -c (or -codec) for choosing the decoder/encoder to
use, which allows to precisely specify target stream(s) consistently with
other options. E.g. -c:v lib264 sets the codec for all video
streams, -c:a:0
libvorbis sets the codec for the first audio stream and -c copy copies all
the streams without reencoding. Old -vcodec/-acodec/-scodec
options are now
aliases to -c:v/a/s
* It is now possible to precisely specify which stream should an AVOption
apply to. E.g. -b:v:0 2M sets the bitrate for the first video
stream, while
-b:a 128k sets the bitrate for all audio streams. Note that the
old -ab 128k
syntax is deprecated and will stop working soon.
* -map_chapters now takes only an input file index and applies to the next
output file. This is consistent with how all the other options work.
* -map_metadata now takes only an input metadata specifier and applies to
the next output file. Output metadata specifier is now part of the option
name, similarly to the AVOptions/map/codec feature above.
* -metadata can now be used to set metadata on streams and chapters, e.g.
-metadata:s:1 language=eng sets the language of the first stream to ‘eng’.
This made -vlang/-alang/-slang options redundant, so they were removed.
* -qscale option now uses stream specifiers and applies to all streams, not
just video. I.e. plain -qscale number would now apply to all
streams. To get
the old behavior, use -qscale:v. Also there is now a shortcut -q
for -qscale
and -aq is now an alias for -q:a.
* -vbsf/-absf/-sbsf options were removed and replaced by a -bsf option which
uses stream specifiers. Use -bsf:v/a/s instead of the old options.
* -itsscale option now uses stream specifiers, so its argument is only the
scale parameter.
* -intra option was removed, use -g 0 for the same effect.
* -psnr option was removed, use -flags +psnr for the same effect.
* -vf option is now an alias to the new -filter option, which uses
stream specifiers.
* -vframes/-aframes/-dframes options are now aliases to the new
-frames option.
* -vtag/-atag/-stag options are now aliases to the new -tag option.
- XMV demuxer
- LOAS demuxer
- ashowinfo filter added
- Windows Media Image decoder
- amovie source added
- LATM muxer/demuxer
- Speex encoder via libspeex
- JSON output in ffprobe
- WTV muxer
- Optional C++ Support (needed for libstagefright)
- H.264 Decoding on Android via Stagefright
- Prores decoder
- BIN/XBIN/ADF/IDF text file decoder
- aconvert audio filter added
- audio support to lavfi input device added
- libcdio-paranoia input device for audio CD grabbing
- Apple ProRes decoder
- CELT in Ogg demuxing
- G.723.1 demuxer and decoder
- libmodplug support (–enable-libmodplug)
- VC-1 interlaced decoding
- libutvideo wrapper (–enable-libutvideo)
- aevalsrc audio source added
- Ut Video decoder
- Speex encoding via libspeex
- 4:2:2 H.264 decoding support
- 4:2:2 and 4:4:4 H.264 encoding with libx264
- Pulseaudio input device
- Prores encoder
- Video Decoder Acceleration (VDA) HWAccel module.
- replacement Indeo 3 decoder
- new ffmpeg option: -map_channel
- volume audio filter added
- earwax audio filter added
- libv4l2 support (–enable-libv4l2)
- TLS/SSL and HTTPS protocol support
- AVOptions API rewritten and documented
- most of CODEC_FLAG2_*, some CODEC_FLAG_* and many codec-specific fields in
AVCodecContext deprecated. Codec private options should be used instead.
- Properly working defaults in libx264 wrapper, support for native presets.
- Encrypted OMA files support
- Discworld II BMV decoding support
- VBLE Decoder
- OS X Video Decoder Acceleration (VDA) support
- compact and csv output in ffprobe
- pan audio filter
- IFF Amiga Continuous Bitmap (ACBM) decoder
- ass filter #meldels
- CRI ADX audio format demuxer
- Playstation Portable PMP format demuxer
- Microsoft Windows ICO demuxer
- life source
- PCM format support in OMA demuxer
- CLJR encoder
- new option: -report
- Dxtory capture format decoder
- cellauto source

[Guilherme Garnier] Rails e mass assignment: como aumentar a segurança dos atributos

November 22nd, 2011

Ao utilizar o scaffold do Rails, ele criará todos os métodos necessários no controller. Depois que o usuário preenche os dados do formulário e envia, é executado o método create do controller. Este método faz algo semelhante ao código abaixo (no exemplo é um CRUD de usuário):

@usuario = Usuario.new(params[:usuario])

Na forma em que o Rails cria o formulário, os atributos do usuário são passados ao controller como um hash. O valor do params acima é algo parecido com isso:

{"authenticity_token"=>"xI1Cy+LvUZzg6FR/1Y/JHcaHVPRyWsHmRII8BhMOr0E=",
 "utf8"=>"?",
 "action"=>"create",
 "controller"=>"usuarios",
 "usuario"=>{"nome"=>"Novo usuario", "email"=>"novo@usuario.com"}}

Além da definição do token de segurança, codificação em utf-8, nome do controller e da action que será executada, o parâmetro usuario contém todos os atributos que foram preenchidos no formulário. Desta forma, é muito simples atribuir os parâmetros preenchidos a um objeto Usuario, seja criando um novo (@usuario = Usuario.new(params[:usuario])) ou editando (@usuario.update_params(params[:usuario])). O Rails chama isso de mass assignment.

O problema desta abordagem é que o usuário poderia facilmente inserir novos parâmetros neste hash, simplesmente adicionando tags input hidden no formulário (usando o Firebug, por exemplo):

<input type="hidden" name="usuario[admin]" id="usuario_admin" value="true" />

Adicionando o código acima, o novo usuário criado receberia o valor true no atributo admin, o que representa uma falha grave na segurança da aplicação.

O Rails oferece um mecanismo para garantir a segurança nestes casos, usando os métodos attr_protected e attr_accessible do ActiveModel. O primeiro permite definir atributos que não podem ser alterados através de mass assignment:

class Usuario
  attr_protected :admin
end

E o attr_accessible é uma forma mais segura: somente os atributos passados para este método poderão ser alterados com mass assignment. Os demais ficam protegidos:

class Usuario
  attr_accessible :nome, :email
end

Obviamente estes dois métodos não podem ser usados simultaneamente, pois um exclui o outro.

Se você quiser atualizar um objeto com mass assignment ignorando a segurança fornecida pelo attr_accessible e pelo attr_protected, basta utilizar o parâmetro without_protection (somente no Rails 3.1):

Usuario.create(
  {:nome => "Novo usuario", :email =>"novo@usuario.com", :admin => true},
  :without_protection => true)

No exemplo acima, o usuário criado terá o atributo admin igual a true, mesmo que tenha sido usado o método attr_protected ou o attr_accessible para evitar a alteração deste atributo.

Outra opção interessante para evitar a alteração de atributos indesejados é o método attr_readonly. Os atributos passados para este método só poderão ser definidos na criação do objeto, e não poderão ser alterados depois. Porém, este método faz parte do ActiveRecord::Base, e não do ActiveModel, ou seja, ele não estará disponível se você usar outro ORM. Há uma issue aberta no Github solicitando que este método seja movido para o ActiveModel.

Link relacionado:

Posts relacionados:


[Kenji Yamamoto] Mac App para Gmail

November 17th, 2011

  Atualmente eu comecei a usar uma App chamada Mailplane, para gerenciar o gmail, muito fácil de usar, tem integração com teclas de atalho do MacOS, estava me atendendo muito bem, mas como ela se tornou paga e eu não tô afim de gastar uma grana com esse tipo serviço, eu acabei abandonando a app. [...]

Kenji Yamamoto is a RSS from: Kenji Yamamoto

[Kenji Yamamoto] Alinhamento vertical apenas CSS

November 17th, 2011

Todo desenvolvedor Front-end já se deparou com aquele PSD em que voce tem um elemento centralizado verticalmente e com conteudo fluído. Formas de resolver esse problema, temos várias, faz um javascript que resolve, usa o display: table-cell, usa a boa e velha tabela, mas nenhuma solução verdadeiramente utilizando html e css apenas. Com essa necessidade [...]

Kenji Yamamoto is a RSS from: Kenji Yamamoto

[Kenji Yamamoto] Dicas sobre HTML5 e CSS3

November 17th, 2011

Ultimamente conversando com alguns amigos vejo a insatisfação que eles tem de querer ter um efeito, ou uma forma dentro do seu site, mas são impedidos pelas limitações da tecnologia. Com isso vem a grande pergunta, vamos dar suporte a quais browser? Partindo desse ponto, podemos saber em que passo caminhar para a implementação de [...]

Kenji Yamamoto is a RSS from: Kenji Yamamoto

[Kenji Yamamoto] GrooveShark Widget for Mac

November 17th, 2011

GrooveShark Widget for Mac

Kenji Yamamoto is a RSS from: Kenji Yamamoto