Python Web开发实战:构建现代Web应用

Flask之旅《Flask Web开发:基于Python的Web应用开发实战》学习笔记 Flask 搭建博客网站 用户自定义头像 数据库模型,自动产生EER 阅读详情

Python Web开发实战:构建现代Web应用

Web开发的重要性

Web开发是现代软件开发中最活跃的领域之一,Python作为一种功能强大的编程语言,在Web开发中有着广泛的应用。从简单的个人网站到复杂的企业级应用,Python都能胜任。本文将介绍Python Web开发的核心概念、常用框架和最佳实践。

基本概念

HTTP协议

HTTP(超文本传输协议)是Web应用的基础,它定义了客户端和服务器之间的通信规则。了解HTTP协议的基本原理对于Web开发至关重要。

MVC架构

MVC(模型-视图-控制器)是一种常用的Web应用架构模式,它将应用分为三个部分:

  • 模型(Model):处理数据逻辑
  • 视图(View):负责显示数据
  • 控制器(Controller):处理用户输入和业务逻辑

RESTful API

REST(表述性状态转移)是一种软件架构风格,用于设计网络应用接口。RESTful API使用HTTP方法(GET、POST、PUT、DELETE等)来操作资源。

常用Web框架

Flask

Flask是一个轻量级的Python Web框架,它简洁、灵活,适合构建小型到中型的Web应用。

from flask import Flask, request, jsonify, render_template

app = Flask(__name__)

# 路由
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/users', methods=['GET'])
def get_users():
    users = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"}
    ]
    return jsonify(users)

@app.route('/api/users', methods=['POST'])
def create_user():
    user = request.get_json()
    return jsonify(user), 201

@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = {"id": user_id, "name": "Alice"}
    return jsonify(user)

@app.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    user = request.get_json()
    user["id"] = user_id
    return jsonify(user)

@app.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    return jsonify({"message": "User deleted"}), 200

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

Django

Django是一个功能强大的Python Web框架,它提供了完整的MVC架构和许多内置功能,适合构建大型Web应用。

# models.py
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models import User

@csrf_exempt
def user_list(request):
    if request.method == 'GET':
        users = User.objects.all()
        users_list = [{'id': user.id, 'name': user.name, 'email': user.email} for user in users]
        return JsonResponse(users_list, safe=False)
    elif request.method == 'POST':
        data = json.loads(request.body)
        user = User.objects.create(name=data['name'], email=data['email'])
        return JsonResponse({'id': user.id, 'name': user.name, 'email': user.email}, status=201)

@csrf_exempt
def user_detail(request, user_id):
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        return JsonResponse({'error': 'User not found'}, status=404)

    if request.method == 'GET':
        return JsonResponse({'id': user.id, 'name': user.name, 'email': user.email})
    elif request.method == 'PUT':
        data = json.loads(request.body)
        user.name = data['name']
        user.email = data['email']
        user.save()
        return JsonResponse({'id': user.id, 'name': user.name, 'email': user.email})
    elif request.method == 'DELETE':
        user.delete()
        return JsonResponse({'message': 'User deleted'}, status=200)

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('api/users/', views.user_list),
    path('api/users/<int:user_id>/', views.user_detail),
]

FastAPI

FastAPI是一个现代、快速的Python Web框架,它基于Starlette和Pydantic,提供了自动API文档和类型提示。

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI()

class UserBase(BaseModel):
    name: str
    email: str

class UserCreate(UserBase):
    pass

class User(UserBase):
    id: int

    class Config:
        orm_mode = True

# 模拟数据库
users = [
    User(id=1, name="Alice", email="alice@example.com"),
    User(id=2, name="Bob", email="bob@example.com")
]

@app.get('/api/users', response_model=List[User])
def get_users():
    return users

@app.post('/api/users', response_model=User, status_code=201)
def create_user(user: UserCreate):
    new_user = User(id=len(users) + 1, **user.dict())
    users.append(new_user)
    return new_user

@app.get('/api/users/{user_id}', response_model=User)
def get_user(user_id: int):
    for user in users:
        if user.id == user_id:
            return user
    raise HTTPException(status_code=404, detail="User not found")

@app.put('/api/users/{user_id}', response_model=User)
def update_user(user_id: int, user: UserCreate):
    for i, existing_user in enumerate(users):
        if existing_user.id == user_id:
            users[i] = User(id=user_id, **user.dict())
            return users[i]
    raise HTTPException(status_code=404, detail="User not found")

@app.delete('/api/users/{user_id}', status_code=200)
def delete_user(user_id: int):
    for i, user in enumerate(users):
        if user.id == user_id:
            users.pop(i)
            return {"message": "User deleted"}
    raise HTTPException(status_code=404, detail="User not found")

数据库操作

SQLite

SQLite是一种轻量级的嵌入式数据库,适合小型应用。

import sqlite3

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

# 创建表
c.execute('''CREATE TABLE IF NOT EXISTS users
             (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')

# 插入数据
c.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Alice", "alice@example.com"))

# 提交更改
conn.commit()

# 查询数据
c.execute("SELECT * FROM users")
print(c.fetchall())

# 关闭连接
conn.close()

PostgreSQL

PostgreSQL是一种功能强大的开源关系型数据库,适合大型应用。

import psycopg2

# 连接数据库
conn = psycopg2.connect(
    host="localhost",
    database="mydb",
    user="myuser",
    password="mypassword"
)

# 创建游标
cur = conn.cursor()

# 创建表
cur.execute('''CREATE TABLE IF NOT EXISTS users
             (id SERIAL PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) UNIQUE)''')

# 插入数据
cur.execute("INSERT INTO users (name, email) VALUES (%s, %s)", ("Alice", "alice@example.com"))

# 提交更改
conn.commit()

# 查询数据
cur.execute("SELECT * FROM users")
print(cur.fetchall())

# 关闭游标和连接
cur.close()
conn.close()

SQLAlchemy

SQLAlchemy是Python的ORM(对象关系映射)库,它提供了一种面向对象的方式来操作数据库。

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建引擎
engine = create_engine('sqlite:///example.db')

# 创建基类
Base = declarative_base()

# 定义模型
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String, unique=True)

# 创建表
Base.metadata.create_all(engine)

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()

# 插入数据
user = User(name="Alice", email="alice@example.com")
session.add(user)
session.commit()

# 查询数据
users = session.query(User).all()
for user in users:
    print(f"ID: {user.id}, Name: {user.name}, Email: {user.email}")

# 关闭会话
session.close()

前端集成

Jinja2模板

Jinja2是Python的模板引擎,它可以生成HTML、XML等文档。

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    user = {"name": "Alice", "email": "alice@example.com"}
    return render_template('index.html', user=user)

# templates/index.html
# <!DOCTYPE html>
# <html>
# <head>
#     <title>Home</title>
# </head>
# <body>
#     <h1>Hello, {{ user.name }}!</h1>
#     <p>Your email is {{ user.email }}</p>
# </body>
# </html>

静态文件

静态文件(如CSS、JavaScript、图片)是Web应用的重要组成部分。

from flask import Flask

app = Flask(__name__)

# 静态文件将从static目录提供
# <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
# <script src="{{ url_for('static', filename='script.js') }}"></script>

RESTful API与前端集成

// 使用fetch API调用RESTful API
fetch('/api/users')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        // 渲染数据
    });

// 发送POST请求
fetch('/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({name: 'Alice', email: 'alice@example.com'})
})
.then(response => response.json())
.then(data => {
    console.log(data);
});

认证与授权

JWT认证

JWT(JSON Web Token)是一种用于身份验证的令牌格式。

from flask import Flask, request, jsonify
import jwt
import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

def generate_token(user_id):
    payload = {
        'user_id': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)
    }
    return jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')

def verify_token(token):
    try:
        payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
        return payload['user_id']
    except:
        return None

@app.route('/login', methods=['POST'])
def login():
    # 验证用户
    user_id = 1  # 假设用户验证成功
    token = generate_token(user_id)
    return jsonify({'token': token})

@app.route('/protected', methods=['GET'])
def protected():
    token = request.headers.get('Authorization')
    if not token:
        return jsonify({'error': 'Token required'}), 401
    
    # 移除Bearer前缀
    token = token.split(' ')[1]
    user_id = verify_token(token)
    if not user_id:
        return jsonify({'error': 'Invalid token'}), 401
    
    return jsonify({'message': 'Protected route', 'user_id': user_id})

OAuth2认证

OAuth2是一种用于授权的协议,它允许用户授权第三方应用访问其资源。

from flask import Flask, redirect, url_for, session
from authlib.integrations.flask_client import OAuth

app = Flask(__name__)
app.secret_key = 'your-secret-key'

oauth = OAuth(app)
github = oauth.register(
    name='github',
    client_id='your-client-id',
    client_secret='your-client-secret',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    api_base_url='https://api.github.com/',
    client_kwargs={'scope': 'user:email'},
)

@app.route('/login')
def login():
    redirect_uri = url_for('authorize', _external=True)
    return github.authorize_redirect(redirect_uri)

@app.route('/authorize')
def authorize():
    token = github.authorize_access_token()
    session['token'] = token
    return redirect('/profile')

@app.route('/profile')
def profile():
    if 'token' not in session:
        return redirect('/login')
    
    resp = github.get('user')
    user_info = resp.json()
    return jsonify(user_info)

部署与扩展

部署到生产环境

使用Gunicorn

Gunicorn是一个Python WSGI HTTP服务器,它可以处理并发请求。

# 安装Gunicorn
pip install gunicorn

# 启动服务器
gunicorn app:app -w 4 -b 0.0.0.0:8000
使用Nginx作为反向代理
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

容器化

使用Docker容器化Web应用可以简化部署和扩展。

# Dockerfile
FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:8000"]
# 构建镜像
docker build -t myapp .

# 运行容器
docker run -p 8000:8000 myapp

扩展

缓存

使用缓存可以提高Web应用的性能。

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
app.config['CACHE_TYPE'] = 'redis'
app.config['CACHE_REDIS_URL'] = 'redis://localhost:6379/0'
cache = Cache(app)

@app.route('/api/users')
@cache.cached(timeout=60)
def get_users():
    # 从数据库获取用户
    users = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
    return jsonify(users)
负载均衡

使用负载均衡可以分发请求,提高应用的可用性和性能。

upstream backend {
    server localhost:8000;
    server localhost:8001;
    server localhost:8002;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

实用应用

博客系统

from flask import Flask, request, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
db = SQLAlchemy(app)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

# 创建表
db.create_all()

@app.route('/')
def index():
    posts = Post.query.all()
    return render_template('index.html', posts=posts)

@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        post = Post(title=title, content=content)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('create.html')

@app.route('/post/<int:post_id>')
def post(post_id):
    post = Post.query.get_or_404(post_id)
    return render_template('post.html', post=post)

@app.route('/edit/<int:post_id>', methods=['GET', 'POST'])
def edit(post_id):
    post = Post.query.get_or_404(post_id)
    if request.method == 'POST':
        post.title = request.form['title']
        post.content = request.form['content']
        db.session.commit()
        return redirect(url_for('post', post_id=post.id))
    return render_template('edit.html', post=post)

@app.route('/delete/<int:post_id>', methods=['POST'])
def delete(post_id):
    post = Post.query.get_or_404(post_id)
    db.session.delete(post)
    db.session.commit()
    return redirect(url_for('index'))

API服务

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
import uvicorn

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    price: float
    description: str = None

# 模拟数据库
items = [
    Item(id=1, name="Item 1", price=10.99, description="This is item 1"),
    Item(id=2, name="Item 2", price=19.99, description="This is item 2")
]

@app.get('/api/items', response_model=List[Item])
def get_items():
    return items

@app.post('/api/items', response_model=Item, status_code=201)
def create_item(item: Item):
    items.append(item)
    return item

@app.get('/api/items/{item_id}', response_model=Item)
def get_item(item_id: int):
    for item in items:
        if item.id == item_id:
            return item
    raise HTTPException(status_code=404, detail="Item not found")

@app.put('/api/items/{item_id}', response_model=Item)
def update_item(item_id: int, item: Item):
    for i, existing_item in enumerate(items):
        if existing_item.id == item_id:
            items[i] = item
            return item
    raise HTTPException(status_code=404, detail="Item not found")

@app.delete('/api/items/{item_id}', status_code=200)
def delete_item(item_id: int):
    for i, item in enumerate(items):
        if item.id == item_id:
            items.pop(i)
            return {"message": "Item deleted"}
    raise HTTPException(status_code=404, detail="Item not found")

if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8000)

最佳实践

1. 代码组织

  • 使用模块化的结构,将不同功能的代码分离到不同的文件和目录中
  • 遵循MVC或类似的架构模式
  • 使用蓝图(Blueprint)或类似机制组织路由

2. 安全性

  • 使用HTTPS保护数据传输
  • 对用户输入进行验证和转义,防止SQL注入和XSS攻击
  • 使用密码哈希存储用户密码
  • 实现适当的认证和授权机制
  • 定期更新依赖库,修复安全漏洞

3. 性能优化

  • 使用缓存减少数据库查询
  • 优化数据库查询,使用索引
  • 启用Gzip压缩减少传输数据大小
  • 使用异步处理提高并发性能
  • 优化静态文件,使用CDN分发

4. 测试

  • 编写单元测试和集成测试
  • 使用测试框架如pytest
  • 实现持续集成和持续部署

5. 文档

  • 为API编写文档,使用Swagger或ReDoc
  • 为代码添加注释和文档字符串
  • 编写项目文档,包括安装和使用说明

常见问题和解决方案

1. 数据库连接问题

问题:应用无法连接到数据库

解决方案:

  • 检查数据库服务是否正在运行
  • 检查连接字符串是否正确
  • 检查数据库用户是否有适当的权限
  • 检查防火墙是否阻止了连接

2. 性能问题

问题:应用响应缓慢

解决方案:

  • 使用缓存减少数据库查询
  • 优化数据库查询
  • 启用Gzip压缩
  • 使用异步处理
  • 检查是否有内存泄漏

3. 部署问题

问题:应用在生产环境中无法正常运行

解决方案:

  • 确保所有依赖库都已正确安装
  • 检查环境变量是否正确设置
  • 检查日志文件,查找错误信息
  • 确保端口已正确配置

4. 安全问题

问题:应用存在安全漏洞

解决方案:

  • 使用HTTPS
  • 对用户输入进行验证和转义
  • 使用密码哈希
  • 实现适当的认证和授权机制
  • 定期更新依赖库

总结

Python Web开发是一个广阔而充满活力的领域,它提供了丰富的工具和框架,使得构建现代Web应用变得更加简单和高效。通过掌握Python Web开发的核心概念和最佳实践,我们可以构建各种类型的Web应用,从简单的个人网站到复杂的企业级应用。

在实际开发中,Python Web开发常用于:

  • 构建Web应用和网站
  • 开发API服务
  • 创建管理系统
  • 实现数据可视化
  • 构建电子商务平台

通过不断学习和实践,我们可以掌握Python Web开发的精髓,构建更加可靠、高效、安全的Web应用。

77、Python前后端分离开发:掌握现代Web应用构建技巧 本文介绍了前后端分离的开发模式,以及如何在Python项目中采用这种模式。通过实际案例和技巧,我们探讨了技术选型、API设计、编写代码、测试和部署等关键环节。文章强调了前后端分离带来的优点,如易于维护、技术选型灵活和提高开发效率。同时,我们也提醒了在实施前后端分离时可能遇到的一些挑战,并提供了相应的解决方案。掌握前后端分离的开发模式,可以让我们更好地应对复杂的Web应用开发挑战,提高开发效率和应用质量。 阅读详情

相关推荐

《Flask Web开发:基于Python的Web应用开发实战》笔记(原创)

引子 对不起,我向您坦白:我接触python才短短数月,和“程序员”这个class还差十万个为什么Object的距离,连给“码农”提鞋的都会被嫌弃。多年以后当我站在“代码”的世界里,准会回忆起“拒绝无码”这个疯狂的点子从脑子里蹦出的那个黄昏。那时的世界美好单纯,傻白甜有傻白甜的幸福。但命运在这个黄昏发生了不可逆转的变化,在’拒绝无码’的我背后经历了什么?是什么样的精神力量在支撑着我?前面的出路又在...

码码码 4935

Path of Building PoE2 构建规划实战:一套离线工作流

Path of Building PoE2 是一款完全离线的 Path of Exile 2 构建规划工具:技能 DPS 与伤害随时间、生命/魔力/能量护盾总量、天赋树节点收益、装备词缀解析,全部在本地完成计算。它的价值在于让你在烧材料之前,先用数值验证方向。 ## 首次打开后,如何最快拿到第一个可用构建 程序从 Releases 页面下载,提供安装向导和 portable zip 两种形态,

gitblog_00017的博客 127

Python Flask Web应用开发实战指南

Flask是一个轻量级的Web应用框架,遵循Python编程语言的“约定优于配置”的原则。它为开发者提供了一个强大的基础,用于构建Web应用和服务。Flask的设计初衷是帮助开发者创建一个简单的应用,但是又不失扩展性,允许开发人员在必要时增加更多的功能。通过使用Jinja2作为模板引擎,以及Werkzeug作为WSGI工具集,Flask得以以简洁的API和灵活的方式快速构建Web应用。在Web开发中,路由和视图函数是构建应用基础结构的两个关键要素。它们共同作用于将用户请求转换为相应的页面或功能。

weixin_31459297的博客 1869

Python Django 5 Web应用开发实战

本文主要介绍了Python Django 5 Web应用开发实战,希望能对学习Python Web应用开发的同学们有所帮助。 文章目录 1. 前言 2. 书籍推荐 2.1 内容简介 2.2 本书作者 2.3 本书目录 2.4 适合读者 3. 购买链接

weixin_43178406的博客 2万+

单片机技术入门与实战:从零基础到项目开发

单片机(MCU)作为嵌入式系统的核心组件,集成了CPU、内存和各种接口电路,广泛应用于智能家居、工业控制和汽车电子等领域。其工作原理基于实时控制和低功耗设计,通过定时器、中断系统和通信接口等功能模块实现各种控制任务。在物联网和智能硬件快速发展的背景下,掌握单片机开发技术成为电子工程师的重要技能。本文以STM32和PIC系列为例,详细解析单片机的基本概念、功能模块和选型指南,并分享从入门到项目实战的系统学习方法,帮助开发者在3-6个月内快速掌握这一关键技术。

weixin_35753291的博客 660

利用Android系统漏洞实现后台弹窗(外弹)

关键:从 Android 8.0(API 26)开始,禁止使用 context.sendBroadcast() 发送隐式广播(即没有指定 setPackage() 或明确组件的广播)。demo核心代码展示利用Android显示系统和广播系统的漏洞实现在后台弹窗的功能,支持最新Android15,16版本。核心功能都是在so层去做,大量使用了jni反调, 如果要上架到应用市场,需要对代码做进一步混淆,加固以应对市场安全扫描。3,开启虚拟显示窗口,这是个透明像素窗口。5,可开启一个线程,调用这个外弹窗口。

2018,再出发~ 1330

Python web实战 | 用 Flask 框架快速构建 Web 应用【实战】

Python web 开发已经有了相当长的历史,从最早的 CGI 脚本到现在的全栈 Web 框架,现在已经成为了一种非常流行的方式。 Python 最早被用于 Web 开发是在 1995 年(90年代早期),当时使用 CGI 脚本编写动态 Web 页面。2004 年 Django 框架发布,它是一个高度模块化的框架,提供了许多开箱即用的功能,使得 Web 开发更加容易和快速。Flask 框架于 2010 年发布,是一个轻量级的框架,它提供了更少的默认功能,但也更灵活,允许开发者根据需要添加或删除功能。

Rocky006的博客 1万+

FDTD超表面仿真详细教程,几何相位,共振相位,传播相位

FDTD的超表面主要几何相位型(PB型)和共振型两种类型,其中PB型每个cell中的纳米棒的长宽相同,旋转角度不同,共振型长宽不同,旋转角度相同。本博文中以最常见的长方形纳米棒为例,用FDTD演示两种超表面实现的聚焦透镜的功能,包含详细步骤,其他形状,材料的超表面可自行尝试。

wuyuerhhg的博客 3万+

Mesop Python Web框架终极指南:用纯Python构建现代化Web应用

Mesop是一个革命性的Python Web框架,让你无需编写JavaScript、CSS或HTML,就能快速构建现代化Web应用。作为Google内部快速应用开发的首选工具,Mesop将Python的简洁优雅与Web开发的强大功能完美结合,为开发者提供了前所未有的开发体验。无论你是UI新手还是经验丰富的开发者,Mesop都能让你在几分钟内创建出功能完整的Web应用。 ## 为什么选择Mesop

gitblog_00158的博客 1090

使用verilog实现基于FPGA的TDC设计

verilog实现TDC 高精度时间数字转换器概述(TDC) 简介: TDC被用于测量时间间隔,应用在物理研究、飞行时间测量领域等。 本设计使用verilog实现并在xilinx和altera的FPGA上均可实现! 设计中使用到下述几个模块,包括FIFO,COUNT等,在xilinx下也使用到了一些原语等。下面有实现的代码和仿真截图等。 顶层模块设计如下: module top( input wire start, input wire stop, input wire clk, output wire T

QQ_778132974的博客 6258

27、振动信号实时并行处理与风力发电机模型鲁棒控制设计

本文探讨了振动信号实时并行处理与风力发电机模型鲁棒控制设计两大核心技术。在振动信号处理方面,提出基于FPGA、RT和PC三级架构的并行采集与处理系统,实现高效、实时的振动分析,适用于电机状态监测与预测性维护。在风力发电控制方面,研究风力农场布局优化(WFLO)问题,比较九种多目标元启发式算法性能,并提出基于扰动观察法的最大功率点跟踪(MPPT)控制策略,提升发电效率与系统鲁棒性。研究成果为工业设备智能监控与可再生能源优化提供了有效技术路径。

sunny的博客 76

01 如何学习Python Web开发从入门到实战

Python Web开发从入门到实战,适用于新手以及具有一定计算机基础。

Cys_33的博客 5387

C# 零基础入门知识点汇总

本文属于C#零基础入门之百识百例系列目录文章。此系列文章已经完结,欢迎大家点击文中文章链接查看详情进行学习。

陈言必行 -- Unity游戏开发领域优质博主 5400

NiceGUI脚手架:5分钟搭建现代化Python Web应用

大家好,今天给大家介绍一个基于NiceGUI的应用脚手架。这个脚手架不仅可以帮助你快速搭建NiceGUI应用,还能作为学习NiceGUI的入门教程。对于想要快速上手Python Web开发的同学来说,这是一个非常好的起点。

Ktovoz的博客 2949

MFC中的CMFCToolBar:自定义按钮提示消息

通过以上步骤,您可以在MFC应用程序中使用CMFCToolBar创建自定义按钮,并设置按钮的提示消息。通过以上步骤,您可以在MFC应用程序中使用CMFCToolBar创建自定义按钮,并设置按钮的提示消息。通过上述代码,您可以在MFC应用程序中添加一个名为"ID_BUTTON_CUSTOM"的自定义按钮,并将其提示消息设置为"自定义提示消息"。通过上述代码,您可以在MFC应用程序中添加一个名为"ID_BUTTON_CUSTOM"的自定义按钮,并将其提示消息设置为"自定义提示消息"。

PixelInk的博客 1092

利用Python爬虫采集京东商品评论情感分析案例(含完整代码)

在电商蓬勃发展的今天,商品评论蕴含着巨大的商业价值。本文以京东商品评论为研究对象,系统介绍如何使用Python构建一个完整的评论采集与情感分析系统。文章涵盖京东反爬机制分析、动态请求模拟、评论数据解析、中文文本预处理、基于SnowNLP和深度学习的情感极性分类、以及可视化展示等完整技术链路。所有代码均基于2025-2026年最新可用接口编写,并提供可直接运行的完整源码。全文力求详实,总字数逾八千字,适合Python数据分析从业者、电商运营人员及自然语言处理初学者参考实践。目录摘要第一章 引言。

2201_76125261的博客 94

使用Python Flask实战构建Web应用

在上面的示例代码中,我们首先导入了必要的模块,包括Flask和MySQL数据库驱动程序。在这个表单中,使用了标签来创建一个表单,并设置了method属性为"POST",action属性 为"/login",表示表单数据将通过POST请求提交到"/login"路由。需要注意的是,在处理表单时,应该对用户输入进行验证和处理,以确保数据的安全性和完整性。在这里,我们获取了用户名和密码字段的值,并进行了简单的验证。接下来,在Flask应用中定义一个处理登录表单的路由和视图函数。

chengxuyuznguoke的博客 1378

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Reflex 完全指南:用 Python 构建现代 Web 应用的终极体验

Reflex 是一个用 Python 构建完整前后端 Web 应用的开源框架。让开发者只使用 Python,即可编写完整 Web 应用;自动生成 React 前端与 FastAPI 后端;零 JavaScript / HTML 代码,代码更纯粹、维护成本更低;支持静态部署、动态部署与 SPA 构建。🌍 官网: https://reflex.devReflex 正在以惊人的速度迭代,目标是成为 Python 世界的“Next.js”。是一名 Python 开发者但不想写前端;

萧鼎的博客 5861

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

使用Python进行Web开发:从入门到实战

使用Python进行Web开发:从入门到实战

lpl1123143的博客 3930

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

如何用Ludic和htmx在纯Python中创建现代化Web应用:5个实战技巧

在当今快速发展的Web开发领域,Python开发者一直在寻找更高效、更安全的方式来构建现代化Web应用。Ludic作为一个类型安全的HTML模板引擎,结合htmx的强大功能,为Python开发者提供了一种革命性的解决方案,让你无需编写JavaScript就能创建动态、交互式的Web应用。🌳 [![Ludic框架Logo](https://raw.gitcode.com/gh_mirrors/l

gitblog_00713的博客 954

用纯Python构建现代Web应用:Rio框架完全指南

你是一个文章写手,你负责为开源项目写专业易懂的文章。Rio是一个革命性的Python Web应用框架,让你无需编写任何HTML、CSS或JavaScript代码就能构建现代化的Web应用和桌面应用。这个纯Python框架将前端开发完全Python化,让Python开发者能够专注于业务逻辑而不是前端技术栈。 ## 为什么Python开发者需要Rio?🚀 在传统的Web开发中,Python开发者

gitblog_00369的博客 1299

3步掌握FastHTML组件开发:构建现代化Web应用的完整指南

FastHTML是创建HTML应用程序的最快方式,它提供了简洁高效的组件开发模式,帮助开发者快速构建现代化Web应用。本指南将通过三个简单步骤,带你掌握FastHTML组件开发的核心技巧,从零开始构建功能完善的Web界面。 ## 一、环境准备:快速搭建FastHTML开发环境 开始FastHTML组件开发前,需要先准备好开发环境。首先克隆官方仓库到本地: ```bash git clone

gitblog_00648的博客 691

Solara 终极指南:用纯 Python 构建现代化 Web 应用

在当今数据驱动的世界中,快速构建交互式 Web 应用已成为开发者的核心需求。Solara 应运而生,这是一个基于纯 Python 的 React 风格框架,让你能够轻松创建功能强大的 Jupyter 和 Web 应用程序。无论你是数据科学家、机器学习工程师还是全栈开发者,Solara 都能为你提供前所未有的开发体验。 ## 为什么选择 Solara:解决传统开发痛点 传统 Web 开发往往需要

gitblog_00220的博客 1252

深入解读 FastAPI:现代、高性能的 Python Web 框架

FastAPI 是一个高性能的 Web 框架,基于 Python 3.7+ 构建,依赖于 Starlette(用于网络框架核心)和 Pydantic(用于数据校验)。它以 OpenAPI 和 JSON Schema 标准为核心,为开发者提供自动化的文档生成和强大的数据验证功能。id: inttitle: strFastAPI 凭借其类型安全、异步支持和自动文档生成,已经成为构建现代 Web 和 API 服务的热门选择。从简单的增删改查到复杂的异步任务处理,FastAPI 为开发者提供了丰富的功能。

私聊前往站内信:https://i.csdn.net/#/msg/chat/weixin_44976692 1万+
上一篇: Rust 智能指针实战指南:从原理到应用
下一篇: Python 数据科学实战:从数据到洞察
第一程序员
博客等级 码龄1年 1万+粉丝 1912原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址