0

I'm trying to create a python flask script that will add a row to a database. Here's my code:

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

And finally, my 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

Unfortunately, upon testing it in CocoaRestClient, via http://127.0.0.1:5000/customers/addtest:

enter image description here

I get the following unhelpful error:

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

And I have no idea what's wrong. Can I have some help, please?

1 Answer 1

1

The last two lines of your query and commit_ret_lastrow methods don't make any sense. If there's an exception, you catch it, and then return it. So Flask tries to serve it as your actual app, which it obviously can't do.

Drop those lines, and the try/except completely. You shouldn't be catching all exceptions anyway; maybe, if you're sure, you could catch a specific database exception - eg IntegrityError - but usually you should only catch the ones you know that you can deal with. Otherwise, simply let the exception bubble up, and the framework can log or display it.

Sign up to request clarification or add additional context in comments.

1 Comment

I removed the entire try / except and found out what caused it - one of my fields was misspelled in the query. I'm still getting a TypeError: 'long' object is not callable (possibly something to do with the return statement, as it was inserted into the database anyway). Anyway, could I ask for a suggestion on how to better implement try / except for the DB connection part? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.