Permission denied when trying to write to file from a view

后端 未结 1 1243
小蘑菇
小蘑菇 2021-01-03 00:29

I\'ve created a chat for this question: here

I have a view that attempts to execute f = open(\'textfile.txt\', \'w\') but on my live server this brings

相关标签:
1条回答
  • 2021-01-03 01:08

    Given the following:

    f = open('textfile.txt', 'w')
    

    It should be creating the file in same directory as __file__, the currently running script or views.py in your scenario.

    However, it's better to be explicit, and therefore rule out any potential deviations. I'd recommend changing that line to:

    import os
    f = open(os.path.join(os.path.dirname(__file__), 'textfile.txt'), 'w')
    

    Or even better, something like:

    import os
    from django.conf import settings
    f = open(os.path.join(settings.MEDIA_ROOT, 'textfile.txt'), 'w')
    

    Then, you're always assured exactly where the file is being saved, which should allow you to optimize your permissions more appropriately. Alternatively, you can use a PROJECT_ROOT.

    0 讨论(0)
提交回复
热议问题