连接被拒绝的sqlalchemy Flask

时间:2019-12-13 16:35:40

标签: python flask sqlalchemy

我在Ubuntu 18.0,flask_sqlalchemy和MYSQL数据库上运行flask应用程序,当我尝试登录时有时出现500个内部服务器错误,我必须重新启动MYSQL服务器和Apache。

我检查了serevr日志,发现此错误,我听不懂  error.log

ERROR:flask.app:Exception on / [POST], referer: {domain.com}
 Traceback (most recent call last):, referer: {domain.com}
   File "/usr/local/lib/python3.6/dist-packages/pymysql/connections.py", line 583, in connect, referer: {domain.com}
     **kwargs), referer: {domain.com}
   File "/usr/lib/python3.6/socket.py", line 724, in create_connection, referer: {domain.com}
     raise err, referer: {domain.com}
   File "/usr/lib/python3.6/socket.py", line 713, in create_connection, referer: {domain.com}
     sock.connect(sa), referer: {domain.com}
ConnectionRefusedError: [Errno 111] Connection refused, referer: {domain.com}
, referer: {domain.com}
During handling of the above exception, another exception occurred:, referer: {domain.com}
, referer: {domain.com}
Traceback (most recent call last):, referer: {domain.com}
 File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 2158, in _wrap_pool_connect, referer: {domain.com}
   return fn(), referer: {domain.com}
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1805, in full_dispatch_request, referer: {domain.com}
  rv = self.dispatch_request(), referer: {domain.com}
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1791, in dispatch_request, referer: {domain.com}
  return self.view_functions[rule.endpoint](**req.view_args), referer: {domain.com}
File "/var/www/Dashboard/dashboard/routes.py", line 23, in login, referer: {domain.com}
  User = db.session.query(Users).filter_by(Email = request.form['Email']).first(), referer: {domain.com}
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager 

app = Flask(__name__)
app.config['SECRET_KEY'] = 'SECRET_KEY'
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://username:password@localhost/database"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

from dashboard import routes
from dashboard import api

2 个答案:

答案 0 :(得分:0)

使用如下所示的套接字连接到数据库:

socket_location = "/var/run/mysqld/mysqld.sock"
app.config['SQLALCHEMY_DATABASE_URI'] = \
    "mysql+pymysql://username:password@localhost/database?unix_socket=" + socket_location

要找到正确的套接字位置,请尝试在数据库配置文件中进行搜索,例如在 /etc/mysql/my.cnf 中。

在使用数据库之前,请确保它存在:

db = SQLAlchemy(app)

with app.app_context():
    db.create_all()

# ...
app.run(...)

答案 1 :(得分:0)

每次我执行POST或GET请求时,我的内存不足都会导致MySQL服务器崩溃。

我当时在使用带有1GB RAM的Ubuntu DigitalOcean Droplet 25GB存储,APACHE服务器和MYSQL服务器。

我所做的是在独立的Droplet中运行MySQL服务器并远程连接flask应用程序,并且它的工作非常稳定。

谢谢