【问题标题】:Flask router from other file来自其他文件的烧瓶路由器
【发布时间】:2017-07-25 07:30:39
【问题描述】:

我现在正在构建如下所示的 Flask 应用程序。

myserver
- server.py
- myapp
-- urls.py
-- models.py
-- views.py
-- consts.py

我的代码在这里。

server.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# Flask App
application = Flask(__name__)

# SQLAlchemy
application.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:./local.db"
db = SQLAlchemy(application)

if __name__ == "__main__":
    application.run(debug=True)

urls.py

from server import application
from . import views

@application.route('/')
def version():
    return views.version()

但是当我运行 server.py 并打开 http://localhost:5000/ 服务器时显示 404 Not Found

于是我在stackoverflow上搜索,发现了一些关于Blueprint的描述。我制作了像 app = Blueprint('app', __name__) 这样的蓝图命名应用程序并从 server.py 注册它但我得到了 AttributeError: module 'urls' has no attribute 'app'

如何在其他文件中定义 url 路由器?

【问题讨论】:

  • 您正在调用“应用程序”,但 python 不知道“应用程序”是什么。您是否忘记还为“应用程序”添加导入?你能发布更新的代码吗?
  • @FuzzyAmi 我也在server.py from myapp import urls 和注册的蓝图urls.app 中添加了这一行

标签: python flask routes attributeerror


【解决方案1】:

这里以Blueprint 为例。文件结构:

/project_folder
   server.py
   urls.py
   urls2.py

server.py:

from flask import Flask
from urls import urls_blueprint
from urls2 import urls2_blueprint


app = Flask(__name__)
# register routes from urls
app.register_blueprint(urls_blueprint)
# we can register routes with specific prefix
app.register_blueprint(urls2_blueprint, url_prefix='/urls2')

if __name__ == "__main__":
    app.run(debug=True)

urls.py:

from flask import Blueprint

urls_blueprint = Blueprint('urls', __name__,)


@urls_blueprint.route('/')
def index():
    return 'urls index route'

urls2.py:

from flask import Blueprint
urls2_blueprint = Blueprint('urls2', __name__,)


@urls2_blueprint.route('/')
def index():
    return 'urls2 index route'

运行服务器并打开http://localhost:5000/http://localhost:5000/urls2/

希望这会有所帮助。

【讨论】:

  • 我的问题与蓝图无关,但感谢您的回答:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多