我正在尝试创建一个 python Flask 脚本,它将向数据库添加一行。这是我的代码:
main.py
:
import json
import sys
from flask import Flask, request
from app.config import DB
from app.items.items import ItemsAPI
from app.users.accounts import AccountsAPI
from app.users.customers import CustomersAPI
app = Flask(__name__)
db = DB()
app.register_blueprint(ItemsAPI)
app.register_blueprint(CustomersAPI)
app.register_blueprint(AccountsAPI)
@app.route('/home')
def hello_world():
return "Welcome to Omnimoda."
@app.route('/dbtest', methods=['GET'])
def hello_database():
q_sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = %s"
a_sql = ("omnimoda",)
test_request = db.query(q_sql, a_sql)
result_request = test_request.fetchall()
if (result_request is None):
return "Database does not exist."
else:
return "Database exists."
if __name__ == '__main__':
app.run(host = '0.0.0.0', debug=True)
customers.py
:
from flask import Flask, request, jsonify, json, Blueprint
#from time import mktime
from json import dumps
from datetime import datetime
from app.config import DB
CustomersAPI = Blueprint('CustomersAPI', __name__)
db = DB()
@CustomersAPI.route('/customers/addtest', methods=['POST'])
def add_test():
first_name = request.form['first_name']
last_name = request.form['last_name']
birthdate = request.form['birthdate']
email = request.form['email']
gender = request.form['gender']
occupation = request.form['occupation']
address = request.form['address']
others = request.form['others']
q_add_one = "INSERT INTO `customer_info` (`first_name`, `last_name`, `birthdate`, `init_email`, `gender`, `occupation`, `address`, `others`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"
a_add_one = (first_name, last_name, birthdate, email, gender, occupation, address, others)
items_add = db.commit_ret_lastrow(q_add_one, a_add_one)
return items_add
最后,我的 config.py
:
from flask import Flask
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect(host="localhost", user="lance", passwd="lance", db="omnimoda")
self.conn.autocommit(True)
def query(self, sql, values):
try:
print values
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql, values)
return cursor
except Exception, e:
return e
def commit_ret_lastrow(self, sql, values):
try:
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql, values)
return cursor.lastrowid
except Exception, e:
return e
不幸的是,在 CocoaRestClient 中通过 http://127.0.0.1:5000/customers/addtest
进行测试时:
我收到以下无用的错误:
127.0.0.1 - - [30/Jun/2015 22:04:22] "POST /customers/addtest HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Library/Python/2.7/site-packages/werkzeug/test.py", line 867, in run_wsgi_app
app_iter = app(environ, start_response)
TypeError: 'OperationalError' object is not callable
我不知道出了什么问题。请问我可以帮忙吗?
最佳答案
查询和 commit_ret_lastrow 方法的最后两行没有任何意义。如果出现异常,您可以捕获它,然后返回它。因此 Flask 尝试将其作为您的实际应用程序提供服务,但这显然是做不到的。
完全删除这些行和 try/except 。无论如何,你不应该捕获所有异常;也许,如果您确定,您可以捕获特定的数据库异常 - 例如 IntegrityError - 但通常您应该只捕获您知道可以处理的异常。否则,只需让异常冒泡,框架就可以记录或显示它。
关于Python flask : Getting an 'OperationalError' object is not callable when inserting to database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31140668/