3from django.views.decorators.http import require_http_methods
4
5
6@require_http_methods(["GET", "POST"]) # Sensitive 7def current_datetime(request):
8 now = datetime.datetime.now()
9 html = "<html><body>It is %s.</body></html>" % now
An HTTP method is safe if it doesn't alter the state of the server i.e it leads to a read-only operation.
Common safe HTTP methods: GET
, HEAD
, and OPTIONS
.
Whereas, POST
, PUT
, and DELETE
are unsafe because they alter the server state.
The use of both safe and unsafe HTTP methods on a view makes the application vulnerable to Cross-Site Request Forgery (CSRF). CSRF protections are responsible for protecting operations performed by unsafe HTTP methods. They do not protect if safe HTTP methods used for a route that can change the state of an application.
It is recommended to use safe HTTP methods only when read-only operations need to be performed. Don't use safe and unsafe methods together.
For Django:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET", "POST"]) # Sensitive
def register(request):
...
For Flask:
import flask
from flask import Flask
app = Flask(__name__)
@app.route('/sensitive', methods=['GET', 'POST']) # Sensitive
def register():
...
For Django
from django.views.decorators.http import require_POST, require_GET
@require_POST
def register(request):
...
@require_GET
def post(request):
...
For Flask
import flask
from flask import Flask
app = Flask(__name__)
@app.route('/sensitive', methods=['POST']) # Sensitive
def register():
...
@app.route('/sensitive', methods=['GET']) # Sensitive
def hello_world():
return "Hello World"