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

作者:Gaidy 时间:2022-02-08 19:04:55 

路由

路由可以定义在工程的目录下(看你的需求),也可以定义在各个应用中来保存应用的路由,用主路文件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防护注释掉

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

向服务器传递参数的方式

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

运行(后面在加)

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

请求体(传递参数)

表单类

路由设置


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

运行

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

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

非表单类

路由


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

运行

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

请求头(传递参数)

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

路由


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

视图函数


def get_head(request):
 print(request.META['CONTENT_TYPE'])
 return HttpResponse('OK')

运行

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

常见的请求头

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'})

运行结果

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

redirect重定向


from django.shortcuts import redirect

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

来源:http://www.cnblogs.com/gaidy/p/9254788.html

标签:Django,路由,请求响应
0
投稿

猜你喜欢

  • django中的图片验证码功能

    2022-06-10 00:07:54
  • Django使用中间件解决前后端同源策略问题

    2022-09-05 10:33:32
  • Python中的套接字编程是什么?

    2021-02-28 12:46:01
  • 如何利用Python批量处理行、列和单元格详解

    2023-02-05 05:07:35
  • PHP安全的URL字符串base64编码和解码

    2023-09-06 22:04:45
  • python使用tkinter实现简单计算器

    2021-10-01 00:20:57
  • python GUI库图形界面开发之PyQt5状态栏控件QStatusBar详细使用方法实例

    2021-12-11 14:20:36
  • [译]“我心中的ebay”

    2008-06-04 12:09:00
  • numpy.insert()的具体使用方法

    2021-12-23 15:33:34
  • 编程活动中几个不良现象

    2008-09-01 12:23:00
  • opencv实现图像校正

    2023-12-26 02:07:49
  • python 字符串格式化的示例

    2021-01-23 23:33:06
  • 如何建设一个多语言版的ASP网站?

    2009-11-26 20:36:00
  • python3中替换python2中cmp函数的实现

    2021-08-15 01:42:41
  • asp查询ip地址源代码

    2009-07-27 17:51:00
  • 解决Python中定时任务线程无法自动退出的问题

    2022-09-05 22:52:52
  • 如何用python批量发送工资条邮件

    2021-03-07 10:53:09
  • python url 参数修改方法

    2023-09-12 19:02:24
  • python timestamp和datetime之间转换详解

    2021-02-07 11:17:51
  • 整理Python最基本的操作字典的方法

    2022-03-01 07:04:38
  • asp之家 网络编程 m.aspxhome.com