How to call a Python Bottle API from within that application

Viewed 212

I have created an API using the Bottle Library in Python. It endpoints look like this

@app.get('/api/users/<id>', name='user')
def get_user(model, id):

    user = model.get_user(id)
    if not user:
        return HTTPError(404, 'User not found')
    else:
        response.content_type = "application/json"
        return json.dumps(user)

I want to call the API in other functions within the same app

@app.route('/users/<id>')
def users (id=1):
    user = request.get("http://localhost:8001/api/user/1")
    return template('user', user=user)

However, this is showing no results. The request get timed out each time

So my question is, how to call a bottle API from within that app using Requests library or through any other means.

1 Answers

Are you running Bottle in single-threaded mode (the default)? If so, then your internal get request will hang forever. This is because your server can serve only one request at a time, and you are asking it to handle two at once: the first call to /users/<id>, and then the second call to /api/users/<id>.

A band-aid fix would be to run the server in asynchronous mode. Try this method and see if your timeouts go away:

run(host='0.0.0.0', port=YOUR_PORT_NUMBER, server='gevent')

However: You shouldn't be designing your application this way in the first place. Instead, refactor your code so that both methods can call a function that returns the JSON representation of a user. Then one api call can return that raw json object, while the other api call can present it as HTML. NOTE: that's not how I would design this API, but it's the answer that's the shortest distance from how you've structured your application so far.

Related