Ошибка 304 flask

I’m building a web app. All the external links worked in my Project directory worked fine before but I noticed that yesterday every time I modify the .css file it didn’t render this change at all. It actually is freezed with the same style regardless if I even erase the whole .css file content.

This is the response that I’m getting when I run flask:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 230-950-485
127.0.0.1 - - [09/Mar/2017 17:53:09] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [09/Mar/2017 17:53:10] "GET /static/css/main.css HTTP/1.1" 200 -
127.0.0.1 - - [09/Mar/2017 17:53:10] "GET /static/js/main.js HTTP/1.1" 200 -
127.0.0.1 - - [09/Mar/2017 17:53:10] "GET /static/css/main.css HTTP/1.1" 304 -
127.0.0.1 - - [09/Mar/2017 17:53:14] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [09/Mar/2017 17:54:04] "GET / HTTP/1.1" 200 -

Notice the 304, seems like that might be the problem? I appreciate any advice in what steps to take.

asked Mar 9, 2017 at 23:05

tadm123's user avatar

1

In Flask this is very common, whether you use Internal or external files:

HTTP Response

304 NOT MODIFIED

A conditional GET or HEAD request has been received and would have resulted in a 200 OK response if it were not for the fact that the condition evaluated to false.

In other words, there is no need for the server to transfer a representation of the target resource because the request indicates that the client, which made the request conditional, already has a valid representation; the server is therefore redirecting the client to make use of that stored representation as if it were the payload of a 200 OK response.

This means Flask is telling the browser that it already has the content.

If you clear your browser cache and you will notice that Flask returns a 200 on your next request.

Community's user avatar

answered Jan 11, 2018 at 10:24

Mahendra S. Chouhan's user avatar

Disabling cash solutions for this issue is not working for me.
If it doesn’t update the file because it already represented, it means if i have new code in my file, i will never be able to push these modifications

answered Nov 8, 2020 at 9:51

SystemX's user avatar

SystemXSystemX

4814 silver badges10 bronze badges

1

304 means you have compiled that file before and there are no modifications to the file. You can clear them by deleting cache file on pycache folder

answered Apr 8 at 2:20

Herahadi An's user avatar

Skip to content

I’m new to python and I faced an error which I totally don’t understand why occures.
In the Insomnia client REST API I’m creating item with POST method, and it works well, below it the code

@app.post('/item')
def create_item():
    item_data = request.get_json()
    if (
        "price" not in item_data
        or "store_id" not in item_data
        or "name" not in item_data
    ):
        abort(
            400,
            message="Bad request"
        )

    for item in items.values():
        if (
            item_data["name"] == item["name"]
            and item_data["store_id"] == item["store_id"]
        ):
            abort(400, message="Item already exist")
    if item_data["store_id"] not in stores:
        abort(404, message="Store not found")

    if item_data["store_id"] not in stores:
        abort(404, message="Store not found")

    item_id = uuid.uuid4().hex
    item = {**item_data, "id": item_id}
    items["item_id"] = item

    return item, 201

and here is the outcome of post method, created item with «id»
{
«id»: «1c0deba2c86542e3bde3bcdb5da8adf8»,
«name»: «chair»,
«price»: 17,
«store_id»: «e0de0e2641d0479c9801a32444861e06»
}

when I run GET method using «id» from above item putting it to the link I get error code 304

@app.get("/item/<string:item_id>")
def get_item(item_id):
    try:
        return items[item_id]
    except KeyError:
        abort(404, message="Item not found")

enter image description here

Can You please suggest what is wrong here ?

thanks

>Solution :

@app.route('/item/<string:id>')
def get_item(id):
    instance = YourMOdel.query.filter_by(id=id).first()
    if instance:
        return render_template('data.html', instance = instance)
    return f"Employee with id ={id} Doenst exist"

Flask API includes a set of named constants that you can use to make more code more obvious and readable.

from flask_api import status

...

@app.route('/empty-view/')
def empty_view(self):
    content = {'please move along': 'nothing to see here'}
    return content, status.HTTP_404_NOT_FOUND

The full set of HTTP status codes included in the status module is listed below.

The module also includes a set of helper functions for testing if a status code is in a given range.

from flask_api import status
import unittest

...

class ExampleTestCase(unittest.TestCase):
    def test_success(self):
        with app.test_client() as client:
            response = client.get('/')
            self.assertTrue(status.is_success(response.status_code))

For more information on proper usage of HTTP status codes see RFC 2616
and RFC 6585.

Informational — 1xx

This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.

HTTP_100_CONTINUE
HTTP_101_SWITCHING_PROTOCOLS

Successful — 2xx

This class of status code indicates that the client’s request was successfully received, understood, and accepted.

HTTP_200_OK
HTTP_201_CREATED
HTTP_202_ACCEPTED
HTTP_203_NON_AUTHORITATIVE_INFORMATION
HTTP_204_NO_CONTENT
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT

Redirection — 3xx

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.

HTTP_300_MULTIPLE_CHOICES
HTTP_301_MOVED_PERMANENTLY
HTTP_302_FOUND
HTTP_303_SEE_OTHER
HTTP_304_NOT_MODIFIED
HTTP_305_USE_PROXY
HTTP_306_RESERVED
HTTP_307_TEMPORARY_REDIRECT

Client Error — 4xx

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

HTTP_400_BAD_REQUEST
HTTP_401_UNAUTHORIZED
HTTP_402_PAYMENT_REQUIRED
HTTP_403_FORBIDDEN
HTTP_404_NOT_FOUND
HTTP_405_METHOD_NOT_ALLOWED
HTTP_406_NOT_ACCEPTABLE
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
HTTP_408_REQUEST_TIMEOUT
HTTP_409_CONFLICT
HTTP_410_GONE
HTTP_411_LENGTH_REQUIRED
HTTP_412_PRECONDITION_FAILED
HTTP_413_REQUEST_ENTITY_TOO_LARGE
HTTP_414_REQUEST_URI_TOO_LONG
HTTP_415_UNSUPPORTED_MEDIA_TYPE
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
HTTP_417_EXPECTATION_FAILED
HTTP_428_PRECONDITION_REQUIRED
HTTP_429_TOO_MANY_REQUESTS
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE

Server Error — 5xx

Response status codes beginning with the digit «5» indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.

HTTP_500_INTERNAL_SERVER_ERROR
HTTP_501_NOT_IMPLEMENTED
HTTP_502_BAD_GATEWAY
HTTP_503_SERVICE_UNAVAILABLE
HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED

Helper functions

The following helper functions are available for identifying the category of the response code.

is_informational()  # 1xx
is_success()        # 2xx
is_redirect()       # 3xx
is_client_error()   # 4xx
is_server_error()   # 5xx

Flask – Redirects and Errors explained – why are they important?

In this tutorial, we are going to learn about redirects and errors in flask. We are also going to learn about the importance of these in our webpage and how to implement them on our webpage.

  • Introduction and overview of Flask Framework and how to install it?

In flask, the redirect() function has many functions. It is used to redirect the user to a specified location with a specified code by returning a response object.

The code prototype is as follows –

Flask.redirect(location, statuscode, response)

Parameters in the above function are –

  • location parameter decides where the URL will take the user to.
  • statuscode defaults to 302, when sent to the browser’s header.
  • response parameter is used to instantiate a response.

Following is a list of standardized statuscodes –

  • HTTP_300_MULTIPLE_CHOICES
  • HTTP_301_MOVED_PERMANENTLY
  • HTTP_302_FOUND
  • HTTP_303_SEE_OTHER
  • HTTP_304_NOT_MODIFIED
  • HTTP_305_USE_PROXY
  • HTTP_306_RESERVED
  • HTTP_307_TEMPORARY_REDIRECT

In the following example, the redirect() function is used to display the login page again and again, when the login attempt fails.

from flask import Flask, redirect, url_for, render_template, request
# Initialize the Flask application
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST' and
   request.form['username'] == 'admin' :
   return redirect(url_for('success'))
   return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'
  
if __name__ == '__main__':
   app.run(debug = True)

Flask – Errors

For displaying error pages, Flask class has an abort() function.

The code prototype is as follows –

Flask.abort(code)

The following values are accepted by the code parameter –

  • 400: for Bad Request
  • 401: for Unauthenticated
  • 403: for Forbidden
  • 404: for Not Found
  • 406: for Not Acceptable
  • 415: for Unsupported Media Type
  • 429: Too Many Requests

Now to understand the abort() function and how error pages work in flask, let us make slight changes to our above code. So, now the login() function instead of again displaying the login form, it will now display an ‘unauthenticated‘ page.

from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      if request.form['username'] == 'admin' :
         return redirect(url_for('success'))
      else:
         abort(401)
   else:
      return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'

if __name__ == '__main__':
   app.run(debug = True)

I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything described here, please feel free to comment them down below.

Also read:

  • Message flashing in Flask explained and why are they important?

Repro

  1. Create minimal hello world application as in http://flask.pocoo.org/
  2. Also create file /static/my_style.css with arbitrary content
  3. Run the application: FLASK_APP=hello.py flask run
  4. Visit http://localhost:5000/static/my_style.css
  5. Refresh the page to trigger «not modified» response

Expected behavior

Only request log to appear in stderr:

127.0.0.1 - - [31/Dec/2017 22:24:38] "GET /static/my_style.css HTTP/1.1" 200 -
127.0.0.1 - - [31/Dec/2017 22:24:38] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [31/Dec/2017 22:24:43] "GET /static/my_style.css HTTP/1.1" 304 -

Actual behavior

The following also appears in stderr:

Error on request:
Traceback (most recent call last):
  File "c:\python36\lib\site-packages\werkzeug\serving.py", line 270, in run_wsgi
    execute(self.server.app)
  File "c:\python36\lib\site-packages\werkzeug\serving.py", line 263, in execute
    write(b'')
  File "c:\python36\lib\site-packages\werkzeug\serving.py", line 232, in write
    status < 200 or status in (204, 304)):
TypeError: '<' not supported between instances of 'str' and 'int'

When this happens, status is '304 NOT MODIFIED'.

I think this defect became visible after 0c5cad57.

Environment

  • Python version: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
  • Flask version: 0.12.2
  • Werkzeug version: 0.14

Понравилась статья? Поделить с друзьями:
  • Ошибка 304 css
  • Ошибка 3025 сбер мегамаркет
  • Ошибка 3036 windows 7
  • Ошибка 3035 фейсит
  • Ошибка 303 zoom