Commit c57eb9dd authored by Administrator's avatar Administrator

iniciando o versionamento

parents
Pipeline #3667 failed with stages
in 0 seconds
File added
image: docker:stable
stages:
- pre-build
- build
- test
- deploy
- notificacao
build-docker:
services:
- docker:dind
retry: 2
before_script:
- docker info
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
stage: pre-build
script:
- docker build -t minha-imagem .
- docker tag minha-imagem jnlucas/minha-imagem:latest
- docker push jnlucas/minha-imagem:latest
build-project:
image: jnlucas/minha-imagem:latest
retry: 2
services:
- docker:dind
- mysql:5.7
variables:
MYSQL_USER: $DB_USER
MYSQL_PASSWORD: $DB_PASSWORD
MYSQL_DATABASE: $DB_DATABASE
MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
DB_NAME: $DB_DATABASE
DB_USER: $DB_USER
DB_PASSWORD: $DB_PASSWORD
DB_PORT: '3306'
DB_HOST: 'mysql'
SECRET_KEY: $DB_SECRET_KEY
stage: build
tags:
- executor-tarefas
dependencies:
- build-docker
script:
- python manage.py makemigrations
- python manage.py migrate
test-project:
image: jnlucas/minha-imagem:latest
stage: test
services:
- docker:dind
- mysql:5.7
variables:
MYSQL_USER: $DB_USER
MYSQL_PASSWORD: $DB_PASSWORD
MYSQL_DATABASE: $DB_DATABASE
MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
DB_NAME: $DB_DATABASE
DB_USER: $DB_USER
DB_PASSWORD: $DB_PASSWORD
DB_PORT: '3306'
DB_HOST: 'mysql'
SECRET_KEY: $DB_SECRET_KEY
dependencies:
- build-project
tags:
- executor-tarefas
script:
- python -m unittest setUp
deploy-project:
stage: deploy
tags:
- executor-deploy
dependencies:
- test-project
script:
- tar cfz arquivos.tgz *
- scp arquivos.tgz aluraverde@192.168.1.34:/Users/Shared/deploy/
- ssh aluraverde@192.168.1.34 ' cd /Users/Shared/deploy/; tar xfz arquivos.tgz; /usr/local/bin/docker-compose up -d'
notificacao-sucesso:
stage: notificacao
tags:
- executor-deploy
when: on_success
script:
- sh notificacaoSucesso.sh
notificacao-falhas:
stage: notificacao
tags:
- executor-deploy
when: on_failure
script:
- echo sh notificacaoFalha.sh
FROM python:3.6
#Copiando os arquivos do projeto para o diretorio usr/src/app
COPY . /usr/src/app
#Definindo o diretorio onde o CMD será executado e copiando o arquivo de requerimentos
WORKDIR /usr/src/app
COPY requirements.txt ./
# Instalando os requerimentos com o PIP
RUN pip install --no-cache-dir -r requirements.txt
# Expondo a porta da APP
EXPOSE 8000
# Executando o comando para subir a aplicacao
CMD ["gunicorn", "to_do.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "3"]
\ No newline at end of file
# django-todolist
Simple todolist write in django for general use and pipeline automation..
- Be kind with my baby
### Quick and free tip:
> With great power comes great responsibility
### Tech
Dillinger uses a number of open source projects to work properly:
* [Django] - Django makes it easier to build better Web apps more quickly and with less code.
* [Python-Venv] - The venv module provides support for creating lightweight “virtual environments” with their own site directories
* [MySQL] - MySQL is an Oracle-backed open source relational database management system (RDBMS) based on Structured Query Language (SQL).
### Installation
Install the dependencies and start the server.
```sh
$ cd django-todolist
$ pip install -r requirements.txt
$ python manage.py migrate # Running the migrations
$ python manage.py createsuperuser # Create a superuser
$ python manage.py runserver
```
License
----
GPL
from django.contrib import admin
from .models import Todo
admin.site.register(Todo)
\ No newline at end of file
from django.apps import AppConfig
class CoreConfig(AppConfig):
name = 'core'
from django import forms
from .models import Todo
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = ('title', 'text', 'completed')
# Generated by Django 2.1.7 on 2019-03-06 04:09
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Todo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('text', models.TextField(blank=True)),
('created_at', models.DateField(blank=True, default=datetime.datetime.now)),
('completed', models.BooleanField(default=False)),
],
),
]
# Generated by Django 2.1.7 on 2019-03-06 04:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='todo',
name='completed_at',
field=models.DateField(blank=True, null=True),
),
]
# Generated by Django 2.1.7 on 2019-03-07 18:00
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_todo_completed_at'),
]
operations = [
migrations.AddField(
model_name='todo',
name='due_date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='todo',
name='created_at',
field=models.DateField(blank=True, default=datetime.datetime(2019, 3, 7, 15, 0, 36, 987938)),
),
migrations.AlterField(
model_name='todo',
name='text',
field=models.TextField(blank=True, max_length=280),
),
]
# Generated by Django 2.1.7 on 2019-03-22 00:23
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20190307_1500'),
]
operations = [
migrations.AlterField(
model_name='todo',
name='created_at',
field=models.DateField(blank=True, default=datetime.datetime(2019, 3, 21, 21, 23, 27, 716142)),
),
]
# Generated by Django 2.1.7 on 2019-03-26 02:22
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20190321_2123'),
]
operations = [
migrations.AlterField(
model_name='todo',
name='created_at',
field=models.DateField(blank=True, default=datetime.datetime(2019, 3, 25, 23, 22, 50, 245819)),
),
]
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=200)
text = models.TextField(blank=True, max_length=280)
created_at = models.DateField(default=datetime.now(), blank=True)
completed = models.BooleanField(default=False)
completed_at = models.DateField(blank=True, null=True)
due_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.title
{% load static %}
<!DOCTYPE html>
<html lang="br">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Todos</title>
{% block extra_styles %}
{% endblock %}
</head>
<body>
<nav>
<div class="nav-wrapper blue darken-4">
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><a href="{% url 'list_to_do' %}"><i class="fas fa-list-ul text-white fa-2x"></i></a></li>
<li><a href="{% url 'new_to_do' %}"><i class="fas fa-plus text-white fa-2x"></i></a></li>
</ul>
{% if user.is_authenticated %}
<div class="text-right">
<button type="button" class="btn btn-warning" >User: {{ user.get_username }}</button>
<a class="btn btn-outline-info" href="{% url 'logout' %}" role="button">Log Out</a>
{% endif %}
</div>
</div>
</nav>
<br>
<div class="container">
{% block content %}
{% endblock %}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
\ No newline at end of file
{% extends 'core/base.html' %}
{% block extra_styles %}
<style>
.card-columns {
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(xl) {
column-count: 5;
}
}
</style>
{% endblock %}
{% block content %}
{% for todo in todos %}
<div class="row">
<div class="col s10 m12">
<div class="card blue darken-3">
<div class="card-content white-text">
<span class="card-title">#{{todo.id}} - {{todo.title}}</span>
<p class="alert alert-info">{{todo.text}}</p>
</div>
<div class="card-action">
{% if not todo.completed %}
<div class="alert alert-warning right">
<a href="{% url 'completed' pk=todo.pk %}"><i class="fas fa-check fa-1x"></i></a>
<strong>Open since {{todo.created_at}}</strong>
</div>
{% else %}
<div class="card-content white-text">
<div class="alert alert-success right">
<a class="fas fa-check-double fa-1x"></a>
<strong>Completed at: {{todo.completed_at}}</strong>
</div>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% empty %}
<div class="alert alert-info">
<strong>No tasks!</strong>
</div>
{% endfor %}
{% endblock %}
{% extends 'core/base.html' %}
{% load bootstrap%}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form|bootstrap }}
<button type="submit" class="btn btn-warning">Save</button>
</form>
{% endblock %}
\ No newline at end of file
from django.contrib.auth.models import User
from django.urls import reverse
from django.test import TestCase
from .models import Todo
class TodoTestCase(TestCase):
def setUp(self):
self.user = User.objects.create_user(
username='test', password='test')
self.user.save()
def test_system(self):
# Logging
login = self.client.login(username='test', password='test')
self.assertEquals(login, True)
response = self.client.get(reverse('new_to_do'))
self.assertEqual(response.status_code, 200)
self.assertEqual(str(response.context['user']), 'test')
# Todo Test
self.client.post('/todo/new/', {'title': "test_title", 'text': "test_text"})
self.assertIsInstance(Todo.objects.last(), Todo)
# Checking inserted tasks
self.assertEqual(Todo.objects.last().title, 'test_title')
self.assertEqual(Todo.objects.last().text, 'test_text')
\ No newline at end of file
from django.urls import path
from . import views
urlpatterns = [
path('', views.TodoList.as_view(), name='list_to_do'),
path('todo/new/', views.TodoCreate.as_view(), name='new_to_do'),
path('completed/<int:pk>/', views.completed, name='completed'),
]
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from .models import Todo
from .forms import TodoForm
from django.urls import reverse_lazy
from datetime import datetime
class TodoCreate(CreateView):
model = Todo
template_name = "core/new.html"
form_class = TodoForm
success_url = reverse_lazy('list_to_do')
class TodoList(ListView):
model = Todo
context_object_name = 'todos'
template_name = 'core/index.html'
def get_queryset(self):
todo= Todo.objects.all().order_by('completed')
return todo
def completed(request, pk):
todo = get_object_or_404(Todo, pk=pk)
todo.completed = True
todo.completed_at = datetime.now()
todo.save()
return redirect('list_to_do')
version: '3'
services:
db:
image: mysql:5.7
ports:
- '3309:3306'
environment:
MYSQL_DATABASE: 'todo_dev'
MYSQL_USER: 'devops_dev'
MYSQL_PASSWORD: 'mestre'
MYSQL_ROOT_PASSWORD: 'senha'
web:
image: jnlucas/minha-imagem:latest
volumes:
- ./env:/usr/src/app/to_do/.env
ports:
- "8009:8000"
depends_on:
- db
# Fazendo a migracao inicial dos dados
#docker-compose run web python manage.py makemigrations
#docker-compose run web python manage.py migrate
# Criando o superuser para acessar a app
#docker-compose run web python manage.py createsuperuser
[config]
# Secret configuration
SECRET_KEY = 'r*5ltfzw-61ksdm41fuul8+hxs$86yo9%k1%k=(!@=-wv4qtyv'
# conf
DEBUG=True
# Database
DB_NAME = "todo_dev"
DB_USER = "devops_dev"
DB_PASSWORD = "mestre"
DB_HOST = "db"
DB_PORT = "3309"
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'to_do.settings')
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)
#!/bin/bash
curl -X POST -H 'Content-type: application/json' --data '{"text":"ops! algo deu errado"}' https://hooks.slack.com/services/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
\ No newline at end of file
#!/bin/bash
curl -X POST -H 'Content-type: application/json' --data '{"text":"tudo deu certo na pipeline!"}' https://hooks.slack.com/services/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
\ No newline at end of file
wheel==0.29.0
Django==2.1.7
django-bootstrap-form==3.4
django-glrm==1.1.3
django-widget-tweaks==1.4.3
mysqlclient==1.4.2.post1
pytz==2018.9
uWSGI==2.0.18
gunicorn==19.9.0
python-decouple==3.1
html,
body {
height: 100%;
}
body {
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-ms-flex-align: center;
-ms-flex-pack: center;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .checkbox {
font-weight: 400;
}
.form-signin .form-control {
position: relative;
box-sizing: border-box;
height: auto;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
\ No newline at end of file
{% extends 'core/base.html' %}
{% load bootstrap%}
{% load widget_tweaks %}
{% load static %}
{% load staticfiles %}
{% block extrastylesheets %}
<link rel="stylesheet" href="{% static '' %}">
{% endblock %}
{% block menu %}
{% endblock %}
{% block content %}
<div class="container text-center">
<form class="form-signin" method="post">
{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Login</h1>
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% render_field form.username class="form-control " placeholder='Login' %}
{% render_field form.password class="form-control " placeholder='Senha' %}
<button class="btn btn-lg btn-outline-success btn-block" type="submit">Log In</button>
<p class="mt-5 mb-3 text-muted">Jenkins Alura</p>
</form>
</div>
{% endblock %}
{% block extrascripts %}
{% endblock %}
"""
Django settings for to_do project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'bootstrapform',
'widget_tweaks',
]
MIDDLEWARE = [
'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',
'global_login_required.GlobalLoginRequiredMiddleware',
]
ROOT_URLCONF = 'to_do.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'to_do.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':config('DB_NAME'),
'USER':config('DB_USER'),
'PASSWORD':config('DB_PASSWORD'),
'HOST':config('DB_HOST'),
'PORT':config('DB_PORT'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en_US'
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
#LOGIN
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = 'list_to_do'
LOGOUT_REDIRECT_URL = 'login'
PUBLIC_VIEWS = [
'django.contrib.auth.views.LoginView',
'django.contrib.auth.views.LogoutView'
]
\ No newline at end of file
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
path('login/', LoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(), name='logout'),
]
"""
WSGI config for to_do 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'to_do.settings')
application = get_wsgi_application()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment