使用sqlalchemy在我的数据库上执行sql查询的问题

41ik7eoe  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(494)

我正在做一个项目,在一个使用flask和sqlalchemy(托管在awsrds上)连接到mysql服务器的网站上工作,我遵循这个教程,但是当我尝试做(/api/bar)时,我得到了这个错误。当我做我的工作的时候localhost:8080 it 显示“你好世界”非常好。
sqlalchemy.exc.operationalerror:(pymysql.err.operationalerror)(2003,“无法连接到'localhost'([winerror 10061]无法建立连接,因为目标计算机主动拒绝了它)”)(此错误的背景信息:http://sqlalche.me/e/e3q8)
config.py database\u url=“mysql数据库”+pymysql://username:password@localhost:3306/芭比酒鬼“
这是我的初始密码

from flask import Flask
from flask import jsonify
from flask import make_response
from flask import request
import json

from barbeerdrinker import database

# Flask application

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello World"

@app.route("/api/bar", methods=["GET"])
def get_bars():
    return jsonify(database.get_bars())

@app.route("/api/bar/<name>", methods=["GETS"])
def find_bar(name):
    try:
        if name is None:
            raise ValueError("Bar is not specified")
        bar = database.find_bar(name)
        if bar is None:
            return make_response("No bar found within given name", 404)
        return jsonify(bar)
    except ValueError as e:
        return make_response(str(e), 400)
    except Exception as e:
        return make_response(str(e), 500) 

@app.route("/api/beers_cheaper_than", methods=["POST"])
def find_beers_cheaper_than():
    body = json.loads(request.data)
    max_price = body['maxPrice']
    return jsonify(database.filter_beers(max_price))

数据库.py

from sqlalchemy import create_engine
from sqlalchemy import sql

from barbeerdrinker import config

engine = create_engine(config.database_url)

def get_bars():
    with engine.connect() as con:
        rs = con.execute("SELECT name, address, city, opening, closing, phoneNum FROM bars")
        return [dict(row) for row in rs]

def find_bar(name):
    with engine.connect() as con:
        query = sql.text("SELECT * FROM bars WHERE name = :name;")
        rs = con.execute(query, name=name)
        result = rs.first()
        if result is None:
            return None
        return dict(result)

def filter_beers(max_price):
    with engine.connect() as con:
        query = sql.text("SELECT * FROM sells WHERE price < : max_price;")
        rs = con.execute(query, max_price=max_price)
        results = [dict(row) for row in rs]
        for r in results:
            r['price'] = float(r['price'])
        return results

**编辑:所以问题似乎不是我的代码问题,而是windows错误。我尝试的一个解决方案是通过防火墙打开所需的端口,但没有效果。

u59ebvdq

u59ebvdq1#

我刚想出来,原来这个问题不是windows的问题。这个问题在我的范围内 config.py :
而不是: database_url = "mysql+pymysql://username:password@localhost:3306/barbeerdrinker" 应该是: database_url = "mysql+pymysql://username:password@**AWSENDPOINT/HOSTNAME**:3306/barbeerdrinker"

相关问题