Trăn hỏi

Tiếp tục với loạt bài này mình sẽ giới thiệu với mọi người về module yêu cầu giúp mọi người có thể gửi yêu cầu một cách đơn giản nhất trong Python

Vì module này hỗ trợ ta gửi request rất đa dạng nên mình chỉ trình bày những gì hay dùng nhất thôi, còn các bạn muốn xem chi tiết thì có thể up trang chủ của nó để xem

1, Mô-đun yêu cầu là gì?

Mô-đun yêu cầu là một thư viện hỗ trợ chúng tôi có thể gửi bất kỳ loại yêu cầu HTTP nào theo cách đơn giản nhất. Và tác giả của mô-đun này chính là Kenneth Reitz tác giả của các mô-đun đơn giản mà rất thần thánh trong giới Python. D

Mô-đun này hỗ trợ cả python 2 và 3 nhưng Python 3 thì sẽ hoàn hảo hơn

Trong bài viết này mình sẽ demo trên Python 3

2, Cài đặt

Mặc định thì thư viện này không được cài đặt kèm theo python. Nếu bạn muốn sử dụng thì cần phải tải nó. To install it, you only need to run command

pip install requests

Để kiểm tra đã thành công hay chưa, bạn chỉ cần nhập yêu cầu mô-đun vào và chạy, nếu không có lỗi gì thì đã thành công
VD

[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 

3, Sử dụng

Đầu tiên để có thể sử dụng được mô-đun này, bạn cần phải nhập nó vào đầu chương trình

import requests

Tạo yêu cầu

To make a request you only need to use the theo cú pháp sau

requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
# hoặc
requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]

in which

  • [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    0 sẽ là phương thức yêu cầu HTTP mà bạn muốn tạo, các phương thức này có thể là. NHẬN, ĐĂNG, ĐƯA, VÁ, XÓA và TÙY CHỌN
  • [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    1 là
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    2 chứa URL của trang web mà bạn muốn gửi yêu cầu đến
  • [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    3 là một
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    4 hoặc danh sách các bộ dữ liệu hoặc byte và bạn muốn gửi kèm theo trong nội dung yêu cầu. The number of this can may bỏ trống
  • [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    5 tương tự như
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    3, nhưng kiểu dữ liệu là đối tượng Python có thể tuần tự hóa JSON. The number of this can may bỏ trống
  • [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    7 là một
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    4 chứa các tiêu đề HTTP mà bạn muốn gửi kèm theo yêu cầu. The number of this can may bỏ trống
  • [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    9 là một
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    4 hoặc Đối tượng CookieJar chứa các cookie mà bạn muốn gửi kèm theo yêu cầu. The number of this can may bỏ trống
  • import requests
    1 is a
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    4 chứa các đối tượng tệp [đối tượng tệp là kết quả của hàm open[]] mà bạn muốn gửi kèm theo yêu cầu. The number of this can may bỏ trống
  • import requests
    3 là một
    import requests
    4 chứa tên người dùng, mật khẩu của trang web mà bạn muốn gửi yêu cầu đến nếu như trang web đó được bảo mật bởi Basic/Digest/Custom xác thực. The number of this can may bỏ trống
  • import requests
    5 là một
    import requests
    6 hoặc
    import requests
    7 đơn vị tính bằng giây thiết lập yêu cầu có thể chờ tối đa là bao nhiêu giây. The number of this can may bỏ trống
  • import requests
    8 là một
    import requests
    9 thiết lập xem yêu cầu này có cho phép chuyển hướng không, mặc định thì giá trị này bằng
    requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    # hoặc
    requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    0 có nghĩa là cho phép. The number of this can may bỏ trống
  • requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    # hoặc
    requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    1 là một
    [email protected]_info:~$ python3
    Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import requests
    >>> 
    
    4 chứa các giao thức để ánh xạ tới proxy của URL. The number of this can may bỏ trống
  • requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    # hoặc
    requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    3  là một
    import requests
    9 cấu hình xem có cho phép xác thực TLS hay không, mặc định là True. The number of this can may bỏ trống
  • requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    # hoặc
    requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    5 là một
    import requests
    9 cấu hình xem dữ liệu trả về có Stream hay không. The number of this can may bỏ trống
  • requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    # hoặc
    requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
    7 là một Chuỗi chứa đường dẫn đến tệp ứng dụng khách ssl [. pem]. The number of this can may bỏ trống

Phương thức này sẽ trả về một đối tượng phản hồi

VD

  • Gửi một yêu cầu đến Toidicode. com
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
  • Gửi một yêu cầu GET đính kèm tham số
import requests

requests.get["//toidicode.com/", params= {"post_id": 135}]
# hoặc
requests.get["//toidicode.com/?post_id=135"]

#request: //toidicode.com/?post_id=135
  • Gửi yêu cầu dữ liệu POST kèm theo thời gian chờ là 3 giây
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
  • Tạo yêu cầu POST upload file lên server
import requests

requests.post["//toidicode.com/", files={'image': open['images/logo.png']}]

Data return - Phản hồi

Khi tạo yêu cầu thành công thì dữ liệu trả về sẽ là một đối tượng chứa các thuộc tính và phương thức với chức năng như sau

KeyTypeReturnDescription

requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
# hoặc
requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
8Thuộc tính
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
2 Trả về kiểu mã hóa của dữ liệu trả về
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
0Phương thức
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1Đóng connection
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
2Thuộc tính
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
2Dữ liệu server trả về
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
9Thuộc tính
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
5 hoặc
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1Cookies của request server trả về
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
7Thuộc tính
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1 hoặc 
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
9Thời gian thực thi request
import requests

requests.get["//toidicode.com/", params= {"post_id": 135}]
# hoặc
requests.get["//toidicode.com/?post_id=135"]

#request: //toidicode.com/?post_id=135
0Thuộc tính
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1 hoặc
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
2Kiểu mã hóa dữ liệu khi truy cập thuộc tính
import requests

requests.get["//toidicode.com/", params= {"post_id": 135}]
# hoặc
requests.get["//toidicode.com/?post_id=135"]

#request: //toidicode.com/?post_id=135
3
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
7Thuộc tính
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1 hoặc
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
4Header .
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
0Thuộc tính
import requests
9Trả về
requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
# hoặc
requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
0 nếu request có redirect
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
3Thuộc tính
import requests
9Trả về
requests.method[url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
# hoặc
requests.Request[method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, verify, stream, cert]
0 nếu request có redirect bằng HTTP code
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
6Phương thức
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
7Lặp lại dữ liệu trả về khi Request set
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
8
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
9Phương thức
import requests

requests.post["//toidicode.com/", data={"post_id": 135}, timeout=3]
7Tương tự phương thức iter_content[] nhưng sẽ lặp lại theo dòng
import requests

requests.post["//toidicode.com/", files={'image': open['images/logo.png']}]
1Phương thức
import requests

requests.post["//toidicode.com/", files={'image': open['images/logo.png']}]
2Chuyển đổi dữ liệu trả về thành Json, .
import requests

r = requests.get["//ip-api.com/json"]

#request: //toidicode.com/?post_id=135

print[r.apparent_encoding]
# print[r.content]
print[r.encoding]
print[r.cookies]
print[r.elapsed]
print[r.encoding]
print[r.headers]
print[r.history]
print[r.is_permanent_redirect]
print[r.iter_content[]]
print[r.links]
print[r.raise_for_status[]]
print[r.json[]]
7Thuộc tính
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1 hoặc 
import requests

requests.post["//toidicode.com/", files={'image': open['images/logo.png']}]
6Xem chi tiết tại
ascii
utf-8

0:00:00.165961
utf-8
{'Content-Length': '271', 'Date': 'Mon, 17 Sep 2018 01:33:24 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*'}
[]
False

{}
None
{'as': 'AS7552 Viettel Group', 'zip': '', 'regionName': 'Hanoi', 'lat': 21.0333, 'country': 'Vietnam', 'status': 'success', 'timezone': 'Asia/Ho_Chi_Minh', 'lon': 105.85, 'countryCode': 'VN', 'org': 'Viettel Group', 'city': 'Hanoi', 'isp': 'Viettel Group', 'region': 'HN', 'query': '117.4.242.101'}
0Thuộc tính
import requests

requests.get["//toidicode.com/"]

# //toidicode.com/
1 hoặc
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
2Trạng thái HTTP mà máy chủ trả về
import requests

requests.get["//toidicode.com/", params= {"post_id": 135}]
# hoặc
requests.get["//toidicode.com/?post_id=135"]

#request: //toidicode.com/?post_id=135
3Thuộc tính
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
2Nội dung của yêu cầu trả về.
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
1Thuộc tính_______32_______1 hoặc
[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
2URL cuối cùng sau khi thực hiện yêu cầu

VD

import requests

r = requests.get["//ip-api.com/json"]

#request: //toidicode.com/?post_id=135

print[r.apparent_encoding]
# print[r.content]
print[r.encoding]
print[r.cookies]
print[r.elapsed]
print[r.encoding]
print[r.headers]
print[r.history]
print[r.is_permanent_redirect]
print[r.iter_content[]]
print[r.links]
print[r.raise_for_status[]]
print[r.json[]]

Kết quả trả lại

ascii
utf-8

0:00:00.165961
utf-8
{'Content-Length': '271', 'Date': 'Mon, 17 Sep 2018 01:33:24 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*'}
[]
False

{}
None
{'as': 'AS7552 Viettel Group', 'zip': '', 'regionName': 'Hanoi', 'lat': 21.0333, 'country': 'Vietnam', 'status': 'success', 'timezone': 'Asia/Ho_Chi_Minh', 'lon': 105.85, 'countryCode': 'VN', 'org': 'Viettel Group', 'city': 'Hanoi', 'isp': 'Viettel Group', 'region': 'HN', 'query': '117.4.242.101'}

Các ngoại lệ có thể xảy ra

ascii
utf-8

0:00:00.165961
utf-8
{'Content-Length': '271', 'Date': 'Mon, 17 Sep 2018 01:33:24 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*'}
[]
False

{}
None
{'as': 'AS7552 Viettel Group', 'zip': '', 'regionName': 'Hanoi', 'lat': 21.0333, 'country': 'Vietnam', 'status': 'success', 'timezone': 'Asia/Ho_Chi_Minh', 'lon': 105.85, 'countryCode': 'VN', 'org': 'Viettel Group', 'city': 'Hanoi', 'isp': 'Viettel Group', 'region': 'HN', 'query': '117.4.242.101'}
8 - Có một lỗi nào đó xảy ra trong quá trình thực hiện yêu cầu của bạn

ascii
utf-8

0:00:00.165961
utf-8
{'Content-Length': '271', 'Date': 'Mon, 17 Sep 2018 01:33:24 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*'}
[]
False

{}
None
{'as': 'AS7552 Viettel Group', 'zip': '', 'regionName': 'Hanoi', 'lat': 21.0333, 'country': 'Vietnam', 'status': 'success', 'timezone': 'Asia/Ho_Chi_Minh', 'lon': 105.85, 'countryCode': 'VN', 'org': 'Viettel Group', 'city': 'Hanoi', 'isp': 'Viettel Group', 'region': 'HN', 'query': '117.4.242.101'}
9 - Lỗi kết nối

import requests

r = requests.get["//ip-api.com/json"]

#request: //toidicode.com/?post_id=135

print[r.apparent_encoding]
# print[r.content]
print[r.encoding]
print[r.cookies]
print[r.elapsed]
print[r.encoding]
print[r.headers]
print[r.history]
print[r.is_permanent_redirect]
print[r.iter_content[]]
print[r.links]
print[r.raise_for_status[]]
print[r.json[]]
3 - Có lỗi HTTP xảy ra

[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
01 -  URL của bạn không chính xác

[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
02 - Yêu cầu chuyển hướng quá nhiều lần

[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
03 - Ngược lại bị timeout

[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
04 - Máy chủ không trả về dữ liệu trì hoãn trong khoảng thời gian được phân bổ

[email protected]_info:~$ python3
Python 3.5.2 [default, Nov 23 2017, 16:37:01] 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> 
05 - Request is timeout [Nên sử dụng ngoại lệ này để bắt cả ConectionTimeout và ReadTimeout nếu bạn muốn rút ngắn mã]

4, Kết quả

Phần trên mới chỉ là một phần giới thiệu nhanh gọn về yêu cầu mô-đun thôi, nếu như bạn cần tìm hiểu sâu hơn về mô-đun này thì hãy lên trang chủ của nó. Cảm ơn, chúc may mắn

Đăng ký nhận tin

Chúng tôi chỉ gửi tối đa 2 lần trong 1 tháng. Tuyên bố không spam mail

Đăng ký

TRƯNG NÂNG CAO

Bài trước   Bài sau

8 nhận xét 766 lượt thích

Vũ Thành Tài

Về tác giả

Cách học tốt nhất là chia sẻ

Xem tất cả bài đăng

Bài Viết Mới

  • Những tính năng mới trong PHP 8. 1

    1 năm trước 7 Nhận xét

  • Bài 39. Bộ đệm trong Laravel 8

    2 năm trước 1 Nhận xét

  • PHP Swoole là gì?

    2 năm trước 0 Nhận xét

  • Cài đặt SSL trên local sử dụng mkcert

    2 năm trước 4 Nhận xét

8 bình luận

bạn ơi cho mình hỏi khi chạy nó báo lỗi "AttributeError. module 'requests' không có thuộc tính 'get'", mình đã install và import thư viện request vào rồi mà vẫn bị, ko biết ntn nữa

Chủ Đề