简体   繁体   English

使用 SQLalchemy 连接到 MySql 数据库时出错

[英]Error connecting to MySql database with SQLalchemy

I am giving it a last try before I give up, I have googling everywhere but still havent found a solution to my error.我在放弃之前最后一次尝试,我到处搜索,但仍然没有找到解决我的错误的方法。

Just so clarify some things:只是澄清一些事情:

  • MySql server IS UP and running MySql 服务器已启动并正在运行
  • I am running and PHP admin panel together with mysql in the same server(confirming once again that the mysql server works)我正在运行 PHP 管理面板和 mysql 在同一台服务器上(再次确认 mysql 服务器正常工作)
  • The connection to the server is TCP与服务器的连接是TCP
  • When i run this python script locally on my windows machine with XAMPP, it works as it should.当我使用 XAMPP 在我的 windows 机器上本地运行此 python 脚本时,它可以正常工作。

When i create docker image and run it, i get the following error:当我创建 docker 映像并运行它时,我收到以下错误:

sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2002, "Can't con                    nect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")

So here is my "main.py" file:所以这是我的“main.py”文件:

    from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource
from flask_mysqldb import MySQL

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myUser:myPassword@MyIpAdress/just_a_test'



db = SQLAlchemy(app)
ma = Marshmallow(app)
api = Api(app)




#------------------------------------------------------------------------------------------------------
class exercise(db.Model):
    exerciseId = db.Column(db.Integer(), primary_key=True)
    exerciseName = db.Column(db.String(50))
    repetitions = db.Column(db.Integer())
    timeTakenToCompleteRepetitions = db.Column(db.Integer())



class exerciseSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = exercise


exercise_schema = exerciseSchema()
exercises_schema = exerciseSchema(many=True)


class exerciseListResource(Resource):

    def get(self):
        exercise = exercise.query.all()
        return exercises_schema.dump(exercise)

    def post(self):
        new_exercise = exercise(
            exerciseId=request.json['exerciseId'],
            exerciseName=request.json['exerciseName'],
            repetitions=request.json['repetitions'],
            timeTakenToCompleteRepetitions=request.json['timeTakenToCompleteRepetitions']
        )
        db.session.add(new_exercise)
        db.session.commit()
        return_data = exercise_schema.dump(new_exercise)
        return return_data, 201



class exerciseResource(Resource):
    def get(self, exercise_exerciseId):
        exercise = exercise.query.get_or_404(exercise_exerciseId)
        return exercise_schema.dump(exercise)

    def patch(self, exercise_exerciseId):
        exercise = exercise.query.get_or_404(exercise_exerciseId)

        if request.json.get('exerciseName'):
            exercise.exerciseName = request.json['exerciseName']
        if request.json.get('repetitions'):
            exercise.repetitions = request.json['repetitions']
        if request.json.get('timeTakenToCompleteRepetitions'):
            exercise.timeTakenToCompleteRepetitions = request.json['timeTakenToCompleteRepetitions']

        db.session.commit()
        return exercise_schema.dump(exercise)

    def delete(self, exercise_exerciseId):
        exercise = exercise.query.get_or_404(exercise_exerciseId)
        db.session.delete(exercise)
        db.session.commit()
        return '', 204


api.add_resource(exerciseListResource, '/exercise')
api.add_resource(exerciseResource, '/exercise/<int:exercise_exerciseId>')
#---------------------------------------------------------------------------------------------------



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

What could the problem be?问题可能是什么?

Need to expose the Mysql port via Docker's -p option like so:需要通过 Docker 的-p选项公开 Mysql 端口,如下所示:

docker run -p 3306:3306 --name mysql-server -e MYSQL_ROOT_PASSWORD=password -d mysql:latest

Also, if connecting to local, use 127.0.0.1 instead of localhost so the connection is made via tcp instead of local socket file.此外,如果连接到本地,请使用127.0.0.1而不是localhost ,以便通过 tcp 而不是本地套接字文件进行连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM