Hướng dẫn if response 200 python

What is the easiest way to check whether the response received from a requests post was "200 OK" or an error has occurred?

I tried doing something like this:

....
resp = requests.post(my_endpoint_var, headers=header_var, data=post_data_var)
print(resp)
if resp == "":
    print ('OK!')
else:
    print ('Boo!')

The output on the screen is:

Response [200] (including the "<" and ">")
Boo!

So even though I am getting a 200, my check in the if statement is somehow not matching?

Shaido

26.3k21 gold badges68 silver badges72 bronze badges

asked Jan 8, 2019 at 7:47

3

According to the docs, there's a status_code property on the response-object. So you can do the following:

if resp.status_code == 200:
    print ('OK!')
else:
    print ('Boo!')

EDIT:

As others have pointed out, a simpler check would be

if resp.ok:
    print ('OK!')
else:
    print ('Boo!')

if you want to consider all 2xx response codes and not 200 explicitly. You may also want to check Peter's answer for a more python-like way to do this.

answered Jan 8, 2019 at 7:52

eoleol

21k4 gold badges34 silver badges56 bronze badges

3

Just check the response attribute resp.ok. It is True for all 2xx responses, but False for 4xx and 5xx. However, the pythonic way to check for success would be to optionally raise an exception with Response.raise_for_status():

try:
    resp = requests.get(url)
    resp.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)

EAFP: It’s Easier to Ask for Forgiveness than Permission: You should just do what you expect to work and if an exception might be thrown from the operation then catch it and deal with that fact.

answered Oct 19, 2019 at 15:37

PeterPeter

5,3412 gold badges20 silver badges32 bronze badges

5

Much simpler check would be

    if resp.ok :
        print ('OK!')
    else:
        print ('Boo!')

answered Feb 29, 2020 at 1:59

MrHumbleMrHumble

711 silver badge1 bronze badge

1

Since any 2XX class response is considered successful in HTTP, I would use:

if 200 <= resp.status_code <= 299:
    print ('OK!') 
else:
    print ('Boo!')

answered Oct 14, 2019 at 20:37

roublerouble

14.7k16 gold badges101 silver badges97 bronze badges

3

I'm surprised no one has mentioned this so:

If you want to check for exactly a 200 response:

if resp.status_code == requests.codes.ok:

The status_code of a response contains the HTTP status returned.

requests.codes.ok is exactly 200.


If you want to check if the status code is "ok", and not an error:

if resp.ok:

The ok attribute of a response checks that the status code of the response is less than 400.


Make sure you know what it is you want to check, for example a 201 HTTP Created is a successful response that you would be omitting if you only check for exactly 200.

answered Feb 18 at 9:51

Hướng dẫn if response 200 python

gdvalderramagdvalderrama

6891 gold badge20 silver badges25 bronze badges

try:

if resp.status_code == 200:
    print ('OK!')
else:
    print ('Boo!)

answered Jan 8, 2019 at 7:52

Caders117Caders117

3193 silver badges18 bronze badges

In easy case:

import requests

response = requests.get(url)
if not response:
    #handle error here
else:
    #handle normal response

answered Nov 19, 2019 at 5:44

qloveshmilyqloveshmily

9118 silver badges5 bronze badges

Not the answer you're looking for? Browse other questions tagged python python-requests or ask your own question.

Hướng dẫn if response 200 python

Hướng dẫn python multiplication game

For loop python guessing gameOnyejiaku Theophilus ChidaluOverview The while loop in python is used to execute a code block multiple times. They are often used in building interactive programs and ...

Hướng dẫn if response 200 python

Save array to json python

I want to create a json file like { a:[12,34,23,...], b:[13,14,45,....], . . . } key should come from the list:lis = [a,b,...] and value from the sql query select id from + i , ...

Hướng dẫn if response 200 python

Write number to text file python

Would using the pickle function be the fastest and most robust way to write an integer to a text file?Here is the syntax I have so far:import pickle pickle.dump(obj, file) If there is a more robust ...

Hướng dẫn if response 200 python

Hướng dẫn if response 200 python

For loop in for loop python

Loops Inside LoopsA nested loop is a loop inside a loop.The inner loop will be executed one time for each iteration of the outer loop:ExamplePrint each adjective for every fruit: adj = [red, ...

Hướng dẫn if response 200 python

Hướng dẫn crosstab in python

Đưa ra một khung dữ liệu với các biến phân loại khác nhau, làm cách nào để trả về bảng chéo với tỷ lệ phần trăm thay vì tần số?Nội dung chínhHow to use ...

Hướng dẫn if response 200 python

Hướng dẫn if response 200 python

How to handle timeout exception in python

Im looking for a way to handle timeout exceptions for my Reddit bot which uses PRAW (Python). It times out at least once every day, and it has a variable coded in so I have to update the variable ...

Hướng dẫn if response 200 python

Python parse log file to csv

I have a log file which is around 1.5 GB. The file contains log data in the following format:A|B|C|D delimited by | character and does not have column names. It has only four columns How can I ...

Hướng dẫn if response 200 python

Hướng dẫn dùng python init python

Trong bài này, chúng ta sẽ tìm hiểu về hàm khởi tạo (constructor) của class trong Python. Đây là bài tiếp theo của bài Xây dựng lớp (class) và tạo đối tượng ...

Hướng dẫn if response 200 python

Hướng dẫn dùng coor definition python

Hướng dẫn sử dụng def trong python. Bạn sẽ học được cách sử dụng def để khai báo hàm trong python, cũng như cách gọi hàm trong python đã được khai báo sau ...

Hướng dẫn if response 200 python

Plot multiple bar graphs python

View DiscussionImprove ArticleSave ArticleReadDiscussView DiscussionImprove ArticleSave ArticleA multiple bar chart is also called a Grouped Bar chart. A Bar plot or a Bar Chart has many ...

Hướng dẫn if response 200 python

Hướng dẫn dùng x trains python

Dẫn nhậpTrong bài trước, chúng ta đã tìm hiểu về TỔNG KẾT LINEAR REGRESSION.Nội dung chínhDẫn nhậpDebug thuật toán Machine LearningPhân biệt các trường hợp Bias ...

Hướng dẫn if response 200 python

Python sort by key in dictionary

There is an easy way to sort a dictionary.According to your question,The solution is :c={2:3, 1:89, 4:5, 3:0} y=sorted(c.items()) print y (Where c,is the name of your dictionary.)This program gives ...

Hướng dẫn if response 200 python

Hướng dẫn socket python

Bài viết giới thiệu căn bản về lập trình socket mà cụ thể là lập trình socket sử dụng TCP/IP bằng ngôn ngữ Python.1. Socket là gì?Một socket là một ...

Hướng dẫn if response 200 python

Hướng dẫn parser.add_argument python

Xin chào các bạn. Hôm nay mình xin phép giới thiệu argparse. Đây là một thư viện có sẵn và sẽ sẽ giúp bạn viết CLI (Command Line Interface) trong Python một cách ...

Hướng dẫn if response 200 python

Hướng dẫn dùng read_lines r trong PHP

Rất nhiều người học PHP thường nghĩ rằng PHP luôn phải gắn chặt với phát triển ứng dụng web.Nội dung chínhChuẩn bị projectChuẩn bị ứng dụngCấu trúc ...

Hướng dẫn if response 200 python

Hướng dẫn if response 200 python

Hướng dẫn python setattr function

Trong Python, hàm setattr() có nhiệm vụ thiết lập giá trị cho một thuộc tính của đối tượng.Nội dung chínhCú pháp của hàm setattr() trong PythonCác tham số ...

Hướng dẫn if response 200 python

Hướng dẫn python time unit conversion

Does python provide support for time unit conversions beyond explicit arithmetic? For example, in Java:TimeUnit.DAYS.toMillis(1); // 1 day to milliseconds. TimeUnit.MINUTES.toMillis(23); // 23 ...

Hướng dẫn if response 200 python

Hướng dẫn dùng differenc python

Kiểu dữ liệu Dictionary trong Python là một tập hợp các cặp key-value không có thứ tự, có thể thay đổi và lập chỉ mục (truy cập phần tử theo chỉ mục). ...

Hướng dẫn if response 200 python

What are methods called in python?

FunctionA function is a block of code to carry out a specific task, will contain its own scope and is called by name. All functions may contain zero(no) arguments or more than one arguments. On exit, ...

Hướng dẫn if response 200 python

Python certification for business analyst

Celebrate Festival with us: Invest Less & Grab 5 More Exclusive Offers: OFFER ENDING IN Days Hours Minutes SecondsCheck Now Check Now Request For Free DemoKey FeaturesRanked Top Analytics ...

Hướng dẫn if response 200 python

How do you reverse a reverse number in python?

Example 1: Reverse a Number using a while loopnum = 1234 reversed_num = 0 while num != 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10 print(Reversed Number: ...

Hướng dẫn if response 200 python

Hướng dẫn if response 200 python

Hướng dẫn symmetric difference in python

The symmetric_difference() method returns all the items present in given sets, except the items in their intersections.ExampleA = {a, b, c, d} B = {c, d, e } # returns all items to ...

Hướng dẫn if response 200 python

Hướng dẫn dùng numpy slice python

Indexing cũng giống với các kiểu dữ liệu khác trong python, như tuple và list.import numpy as np F = np.array([1, 1, 2, 3, 5, 8, 13, 21]) print the first element of F, i.e. the ...

Hướng dẫn if response 200 python

Hướng dẫn dùng tried meaning python

Từ điển trong Python là danh sách các giá trị dữ liệu không được sắp xếp và có thể được thay đổi bằng cách sử dụng các phương thức tích hợp sẵn. ...

Hướng dẫn if response 200 python

Hướng dẫn python octal to ascii

I just started learning python and I thought it would be good practise to play a CTF and make “get flag” scripts in order to learn the different modules. I am stuck on a challenge that makes me ...

Hướng dẫn if response 200 python

How do you make a twilio call in python?

Twilio is launching a new Console. Some screenshots on this page may show the Legacy Console and therefore may no longer be accurate. We are working to update all screenshots to reflect the new ...

Hướng dẫn if response 200 python

How do i get rid of punctuation in python?

Many times while working with Python strings, we have a problem in which we need to remove certain characters from strings. This can have applications in data preprocessing in the Data Science domain ...

Hướng dẫn if response 200 python

Hướng dẫn python urllib

Urllib là gì?urllib là một mô-đun của Python có thể dùng để mở các URL. Nó định nghĩa các hàm và lớp giúp thao tác với URL.Với Python, bạn cũng có thể truy ...

Hướng dẫn if response 200 python

Hướng dẫn uuid python là gì

Source code: Lib/uuid.pyThis module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in ...

Hướng dẫn if response 200 python

Is c++ easier after python?

I learned Python as well as some other interpreted languages before learning C, and absolutely loved C when I started learning it (with The C Book) due to how much more sense it made to me, seeing ...

Hướng dẫn if response 200 python

Hướng dẫn if response 200 python

Hướng dẫn sqlalchemy trong python

Pythons SQLAlchemy và Object-Relational MappingMột nhiệm vụ phổ biến khi bắt đầu xây dựng một web service bất kỳ là làm sao để xây dựng một cơ sở dữ liệu ...

Hướng dẫn if response 200 python

How do i read a notepad file in python?

Open a File on the ServerAssume we have the following file, located in the same folder as Python:demofile.txt Hello! Welcome to demofile.txtThis file is for testing purposes.Good Luck!To open the ...

Hướng dẫn if response 200 python

Hướng dẫn if response 200 python

How do you show large numbers in python?

When dividing 2 large numbers in Python the output was 1.5640891676957637e+308. How do I print the entire number? asked Aug 11, 2019 at 14:49 2This cant be done because thats all the precision the ...

Hướng dẫn if response 200 python

How do you give a value to null in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.The python equivalent of NULL is called None (good info ...