🔍 Code Extractor

class OneNotePageCreateQuery

Maturity: 40

A specialized query class for creating OneNote pages with multipart form-data requests, handling presentation files and optional attachments.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/onenote/internal/multipart_page_query.py
Lines:
20 - 79
Complexity:
complex

Purpose

This class extends ClientQuery to handle the creation of OneNote pages through the Microsoft Graph API. It constructs multipart/form-data HTTP requests that include a required presentation file (typically HTML content) and optional attachment files. The class manages the complex process of building MIME multipart messages with proper boundaries, content types, and dispositions required by the OneNote API.

Source Code

class OneNotePageCreateQuery(ClientQuery):
    def __init__(self, pages, presentation_file, attachment_files=None):
        """
        :type pages: office365.onenote.pages.collection.OnenotePageCollection
        :type presentation_file: typing.IO
        :type attachment_files: dict or None
        """
        super(OneNotePageCreateQuery, self).__init__(pages.context, pages)
        pages.context.before_execute(self._construct_multipart_request)
        self._presentation = presentation_file
        if attachment_files is None:
            attachment_files = {}
        self._files = attachment_files

    def _construct_multipart_request(self, request):
        """
        :type request: office365.runtime.http.request_options.RequestOptions
        """
        request.method = HttpMethod.Post
        boundary = create_boundary("PageBoundary", True)
        request.set_header(
            "Content-Type", "multipart/form-data; boundary={0}".format(boundary)
        )

        main_message = Message()
        main_message.add_header(
            "Content-Type", "multipart/form-data; boundary={0}".format(boundary)
        )
        main_message.set_boundary(boundary)

        c_type, _enc = get_mime_type(self._presentation.name)
        presentation_message = Message()
        presentation_message.add_header("Content-Type", c_type)
        presentation_message.add_header(
            "Content-Disposition", 'form-data; name="Presentation"'
        )
        presentation_message.set_payload(self._presentation.read())
        main_message.attach(presentation_message)

        for name, file in self._files.items():
            file_message = Message()
            c_type, _enc = get_mime_type(file.name)
            file_message.add_header("Content-Type", c_type)
            file_message.add_header(
                "Content-Disposition", 'form-data; name="{0}"'.format(name)
            )
            file_content = file.read()
            file_message.set_payload(file_content)
            main_message.attach(file_message)

        request.data = _message_to_payload(main_message)

    @property
    def return_type(self):
        if self._return_type is None:
            from office365.onenote.pages.page import OnenotePage

            self._return_type = OnenotePage(self.context)
            self.binding_type.add_child(self._return_type)
        return self._return_type

Parameters

Name Type Default Kind
bases ClientQuery -

Parameter Details

pages: An OnenotePageCollection instance representing the collection to which the new page will be added. This provides the context and parent resource for the operation.

presentation_file: A file-like object (typing.IO) containing the presentation content for the OneNote page, typically HTML markup. Must have a 'name' attribute for MIME type detection and a 'read()' method to retrieve content.

attachment_files: Optional dictionary mapping attachment names (strings) to file-like objects. Each file must have 'name' and 'read()' attributes. Defaults to an empty dictionary if None is provided. Used for embedding images or other resources in the page.

Return Value

The constructor returns an instance of OneNotePageCreateQuery. The return_type property returns a OnenotePage instance representing the newly created page after the query executes successfully. This page object is automatically added as a child to the binding type and can be used to access the created page's properties.

Class Interface

Methods

__init__(self, pages: OnenotePageCollection, presentation_file: typing.IO, attachment_files: dict = None)

Purpose: Initializes the OneNote page creation query with presentation content and optional attachments

Parameters:

  • pages: OnenotePageCollection instance providing context and target collection
  • presentation_file: File-like object containing the page presentation (HTML content)
  • attachment_files: Optional dictionary mapping names to file-like objects for attachments

Returns: None (constructor)

_construct_multipart_request(self, request: RequestOptions) -> None

Purpose: Internal method that constructs the multipart/form-data HTTP request with presentation and attachments

Parameters:

  • request: RequestOptions object to be modified with multipart content

Returns: None (modifies request in-place)

@property return_type(self) -> OnenotePage property

Purpose: Lazy-loaded property that returns the OnenotePage instance representing the created page

Returns: OnenotePage instance that will contain the created page data after query execution

Attributes

Name Type Description Scope
_presentation typing.IO Stores the presentation file object containing the page content instance
_files dict Dictionary mapping attachment names to file-like objects for additional resources instance
_return_type OnenotePage or None Cached OnenotePage instance representing the query result, initialized on first access instance

Dependencies

  • office365
  • email

Required Imports

from office365.onenote.pages.collection import OnenotePageCollection
from office365.onenote.pages.page import OnenotePage
from office365.runtime.queries.client_query import ClientQuery

Conditional/Optional Imports

These imports are only needed under specific conditions:

from email.message import Message

Condition: Required internally for constructing multipart MIME messages

Required (conditional)
from office365.runtime.compat import get_mime_type

Condition: Required internally for determining file MIME types

Required (conditional)
from office365.runtime.http.http_method import HttpMethod

Condition: Required internally for setting HTTP method

Required (conditional)
from office365.runtime.queries.batch import create_boundary

Condition: Required internally for creating multipart boundaries

Required (conditional)

Usage Example

from office365.graph_client import GraphClient
from office365.onenote.pages.collection import OnenotePageCollection

# Authenticate and get client
client = GraphClient.with_token(lambda: 'your_access_token')

# Get the pages collection for a specific section
section_id = 'your_section_id'
pages = client.me.onenote.sections.get_by_id(section_id).pages

# Prepare presentation file (HTML content)
with open('page_content.html', 'rb') as presentation:
    # Optional: prepare attachments
    attachments = {
        'image1': open('image1.png', 'rb')
    }
    
    # Create the query
    query = OneNotePageCreateQuery(pages, presentation, attachments)
    
    # Execute the query (typically done through the context)
    pages.context.execute_query()
    
    # Access the created page
    new_page = query.return_type
    print(f'Created page: {new_page.title}')

Best Practices

  • Always ensure presentation_file is a file-like object with 'name' and 'read()' attributes before instantiation
  • Close file handles properly after query execution to prevent resource leaks
  • The query automatically registers a before_execute hook, so instantiation triggers request construction setup
  • The return_type property should only be accessed after query execution to get the created page
  • Attachment files dictionary keys become the 'name' attribute in the multipart form-data
  • File MIME types are automatically detected from file names, so ensure files have proper extensions
  • The query modifies the request object during execution through the _construct_multipart_request callback
  • This class is designed to be used once per page creation; create new instances for multiple pages
  • The parent pages collection context must be properly authenticated before instantiation

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class OnenotePageCollection 70.7% similar

    A collection class for managing OneNote pages within a OneNote notebook, providing methods to create and manage multiple OnenotePage instances.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/onenote/pages/collection.py
  • class OnenotePage 61.2% similar

    A page in a OneNote notebook.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/onenote/pages/page.py
  • class Onenote 58.9% similar

    The Onenote class serves as the entry point for accessing Microsoft OneNote resources through the Microsoft Graph API, providing access to notebooks, pages, sections, and other OneNote entities.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/onenote/onenote.py
  • class NotebookCollection 58.1% similar

    A collection class for managing OneNote notebooks, providing methods to create, retrieve, and query notebooks within Microsoft 365, SharePoint, or group contexts.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/onenote/notebooks/collection.py
  • class Notebook 56.4% similar

    Represents a OneNote notebook entity with access to its sections and section groups, providing a hierarchical structure for organizing OneNote content.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/onenote/notebooks/notebook.py
← Back to Browse