Django 请求参数获取问题

1.获取URL路径中的参数

(1)未命名参数(位置参数)

# 在项目下的urls.py下增加设置:
url(r'^user/(\d+)/(\d+)$',views.index)

# 在user.views的index视图中:
def index(request,a,b):            # 接受的参数按顺序的
    return HttpResponse("获得数据 %s %s"%(a,b))
###(2)命名参数(关键字参数)
# 在项目下的urls.py下增加设置:
url(r'^user/(?P<category>\d+)/(?P<id>\d+)$',views.index)

# 在user.views的index视图中:
def index(request,id,category):            # 接受的参数可以不用按顺序的
    return HttpResponse("获得数据 %s %s"%(category,id))

2.获取查询字符串

需求:获取127.0.0.1:8000/user?id=1&pid=99的查询字符串的值

# 在项目下的urls.py下增加设置:
url(r'^user/$',views.index)

# 在user.views的index视图中:
def index(request):
    id = request.GET.get("id")
    pid = request.GET.get("pid")
    return HttpResponse("获得数据 %s %s"%(id,pid))

注意:查询字符串的获取与请求方式无关:不管是 GET 还是 POST请求, 都可以通过request.GET 属性来获取!!!

    username = request.GET.get("username")
    password = request.GET.get("password")
    # username = request.POST.get("username")
    # password = request.POST.get("password")

3.获取表单数据

def index(request):
    id = request.POST.get("id")
    pid = request.POST.get("pid")
    return HttpResponse("获得数据 %s %s"%(id,pid))

注意:request.POST 只能用来获取POST方式的请求体表单数据!

4.获取非表单类型

request.body属性:获取非表单类型的请求体数据,如:JSON、XML等,获取到的数据类型为bytes类型
获取数据后,自己解析数据取出参数

def index(request):
    json_str = request.body
    json_str = json_str.decode()  # python3.6及以上不用这一句代码
    dict_data = json.loads(json_str)  # loads把str转换为dict,dumps把dict转换为str
    id = dict_data.get("id")
    pid = dict_data.get("pid")
    return HttpResponse("获得数据 %s %s"%(id,pid))

5.获取请求头的内容

常见的请求头如下:

CONTENT_LENGTH – The length of the request body (as a string).
CONTENT_TYPE – The MIME type of the request body.
HTTP_ACCEPT – Acceptable content types for the response.
HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
HTTP_HOST – The HTTP Host header sent by the client.
HTTP_REFERER – The referring page, if any.
HTTP_USER_AGENT – The client’s user-agent string.
QUERY_STRING – The query string, as a single (unparsed) string.
REMOTE_ADDR – The IP address of the client.
REMOTE_HOST – The hostname of the client.
REMOTE_USER – The user authenticated by the Web server, if any.
REQUEST_METHOD – A string such as "GET" or "POST".
SERVER_NAME – The hostname of the server.
SERVER_PORT – The port of the server (as a string).

获取请求头内容的用META

def index(request):
    ip = request.META.get("REMOTE_ADDR")
    return HttpResponse("你的ip地址是%s"%ip)

6.获取自定义请求头的内容

用postman增加一个自定义的请求头,key=id,value=1。那么应该怎么取呢?

代码如下:

def index(request):
    id = request.META.get("HTTP_ID")
    return HttpResponse("你的id:%s"%id)

注意:获取自定义的请求头属性值时,需要添加前缀 HTTP_ 并转成大写,作为键来获取值

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容