gpt4 book ai didi

flask - Flask和SubdomainDispatcher,应用程序如何首先运行?

转载 作者:行者123 更新时间:2023-12-03 17:36:13 26 4
gpt4 key购买 nike

我正在使用Flask构建网站,我想使用指示的SubdomainDispatcher,但我不知道如何使它工作(缺少启动服务器的初始run)。

这是代码:

给定here的create_app函数:

def create_app(database_uri, debug=False):
app = Flask(__name__)
app.debug = debug

# set up your database
app.engine = create_engine(database_uri)

# add your modules
app.register_module(frontend)

# other setup tasks

return app


SubdomainDispatcher:

class SubdomainDispatcher(object):

def __init__(self, domain, create_app):
self.domain = domain
self.create_app = create_app
self.lock = Lock()
self.instances = {}

def get_application(self, host):
host = host.split(':')[0]
assert host.endswith(self.domain), 'Configuration error'
subdomain = host[:-len(self.domain)].rstrip('.')
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_app(subdomain)
self.instances[subdomain] = app
return app

def __call__(self, environ, start_response):
app = self.get_application(environ['HTTP_HOST'])
return app(environ, start_response)


主要应用程式:

def make_app(subdomain):
user = get_user_for_subdomain(subdomain)
if user is None:
# if there is no user for that subdomain we still have
# to return a WSGI application that handles that request.
# We can then just return the NotFound() exception as
# application which will render a default 404 page.
# You might also redirect the user to the main page then
return NotFound()

# otherwise create the application for the specific user
return create_app(user)

application = SubdomainDispatcher('example.com', make_app)


到目前为止,我的代码可以正常运行,但是随后停止了。这是正常现象,因为没有位置:

if __name__ == "__main__":
application = create_app(config.DATABASE_URI, debug=True)
application.run()


使初始服务器运行的代码。

我尝试了这个:

if __name__ == "__main__":
application = SubdomainDispatcher('example.com', make_app)
application.run()


但是它失败了:


AttributeError:'SubdomainDispatcher'对象没有属性'run'


如何使用SubdomainDispatcher运行它?

最佳答案

让我们分析一下您的代码。

您创建一个SubdomainDispatcher类,该类创建一个Flask application并根据在host中传递的get_application返回它

这也是一个callable

问题在于.run方法属于Flask对象(应用程序本身)。
它仅在开发期间用于test应用程序,并且适用于单个应用程序。

因此,您不能在整个开发服务器上对其进行测试。您一次只能测试一个域(应用程序)。

if __name__ == "__main__":
application = SubdomainDispatcher('example.com', make_app)
app = application.get_application('example.com')
app.run()


测试服务器不是功能齐全的服务器。

更好的解决方案

顺便说一句,我认为,如果您解释要实现的目标(而不是打算如何在flask中实现这一目标,:)),我们可以找到更好的解决方案。即使用Flask子域关键字,或使用 @before_request根据某些内容对应用程序参数进行本地化。
如果问题仅在于基于子域加载用户类,则无需使用其他Flask Apps(特别是因为您使用的是相同的代码库),而您只需要一个 @before_request处理程序。

关于flask - Flask和SubdomainDispatcher,应用程序如何首先运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18398719/

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