Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python flask Main class gives "127.0.0.1 – – [05/May/2022 09:27:04] "GET / HTTP/1.1" 404 – 127"

I am creating a Python script that uses flask to give me a list of books as json.

My problem is that when I go to the URLs I get the following:

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 Python states the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C:\Users\s\AppData\Local\Programs\Python\Python310\python.exe C:/Users/s/PycharmProjects/TodayPython/Main.py
 * Serving Flask app 'Main' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:3000 (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 100-706-506
127.0.0.1 - - [05/May/2022 09:27:04] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [05/May/2022 09:27:04] "GET /favicon.ico HTTP/1.1" 404 -

This is my Python code:

Main.py

import flask
from flask import jsonify, request


class Main:
    app = flask.Flask(__name__)  # Creates the Flask application object
    app.config["DEBUG"] = True

    app.run(host="localhost", port=3000, debug=True)

    def __init__(self):

        # Create some test data for our catalog in the form of a list of dictionaries.
        books = [
            {'id': 0,
             'title': 'A Fire Upon the Deep',
             'author': 'Vernor Vinge',
             'first_sentence': 'The coldsleep itself was dreamless.',
             'year_published': '1992'},
            {'id': 1,
             'title': 'The Ones Who Walk Away From Omelas',
             'author': 'Ursula K. Le Guin',
             'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
             'published': '1973'},
            {'id': 2,
             'title': 'Dhalgren',
             'author': 'Samuel R. Delany',
             'first_sentence': 'to wound the autumnal city.',
             'published': '1975'}
        ]



    @app.route('/', methods=['GET'])
    def home(self):
        return '''<h1>Distant Reading Archive</h1>
    <p>A prototype API for distant reading of science fiction novels.</p>'''



    @app.route('/api/v1/resources/books/all', methods=['GET'])
    def api_all(self):
        return jsonify(self.books)


    @app.route('/api/v1/resources/books', methods=['GET'])
    def api_id(self):
        # Check if an ID was provided as part of the URL.
        # If ID is provided, assign it to a variable.
        # If no ID is provided, display an error in the browser.
        if 'id' in request.args:
            id = int(request.args['id'])
        else:
            return "Error: No id field provided. Please specify an id."

        # Create an empty list for our results
        results = []

        # Loop through the data and match results that fit the requested ID.
        # IDs are unique, but other fields might return many results
        for book in self.books:
            if book['id'] == id:
                results.append(book)

        # Use the jsonify function from Flask to convert our list of
        # Python dictionaries to the JSON format.
        return jsonify(results)
Main();

>Solution :

The routes weren’t found because the Flask app ran before the routes were defined.

I’ve gone ahead and did the changes and it is now working.

import flask
from flask import jsonify, request


class Main:
    app = flask.Flask(__name__)  # Creates the Flask application object
    app.config["DEBUG"] = True

    def __init__(self):
        # Create some test data for our catalog in the form of a list of dictionaries.
        self.books = [
            {'id': 0,
             'title': 'A Fire Upon the Deep',
             'author': 'Vernor Vinge',
             'first_sentence': 'The coldsleep itself was dreamless.',
             'year_published': '1992'},
            {'id': 1,
             'title': 'The Ones Who Walk Away From Omelas',
             'author': 'Ursula K. Le Guin',
             'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
             'published': '1973'},
            {'id': 2,
             'title': 'Dhalgren',
             'author': 'Samuel R. Delany',
             'first_sentence': 'to wound the autumnal city.',
             'published': '1975'}
        ]
        @self.app.route('/', methods=['GET'])
        def __home():
            return self.home()
        @self.app.route('/api/v1/resources/books/all', methods=['GET'])
        def __api_all():
            return self.api_all()
        @self.app.route('/api/v1/resources/books', methods=['GET'])
        def __api_id():
            return self.api_id()
        
        self.app.run(host="localhost", port=3000, debug=True)
        

    def home(self):
        return '''<h1>Distant Reading Archive</h1>
    <p>A prototype API for distant reading of science fiction novels.</p>'''

    def api_all(self):
        return jsonify(self.books)

    def api_id(self):
        # Check if an ID was provided as part of the URL.
        # If ID is provided, assign it to a variable.
        # If no ID is provided, display an error in the browser.
        if 'id' in request.args:
            id = int(request.args['id'])
        else:
            return "Error: No id field provided. Please specify an id."

        # Create an empty list for our results
        results = []

        # Loop through the data and match results that fit the requested ID.
        # IDs are unique, but other fields might return many results
        for book in self.books:
            if book['id'] == id:
                results.append(book)

        # Use the jsonify function from Flask to convert our list of
        # Python dictionaries to the JSON format.
        return jsonify(results)
Main();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading