本文介绍了分割应用程式和检视程式码时出现NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的代码分为两部分,应用程序初始化和视图定义.我导入视图并定义我的应用程序,但得到NameError: name 'manager' is not defined.为什么会出现此错误?如何正确分割我的代码?

I want to divide my code into two parts, the app initialization and the view definitions. I import my views and define my app, but I get NameError: name 'manager' is not defined. Why am I getting this error? How do I split up my code correctly?

manage.py:

from flask import Flask,render_template
from flask.ext.script import Manager

import viewports

manager = Flask(__name__)

if __name__=='__main__':
     manager.run()

viewports.py

@manager.route('/')
def Home():
     return render_template('Home.html', title='FrontPage')

推荐答案

您创建了一个循环导入:首先导入viewports,它导入manager,只有在导入viewports之后才定义.您还没有正确组织代码,所有内容都应放在一个程序包中.您还将创建Flask-Script管理器与创建Flask应用程序混淆了.另外,不建议使用flask.ext,直接从程序包名称导入.

You created a circular import: first you import viewports, which imports manager, which is only defined after you import viewports. You also didn't organize your code correctly, everything should be under one package. You also confused creating a Flask-Script manager with creating a Flask app. Also, flask.ext is deprecated, import directly from the package name.

my_project/
    my_app/
        __init__.py
        views.py
    manage.py

__init__.py:

from flask import Flask
from flask_script import Manager

app = Flask(__name__)
manager = Manager(app)

from my_app import views

views.py:

from my_app import app

@app.route('/')
def index():
    return 'Hello, World!'

manage.py:

from my_app import manager

manager.run()

这篇关于分割应用程式和检视程式码时出现NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 01:24