Python flask Main class 给出“127.0.0.1 - - [05/May/2022 09:27:04] "GET / HTTP/1.1" 404 - 127”

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

我正在创建一个 Python 脚本,该脚本使用 flask 为我提供 json 图书列表。

我的问题是,当我转到 URL 时,我得到以下信息:

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

并且 Python 声明如下:

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 -

这是我的 Python 代码:

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

找不到路由,因为 Flask 应用 运行 在定义路由之前。

我已经进行了更改,现在可以使用了。

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

问题是您在 def __init__() 和其他路由之前声明了命令 app.run(host="localhost", port=3000, debug=True)

所以你应该把那个命令移到最后一行。