You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python3与Django1.9,如何同时支持API及Socket连接?

Hey there! Let's break down how to build your system with Python 3, Django 1.9, and an Android frontend, covering both API and Socket connections as you've outlined.

整体架构概述
  • 后端:Python 3 + Django 1.9,负责处理API请求和Socket连接
  • 前端:Android平台,通过API提交用户个人信息,通过Socket接收硬件数据、故障日志和实时推送更新

1. API连接实现(用户个人信息提交)

For handling user info submissions, Django 1.9 works great with Django REST Framework 3.3.3 (the compatible version for Django 1.9). Here's a step-by-step implementation:

核心代码示例

1.1 Define a User Profile Model (models.py)

from django.db import models

class UserProfile(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    phone = models.CharField(max_length=20)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

1.2 Create a Serializer (serializers.py)

Convert model data to JSON for frontend interaction:

from rest_framework import serializers
from .models import UserProfile

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('name', 'email', 'phone')

1.3 Build the API View (views.py)

Handle POST requests from Android to save user data:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import UserProfile
from .serializers import UserProfileSerializer

class SubmitUserInfoView(APIView):
    def post(self, request):
        serializer = UserProfileSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1.4 Configure API Routes (urls.py)

from django.conf.urls import url
from .views import SubmitUserInfoView

urlpatterns = [
    url(r'^api/submit-user-info/$', SubmitUserInfoView.as_view(), name='submit-user-info'),
]

Android Integration

Your Android app can use libraries like OkHttp or Retrofit to send a POST request to the API endpoint with JSON-formatted user data.


2. Socket连接实现(硬件数据接收、日志存储和推送更新)

You've got a solid start with your Socket server snippet. Let's refine it to support multi-threading (for handling multiple hardware connections) and integrate with your Django environment for log storage.

Refined Multi-Threaded Socket Server Code

import socket
import ssl
import json
from threading import Thread, active_count
from socketserver import ThreadingMixIn, TCPServer, BaseRequestHandler

# Uncomment below to connect to Django database (run this before importing app modules)
# import os
# import django
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")
# django.setup()
# from your_app.serializers import create_log_entry

class ThreadedTCPRequestHandler(BaseRequestHandler):
    def handle(self):
        # Optional: Enable SSL for encrypted hardware-server communication
        # self.request = ssl.wrap_socket(
        #     self.request, 
        #     server_side=True, 
        #     certfile="server.crt", 
        #     keyfile="server.key"
        # )
        
        try:
            # Receive data from hardware
            raw_data = self.request.recv(1024).decode('utf-8')
            if not raw_data:
                return
            
            payload = json.loads(raw_data)
            client_addr = self.client_address[0]

            # Handle different data types
            if payload.get('type') == 'hardware_data':
                print(f"Received hardware data from {client_addr}: {payload}")
                # Add logic here to push updates to Android (e.g., via WebSocket or FCM)
            elif payload.get('type') == 'fault_log':
                print(f"Received fault log from {client_addr}: {payload}")
                # create_log_entry(payload)  # Save log to Django DB using your serializer
            
            # Send confirmation to hardware
            response = json.dumps({'status': 'success', 'message': 'Data received'})
            self.request.sendall(response.encode('utf-8'))
            
        except json.JSONDecodeError:
            error_msg = json.dumps({'status': 'error', 'message': 'Invalid JSON format'})
            self.request.sendall(error_msg.encode('utf-8'))
        except Exception as e:
            print(f"Error handling connection from {client_addr}: {str(e)}")
        finally:
            self.request.close()

class ThreadedTCPServer(ThreadingMixIn, TCPServer):
    allow_reuse_address = True  # Prevent "address already in use" errors on restart

def run_socket_server(host='0.0.0.0', port=9999):
    server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
    print(f"Socket server running on {host}:{port}")
    print(f"Active threads: {active_count()}")

    # Start server in a daemon thread
    server_thread = Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()

    # Keep main thread alive
    try:
        while True:
            pass
    except KeyboardInterrupt:
        server.shutdown()
        print("Socket server stopped gracefully")

if __name__ == "__main__":
    run_socket_server()

Key Notes

  • Multi-Threading: ThreadingMixIn lets the server handle multiple hardware connections simultaneously.
  • Django DB Integration: Uncomment the Django setup code if you need to save logs directly to your Django database from the Socket server.
  • Android Push Updates: For real-time pushes to Android, you can use:
    • WebSocket: Implement a WebSocket client in Android (e.g., OkHttp WebSocket) to connect to the Socket server.
    • FCM: Trigger Firebase Cloud Messaging API calls from the Socket server when new hardware data arrives.

Deployment Tips

  • API Service: Use Django's runserver for development; for production, deploy with Gunicorn + Nginx.
  • Socket Service: Run it as a standalone Python process. On Linux, use systemd to manage the service (ensure it starts on boot).

内容的提问来源于stack exchange,提问作者Pratibha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:59:36