python - Flask:在一个应用程序中使用多个包

标签 python routing blogs package flask

我刚开始使用 flask ,但遇到了障碍。我正在尝试写一个小博客来适应这个框架,所以我做了两个包,一个“auth”和“posts”。我通读了 Flask docs 中的大型应用程序部分。 .

我的目录如下所示。

>/root
>>run.py 

>>/posts

>>>____init____.py  
>>>views.py  
>>>/templates
>>>/static  

>>/auth  
>>>____init____.py  
>>>views.py  
>>>/templates
>>>/static

run.py 看起来像这样:

from flask import Flask
from auth import auth_app
from posts import posts_app

auth_app.run()
posts_app.run()

/posts/__init__.py/auth/__init__.py 看起来像这样:

from flask import Flask

auth_app = Flask(__name__)

import auth.views

views.py 看起来像这样:

from auth import auth_app

@auth_app.route('/auth/')
def index():
    return "hello auth!"

但是每当我运行服务器时,只有 localhost/auth/可用,其他所有内容都给出 404,所以我假设帖子应用程序没有运行。

有人能帮忙吗?

最佳答案

您的 auth_app.run() 方法会阻止您的程序继续运行。这就是 posts_apps 应用程序无法运行的原因。提供页面的整个过程发生在 Flask 的 run() 方法中。因此,您可以得出结论,您不能在同一进程中运行两个 Flask 应用程序。

如果您希望像这样将您的应用程序一分为二,推荐的方法是使用 blueprints .您不是创建两个应用程序(auth 和 posts),而是创建两个蓝图。然后你像这样创建一个应用程序......

from flask import Flask
from auth import auth_blueprint
from posts import post_blueprint

app = Flask(__name__)
app.register_blueprint(auth_blueprint)
app.register_blueprint(post_blueprint)
app.run()

关于python - Flask:在一个应用程序中使用多个包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11141710/

相关文章:

ruby-on-rails - ActionController::RoutingError(未初始化的< Controller 名称>)

python - 将单词与最近的索引组合起来

python - Python 中的替代构造函数

asp.net - ASP.Net MVC 中是否有与 Ruby on Rails 的respond_to format.xml 等价的等价物?

ruby-on-rails - 在 Ruby on Rails 中嵌入博客

node.js - Ghost CMS - sudo npm install --product - 错误

javascript - amcharts 交互式 map : making selected states a clickable link

python - Python中集合的迭代顺序

python - 用 Winapi 替换 WMI 调用

routing - 将查询字符串中的参数值映射到DTO属性