【问题标题】:Flask WSGI application running out of memoryFlask WSGI 应用程序内存不足
【发布时间】:2012-02-19 12:05:12
【问题描述】:

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

对于 MySql 连接,我确实使用了一个全局引擎。

使用 JMeter 产生一些负载,Apache2 进程每 5 秒增加 0.5% 个单位的 RAM 使用率,并且很快耗尽 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

ma​​in.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 进程正在填满什么?

感谢您的帮助!

【问题讨论】:

  • 你有什么理由自己处理 sqlalchemy 而不是使用Flask-SQLAlchemy
  • 我错过了那个,谢谢你的提示!
  • @ThiefMaster 这实际上解决了我的问题!每秒 250 个请求,我什至没有超过 1.5% 的 RAM 使用率。如果你写一个我很高兴给你答案!
  • 在更大的应用程序上,使用普通的 SQLAlchemy 要容易得多。

标签: python apache sqlalchemy flask


【解决方案1】:

使用Flask-SQLAlchemy。它负责正确处理连接和清理事物。

除此之外,它还给你很多糖,例如 Modelclass.query 而不是 db.session.query(Modelclass)

【讨论】:

    【解决方案2】:

    您没有在请求结束时删除 SQLAlchemy 会话对象。这应该在您的应用程序的 teardown_request 处理程序中完成(参见 Flask 文档中的示例)。 Flask-SQLAlchemy 会为您完成这项工作,但目前不需要切换到 Flask-SQLAlchemy。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 2016-03-18
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多