def create_listing(request): # /create-listing
if request.method != 'POST':
return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")
form = ListingForm(request.POST)
if not form.is_valid():
return _error_response(request, err_exp.E_FORM_INVALID, "listing form not correctly filled out")
post_data = form.cleaned_data
post_data['auth'] = request.POST['auth']
post_data['last_checked_out'] = datetime.datetime.now()
post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
req = urllib.request.Request('http://models-api:8000/api/v1/drone/create/', data=post_encoded, method='POST')
resp_json = urllib.request.urlopen(req).read().decode('utf-8')
resp = json.loads(resp_json)
if not resp:
return _error_response(request, err_exp.E_REGISTER_FAILED, "no response from models API")
if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
return _error_response(request, err_exp.E_REGISTER_FAILED, resp)
post_data['_drone_key'] = resp['resp']['drone_id']
post_data['time_posted'] = datetime.datetime.now()
post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
req = urllib.request.Request('http://models-api:8000/api/v1/listing/create/', data=post_encoded, method='POST')
resp_json = urllib.request.urlopen(req).read().decode('utf-8')
resp = json.loads(resp_json)
if not resp:
return _error_response(request, err_exp.E_REGISTER_FAILED, "no response from models API")
if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
return _error_response(request, err_exp.E_REGISTER_FAILED, {'resp':resp})
# add newly created listing to Kafka
# get listing
'''
req = urllib.request.Request('http://models-api:8000/api/v1/listing/'+resp['resp']['listing_id'])
resp_json = urllib.request.urlopen(req).read().decode('utf-8')
resp1 = json.loads(resp_json)
resp1['listing_id'] = resp['listing_id']
'''
# add to kafka
producer = KafkaProducer(bootstrap_servers='kafka:9092')
# need to pass dictionary object
new_listing = resp['resp']['listing']
producer.send('new-listings-topic', json.dumps(new_listing).encode('utf-8'))
print(new_listing)
return _success_response(request, resp['resp']['listing'])
评论列表
文章目录