Search code examples
pythonflaskflask-restful

How to return exact error from the python script through flask


I am calling python function to call a script to create a directory.

app = Flask(__name__)

 

@app.route('/', methods=['POST'])

def share_drive():

    try:
    
        parentdir = request.json.get("parentdir")

        dirname = request.json.get("dirname")

        #parentdir = request.values.get("parentdir")

        #dirname = request.values.get("dirname")

                path = os.path.join(parentdir, dirname)

    # makedirs create directory recursively

    try:
    
        os.makedirs(path)

        #return ("Success Fileshare created: {} ".format(dirname))
        resp = make_resopnse('{} successfully created.'.format(dirname))
        resp.status_code = 200
        return resp
    
    except OSError as error:
    
        #return ("Fileshare creation failed: {} ".format(dirname))       
        resp = make_resopnse('Failed to create fileshare {}'.format(dirname))
        resp.status_code = 400
        return resp 

I am calling it through post man, return statements are working. But I am making response from return and passing resp.status code and that part is failing.

Error in post man

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

Solution

  •     os.makedirs(path)
    
        #return ("Success Fileshare created: {} ".format(dirname))
        resp = Response('{} successfully created.'.format(dirname))
        print (resp)
        resp.status_code = 200
        return resp
    
    except OSError as error:
    
        #print(error)
        resp = Response('{} fileshare creation failed.{} filename  already exists'.format(dirname, error))
        print (resp)
        resp.status_code = 200
        return resp 
        #return ("Fileshare creation failed: {} ".format(dirname)) 
    

    This has fixed.