Http error 500 python

I am using an API, which receives a pdf file and does some analysis, but I am receiving Response 500 always Have initially tested using Postman and the request goes through, receiving response 200...

I am using an API, which receives a pdf file and does some analysis, but I am receiving Response 500 always

Have initially tested using Postman and the request goes through, receiving response 200 with the corresponding JSON information. The SSL security should be turned off.

However, when I try to do request via Python, I always get Response 500

Python code written by me:

import requests

url = "https://{{BASE_URL}}/api/v1/documents"
fin = open('/home/train/aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf', 'rb')
files = {'file': fin}
r = requests.post(url, files=files, verify=False)
print (r)
#r.text is empty

Python code, produced by the Postman:

import requests

url = "https://{{BASE_URL}}/api/v1/documents"

payload = "------WebKitFormBoundary7MA4YWxkTrZu0gWrnContent-Disposition: form-data; name="file"; filename="aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf"rnContent-Type: application/pdfrnrnrn------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
    'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    'Content-Type': "application/x-www-form-urlencoded",
    'cache-control': "no-cache",
    'Postman-Token': "65f888e2-c1e6-4108-ad76-f698aaf2b542"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

Have masked the API link as {{BASE_URL}} due to the confidentiality

Response by Postman:

{
    "id": "5e69058e2690d5b0e519cf4006dfdbfeeb5261b935094a2173b2e79a58e80ab5",
    "name": "aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf",
    "fileIds": {
        "original": "5e69058e2690d5b0e519cf4006dfdbfeeb5261b935094a2173b2e79a58e80ab5.pdf"
    },
    "creationDate": "2019-06-20T09:41:59.5930472+00:00"
}

Response by Python:

Response<500>

UPDATE:

Tried the GET request — works fine, as I receive the JSON response from it. I guess the problem is in posting pdf file. Is there any other options on how to post a file to an API?

Postman Response RAW:

POST /api/v1/documents
Content-Type: multipart/form-data; boundary=--------------------------375732980407830821611925
cache-control: no-cache
Postman-Token: 3e63d5a1-12cf-4f6b-8f16-3d41534549b9
User-Agent: PostmanRuntime/7.6.0
Accept: */*
Host: {{BASE_URL}}
cookie: c2b8faabe4d7f930c0f28c73aa7cafa9=736a1712f7a3dab03dd48a80403dd4ea
accept-encoding: gzip, deflate
content-length: 3123756

file=[object Object]

HTTP/1.1 200
status: 200
Date: Thu, 20 Jun 2019 10:59:55 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Location: /api/v1/files/95463e88527ecdc94393fde685ab1d05fa0ee0b924942f445b14b75e983c927e
api-supported-versions: 1.0
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Referrer-Policy: strict-origin

{"id":"95463e88527ecdc94393fde685ab1d05fa0ee0b924942f445b14b75e983c927e","name":"aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf","fileIds":{"original":"95463e88527ecdc94393fde685ab1d05fa0ee0b924942f445b14b75e983c927e.pdf"},"creationDate":"2019-06-20T10:59:55.7038573+00:00"}

CORRECT REQUEST

So, eventually — the correct code is the following:

import requests

files = {
    'file': open('/home/train/aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf', 'rb'),
}
response = requests.post('{{BASE_URL}}/api/v1/documents', files=files, verify=False)
print (response.text)

Содержание

  1. How to fix error in python requests?
  2. 1 Answer 1
  3. python requests http response 500 (site can be reached in browser)
  4. 3 Answers 3
  5. But Wait! There’s More!
  6. Jupyter Notebook 500 : Internal Server Error
  7. 33 Answers 33
  8. Catching a 500 server error in Flask
  9. 6 Answers 6
  10. Linked
  11. Related
  12. Hot Network Questions
  13. Subscribe to RSS
  14. HOWTO Fetch Internet Resources Using The urllib PackageВ¶
  15. IntroductionВ¶
  16. Fetching URLsВ¶
  17. DataВ¶
  18. HeadersВ¶
  19. Handling ExceptionsВ¶
  20. URLErrorВ¶
  21. HTTPErrorВ¶
  22. Error CodesВ¶
  23. Wrapping it UpВ¶
  24. Number 1В¶
  25. Number 2В¶
  26. info and geturlВ¶
  27. Openers and HandlersВ¶
  28. Basic AuthenticationВ¶
  29. ProxiesВ¶
  30. Sockets and LayersВ¶
  31. FootnotesВ¶

How to fix error in python requests?

I am using an API, which receives a pdf file and does some analysis, but I am receiving Response 500 always

Have initially tested using Postman and the request goes through, receiving response 200 with the corresponding JSON information. The SSL security should be turned off.

However, when I try to do request via Python, I always get Response 500

Python code written by me:

Python code, produced by the Postman:

Have masked the API link as <> due to the confidentiality

Response by Postman:

Response by Python:

UPDATE:

Tried the GET request — works fine, as I receive the JSON response from it. I guess the problem is in posting pdf file. Is there any other options on how to post a file to an API?

Postman Response RAW:

CORRECT REQUEST

So, eventually — the correct code is the following:

1 Answer 1

A 500 error indicates an internal server error, not an error with your script.

If you’re receiving a 500 error (as opposed to a 400 error, which indicates a bad request), then theoretically your script is fine and it’s the server-side code that needs to be adjusted.

In practice, it could still be due a bad request though.

If you’re the one running the API, then you can check the error logs and debug the code line-by-line to figure out why the server is throwing an error.

In this case though, it sounds like it’s a third-party API, correct? If so, I recommend looking through their documentation to find a working example or contacting them if you think it’s an issue on their end (which is unlikely but possible).

Источник

python requests http response 500 (site can be reached in browser)

I am trying to figure out what I’m doing wrong here, but I keep getting lost.

In python 2.7, I’m running following code:

If I open this one in browser, it responds properly. I was digging around and found similar one with urllib library (500 error with urllib.request.urlopen), however I am not able to adapt it, even more I would like to use requests here.

I might be hitting here some missing proxy setting, as suggested for example here (Perl File::Fetch Failed HTTP response: 500 Internal Server Error), but can someone explain me, what is the proper workaround with this one?

3 Answers 3

One thing that is different with the browser request is the User-Agent; however you can alter it using requests like this:

Some web applications will also check the Origin and/or the Referer headers (for example for AJAX requests); you can set these in a similar fashion to User-Agent .

Remember, you are setting these headers to basically bypass checks so please be a good netizen and don’t abuse people’s resources.

The User-Agent, and also other header elements, could be causing your problem.

When I came accross this error I watched a regular request made by a browser using Wireshark, and it turned out there were things other than just the User-Agent in the header which the server expected to be there.

After emulating the header sent by the browser in python requests, the server stopped throwing errors.

But Wait! There’s More!

The above answers did help me on the path to resolution, but I had to find still more things to add to my headers so that certain sites would let me in using python requests. Learning how to use Wireshark (suggested above) was a good new skill for me, but I found an easier way.

If you go to your developer view (right-click then click Inspect in Chrome), then go to the Network tab, and then select one of the Names at left and then look under Headers for Requests Headers and expand, you’ll get a complete list of what your system is sending to the server. I started adding elements that I thought were most likely needed one at a time and testing until my errors went away. Then I reduced that set to the smallest possible set that worked. In my case, with my headers having only User-Agent to deal with other code issues, I only needed to add the Accept-Language key to deal with a few other sites. See picture below as a guide to the text above.

I hope this process helps others to find ways to eliminate undesirable python requests return codes where possible.

Источник

Jupyter Notebook 500 : Internal Server Error

I want to learn how to use Jupyter Notebook. So far, I have managed to download and install it (using pip), but I’m having trouble opening it.

I am opening it by typing:

in my terminal. It opens in my browser, with the URL:

and I just get a big:

message. Could someone point me in the right direction of what’s going wrong please?

The full error message in my terminal:

When attempting to update ipython as advised, the following error message was produced:

33 Answers 33

Try upgrading jupyter hub first:

If you are inside a conda environment, run the following command instead.

After trying all the solutions on this page without success, a variation of @kruger answer is what worked for me, simply this:

pip install —upgrade nbconvert

Was having a similar problem. Fixed it after upgrading ipython with this command

sudo pip install —upgrade «ipython[all]»

Note: make sure to type ipython with double quotes and [all]

I solved this by upgrading the nbconvert package

I had the same problem and was a bit painful until I managed to fix it. The magic line the worked for me was

I also encountered this problem. The root cause in my case was that I already had Jinja2 installed with root permissions (having used sudo pip install before I knew better).

My solution was to uninstall Jinja2 with sudo pip uninstall (which was required because it was installed with root permissions), and re-run pip install jupyter to reinstall it with regular user permissions.

While using sudo to install works here, it makes the problem worse in the longer term because all its packages are installed with root permissions, leading to further problems like this in future with other packages. It’s kind of like kicking that can down the road.

Many won’t care of course, as long as it works. But for those that do I thought I’d mention.

There’s no way to know for sure what the offending package is, but it’s likely to be one of those in the stack trace. I noticed Jinja2 as one I vaguely remembered from my early days in Python so I started there and it worked.

Источник

Catching a 500 server error in Flask

I love Flask’s error catching. It’s beautifully simple:

works like charm. But it doesn’t work for the 500 error code. I want to catch Python errors when something goes wrong an exception is raised in the code. Is that possible?

I should note that if I explicitly call return abort(500) in a view then the 500 errorhandler does work. So this is explicitly for when the Python code fails.

Is this possible?

6 Answers 6

What you have described is, by default, how Flask works. My assumption is that you are running in debug mode, and therefore exceptions are being shown to you in the debug screen. Make sure debug mode is off, then try again. Here is a comment directly from the code itself:

Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed.

It works fine in my side:

Flask will not set the error code for you, so make sure to also provide the HTTP status code when returning a response.

here is my code snippt

My solution to this was to turn on the propagation of exceptions, by modifying the config dictionary:

The issue is that within the code, not all Exceptions are HTTPException , but Flask catches these by default and returns a generic 500 error response (which may or may not include the original error message as described by @Mark Hildreth). Thus, using @app.errorhandler(500) will not catch those errors, since this happens before Flask returns the generic 500 error.

You would need to have a generic errorhandler(Exception) which works similar to except Exception: in python, which captures everything. A good solution is provided in Flask pallets projects:

You can also return JSON if you’d like and also include the original error message if you’re in debug mode. E.g.

this code catching 500 status code and get exception error

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

HOWTO Fetch Internet Resources Using The urllib PackageВ¶

There is a French translation of an earlier revision of this HOWTO, available at urllib2 — Le Manuel manquant.

IntroductionВ¶

You may also find useful the following article on fetching web resources with Python:

A tutorial on Basic Authentication, with examples in Python.

urllib.request is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the urlopen function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations — like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers.

urllib.request supports fetching URLs for many “URL schemes” (identified by the string before the «:» in URL — for example «ftp» is the URL scheme of «ftp://python.org/» ) using their associated network protocols (e.g. FTP, HTTP). This tutorial focuses on the most common case, HTTP.

For straightforward situations urlopen is very easy to use. But as soon as you encounter errors or non-trivial cases when opening HTTP URLs, you will need some understanding of the HyperText Transfer Protocol. The most comprehensive and authoritative reference to HTTP is RFC 2616. This is a technical document and not intended to be easy to read. This HOWTO aims to illustrate using urllib, with enough detail about HTTP to help you through. It is not intended to replace the urllib.request docs, but is supplementary to them.

Fetching URLsВ¶

The simplest way to use urllib.request is as follows:

If you wish to retrieve a resource via URL and store it in a temporary location, you can do so via the urlretrieve() function:

Many uses of urllib will be that simple (note that instead of an ‘http:’ URL we could have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s the purpose of this tutorial to explain the more complicated cases, concentrating on HTTP.

HTTP is based on requests and responses — the client makes requests and servers send responses. urllib.request mirrors this with a Request object which represents the HTTP request you are making. In its simplest form you create a Request object that specifies the URL you want to fetch. Calling urlopen with this Request object returns a response object for the URL requested. This response is a file-like object, which means you can for example call .read() on the response:

Note that urllib.request makes use of the same Request interface to handle all URL schemes. For example, you can make an FTP request like so:

In the case of HTTP, there are two extra things that Request objects allow you to do: First, you can pass data to be sent to the server. Second, you can pass extra information (“metadata”) about the data or the about request itself, to the server — this information is sent as HTTP “headers”. Let’s look at each of these in turn.

DataВ¶

Sometimes you want to send data to a URL (often the URL will refer to a CGI (Common Gateway Interface) script or other web application). With HTTP, this is often done using what’s known as a POST request. This is often what your browser does when you submit a HTML form that you filled in on the web. Not all POSTs have to come from forms: you can use a POST to transmit arbitrary data to your own application. In the common case of HTML forms, the data needs to be encoded in a standard way, and then passed to the Request object as the data argument. The encoding is done using a function from the urllib.parse library.

Note that other encodings are sometimes required (e.g. for file upload from HTML forms — see HTML Specification, Form Submission for more details).

If you do not pass the data argument, urllib uses a GET request. One way in which GET and POST requests differ is that POST requests often have “side-effects”: they change the state of the system in some way (for example by placing an order with the website for a hundredweight of tinned spam to be delivered to your door). Though the HTTP standard makes it clear that POSTs are intended to always cause side-effects, and GET requests never to cause side-effects, nothing prevents a GET request from having side-effects, nor a POST requests from having no side-effects. Data can also be passed in an HTTP GET request by encoding it in the URL itself.

This is done as follows:

Notice that the full URL is created by adding a ? to the URL, followed by the encoded values.

We’ll discuss here one particular HTTP header, to illustrate how to add headers to your HTTP request.

Some websites [1] dislike being browsed by programs, or send different versions to different browsers [2]. By default urllib identifies itself as Python-urllib/x.y (where x and y are the major and minor version numbers of the Python release, e.g. Python-urllib/2.5 ), which may confuse the site, or just plain not work. The way a browser identifies itself is through the User-Agent header [3]. When you create a Request object you can pass a dictionary of headers in. The following example makes the same request as above, but identifies itself as a version of Internet Explorer [4].

The response also has two useful methods. See the section on info and geturl which comes after we have a look at what happens when things go wrong.

Handling ExceptionsВ¶

urlopen raises URLError when it cannot handle a response (though as usual with Python APIs, built-in exceptions such as ValueError , TypeError etc. may also be raised).

HTTPError is the subclass of URLError raised in the specific case of HTTP URLs.

The exception classes are exported from the urllib.error module.

URLErrorВ¶

Often, URLError is raised because there is no network connection (no route to the specified server), or the specified server doesn’t exist. In this case, the exception raised will have a ‘reason’ attribute, which is a tuple containing an error code and a text error message.

HTTPErrorВ¶

Every HTTP response from the server contains a numeric “status code”. Sometimes the status code indicates that the server is unable to fulfil the request. The default handlers will handle some of these responses for you (for example, if the response is a “redirection” that requests the client fetch the document from a different URL, urllib will handle that for you). For those it can’t handle, urlopen will raise an HTTPError . Typical errors include ‘404’ (page not found), ‘403’ (request forbidden), and ‘401’ (authentication required).

See section 10 of RFC 2616 for a reference on all the HTTP error codes.

The HTTPError instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server.

Error CodesВ¶

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100–299 range indicate success, you will usually only see error codes in the 400–599 range.

http.server.BaseHTTPRequestHandler.responses is a useful dictionary of response codes in that shows all the response codes used by RFC 2616. The dictionary is reproduced here for convenience

When an error is raised the server responds by returning an HTTP error code and an error page. You can use the HTTPError instance as a response on the page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods as returned by the urllib.response module:

Wrapping it UpВ¶

So if you want to be prepared for HTTPError or URLError there are two basic approaches. I prefer the second approach.

Number 1В¶

The except HTTPError must come first, otherwise except URLError will also catch an HTTPError .

Number 2В¶

info and geturlВ¶

The response returned by urlopen (or the HTTPError instance) has two useful methods info() and geturl() and is defined in the module urllib.response ..

geturl — this returns the real URL of the page fetched. This is useful because urlopen (or the opener object used) may have followed a redirect. The URL of the page fetched may not be the same as the URL requested.

info — this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an http.client.HTTPMessage instance.

Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the Quick Reference to HTTP Headers for a useful listing of HTTP headers with brief explanations of their meaning and use.

Openers and HandlersВ¶

When you fetch a URL you use an opener (an instance of the perhaps confusingly-named urllib.request.OpenerDirector ). Normally we have been using the default opener — via urlopen — but you can create custom openers. Openers use handlers. All the “heavy lifting” is done by the handlers. Each handler knows how to open URLs for a particular URL scheme (http, ftp, etc.), or how to handle an aspect of URL opening, for example HTTP redirections or HTTP cookies.

You will want to create openers if you want to fetch URLs with specific handlers installed, for example to get an opener that handles cookies, or to get an opener that does not handle redirections.

To create an opener, instantiate an OpenerDirector , and then call .add_handler(some_handler_instance) repeatedly.

Alternatively, you can use build_opener , which is a convenience function for creating opener objects with a single function call. build_opener adds several handlers by default, but provides a quick way to add more and/or override the default handlers.

Other sorts of handlers you might want to can handle proxies, authentication, and other common but slightly specialised situations.

install_opener can be used to make an opener object the (global) default opener. This means that calls to urlopen will use the opener you have installed.

Opener objects have an open method, which can be called directly to fetch urls in the same way as the urlopen function: there’s no need to call install_opener , except as a convenience.

Basic AuthenticationВ¶

To illustrate creating and installing a handler we will use the HTTPBasicAuthHandler . For a more detailed discussion of this subject – including an explanation of how Basic Authentication works — see the Basic Authentication Tutorial.

When authentication is required, the server sends a header (as well as the 401 error code) requesting authentication. This specifies the authentication scheme and a ‘realm’. The header looks like: WWW-Authenticate: SCHEME realm=»REALM» .

The client should then retry the request with the appropriate name and password for the realm included as a header in the request. This is ‘basic authentication’. In order to simplify this process we can create an instance of HTTPBasicAuthHandler and an opener to use this handler.

The HTTPBasicAuthHandler uses an object called a password manager to handle the mapping of URLs and realms to passwords and usernames. If you know what the realm is (from the authentication header sent by the server), then you can use a HTTPPasswordMgr . Frequently one doesn’t care what the realm is. In that case, it is convenient to use HTTPPasswordMgrWithDefaultRealm . This allows you to specify a default username and password for a URL. This will be supplied in the absence of you providing an alternative combination for a specific realm. We indicate this by providing None as the realm argument to the add_password method.

The top-level URL is the first URL that requires authentication. URLs “deeper” than the URL you pass to .add_password() will also match.

In the above example we only supplied our HTTPBasicAuthHandler to build_opener . By default openers have the handlers for normal situations – ProxyHandler (if a proxy setting such as an http_proxy environment variable is set), UnknownHandler , HTTPHandler , HTTPDefaultErrorHandler , HTTPRedirectHandler , FTPHandler , FileHandler , DataHandler , HTTPErrorProcessor .

top_level_url is in fact either a full URL (including the ‘http:’ scheme component and the hostname and optionally the port number) e.g. «http://example.com/» or an “authority” (i.e. the hostname, optionally including the port number) e.g. «example.com» or «example.com:8080» (the latter example includes a port number). The authority, if present, must NOT contain the “userinfo” component — for example «joe:password@example.com» is not correct.

ProxiesВ¶

urllib will auto-detect your proxy settings and use those. This is through the ProxyHandler , which is part of the normal handler chain when a proxy setting is detected. Normally that’s a good thing, but there are occasions when it may not be helpful [5]. One way to do this is to setup our own ProxyHandler , with no proxies defined. This is done using similar steps to setting up a Basic Authentication handler:

Currently urllib.request does not support fetching of https locations through a proxy. However, this can be enabled by extending urllib.request as shown in the recipe [6].

HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set; see the documentation on getproxies() .

Sockets and LayersВ¶

The Python support for fetching resources from the web is layered. urllib uses the http.client library, which in turn uses the socket library.

As of Python 2.3 you can specify how long a socket should wait for a response before timing out. This can be useful in applications which have to fetch web pages. By default the socket module has no timeout and can hang. Currently, the socket timeout is not exposed at the http.client or urllib.request levels. However, you can set the default timeout globally for all sockets using

This document was reviewed and revised by John Lee.

Источник

1. None поправил
2. timeout=0.001 — без этого параметра ошибка такая же

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@app.route('/node', methods=['GET', 'POST'])
def node():
    response = {
            'send adress': request.form['key1'],
            'send atom': request.form['key2'],
        }
    return jsonify(response), 200
 
 
@app.route('/post', methods=['GET', 'POST'])
def post_to_node():
    base_url = "http://localhost:5000/node"
    payload = {'key1': 'value1', 'key2': 'value2'}
    response = requests.post(base_url, data=payload, timeout=0.001)
    #response = requests.get(base_url, data=payload, timeout=0.001)
    res = response.text
    if print(response.text) is not None:
        res = response.text
    else:
        res = 'none'
    return  print(res)# TEXT/HTML

Добавлено через 3 минуты
Лог ошибки:

Кликните здесь для просмотра всего текста

C:Users230AppDataLocalProgramsPythonPython3 6-32python.exe C:/Work/phyton/main.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
[2018-04-02 21:02:32,454] ERROR in app: Exception on /post [GET]
Traceback (most recent call last):
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3connectionpool.py», line 387, in _make_request
six.raise_from(e, None)
File «<string>», line 2, in raise_from
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3connectionpool.py», line 383, in _make_request
httplib_response = conn.getresponse()
File «C:Users230AppDataLocalProgramsPythonPython 36-32libhttpclient.py», line 1331, in getresponse
response.begin()
File «C:Users230AppDataLocalProgramsPythonPython 36-32libhttpclient.py», line 297, in begin
version, status, reason = self._read_status()
File «C:Users230AppDataLocalProgramsPythonPython 36-32libhttpclient.py», line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), «iso-8859-1»)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsocket.py», line 586, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesrequestsadapters.py», line 440, in send
timeout=timeout
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3connectionpool.py», line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3utilretry.py», line 357, in increment
raise six.reraise(type(error), error, _stacktrace)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3packagessix.py», line 686, in reraise
raise value
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3connectionpool.py», line 601, in urlopen
chunked=chunked)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3connectionpool.py», line 389, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesurllib3connectionpool.py», line 309, in _raise_timeout
raise ReadTimeoutError(self, url, «Read timed out. (read timeout=%s)» % timeout_value)
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host=’localhost’, port=5000): Read timed out. (read timeout=1)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesflaskapp.py», line 1982, in wsgi_app
response = self.full_dispatch_request()
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesflaskapp.py», line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesflaskapp.py», line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesflask_compat.py», line 33, in reraise
raise value
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesflaskapp.py», line 1612, in full_dispatch_request
rv = self.dispatch_request()
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesflaskapp.py», line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File «C:/Work/phyton/main.py», line 148, in post_to_node
response = requests.post(base_url, data=payload, timeout=1)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesrequestsapi.py», line 112, in post
return request(‘post’, url, data=data, json=json, **kwargs)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesrequestsapi.py», line 58, in request
return session.request(method=method, url=url, **kwargs)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesrequestssessions.py», line 508, in request
resp = self.send(prep, **send_kwargs)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesrequestssessions.py», line 618, in send
r = adapter.send(request, **kwargs)
File «C:Users230AppDataLocalProgramsPythonPython 36-32libsite-packagesrequestsadapters.py», line 521, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host=’localhost’, port=5000): Read timed out. (read timeout=1)
127.0.0.1 — — [02/Apr/2018 21:02:32] «GET /post HTTP/1.1» 500 —
127.0.0.1 — — [02/Apr/2018 21:02:32] «POST /node HTTP/1.1» 200 —

Добавлено через 2 минуты
если таймаут убрать, страница бесконечно пытается грузится с пустым экраном

Обработка HTTP-ошибок 404, 500 и т.д. во Flask.

Если какая-то часть кода кода сайта на Flask ломается при обработке запроса и нет зарегистрированных обработчиков ошибок, то по умолчанию будет возвращена ошибка 500 Internal Server Error (InternalServerError). Точно так же будет выводится стандартная страница с ошибкой 404 Not Found , если запрос будет отправлен на незарегистрированный URL-адрес. Если маршрут получает недопустимый метод запроса, будет активирован HTTP-метод 405 Not Allowed. Все это подклассы HTTPException, которые по умолчанию предоставляются в Flask.

Фреймворк Flask дает возможность вызывать любое исключение HTTP, зарегистрированное Werkzeug, но по умолчанию отдаются простые/стандартные страницы ошибок. Для удобства пользователя сайта, а так же повышения лояльности поисковых систем к сайту необходимо показывать настроенные страницы ошибок (вместо стандартных). Это можно сделать, зарегистрировав обработчики ошибок.

Обработчик ошибок — это функция, которая возвращает ответ при возникновении определенного типа ошибки, аналогично тому, как представление является функцией, которая возвращает ответ при совпадении URL-адреса запроса. Ему передается экземпляр обрабатываемой ошибки, который будет является исключением werkzeug.exceptions.HTTPException.

Когда Flask перехватывает исключение при обработке запроса, сначала выполняется поиск по коду. Если в коде не зарегистрирован обработчик, то Flask ищет ошибку в иерархии классов и выбирает наиболее конкретный обработчик. В том случае, если обработчик не зарегистрирован, то подклассы HTTPException показывают наиболее подходящую стандартную страницу с ошибкой, в то время как другие исключения преобразуются в общую страницу 500 Internal Server Error.

Например, если возникает экземпляр ConnectionRefusedError и зарегистрированы обработчики ConnectionError и ConnectionRefusedError, то для генерации ответа будет вызываться более конкретный обработчик ConnectionRefusedError.

Содержание.

  • Регистрация обработчика ошибок в веб-приложении на Flask;
  • Универсальные обработчики исключений во Flask;
  • Как Flask обрабатывает необработанные исключения?
  • Создание собственной страницы с HTTP-ошибкой 404;
  • Пример пользовательской страницы ошибки с кодом 500;
  • Особенности обработки ошибок в схемах blueprint Flask;
  • Возврат ошибок API в формате JSON.

Регистрация обработчика ошибок в веб-приложении на Flask.

Зарегистрировать функцию-обработчик для модуля Flask, можно указав перед ней декоратор @app.errorhandler(), или зарегистрировать обработчик, использовав функцию app.register_error_handler(). Не забудьте установить код ошибки при возврате ответа.

# регистрируем обработчик `handle_bad_request()` декоратором
@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    return 'bad request!', 400

# регистрируем тот же обработчик без декоратора
app.register_error_handler(400, handle_bad_request)

Подклассы HTTPException, такие как BadRequest и их HTTP-коды, взаимозаменяемы при регистрации обработчиков. (BadRequest.code == 400)

Нестандартные HTTP-коды (такие как HTTP 507 Insufficient Storage) нельзя зарегистрировать, так как они не известны модулю Werkzeug. Для регистрации неизвестных HTTP-кодов определите подкласс werkzeug.exceptions.HTTPException с соответствующим кодом, зарегистрируйте и где надо вернуть HTTP-код 507 Insufficient Storage принудительно вызовите этот класс исключения при помощи инструкции raise.

# создаем подкласс исключения HTTP 507
class InsufficientStorage(werkzeug.exceptions.HTTPException):
    code = 507
    description = 'Not enough storage space.'

# регистрируем HTTP 507
app.register_error_handler(InsufficientStorage, handle_507)

# принудительно вызываем исключение `InsufficientStorage`
raise InsufficientStorage()

Обработчики могут быть зарегистрированы для любого класса исключений, а не только для подклассов HTTPException или кодов состояния HTTP. Обработчики могут быть зарегистрированы для определенного класса или для всех подклассов родительского класса.

Обработчики, зарегистрированные в blueprint, имеют приоритет над обработчиками, зарегистрированными глобально в веб-приложении, при условии, что blueprint (схема) обрабатывает запрос, вызывающий исключение. Однако blueprint не может обрабатывать ошибки маршрутизации 404, так как ошибка 404 возникает на уровне маршрутизации до того, как можно определить схему blueprint.

Универсальные обработчики исключений.

Можно зарегистрировать обработчики ошибок для очень общих базовых классов, таких как HTTPException или даже Exception, но имейте в виду, что они будут ловить все ошибки подряд (больше, чем можно ожидать) и в итоге получится одна страница ошибки на разные ситуации.

Например, обработчик ошибок для HTTPException может быть полезен для преобразования страниц ошибок HTML по умолчанию в JSON. Но тогда этот обработчик будет запускать, например ошибки 404 и 405 во время маршрутизации. В общем будьте внимательны при создании универсальных обработчиков.

from flask import json
from werkzeug.exceptions import HTTPException

@app.errorhandler(HTTPException)
def handle_exception(e):
    """Возвращает JSON вместо HTML для ошибок HTTP"""
    # сначала перехватываем ответ Flask для извлечения 
    # правильных заголовков и кода состояния из ошибки
    response = e.get_response()
    # заменяем тело ответа сервера на JSON
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
    })
    response.content_type = "application/json"
    # возвращаем ответ сервера
    return response

Обработчик ошибок для Exception может !показаться! полезным для изменения способа представления пользователю всех ошибок, даже не перехваченных в коде. Другими словами: страница ошибки с одним и тем же HTTP-кодом для разных ситуаций (о чем говорилось выше). Исключение Exception в Python фиксирует все необработанные ошибки, при этом будут включены все коды состояния HTTP.

Правильнее будет безопаснее зарегистрировать обработчики для более конкретных исключений, т.к. экземпляры HTTPException являются действительными ответами WSGI.

from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    # исключаем ошибки HTTP
    if isinstance(e, HTTPException):
        # если это ошибка HTTP, то просто
        # возвращаем ее без изменений
        return e

    # в остальных случаях (ошибка кода веб-приложения) 
    # генерируем страницу с ошибкой HTTP 500
    return render_template("500_generic.html", e=e), 500

Обработчики ошибок по-прежнему соблюдают иерархию классов исключений. Если зарегистрировать обработчики как для HTTPException, так и для Exception, то обработчик Exception не будет обрабатывать подклассы HTTPException, т.к. он является более конкретным обработчиком HTTPException.

Как Flask обрабатывает необработанные исключения?

Если код сайта на Flask во время работы ломается, то есть возникло исключение, для которого не зарегистрирован обработчик ошибок, то будет возвращена ошибка 500 Internal Server

Если для исключения InternalServerError зарегистрирован обработчик ошибок, то будет вызван этот обработчик. Начиная с Flask 1.1.0, этому обработчику ошибок всегда будет передаваться экземпляр InternalServerError, а не исходная не перехваченная ошибка. Исходная ошибка доступна как e.original_exception.

Обработчику ошибок 500 Internal Server Error будут передаваться неперехваченные исключения в дополнение к явным ошибкам 500. В режиме отладки обработчик 500 Internal Server Error не используется, а показывается интерактивный отладчик.

Создание собственной страницы с HTTP-ошибкой 404.

Почти всегда при создании сайта на Flask необходимо потребоваться вызвать исключение HTTPException, чтобы сообщить пользователю, что с запросом что-то не так. Фреймворк Flask поставляется с удобной функцией flask.abort(), которая прерывает запрос со стандартной страницей HTTP-ошибки (только основное описание), зарегистрированной в модуле werkzeug.

В зависимости от кода ошибки, вероятность того, что пользователь действительно увидит конкретную ​​ошибку, меньше или больше.

Рассмотрим приведенный ниже код. Например, может быть маршрут профиля пользователя, и если пользователь не может передать имя пользователя, то можно выдать 400 Bad Request. Если пользователь передает имя пользователя, а сайт не можем его найти, то выдаем сообщение 404 Not Found.

from flask import abort, render_template, request

# имя пользователя должно быть указано в параметрах запроса
# успешный запрос будет похож на /profile?username=jack
@app.route("/profile")
def user_profile():
    username = request.arg.get("username")
    # если имя пользователя не указано в запросе,
    # то вернем `400 Bad Request`
    if username is None:
        abort(400)

    user = get_user(username=username)
    # Если пользователь не наёден, то `404 not found`
    if user is None:
        abort(404)

    return render_template("profile.html", user=user)

Для того, что бы возвращалась страница 404 not found с собственным дизайном, необходимо создать функцию обработчик:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    # в функцию `render_template()` передаем HTML-станицу с собственным
    # дизайном, а так же явно устанавливаем статус 404
    return render_template('404.html'), 404
from flask import Flask, render_template

# обработчик
def page_not_found(e):
  return render_template('404.html'), 404

def create_app(config_filename):
    app = Flask(__name__)
    # регистрация обработчика
    app.register_error_handler(404, page_not_found)
    return app

Пример шаблона страницы с ошибкой 404.html может быть таким:

{% extends "layout.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
  <h1>Page Not Found</h1>
  <h3>То, что вы искали, просто не существует.</h3>
  <p>Для продолжения перейдите <a href="{{ url_for('index') }}">на главную страницу сайта</a></p>
{% endblock %}

Пример пользовательской страницы ошибки с кодом 500.

Приведенные выше примеры не на много улучшат страницы HTTP-ошибок по умолчанию. Так же можно создать собственный шаблон 500.html следующим образом:

{% extends "layout.html" %}
{% block title %}Internal Server Error{% endblock %}
{% block body %}
  <h1>Internal Server Error</h1>
  <h3>Мы уже знаем об этой ошибке и делаем все возможное для ее устранения!</h3>
  <p>Приносим извинения за причлененные неудобства, скоро все заработает.</p>
{% endblock %}

Создаем функцию обработчик HTTP-ошибок 500 Internal Server Error:

from flask import render_template

@app.errorhandler(500)
def internal_server_error(e):
    # Обратите внимание, что необходимо 
    # явно установить статус 500
    return render_template('500.html'), 500

При использовании фабрик приложений:

from flask import Flask, render_template

# обработчик
def internal_server_error(e):
  return render_template('500.html'), 500

def create_app():
    app = Flask(__name__)
    # регистрация обработчика
    app.register_error_handler(500, internal_server_error)
    return app
from flask import Blueprint

blog = Blueprint('blog', __name__)

# регистрация обработчика при помощи декоратора
@blog.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

# или с использованием метода `register_error_handler()`
blog.register_error_handler(500, internal_server_error)

Особенности обработки ошибок в схемах blueprint Flask.

В модульных приложениях с blueprint большинство обработчиков ошибок будут работать должным образом, но есть предостережение относительно обработчиков исключений 404 и 405. Эти обработчики вызываются только из соответствующего оператора raise или вызывают flask.abort() в другой функции-представлении схемы blueprint. Они не вызываются, например, из-за недействительного доступа к URL-адресу.

Это связано с тем, что blueprint не принадлежит определенное пространство URL-адресов, поэтому экземпляр приложения не имеет возможности узнать, какой обработчик ошибок схемы (blueprint) необходимо запустить, если указан недопустимый URL-адрес. Если необходимо использовать различные стратегии обработки этих ошибок на основе префиксов URL-адресов, то они могут быть определены на уровне приложения с помощью объекта прокси-сервера запроса flask.request.

from flask import jsonify, render_template

# на уровне всего веб-приложения
# это не уровень определенной схемы blueprint
@app.errorhandler(404)
def page_not_found(e):
    # Если запрос находится в пространстве URL блога
    if request.path.startswith('/blog/'):
        # то возвращаем кастомную 404 ошибку для блога 
        return render_template("blog/404.html"), 404
    else:
        # в противном случае возвращаем 
        # общую 404 ошибку  для всего сайта
        return render_template("404.html"), 404

@app.errorhandler(405)
def method_not_allowed(e):
    # Если в запросе указан неверный метод к API
    if request.path.startswith('/api/'):
        # возвращаем json с 405 HTTP-ошибкой
        return jsonify(message="Method Not Allowed"), 405
    else:
        # в противном случае возвращаем 
        # общую 405 ошибку для всего сайта
        return render_template("405.html"), 405

Возврат ошибок API в формате JSON

При создании API-интерфейсов во Flask некоторые разработчики понимают, что встроенные исключения недостаточно выразительны для API-интерфейсов и что тип содержимого text/html, который они генерируют, не очень полезен для потребителей API.

Используя те же методы, что и выше плюс flask.jsonify(), можно возвращать ответы JSON на ошибки API. Функция flask.abort() вызывается с аргументом description. Обработчик ошибок будет использовать это как сообщение об ошибке JSON и установит код состояния на 404.

from flask import abort, jsonify

@app.errorhandler(404)
def resource_not_found(e):
    return jsonify(error=str(e)), 404

@app.route("/cheese")
def get_one_cheese():
    resource = get_resource()

    if resource is None:
        abort(404, description="Resource not found")

    return jsonify(resource)

Можно создавать собственные классы исключений. Например, можно ввести новое настраиваемое исключение для API, которое будет принимать правильное удобочитаемое сообщение, код состояния для ошибки и некоторую дополнительную полезную информацию, чтобы дать больше конкретики для ошибки.

from flask import jsonify, request

class InvalidAPIUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        super().__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.errorhandler(InvalidAPIUsage)
def invalid_api_usage(e):
    return jsonify(e.to_dict())

# маршрут API для получения информации о пользователе
# правильный запрос может быть /api/user?user_id=420
@app.route("/api/user")
def user_api(user_id):
    user_id = request.arg.get("user_id")
    if not user_id:
        raise InvalidAPIUsage("No user id provided!")

    user = get_user(user_id=user_id)
    if not user:
        raise InvalidAPIUsage("No such user!", status_code=404)

    return jsonify(user.to_dict())

Теперь функция-представление может вызвать это исключение с сообщением об ошибке. Кроме того, дополнительная полезная информация может быть предоставлена ​​в виде словаря через параметр payload.

I need to send a Json from a file to a server. The server doesn’t allow to send bulk Json, juste one by one. I put my json in a file and I have to send that in a loop one by one.
I have a response 500. below my codes :

import codecs
import json
import requests
from requests.auth import HTTPBasicAuth
BASE_API_ENDPOINT ="https://bookumadesu.org/api/elements/"
headers={'Content-type':'application/json'}

f = codecs.open('data.txt', 'r','utf-8')
lines=f.read()
txt=[]
txt=lines.split('*')
for i in txt :
    #print(i.replace('n',' '))
    payload=json.loads(i)
    ID=payload["id"]
    # sending post request and saving response as response object
    FINAL_ENDPOINT=BASE_API_ENDPOINT+ID+"/translations"
    print("EndPoint : ",FINAL_ENDPOINT)
    print(i)
    r = requests.put(url = FINAL_ENDPOINT,data=i, auth=HTTPBasicAuth('username', 'xxx'), headers=headers)

    print("Response ",r.status_code)


f.close()

The json in My txt file :

{«id»: «fbfJHSPpUQD»,
«displayName»: «ANC 1st visit»,
«translations»: [

{
«property»: «FORM_NAME»,
«locale»: «pt»,
«value»: «O SDP é acessível por transporte público?»
},
{
«property»: «FORM_NAME»,
«locale»: «fr»,
«value»: «Le PPS est-il accessible par les transports en commun ?»
}
]
}

I want to point out that this same Json when I use it in Postman, it works! Hand

Posts: 6

Threads: 1

Joined: Jun 2020

Reputation:
0

Jun-10-2020, 09:58 AM
(This post was last modified: Jun-10-2020, 10:03 AM by ChaitanyaPy.)

It is a problem with the server end. Maybe the server is unable to handle the request.
The HTTP Error 500 literally means that. If the server is a python-based server built with services like Pythonanywhere, then recheck your server-side code.
If it’s an external service, then check their API documentation.


And are you sure that there is nothing wrong with JSON file?
Because it contains non-English characters like "value": "O SDP é acessível por transporte público?" and "value": "Le PPS est-il accessible par les transports en commun ?"

rndoma

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jun 2020

Reputation:
0

Jun-10-2020, 10:04 AM
(This post was last modified: Jun-10-2020, 10:19 AM by rndoma.)

@ChaitanyaPy,
The server is a java-base server.
I sent the same Json with Postman, It worked.
Thanks


(Jun-10-2020, 09:58 AM)ChaitanyaPy Wrote: It is a problem with the server end. Maybe the server is unable to handle the request.
The HTTP Error 500 literally means that. If the server is a python-based server built with services like Pythonanywhere, then recheck your server-side code.
If it’s an external service, then check their API documentation.


And are you sure that there is nothing wrong with JSON file?
Because it contains non-English characters like "value": "O SDP é acessível por transporte público?" and "value": "Le PPS est-il accessible par les transports en commun ?"

No, I told you I sent the sams Json in Postman. It’s the translation of an Element in 2 languages (portugeuse and french).

Posts: 6

Threads: 1

Joined: Jun 2020

Reputation:
0

Have you checked the API documentation of that service? I have experience using python-based servers, and most of the time the reason for a HTTP Error 500 has always been a server-side code error which I myself have made.

rndoma

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jun 2020

Reputation:
0

(Jun-10-2020, 10:35 AM)ChaitanyaPy Wrote: Have you checked the API documentation of that service? I have experience using python-based servers, and most of the time the reason for a HTTP Error 500 has always been a server-side code error which I myself have made.

I told you that it’s a Java-based server not Python-based server.

Posts: 6

Threads: 1

Joined: Jun 2020

Reputation:
0

Is it an online service or a local java-server that you are running? If it’s an online service, then there should at least be some bare documentation on what request method to use for a specific function and stuff. Like some instructions on what will work and what won’t.
And while scrolling through your code, I saw the endpoint and tried to just go their site for some help.
Then Chrome replied with an error that basically says that the server can’t be reached.
Then I tried to request the server with Python, which ended up with a bunch of errors ending with:

Error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='bookumadesu.org', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000219AF008460>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

.
Which got me to thinking if the endpoint even exists?
I am sorry if I am just thinking all of this in the wrong way.

rndoma

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jun 2020

Reputation:
0

(Jun-10-2020, 11:12 AM)ChaitanyaPy Wrote: Is it an online service or a local java-server that you are running? If it’s an online service, then there should at least be some bare documentation on what request method to use for a specific function and stuff. Like some instructions on what will work and what won’t.
And while scrolling through your code, I saw the endpoint and tried to just go their site for some help.
Then Chrome replied with an error that basically says that the server can’t be reached.
Then I tried to request the server with Python, which ended up with a bunch of errors ending with:

Error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='bookumadesu.org', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000219AF008460>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

.
Which got me to thinking if the endpoint even exists?
I am sorry if I am just thinking all of this in the wrong way.

Please can you cheick your email please? I sent you an email please.

rndoma

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jun 2020

Reputation:
0

I resolved the problem my self it woks now.
Thanks!

This article will deal with different types of  HTTP errors and then learn how to use Flask error handling to tackle these errors. So let’s get started!

Why do we Need Error Handling?

An error in a web application can happen due to several reasons. It can be due to an incorrect code in the App or some bad requests by the user or server downtime.

Hence it is critical to handle these errors. The browsers, though by-default handles HTTP errors for you, the output is not quite aesthetic. 

For example, while building a Flask application, you might have come across 500 internal server error.

500 Internal Server Error
500 Internal Server Error

A simple line indicating the reason for the error would have sufficed, instead of displaying irrelevant data.

This is where Flask Error handlers come into the picture.

With Flask error Handlers, we can:

  1. Customize the error page look.
  2. Show only relevant data to the user.

Common HTTP errors

Some of the most common errors raised are:

HTTP Error Codes Meaning
301 Moved Permanently
302 Moved Temporarily
400 Bad Request
403 Forbidden
404 Not Found
429 Too Many Requests
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
HTTP Errors

Hands-On with Flask Error Handling

Error codes – 404 and 500 are the most common errors that we deal with every day.

So in this section we will build a simple Error handler for 404 and 500. The syntax for other errors will be exactly the same.

In flask, we use the built-in error_handler decorator.

The syntax is:

@app.errorhandler(status_code)
def function_name(error):
    return render_template('xyz.html'),status_code

Hence consider the following Flask application example:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/blogs')
def blog():
    return render_template('blog.html')

#Handling error 404 and displaying relevant web page
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'),404

#Handling error 500 and displaying relevant web page
@app.errorhandler(500)
def internal_error(error):
    return render_template('500.html'),500

#app.run(host='localhost', port=5000)
app.run(host='localhost', port=5000)

The Blog.html:

<h2>Welcome to the Blog</h2>

The 404.html file:

<h2>The webpage you are trying is not found</h2>
<img src = "{{url_for('static','images/opps.jpg') }}"

Here we are using a image to show on the 404 web page as well

Similarly the 500.html file:

<h2>Something Went Wrong</h2>

Implementation

Now run the server and go to any arbitary non-existant URL endpoint

404
404

Now to get the 500 error, deliberately interchange a few letters of render_template() to let’s say remder_template()

Now restart the server and go to “/blogs” URL. You will now get the 500 error page

500 Error page
500 Error Page

Perfect!

Conclusion

That’s it, guys !! You can now customize the error pages as well based on your webpage theme. Do check out our other Flask tutorials to know more about Flask.

See you guys in the next article !! Happy Coding 🙂

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Http error 500 phpmyadmin
  • Http error 431 яндекс справочник
  • Http error 500 phpbb
  • Http error 431 что значит
  • Http error 431 как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии