Python + Flask + Protobuf + iOS

user.proto

syntax = "proto3";
message User{
        string name = 1;
        int32 age =2;
}

生成 iOS user.proto.m/h
protoc *.proto --objc_out=./

生成 python user.proto.py
protoc *.proto --python_out=./


main.py

from flask import Flask, request
from user_pb2 import User
app = Flask(__name__)

@app.route('/proto',methods=["POST"])
def hello_world():
    data = request.stream.read()
    user = User()
    user.ParseFromString(data)
    print(len(data))
    print(user.name)
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

启动:python main.py


iOS

pod 'Protobuf'
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    User *name = [[User alloc] init];
    name.name = @"娃哈哈";
    name.age = 1;
    NSData *data = [name data];
    [self sendData:data];
    User *t = [User parseFromData:data error:nil];
    NSLog(@"%@",t.name);
}
-(void)sendData:(NSData *)data{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost:5000/proto"]];
    [request setHTTPBody:data];
    [request setHTTPMethod:@"POST"];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionTask *task = [session uploadTaskWithStreamedRequest:request];
    [task resume];
}

pod install

出错:
AttributeError: module 'google.protobuf.descriptor' has no attribute '_internal_create_key'

解决方法:
proto版本对不上,要么升级pip , 要么升级pod的版本

你可能感兴趣的:(Python + Flask + Protobuf + iOS)