Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_os.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os
  2. import tempfile
  3. from os.path import abspath, dirname, join, normcase, sep
  4. from django.core.exceptions import SuspiciousFileOperation
  5. from django.utils.encoding import force_text
  6. # For backwards-compatibility in Django 2.0
  7. abspathu = abspath
  8. def upath(path):
  9. """Always return a unicode path (did something for Python 2)."""
  10. return path
  11. def npath(path):
  12. """
  13. Always return a native path, that is unicode on Python 3 and bytestring on
  14. Python 2. Noop for Python 3.
  15. """
  16. return path
  17. def safe_join(base, *paths):
  18. """
  19. Join one or more path components to the base path component intelligently.
  20. Return a normalized, absolute version of the final path.
  21. Raise ValueError if the final path isn't located inside of the base path
  22. component.
  23. """
  24. base = force_text(base)
  25. paths = [force_text(p) for p in paths]
  26. final_path = abspath(join(base, *paths))
  27. base_path = abspath(base)
  28. # Ensure final_path starts with base_path (using normcase to ensure we
  29. # don't false-negative on case insensitive operating systems like Windows),
  30. # further, one of the following conditions must be true:
  31. # a) The next character is the path separator (to prevent conditions like
  32. # safe_join("/dir", "/../d"))
  33. # b) The final path must be the same as the base path.
  34. # c) The base path must be the most root path (meaning either "/" or "C:\\")
  35. if (not normcase(final_path).startswith(normcase(base_path + sep)) and
  36. normcase(final_path) != normcase(base_path) and
  37. dirname(normcase(base_path)) != normcase(base_path)):
  38. raise SuspiciousFileOperation(
  39. 'The joined path ({}) is located outside of the base path '
  40. 'component ({})'.format(final_path, base_path))
  41. return final_path
  42. def symlinks_supported():
  43. """
  44. Return whether or not creating symlinks are supported in the host platform
  45. and/or if they are allowed to be created (e.g. on Windows it requires admin
  46. permissions).
  47. """
  48. with tempfile.TemporaryDirectory() as temp_dir:
  49. original_path = os.path.join(temp_dir, 'original')
  50. symlink_path = os.path.join(temp_dir, 'symlink')
  51. os.makedirs(original_path)
  52. try:
  53. os.symlink(original_path, symlink_path)
  54. supported = True
  55. except (OSError, NotImplementedError):
  56. supported = False
  57. return supported