Package: custom-session
CustomSessionOverviewCustomSession is a Python package that provides a flexible and customizable HTTP client for making synchronous and
asynchronous HTTP requests. This package is built on top of the popular HTTP client librarys, httpx and requests, and
offers several features to simplify and enhance your HTTP requests.FeaturesSynchronous and Asynchronous Support: CustomSession provides both synchronous and asynchronous HTTP clientsRandom User-Agent: Randomly generated desktop user-agent for all requests sent by an HTTP clientProxy Support: CustomSession allows you to specify an HTTP/s proxy for all requests sent by an HTTP clientRetry Mechanism: Configure the number of retries for each request to handle exceptions gracefully.Exception Handling: Customize the exceptions to be ignored during retries, allowing you to manage specific error
conditions.Session Metadata: Store and manage miscellaneous session data as a dictionary, making it easier to maintain
context between requests.InstallationYou can install CustomSession using pip:$pipinstallcustom-sessionUsageSynchronous ClientHere's how you can use CustomSession synchronously:fromCustomSessionimportSyncSession# Create a synchronous sessionwithSyncSession()assession:response=session.get('https://example.com')print(response.text)Read morehereAsynchronous ClientTo use CustomSession asynchronously, you use it within an asynchronous context:importasynciofromCustomSessionimportAsyncSessionasyncdefmain():asyncwithAsyncSession()assession:response=awaitsession.get('https://example.com')print(response.text)# Run the asynchronous codeloop=asyncio.run(main())Read morehereAPI ReferenceSyncSessionOverviewSyncSessionis an synchronous HTTP client class in Python, inherited fromrequests.Sessionfromrequests. It is designed to simplify making HTTP requests with features such as
maintaining a unique user-agent, handling metadata, and optional proxy support.This class is particularly useful for building synchronous web scraping or web automation scripts.UsageTo use theSyncSessionclass, you should first import it and then create an instance of it. You can customize the
behavior of the session by passing optional parameters during initialization.fromCustomSessionimportSyncSession# Create an instance of SyncSessionsession=SyncSession(proxy="1.1.1.1",ignore_exceptions=(Exception,))Parametersproxy(optional): Specifies an HTTP/s proxy to use when sending requests.ignore_exceptions(optional): A tuple of exceptions to be ignored when sending requests. If an exception specified
in this tuple occurs during a request, it will be caught, and the request will be retried.user_agent(UserAgent, optional): A user agent for the session. Default is a randomly generated user agent for a
desktop device.meta_data(SessionMetaData | dict, optional): Additional metadata for the session. Default is an instance
ofSessionMetaDataor an empty dictionary.MethodsSyncSession provides several asynchronous HTTP request methods,
includingget,post,put,delete,patch,head, andoptions. These methods allow you to make various types
of HTTP requests and handle retries automatically in case of specified exceptions.get: Sends an HTTP GET request.post: Sends an HTTP POST request.put: Sends an HTTP PUT request.delete: Sends an HTTP DELETE request.patch: Sends an HTTP PATCH request.head: Sends an HTTP HEAD request.options: Sends an HTTP OPTIONS request.Each of these methods accepts parameters for request configuration and allows you to specify the number of retries in
case of exceptions.ExampleHere is an example of how to use theSyncSessionclass to send a GET request:fromCustomSessionimportSyncSession# Create an instance of SyncSessionsession=SyncSession()# Send a GET requestresponse=session.get("https://example.com")# Check the response status codeifresponse.status_code==200:print("Request was successful")else:print("Request failed")Exception HandlingTheSyncSessionclass handles exceptions during HTTP requests by retrying the request up to the specified number of
times (retriesparameter) if the exception matches any of the types listed inignore_exceptions. If the maximum
number of retries is reached, it raises aRetriesExceededexception with an error message indicating the number of
failed attempts.Please make sure to handleRetriesExceededexceptions appropriately in your code.fromCustomSessionimportSyncSession,RetriesExceededsession=SyncSession()try:response=session.get("https://example.com",retries=5)print("Request was successful")exceptRetriesExceededase:print(f"Request failed after{e.retries_attempted}attempts")AsyncSessionOverviewAsyncSessionis an asynchronous HTTP client class in Python, inherited fromhttpx.AsyncClientfromhttpx. It is designed to simplify making HTTP requests with features such as
maintaining a unique user-agent, handling metadata, and optional proxy support.This class is particularly useful for building asynchronous web scraping or web automation scripts.UsageTo use theAsyncSessionclass, you can create an instance of it using theasync withstatement, which allows you to
manage the lifecycle of the client. Here's a basic example of how to use it:importasynciofromCustomSessionsimportAsyncSessionasyncdefmain():asyncwithAsyncSession()asclient:response=awaitclient.get('https://example.org')print(response.text)if__name__=="__main__":asyncio.run(main())ParametersTheAsyncSessionclass accepts several optional parameters:proxy(optional): Specifies an HTTP/s proxy to use when sending requests.ignore_exceptions(optional): A tuple of exceptions to be ignored when sending requests. If an exception specified
in this tuple occurs during a request, it will be caught, and the request will be retried.auth(optional): An authentication class to use when sending requests. This allows you to provide authentication
credentials for requests, such as username and password.meta_data(optional): A dictionary or an instance ofSessionMetaDatathat can be used to store miscellaneous
session data. This data persists across requests and can be useful for storing session-specific information.MethodsAsyncSession provides several asynchronous HTTP request methods,
includingget,post,put,delete,patch,head, andoptions. These methods allow you to make various types
of HTTP requests and handle retries automatically in case of specified exceptions.get: Sends an HTTP GET request.post: Sends an HTTP POST request.put: Sends an HTTP PUT request.delete: Sends an HTTP DELETE request.patch: Sends an HTTP PATCH request.head: Sends an HTTP HEAD request.options: Sends an HTTP OPTIONS request.Each of these methods accepts parameters for request configuration and allows you to specify the number of retries in
case of exceptions.ExampleHere's an example of using thegetmethod with retries:asyncwithAsyncSession()asclient:response=awaitclient.get('https://example.org',retries=3)ifresponse.status_code==200:print(response.text)else:print("Request failed")In this example, thegetmethod is used to make a GET request tohttps://example.org, and it
will retry up to 3 times if certain exceptions specified in theignore_exceptionsparameter occur.Exception HandlingTheAsyncSessionclass handles exceptions during HTTP requests by retrying the request up to the specified number of
times (retriesparameter) if the exception matches any of the types listed inignore_exceptions. If the maximum
number of retries is reached, it raises aRetriesExceededexception with an error message indicating the number of
failed attempts.Please make sure to handleRetriesExceededexceptions appropriately in your code.fromCustomSessionimportAsyncSession,RetriesExceededsession=AsyncSession()try:asyncwithAsyncSession()asclient:response=awaitclient.get("https://example.com",retries=5)print("Request was successful")exceptRetriesExceededase:print(f"Request failed after{e.retries_attempted}attempts")