Skip to content

Commit 4b45acd

Browse files
committed
posts postgresql
1 parent efbc099 commit 4b45acd

File tree

5 files changed

+1008
-0
lines changed

5 files changed

+1008
-0
lines changed

content/images/regisdasilva/erd.png

5.9 KB
Loading
4.66 KB
Loading

content/postgresql-django.rst

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
PostgreSql + Django
2+
===================
3+
4+
:date: 2015-02-05 18:00
5+
:tags: python, postresql, banco de dados
6+
:category: Python, Banco de dados
7+
:slug: postgresql-django
8+
:author: Regis da Silva
9+
10+
:github: rg3915
11+
:summary: Esta é a parte 3 (de 3) da série de posts sobre PostgreSql...
12+
13+
Se você já leu o *Tutorial Postgresql* e *Postgresql + Python3*, este post é uma continuação. Aqui nós veremos usar PostgreSql no `Django <http://pythonclub.com.br/tutorial-django-17.html>`_.
14+
15+
Para quem já leu `Two Scoops of Django <http://twoscoopspress.com/products/two-scoops-of-django-1-6>`_ sabe que o `PyDanny <http://www.pydanny.com/>`_ recomenda fortemente o uso do `PostgreSQL <http://www.postgresql.org/>`_ em seus projetos.
16+
17+
Então vejamos aqui como configurar o Postgresql para ser usado no `Django <http://pythonclub.com.br/tutorial-django-17.html>`_.
18+
19+
Precisamos criar o banco manualmente
20+
------------------------------------
21+
22+
Começando...
23+
24+
.. code-block:: bash
25+
26+
$ sudo su - postgres
27+
28+
Veja o prompt:
29+
30+
.. code-block:: bash
31+
32+
postgres@myuser:~$
33+
34+
Criando o banco
35+
36+
.. code-block:: bash
37+
38+
$ createdb mydb
39+
40+
Se existir o banco faça
41+
42+
.. code-block:: bash
43+
44+
$ dropdb mydb
45+
46+
e crie novamente. Para sair digite
47+
48+
.. code-block:: bash
49+
50+
$ exit
51+
52+
Django
53+
------
54+
55+
Vamos criar um virtualenv e instalar o `psycopg2 <http://initd.org/psycopg/docs/install.html#use-a-python-package-manager>`_, além do django.
56+
57+
.. code-block:: bash
58+
59+
virtualenv -p /usr/bin/python3 teste
60+
cd teste
61+
source bin/activate
62+
pip install psycopg2 django
63+
pip freeze
64+
pip freeze > requirements.txt
65+
66+
**Dica**: Para diminuir o caminho do prompt digite
67+
68+
.. code-block:: bash
69+
70+
$ PS1="(`basename \"$VIRTUAL_ENV\"`):/\W$ "
71+
72+
**Dica**:
73+
74+
.. code-block:: bash
75+
76+
vim ~/.bashrc +
77+
alias manage='python $VIRTUAL_ENV/manage.py'
78+
79+
Com isto nós podemos usar apenas ``manage`` ao invés de ``python manage.py``.
80+
81+
Criando o projeto
82+
^^^^^^^^^^^^^^^^^
83+
84+
.. code-block:: bash
85+
86+
django-admin.py startproject myproject .
87+
cd myproject
88+
python ../manage.py startapp core
89+
90+
**Edite o settings.py**
91+
92+
.. code-block:: python
93+
94+
DATABASES = {
95+
'default': {
96+
'ENGINE': 'django.db.backends.postgresql_psycopg2',
97+
'NAME': os.path.join(BASE_DIR, 'mydb'),
98+
'USER': 'myuser',
99+
'PASSWORD': 'mypassword',
100+
'HOST': '127.0.0.1',
101+
'PORT': '', # 8000 is default
102+
}
103+
}
104+
105+
**Rode a aplicação**
106+
107+
.. code-block:: bash
108+
109+
python manage.py migrate
110+
python manage.py runserver
111+
112+
http://127.0.0.1:8000/ ou http://localhost:8000/
113+
114+
**Edite o models.py**
115+
116+
.. code-block:: python
117+
118+
from django.db import models
119+
from django.utils.translation import ugettext_lazy as _
120+
121+
122+
class Person(models.Model):
123+
name = models.CharField(_('Nome'), max_length=50)
124+
email = models.EmailField(_('e-mail'), max_length=30, unique=True)
125+
age = models.IntegerField(_('Idade'))
126+
active = models.BooleanField(_('Ativo'), default=True)
127+
created_at = models.DateTimeField(
128+
_('Criado em'), auto_now_add=True, auto_now=False)
129+
130+
class Meta:
131+
ordering = ['name']
132+
verbose_name = "pessoa"
133+
verbose_name_plural = "pessoas"
134+
135+
def __str__(self):
136+
return self.name
137+
138+
Leia mais em
139+
140+
`Tutorial Django 1.7 <http://pythonclub.com.br/tutorial-django-17.html>`_
141+
142+
`Como criar um site com formulário e lista em 30 minutos? <http://pythonclub.com.br/criar-site-com-form-lista-30-min.html>`_
143+
144+
**Edite o settings.py** novamente
145+
146+
Em *INSTALLED_APPS* insira a app *core*.
147+
148+
.. code-block:: python
149+
150+
INSTALLED_APPS = (
151+
...
152+
'myproject.core',
153+
)
154+
155+
**Faça um migrate**
156+
157+
.. code-block:: bash
158+
159+
python manage.py makemigrations core
160+
python manage.py migrate
161+
162+
Um pouco de shell
163+
^^^^^^^^^^^^^^^^^
164+
165+
.. code-block:: bash
166+
167+
python manage.py shell
168+
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
169+
[GCC 4.8.2] on linux
170+
Type "help", "copyright", "credits" or "license" for more information.
171+
(InteractiveConsole)
172+
>>>
173+
174+
175+
176+
Serve para manipular a app pelo **terminal**.
177+
178+
.. code-block:: python
179+
180+
>>> from myproject.core.models import Person
181+
>>> p = Person.objects.create(name='Regis',email='[email protected]',age=35)
182+
>>> p.id
183+
>>> p.name
184+
>>> p.email
185+
>>> p.age
186+
>>> p.active
187+
>>> p.created_at
188+
>>> p = Person.objects.create(name='Xavier',email='[email protected]',age=66,active=False)
189+
>>> persons = Person.objects.all().values()
190+
>>> for person in persons: print(person)
191+
>>> exit()
192+
193+
Leia mais em
194+
195+
*Tutorial PostgreSql*
196+
197+
*PostgreSql + Python3*
198+
199+
`Tutorial Django 1.7 <http://pythonclub.com.br/tutorial-django-17.html>`_
200+
201+
`Como criar um site com formulário e lista em 30 minutos? <http://pythonclub.com.br/criar-site-com-form-lista-30-min.html>`_
202+
203+
`How To Install and Configure Django with Postgres, Nginx, and Gunicorn <https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-django-with-postgres-nginx-and-gunicorn>`_
204+
205+
http://www.postgresql.org/docs/9.4/static/tutorial-createdb.html
206+
207+
http://www.postgresql.org/docs/9.4/static/index.html
208+
209+
http://www.postgresql.org/docs/9.4/static/tutorial-sql.html

content/postgresql-python3.rst

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
PostgreSql + Python3
2+
====================
3+
4+
:date: 2015-02-05 13:00
5+
:tags: python, postresql, banco de dados
6+
:category: Python, Banco de dados
7+
:slug: postgresql-python3
8+
:author: Regis da Silva
9+
10+
:github: rg3915
11+
:summary: Esta é a parte 2 (de 3) da série de posts sobre PostgreSql...
12+
13+
Se você já leu o *Tutorial Postgresql* este post é uma continuação. Aqui nós veremos como manipular um banco de dados PostgreSql no Python3.
14+
15+
Além da instalação mostrada no primeiro post precisaremos de
16+
17+
.. code-block:: bash
18+
19+
$ sudo apt-get install python-psycopg2 # para python2
20+
# ou
21+
$ sudo apt-get install python3-psycopg2 # para python3
22+
23+
Começando...
24+
25+
.. code-block:: bash
26+
27+
$ sudo su - postgres
28+
29+
Veja o prompt:
30+
31+
.. code-block:: bash
32+
33+
postgres@myuser:~$
34+
35+
Criando o banco
36+
37+
.. code-block:: bash
38+
39+
$ createdb mydb
40+
41+
Se existir o banco faça
42+
43+
.. code-block:: bash
44+
45+
$ dropdb mydb
46+
47+
e crie novamente. Para sair digite
48+
49+
.. code-block:: bash
50+
51+
$ exit
52+
53+
Abra o python3.
54+
55+
.. code-block:: bash
56+
57+
$ python3
58+
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
59+
[GCC 4.8.2] on linux
60+
Type "help", "copyright", "credits" or "license" for more information.
61+
>>>
62+
63+
Importe o psycopg2
64+
65+
.. code-block:: python
66+
67+
>>> import psycopg2
68+
69+
Conectando a um banco de dados existente
70+
71+
.. code-block:: python
72+
73+
>>> conn = psycopg2.connect("dbname=mydb user=myuser")
74+
75+
Abrindo um cursor para manipular o banco
76+
77+
.. code-block:: python
78+
79+
>>> cur = conn.cursor()
80+
81+
Criando uma nova tabela
82+
83+
.. code-block:: python
84+
85+
>>> cur.execute("CREATE TABLE person (id serial PRIMARY KEY, name text, age integer);")
86+
87+
Inserindo dados.O Psycopg faz a conversão correta. Não mais injeção SQL.
88+
89+
.. code-block:: python
90+
91+
>>> cur.execute("INSERT INTO person (name, age) VALUES (%s, %s)",("O'Relly", 60))
92+
>>> cur.execute("INSERT INTO person (name, age) VALUES (%s, %s)",('Regis', 35))
93+
94+
Grava as alterações no banco
95+
96+
.. code-block:: python
97+
98+
>>> conn.commit()
99+
100+
# Select
101+
102+
.. code-block:: python
103+
104+
>>> cur.execute("SELECT * FROM person;")
105+
>>> cur.fetchall()
106+
107+
Fecha a comunicação com o banco
108+
109+
.. code-block:: python
110+
111+
>>> cur.close()
112+
>>> conn.close()
113+
>>> exit()
114+
115+
Leia também
116+
117+
*Tutorial PostgreSql*
118+
119+
*PostgreSql + Django*
120+
121+
http://initd.org/psycopg/docs/
122+
123+
http://initd.org/psycopg/docs/usage.html

0 commit comments

Comments
 (0)