Flask api server not working across local network

Question:

I have a Flask api server running, worked absolutely fine on 127.0.0.1 right up until I started tinkering with trying to get it working across the LAN. I can see the connections from other devices on the LAN in the debug log, and it is receiving the connections fine, but not serving any pages, only 404, but not even my custom 404.
I have enabled Network Discovery, set network to Private, allowed Python through the firewall and tried using a non standard port (51234), disabled firewalls but I still get 404 errors.

127.0.0.1 - - [20/Oct/2022 12:38:00] "GET / HTTP/1.1" 404 -
192.168.1.205 - - [20/Oct/2022 12:38:11] "GET /api/companies?id=1 HTTP/1.1" 404 -
192.168.1.168 - - [20/Oct/2022 12:38:25] "GET / HTTP/1.1" 404 -
192.168.1.113 - - [20/Oct/2022 12:38:41] "GET / HTTP/1.1" 404 -
192.168.1.205 - - [20/Oct/2022 12:43:58] "GET / HTTP/1.1" 404 - 

So in order to test it, I went back to basics and only allowed localhost again, and now nothing is working!

* Serving Flask app 'training_server' * Debug mode: on * Running on http://127.0.0.1:5155 Press CTRL+C to quit * Restarting with stat * Debugger is active! 127.0.0.1 - - [20/Oct/2022 12:44:54] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [20/Oct/2022 12:45:12] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [20/Oct/2022 12:45:12] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - [20/Oct/2022 12:50:09] "GET / HTTP/1.1" 404 -

from flask import Flask, json, jsonify, request

companies = [{"id": 0, "name": "ACME", "state":"Essex"}, 
{"id": 1, "name": "Bluebell", "state":"Hertfordshire"}
]

users = [{"company":"ACME","name": "Steve Herbert", "employeeID":"125785", "email":"[email protected]"}, 
{"company":"ACME","name": "Steve Herbert", "employeeID":"125785", "email":"[email protected]"}
]

api = Flask(__name__)
api.config["DEBUG"] = True
api.config['JSON_SORT_KEYS'] = False
api.run(host='127.0.0.1', port=5155)

@api.route('/', methods=['GET'])
def home():
    return "<h1>Company Directory</h1><p>This site is a prototype API for company directory listing.</p>"

@api.route('/api/companies/all', methods=['GET'])
def get_companies():
    return jsonify(companies)
    
@api.route('/api/companies', methods=['GET'])
# Check if a param was provided as part of the URL.
# If param is provided, assign it to a variable. If not, display an error in the browser.
def get_company():
    print('req' + str(request.args))
    print('hello' + next(iter(request.args.keys())))
    #print([elem[0:] for elem in request.args.keys()])
    
    if 'id' in request.args:
        filter = next(iter(request.args.keys()))
        param = int(next(iter(request.args.values())))
    elif 'name' in request.args:
        filter = next(iter(request.args.keys()))
        param = str(next(iter(request.args.values())))
    else:
        return "Error: No param field provided. Please specify a value."
        
    results = apiParam(param, filter, companies)
    return jsonify(results)
    

def apiParam(param, filter, list):
    print('filter' + str(filter))
    results = []
    # Loop through the data and match results that fit the requested parameter.
    for li in list:
        if li[filter] == param:
            results.append(li)
    return results
  
     
if __name__ == '__main__':
    api.run() 
Asked By: jerrythebum

||

Answers:

Fixed it after some more research/Googling while I waited for answers

Moved the host declaration to underneath the if name call

import os

if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5155))
    api.run(host='0.0.0.0', port=port)
Answered By: jerrythebum

The problem comes from run.api() at the start. This is blocking the script so the route handlers are never reached.

Move that line to the end, inside the if __name__ block.

Answered By: VagrantPaladin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.