1659810600
Requests in Pythonは、あらゆる種類の HTTP リクエストを送信するために使用できるモジュールです。使い方は簡単で、人に優しい HTTP ライブラリです。リクエスト ライブラリの使用。URL にクエリ文字列を手動で追加する必要はありません。この記事では、リクエスト ライブラリのさまざまな機能と、get および post リクエストの作成方法について学習します。
インストール
まず、システムに pipenv をインストールしてから、次のコマンドを入力します。
$ pip install requests
HTTP GET 要求は通常、サーバーのデータを取得するために使用されます。リクエストから受け取ったコンテンツを使用して、API から取得したデータのリストをレンダリングしたり、クエリ文字列に基づいて製品のリストをフィルタリングしたりできます。
構文:
import requests
r=requests.get(url)
get リクエストを作成するには、まずリクエスト ライブラリをインポートしてから、レスポンス オブジェクト 'r' を作成します。次に、「URL」を get 関数に渡します。応答オブジェクト「r」には、URL から受信したすべての情報が含まれます。例えば、
URL でパラメーターを渡す:
URL パラメータは、ページに追加情報を動的に送信するために使用されます。
そのために、最初にキーと値のペアを含むディクショナリを作成しました。次に、次の例に示すように、辞書を params キーワードに渡します。
payload={"Name":"Harry","location":"USA"}
r=requests.get("https://httpbin.org/get", params=payload)
投稿のリクエストは、フォームからデータを送信したり、ファイルをアップロードしたりするときに最もよく使用されます。投稿リクエストは、リソースを作成または更新し、1 回のリクエストでより多くのコンテンツを送信できるように設計されています。
構文:
import requests
payload={key1:value1, key2:value2}
response=requests.post(url,data=payload)
まず、リクエストをインポートしてから、Post () リクエスト メソッドを使用してデータを渡します。最後に、データを URL と一緒に渡します。ポスト リクエストを介して渡す辞書は、サーバーに送信されます。
例:
payload={'title': "john",
'body': "John is an engineer",
'id': 101}
res2=requests.post('https://httpbin.org/post',data=payload)
print(res2.text)
{ "args": {}, "data": "", "files": {}, "form": { "body": "John is an engineer", "id": "101", "title": "john" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "42", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.23.0", "X-Amzn-Trace-Id": "Root=1-62ea4ab9-0f517641690c12251f337283" }, "json": null, "origin": "34.75.8.147", "url": "https://httpbin.org/post" }
ファイルの投稿:
リクエストを使用してファイルを簡単にアップロードできます。
import requests
files={'file':open('/content/data1.txt','rb')}
r=requests.post('https://httpbin.org/post',files=files)
ステータス コード:
ステータス コードにより、リクエストのステータスを知ることができます。サーバーは、サーバーに対するクライアントの要求に応答してステータス コードを発行します。ステータス コードにアクセスするには、以下に示すようにキーワードstatus_codeを使用します。
r.status_code
HTTP ステータス コード
1xx の範囲のステータス コードは、応答が情報提供であることを示します。2xx の範囲内にある場合は、要求が成功したことを示します。この範囲で、200 の場合は OK、201 は Created、202 は Accepted、203 は非正式な情報、204 は No Content などを示します。同様に、301 は永続的に移動されたことを示し、400 は不正な要求、401 は無許可、500 は内部サーバー エラーなどを示します。
バイナリ レスポンス コンテンツ
応答コンテンツにバイト単位 (テキスト以外) でアクセスするには、次を使用します。
print(r.content)
b'{n "args": {n "Name": "Harry", n "location": "USA"n }, n "headers": {n "Accept": "*/*", n "Accept-Encoding": "gzip, deflate", n "Host": "httpbin.org", n "User-Agent": "python-requests/2.23.0", n "X-Amzn-Trace-Id": "Root=1-62d53aa9-28ea914146efe4cb04727f3f"n }, n "origin": "34.73.170.219", n "url": "https://httpbin.org/get?Name=Harry&location=USA"n}n'
応答を文字列またはテキストの形式で表示するには、次を使用します
print(r.text)
{n "args": {n "Name": "Harry", n "location": "USA"n }, n "headers": {n "Accept": "*/*", n "Accept-Encoding": "gzip, deflate", n "Host": "httpbin.org", n "User-Agent": "python-requests/2.23.0", n "X-Amzn-Trace-Id": "Root=1-62d53aa9-28ea914146efe4cb04727f3f"n }, n "origin": "34.73.170.219", n "url": "https://httpbin.org/get?Name=Harry&location=USA"n}n
JSON (JavaScript オブジェクト表記):
要求ライブラリには、サーバーからの応答として送信される JSON コンテンツを処理する組み込みの JSON デコーダーがあります。JSON デコーダーを使用すると、JSON 応答を Python オブジェクトに解析できます。JSON 形式のデータは、カンマで区切られた名前と値のペアで保存されます。中括弧の使用はオブジェクトを示し、角括弧は配列を定義します。
例:
import requests
r=requests.get('https://api.coinbase.com/v2/currencies')
data=r.json()
print(data)
最初の要素を印刷するには、次を使用します
print(data['data'][0])
{‘id’: ‘AED’, ‘min_size’: ‘0.01000000’, ‘name’: ‘United Arab Emirates Dirham’}
サーバーに対して要求が行われると、応答オブジェクトには、要求内で追加情報を渡すヘッダーが含まれます。一般的なヘッダーの 1 つは content-type ヘッダーで、リソースのメディア タイプを示します。前の例 (JSON) で作成された応答オブジェクトのヘッダーを見てみましょう。
コンテンツ タイプをさらに調べたい場合は、次のコードを使用します。最初の文字を大文字にせずにコンテンツ タイプを指定することもできます。
print(r.headers['Content-Type'])
アプリケーション/json; 文字セット=utf-8
content-type のメディア タイプが「application/JSON」であることがわかりました。その他の一般的なメディア タイプには、「text/plain」、「text/javascript」、「multipart/form-data」などがあります。headers 関数を呼び出すと、応答オブジェクトからすべてのヘッダーの辞書が返されます。
以下に示すように、投稿リクエスト用のカスタム ヘッダーを作成することもできます。
headers={'content-type':'text/javascript'}
r=requests.post('https://httpbin.org/post',headers=headers)
print(r.request.headers)
{'User-Agent': 'python-requests/2.23.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'content-type': 'text/javascript', 'Content-Length': '0'}
requests ライブラリを使用すると、サーバーから HTTP Cookie を作成して読み取ることができます。Cookie は、サーバーがユーザーの Web ブラウザーに送信する小さなデータです。
cookies={'Status':'Active'}
r=requests.get('https://httpbin.org/cookies',cookies=cookies)
print(r.text){
"cookies": {
"Status": "Active"
}
}
RequestsCookieJar は、Cookie の送信先をカスタマイズできる特別な形式の辞書です。Cookie は RequestsCookiesJar で返されます。例を見てみましょう:
jar=requests.cookies.RequestsCookieJar()
jar.set('location','India',domain='httpbin.org',path='/cookies')
jar.set('Name','Harry',domain='httpbin.org',path='/profile')
r=requests.get('https://httpbin.org/cookies',cookies=jar)
print(r.text)
{
"cookies": {
"location": "India"
}
}
この例では、r.text を印刷するときに、パス「/cookies」を要求するため、1 つの Cookie のみを取得します。これは、複数のドメインまたはパスに Cookie を設定できる方法です。
場合によっては、リクエストが失敗することがあります。status_code を見て、応答が成功したかどうかを判断できます。一般的に発生する別の例外はタイムアウト例外です。応答しないサーバーが原因でプログラムがハングするのを防ぐため、要求ごとにタイムアウト値を定義することをお勧めします。
関数 response.raise_for_status() は、失敗した HTTP ステータス コードが返された場合に HTTPError を発生させます。
例えば、
セッションは、個々のユーザーのデータを保存するために使用されます。
サーバーに Cookie を設定するために使用できるセッション オブジェクトを作成します。このセッション オブジェクトが存続している限り、Cookie は複数の要求にわたってデータを保持します。
例:
import requests
#creating a session object
s=requests.Session()
cookis={'location':'India'}
r=s.get('https://httpbin.org/cookies/set',params=cookis)
#getting all the cookies
r=s.get('https://httpbin.org/cookies')
print(r.text)
{
"cookies": {
"location": "India"
}
}
この記事は、Python の requests ライブラリの完全なガイドです。GET や POST などのさまざまな HTTP メソッドを使用して、サーバーに基本的な要求を行う方法を学びました。また、ヘッダーをカスタマイズしてさまざまな Cookie を渡す方法も学びました。最後に、セッションでのリクエストの使用について学びました。要するに、
これが素晴らしいアプリケーションを構築するのに役立つことを願っています. より高度な概念については、ドキュメント https://requests.readthedocs.io を参照してください。
ソース: https://www.analyticsvidhya.com/blog/2022/08/introduction-to-requests-library-in-python/
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1602968400
Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?
In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.
Swapping value in Python
Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead
>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName
>>> print(FirstName, LastName)
('Jordan', 'kalebu')
#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development
1602666000
Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.
In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.
Heres a solution
Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.
But How do we do it?
If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?
The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.
There’s a variety of hashing algorithms out there such as
#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips
1597751700
Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…
You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).
Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.
class AnyClass:
def __init__():
print("Init called on its own")
obj = AnyClass()
The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.
The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.
Init called on its own
Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,
class AnyClass:
def __init__(self, var):
self.some_var = var
def __add__(self, other_obj):
print("Calling the add method")
return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2
#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python