杰瑞科技汇

Python连接方法有哪些?

Of course! The term "Python connectivity" is broad, but it generally refers to the ability of Python applications to connect to and interact with other systems, databases, services, and devices.

Python连接方法有哪些?-图1
(图片来源网络,侵删)

I'll break this down into the most common areas of connectivity in Python, providing explanations, code examples, and popular libraries for each.


Database Connectivity

This is one of the most frequent tasks for Python applications, especially in backend development. Python uses database drivers (or connectors) to communicate with different database systems.

Key Concepts:

  • Driver/Connector: A library that translates Python commands into a language the database understands (e.g., SQL).
  • DB-API 2.0: A standard Python specification for database connections. Most modern drivers conform to this, making it easier to switch databases.
  • Connection Pooling: A technique to manage a pool of database connections to improve performance and reduce overhead.

a) Connecting to SQL Databases (PostgreSQL, MySQL, SQL Server, SQLite)

SQLite is a great starting point because it's built into Python and requires no separate server.

# --- SQLite Example (Built-in) ---
import sqlite3
# Connect to a database (it will be created if it doesn't exist)
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
                  (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
# Insert data
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Alice', 'alice@example.com'))
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Bob', 'bob@example.com'))
# Commit the changes
conn.commit()
# Query data
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
    print(row)
# Close the connection
conn.close()

For other SQL databases (PostgreSQL, MySQL), you need to install an external driver.

Python连接方法有哪些?-图2
(图片来源网络,侵删)
  • PostgreSQL: pip install psycopg2-binary
  • MySQL: pip install mysql-connector-python or pip install PyMySQL
# --- PostgreSQL Example (using psycopg2) ---
import psycopg2
try:
    # Establish a connection
    conn = psycopg2.connect(
        dbname="your_db",
        user="your_user",
        password="your_password",
        host="localhost"
    )
    cursor = conn.cursor()
    # Execute a query
    cursor.execute("SELECT version();")
    db_version = cursor.fetchone()
    print(f"Connected to PostgreSQL, version: {db_version[0]}")
except (Exception, psycopg2.DatabaseError) as error:
    print(error)
finally:
    # Close the connection
    if conn is not None:
        cursor.close()
        conn.close()
        print("Database connection closed.")

b) Connecting to NoSQL Databases

MongoDB (Document Store)

You need the pymongo driver.

pip install pymongo
# --- MongoDB Example (using pymongo) ---
from pymongo import MongoClient
# Connect to MongoDB (default is localhost on port 27017)
try:
    client = MongoClient('mongodb://localhost:27017/')
    db = client['test_database']  # Get a database
    collection = db['users']      # Get a collection (like a table)
    # Insert a document (like a row)
    user_data = {
        "name": "Charlie",
        "email": "charlie@example.com",
        "age": 30
    }
    insert_result = collection.insert_one(user_data)
    print(f"Inserted document with id: {insert_result.inserted_id}")
    # Find a document
    found_user = collection.find_one({"name": "Charlie"})
    print(f"Found user: {found_user}")
    # Close the connection
    client.close()
except Exception as e:
    print(f"An error occurred: {e}")

Redis (Key-Value Store / Cache)

You need the redis library.

Python连接方法有哪些?-图3
(图片来源网络,侵删)
pip install redis
# --- Redis Example (using redis-py) ---
import redis
# Connect to Redis (default is localhost on port 6379)
try:
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.ping()  # Test the connection
    print("Successfully connected to Redis!")
    # Set a key-value pair
    r.set('language', 'Python')
    print("Set key 'language' to 'Python'")
    # Get the value
    language = r.get('language')
    print(f"Got value for key 'language': {language.decode('utf-8')}")
    # Use as a counter
    r.incr('visitor_count')
    print(f"Visitor count is now: {r.get('visitor_count').decode('utf-8')}")
except redis.ConnectionError as e:
    print(f"Could not connect to Redis: {e}")

API Connectivity (HTTP/REST)

Connecting to web APIs is fundamental for modern applications. The standard library has urllib, but the community overwhelmingly prefers the requests library for its simplicity.

pip install requests
# --- API Example (using requests) ---
import requests
import json
# Define the API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"
try:
    # Make a GET request
    response = requests.get(url)
    # Raise an exception if the request was unsuccessful (e.g., 404, 500)
    response.raise_for_status()
    # Parse the JSON response
    data = response.json()
    # Print the data
    print(f"Post Title: {data['title']}")
    print(f"Post Body: {data['body']}")
    # Example of a POST request (sending data)
    new_post = {
        "title": "foo",
        "body": "bar",
        "userId": 1
    }
    post_response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post)
    post_response.raise_for_status()
    print("\nSuccessfully created a new post!")
    print(f"New Post ID: {post_response.json()['id']}")
except requests.exceptions.HTTPError as errh:
    print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
    print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
    print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
    print(f"Oops: Something Else: {err}")

Real-Time Connectivity (WebSockets)

WebSockets provide full-duplex communication channels over a single, long-lived connection, perfect for chat applications, live notifications, or real-time dashboards.

A popular library for both client and server is websockets.

pip install websockets

Simple WebSocket Server:

# --- WebSocket Server Example ---
import asyncio
import websockets
# This function will handle each new connection
async def handler(websocket, path):
    print(f"A new client connected from {path}")
    try:
        # Keep listening for messages from the client
        async for message in websocket:
            print(f"Received message: {message}")
            # Echo the message back to the client
            await websocket.send(f"Server received: {message}")
    except websockets.exceptions.ConnectionClosed as e:
        print(f"Client disconnected: {e}")
# Start the server
start_server = websockets.serve(handler, "localhost", 8765)
print("WebSocket server started on ws://localhost:8765")
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Simple WebSocket Client:

# --- WebSocket Client Example ---
import asyncio
import websockets
async def client_handler():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        print("Connected to server!")
        await websocket.send("Hello, Server!")
        print("Sent message: Hello, Server!")
        # Wait for a response
        response = await websocket.recv()
        print(f"Received response: {response}")
# Run the client
asyncio.get_event_loop().run_until_complete(client_handler())

Device-Level Connectivity (Hardware & IoT)

Python is also used to communicate with physical hardware, often in IoT or robotics projects. The pyserial library is the standard for serial communication.

pip install pyserial
# --- Serial Port Example (e.g., communicating with an Arduino) ---
import serial
import time
# Configure the serial port ('COM3' on Windows, '/dev/ttyUSB0' on Linux)
ser = serial.Serial(
    port='/dev/ttyUSB0',  # Change this to your port
    baudrate=9600,
    timeout=1
)
print(f"Connected to {ser.name}")
try:
    # Send a command to the device
    ser.write(b'1')  # Send the character '1'
    print("Sent: 1")
    # Read a response from the device
    if ser.in_waiting > 0:
        line = ser.readline().decode('utf-8').rstrip()
        print(f"Received: {line}")
except serial.SerialException as e:
    print(f"Serial error: {e}")
finally:
    # Close the port
    ser.close()
    print("Serial port closed.")

Summary of Key Libraries

Connectivity Type Popular Libraries Description
SQL Databases sqlite3 (built-in), psycopg2, mysql-connector-python For relational databases like PostgreSQL, MySQL, SQLite.
NoSQL (MongoDB) pymongo For document-based databases.
NoSQL (Redis) redis For in-memory data stores, caches, and message brokers.
HTTP/REST APIs requests The de-facto standard for making HTTP requests.
WebSockets websockets A library for building WebSocket clients and servers.
Serial (Hardware) pyserial For communicating with devices over a serial port (UART).
Cloud Services boto3 (AWS), azure-storage-blob (Azure), google-cloud-storage (GCP) For interacting with cloud provider services.

Choosing the right library depends entirely on what you are trying to connect to. For most web development, requests for APIs and a database driver (like psycopg2) are essential starting points.

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