Enzo Yair

configuraciones para develop

*.log
*.py[codt]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
logs
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
coverage.xml
junit.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Complexity
output/*.html
output/*/index.html
# Sphinx
docs/_build
.webassets-cache
# Virtualenvs
venv
# intellij
*.ipr
*.iml
*.iws
# vim
*.sw[o,p]
.DS_Store
# node
node_modules/
# bower packages
.sass-cache/
.idea/.name
.idea/scopes/scope_settings.xml
.idea/encodings.xml
.idea/workspace.xml
# models
models.png
.idea/*
*.db
secret.key
.bash_history
.vagrant/*
# Sublime Text 3
*.sublime-project
*.sublime-workspace
# ?
.cache
src
# Configuration
.env
# Virtual Environment
.venv
tmp
Procfile.dev
# Cython .C files (precompilation)
*.c
__pycache__/
# Logs nginx
deployment/logs/
.pytest_cache/
project/settings/production.py
project/static/*
project/media/*
... ...
[socket:PROJECT-NAME]
host = 127.0.0.1
port = 8000
[watcher:PROJECT-NAME]
cmd = /path/virtualenv/bin/chaussette
args = --fd $(circus.sockets.PROJECT-NAME) PROJECT-NAME.wsgi.application
use_sockets = True
numprocesses = 3
autostart = True
stdout_stream.class = FileStream
stdout_stream.filename = /PATH/PROJECT/deployment/logs/circus-stdout.log
stderr_stream.class = FileStream
stderr_stream.filename = /PATH/PROJECT/deployment/logs/circus-stderr.log
[env:PROJECT-NAME]
PYTHONPATH = /PATH/SOURCE/PROJECT-NAME/
... ...
server {
listen 80;
charset utf-8;
server_name URL-PROJECT-NAME;
return 301 https://$host$request_uri;
}
server {
listen 443;
charset utf-8;
server_name URL-PROJECT-NAME;
client_max_body_size 4G;
ssl on;
ssl_certificate /etc/letsencrypt/live/URL-PROJECT-NAME/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/URL-PROJECT-NAME/privkey.pem;
location /static/ {
# autoindex off;
alias /PATH/PROJECT/PROJECT-NAME/static/;
}
location /media/ {
# autoindex off;
alias /PATH/PROJECT/PROJECT-NAME/media/;
}
location / {
proxy_pass http://localhost:8000;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
## Logs
access_log /PATH/PROJECT/deployment/logs/nginx-access.log;
error_log /PATH/PROJECT/deployment/logs/nginx-errors.log;
}
... ...
# General settings
DJANGO_DEBUG=true
DJANGO_SECRET_KEY=CHANGEME!!!
DJANGO_ALLOWED_HOSTS=*,127.0.0.1
# Database
DATABASE_URL=postgres://dbuser:dbpass@localhost:port/mydb
# SQLite
# DATABASE_URL=sqlite:///mydb.db
# Security! Better to use DNS for this task, but you can use redirect
DJANGO_SECURE_SSL_REDIRECT=False
# Facebook configuration
SOCIAL_AUTH_FACEBOOK_KEY=<your app id goes here>
SOCIAL_AUTH_FACEBOOK_SECRET=<your app secret goes here>
PROJECT_NAME_HEADER=Name Project
PROJECT_NAME_TITLE=Name Project
ACTIVAR_HERRAMIENTAS_DEBBUGING=false
\ No newline at end of file
... ...
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.base")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
... ...
from django.contrib import admin
from django.utils import timezone
from django.utils.translation import gettext as _
from . import filters
class PublicadoAdmin(admin.ModelAdmin):
actions = ['publicar', 'no_publicar']
def publicar(self, request, queryset):
updated_records = queryset.update(publicado=timezone.now())
message = _('updated records %s' % updated_records)
self.message_user(request, message)
publicar.short_description = 'Publicar los registros seleccionados'
def no_publicar(self, request, queryset):
registros_actualizados = queryset.update(publicado=None)
mensaje = f'Registros actualizados {registros_actualizados}'
self.message_user(request, mensaje)
no_publicar.short_description = 'No publicar los registros seleccionados'
def get_list_display(self, request):
return list(super().get_list_display(request)) + ['publicado']
def get_list_filter(self, request):
list_filter = [filters.PublicadoListFilter] + list(super().get_list_filter(request))
return list_filter
... ...
from django.apps import AppConfig
class CoreConfig(AppConfig):
name = 'core'
... ...
from django.contrib import admin
from django.utils.translation import gettext as _
# Filters Admin
class PublicadoListFilter(admin.SimpleListFilter):
title = 'Publicado'
# Parameter for the filter that will be used in the URL query.
parameter_name = 'publicado'
def lookups(self, request, model_admin):
return (
('true', 'Publicados'),
('false', 'No Publicados'),
)
def queryset(self, request, queryset):
value = self.value()
if value:
return queryset.exclude(publicado__isnull=value == 'true')
return queryset.all()
# DRF Filter Common.
def filter_unaccent_contains(queryset, name, value):
# TODO: add unaccent within the join list.
lookup = '__'.join([name, 'icontains'])
return queryset.filter(**{lookup: value})
... ...
from django.db import models
from django.utils import timezone
from .querysets import PublicadoQuerySet
class Publicado(models.Model):
class Meta:
abstract = True
publicado = models.DateTimeField(blank=True, null=True)
objects = PublicadoQuerySet.as_manager()
def publicar(self, estado=True):
self.publicado = timezone.now() if estado else None
self.save(update_fields=('publicado',))
... ...
from rest_framework_json_api.pagination import JsonApiPageNumberPagination
class LargePagination(JsonApiPageNumberPagination):
max_page_size = 300
page_size_query_param = 'page_size'
\ No newline at end of file
... ...
from django.db.models import QuerySet
class PublicadoQuerySet(QuerySet):
def get_queryset(self):
return self.filter(publicado__isnull=False)
... ...
from django.test import TestCase
# Create your tests here.
... ...
import json
import pytest
from django.contrib.auth import get_user_model
from oauth2_provider.models import get_application_model
from rest_framework.test import APIClient
User = get_user_model()
CONTENT_TYPE_JSON = 'application/json'
@pytest.fixture
def create_user(username, first_name='Admin', last_name='Root', email=None):
user, created = User.objects.get_or_create(
username=username,
email='{}@root.com'.format(username) if email is None else email,
defaults=dict(
first_name=first_name,
last_name=last_name,
password='password'
)
)
return user
@pytest.fixture
def get_default_test_user():
test_user = create_user(username='test_user', first_name='Test', last_name='User', email='test@user')
return test_user
def get_client_application():
Application = get_application_model()
application, _ = Application.objects.get_or_create(
name='TestApp',
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
skip_authorization=True
)
return application
def client_authorized():
app = get_client_application()
client = APIClient()
r = client.post('/oauth2/token/', {
'grant_type': 'client_credentials',
'client_id': app.client_id,
'client_secret': app.client_secret
})
response = json.loads(r.content)
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Bearer ' + response['access_token'])
return client
... ...
import json
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from .fixtures import create_user
JSON_CONTENT_TYPE = "application/json"
JSON_API_CONTENT_TYPE = "application/vnd.api+json"
JSON_API_ACCEPT_HEADER = "application/vnd.api+json"
def get_authenticated_client(user=None):
client = APIClient()
if user is not None:
client.force_authenticate(user=user)
return client
def get(url, params=None, headers=None, user_logged=None):
url += "?{}".format(params) if params else ''
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.get(url, **headers)
return response
def post(url, data=None, content_type=JSON_API_CONTENT_TYPE, headers=None, user_logged=None):
url = url + '/' if not url.endswith('/') else url
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.post(url, data=json.dumps(data), content_type=content_type, **headers)
return response
def patch(url, data=None, content_type=JSON_API_CONTENT_TYPE, headers=None, user_logged=None):
url = url + '/' if not url.endswith('/') else url
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.patch(url, data=json.dumps(data), content_type=content_type, **headers)
return response
def delete(url, data=None, content_type=JSON_API_CONTENT_TYPE, headers=None, user_logged=None):
url = url + '/' if not url.endswith('/') else url
client = get_authenticated_client(user_logged)
if headers is None:
headers = {'HTTP_ACCEPT': JSON_API_ACCEPT_HEADER}
response = client.delete(url, data=json.dumps(data), content_type=content_type, **headers)
return response
... ...
from django.shortcuts import render
# Create your views here.
... ...
from rest_framework import routers
# Define routes
router = routers.DefaultRouter()
... ...
import sys
import environ
import os
from django.utils.translation import gettext_lazy as _
ROOT_DIR = environ.Path(__file__) - 3
PROJECT_DIR = ROOT_DIR.path('project')
APPS_DIR = PROJECT_DIR.path('apps')
sys.path.insert(0, str(APPS_DIR))
# Load operating system environment variables and then prepare to use them
env = environ.Env()
# patch for https://github.com/joke2k/django-environ/issues/119
env_file = str(ROOT_DIR.path('.env'))
env.read_env(env_file)
# PROJECT
PROJECT_NAME_HEADER = env('PROJECT_NAME_HEADER', default='Project Name')
PROJECT_NAME_TITLE = env('PROJECT_NAME_TITLE', default='Project Name')
# DEBUG
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool('DJANGO_DEBUG', False)
SECRET_KEY = env('DJANGO_SECRET_KEY', default='CHANGEME!!!') # noqa
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default='*') # noqa
DATABASES = {
'default': {
'ENGINE': os.environ.get('POSTGRES_ENGINE'),
'NAME': os.environ.get('POSTGRES_DB'),
'USER': os.environ.get('POSTGRES_USER'),
'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),
'HOST': os.environ.get('POSTGRES_HOST'),
'PORT': os.environ.get('POSTGRES_PORT'),
}
}
DJANGO_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
THIRD_PARTY_APPS = (
'rest_framework',
'django_filters',
'corsheaders',
)
PROJECT_APPS = (
'core',
)
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS
MIDDLEWARE = (
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'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',
)
ROOT_URLCONF = 'project.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'project.wsgi.application'
LANGUAGE_CODE = 'es-ar'
TIME_ZONE = 'America/Argentina/Catamarca'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
('es', _('Español')),
('en', _('English')),
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = str(PROJECT_DIR.path('static'))
STATIC_URL = '/static/'
MEDIA_ROOT = str(PROJECT_DIR.path('media'))
MEDIA_URL = env.str('MEDIA_URL', default='/media/')
CORS_ORIGIN_ALLOW_ALL = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(PROJECT_DIR.path('templates'))],
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
LOGIN_URL = '/admin/login/'
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
REST_FRAMEWORK = {
'PAGE_SIZE': 50,
'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
'DEFAULT_PAGINATION_CLASS': 'core.paginations.LargePagination',
'DEFAULT_PARSER_CLASSES': (
'rest_framework_json_api.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_RENDERER_CLASSES': ('rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer'),
'DEFAULT_FILTER_BACKENDS': (
'rest_framework_json_api.filters.QueryParameterValidationFilter',
'rest_framework_json_api.filters.OrderingFilter',
'rest_framework_json_api.django_filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
),
'SEARCH_PARAM': 'filter[search]',
'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework_json_api.renderers.JSONRenderer',
'rest_framework.renderers.MultiPartRenderer',
),
'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json',
}
ACTIVAR_HERRAMIENTAS_DEBBUGING = env.bool('ACTIVAR_HERRAMIENTAS_DEBBUGING', default=False)
if ACTIVAR_HERRAMIENTAS_DEBBUGING:
INSTALLED_APPS += (
'debug_toolbar',
'django_extensions',
)
MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
... ...
from .base import *
SECRET_KEY = 'CHANGEME!!!'
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
MEDIA_ROOT = str(PROJECT_DIR.path('test_media'))
\ No newline at end of file
... ...
"""portal URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from .router import router
# I added platform's name.
admin.site.site_header = getattr(settings, 'PROJECT_NAME_HEADER')
admin.site.site_title = getattr(settings, 'PROJECT_NAME_TITLE')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(router.urls)),
]
... ...
"""
WSGI config for portal project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from os.path import abspath, dirname
from sys import path
from django.core.wsgi import get_wsgi_application
SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.base")
application = get_wsgi_application()
... ...
[pytest]
DJANGO_SETTINGS_MODULE=PROJECTproject-NAME.settings.testing
norecursedirs = requirements deployment
testpaths = tests
addopts = --capture=fd --nomigrations
... ...
# Requeriments base.
Django==4.2.9
django-cors-headers==4.3.0
django-filter==23.3
djangorestframework==3.14.0
django-environ==0.11.2
djangorestframework-jsonapi==6.1.0
django-oauth-toolkit==2.3.0
mozilla-django-oidc==3.0.0
# database
psycopg2==2.9.9
psycopg2-binary==2.9.9
\ No newline at end of file
... ...
-r testing.txt
django-extensions==3.1.3
django-debug-toolbar==3.2.2
... ...
-r base.txt
chaussette==1.3.0
... ...
-r base.txt
pytest==6.2.5
pytest-django==4.4.0
... ...