杰瑞科技汇

python localstorage

Of course! This is a very common point of confusion for developers coming from a web development background (JavaScript) to Python.

python localstorage-图1
(图片来源网络,侵删)

Let's break it down clearly.

The Short Answer

Python does not have a built-in localStorage equivalent.

localStorage is a web browser API. It's a feature of the JavaScript language that runs inside a web browser to store data on the user's computer. Python, being a general-purpose programming language, does not run inside a web browser by default and therefore doesn't have this API.


The Core Concept: Storing Data Locally in Python

The idea behind localStorage is to store small amounts of key-value data persistently on a user's machine. Python has several ways to achieve this, each suited for different use cases.

python localstorage-图2
(图片来源网络,侵删)

Here are the most common Python alternatives, ordered from simplest to most robust.


The Simplest Method: shelve (In-Memory Database)

The shelve module is perfect for this. It's built into Python and provides a simple dictionary-like interface for storing persistent data in a file.

Key Features:

  • Built-in library (no installation needed).
  • Stores data in a file.
  • Can store any Python object that can be pickled (strings, numbers, lists, dicts, etc.).
  • Very easy to use.

How it works:

python localstorage-图3
(图片来源网络,侵删)

You treat the "shelf" (the file) like a dictionary.

import shelve
# 'w' for write, 'c' for create if it doesn't exist, 'n' for new
# 'r' for read-only
with shelve.open('my_local_storage') as storage:
    # --- Storing data (like localStorage.setItem) ---
    storage['username'] = 'Alice'
    storage['user_id'] = 123
    storage['is_logged_in'] = True
    storage['settings'] = {'theme': 'dark', 'language': 'en'}
    print("Data stored successfully!")
# --- Retrieving data (like localStorage.getItem) ---
with shelve.open('my_local_storage') as storage:
    print(f"Username: {storage.get('username')}")
    print(f"User ID: {storage.get('user_id')}")
    print(f"Settings: {storage.get('settings')}")
    # --- Checking if a key exists (like localStorage.getItem) ---
    if 'theme' in storage:
        print(f"Theme found: {storage.get('theme')}")
    # --- Deleting an item (like localStorage.removeItem) ---
    del storage['is_logged_in']
    print("Deleted 'is_logged_in'")
# --- Confirming deletion ---
with shelve.open('my_local_storage') as storage:
    print(f"Is user logged in? {storage.get('is_logged_in', 'No')}")

Note: shelve sometimes creates multiple files (e.g., my_local_storage.db, my_local_storage.bak). This is normal.


The Most Common Method: json + File I/O

This is the most fundamental and widely understood way to handle persistent data in Python. You simply read from and write to a text file, using JSON to format the data.

Key Features:

  • Built-in library (json and open).
  • Human-readable data format (the file is just text).
  • Great for configuration files and simple data storage.

How it works:

import json
# Define a file name
DATA_FILE = 'user_data.json'
# --- Storing data (like localStorage.setItem) ---
data_to_store = {
    'username': 'Bob',
    'user_id': 456,
    'is_logged_in': False,
    'settings': {'theme': 'light', 'language': 'es'}
}
try:
    with open(DATA_FILE, 'w') as f:
        # json.dump writes the Python object to the file as a JSON string
        json.dump(data_to_store, f)
    print("Data stored to JSON file.")
except IOError as e:
    print(f"Error writing to file: {e}")
# --- Retrieving data (like localStorage.getItem) ---
try:
    with open(DATA_FILE, 'r') as f:
        # json.load reads the JSON string from the file and converts it to a Python object
        loaded_data = json.load(f)
    print(f"Username: {loaded_data.get('username')}")
    print(f"User ID: {loaded_data.get('user_id')}")
    print(f"Settings: {loaded_data.get('settings')}")
except FileNotFoundError:
    print("Data file not found. It's the first run.")
except json.JSONDecodeError:
    print("Error: Could not decode JSON from the file.")
except IOError as e:
    print(f"Error reading file: {e}")

The Powerful Method: sqlite3 (Relational Database)

If your data is more complex, or you need to query it efficiently, you should use a lightweight database. SQLite is perfect for this. It's a serverless, self-contained SQL database engine built into Python.

Key Features:

  • Built-in library (sqlite3).
  • Full power of SQL for querying, sorting, and joining data.
  • Excellent for structured data.
  • Much faster than file I/O for large or complex datasets.

How it works:

import sqlite3
# Connect to a database file (it will be created if it doesn't exist)
# The file extension is typically .db or .sqlite
conn = sqlite3.connect('app_database.db')
cursor = conn.cursor()
# --- Create a table (like setting up a schema) ---
cursor.execute('''
    CREATE TABLE IF NOT EXISTS user_settings (
        key TEXT PRIMARY KEY,
        value TEXT
    )
''')
# --- Storing data (like localStorage.setItem) ---
def set_item(key, value):
    cursor.execute("INSERT OR REPLACE INTO user_settings (key, value) VALUES (?, ?)", (key, str(value)))
    conn.commit()
# --- Retrieving data (like localStorage.getItem) ---
def get_item(key):
    cursor.execute("SELECT value FROM user_settings WHERE key = ?", (key,))
    result = cursor.fetchone()
    return result[0] if result else None
# --- Using the functions ---
set_item('username', 'Charlie')
set_item('user_prefs', {'notifications': True, 'fontSize': 14})
set_item('last_login', '2025-10-27T10:00:00Z')
username = get_item('username')
print(f"Username: {username}")
prefs = get_item('user_prefs')
print(f"User Preferences: {prefs}")
# Don't forget to close the connection when you're done
conn.close()

Summary: Which One Should You Use?

Method Best For... Pros Cons
shelve Quick, simple key-value storage, similar to localStorage. - Very easy to use.
- Built-in.
- Stores any Python object.
- Can be less efficient than JSON for simple data.
- Can create multiple files.
json + File Configuration files, settings, and simple data structures. - Human-readable.
- Universal standard.
- Simple and reliable.
- Not efficient for frequent reads/writes.
- Requires manual file handling.
sqlite3 Complex data, large datasets, or when you need to query data. - Powerful SQL queries.
- Very fast and efficient.
- Robust and scalable.
- More complex to set up and use.
- Overkill for very simple key-value pairs.

For a direct localStorage replacement, shelve is the closest and most convenient option. For simple configurations, json is the standard. For anything more serious, sqlite3 is the professional choice.

分享:
扫描分享到社交APP
上一篇
下一篇