customStorage manager in Sistemas app and zip views to upload the zip

This commit is contained in:
fjrodriguez
2023-02-10 07:39:25 -06:00
parent b73a4d50d0
commit ddc4be05a2
6 changed files with 120 additions and 11 deletions

View File

@@ -42,20 +42,15 @@ def read_env_file():
#env_file = os.listdir(settings.BASE_DIR) #env_file = os.listdir(settings.BASE_DIR)
storage = FileSystemStorage(location=settings.BASE_DIR) storage = FileSystemStorage(location=settings.BASE_DIR)
env_file= os.path.join(settings.BASE_DIR,'.env') env_file= os.path.join(settings.BASE_DIR,'.env')
lista =['asds', 'asdasd','sss','com' ,'pol.com'] lista =['asds', 'asdasd','sss','com' ,'pol.com']
if storage.exists(env_file): if storage.exists(env_file):
with open(env_file, 'r') as file: with open(env_file, 'r') as file:
data = file.read() data = file.read()
data =re.findall('"([^"]*)"',data) data =re.findall('"([^"]*)"',data)
for x in lista: for x in lista:
data.append(x) data.append(x)
res= ' '.join(data) res= ' '.join(data)
final = '"'+res+'"' final = '"'+res+'"'
with open(env_file, 'w') as newFile: with open(env_file, 'w') as newFile:
newFile.write("export hosts="+final) newFile.write("export hosts="+final)
except: except:

18
Sistemas/customStorage.py Normal file
View File

@@ -0,0 +1,18 @@
from django.core.files.storage import FileSystemStorage
import os
class CustomStorage(FileSystemStorage):
def __init__(self, location):
self.location=location
super(CustomStorage,self).__init__(location=location, base_url=None)
def save(self, name, content):
if self.exists(name):
self.delete(name)
return super()._save(name,content)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
download_system_dir = os.path.join(BASE_DIR,'downloadSystems')
custom_stoarge = CustomStorage(location=download_system_dir)

View File

@@ -14,10 +14,11 @@ from .views import (
AuthenticateDeviceView, AuthenticateDeviceView,
LogoutView, LogoutView,
CheckVersionView, CheckVersionView,
UploadZipVersionView,
#function #function
download_version_FromServer, download_version_FromServer,
uploadZipViewHTML
) )
urlpatterns = [ urlpatterns = [
path('',SistemasXCliente_ListView.as_view(),name='lista_sistmas'), path('',SistemasXCliente_ListView.as_view(),name='lista_sistmas'),
@@ -28,4 +29,6 @@ urlpatterns = [
path('usuariosConectados/', UsersConnectedList.as_view(), name='lista_usuarios'), path('usuariosConectados/', UsersConnectedList.as_view(), name='lista_usuarios'),
path('checkVersion/', CheckVersionView.as_view(), name='checkVersion'), path('checkVersion/', CheckVersionView.as_view(), name='checkVersion'),
path('download_version_FromServer/',download_version_FromServer, name='downloadVersionFromServer'), path('download_version_FromServer/',download_version_FromServer, name='downloadVersionFromServer'),
path('uploadZip/', UploadZipVersionView.as_view(), name='uploadZip'),
path('uploadZip2/', uploadZipViewHTML, name="uploadZipViewHTML"),
] ]

View File

@@ -28,6 +28,49 @@ import os
import mimetypes import mimetypes
import traceback import traceback
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from .customStorage import CustomStorage
from django.contrib.auth.decorators import login_required
@login_required
def uploadZipViewHTML(request):
if request.method=="GET":
user = request.user
if user.is_superuser:
token= Token.objects.get(user=user)
else:
redirect('index')
context = {
'token':token.key,
}
template_name= 'Sistemas/manageSystem/uploadZip.html'
return render(request, template_name,context)
return HttpResponse('Only GET request are allowed')
class UploadZipVersionView(APIView):
"""API CLASS for upload the CFDI Version into the server"""
permissions_classes=[IsAuthenticated,]
#authentication_classes = (TokenAuthentication,) #this is by default in settings.py
def post(self,request,format=None):
try:
zip_file=request.FILES['zip_file']
except KeyError:
return Response({'error':'Zip file is required'},status=status.HTTP_400_BAD_REQUEST)
try:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
download_system_dir = os.path.join(BASE_DIR,'downloadSystems')
custom_storage = CustomStorage(location=download_system_dir)
print('path exist? ',os.path.exists(download_system_dir))
fileName = custom_storage.save(zip_file.name, ContentFile(zip_file.read()))
except Exception as ex:
BitacoraErrores.objects.create(level=2, message=str(ex), traceback=traceback.format_exc(), view='Sistemas.UploadZipVersionView')
return Response({'error':str(ex)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response({'message':'File uploaded successfully'}, status=status.HTTP_201_CREATED)
def download_version_FromServer(request): def download_version_FromServer(request):
try: try:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -38,8 +81,7 @@ def download_version_FromServer(request):
with open(filepath, 'rb') as path: with open(filepath, 'rb') as path:
mime_type, _ = mimetypes.guess_type(filepath) mime_type, _ = mimetypes.guess_type(filepath)
response = HttpResponse(path.read(),content_type=mime_type) response = HttpResponse(path.read(),content_type=mime_type)
response['Content-Disposition']= f'attachment; filename={filename}' response['Content-Disposition']= f'attachment; filename={filename}'
return response return response
except Exception as ex: except Exception as ex:
@@ -165,7 +207,7 @@ class CheckVersionView(APIView):
version = request.data.get('version') version = request.data.get('version')
client_version = [int(x) for x in version.split(".")] client_version = [int(x) for x in version.split(".")]
print('client_version: ',client_version) #print('client_version: ',client_version)
try: try:
ver = Sistema.objects.get(nombre_sistema="CFDI") ver = Sistema.objects.get(nombre_sistema="CFDI")
server_version = [int(x) for x in ver.version.split(".")] server_version = [int(x) for x in ver.version.split(".")]

View File

@@ -0,0 +1,51 @@
{% extends 'base.html' %}
{% block title %}
| Sistemas
{% endblock title %}
{% block content %}
<form id="upload-form">
<input type="file" name="zip_file">
<button type="submit">Upload</button>
</form>
<input type="hidden" id="id_token" name="token" value="{{ token }}">
{% endblock content %}
{% block scripts %}
<script>
document.getElementById('upload-form').addEventListener('submit', function (event) {
event.preventDefault();
let formData = new FormData(event.target);
let token = document.getElementById("id_token").value;
fetch(`{% url 'uploadZip' %}`, {
method: 'POST',
body: formData,
headers: {
'Authorization': 'Token ' + token,
},
})
.then(function (response) {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(function (data) {
console.log(data);
window.location.reload();
})
.catch(function (error) {
console.error(error);
});
});
</script>
{% endblock scripts %}

View File

@@ -69,7 +69,7 @@
<div class="dropdown-divider"></div> <div class="dropdown-divider"></div>
{% endif %} {% endif %}
<a class="dropdown-item" href="#">Something else here</a> <a class="dropdown-item" href="{% url 'uploadZipViewHTML' %}">Actualizar CFDI Version</a>
</div> </div>
</li> </li>
</div> </div>