I am using pyshark module in a Django view to get the ports breakdown from an uploaded PCAP file.
views.py
class ProtocolAnalysisView(APIView):
parser_classes = (MultiPartParser,)
def analyze_pcap(self, pcap_file):
res = {}
capture = pyshark.FileCapture(
pcap_file.temporary_file_path(), keep_packets=True)
hl_dict = {}
tl_dict = {}
try:
i = 0
while True:
hl = capture[i].highest_layer
tl = capture[i].transport_layer
if hl not in hl_dict:
hl_dict[hl] = 0
if tl not in tl_dict:
tl_dict[tl] = 0
hl_dict[hl] += 1
tl_dict[tl] += 1
i += 1
except KeyError:
capture.close()
res["tcp_packet_counts"] = tl_dict.get("TCP", 0)
res["udp_packet_counts"] = tl_dict.get("UDP", 0)
res["transport_layer_breakdown"] = [
{"transport_layer_protocol": key, "count": value} for key, value in tl_dict.items()
]
res["protocol_breakdown"] = [
{"highest_layer_protocol": key, "count": value} for key, value in hl_dict.items()
]
return res
def post(self, request, *args, **kwargs):
serializer = PcapFileSerializer(data=request.data)
if serializer.is_valid():
pcap_file = serializer.validated_data['pcap_file']
res = self.analyze_pcap(pcap_file)
return Response({"data": res}, status=200)
else:
return Response(serializer.errors, status=400)
The serializer used here:
class PcapFileSerializer(serializers.Serializer):
pcap_file = serializers.FileField(
allow_empty_file=False, allow_null=False, help_text="Upload a pcap file.")
When I POST the a using form-data, Django throws the below exception: Exception Value: There is no current event loop in thread 'Thread-1 (process_request_thread)'.
Using library like scapy and dpkt is not an option for me. So I dig deep anf got to know that pyshark uses async call under the hood and django works in a synchronous manner.
I have tried to use async calls , but I was getting below errors:
*Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'coroutine'> *
Please suggest me an approach.