آشنایی با requests

  • مدرس: علی بیگدلی
  • تاریخ انتشار: Jan 09, 2021

کتابخانه Requests یکی از اجزای جدایی ناپذیر Python برای ایجاد درخواست های HTTP به یک URL مشخص است. خواه REST API باشد یا Web Scrapping ، برای ادامه کار با این فناوری ها باید درخواست ها را یاد گرفت. وقتی شخصی درخواستی را به URI می دهد ، پاسخ را برمی گرداند. درخواست های پایتون قابلیت های داخلی برای مدیریت درخواست و پاسخ را فراهم می کند.

request و response چگونه کار می کند؟

ارتباط HTTP شامل دو اصطلاح مهم است و Client و Server هستند.
clinet : آن است که درخواست HTTP را ارائه می دهد. به عنوان مثال مرورگر مشتری است.

server : سرور کسي است که درخواست را دريافت کرده و پاسخ را ارسال مي کند. در واقع سرور قطعه ای از کد است که وظیفه پذیرش درخواست و ارسال پاسخ را بر عهده دارد. معمولاً رایانه ای که کد سرور بر روی آن اجرا می شود ، سرور نامیده می شود. ارتباط ساده HTTP در زیر نشان داده شده است

 

چرا ماژول requests پایتون را یاد بگیریم؟

Requests یک کتابخانه HTTP دارای مجوز Apache2 است که امکان ارسال درخواست های HTTP / 1.1 را با استفاده از Python فراهم می کند.
برای کار با وب، Requests الزامی است. با استفادهاز آن می توان با api ها کار کرد و و اطلاعات بسیار مفیدی را از سرویس ها و یا صفحات تحت وب استخراج نمود.
درخواست ها نقش عمده ای دارند که با REST API و Web Scrapping سرو کار دارند.
همچنین مجموعه ای از کتابخانه ها به ما این دسترسی را برای webscrapping و  ساخت ربات هایی برای اتوماسین صفحات وب می دهند از جمله این ماژول ها عبارت اند از : 

  • Beautiful Soup
  • LXML
  • MechanicalSoup
  • Python Requests
  • Scrapy
  • Selenium
  • Urllib

که در دوره مجزای webscrapping و atumation با پایتون فرا خواهیم گرفت.

نصب کتابخانه requests

نصب requests  بستگی به نسخه سیستم عامل دارد اما در همه آن ها می توانید با استفاده از pip اقدام به نصب نمایید.

pip install requests

روش اصلی برای نصب requests  بر روی هر سیستم عامل ، گرفتن فایل های پایه و نصب دستی است و Requests به طور فعال در GitHub ، جایی که کد همیشه در دسترس است ، توسعه می یابد. برای رفتن به repo مربوطه  به اینجا مراجعه کنید.

متد های قابل اجرا با دستور requests:

Method Description
GET GET method is used to retrieve information from the given server using a given URI.
POST POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it
PUT The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI.
DELETE The DELETE method deletes the specified resource
HEAD The HEAD method asks for a response identical to that of a GET request, but without the response body.
PATCH It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource

مثال زیر نمونه ای ساده از یک request از نوع get است.

import requests 
   
# Making a GET request 
response = requests.get('https://api.github.com/users/alibigdeli') 
  
# check status code for response received 
# success code - 200 
print(response) 
  
# print content of request 
print(response.content) 

که خروجی مشابه زیر خواهد داشت:

<Response [200]>
b'{
  "login": "AliBigdeli",
  "id": 29748439,
  "node_id": "MDQ6VXNlcjI5NzQ4NDM5",
  "avatar_url": "https://avatars.githubusercontent.com/u/29748439?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/AliBigdeli",
  "html_url": "https://github.com/AliBigdeli",
  "followers_url": "https://api.github.com/users/AliBigdeli/followers",
  "following_url": "https://api.github.com/users/AliBigdeli/following{/other_user}",
  "gists_url": "https://api.github.com/users/AliBigdeli/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/AliBigdeli/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/AliBigdeli/subscriptions",
  "organizations_url": "https://api.github.com/users/AliBigdeli/orgs",
  "repos_url": "https://api.github.com/users/AliBigdeli/repos",
  "events_url": "https://api.github.com/users/AliBigdeli/events{/privacy}",
  "received_events_url": "https://api.github.com/users/AliBigdeli/received_events",
  "type": "User",
  "site_admin": false,
  "name": "TheAliBigdeli",
  "company": "icc-aria",
  "blog": "https://www.icc-aria.ir",
  "location": "iran,karaj",
  "email": null,
  "hireable": null,
  "bio": "I am Ali Bigdeli, my passion for development took me from networking manager to python programming and AI plus IOT contributer.",
  "twitter_username": null,
  "public_repos": 32,
  "public_gists": 0,
  "followers": 39,
  "following": 1,
  "created_at": "2017-06-28T07:21:45Z",
  "updated_at": "2022-01-05T10:36:42Z"
}'

اما هر object که از request ایجاد می شود می تواند دارای ویژگی های متعددی باشد که در بالا 2 مورد کد پاسخ یا response code و همچنین محتوای پاسخ را مشاهده می کنید.

کدهای وضعیت پاسخ HTTP نشان می دهد که آیا یک درخواست خاص HTTP با موفقیت انجام شده است. پاسخ ها در پنج کلاس گروه بندی می شوند:

  • پاسخ های اطلاعاتی (100–199) info
  • پاسخ های موفق (200–299) successful
  • هدایت (300-399) redirect
  • خطاهای مشتری (400–499) client errors
  • خطاهای سرور (500–599) server errors

که در بخش بعدی به طور کامل بررسی خواهیم کرد.

اما علاوه بر این کد شاخص های دیگری نیز در یک response گنجانده شده اند.

Method Description
response.headers response.headers returns a dictionary of response headers.
response.encoding response.encoding returns the encoding used to decode response.content.
response.elapsed response.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response.
response.close() response.close() closes the connection to the server.
response.content response.content returns the content of the response, in bytes.
response.cookies response.cookies returns a CookieJar object with the cookies sent back from the server.
response.history response.history returns a list of response objects holding the history of request (url).
response.is_permanent_redirect response.is_permanent_redirect returns True if the response is the permanent redirected url, otherwise False.
response.is_redirect response.is_redirect returns True if the response was redirected, otherwise False.
response.iter_content() response.iter_content() iterates over the response.content.
response.json() response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).
response.url response.url returns the URL of the response.
response.text response.text returns the content of the response, in unicode.
response.status_code response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found).
response.request response.request returns the request object that requested this response.
response.reason response.reason returns a text corresponding to the status code.
response.raise_for_status() response.raise_for_status() returns an HTTPError object if an error has occurred during the process.
response.ok response.ok returns True if status_code is less than 200, otherwise False.
response.links response.links returns the header links.
ثبت دیدگاه
نام *
ایمیل*
دیدگاه *
0دیدگاه