Gaga Codex - WEB - 2022-04-03
Gaga Codex - WEB - 2022-04-03
Gabriel Cardoso
7 de abril de 2022
Gabriel Cardoso Gaga’s Codex - Programação Web Django I
Resumo
O objetivo deste arquivo é registrar conhecimentos em programação WEB para desenvolvimento tanto de frontend com
backend.
R esumo I
1 Protocolos 1
1.1 IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 FTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 IMAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.5 POP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.6 SSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
8 Django Shell 2
15 Publicando na Internet 15
1 Protocolos
1.1 IP
1.2 HTTP
1.3 FTP
1.4 IMAP
1.5 POP
1.6 SSL
Arquivo: 03-protocolo-http-e-seus-verbos.pdf
8 Django Shell
Entra no Shell como um terminal python. Permite que se manipule banco de dados manualmente e execute funções python.
É possı́vel testar comandos python.
Para utilizar o comando Django Shell utilize: python manage.py shell.
USER -> BROWSER -> URL -> VIEW -> -> MODELS -> DATABASE -> TEMPLATES -> BROWSER -> USER
views.py Contém as funções que serão chamadas pelas rotas para abrir os templates.
IMPORTANTE: Para cada aplicação criada, deve-se ir na seção settings.py do projeto, INSTALLED APPS e informar
o nome da aplicação. EX: ’core’,
IMPORTANTE 2: Ainda em settings.py na seção TEMPLATES em ’DIRS’ colocar ’templates’
9.3 URL
No pycharm, clique no diretório com o nome da aplicação, New, Python file. Dê o nome ”urls.py”.
9.4 Views
Uma view é uma função.
Exemplo:
9.5 Models
https://developer.mozilla.org/pt-BR/docs/Learn/Server-side/Django/Models
O projeto não tem Models. Quem possui models são as aplicações.
Os models são modelos de dados. São definidas classes nos models. Servirão para o Django criar bancos de dados
para o projeto.
O arquivo é chamado de ”models.py”.
Exemplo de criação de classes:
Confirme em settings se você informou a aplicação em INSTALLED APPS.
Em seguida é necessário realizar as migrações. Ele pegará todas as aplicações, todos os modelos e criar um arquivo
de migrations. Para isso, utilize o comando: python manage.py makemigrations
O banco de dado criado é referenciado no arquivo de settings na parte DATABASES.
O migration serve para gerenciar o histórico de modificações do banco de dados em comparação aos modelos de dados.
O próprio Django gerencia. Caso seja necessário voltar a um modelo de dados anterior será possı́vel.
Além de criar uma migration, é necessário aplicar a migração. Para isso utilize o comando: python manage.py migrate
Cada vez que for criada ou alterada uma classe deverá ser feito tanto a criação da migração quanto a migração.
9.6 Templates
É preciso configurar qual template será utilizado no arquivo settings.py do projeto.
É recomendado que o template de cada aplicação seja salvo independente dentro delas. Para isso deve-se criar uma
pasta dentro da aplicação chamada ”templates”.
Na seção TEMPLATES, na parte DIR, colocar o nome do(s) templates. EX:
% TEMPLATES = [
% {
% ’BACKEND ’: ’django . template . backends . django . DjangoTemplates ’,
% ’DIRS ’: [’templates ’],
% ’ APP DIRS ’: True ,
% ’OPTIONS ’: {
% ’ context processors ’: [
% ’django . template . context processors .debug ’,
% ’django . template . context processors . request ’,
% ’django . contrib .auth. context processors .auth ’,
% ’django . contrib . messages . context processors . messages ’,
% ],
% },
% },
%]
Deve ser configuradas também as views. Para isso é necessário clicar em New¿HTML File e criar as views de cada
página dentro da pasta ”templates”criada anteriormente.
O Django possui templates para url digitados incorretamente no dominio do site. Para Utilizar o template importe
com o comando no arquivo de views:
from django . shortcuts import get object or 404
A view do produto deverá também sofrer uma alteração conforme mostrado a seguir:
from django . shortcuts import get object or 404
from django .http import HttpResponse
from django . template import loader
Abra o Pycharm.
[auth]
changepassword
createsuperuser
[contenttypes]
remove\_ stale\_ contenttypes
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
[sessions]
clearsessions
[staticfiles]
collectstatic
findstatic
runserver
Para mais informações sobre um comando especı́fico utilize o comando: python manage.py help [Comando]
11.2.3 requirements.txt
11.2.4 urls.py
Por padrão o arquivo URLS somente vem no projeto e não na aplicação. É possı́vel utilizar o URLs da aplicação importanto
para o projeto.
from django . contrib import admin
from django .urls import path
from core. views import index , contato
É importante também adicionar os paths para as paginas, mostrando a ”condição”de chamada. A página atribuı́da ao
parâmetro ” será a página inicial.
urlpatterns = [
path(’admin/’, admin.site.urls),
path(’’,index),
path(’contato ’, contato )
]
Caso uma rota não seja adicionada e um cliente solicita essa rota será mostrado um erro dizendo que não foi encontrada a
rota. Não é recomendado configurar as rotas no projeto e sim nas aplicações. O ideal seria:
11.2.5 wsgi.py
Arquivo exclusivo para publicação. Geralmente não se mexe nesse arquivo.
OBS: Caso dê problema tente reinstalar o django com o comando pip install django
makemigrations , which is responsible for creating new migrations based on the changes you have made to your
models.
sqlmigrate, which displays the SQL statements for a migration.
You should think of migrations as a version control system for your database schema. makemigrations is responsible
for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for
applying those to your database.
The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed
to, and distributed as part of, its codebase. You should be making them once on your development machine and then running
the same migrations on your colleagues’ machines, your staging machines, and eventually your production machines.
Migrations will run the same way on the same dataset and produce consistent results, meaning that what you see
in development and staging is, under the same circumstances, exactly what will happen in production. Django will make
migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can
reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations
later on (for example, if you’ve set custom validators) 1 2
setting.
2 Referência: https:docs.djangoproject.comen4.0topicsmigrations
STATIC ROOT
STATIC URL
STATICFILES DIRS
STATICFILES STORAGE
STATICFILES FINDERS
11.3.5 settings.py
Configurações Django do projeto
- DEBUG
Quando publicar o projeto o DEBUG deve ficar em FALSE. Impedirá das mensagens serem mostradas ao usuário.
- ALLOWED HOSTS
Serve para definir qual o domı́nio que deverá executar a aplicação. Somente será utilizada quando o DEBUG estiver em
FALSE. Parâmetro [ ’ ’ ] fará com que qualquer um tenha acesso.
- MIDDLEWARE
Verifica configurações de segurança como controle de usuário, sessão, comum, segurança de formulários, autenticação, etc...
É possı́vel criar os próprios middlewares.
- ROOT URLCONF
- TEMPLATES
- WSGI APPLICATION
- DATABASES
Por padrão o Django utiliza o Banco de dados SQLite3. Já é nativo no Python, não precisa instalar nada a mais.
Configura recursos de validação de senhas de usuário por aproximação, senha comum, comprimento mı́nimo, somente números
e etc...
- LANGUAGE CODE
- TIMEZONE
- USE I18N
Configuração de multilinguagem.
- USE L10N
???
- USE TZ
- STATIC URL
11.3.6 admin.py
A web-based administrative back end is a standard feature of modern websites. The administrative interface, or admin
for short, allows trusted site administrators to create, edit and publish content, manage site users, and perform other
administrative tasks.
Django comes with a built-in admin interface. With Django’s admin you can authenticate users, display and handle
forms, and validate input; all automatically. Django also provides a convenient interface to manage model data.
When you ran startproject in Chapter 2, Django created and configured the default admin site for you. All you need to
do now is create an admin user (superuser) to log into the admin site. To create an admin user, run the following command
from inside your virtual environment:
python manage.py createsuperuser
Enter your desired username and press enter:
Username: admin
Django then prompts you for your email address:
Email address: [email protected]
The final step is to enter your password. Enter your password twice, the second time to confirm your password:
Password: ********** Password (again): ********* Superuser created successfully.
Now you have created an admin user, you’re ready to use the Django admin. Let’s start the development server and
explore.
First, make sure the development server is running, then open a web browser to http:127.0.0.1:8000admin. You should
see the admin’s login screen (Figure 7-1).
Log in with the superuser account you created. Once logged in, you should see the Django admin index page (Figure
7-2).
At the top of the index page is the Authentication and Authorization group with two types of editable content: Groups
and Users. They are provided by the authentication framework included in Django. We will look at users and groups later
in the chapter.
The superuser we created earlier has full access to all models in the admin and can add, change, and delete any model
record. In a real application, you will want to limit the number of users who have full access to your site.
Adding a new user is easy—go to the admin index page and click the green plus sign on the right of the Users entry
on the admin home page. Enter a username and password and click save to add the new user.
Return to the admin home page and click Users to open the user change list (Figure 7-12). Click on the username to
open the user edit screen.
11.3.7 apps.py
Django contains a registry of installed applications that stores configuration and provides introspection. It also maintains a
list of available models.
This registry is called apps and it’s available in django.apps:
from django .apps import apps
>>>
>>> apps. get app config (’admin ’). verbose name
’Administration ’
INSTALLED APPS = [
...
’polls .apps. PollsAppConfig ’,
...
]
11.3.8 models.py
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the
data you’re storing. Generally, each model maps to a single database table.
The basics:
Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a
database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries.
Quick example¶
This example model defines a Person, which has a first name and last name:
from django .db import models
class Person ( models .Model ):
first name = models . CharField ( max length =30)
last name = models . CharField ( max length =30)
first name and last name are fields of the model. Each field is specified as a class attribute, and each attribute maps
to a database column.
The above Person model would create a database table like this:
CREATE TABLE myapp person (
"id" serial NOT NULL PRIMARY KEY ,
" first name " varchar (30) NOT NULL ,
" last name " varchar (30) NOT NULL
);
Some technical notes:
The name of the table, myapp person, is automatically derived from some model metadata but can be overridden.
See Table names for more details. An id field is added automatically, but this behavior can be overridden. See Automatic
primary key fields. The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it’s worth noting
Django uses SQL tailored to the database backend specified in your settings file.
Using models
Once you have defined your models, you need to tell Django you’re going to use those models. Do this by editing your
settings file and changing the INSTALLED APPS setting to add the name of the module that contains your models.py.
For example, if the models for your application live in the module myapp.models (the package structure that is created
for an application by the manage.py startapp script), INSTALLED APPS should read, in part:
INSTALLED APPS = [
#...
’myapp ’,
#...
]
When you add new apps to INSTALLED APPS, be sure to run manage.py migrate, optionally making migrations for
them first with manage.py makemigrations.
Fields
The most important part of a model – and the only required part of a model – is the list of database fields it defines.
Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean,
save, or delete.
Example:
from django .db import models
class Musician ( models .Model ):
first name = models . CharField ( max length =50)
last name = models . CharField ( max length =50)
11.3.9 tests.py
This document is split into two primary sections. First, we explain how to write tests with Django. Then, we explain how
to run them.
Writing tests¶
Django’s unit tests use a Python standard library module: unittest. This module defines tests using a class-based
approach.
Here is an example which subclasses from django.test.TestCase, which is a subclass of unittest.TestCase that runs
each test inside a transaction to provide isolation:
from django .test import TestCase
from myapp . models import Animal
11.3.10 urls.py
A request in Django first comes to urls.py and then goes to the matching function in views.py. Python functions in views.py
take the web request from urls.py and give the web response to templates. It may go to the data access layer in models.py
as per the queryset.
If we look at the 3-tier architecture of an app. Views are like the business logic layer. It is the controller in a typical
MVC (Model View Controller) design but Django has a slightly different naming convention called MVT (Model View
Template) where:
Model is the data access layer,
View is the business logic layer and
Template is the presentation layer.
Django has a urls.py file under the project by default. It also has a prep-defined path for the admin app. However,
Django recommends mapping all resources via another urls.py newly created under the app. The below explains it:
mysite – urls.py
urlpatterns = [
path(’’, views.index), # app homepage
]
Django View Function
The URL mapping will redirect requests from project URLs to app URLs and then to the respective view function.
A sample view function code may look like this:
def index ( request ):
return render (request , ’index.html ’, { } )
or ,
11.3.11 views.py
A view function, or view for short, is a Python function that takes a web request and returns a web response. This response
can be the HTML contents of a web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything,
really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere
you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of
putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application
directory.
A simple view
Here’s a view that returns the current date and time, as an HTML document:
from django .http import HttpResponse
import datetime
11.3.12 asgi.py
Como fazer o deploy com ASGI
As well as WSGI, Django also supports deploying on ASGI, the emerging Python standard for asynchronous web
servers and applications.
Django’s startproject management command sets up a default ASGI configuration for you, which you can tweak as
needed for your project, and direct any ASGI-compliant application server to use.
Django includes getting-started documentation for the following ASGI servers:
How to use Django with Daphne How to use Django with Uvicorn
5. Utilize o comando a seguir para criar um projeto Django sem criação de subdiretórios.
django-admin startproject django2 .
6. Utilize o comando para criar uma aplicação
django-admin startapp core
CSS;
Javascript;
HTML.
15 Publicando na Internet
Será utilizado o domı́nio do ”heroku”. Especificamente para esse caso as configurações do arquivo settings.py devem ter as
seguintes especificações:
ALLOWED HOSTS = [’ * ’]
MIDDLEWARE = [
’django . middleware . security . SecurityMiddleware ’,
’whitenoise . middleware . WhitheNoiseMiddleware ’,
’django . contrib . sessions . middleware . SessionMiddleware ’,
’django . middleware . common . CommonMiddleware ’,
’django . middleware .csrf. CsrfViewMiddleware ’,
’django . contrib .auth. middleware . AuthenticationMiddleware ’,
’django . contrib . messages . middleware . MessageMiddleware ’,
’django . middleware . clickjacking . XFrameOptionsMiddleware ’,
STATIC URL = ’/ static /’
STATIC ROOT = os.path.join( BASE DIR , ’staticfiles ’)
]
Devem ser instaladas as bibliotecas whitenoise e gunicorn com os comandos. O Whitenoise serve para o django mostrar
os arquivos estáticos em modo produção. O gunicorn é um servidor para rodar em modo produção.
pycache
*.*
*.pyc
.idea
12. Para atualizar o arquivo requirements com as novas bibliotecas execute o comando: pip freeze ¿ requirements.txt
13. Na pasta raı́z do projeto, crie um arquivo chamado ”Procfile”. Se o Pycharm perguntar o tipo informe que é um
arquivo de texto. Este arquivo será utilizado pelo Heroku. Dentro do arquivo criado escreva:
18. Para enviar o código e enviar parao projeto digite o comando ”git push heroku master”
19. Pronto! Acesse o site da sua aplicação.