Skip to content

Commit

Permalink
Cast paths to strings (they may be Pathlib instances)
Browse files Browse the repository at this point in the history
Fixes #192 and replaces #193 and #195

Thanks @browniebroke for the original patches.
  • Loading branch information
evansd committed Sep 11, 2018
1 parent 26cf851 commit 6042b80
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
9 changes: 9 additions & 0 deletions tests/test_whitenoise.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import os
import tempfile
import unittest
from unittest import TestCase
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import shutil
import sys
import warnings
from wsgiref.simple_server import demo_app

Expand Down Expand Up @@ -255,3 +257,10 @@ def test_immutable_file_test_accepts_regex(self):
instance = WhiteNoise(None, immutable_file_test=r'\.test$')
self.assertTrue(instance.immutable_file_test('', '/myfile.test'))
self.assertFalse(instance.immutable_file_test('', 'file.test.txt'))

@unittest.skipIf(sys.version_info < (3, 4), "Pathlib was added in Python 3.4")
def test_directory_path_can_be_pathlib_instance(self):
from pathlib import Path
root = Path(Files('root').directory)
# Check we can construct instance without it blowing up
WhiteNoise(None, root=root, autorefresh=True)
2 changes: 1 addition & 1 deletion whitenoise/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def serve(static_file, environ, start_response):
return []

def add_files(self, root, prefix=None):
root = decode_if_byte_string(root)
root = decode_if_byte_string(root, force_text=True)
root = root.rstrip(os.path.sep) + os.path.sep
prefix = decode_if_byte_string(prefix)
prefix = ensure_leading_trailing_slash(prefix)
Expand Down
6 changes: 5 additions & 1 deletion whitenoise/string_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@

if sys.version_info[0] >= 3:
BINARY_TYPE = bytes
TEXT_TYPE = str
else:
BINARY_TYPE = str
TEXT_TYPE = unicode


def decode_if_byte_string(s):
def decode_if_byte_string(s, force_text=False):
if isinstance(s, BINARY_TYPE):
s = s.decode('utf-8')
if force_text and not isinstance(s, TEXT_TYPE):
s = TEXT_TYPE(s)
return s


Expand Down

0 comments on commit 6042b80

Please sign in to comment.