偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

兩小時(shí)上手 Flask:用 Python 快速構(gòu)建 Web 服務(wù)的極簡教程

開發(fā)
本文介紹Flask開發(fā)的基本框架,希望大家通過本文的學(xué)習(xí),能快速熟悉Flask的使用。

Flask是Python中輕量級的開發(fā)開源庫,本文介紹Flask開發(fā)的基本框架,希望大家通過本文的學(xué)習(xí),能快速熟悉Flask的使用。

1. Flask框架簡介與環(huán)境配置

Flask是一個(gè)輕量級的Python Web框架,基于Werkzeug WSGI工具箱和Jinja2模板引擎,被稱為"微框架"的核心在于其可擴(kuò)展性設(shè)計(jì)。

環(huán)境安裝:

# 創(chuàng)建虛擬環(huán)境(推薦)
python -m venv flask-env

# 激活虛擬環(huán)境
# Windows:
flask-env\Scripts\activate
# macOS/Linux:
source flask-env/bin/activate

# 安裝Flask
pip install flask

最小應(yīng)用示例:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

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

2. 路由系統(tǒng)詳解

基本路由配置:

@app.route('/user/<username>')
def show_user_profile(username):
    return f'User {username}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post {post_id}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    return f'Subpath {subpath}'

HTTP方法處理:

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_login()
    else:
        return show_login_form()

3. 模板引擎(Jinja2)使用

(1) 基礎(chǔ)模板渲染

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

模板文件templates/hello.html:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello World!</h1>
{% endif %}

(2) 模板繼承示例

基礎(chǔ)模板templates/base.html:

<html>
<head>
  <title>{% block title %}{% endblock %}</title>
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

子模板templates/page.html:

{% extends "base.html" %}

{% block title %}Page Title{% endblock %}

{% block content %}
  <h1>This is the page content</h1>
{% endblock %}

4. 請求與響應(yīng)處理

訪問請求數(shù)據(jù):

from flask import request

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form.get('password')

    # 處理文件上傳
    uploaded_file = request.files['file']
    if uploaded_file:
        uploaded_file.save('/tmp/uploaded_file')

    return'Login processed'

自定義響應(yīng):

from flask import make_response

@app.route('/custom')
def custom_response():
    response = make_response(render_template('custom.html'))
    response.headers['X-Custom-Header'] = 'Value'
    response.set_cookie('username', 'john')
    return response

5. 會話與Cookies管理

會話使用示例:

from flask import session

# 必須設(shè)置secret_key
app.secret_key = 'your_secret_key_here'

@app.route('/setsession')
def set_session():
    session['username'] = 'john'
    return 'Session set'

@app.route('/getsession')
def get_session():
    return session.get('username', 'Guest')

Cookies操作:

from flask import request, make_response

@app.route('/setcookie')
def set_cookie():
    resp = make_response('Cookie set')
    resp.set_cookie('username', 'john')
    return resp

@app.route('/getcookie')
def get_cookie():
    username = request.cookies.get('username')
    return f'Hello {username}' if username else 'Hello Guest'

6. 文件上傳處理

文件上傳實(shí)現(xiàn)

from werkzeug.utils import secure_filename
import os

UPLOAD_FOLDER = UPLOAD_FOLDER = '/path/to/uploads'
'/path/to/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return'.'in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    if'file'notin request.files:
        return'No file part'

    file = request.files['file']

    if file.filename == '':
        return'No selected file'

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return'File uploaded successfully'

7. 錯(cuò)誤處理與調(diào)試

自定義錯(cuò)誤頁面:

@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404

調(diào)試模式使用:

if __name__ == '__main__':
    app.run(debug=True)
  
# 或者設(shè)置環(huán)境變量
# export FLASK_ENV=development
# flask run

8. Flask擴(kuò)展與中間件

常用擴(kuò)展介紹:

# Flask-SQLAlchemy (數(shù)據(jù)庫ORM)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

# Flask-WTF (表單處理)
from flask_wtf import FlaskForm
from wtforms import StringField

# Flask-Login (用戶認(rèn)證)
from flask_login import LoginManager
login_manager = LoginManager(app)

# Flask-Migrate (數(shù)據(jù)庫遷移)
from flask_migrate import Migrate
migrate = Migrate(app, db)

中間件示例

@app.before_request
def before_request():
    g.user = current_user if current_user.is_authenticated else None

@app.after_request
def after_request(response):
    # 可以在響應(yīng)中添加統(tǒng)一的headers等
    return response

@app.teardown_request
def teardown_request(exceptinotallow=None):
    # 請求結(jié)束時(shí)執(zhí)行的清理工作
    pass

9. 項(xiàng)目結(jié)構(gòu)與藍(lán)圖(Blueprint)

項(xiàng)目標(biāo)準(zhǔn)目錄結(jié)構(gòu):

/project
    /app
        /static        # 靜態(tài)文件
        /templates     # 模板文件
        /views         # 視圖函數(shù)
            __init__.py
            auth.py    # 認(rèn)證相關(guān)路由
            blog.py    # 博客相關(guān)路由
        __init__.py    # 應(yīng)用工廠
        models.py      # 數(shù)據(jù)模型
    config.py          # 配置文件
    manage.py          # 啟動腳本

藍(lán)圖使用示例:

# app/views/auth.py
from flask import Blueprint

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login')
def login():
    return 'Login Page'

# app/__init__.py
from .views.auth import auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')

10. 部署與性能優(yōu)化

生產(chǎn)環(huán)境部署(Gunicorn):

# 安裝Gunicorn
pip install gunicorn

# 啟動命令
gunicorn -w 4 -b 127.0.0.1:8000 your_app:app

性能優(yōu)化建議:

  • 啟用模板緩存: app.config['TEMPLATES_AUTO_RELOAD'] = False
  • 使用flask-compress壓縮響應(yīng)
  • 靜態(tài)文件使用CDN加速
  • 數(shù)據(jù)庫連接池配置
  • 使用緩存(memcached/Redis)
責(zé)任編輯:趙寧寧 來源: Python數(shù)智工坊
相關(guān)推薦

2011-12-16 16:19:58

移動Web

2021-07-28 06:51:08

FlaskPythonWeb

2023-01-03 08:32:38

2023-06-29 07:45:03

2009-03-24 09:12:15

2015-10-26 11:53:36

OpenStackOpenStack部署RDO

2010-12-24 10:09:04

2011-03-21 14:41:04

LAMPapacheweb

2011-12-29 10:38:19

移動Web

2024-09-29 16:36:16

2021-10-18 22:07:05

裝機(jī)顯卡硬件

2017-04-05 11:40:34

Min瀏覽器web噪音

2021-05-31 11:45:37

LinuxRustShell

2020-06-04 17:38:49

PythonFastAPIWeb服務(wù)

2009-07-28 09:18:17

2016-11-14 14:10:15

電信斷網(wǎng)寬帶網(wǎng)絡(luò)

2025-01-07 08:28:22

2018-01-03 14:32:32

2013-03-13 10:15:02

應(yīng)用經(jīng)濟(jì)調(diào)查數(shù)據(jù)智能機(jī)

2018-06-14 16:59:42

TensorFlowEager深度學(xué)習(xí)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號