skip to Main Content

I am new to Flask, I wanted to know few things around it, like how to create a REST api
i am getting this error TypeError: The view function for 'create_employee' did not return a valid response

Been checking some stuff on the internet and not been able to see this to solve this correctly.

My source code is looking like this :

import pymysql
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request


@app.route('/api/create',methods=['POST'])
def create_employee():
    try:
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _phone = _json['phone']
        _address = _json['address']
        _salary = _json['salary']

        if _name and _email and _phone  and _address and _salary and request.methods == 'POST' :
            conn = mysql.connect()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            query = "insert into empData (name, email, phone, address, salary) values (%s, %s,%s, %s,%s)"
            bindData = (_name, _email, _phone, _address, _salary)
            cursor.execute(query,bindData)  
            conn.commit()
            respone = jsonify({"message":"OK"})
            respone.status_code = 200
            return respone
        else:
            return showMessage()
    except Exception as e:
        print(e)


@app.route('/api/employee')
def listEmployee():
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("select * from empData")
        empRows = cursor.fetchall()
        respone = jsonify(empRows)
        respone.status_code = 200
        return respone
    except Exception as e:
        print(e)


@app.route('/api/employee/<int:emp_id>')
def listsingleEmployee(emp_id):
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("select * from empData where id = %s", emp_id)
        empRows = cursor.fetchone()
        respone = jsonify(empRows)
        respone.status_code = 200
        return respone
    except Exception as e:
        print(e)


@app.route('/api/update',methods=['PUT'])
def update_employee():
    try:
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _phone = _json['phone']
        _address = _json['address']
        _salary = _json['salary']

        if _name and _email and _phone  and _address and _salary and request.methods == 'PUT' :
            conn = mysql.connect()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            #query = "insert into empData (name, email, phone, address, salary) values (%s, %s,%s, %s,%s)"
            query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
            bindData = (_name, _email, _phone, _address, _salary)
            cursor.execute(query,bindData)  
            conn.commit()
            respone = jsonify({"message":"OK"})
            respone.status_code = 200
            return respone
        else:
            return showMessage()
    except Exception as e:
        print(e)



@app.errorhandler(404)
def showMessage(error=None):
    message = {
        'status': 404,
        'message': 'Record not found: ' + request.url,
    }
    respone = jsonify(message)
    respone.status_code = 404
    return respone

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

I am just starting out with Flask today. I kind of need clarification in this point.

2

Answers


  1. Chosen as BEST ANSWER

    I fixed it :) Thanks people. had to closely look at the documentation and some quick videos again

    The code looks like this

    main.py

    import pymysql
    from app import app
    from config import mysql
    from flask import jsonify
    from flask import flash, request
    
    
    @app.route('/api/create',methods=['POST'])
    def create_employee():
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _phone = _json['phone']
        _address = _json['address']
        _salary = _json['salary']
    
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        query = "insert into empData (name, email, phone, address, salary) values (%s, %s,%s, %s,%s)"
                #query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
        bindData = (_name, _email, _phone, _address, _salary)
        cursor.execute(query,bindData)  
        conn.commit()
        cursor.close()
        output = {'name':_name, 'email':_phone, 'address':_address, 'salary':_salary, 'message':'ok'}
    
        return jsonify({'result':output})
    
    
    
    @app.route('/api/employee')
    def listEmployee():
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("select * from empData")
        empRows = cursor.fetchall()
        respone = jsonify(empRows)
        respone.status_code = 200
        return respone
    
    
    
    @app.route('/api/employee/<int:emp_id>')
    def listsingleEmployee(emp_id):
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("select * from empData where id = %s", emp_id)
        empRows = cursor.fetchone()
        respone = jsonify(empRows)
        respone.status_code = 200
        return respone
        
    
    
    @app.route('/api/update',methods=['PUT'])
    def update_employee():
        _json = request.json
        _name = _json['name']
        _email = _json['email']
        _phone = _json['phone']
        _address = _json['address']
        _salary = _json['salary']
    
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
                #query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
        bindData = (_name, _email, _phone, _address, _salary)
        cursor.execute(query,bindData)  
        conn.commit()
        cursor.close()
        output = {'name':_name, 'email':_phone, 'address':_address, 'salary':_salary, 'message':'ok'}
    
        return jsonify({'result':output})
    
    
    
    @app.errorhandler(404)
    def showMessage(error=None):
        message = {
            'status': 404,
            'message': 'Record not found: ' + request.url,
        }
        respone = jsonify(message)
        respone.status_code = 404
        return respone
    
    if __name__ == "__main__":
        app.run()
    

    app.py

    from flask import Flask
    from flask_cors import CORS, cross_origin
    
    app = Flask(__name__)
    CORS(app)
    

    config.py

    from app import app
    from flaskext.mysql import MySQL
    
    mysql = MySQL()
    app.config['MYSQL_DATABASE_USER'] = 'root'
    app.config['MYSQL_DATABASE_PASSWORD'] = ''
    app.config['MYSQL_DATABASE_DB'] = 'empdb5'
    app.config['MYSQL_DATABASE_HOST'] = 'localhost'
    mysql.init_app(app)
    

    Which is exactly what i needed, Just need to have good understanding og indentation. Thanks everyone.


  2. In flask,you not need return a response,just need return jsonify(),maybe you need read the document carefully

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search