Home > Back-end >  Python flask Main class gives "127.0.0.1 - - [05/May/2022 09:27:04] "GET / HTTP/1.1"
Python flask Main class gives "127.0.0.1 - - [05/May/2022 09:27:04] "GET / HTTP/1.1"

Time:05-05

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:

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();

CodePudding user response:

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();

CodePudding user response:

The problem is you declare command app.run(host="localhost", port=3000, debug=True) before def init() and other route. So you should push it to the last line

  • Related