question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

routing for flask_restful is not working

See original GitHub issue

Subsequent to my last issue I now have SPA React pages served from my docker container.

But the flask_restful implementation seems to hide the route information normally exposed using the @app.route annotation. My main.py (webapp.py in my case) has the following:

from flask_restful import Api
...
api = Api(app)

api.add_resource(resources.Login, '/api/login', methods=['POST'])
api.add_resource(resources.Logout, '/api/logout', methods=['POST'])
api.add_resource(resources.RegisterOtp, '/api/register_otp', methods=['POST'])
...
@app.route('/', methods=['POST', 'GET'])
def index():
    index_path = os.path.join(app.static_folder, 'index.html')
    return send_file(index_path)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

@app.errorhandler(500)
def server_error(e):
    logging.exception('An error occurred during a request. %s', e)
    return "An internal error occurred", 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=80, use_reloader=False)

The additional nginx config, derived from what I has when running native with werkzurg serving on port 5000 is as follows:

server {
    listen       80;
    server_name  localhost;
    root         /app/ui;

    index index.html index.htm;
    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /api {
            proxy_redirect          off;
            proxy_pass_header       Server;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Scheme $scheme;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-NginX-Proxy true;
            proxy_connect_timeout   5;
            proxy_read_timeout      240;
            proxy_intercept_errors  on;
            proxy_pass http://127.0.0.1:5000;
        }

    error_page 404 /404.html;
            location = /40x.html {
        }

    error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
}

I realise that uwsgi is not serving on port 5000, but it is not clear on what changes I need to make.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
tiangolocommented, Apr 12, 2020

I don’t use Flask-Restful, as I would instead use FastAPI 🤷‍♂️ , but anyway, here’s a working example:

.
├── app
│   ├── main.py
│   └── uwsgi.ini
├── Dockerfile
└── requirements.txt

app/main.py:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/rest/<string:todo_id>')

@app.route("/hello")
def hello():
    return "Hello"

if __name__ == '__main__':
    app.run(debug=True)

app/uwsgi.ini:

[uwsgi]
module = main
callable = app

Dockerfile:

FROM tiangolo/uwsgi-nginx-flask:python3.7

COPY requirements.txt /tmp/
RUN pip install -r /tmp/requirements.txt
COPY ./app /app

requirements.txt:

flask
flask_restful

$ docker build -t restfully .

---> 100%

$ docker run -d --name restfully -p 80:80 restfully

c61078da16d22

// Check that standard Flask works
$  curl http://localhost/hello

Hello

$ curl http://localhost/rest/todo1 -d "data=Remember the milk" -X PUT

{"todo1": "Remember the milk"}

$ curl http://localhost/rest/todo1

// Error because it was probably served by one of the processes that don't have the dict in memory, still, you wouldn't store that in memory but in a DB
{"message": "Internal Server Error"}

// But try again
$ curl http://localhost/rest/todo1

// It's probably served by the process that has the dict in memory
{"todo1": "Remember the milk"}

I hope that can help to guide you to solve your own issues.

0reactions
github-actions[bot]commented, May 6, 2020

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Python Flask App route not working as expected
Are you restarting the server when reloading @app.route('/') ? Also, try clearing your cache. With Chrome, you can do that by hitting SHIFT ......
Read more >
Flask routing not working
Flask routing not working ; from flask import Flask ; app = Flask( ; __name__, ; template_folder='templates', ; static_folder='static'.
Read more >
The Art of Routing in Flask
Empower your Flask application to grow dynamically with intelligent ... This means that changing route URLs won't result in broken links between pages!...
Read more >
Flask App Routing
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more...
Read more >
Quickstart — Flask Documentation (2.2.x)
flask --app hello --debug run * Serving Flask app 'hello' * Debug mode: on * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) *...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found