Request and SYS library functions
Requests Library
The Requests library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.
Some key features of the Requests library include:
Sending HTTP Requests: Requests provides methods for sending various types of HTTP requests, such as
GET
,POST
,PUT
,DELETE
,HEAD
, andOPTIONS
. You can easily make requests to a specified URL and retrieve the response.Handling Responses: When a request is made, Requests returns a
Response
object that contains all the response data, including the content, encoding, status code, and headers. You can access and manipulate this data to extract the information you need.Customizing Requests: Requests allows you to customize your requests by setting headers, sending data in the request body, and passing parameters in the URL. You can also handle authentication, cookies, and file uploads/downloads.
Handling SSL Certificates: Requests automatically verifies SSL certificates by default, ensuring secure connections. You can also customize SSL certificate verification behavior if needed.
Session Management: Requests provides a
Session
object that allows you to persist certain parameters across multiple requests, such as cookies, headers, and authentication credentials. This is useful for maintaining session state and improving performance.
Requests Library:
requests.get(): Send a GET request
response = requests.get('https://api.example.com/data')
requests.post(): Send a POST request
response = requests.post('https://api.example.com/submit', data={'key': 'value'})
requests.put(): Send a PUT request
response = requests.put('https://api.example.com/update', data={'id': 1, 'name': 'John'})
requests.delete(): Send a DELETE request
response = requests.delete('https://api.example.com/remove/1')
response.status_code: Get the status code of the response
print(response.status_code)
response.text: Get the response content as text
print(response.text)
response.json(): Parse JSON content from the response
data = response.json()
response.headers: Get the headers of the response
print(response.headers)
requests.Session(): Create a session to persist parameters across requests
session = requests.Session() session.get('https://api.example.com/login')
requests.Request(): Construct a request object
req = requests.Request('GET', 'https://api.example.com/data')
requests.exceptions: Handle request exceptions
try: response = requests.get('https://api.example.com/data') except requests.exceptions.RequestException as e: print(e)
response.raise_for_status(): Raise an exception for unsuccessful status codes
response.raise_for_status()
requests.utils.dict_from_cookiejar(): Convert cookies to a dictionary
cookie_dict = requests.utils.dict_from_cookiejar(response.cookies)
requests.auth.HTTPBasicAuth(): Use HTTP Basic Authentication
response = requests.get('https://api.example.com/secure', auth=requests.auth.HTTPBasicAuth('user', 'pass'))
requests.head(): Send a HEAD request
response = requests.head('https://api.example.com/data')
sys Library
The sys
module in Python provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It allows you to interact with the Python interpreter and provides tools for working with the operating system.
Some key features of the sys
module include:
Command-Line Arguments: The
sys
module provides access to the command-line arguments passed to a Python script through thesys.argv
list. You can use this to pass arguments to your script and customize its behavior.Standard Input/Output/Error: The
sys
module gives you access to the standard input (sys.stdin
), output (sys.stdout
), and error (sys.stderr
) streams. You can use these to read input from the user, print output, or handle errors.Exit the Python Interpreter: The
sys
module allows you to exit the Python interpreter using thesys.exit()
function. You can specify an optional exit status code to indicate the success or failure of your script.Path Management: The
sys
module provides access to thesys.path
list, which contains the directories that the Python interpreter searches when it tries to import a module. You can modify this list to add or remove directories from the search path.Platform-Specific Information: The
sys
module provides information about the platform on which the Python interpreter is running, such as the version of Python, the operating system, and the machine architecture.
Both the Requests and sys
libraries are powerful tools in the Python ecosystem. The Requests library simplifies the process of making HTTP requests and interacting with web services, while the sys
module provides access to various Python interpreter and operating system features.
Now, let’s cover 15 important functions and attributes from the sys module:
sys.argv: Access command-line arguments
print(sys.argv[1]) # Print the first command-line argument
sys.exit(): Exit the Python interpreter
sys.exit(1) # Exit with status code 1
sys.path: List of directories Python looks in for modules
print(sys.path)
sys.version: Python version string
print(sys.version)
sys.platform: Identifier of the platform
print(sys.platform)
sys.stdin, sys.stdout, sys.stderr: Standard input, output, and error streams
sys.stdout.write("Hello, World!\n")
sys.modules: Dictionary of loaded modules
print(sys.modules.keys())
sys.executable: Path to the Python interpreter
print(sys.executable)
sys.getsizeof(): Get the size of an object in bytes
print(sys.getsizeof([1, 2, 3]))
sys.getrecursionlimit(): Get the maximum recursion depth
print(sys.getrecursionlimit())
sys.setrecursionlimit(): Set the maximum recursion depth
sys.setrecursionlimit(3000)
sys.maxsize: Largest integer supported by the platform’s Py_ssize_t type
print(sys.maxsize)
sys.flags: Information about command-line flags
print(sys.flags)
sys.float_info: Information about float type
print(sys.float_info)
sys.exc_info(): Information about the current exception
try: 1/0 except: type, value, traceback = sys.exc_info() print(type, value)
Citations:
[1] https://realpython.com/python-requests/
[2] https://www.codecademy.com/resources/docs/python/requests-module
[3] https://datasciencedojo.com/blog/requests-library/
[4] https://www.geeksforgeeks.org/python-requests-tutorial/
[5] https://www.javatpoint.com/python-requests-module-http-request