Backend Development 8 min read

Python Concurrency, Asyncio, Flask Web Development, SQLite, and Git Basics

This article introduces Python concurrency models—including threading, multiprocessing, and asyncio—provides step‑by‑step Flask web application examples, demonstrates SQLite database operations, and covers essential Git commands for version control, all with complete code snippets for practical learning.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Concurrency, Asyncio, Flask Web Development, SQLite, and Git Basics

Concurrency programming is a vital part of modern software development, and Python offers several models such as multithreading, multiprocessing, and asynchronous programming with asyncio .

Multithreading (threading module) allows multiple tasks to run simultaneously within a single program, improving efficiency. Example code:

# 导入 threading 模块:
import threading

# 定义线程:
def worker():
    print(threading.current_thread().name, "Starting")
    # Your code here
    print(threading.current_thread().name, "Exiting")

thread1 = threading.Thread(target=worker)
thread2 = threading.Thread(target=worker)
thread1.start()
thread2.start()
thread1.join()
thread2.join()

# 传递参数:
def worker(name):
    print(threading.current_thread().name, "Starting", name)
    # Your code here
    print(threading.current_thread().name, "Exiting", name)

thread1 = threading.Thread(target=worker, args=("Thread 1",))
thread2 = threading.Thread(target=worker, args=("Thread 2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()

# 线程同步:
lock = threading.Lock()

def worker(name):
    with lock:
        print(threading.current_thread().name, "Starting", name)
        # Your code here
        print(threading.current_thread().name, "Exiting", name)

thread1 = threading.Thread(target=worker, args=("Thread 1",))
thread2 = threading.Thread(target=worker, args=("Thread 2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()

Multiprocessing (multiprocessing module) runs tasks in parallel across multiple CPU cores, boosting computational power. Example code:

# 导入 multiprocessing 模块:
import multiprocessing

# 定义进程:
def worker():
    print(multiprocessing.current_process().name, "Starting")
    # Your code here
    print(multiprocessing.current_process().name, "Exiting")

process1 = multiprocessing.Process(target=worker)
process2 = multiprocessing.Process(target=worker)
process1.start()
process2.start()
process1.join()
process2.join()

# 传递参数:
def worker(name):
    print(multiprocessing.current_process().name, "Starting", name)
    # Your code here
    print(multiprocessing.current_process().name, "Exiting", name)

process1 = multiprocessing.Process(target=worker, args=("Process 1",))
process2 = multiprocessing.Process(target=worker, args=("Process 2",))
process1.start()
process2.start()
process1.join()
process2.join()

Asynchronous programming (asyncio module) enables non‑blocking execution of tasks, improving responsiveness. Example code:

# 导入 asyncio 模块
import asyncio

# 定义异步函数
async def fetch_data(url):
    print("Fetching data from", url)
    await asyncio.sleep(1)  # 模拟网络延迟
    print("Data fetched from", url)

async def main():
    task1 = asyncio.create_task(fetch_data("http://example.com"))
    task2 = asyncio.create_task(fetch_data("http://example.org"))
    await task1
    await task2

asyncio.run(main())

# 并发执行多个任务
async def main():
    urls = ["http://example.com", "http://example.org", "http://example.net"]
    tasks = [fetch_data(url) for url in urls]
    await asyncio.gather(*tasks)

asyncio.run(main())

Web development basics (Flask framework) – Flask is a lightweight Python web framework suitable for beginners. Install it and create a simple web app with routes and form handling. Example code:

# 安装 Flask
pip install Flask

# 定义路由:
from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the home page!"

@app.route('/about')
def about():
    return "This is the about page."

if __name__ == '__main__':
    app.run(debug=True)

# 处理表单数据:
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        return f"Username: {username}, Password: {password}"
    return '''
Username:
Password:
'''

if __name__ == '__main__':
    app.run(debug=True)

Database operations (sqlite3 module) – SQLite is a lightweight, file‑based database useful for automation testing. Example code demonstrates creating a database, a table, inserting, querying, and closing the connection.

# 导入 sqlite3 模块
import sqlite3

# 连接数据库:
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# 创建表:
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        email TEXT NOT NULL UNIQUE
    )
''')
conn.commit()

# 插入数据:
cursor.execute('''
    INSERT INTO users (name, email) VALUES (?, ?)
''', ('Alice', '[email protected]'))
conn.commit()

# 查询数据:
cursor.execute('SELECT * FROM users WHERE name = ?', ('Alice',))
rows = cursor.fetchall()
for row in rows:
    print(row)

# 关闭连接:
conn.close()

Version control (Git) – Git is an essential tool for software development. The article covers installation on various platforms, repository initialization, adding and committing files, checking status, cloning remote repositories, and pushing/pulling changes. Example commands:

# Ubuntu/Debian
sudo apt-get install git
# macOS (Homebrew)
brew install git
# Windows – download from https://git-scm.com/download/win

# 初始化仓库
mkdir my_project
cd my_project
git init

# 添加和提交文件
touch example.py
git add example.py
git commit -m "Initial commit"

# 查看状态
git status

# 克隆远程仓库
git clone https://github.com/username/repo.git

# 推送和拉取代码
git push origin main
git pull origin main
backend developmentConcurrencyGitFlaskSQLiteasyncio
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.