django project does not write to file and there is no error, the file does not appear

I’m trying to write to a file and django doesn’t do it. There is no error of any kind but the file does not appear. Using the process monitor I don’t see any attempt to write. In a python file the same code works fine.

Test performed:

@method_decorator(login_required, name='dispatch')
class TestWrite(TemplateView):
    template_name = 'test.html'

    with open(r'd:\djangotest.txt', "w") as fo:
        fo.write('test')
        fo.close()

I did the test with Popen and it doesn’t work either.

p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = p.communicate()
returncode = p.returncode

In the case of Popen I used pg_dump.exe and in stderr I got the result of the program running correctly but no file anywhere.

It doesn’t matter which path you select to write, inside the project, outside of it, ect. the file does not appear.

I don’t know if it’s important, but I did the tests in pycharm.

Under what condition, or event, or situation are you expecting this to run?

You have the code defined at the class level and not within a method.

(Side note: The LoginRequiredMixin is the CBV-version of the login_required decorator.)

The real reason is the database save when a user touches the button in the browser but since the save file doesn’t appear even though pg_dump works fine I tried writing a file directly.
The code is in views.py. The code is executed when the button is clicked but the file does not appear anywhere. Using process monitor you don’t see any attempt to write to disk.

If that is your complete view, then no, that code will not execute in response to a browser submit.

Review the docs at:

Additionally, I’ve found that the Classy Class Based Views site is a great help in understanding how CBVs function.

I don’t understand why it says it doesn’t run.
If it runs, even with Popen I get the output of pg_dum exactly as if I ran it in cmd.
The Popen output is sent to the browser and it looks perfectly as it reads all the database tables.

Full code of the view.


class TestWrite(TemplateView):
    template_name = 'test.html'
    with open(r'd:/djangotest.txt', "w") as fo:
        fo.write('test')
        fo.close()
		
	from datetime import datetime
    import os
    from django.conf import settings as conf_settings
    basedatos = conf_settings.DATABASES['default']['NAME']
    usuario = conf_settings.DATABASES['default']['USER']
    clave = conf_settings.DATABASES['default']['PASSWORD']
    host = conf_settings.DATABASES['default']['HOST']
    port = conf_settings.DATABASES['default']['PORT']
    camino_salva = conf_settings.PATH_BACKUP
    camino_log = conf_settings.PATH_BACKUP_LOG
    camino_exe = conf_settings.PATH_EXEPOSTGRESQL
    
    archivo_salva = os.path.join(camino_salva, 'salva_' + str(datetime.now().strftime('%Y%m%d%H%M%S')) + '.fc')
    
    cmd = 'PGPASSWORD=' + clave
    if os.name == 'nt':
        cmd = 'SET ' + cmd + '&'

    cmd = cmd + camino_exe + ' -f "' + archivo_salva + '" -h ' + host + " -p " + port + " -U " + usuario + " -F c -Z 9 -v " + basedatos
    #cmd += " 2> " + camino_log
	
    import subprocess
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    stdout, stderr = p.communicate()
    returncode = p.returncode

    extra_context = {'stdout': stdout, 'stderr': stderr, 'cmd': cmd, 'returncode': returncode, 'archivo_salva': archivo_salva}

That is an invalid view. You do not just put code in a class. A CBV is a Python class, and everything that is implied by that. They have a definite structure and flow of execution.

You have attempted to write a CBV as if it were an FBV.

Have you worked your way through the Official Django Tutorial yet? If you haven’t, it’ll help clear up a lot of your questions.

You need to either review the Django tutorial with docs referenced above to learn how you create and use a CBV, or you need to convert this to an FBV.

I think you have not understood me. I’m not sure if the class is written according to django but I’m sure it runs.
When I press the button in the browser I get back the output of the pg_dump, I show the output in the template and it is exactly the same as the output of the same command in the cmd, the code is executed.
The problem is that the file that was sent to save is not written to disk. I don’t know if django has some type of protection that prevents files from being written to disk but I don’t see anything in the documentation about it.
The django tutorial doesn’t mention a word about writing a file to disk that isn’t sent from the browser, nor does it show an example of using Popen. Can you give me a little example about writing a file to disk?

Oh, it runs - but it’s running at the moment the class is imported, not as a result of a browser request.

Fix the more serious problem first (the invalid view), then we can address the lesser issue (not seeing the file). We’re going to need other, more detailed information before working on that.

Actually it is executed twice, when the class is compiled the file appears, when it is commanded to execute from the browser it is executed but the file does not appear.

What is making you think that it’s executing twice?

When I start the server the test file appears, the database save also appears.
When I execute it through the browser, the name of the save file has the date and time, the pg_dump is executed with that file name and I see its output in the browser as if I were seeing it in the cmd. I also show the command line to execute and it brings the updated date and time.

How are you running the server?

Through the green button of the pycharm.

Ok, that may be something special that PyCharm is doing. What you’re describing isn’t standard Python behavior - and isn’t going to happen in a deployment environment.

And I just re-confirmed my expectations. I cannot recreate the behavior you are describing using any of runserver, runserver_plus, or gunicorn.

I would suspect that PyCharm is doing something special with the class loader, but since I don’t have it or use it, I have no practical means to verify that.

Thanks, I’m trying to put it in a function.

Thanks, it worked after putting it in a function.