Skip to main content
 首页 » 编程设计

python之Flask WSGI 应用程序内存不足

2025年05月04日15softidea

我有一个相当简单的 python Flask 应用程序作为 Apache2 下的 WSGI 进程运行。 该应用程序通过使用 SQLAlchemy 从数据库中检索几行数据并将其作为 JSON 发送回而具有一个监听器

对于 MySql 连接,我确实有一个全局引擎被重用。

使用 JMeter 生成一些负载,Apache2 进程每 5 秒增加 RAM 使用 0.5% 个单位,并且很快耗尽 RAM。如果停止生成负载的 JMeter,内存不会被清除。

httpd.conf

<VirtualHost *:80> 
ServerName xxxxxxxxxx.com 
 
<Directory /var/www/xxxxxxxxxx> 
    Order allow,deny 
Allow from all 
</Directory> 
 
WSGIDaemonProcess BiddingPractice user=www-data group=www-data threads=5 
WSGIScriptAlias /flask /var/www/xxxxxxxx/xxxxxxxxxxx.wsgi 
 
<Directory /var/www/BiddingPractice> 
    WSGIProcessGroup BiddingPractice 
    WSGIApplicationGroup %{GLOBAL} 
    Order deny,allow 
    Allow from all 
</Directory> 

WSGI 文件

import sys 
sys.path.insert(0, '/home/stefan/Code/xxxxxx') 
from BiddingPractice import app as application 

_init.py_

    # -*- coding: utf-8 *-* 
from flask import Flask 
from sqlalchemy import * 
 
app = Flask(__name__) 
db = create_engine('mysql://root:xxxxxx@localhost/xxxxxxx') 
 
import BiddingPractice.main 

主.py

    # -*- coding: utf-8 *-* 
from flask import render_template 
from flask import request 
from flask import make_response 
from flask import jsonify 
from BiddingPractice import app, db 
from Data.users import getUsers 
import random 
 
@app.route('/hello/') 
@app.route('/hello/<name>') 
def hello(name=None): 
    return render_template('temp.html', name=name) 
 
@app.route('/getData') 
def getData(): 
 
    un, psw, gids = getUsers() 
 
    random.shuffle(un) 
    random.shuffle(gids) 
 
    usernames = ','.join(map(str, un)) 
    passwords = ','.join(map(str, psw)) 
    guids = ','.join(map(str, gids)) 
 
    return jsonify(usernames=usernames, passwords=passwords, guids=guids) 

任何人都可以告诉我是否遗漏了什么或给我一些关于如何解决内存使用问题的提示,例如我如何才能看到 Apache2 进程正在填充什么?

感谢您的帮助!

请您参考如下方法:

使用Flask-SQLAlchemy .它负责正确处理连接和清理内容。

除此之外,它还为您提供了很多糖分,例如 Modelclass.query 而不是 db.session.query(Modelclass)