modificando json e protobuf

This commit is contained in:
José Henrique 2023-11-04 17:05:55 -03:00
parent 1eb02db473
commit 95a85be35d
15 changed files with 163 additions and 65 deletions

View File

@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using ProtoBuf; using tcc_app.Models;
using System.IO;
namespace TCC.Controllers namespace TCC.Controllers
{ {
@ -24,25 +23,25 @@ namespace TCC.Controllers
return Ok(sum); return Ok(sum);
} }
[HttpGet("json")] [HttpPost("json")]
public async Task<IActionResult> GetJsonResponse() public async Task<IActionResult> PostJson([FromBody] PersonJson person)
{ {
return Ok(new { message = "Hello World!" }); return Ok(person);
} }
[HttpPost("protobuf")] [HttpPost("protobuf")]
public async Task<IActionResult> PostProtobuf() public async Task<IActionResult> PostProtobuf()
{ {
HelloWorld cliente; PersonProto person;
byte[] response; byte[] response;
using (var stream = Request.BodyReader.AsStream()) using (var stream = Request.BodyReader.AsStream())
{ {
cliente = ProtoBuf.Serializer.Deserialize<HelloWorld>(stream); person = ProtoBuf.Serializer.Deserialize<PersonProto>(stream);
} }
using (var stream = new MemoryStream()) using (var stream = new MemoryStream())
{ {
ProtoBuf.Serializer.Serialize(stream, cliente); ProtoBuf.Serializer.Serialize(stream, person);
response = stream.ToArray(); response = stream.ToArray();
} }
@ -51,11 +50,4 @@ namespace TCC.Controllers
} }
} }
[ProtoContract()]
public class HelloWorld
{
[ProtoMember(1)]
public string Message { get; set; }
}
} }

View File

@ -0,0 +1,12 @@
namespace tcc_app.Models
{
public class PersonJson
{
public string Name { get; set; }
public int Age { get; set; }
public List<string> Friends { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using ProtoBuf;
namespace tcc_app.Models
{
[ProtoContract()]
public class PersonProto
{
[ProtoMember(1)]
public string Name { get; set; }
[ProtoMember(2)]
public int Age { get; set; }
[ProtoMember(3)]
public List<string> Friends { get; set; }
[ProtoMember(4)]
public string Email { get; set; }
[ProtoMember(5)]
public string Phone { get; set; }
}
}

View File

@ -1,14 +1,31 @@
use qstring::QString; use qstring::QString;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, HttpRequest, Result}; use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, HttpRequest, Result};
use actix_files::NamedFile; use actix_files::NamedFile;
// use actix_protobuf::{ProtoBuf, ProtoBufResponseBuilder as _};
use actix_protobuf::*; use actix_protobuf::*;
use prost::Message; use prost::Message;
use serde::{Deserialize, Serialize};
#[derive(Clone, PartialEq, Eq, Message)] #[derive(Clone, PartialEq, Eq, Message)]
pub struct HelloWorld { pub struct PersonProtobuf {
#[prost(string, tag = "1")] #[prost(string, tag = "1")]
pub message: String pub name: String,
#[prost(int32, tag = "2")]
pub age: i32,
#[prost(string, repeated, tag = "3")]
pub friends: Vec<String>,
#[prost(string, tag = "4")]
pub email: String,
#[prost(string, tag = "5")]
pub phone: String,
}
#[derive(Deserialize, Serialize)]
pub struct PersonJson {
pub name: String,
pub age: i32,
pub friends: Vec<String>,
pub email: String,
pub phone: String,
} }
#[get("/status/ok")] #[get("/status/ok")]
@ -37,20 +54,13 @@ async fn simulation_harmonic_progression(req: HttpRequest) -> impl Responder {
HttpResponse::Ok().body(format!("{}", sum)) HttpResponse::Ok().body(format!("{}", sum))
} }
#[get("/simulation/json")] #[post("/simulation/json")]
async fn simulation_json() -> impl Responder { async fn simulation_json(msg: web::Json<PersonJson>) -> impl Responder {
let body = serde_json::json!({ HttpResponse::Ok().json(web::Json(msg))
"message": "Hello World!"
});
HttpResponse::Ok()
.json(body)
} }
#[post("/simulation/protobuf")] #[post("/simulation/protobuf")]
async fn simulation_protobuf(msg: ProtoBuf<HelloWorld>) -> impl Responder { async fn simulation_protobuf(msg: ProtoBuf<PersonProtobuf>) -> impl Responder {
println!("model: {:?}", msg.0);
HttpResponse::Ok().protobuf(msg.0) HttpResponse::Ok().protobuf(msg.0)
} }

View File

@ -1,5 +1,5 @@
from flask import request, Blueprint, jsonify from flask import request, Blueprint, jsonify
import helloworld_pb2 import person_pb2
simulation_blueprint = Blueprint('simulation_blueprint', __name__) simulation_blueprint = Blueprint('simulation_blueprint', __name__)
@ -26,15 +26,16 @@ def return_ok():
return str(sum), 200 return str(sum), 200
@simulation_blueprint.route('/simulation/json', methods=['GET']) @simulation_blueprint.route('/simulation/json', methods=['POST'])
def return_helloworld(): def return_helloworld():
return simulation_controller.return_helloworld(), 200 data = request.json
return data, 200
@simulation_blueprint.route('/simulation/protobuf', methods=['POST']) @simulation_blueprint.route('/simulation/protobuf', methods=['POST'])
def return_protobuf(): def return_protobuf():
bytes_data = request.data bytes_data = request.data
helloworld = helloworld_pb2.MyObj() helloworld = person_pb2.Person()
helloworld.ParseFromString(bytes_data) helloworld.ParseFromString(bytes_data)
return helloworld.SerializeToString(), 200 return helloworld.SerializeToString(), 200

View File

@ -1,5 +0,0 @@
syntax = "proto3";
message MyObj {
string message = 1;
}

9
FlaskAPI/person.proto Normal file
View File

@ -0,0 +1,9 @@
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
repeated string friends = 3;
string email = 4;
string phone = 5;
}

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT! # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.proto # source: person.proto
# Protobuf Python Version: 4.25.0 # Protobuf Python Version: 4.25.0
"""Generated protocol buffer code.""" """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor as _descriptor
@ -14,13 +14,13 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\"\x18\n\x05MyObj\x12\x0f\n\x07message\x18\x01 \x01(\tb\x06proto3') DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cperson.proto\"R\n\x06Person\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0b\n\x03\x61ge\x18\x02 \x01(\x05\x12\x0f\n\x07\x66riends\x18\x03 \x03(\t\x12\r\n\x05\x65mail\x18\x04 \x01(\t\x12\r\n\x05phone\x18\x05 \x01(\tb\x06proto3')
_globals = globals() _globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'person_pb2', _globals)
if _descriptor._USE_C_DESCRIPTORS == False: if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None DESCRIPTOR._options = None
_globals['_MYOBJ']._serialized_start=20 _globals['_PERSON']._serialized_start=16
_globals['_MYOBJ']._serialized_end=44 _globals['_PERSON']._serialized_end=98
# @@protoc_insertion_point(module_scope) # @@protoc_insertion_point(module_scope)

View File

@ -1,14 +1,28 @@
import helloworld_pb2 import person_pb2
helloworld = helloworld_pb2.MyObj() person_proto = person_pb2.Person()
helloworld.message = "Hello World!" person_proto.name = "John Doe"
person_proto.age = 30
person_proto.friends.extend(["Jane Doe", "John Smith"])
person_proto.email = "john.doe@email.com"
person_proto.phone = "123-456-7890"
person_proto = person_proto.SerializeToString()
person_json = {
"name": "John Doe",
"age": 30,
"friends": ["Jane Doe", "John Smith"],
"email": "john.doe@email.com",
"phone": "123-456-7890"
}
person_json = str(person_json).encode('utf-8')
FRAMEWORKS = [ FRAMEWORKS = [
('Actix', 'tcc-actix', 'orange'), ('Actix', 'tcc-actix', 'orange'),
('ASP.NET', 'tcc-aspnet', 'blue'), ('ASP.NET', 'tcc-aspnet', 'blue'),
('Flask', 'tcc-flask', 'grey'), ('Flask', 'tcc-flask', 'grey'),
('Express', 'tcc-express', 'red'), # ('Express', 'tcc-express', 'red'),
('Spring', 'tcc-spring', 'green'), # ('Spring', 'tcc-spring', 'green'),
] ]
ENDPOINTS = { ENDPOINTS = {
@ -20,16 +34,16 @@ ENDPOINTS = {
} }
AVG_RUNS = 5 AVG_RUNS = 5
helloworld_pb2
API_REQUESTS = [ API_REQUESTS = [
('/status/ok', 'GET', range(0, 30_000, 5000), None), # ('/status/ok', 'GET', range(0, 30_000, 5000), None),
# ('/simulation/harmonic-progression?n=100000', 'GET', range(0, 30_000, 5000), None), # ('/simulation/harmonic-progression?n=100000', 'GET', range(0, 30_000, 5000), None),
# ('/simulation/json', 'GET', range(0, 30_000, 5000), None), ('/simulation/json', 'POST', range(0, 30_000, 5000), (person_json, "application/json")),
# ('/image/save-big-image', 'POST', range(0, 500, 50), open('big-image.png', 'rb').read()), # ('/image/save-big-image', 'POST', range(0, 500, 50), (open('big-image.png', 'rb').read(), "image/png")),
# ('/image/load-small-image', 'GET', range(0, 30_000, 5000), None), # ('/image/load-small-image', 'GET', range(0, 30_000, 5000), None),
# ('/static/small-image.png', 'GET', range(0, 30_000, 5000), None), # ('/static/small-image.png', 'GET', range(0, 30_000, 5000), None),
# ('/image/load-big-image', 'GET', range(0, 500, 50), None), # ('/image/load-big-image', 'GET', range(0, 500, 50), None),
# ('/static/big-image.png', 'GET', range(0, 500, 50), None), # ('/static/big-image.png', 'GET', range(0, 500, 50), None),
# ('/static/nginx.html', 'GET', range(0, 30_000, 5000), None), # ('/static/nginx.html', 'GET', range(0, 30_000, 5000), None),
('/simulation/protobuf', 'POST', range(0, 30_000, 5000), helloworld.SerializeToString()), ('/simulation/protobuf', 'POST', range(0, 30_000, 5000), (person_proto.SerializeToString(), "application/protobuf")),
] ]

View File

@ -1,5 +0,0 @@
syntax = "proto3";
message MyObj {
string message = 1;
}

9
scripts/person.proto Normal file
View File

@ -0,0 +1,9 @@
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
repeated string friends = 3;
string email = 4;
string phone = 5;
}

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT! # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.proto # source: person.proto
# Protobuf Python Version: 4.25.0 # Protobuf Python Version: 4.25.0
"""Generated protocol buffer code.""" """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor as _descriptor
@ -14,13 +14,13 @@ _sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\"\x18\n\x05MyObj\x12\x0f\n\x07message\x18\x01 \x01(\tb\x06proto3') DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0cperson.proto\"R\n\x06Person\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0b\n\x03\x61ge\x18\x02 \x01(\x05\x12\x0f\n\x07\x66riends\x18\x03 \x03(\t\x12\r\n\x05\x65mail\x18\x04 \x01(\t\x12\r\n\x05phone\x18\x05 \x01(\tb\x06proto3')
_globals = globals() _globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'person_pb2', _globals)
if _descriptor._USE_C_DESCRIPTORS == False: if _descriptor._USE_C_DESCRIPTORS == False:
DESCRIPTOR._options = None DESCRIPTOR._options = None
_globals['_MYOBJ']._serialized_start=20 _globals['_PERSON']._serialized_start=16
_globals['_MYOBJ']._serialized_end=44 _globals['_PERSON']._serialized_end=98
# @@protoc_insertion_point(module_scope) # @@protoc_insertion_point(module_scope)

31
scripts/protobuftest.py Normal file
View File

@ -0,0 +1,31 @@
import person_pb2
import asyncio
import aiohttp
async def fetch(session):
obj = get_object()
# async with session.post('http://172.25.96.1:9090/simulation/protobuf', data=obj.SerializeToString(),
async with session.post('http://127.0.0.1:5000/simulation/protobuf', data=obj.SerializeToString(),
headers={"content-type": "application/protobuf"}) as resp:
print(resp.status)
data = await resp.read()
receiveObj = person_pb2.Person()
receiveObj.ParseFromString(data)
print(receiveObj)
async def go(loop):
async with aiohttp.ClientSession(loop=loop) as session:
await fetch(session)
def get_object():
obj = person_pb2.Person()
obj.name = "John Doe"
obj.age = 30
obj.friends.extend(["Jane Doe", "John Smith"])
obj.email = "john.doe@email.com"
obj.phone = "123-456-7890"
return obj
loop = asyncio.get_event_loop()
loop.run_until_complete(go(loop))
loop.close()

4
scripts/requirements.txt Normal file
View File

@ -0,0 +1,4 @@
protobuf>=4.25.0
matplotlib
numpy
docker

View File

@ -14,7 +14,7 @@ FRAMEWORK_NAME = ""
CONTAINER_NAME = "" CONTAINER_NAME = ""
URL_BASE = 'http://localhost:9090' URL_BASE = 'http://localhost:9090'
def send_request(url, method = 'GET', payload = None): def send_request(url, method = 'GET', data = None):
success = False success = False
responses = { responses = {
2: 0, # OK 2: 0, # OK
@ -27,7 +27,9 @@ def send_request(url, method = 'GET', payload = None):
if method == 'GET': if method == 'GET':
response = requests.get(url) response = requests.get(url)
elif method == 'POST': elif method == 'POST':
response = requests.post(url, data=payload, headers={'Content-Type': 'image/png'}) payload = data[0]
content_type = data[1]
response = requests.post(url, data=payload, headers={'Content-Type': content_type})
except: except:
continue continue
success = response.status_code == 200 success = response.status_code == 200