in flask request.get_data() I read the following quoted sentence and it kept me thinking:
Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
So my first question, should I check the content_length on every data entry, e.g. sign-in from ? or is it only for uploaded files?
here is my flask code for sign-in/sign-out page:
@app.route('/signing', methods=['GET', 'POST'])
def signing():
try:
if current_user.is_anonymous:
if request.method == 'POST':
print(request.content_length)
username = request.form['username']
password = request.form['password']
user = Authorization.query.filter_by(username=username).first()
login_user(user)
return redirect(url_for('home_redirect'))
else:
return render_template('pages/signing.html')
else:
logout_user()
return redirect(url_for('index'))
except:
abort(501)
the print(request.content_length) statement above return 33.
What does the number 33 represent ? Could you please convert it to kB, or Bytes to help me understand the significance of that number.
To prevent memory issues/ denial of service, checking the content-length header can give a representation of bytes of a POST body for an HTTP request. Not using a request with an absurd amount of data would be advised since a client could send a spoofed request with TONS of data that could be very tough for the server to handle. The content-length header is always represented in every valid HTTP request spoofed or from a browser, so it is excellent to utilize. Using that number as an integer and simply checking if it’s greater than a value that would be outlandish but possible such as a few hundred before parsing the response is important.
For more reading, I also suggest you look at Flask Limiter to rate limit your endpoints against clients and users with malicious intent to protect your server's speed and limited resources.