### Initialize PyOData Client with Requests Session Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Demonstrates basic PyOData client initialization using a requests.Session object for synchronous HTTP requests. This is the standard way to get started with PyOData. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' northwind = pyodata.Client(SERVICE_URL, requests.Session()) ``` -------------------------------- ### Local Development and Testing Workflow in PyOData Source: https://github.com/sap/python-pyodata/blob/master/CONTRIBUTING.md This section details the local testing workflow for PyOData, which mirrors the CI process. It involves setting up a virtual environment, installing dependencies, and running tests and linters. ```shell virtualenv venv . venv/bin/activate pip install -r dev-requirements.txt pip install -r requirements.txt pytest --cov-report term --cov=pyodata pylint --rcfile=.pylintrc --output-format=parseable --reports=no pyodata flake8 --config=.flake8 pyodata ``` -------------------------------- ### Install pyodata using pip Source: https://github.com/sap/python-pyodata/blob/master/README.md This command installs and updates the pyodata Python module using pip. It's the standard way to get the library for use in Python projects. ```bash pip install -U pyodata ``` -------------------------------- ### Locust Integration with PyOData for Load Testing Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/urls.rst An example of using PyOData to generate URLs and query parameters for Locust load testing. It demonstrates how to create a PyOData client, define a query, and use it within a Locust HttpUser task. ```python import requests import pyodata import os from locust import HttpUser, task, between SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' odataClient = pyodata.Client(SERVICE_URL, requests.Session()) smith_employees_query = odataClient.entity_sets.Employees.get_entities().filter("FirstName eq 'John' and LastName eq 'Smith'") class MyUser(HttpUser): wait_time = between(5, 15) host = SERVICE_URL @task(1) def filter_query(self): urlpath = smith_employees_query.get_path() url = os.path.join(SERVICE_URL,urlpath) params = smith_employees_query.get_query_params() self.client.get(url,params=params) ``` -------------------------------- ### Set Custom Namespaces in pyodata Client (Deprecated) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Provides an example of how to set custom XML namespaces for a pyodata client, specifically when dealing with services hosted on non-standard URLs. Note that this method is deprecated and using the `config` parameter is recommended. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' namespaces = { 'edmx': 'customEdmxUrl.com', 'edm': 'customEdmUrl.com' } northwind = pyodata.Client(SERVICE_URL, requests.Session(), namespaces=namespaces) ``` -------------------------------- ### Dynamically Access EntitySet using getattr (Python) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/advanced.rst Shows how to dynamically get an EntitySet proxy using `getattr`. This is useful when the EntitySet name is not known until runtime or when iterating over multiple EntitySets. ```python count = getattr(northwind.entity_sets, 'Employees').get_entities().count().execute() print(count) ``` -------------------------------- ### Get EntitySet names using pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/metadata.rst This snippet shows how to create a list of EntitySet names from a service schema using a list comprehension. It extracts the 'name' attribute for each entity set. ```python entity_set_names = [es.name for es in service.schema.entity_sets] ``` -------------------------------- ### Get all entities with selection in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Retrieves all entities from an entity set, but selects only specific fields (e.g., EmployeeID and LastName) to optimize data transfer. ```python employees = northwind.entity_sets.Employees.get_entities().select('EmployeeID,LastName').execute() for employee in employees: print(employee.EmployeeID, employee.LastName) ``` -------------------------------- ### Get entities and total count with pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Fetches entities while also returning the total count of matching entities. This is efficient for paginated results where you need both the data and the total number of items. ```python employees = northwind.entity_sets.Employees.get_entities().count(inline=True).execute() print(employees.total_count) for employee in employees: print(employee.EmployeeID, employee.LastName) ``` -------------------------------- ### Get single entity by key with pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Retrieves a single entity from an entity set using its key. This is useful for fetching specific records like an employee by their ID. ```python employee1 = northwind.entity_sets.Employees.get_entity(1).execute() print(employee1.FirstName) ``` -------------------------------- ### Get entity count with pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Retrieves the total count of entities in an entity set, useful for knowing the number of records without fetching them all. ```python count = northwind.entity_sets.Employees.get_entities().count().execute() print(count) ``` -------------------------------- ### Get single entity with non-scalar key in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Fetches a single entity where the key is composed of multiple values, such as an order detail identified by both OrderID and ProductID. ```python order = northwind.entity_sets.Order_Details.get_entity(OrderID=10248, ProductID=42).execute() print(order.Quantity) ``` -------------------------------- ### Filter entities with pyodata ORM style (contains/startswith) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Applies filters using ORM style with operators like `contains` and `startswith` for partial string matching, allowing flexible queries like finding names containing 'oh' and starting with 'Smi'. ```python from pyodata.v2.service import GetEntitySetFilter as esf smith_employees_request = northwind.entity_sets.Employees.get_entities() smith_employees_request = smith_employees_request.filter(FirstName__contains="oh", LastName__startswith="Smi") for smith in smith_employees_request.execute(): print(smith.EmployeeID) ``` -------------------------------- ### Get entities and count via navigation property in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Retrieves entities linked by a navigation property and includes the total count of these related entities. This is useful for displaying related data and its total quantity, like orders for an employee. ```python orders = northwind.entity_sets.Employees.get_entity(1).nav('Orders').get_entities().count(inline=True).execute() print(orders.total_count) for order in orders: print(order.OrderID, order.ProductID) ``` -------------------------------- ### Simplify Entity Creation with create_entity() Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Demonstrates a more concise way to create entities by passing properties directly to the create_entity method, reducing the need for a separate set() call. ```python create_request = northwind.entity_sets.Employees.create_entity() create_request.set(**employee_data) ``` ```python create_request = northwind.entity_sets.Employees.create_entity(**employee_data) ``` -------------------------------- ### Prepare Certificate Files for Authentication (Bash) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Provides bash commands using OpenSSL to extract public key, private key, and CA certificates from a PKCS#12 file (mycert.p12), essential for certificate-based authentication. ```bash openssl pkcs12 -in mycert.p12 -out ca.pem -cacerts -nokeys openssl pkcs12 -in mycert.p12 -out client.pem -clcerts -nokeys openssl pkcs12 -in mycert.p12 -out key.pem -nocerts openssl rsa -in key.pem -out key_decrypt.pem ``` -------------------------------- ### Initialize PyOData Client and Query Customers Source: https://github.com/sap/python-pyodata/blob/master/docs/index.rst Demonstrates how to initialize a PyOData client using the requests library and query customer data from the Northwind OData service. It iterates through the results and prints customer ID and company name. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' HTTP_LIB = requests.Session() northwind = pyodata.Client(SERVICE_URL, HTTP_LIB) for customer in northwind.entity_sets.Customers.get_entities().execute(): print(customer.CustomerID, customer.CompanyName) ``` -------------------------------- ### Verify Certificate Authentication with Curl Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Shows how to use curl with the extracted certificate files (key_decrypt.pem, ca.pem, client.pem) to test certificate-based authentication against an OData service endpoint. ```bash curl --key key_decrypt.pem --cacert ca.pem --cert client.pem -k 'SERVICE_URL/$metadata' ``` -------------------------------- ### Initialize PyOData Client with Local Metadata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Explains how to initialize a PyOData client using a local metadata XML file. The file content must be provided as bytes to the 'metadata' argument during client instantiation. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' with open('/the/file/path.xml', 'rb') as mtd_file: local_metadata = mtd_file.read() northwind = pyodata.Client(SERVICE_URL, requests.Session(), metadata=local_metadata) ``` -------------------------------- ### Initialize PyOData Async Client with httpx or aiohttp Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Shows how to initialize PyOData clients for asynchronous operations using either the httpx or aiohttp libraries. This requires using the build_async_client class method. ```python import httpx import aiohttp import pyodata SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' service_httpx = await pyodata.Client.build_async_client(SERVICE_URL, httpx) service_aiohttp = await pyodata.Client.build_async_client(SERVICE_URL, aiohttp.ClientSession()) ``` -------------------------------- ### Entity Set Proxy Execute Accepts Query Parameters Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Demonstrates passing query parameters like select, filter, and expand directly to the execute() method of an entity set proxy. ```python client.entity_sets.Employees.get_entities().select('City,Orders').filter("Country eq 'USA'").expand('Orders').execute() ``` ```python client.entity_sets.Employees.get_entities().execute(select='City,Orders', filter="Country eq 'USA'", expand='Orders') ``` -------------------------------- ### Connect to SAP BTP OData Service with pyodata.vendor.SAP Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/vendors.rst Demonstrates how to use the SAP helper to create a pyodata client for an OData service on SAP BTP, ABAP environment. It requires service key details, user credentials, and a requests.Session object. ```python import pyodata from pyodata.vendor import SAP import requests import json with open('key.txt', 'r') as f: KEY = json.loads(f.read()) USER = "MyBtpUser" PASSWORD = "MyBtpPassword" SERVICE_URL = KEY["url"] + "/sap/opu/odata/sap/" + "ZMyBtpService" session = SAP.add_btp_token_to_session(requests.Session(), KEY, USER, PASSWORD) # do something more with session object if necessary (e.g. adding sap-client parameter, or CSRF token) client = pyodata.Client(SERVICE_URL, session) ``` -------------------------------- ### Initialize PyOData Client with Sap-Client Parameter Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Illustrates how to initialize a PyOData client when the OData service requires a specific 'sap-client' parameter, which is configured directly on the requests.Session. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' session = requests.Session() param = {'sap-client': '510'} session.params = param northwind = pyodata.Client(SERVICE_URL, session) ``` -------------------------------- ### Enable Logging with Python's logging Module (Python) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/advanced.rst Demonstrates how to enable detailed logging for the pyodata library by configuring Python's built-in `logging` module. It sets up basic configuration and increases the root logger's level to DEBUG. ```python import logging logging.basicConfig() root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) ``` -------------------------------- ### Create pyodata Client Instance Source: https://github.com/sap/python-pyodata/blob/master/README.md This Python code snippet shows how to import the pyodata module and create an OData client instance. It requires the 'requests' library and a valid OData service URL. ```python import requests import pyodata SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' # Create instance of OData client client = pyodata.Client(SERVICE_URL, requests.Session()) ``` -------------------------------- ### Execute Batch Request with Multiple Entity Queries (Python) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/advanced.rst Demonstrates how to create a batch request containing multiple individual entity queries. The response contains results for each query in the order they were added. ```python batch = northwind.create_batch() batch.add_request(northwind.entity_sets.Employees.get_entity(108)) batch.add_request(northwind.entity_sets.Employees.get_entity(234)) batch.add_request(northwind.entity_sets.Employees.get_entity(23)) response = batch.execute() print(response[0].EmployeeID, response[0].LastName) print(response[1].EmployeeID, response[1].LastName) print(response[2].EmployeeID, response[2].LastName) ``` -------------------------------- ### Function Import Proxy as Callable Request Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Shows that function import proxies are callable and can directly accept parameters, simplifying function call syntax. ```python products = northwind.functions.GetProductsByRating.parameter('rating', 16).execute() ``` ```python products = northwind.functions.GetProductsByRating(rating=16).execute() ``` -------------------------------- ### Initialize PyOData Client with Basic Authentication Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Demonstrates initializing a PyOData client for a service requiring basic HTTP authentication. This involves setting the 'auth' attribute of the requests.Session with username and password. ```python import pyodata import requests SERVICE_URL = 'https://odata.example.com/Secret.svc' session = requests.Session() session.auth = ('MyUser', 'MyPassword') theservice = pyodata.Client(SERVICE_URL, session) ``` -------------------------------- ### Initialize Session with CSRF Token using Requests Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/creating.rst Initializes a Python Requests session and fetches a CSRF token required for making POST requests to protected OData services. It then updates the session headers with the obtained token and creates a pyodata client. ```python import pyodata import requests SERVICE_URL = 'http://example.io/TheServiceRoot/' session = requests.Session() response = session.head(SERVICE_URL, headers={'x-csrf-token': 'fetch'}) token = response.headers.get('x-csrf-token', '') session.headers.update({'x-csrf-token': token}) theservice = pyodata.Client(SERVICE_URL, session) ``` -------------------------------- ### Initialize PyOData Client with Certificate Authentication Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Details the Python initialization of a PyOData client using certificate-based authentication. It configures the requests.Session with 'verify' for CA certificates and 'cert' for client certificate and key. ```python import pyodata import requests SERVICE_URL = 'https://odata.example.com/Secret.svc' session = requests.Session() session.verify = 'ca.pem' session.cert = ('client.pem', 'key_decrypt.pem') client = pyodata.Client(SERVICE_URL, session) ``` -------------------------------- ### Server-Side Pagination with __next in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Illustrates how to handle server-side pagination in pyodata using the '__next' field in responses. It shows how to fetch entities in batches and continue fetching until all entities are retrieved. ```python employees = northwind.entity_sets.Employees.get_entities().select('EmployeeID,LastName').execute() while True: for employee in employees: print(employee.EmployeeID, employee.LastName) # Stop if server has no more entities left if employees.next_url is None: break # We got a partial answer - continue with next page employees = northwind.entity_sets.Employees.get_entities().next_url(employees.next_url).execute() ``` -------------------------------- ### Entity Set Proxy as Request (No get_entities) Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Illustrates that entity set proxies can directly act as requests, removing the need for the explicit get_entities() method when querying. ```python data = client.entity_sets.Releases.get_entities().select('releaseId,releaseName,releaseType').execute() ``` ```python data = client.entity_sets.Releases.select('releaseId,releaseName,releaseType').execute() ``` -------------------------------- ### Access Entity Sets Directly (No entity_sets Proxy) Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Shows how to access entity sets directly from the client object, eliminating the intermediate 'entity_sets' proxy for cleaner code. ```python data = client.entity_sets.Releases.get_entities().select('releaseId,releaseName,releaseType').execute() ``` ```python data = client.Releases.get_entities().select('releaseId,releaseName,releaseType').execute() ``` -------------------------------- ### PyOData URL and Request Body Methods Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/urls.rst Demonstrates methods from the ODataHttpRequest class to retrieve URL components and request bodies without making HTTP requests. Useful for integrating with other libraries. ```python .get_method() .get_path() .get_query_params() .get_body() ``` -------------------------------- ### Access Function Imports Directly (No functions Proxy) Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Demonstrates accessing function imports directly from the client object, removing the 'functions' proxy for improved readability. ```python products = northwind.functions.GetProductsByRating.parameter('rating', 16).execute() ``` ```python products = northwind.GetProductsByRating.parameter('rating', 16).execute() ``` -------------------------------- ### Entity Set Proxy as Callable for Single Entity (No get_entity) Source: https://github.com/sap/python-pyodata/wiki/Next-Version-TODOs Illustrates that entity set proxies can be called directly to retrieve a single entity by its key, removing the need for get_entity(). ```python customer = client.entity_sets.Customers.get_entity('ALFKI').execute() ``` ```python customer = client.entity_sets.Customers('ALFKI').execute() ``` -------------------------------- ### Configure pyodata Client with Custom Parser Policies Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Demonstrates how to configure the pyodata client with custom parser policies for handling XML errors, including default policies and specific policies for different parser error types. This uses the Config object and various Policy enums. ```python import pyodata from pyodata.v2.model import PolicyFatal, PolicyWarning, PolicyIgnore, ParserError, Config import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' namespaces = { 'edmx': 'customEdmxUrl.com', 'edm': 'customEdmUrl.com' } custom_config = Config( xml_namespaces=namespaces, default_error_policy=PolicyFatal(), custom_error_policies={ ParserError.ANNOTATION: PolicyWarning(), ParserError.ASSOCIATION: PolicyIgnore() }) northwind = pyodata.Client(SERVICE_URL, requests.Session(), config=custom_config) ``` -------------------------------- ### Execute Batch Request with Entity Query and Modification (Python) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/advanced.rst Shows how to combine a simple entity query with entity modifications (updates) within a single batch request. This allows for efficient grouping of read and write operations. ```python batch = northwind.create_batch() batch.add_request(northwind.entity_sets.Employees.get_entity(108)) changeset = northwind.create_changeset() changeset.add_request(northwind.entity_sets.Employees.update_entity(45).set(LastName='Douglas')) batch.add_request(changeset) response = batch.execute() print(response[0].EmployeeID, response[0].LastName) ``` -------------------------------- ### Handle HTTP Errors with PyOData (Python) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/advanced.rst Illustrates how to catch and handle `pyodata.exceptions.HttpError` when making requests. It shows how to access the response text from the exception object for detailed error information. ```python try: new_data = create_request.execute() except pyodata.exceptions.HttpError as ex: print(ex.response.text) ``` -------------------------------- ### Filter entities with pyodata GetEntitySetFilter (AND) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Applies filters in a more Pythonic way using `GetEntitySetFilter` for AND conditions between fields, such as finding employees with specific first and last names. ```python from pyodata.v2.service import GetEntitySetFilter as esf smith_employees_request = northwind.entity_sets.Employees.get_entities() smith_employees_request = smith_employees_request.filter(esf.and_( smith_employees_request.FirstName == 'Jonh', smith_employees_request.LastName == 'Smith')) for smith in smith_employees_request.execute(): print(smith.EmployeeID) ``` -------------------------------- ### Iterate EntitySets using pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/metadata.rst This snippet demonstrates how to iterate over all EntitySets in a service schema and print their names. It accesses the 'entity_sets' property of the schema object. ```python for es in service.schema.entity_sets: print(es.name) ``` -------------------------------- ### Delete Entity by EntityKey Object Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/deleting.rst Shows how to delete an entity by creating an `EntityKey` object, which encapsulates the entity's schema and key values, and then passing this object to the `delete_entity` function. The `execute()` method sends the DELETE request. ```python key = EntityKey(service.schema.entity_type('Employee'), ID=23) request = service.entity_sets.Employees.delete_entity(key=key) request.execute() ``` -------------------------------- ### Create Entity with Complex Type Property Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/creating.rst Demonstrates creating an OData entity with a complex type property using the pyodata library. The 'set' method is used to pass entity data, including nested dictionary structures for complex types. ```python employee_data = { 'FirstName': 'Mark', 'LastName': 'Goody', 'Address': { 'HouseNumber': 42, 'Street': 'Paradise', 'City': 'Heaven' } } create_request = northwind.entity_sets.Employees.create_entity() create_request.set(**employee_data) new_employee_entity = create_request.execute() ``` -------------------------------- ### Prevent Default Value Substitution in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Illustrates how to configure the pyodata client to retain null values instead of substituting them with default values when properties are missing. This is achieved by setting `retain_null=True` in the Config object. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' northwind = pyodata.Client(SERVICE_URL, requests.Session(), config=pyodata.v2.model.Config(retain_null=True)) unknown_shipped_date = northwind.entity_sets.Orders_Qries.get_entity(OrderID=11058, CompanyName='Blauer See Delikatessen').execute() print( f'Shipped date: {"unknown" if unknown_shipped_date.ShippedDate is None else unknown_shipped_date.ShippedDate}') ``` -------------------------------- ### Filter entities with pyodata ORM style (exact match) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Uses an ORM-like syntax for filtering entities based on exact matches for field values, simplifying queries for conditions like `FirstName='John'` and `LastName='Smith'`. ```python from pyodata.v2.service import GetEntitySetFilter as esf smith_employees_request = northwind.entity_sets.Employees.get_entities() smith_employees_request = smith_employees_request.filter(FirstName="John", LastName="Smith") for smith in smith_employees_request.execute(): print(smith.EmployeeID) ``` -------------------------------- ### Update Entity with PUT Request using pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/updating.rst Illustrates two methods for updating an entity using an HTTP PUT request with pyodata. The first method specifies the method as 'PUT' for a single call, and the second method sets the default update method for the service to 'PUT' for multiple requests. ```python update_request = northwind.entity_sets.Customers.update_entity(CustomerID='ALFKI', method='PUT') ``` ```python northwind.config['http']['update_method'] = 'PUT' ``` -------------------------------- ### Customize HTTP Error Handling in PyOData (Python) Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/advanced.rst Explains how to subclass `pyodata.exceptions.HttpError` to provide custom error messages or handling logic. This is useful for tailoring error reporting to specific backend implementations. ```python from pyodata.exceptions import HttpError class MyHttpError(HttpError): def __init__(self, message, response): super(MyHttpError, self).__init__('Better message', response) HttpError.VendorType = MyHttpError ``` -------------------------------- ### Check pyodata Schema Validity Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/initialization.rst Shows how to access the 'is_valid' attribute of the pyodata schema object to determine if the parser encountered any errors during schema processing. This attribute's value is independent of the parser policies used. ```python northwind.schema.is_valid ``` -------------------------------- ### Add custom OData query parameters in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Enriches HTTP requests with non-standard OData query parameters using the `custom` method. This allows interaction with services that implement extensions to the OData model. ```python employee = northwind.entity_sets.Employees.get_entity(1).custom('sap-client', '100').execute() ``` ```python employees = northwind.entity_sets.Employees.get_entities().custom('sap-client', '100').custom('$skiptoken', 'ABCD').top(10).execute() ``` -------------------------------- ### Filter entities by string match in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Fetches entities that match a specific string condition in one or more fields, like finding employees named 'John Smith'. ```python smith_employees_request = northwind.entity_sets.Employees.get_entities() smith_employees_request = smith_employees_request.filter("FirstName eq 'John' and LastName eq 'Smith'") for smith in smith_employees_request.execute(): print(smith.EmployeeID) ``` -------------------------------- ### Update Entity with PATCH Request using pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/updating.rst Demonstrates how to update an existing entity in an OData service using an HTTP PATCH request. It involves creating an update request, setting new property values, and executing the request. Dependencies include the pyodata and requests libraries. ```python import pyodata import requests SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' northwind = pyodata.Client(SERVICE_URL, requests.Session()) update_request = northwind.entity_sets.Customers.update_entity(CustomerID='ALFKI') update_request.set(CompanyName='Alfons Kitten') update_request.execute() ``` -------------------------------- ### Delete Entity by PropertyRef Value Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/deleting.rst Demonstrates how to delete a specific entity from an entity set by providing its PropertyRef value directly to the `delete_entity` function. The `execute()` method sends the DELETE request. ```python request = service.entity_sets.Employees.delete_entity(23) request.execute() ``` -------------------------------- ### Disable Path Encoding in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Demonstrates how to disable percent encoding for resource paths in pyodata requests by setting the 'encode_path' variable to False. This is useful when the API does not expect encoded paths. ```python employee = northwind.entity_sets.Employees.get_entity(1, encode_path=False).execute() ``` -------------------------------- ### Verify Property Label in pyodata Schema Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/metadata.rst This snippet verifies that a specific property ('CustomerID') within an entity type ('Customer') has the expected label ('Identifier'). It accesses nested properties through the schema object. ```python assert northwind.schema.entity_type('Customer').proprty('CustomerID').label == 'Identifier' ``` -------------------------------- ### Count entities via navigation property in pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/querying.rst Counts entities related through a navigation property, such as counting all orders associated with a specific employee. ```python count = northwind.entity_sets.Employees.get_entity(1).nav('Orders').get_entities().count().execute() print(count) ``` -------------------------------- ### Explicitly Create Entity with Complex Type Property Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/creating.rst Provides an alternative method for creating an OData entity with a complex type property by explicitly calling the 'set' method with keyword arguments for each property, including the nested dictionary for the complex type. ```python create_request = northwind.entity_sets.Employees.create_entity() create_request.set( FirstName='Mark', LastName='Goody', Address={ 'HouseNumber': 42, 'Street': 'Paradise', 'City': 'Heaven' } ) new_employee_entity = request.execute() ``` -------------------------------- ### Check Property Value Helper in pyodata Schema Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/metadata.rst This snippet checks if a specific property ('City') within an entity type ('Customer') has an associated value helper. It accesses the 'value_helper' attribute of the property object. ```python assert northwind.schema.entity_type('Customer').proprty('City').value_helper is not None ``` -------------------------------- ### Disable OData URL Path Encoding with pyodata Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/updating.rst Shows how to disable the default percent encoding of resource paths in OData requests using pyodata. This is useful when the API does not expect encoded paths. It is achieved by setting the 'encode_path' parameter to False. ```python update_request = northwind.entity_sets.Customers.update_entity(CustomerID='ALFKI', encode_path=False) ``` -------------------------------- ### Delete Entity with Disabled Path Encoding Source: https://github.com/sap/python-pyodata/blob/master/docs/usage/deleting.rst Illustrates how to disable the default percent-encoding of resource paths in OData requests by setting the `encode_path` parameter to `False` in the `delete_entity` function. This is useful when the API expects unencoded paths. ```python request = service.entity_sets.Employees.delete_entity(key=key, encode_path=False) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.