pymongo.errors.ServerSelectionTimeoutError:db:27017:[Errno -2]名称或服务未知

时间:2020-07-28 18:13:16

标签: python api flask pymongo internal-server-error

** im使用flask开发此api,“ /”路由运行正常,但注册路由未运行并给出500INTERNAL SERVER ERROR

我尝试了这个https://pythonexamples.org/pymongo-errors-serverselectiontimeouterror/[solution][1] 根据这篇文章,我检查了mongod是否运行,但是我的mongod没有运行。我使用的端口是标准的27017端口。

i感谢您的帮助或指导 谢谢。 **

**堆栈跟踪如下**

  • 正在投放Flask应用“ app.py”
  • 环境:生产 警告:不要在生产环境中使用开发服务器。 改用生产WSGI服务器。
  • 调试模式:关闭
  • http://127.0.0.1:5000/上运行(按CTRL + C退出) [2020-07-28 23:17:36,761]应用程序中发生错误:/ register [POST]上发生异常 追溯(最近一次通话): 在full_dispatch_request中,文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/flask/app.py”,第1813行 rv = self.dispatch_request() 在dispatch_request中,文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/flask/app.py”,行1799 返回self.view_functionsrule.endpoint 包装中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/flask_restful/init.py”,行468 resp = resource(* args,** kwargs) 在视图中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/flask/views.py”中,第88行 返回self.dispatch_request(* args,** kwargs) 在dispatch_request中,文件583行中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/flask_restful/init.py” resp = meth(* args,** kwargs) 文件“ /home/suraj/Desktop/MyProjects/flask-bank-api/API/app.py”,第30行 如果UserExist(用户名): 文件“ /home/suraj/Desktop/MyProjects/flask-bank-api/API/app.py”,第14行,位于UserExist中 如果users.find({“ Username”:username})。count()== 0: 文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/cursor.py”,行787,计数 cmd,self .__ collat​​ion,session = self .__ session) _count中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/collection.py”,行1600 _cmd,self._read_preference_for(session),session) _retryable_read的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/mongo_client.py”,行1454 read_pref,会话,地址=地址) _select_server中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/mongo_client.py”,行1253 服务器=拓扑。选择服务器(服务器选择器) 在select_server中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/topology.py”,第235行 地址)) 在select_servers中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/topology.py”,第193行 选择器,server_timeout,地址) _select_servers_loop中的文件“ /home/suraj/anaconda3/lib/python3.6/site-packages/pymongo/topology.py”,第209行 self._error_message(选择器) pymongo.errors.ServerSelectionTimeoutError:db:27017:[Errno -2]名称或服务未知 127.0.0.1--[28 / Jul / 2020 23:17:36]“ POST / register HTTP / 1.1” 500-

**我的app.py文件遵循**

from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from pymongo import MongoClient
import bcrypt

app = Flask(__name__)
api = Api(app)

client = MongoClient("mongodb://db:27017")
db = client.MoneyManagementDB
users = db["Users"]

def UserExist(username):
    if users.find({"Username":username}).count() == 0:
        return False
    else:
        return True

class Register(Resource):
    def post(self):
        #Step 1 is to get posted data by the user
        postedData = request.get_json(force=True)

        #Get the data
        username = postedData["username"]
        password = postedData["password"] 
        email = postedData["email"]


        if UserExist(username):
            retJson = {
                'status':301,
                'msg': 'Invalid Username'
            }
            return jsonify(retJson)

        hashed_pw = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())

        #Store username and pw into the database
        users.insert({
            "Username": username,
            "Password": hashed_pw,
            "email":email,
            "Own":0,
            "Debt":0
        })

        retJson = {
            "status": 200,
            "msg": "You successfully signed up for the API"
        }
        return jsonify(retJson)

def verifyPw(username, password):
    if not UserExist(username):
        return False

    hashed_pw = users.find({
        "Username":username
    })[0]["Password"]

    if bcrypt.hashpw(password.encode('utf8'), hashed_pw) == hashed_pw:
        return True
    else:
        return False

def cashWithUser(username):
    cash = users.find({
        "Username":username
    })[0]["Own"]
    return cash

def debtWithUser(username):
    debt = users.find({
        "Username":username
    })[0]["Debt"]
    return debt

def generateReturnDictionary(status, msg):
    retJson = {
        "status": status,
        "msg": msg
    }
    return retJson

def verifyCredentials(username, password):
    if not UserExist(username):
        return generateReturnDictionary(301, "Invalid Username"), True

    correct_pw = verifyPw(username, password)

    if not correct_pw:
        return generateReturnDictionary(302, "Incorrect Password"), True

    return None, False

def updateAccount(username, balance):
    users.update({
        "Username": username
    },{
        "$set":{
            "Own": balance
        }
    })

def updateDebt(username, balance):
    users.update({
        "Username": username
    },{
        "$set":{
            "Debt": balance
        }
    })



class Add(Resource):
    def post(self):
        postedData = request.get_json(force=True)

        username = postedData["username"]
        password = postedData["password"]
        money = postedData["amount"]

        retJson, error = verifyCredentials(username, password)
        if error:
            return jsonify(retJson)

        if money<=0:
            return jsonify(generateReturnDictionary(304, "The money amount entered must be greater than 0"))

        cash = cashWithUser(username)
        money-= 1 #Transaction fee
        #Add transaction fee to bank account
        bank_cash = cashWithUser("BANK")
        updateAccount("BANK", bank_cash+1)

        #Add remaining to user
        updateAccount(username, cash+money)

        return jsonify(generateReturnDictionary(200, "Amount Added Successfully to account"))

class Transfer(Resource):
    def post(self):
        postedData = request.get_json(force=True)

        username = postedData["username"]
        password = postedData["password"]
        to       = postedData["to"]
        money    = postedData["amount"]


        retJson, error = verifyCredentials(username, password)
        if error:
            return jsonify(retJson)

        cash = cashWithUser(username)
        if cash <= 0:
            return jsonify(generateReturnDictionary(303, "You are out of money, please Add Cash or take a loan"))

        if money<=0:
            return jsonify(generateReturnDictionary(304, "The money amount entered must be greater than 0"))

        if not UserExist(to):
            return jsonify(generateReturnDictionary(301, "Recieved username is invalid"))

        cash_from = cashWithUser(username)
        cash_to   = cashWithUser(to)
        bank_cash = cashWithUser("BANK")

        updateAccount("BANK", bank_cash+1)
        updateAccount(to, cash_to+money-1)
        updateAccount(username, cash_from - money)

        retJson = {
            "status":200,
            "msg": "Amount added successfully to account"
        }
        return jsonify(generateReturnDictionary(200, "Amount added successfully to account"))

class Balance(Resource):
    def post(self):
        postedData = request.get_json(force=True)

        username = postedData["username"]
        password = postedData["password"]

        retJson, error = verifyCredentials(username, password)
        if error:
            return jsonify(retJson)

        retJson = users.find({
            "Username": username
        },{
            "Password": 0, #projection
            "_id":0
        })[0]

        return jsonify(retJson)

class TakeLoan(Resource):
    def post(self):
        postedData = request.get_json(force=True)

        username = postedData["username"]
        password = postedData["password"]
        money    = postedData["amount"]

        retJson, error = verifyCredentials(username, password)
        if error:
            return jsonify(retJson)

        cash = cashWithUser(username)
        debt = debtWithUser(username)
        updateAccount(username, cash+money)
        updateDebt(username, debt + money)

        return jsonify(generateReturnDictionary(200, "Loan Added to Your Account"))

class PayLoan(Resource):
    def post(self):
        postedData = request.get_json(force=True)

        username = postedData["username"]
        password = postedData["password"]
        money    = postedData["amount"]

        retJson, error = verifyCredentials(username, password)
        if error:
            return jsonify(retJson)

        cash = cashWithUser(username)

        if cash < money:
            return jsonify(generateReturnDictionary(303, "Not Enough Cash in your account"))

        debt = debtWithUser(username)
        updateAccount(username, cash-money)
        updateDebt(username, debt - money)

        return jsonify(generateReturnDictionary(200, "Loan Paid"))


class test(Resource):
    def get(self):
        return "works fine!!!"



    
api.add_resource(Register, '/register')
api.add_resource(Add, '/add')
api.add_resource(Transfer, '/transfer')
api.add_resource(Balance, '/balance')
api.add_resource(TakeLoan, '/takeloan')
api.add_resource(PayLoan, '/payloan')
api.add_resource(test, '/')





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

0 个答案:

没有答案