简体   繁体   English

如何在 django 中获取请求主机?

[英]How to get request host in django?

How to get request host in django?如何在 django 中获取请求主机? how will I get host URL/name from request我将如何从请求中获取主机 URL/名称

class StoreLocations(APIView):
    """
    GET     :  For fetching store locations
    Returns :  Store Locations
    ---------------
    json  
    """
    permission_classes = []
    http_method_names = ["get"]

    def get(self, request, format=None):
            """
            Want to check from where request is coming from and allow requests coming from specific urls only
            """

You can use the below code snippet to see which host is used.您可以使用下面的代码片段来查看使用了哪个主机。

print(request.environ.get("HTTP_ORIGIN"))

To see the additional details present in request.查看请求中的其他详细信息。

print(request.__dict__)

django request have META dictionary: https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.HttpRequest.META django 请求有 META 字典: https://docs.djangoproject.com/en/4.0/ref/request-response/#django.Z80791B3AE7002CB88C246876D9FAA8FAZ。

I think you search for:我想你搜索:

request.META['REMOTE_ADDR'] # e.g. '1.1.1.1'
request.META['REMOTE_HOST'] # e.g. '1.1.1.1'
request.META['HTTP_REFERER'] # this show url from where was made request

Use HttpRequest.get_host(...)使用HttpRequest.get_host(...)

class StoreLocations(APIView):
    def get(self, request, *args, **kwargs):
        host = request.get_host()
print(request.META.get("HTTP_ORIGIN"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM