URL Parse
Components of an URI
Django Request
Uri
request.build_absolute_uri()
Origin
Method One
origin = '{scheme}://{host}'.format( scheme='https' if request.is_secure() else 'http', host=request.get_host() )
Method Two
parts = urlparse(request.build_absolute_uri()) parts = parts._replace(path='', params='', query='', fragment='') # origin = urlunparse(parts) origin = parts.geturl()
Method Three, Wrapper As A Middleware
class UrlParseMiddleware(object): def process_request(self, request): parts = urlparse(request.build_absolute_uri()) parts = parts._replace(path='', params='', query='', fragment='') request.origin = parts.geturl() return None
Protocol/Scheme
Method One
protocol = 'https' if request.is_secure() else 'http'
Method Two
request.scheme
- New In Django 1.7
- Request and response objects —— django.http.HttpRequest.scheme
Host
request.get_host()
Port
request.get_port()
- New In Django 1.9
- Request and response objects —— django.http.HttpRequest.get_port
Path
request.get_full_path()
django-uri
Installation
pip install django-uri
Settings.py
MIDDLEWARE_CLASSES = ( ... 'uri.middleware.URIMiddleware', ... )
Usage
request.uri.origin request.uri.scheme
References
[1] django-xxx@Github, django-uri — Django URI
[2] Wikipedia, Uniform Resource Identifier