当前位置: 移动技术网 > IT编程>脚本编程>Python > Django框架的使用教程路由请求响应的方法

Django框架的使用教程路由请求响应的方法

2019年06月16日  | 移动技术网IT编程  | 我要评论

帝星风月,株洲在线房产网,连云港采购

路由

路由可以定义在工程的目录下(看你的需求),也可以定义在各个应用中来保存应用的路由,用主路文件urls中使用include()包含各个应用的子路由的数据

路由的解析顺序

django接收到请求后,从主路由文件urlpatterns中的路由从上倒下顺序查找,如果有include包含,则进入子应用的urls中的urlpatterns中查找(从上而下)

路由的结尾斜线

django有/结尾路由,用户不需要加/,就可以直接重定向到/结尾的路径上

路由命名(可以避免不同应用使用相同名字发生冲突)

如:

# 主路由
from django.conf.urls import url,include
from django.contrib import admin
import django_test.urls

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^users/',include(django_test.urls ,namespace='users'))
]

reverser反解析(子应用的路由都需要命名)

注意点:

  1. 对于未指明namespace的,reverse(路由name)
  2. 对于指明namespace的,reverse(命名空间namespace:路由name)

请求(post,put,patch,delete)默认开启csrf防护

post请求那些需要到postman测试工具里面测试

先把csrf防护注释掉

向服务器传递参数的方式

url:直接在url中传递数据

查询字符串:key1=value1&key2=value2;

请求体:在body中传递数据,常见有表单,json,xml

请求头:在http报文头中

url参数传递

未定义参数顺序传递

子应用的路由设置

urlpatterns = [
  # 这边定义子应用的路由
  url(r'^index/$',views.index,name='index'),
  url(r'^show/$',views.show,name='show'),
  url(r'^parameter/([a-z]+)/(\d{4})$',views.parameter,name='parameter'),
]

定义视图函数

# name,和age参数位置调换会影响下面的输出结果
def parameter(request,name, age):

  print('age=%s'%age)
  print('name=%s' % name)
  return httpresponse('ok')

命名参数按照名字传递

子路由

urlpatterns = [
  # 这边定义子应用的路由
  url(r'^index/$',views.index,name='index'),
  url(r'^show/$',views.show,name='show'),
  url(r'^parameter/(?p<name>[a-z]+)/(?p<age>\d{4})$',views.parameter,name='parameter'),
]

视图函数

# age 和name位置改变值不变
def parameter(request,age, name):

  print('age=%s'%age)
  print('name=%s' % name)
  return httpresponse('ok')

查询字符串(传递参数)

注意:查询字符串不区分请求方式,即假使客户端进行post方式的请求,依然可以通过request.get获取请求中的查询字符串数据。

子路由

url(r'^qust/$',views.qust),

视图函数

def qust(request):
  a = request.get.get('a')
  b = request.get.get('b')
  alist = request.get.getlist('a')
  print(a) # 3
  print(b) # 2
  print(alist) # ['1', '3']
  return httpresponse('ok')

运行(后面在加)

请求体(传递参数)

表单类

路由设置

url(r'^get_form/$', views.get_form)

视图函数

def get_form(request):
  name = request.post.get('name')
  age = request.post.get('age')
  alist = request.post.getlist('name')
  print(name)
  print(age)
  print(alist)
  return httpresponse('ok')

运行

非表单类

路由

url(r'^get_body_json/$', views.get_body_json),

视图

def get_body_json(request):
  json_str = request.body
  json_str = json_str.decode() # python3.6 无需执行此步
  req_data = json.loads(json_str)
  print(req_data['a'])
  print(req_data['b'])
  return httpresponse('ok')

运行

请求头(传递参数)

可以通过request.meta属性获取请求头headers的数据

路由

url(r'^get_head/$', views.get_head)

视图函数

def get_head(request):
  print(request.meta['content_type'])
  return httpresponse('ok')

运行

常见的请求头

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).

响应

  1.  httpresponse提供一系列子类
  2. httpresponseredirect 301
  3. httpresponsepermanentredirect 302
  4. httpresponsenotmodified 304
  5. httpresponsebadrequest 400
  6. httpresponsenotfound 404
  7. httpresponseforbidden 403
  8. httpresponsenotallowed 405
  9. httpresponsegone 410
  10. httpresponseservererror 500

案例 # httpresponse(content=响应体,content_type=响应数据类型,status=状态码)

# content:表示返回的内容
# status_code:返回的http响应状态码
# content_type: 指定返回数据的mime类型
from django_http import httpresponse

def index(request):
  return httpresponse('欢迎来到gaidy博客', status=202)

jsonresponse(返回的json数据)

from django.http import jsonresponse

def index(request):
  return jsonresponse({'name': 'gaidy', 'age': '25'})

运行结果

redirect重定向

from django.shortcuts import redirect

# django_test是路由的空间命名
def show(request):
  # 重定向
  return redirect(reverse('django_test:index'))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网