zoukankan      html  css  js  c++  java
  • 限制请求method及页面重定向

    限制请求method

    GET请求:向服务器索取数据,不会向服务器提交数据,对服务器状态不会造成更改。

    POST请求:向服务器提交数据,会对服务器的状态造成更改,比如向服务器提交一篇文章。(如method=‘submit’)

    django内置请求装饰器:

    1.django.http.decorators.http.require_http_methods:这个装饰器需要传递一个允许访问的方法列表(GET或者POST请求都可以,在@require_http_methods([])的中括号里写指定请求方法)

     from django.views.decorators.http import require_http_methods
    
     @require_http_methods(["POST"])#在下个函数中使用post请求
    def index(request):
        pass

    2.django.views.decorators.http.require_GET:只能使用GET请求

     from django.views.decorators.http import require_GET
    
     @require_GET  #在下个视图函数中使用GET请求
     def my_view(request):
         pass

    3.django.views.decotators.http.require_POST:只能使用POST请求

     from django.views.decorators.http import require_POST
    
     @require_POST
     def index(request):
         pass

    4.django.views.decorators.http.require_safe:只能使用相对安全的方式来访问[GET和HEAD请求]因为只有这两种请求不会对服务起产生增删改的行为。

    from django.views.decorators.http import require_safe
    
     @require_safe
     def index(request):
         pass

    页面重定向

    重定向分为永久重定向和暂时性重定向

    • 永久性重定向:http状态码为301  即网址的转换,如京东网站:输入www.jingdong.com你会发现上面的网址会自动转换为www.JD.com当访问的还是同一个网站。
    • 暂时性重定向:http状态码为302 即页面的暂时跳转,如知乎网  进入后会先跳转到登录页面,登录后才能继续访问首页。(跳转的过程就是暂时重定向)
    from django.shortcuts import render,redirect,reverse
    from django.http import HttpResponse
    def index(request):
        #如果没有登陆,就重定向到注册页面
        #如果再url中,传递了username这个参数,那么就认为是登陆了,否则就没有登陆
        #传参的方式:  /?username=xxx
        username = request.GET.get('username')
        if username:
            return HttpResponse('首页')
        else:
            return redirect(reverse('signup'))
    def signup(request):
        return HttpResponse('首页')

    注:在重定向的时候直接给出另一个页面的模板,不是直接跳转。

  • 相关阅读:
    一个好的时间函数
    Codeforces 785E. Anton and Permutation
    Codeforces 785 D. Anton and School
    Codeforces 510 E. Fox And Dinner
    Codeforces 242 E. XOR on Segment
    Codeforces 629 E. Famil Door and Roads
    Codeforces 600E. Lomsat gelral(Dsu on tree学习)
    Codeforces 438D The Child and Sequence
    Codeforces 729E Subordinates
    【ATcoder】D
  • 原文地址:https://www.cnblogs.com/nihao2/p/12256801.html
Copyright © 2011-2022 走看看