3👍
os.sep
gives you the separator for your current system’s file system paths. Your system paths and URI paths aren’t the same.
RFC 3986 gives:
A path consists of a sequence of path segments separated by a slash
("/") character.
If you have an URI like http://foo.bar.baz/a/b/c/d
, you should use urlsplit
to split it into components and extract the path
part. Then you can safely use .split('/')
to get the individual parts of this path, or use '/'.join
to construct a path from the segments (if you know that each segment is a valid segment according to the grammar).
The grammar doesn’t permit this /
to be anything other than a separator in the path segment, check the RFC to be doubly sure. This doesn’t hold for the whole URL though, /
will mean different things in other URL sections.
The opposite of urlsplit
is urlunsplit
which can do what you want once you have the path assembled.
To be safe, you should percent-encode the individual path parts before joining them with /
using urllib.quote('/test', '')
(mind the second parameter – /
isn’t escaped here by default.)
4👍
os.sep will return \
on Windows – whether that’s what you want depends on the protocol you’re using I think, but broadly speaking using I think os.sep isn’t appropriate for URLs that aren’t using file://
(and even then it’s questionable).
You might find urlparse
useful: https://docs.python.org/2/library/urlparse.html
- [Django]-Django Rest Framework view returns an empty object
- [Django]-How painful is a django project deployment to a live (staging) site?
- [Django]-Using prefetch_related to get only a particular entry of a relation
- [Django]-Mod_wsgi (3.4-14) / Apache 2.4.12 / Red Hat (6.7) / Django 1.8.2 hanging under load
3👍
From documentation:
The character used by the operating system to separate pathname
components. This is ‘/’ for POSIX and ‘\’ for Windows. Note that
knowing this is not sufficient to be able to parse or concatenate
pathnames — use os.path.split() and os.path.join() — but it is
occasionally useful. Also available via os.path.
So No, it is note safe to use.
For URI parsing, splitting, joining, etc, you should use the urllib.parse library. (called urlparse in python 2)
- [Django]-Increasing number of initial forms in a Django formset based on data in POST?
- [Django]-Logging Django Haystack search keyword
- [Django]-ForeignKey to 'self' in sub-application throws error on makemigrations in Django project
- [Django]-Why is the difference between Serializer methods and View methods?
- [Django]-Django migration OperationalError: index [name] already exists