gpt4 book ai didi

python - 来自其他文件的 flask 路由器

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:53 28 4
gpt4 key购买 nike

我现在正在构建如下所示的 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 的蓝图,如 app = Blueprint('app', __name__) 并从 server.py 注册它但我得到了 AttributeError: module 'urls' has no attribute 'app' .

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

最佳答案

这里是 Blueprint 的例子。文件结构:

/project_folder
server.py
urls.py
urls2.py

服务器.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/

希望这对您有所帮助。

关于python - 来自其他文件的 flask 路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42608516/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com