My code
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/api')
def my_microservice():
return jsonify({'Hello': 'World!'})
if __name__ == '__main__':
app.run()
Terminal output
python flask_basic.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Nov/2018 14:14:39] "GET / HTTP/1.1" 404 -
I have checked with lsof -i:5000 command and got nothing.
Why?
You set the route to /api (#app.route('/api')), yet you sent the request to /: "GET / HTTP/1.1".
Either change the route to / or send the request to /api
Related
This question already has answers here:
Configure Flask dev server to be visible across the network
(17 answers)
Closed 4 months ago.
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":"sherbert#acme.com"},
{"company":"ACME","name": "Steve Herbert", "employeeID":"125785", "email":"sherbert#acme.com"}
]
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()
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)
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.
Flask restx is a library that develops api functions by dividing them into files in the flask framework and supports swaggerui.
When serving api and web pages on one flask server, the api part can be divided into files and developed using restx.
However, there is a caution when registering namespace to write flask restx.
The difference between the two source codes below is whether the namespace registration part of api and the app.route function part of api, and whether the namespace registration part of api comes before the app.route or later.
from flask import Flask, render_template, url_for
from datetime import datetime
from flask_restx import Api
from test import test
app = Flask(__name__)
#app.route('/')
def index():
return 'index'
api = Api(
app,
doc="/doc/",
version="0.1",
title="test",
)
api.add_namespace(test, '/test')
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, render_template, url_for
from datetime import datetime
from flask_restx import Api
from test import test
app = Flask(__name__)
api = Api(
app,
doc="/doc/",
version="0.1",
title="test",
)
api.add_namespace(test, '/test')
#app.route('/')
def index():
return 'index'
if __name__ == '__main__':
app.run(debug=True)
First, when executed with the first source code, it is normally recognized when approaching the / and /test path.
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET /test HTTP/1.1" 404 -
However, the second source code recognizes only /test normally and / does not.
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET /test HTTP/1.1" 200 -
It can be seen that the console log and web browser are also displaying 404 errors when approaching / route.
However, in the second source code, not all of the subroutes of / are not possible.
from flask import Flask, render_template, url_for
from datetime import datetime
from flask_restx import Api
from test import test
app = Flask(__name__)
api = Api(
app,
doc="/doc/",
version="0.1",
title="test",
)
api.add_namespace(test, '/test')
#app.route('/')
def index():
return 'index'
#app.route('/main')
def main():
return 'main'
if __name__ == '__main__':
app.run(debug=True)
In this way, / root is not recognized, but /main recognizes.
127.0.0.1 - - [27/Sep/2021 15:40:35] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Sep/2021 15:40:40] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [27/Sep/2021 15:40:45] "GET /main HTTP/1.1" 200 -
I don't know why they do this.
Try leaving the route string empty to see if that works
#app.route('')
def index():
return 'index'
I am new to Python and Flask and I need to work on a code base. I have the following files in directory called migration
Name
app
env
__pycache__
requirements.txt
run.py
In the run.py, I have a the following code:
from app import app
app.run(debug=True)
and inside the app directory, I have one __init__.py, which as code :
from app.helpers import get_page_display_name, get_page_url_name
# from app import views
from flask import Flask
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
app.jinja_env.globals.update(get_page_display_name=get_page_display_name)
app.jinja_env.globals.update(get_page_url_name=get_page_url_name)
Now I have a views.py file inside the same app folder and it has the route configuration and corresponding code like :
#app.route('/')
def index():
if 'username' in session:
return render_template("index.html")
return redirect(url_for('login'))
I am trying to run the application. I have used the following commands:
env/Scripts/activate
This has activated the environment and then:
$env:FLASK_APP=.\run.py
flask run
This has shown a message like it is running on http://127.0.0.1:5000 and printed the following messages when I opened the URL in browser:
127.0.0.1 - - [19/Nov/2020 10:23:15] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Nov/2020 10:23:15] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [19/Nov/2020 10:23:16] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Nov/2020 10:23:17] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Nov/2020 10:23:18] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Nov/2020 10:23:18] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [19/Nov/2020 10:23:18] "GET / HTTP/1.1" 404 -
I have also tried with
$env:FLASK_APP=.\app\views.py
flask run
This also has printed the same message as it is running on the same port, but when opened, the same 404 messages are being shown.
How can I run this application ? I have checked the documentation, but the structure is little different for this application. Thanks in advance for the help.
You have to import your views file after definition of app. I suggest you to use blueprint.
EDIT
views.py
from flask import Blueprint
bp = Blueprint('test', __name__, url_prefix='/')
#bp.route('/')
def index():
if 'username' in session:
return render_template("index.html")
return redirect(url_for('login'))
__init__py
from app.helpers import get_page_display_name, get_page_url_name
from views import bp
from flask import Flask
app = Flask(__name__)
app.register_blueprint(bp)
app.config['JSON_SORT_KEYS'] = False
app.jinja_env.globals.update(get_page_display_name=get_page_display_name)
app.jinja_env.globals.update(get_page_url_name=get_page_url_name)
Changes made to the application.py file don't seem to be detected by the server after I save the file, even though debug mode is on. The only way I've been able to see changes is by exiting the server and restarting with flask run
Here is the code for application.py:
import os
import requests
from flask import Flask, session, render_template, request, url_for, flash, redirect, jsonify
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = 'secret!'
socketio = SocketIO(app)
#app.route("/")
def index():
print('hello world')
return 'hello!'
if __name__ == '__main__':
socketio.run(app, debug=True)
And here's the command line/terminal:
λ flask run
* Serving Flask-SocketIO app "application.py"
* Forcing debug mode on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 156-884-244
(3824) wsgi starting up on http://127.0.0.1:5000
(3824) accepted ('127.0.0.1', 50569)
127.0.0.1 - - [10/Sep/2018 20:07:40] "GET /socket.io/?EIO=3&transport=polling&t=1536624459432-5 HTTP/1.1" 200 381 0.000000
(3824) accepted ('127.0.0.1', 50571)
127.0.0.1 - - [10/Sep/2018 20:07:40] "GET /socket.io/?EIO=3&transport=polling&t=1536624460314-6&sid=79eb8e587f664e3383c946bb046717ca HTTP/1.1" 200 215 0.000000
(3824) accepted ('127.0.0.1', 50568)
127.0.0.1 - - [10/Sep/2018 20:07:44] "GET /socket.io/?EIO=3&transport=websocket&sid=79eb8e587f664e3383c946bb046717ca HTTP/1.1" 200 0 4.610168
hello world
127.0.0.1 - - [10/Sep/2018 20:07:44] "GET / HTTP/1.1" 200 152 0.000000
hello world
127.0.0.1 - - [10/Sep/2018 20:07:58] "GET / HTTP/1.1" 200 152 0.000000
hello world
127.0.0.1 - - [10/Sep/2018 20:08:06] "GET / HTTP/1.1" 200 152 0.000000
wsgi exiting
(3824) wsgi exited, is_accepting=True
Those hello world's in command show up every time I change the text in print('hello world') and refresh the browser. Regardless of what I change it to, I always get the original version of the code's print argument.
Couple things I'm noticing:
this issue doesn't occur when I'm just running Flask. When I'm just running Flask, I see in the command line/terminal that changes were detected.
if I return a template of an HTML file, changes to the HTML file are automatically updated.
Hmm. It looks like the reloader does not work with you run the application via flask run. It does work, however, when you run it by running your application file (i.e. python application.py).
I'll log a bug and investigate.
I am trying to get started with Flask, and I get 404 Not Found error for the hello world program.
The program I use:
from flask import Flask
app = Flask(__name__)
#app.route('/')
#app.route('/index.html')
def hello_world():
return 'Hello, World'
if __name__== '__main__':
app.run(host='localhost')
then I run
$export FLASK_APP = minimal.py
$flask run
Which returns:
* Serving Flask app "minimal"
* Forcing debug mode on
* Restarting with stat
* Debugger is active!
* Debugger PIN 127-804-808
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
When I visit http://localhost:5000 or http://127.0.0.1:5000, I get:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
And my host file looks like this:
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
Any idea whats wrong? Thank you
Yeah, you can remove the error 404 not found in following ways:
1: You should write command netstat -a -b to check which port is not free or busy doing something or
2: write in your code app.run(port=4996) instead of app.run() which by default choose port no. 50000.