79552193

Date: 2025-04-03 06:58:28
Score: 0.5
Natty:
Report link

The from x import y import mechanism in Python is specifically designed to work with Python modules (.py files). It looks for a module named x and then imports the name y defined inside it.
A .pem file is simply a text file containing data and not a Python module, you cannot directly use this import syntax to access its contents.
Instead, you should read the .pem file's content within a Python module located (for example) in your lib directory and then import that content.

Make a new Python file in your lib directory called sharepoint_credentials.py.

import os

def load_sharepoint_key(filename="sharepoint_key.pem"):
    filepath = os.path.join(os.path.dirname(__file__), filename)  # sharepoint_key.pem file in the lib directory
    try:
        with open(filepath, 'r') as f:
            private_key = f.read().strip()
        return private_key
    except FileNotFoundError:
        print(f"Error: File not found at {filepath}")
        return None

SHAREPOINT_PRIVATE_KEY = load_sharepoint_key()

You can now access the content by importing it into your various Python scripts.

import sys, os

current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_dir, "..", "..", ".."))
import __root__

from lib.sharepoint_credentials import SHAREPOINT_PRIVATE_KEY, load_sharepoint_key

if SHAREPOINT_PRIVATE_KEY:
    print("Loaded SharePoint Private Key:")
    print(SHAREPOINT_PRIVATE_KEY)
else:
    print("Failed to load SharePoint Private Key.")

# Or you can call the function directly if needed
key = load_sharepoint_key()
if key:
    # Use key

While the method of calculating the current directory and appending to `sys.path` can enable imports from your `lib` directory across various script locations, it's important to understand that this approach has limitations and it's not the most Pythonic way to handle module dependencies.
It doesn't clearly establish a "project root". Instead, it depends on navigating up the directory tree using relative path counting. Consequently, any changes to your project's folder organization will necessitate manually adjusting the number of `..` segments in your `os.path.join` calls across all your scripts. Have we considered turning `lib` into a Python package?
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
Posted by: Lewis