Почему моя индексная HTML-страница не показывает конечную точку '/', но работает для других конечных точек в Python Eve? - PullRequest
0 голосов
/ 31 октября 2019

Я настроил веб-сервер, который обслуживает определенное доменное имя, где я хотел бы, чтобы статические страницы и шаблоны отображались из данных в MongoDB с использованием инфраструктуры Flask (Python Eve). У меня есть главная страница, хранящаяся в шаблоне index.html, предназначенном для конечной точки /, и страница входа в систему на конечной точке /login, которая отлично работает с помощью команды render_template('login.html'). Однако render_template() не работает для конечной точки /, независимо от того, какой шаблон я укажу. Если я настрою конечную точку /test и отредактирую шаблон index.html, он нормально загрузится в браузере. Ниже приведены файлы __init__.py и settings.py для веб-приложения, соответственно (учетные данные mongo были исключены X'ed). Я был бы очень признателен за любую помощь, которую кто-либо может оказать! Огромное спасибо.

__init__.py

# import the Flask class from the flask module                                                                                                                                    
import bcrypt
from flask import Flask, render_template, redirect, url_for, request
from eve import Eve
from eve.auth import BasicAuth
from flask import current_app as app

debug=True

class MyBasicAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource,
                   method):
        if resource in ('index', 'test'):
            return True
        else:
            return username == 'admin' and password == 'secret'


# create the application object                                                                                                                                                   
app = Eve(__name__, auth=MyBasicAuth)

# use decorators to link the function to a url                                                                                                                                    
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/test')
def test():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'admin':
            error = 'Invalid credentials. Please try again.'
        else:
            return redirect(url_for('index'))
    return render_template('login.html', error=error)


# start the server with the run() method                                                                                                                                          
if __name__ == '__main__':
    app = Eve(auth=MyBasicAuth)
    app.run(debug=True,port=8080)

settings.py

MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = XXXXXXXX
MONGO_USERNAME = XXXXXXXXX
MONGO_PASSWORD = XXXXXXXXX



# cross-domains                                                                                                                                 
#X_DOMAINS= '*'                                                                                                                                 
#X_ALLOW_CREDENTIALS=True                                                                                                                       
#X_HEADERS=['Authorization']                                                                                                                    

# Only index is public, the rest requires full authentication to use REST API                                                                   
#DOMAIN = {}                                                                                                                                    
PUBLIC_METHODS = ['GET']
PUBLIC_ITEM_METHODS = ['GET']
DOMAIN = {
    'accountlogin': {
        'public_methods': [],
        'public_item_methods': [],
        }
    }

#URL_PREFIX= 'api'   # By doing this whenever there is request to /, Eve(Flask) will not return the resource catalog instead returns the page a\
s given in __init__.py.                                                                                                                         

schema =  {
    'username': {
        'type': 'string',
        'required': True,
        'unique': True,
        },
    'password': {
        'type': 'string',
        'required': True,
    },
}

accounts = {
    # the standard account entry point is defined as                                                                                            
    # '/accounts/<ObjectId>'. We define  an additional read-only entry                                                                          
    # point accessible at '/accounts/<username>'.                                                                                               
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'username',
    },

    # We also disable endpoint caching as we don't want client apps to                                                                          
    # cache account data.                                                                                                                       
    'cache_control': '',
    'cache_expires': 0,

    # Finally, let's add the schema definition for this endpoint.                                                                               
    'schema': schema,
}



...