我无法与SQL通信

时间:2017-01-31 15:28:04

标签: python mysql flask

我尝试连接到MySQL,它没有显示用户添加的成功状态,我收到以下错误:

{"message": "The method is not allowed for the requested URL."}

我不明白它所说的“方法”是什么...... POST我正在使用POSTMAN?一些帮助将不胜感激!

所以我改变我的代码把MySQL()放在POST方法中,我仍然得到同样的错误....

这是我的“api.py”代码:

from flask import Flask
from flask_restful import Resource, Api, reqparse
from flaskext.mysql import MySQL

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

class CreateUser(Resource):
    def post(self):
        try:
            # Parse the arguments
            parser = reqparse.RequestParser()
            parser.add_argument('email', type=str, help='Email address to create user')
            parser.add_argument('password', type=str, help='Password to create user')
            args = parser.parse_args()

            _userEmail = args['email']
            _userPassword = args['password']

            return {'Email': args['email'], 'Password': args['password']}

            mysql = MySQL()
            # MySQL configurations
            app.config['MYSQL_DATABASE_USER'] = 'root'
            app.config['MYSQL_DATABASE_DB'] = 'itemlistdb'
            app.config['MYSQL_DATABASE_HOST'] = 'localhost'

            mysql.init_app(app)

            conn = mysql.connect()

            cursor = conn.cursor()

            cursor.callproc('spCreateUser',(_userEmail,_userPassword))
            data = cursor.fetchall()

            if len(data) is 0:
               conn.commit()
               return {'StatusCode':'200','Message': 'User creation success'}
            else:
               return {'StatusCode':'1000','Message': str(data[0])}

        except Exception as e:
            return {'error': str(e)}

api.add_resource(CreateUser, '/CreateUser')

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

我使用存储过程在db中写入值,过程是spCreateUser,这里是代码:

BEGIN

if ( select exists (select 1 from tblUser where UserName = p_username) )
THEN

select 'Username Exists !!';

ELSE

insert into tblUser(
UserName,
Password
)
values
(
p_Username,
p_Password
);

END IF;

END

2 个答案:

答案 0 :(得分:0)

  

如果使用不受支持的HTTP方法调用资源,API将返回状态为405 Method Not Allowed的响应。

我猜你试图在浏览器上查看你的资源,所以你有这个错误。如果您想在浏览器上查看资源,则必须支持http get方法。

class CreateUser(Resource):
    def post(self):
        cur.execute("INSERT INTO table VALUES(?,?)",(email,password))
    def get(self):
        #...

还有一个QueryDb方法不会被self调用,你必须在http方法中调用它。

答案 1 :(得分:0)

好的,我解决了所有问题......可能对其他人有用:

首先我把这个函数的名字放在" post"不是"发布"。

然后我收到以下消息:

"在处理完第一个请求后调用了一个设置函数"

解决这个问题的方法是禁用调试模式......

所以这里的代码正在运行:

from flask import Flask
from flask_restful import Resource, Api, reqparse
from flaskext.mysql import MySQL

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

class CreateUser(Resource):
     def post(self):
        try:
            # Parse the arguments
            parser = reqparse.RequestParser()
            parser.add_argument('email', type=str, help='Email address to create user')
            parser.add_argument('password', type=str, help='Password to create user')
            args = parser.parse_args()

            _userEmail = args['email']
            _userPassword = args['password']

            #return {'Email': args['email'], 'Password': args['password']}

            mysql = MySQL()
            # MySQL configurations
            app.config['MYSQL_DATABASE_USER'] = 'root'
            app.config['MYSQL_DATABASE_DB'] = 'itemlistdb'
            app.config['MYSQL_DATABASE_HOST'] = 'localhost'

            mysql.init_app(app)

            conn = mysql.connect()

            cursor = conn.cursor()

            cursor.callproc('spCreateUser',(_userEmail,_userPassword))
            data = cursor.fetchall()

            if len(data) is 0:
               conn.commit()
               return {'StatusCode':'200','Message': 'User creation success'}
               cursor.close()
               conn.close() 
            else:
               return {'StatusCode':'1000','Message': str(data[0])}
               cursor.close()
               conn.close()

        except Exception as e:
            return {'error': str(e)}

api.add_resource(CreateUser, '/CreateUser')

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