Django中的Request和Response

接触Django这么久了,从来没有好好学习关于Django中的Request和Response对象。借着文件上传下载的相关工作,现在总结一下也不错。
当一个页面请求过来,Django会自动创建一个Request对象,匹配URLconf中对应的view方法,并将这个Request对象作为第一个参数传递给view方法。而view方法会经过一系列操作之后,返回一个Response对象,返回给客户端。
具体的Request对象的属性(attribute)有很多(除了seesion都说只读属性):

  1. HttpRequest.path—不包括域的全路径,例如:”/music/bands/the_beatles/”
  2. HttpRequest.method—请求方法,常用的有GET和POST
  3. HttpRequest.encoding—请求的编码格式,很有用!
  4. HttpRequest.GET(POST)---见HttpRequest.method
  5. HttpRequest.REQUEST---类字典的对象,搜索顺序先POST再GET
  6. HttpRequest.COOKIES---标准的python字典对象,键和值都是字符串。
  7. HttpRequest.FILES---类字典对象。键是表单提交的name---<input type="file" name="" />而file是一个上传的对象,它的属性有:read,name,size,chunks
  8. HttpRequest.META---包括标准HTTP头的python字典。如下:
    • CONTENT_LENGTH
    • CONTENT_TYPE
    • HTTP_ACCEPT_ENCODING
    • HTTP_ACCEPT_LANGUAGE
    • 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.
  9. HttpRequest.user---当前登录的用户
  10. HttpRequest.session---一个可读写的类python字典
  11. HttpRequest.raw_post_data---在高级应用中应用,可以算是POST的一个替代,但是不建议使用。
  12. HttpRequest.urlconf---默认情况下,是没有定义的

每个Request对象还有一些很有用的方法:

  1. HttpRequest.get_host()—返回域名,例如:”127.0.0.1:8000″
  2. HttpRequest.get_full_path()—返回请求的全路径(但是不包括域名),例如:”/music/bands/the_beatles/?print=true”
  3. HttpRequest.build_absolute_uri(location)—以上2者的结合
  4. HttpRequest.is_secure()—判断是否为https连接(没有用过)
  5. HttpRequest.is_ajax()—请求为XMLHttpRequest时,返回True

下面看看HttpResponse的属性(attribute):

  1. HttpResponse.content—python string对象,尽量用unicode。
  2. HttpResponse.status_codeHTTP Status code

HttpResponse的方法:

  1. HttpResponse.has_header(header)
  2. HttpResponse.set_cookie
  3. HttpResponse.delete_cookie
  4. HttpResponse.write(content)
  5. HttpResponse.flush()
  6. HttpResponse.tell()

以上说明以后陆续修正吧。
下面一部分是我学习到的东西:告诉浏览器你要下载文件(TELLING THE BROWSER TO TREAT THE RESPONSE AS A FILE ATTACHMENT)!

>>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
>>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
FROM:http://py-bow.appspot.com/?p=20001

原文地址:https://www.cnblogs.com/sundahua/p/7482686.html