在我看来,收到包含数据的帖子后,我将其发送到gcp pub / sub主题。 我有websockets,我想在其中读取较早发送的数据:
@sockets.route('/ws/<string:_id>/some_url/')
def some_function(ws, _id):
if mine_id not in config.MINES:
ws.close()
while not ws.closed:
ws.send(json.dumps({
'type': 'some type',
'data': get_data(_id, 'some type')
}))
time.sleep(100)
它从泛型中获取数据。ListAPIView
def get_data(_id, data_type):
if data_type in config.URLS:
url = data_type
else:
return {'error': 'URL is wrong'}
try:
response = requests.get(
'/'.join([config.API_URL, f"{_id}/" + url + "/"]),
headers={'Authorization': ' '.join(['Token', config.TOKEN])}
)
return response.json()
except HTTPError:
return {'error': 'HTTPError'}
except RequestException:
return {'error': 'RequestException'}
这里的消费者代码:
def consume():
try:
project_id = 'some project'
subscription_name = 'some subscription'
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
project_id, subscription_name)
def callback(message):
print('Received message: {}'.format(message.data))
if message.attributes:
print('Attributes:')
for key in message.attributes:
value = message.attributes.get(key)
print('{}: {}'.format(key, value))
message.ack()
future = subscriber.subscribe(
subscription_path, callback=callback)
try:
data = future.result()
except Exception as e:
logger.exception(
'Listening for some type messages on {} threw an Exception: {}.'.format(
subscription_name, e))
except ConnectionError:
return {'error': 'ConnectionError'}
return data
我尝试过websockets和producer \ consumer,它们都可以独立工作。 如何让他们彼此成为朋友,并在ws.send调用中使用consump()或从其返回的数据?