【发布时间】:2017-08-23 21:11:19
【问题描述】:
我在需要在另一个文件中以main.py 实例化的类中提供信息时遇到困难。描述我正在尝试做的事情的最佳方式可以在下面的流程图中看到:
您可以想象的问题是循环依赖。有没有办法在schema.py 和main.py 之间创建一个接口,以便我可以传递类信息?
感谢您的宝贵时间和您能提供的任何帮助!
编辑:添加代码供参考
ws_transport.py
from autobahn.twisted.websocket import (
WebSocketServerProtocol,
WebSocketServerFactory,
)
from schema import schema
class WsProtocol(WebSocketServerProtocol):
def __init__(self):
# Code here
def onConnect(self, request):
# Code here
def onMessage(self, payload, isBinary):
# Code here
class WsProtocolFactory(WebSocketServerFactory):
def __init__(self):
super(WsProtocolFactory, self).__init__()
self.connection_subscriptions = defaultdict(set)
# Code here
def check_events_db(self):
# Code here
def check_audit_log_db(self):
# Code here
web_transport.py
import sys, os
import json
from twisted.web.resource import Resource
from twisted.web.server import Site, http
from schema import schema
class HttpResource(Resource):
isLeaf = True
def render_OPTIONS(self, request):
# Code here
def render_GET(self, request):
# Code here
def render_POST(self, request):
# Code here
class LoginResource(Resource):
isLeaf = True
def render_OPTIONS(self, request):
# Code here
def render_GET(self, request):
# Code here
def render_POST(self, request):
# Code here
class RefreshResource(Resource):
isLeaf = True
def render_OPTIONS(self, request):
# Code here
def render_GET(self, request):
# Code here
def render_POST(self, request):
# Code here
class HttpFactory(Site):
def __init__(self, resource):
# Code here
schema.py
#!/usr/bin/python
import graphene
import json
import sys, os
from main import factory
class Query(graphene.ObjectType):
# Code here
class Mutation(graphene.ObjectType):
# Code here
class Subscription(graphene.ObjectType):
# Code here
schema = graphene.Schema(query=Query, mutation=Mutation, subscription=Subscription)
main.py
import sys
from twisted.internet import reactor
from twisted.web.resource import Resource
from autobahn.twisted.resource import WebSocketResource
from ws_transport import WsProtocol, WsProtocolFactory
from web_transport import HttpResource, LoginResource, RefreshResource, HttpFactory
if __name__ == '__main__':
factory = WsProtocolFactory()
factory.protocol = WsProtocol
ws_resource = WebSocketResource(factory)
root = Resource()
root.putChild("", HttpResource())
root.putChild("login", LoginResource())
root.putChild("refresh", RefreshResource())
root.putChild(b"ws", ws_resource)
site = HttpFactory(root)
reactor.listenTCP(8000, site)
reactor.run()
干杯,
布赖恩
【问题讨论】:
-
您可以将对象作为参数传递给函数。
-
您能否提供一个带有伪代码的示例,说明如何解决此问题?谢谢彼得!
-
我不熟悉您的“流程图” - 我们可以假设箭头暗示某种通信吗?您能否在您的问题中添加文件中相关的导入语句是什么样的?
-
是的,这是一个安全的假设。我将用一些代码编辑我原来的问题。
-
@wwii 我已经用代码 sn-ps 更新了我的原始帖子。我需要能够将 main.py 中的工厂实例导入 schema.py,以便在定义的类中可以使用此信息。
标签: python design-patterns dependency-injection software-design circular-dependency